BTC and ETH Long strategy - version 2I wrote my first article in May 2020. See below
BTC and ETH Long strategy - version1
After 6 months, it is now time to check the result of my script for the last 6 months.
XBTUSD (4H): 14/05/2020 --> 22/11/2020 = +78% in 4 trades
ETHXBT (4H): 14/05/2020 --> 22/11/2020 = +21% in 9 trades
ETHUSD (4H): 14/05/2020 --> 22/11/2020 = +90% in 6 trades
Using the signals from this strategy to trade manually has shown that this was a bit frustrating because of the low rate of winning trades.
If you have to enter 100 trades and see 75% of them failing and 25% winning, this is frustrating. For sure the strategy makes good money but it is difficult to hold this mentality.
So, I have reviewed and modified it to get a higher winning rate.
After few days of work, tests and validation, I managed to get a wining rate close to 60%.
The key element was also to decrease the number of trades by using a higher time frame. (4H candles instead of 2H candles).
- Entry in position is based on
MACD, EMA (20), SMA (100), SMA (200) moving up
AND EMA (20) > SMA (100)
AND SMA (100) > SMA (200)
- Exit the position if: Stoploss is reached OR EMA (20) crossUnder SMA (100)
The goal of this new script is to be able to follow the signals manually and only make few trades per years.
I have also validated it against some other altcoins where some are giving very good results.
Here are some results for 2020 (from 01/01/2020 until now (22/11/2020). Those results are the one I get when using 4H candles.
ETH/USD: +144% in 8 trades.
BTC/USD: +120% in 7 trades.
ETH/BTC: +33% in 9 trades.
ICX/USD: +123% in 10 trades.
LINK/USD: +155% in 11 trades.
MLN/USD: +388% in 8 trades.
ADA/USD: +180% in 7 trades.
LINK/BTC: +97% in 10 trades.
The best is that above results are without considering compound effect. If you re-invest all gains done in each new trade, this will give you the below results :)
ETH/USD: +189% in 8 trades.
BTC/USD: +260% in 7 trades.
ETH/BTC: +29% in 9 trades.
ICX/USD: +112% in 10 trades.
LINK/USD: +222% in 11 trades.
MLN/USD: +793% in 8 trades.
ADA/USD: +319% in 7 trades.
LINK/BTC: +103% in 10 trades.
As you can see, the results are good and the number of trades for 11 months is not big, which allows the trader to place orders manually.
But still, I'm lazy :), so, I have also coded this strategy in HaasScript language which allows you to automate this strategy using the HaasOnline software specialized in automated crypto trading.
I hope that this strategy will give you ideas or will be the starting point for your own strategy.
Let me know if you need more details.
Cari dalam skrip untuk "想象图:箱线图+折线组合,横轴为国家,纵轴为响应指数(0-100),箱线显示均值±标准差,叠加红色虚线标注各国确诊高峰时间点"
BTC and ETH Long strategy - version 1I will start with a small introduction about myself. I'm now trading cryto currencies manually for almost 2 years. I decided to start after watching a documentary on the TV showing people who made big money during the Bitcoin pump which happened at the end of 2017.
The next day, I asked myself "Why should I not give it a try and learn how to trade".
This was in February 2018 and the price of Bitcoin was around 11500USD.
I didn't know how to trade. In fact, I didn't know the trading industry at all.
So, my first step into trading was to open an account with a broken. Then I directly bought 200$ worst of BTC . At that time, I saw the graph and thought "This can only go back in the upward direction!" :)
I didn't know anything about Stop loss, Take profit and Risk management.
Today, almost 2 years after, I think that I know how to trade and can also confirm that I still hold this bag of 200$ of bitcoin from 2018 :)
I did spend the 2 last years to learn technical analysis , risk management and leverage trading.
Today (14/05/2020), I know what I'm doing and I'm happy to see that the 2 last years have been positive in terms of gains. Of course, I did not make crazy money with my saving but at least I made more than if I would have kept it in my bank account.
Even if I like trading, I have a full time job which requires my full energy and lots of focus, so, the biggest problem I had is that I didn't have enough time to look at the charts.
Also, I realized that sometimes, neither technical analysis , nor fundamentals worked with crypto currency (at least for short time trading). So, as I have a developer background I decided to try to have a look at algo trading.
The goal for me was neither to make complex algos nor to beat the market but just to automate my trading with simple bot catching the big waves.
I then started to take a look at TV pine script and played with it.
I did my first LONG script in February 2020 to Long the BTC Market. It has some limitations but works well enough for me for the time being. Even if the real trades will bring me half of what the back testing shows, this will still be a lot more than what I was used to win during the last 2 years with my manual trading.
So, here we are! Below you will find some details about my first LONG script. I'm happy to share it with you.
Feel free to play with it, give your comments and bring improvements to it.
But please note that it only works fine with the candle size and crypto pair that I have mentioned below. If you use other settings this algo might loose money!
- Crypto pairs : XBTUSD and ETHXBT
- Candle size: 2 Hours
- Indicator used: Volatility , MACD (12, 26, 7), SMA (100), SMA (200), EMA (20)
- Default StopLoss: -1.5%
- Entry in position if: Volatility < 2%
AND MACD moving up
AND AME (20) moving up
AND SMA (100) moving up
AND SMA (200) moving up
AND EMA (20) > SAM (100)
AND SMA (100) > SMA (200)
- Exit the postion if: Stoploss is reached
OR EMA (20) crossUnder SMA (100)
Here is a summary of the results for this script:
XBTUSD : 01/01/2019 --> 14/05/2020 = +107%
ETHXBT : 01/01/2019 --> 14/05/2020 = +39%
ETHUSD : 01/01/2019 --> 14/05/2020 = +112%
It is far away from being perfect. There are still plenty of things which can be done to improve it but I just wanted to share it :) .
Enjoy playing with it....
Fischy Bands (multiple periods)Just a quick way to have multiple periods. Coded at (14,50,100,200,400,600,800). Feel free to tweak it. Default is all on, obviously not as usable! Try just using 14, and 50.
This was generated with javascript for easy templating.
Source:
```
const periods = ;
const generate = (period) => {
const template = `
= bandFor(${period})
plot(b${period}, color=colorFor(${period}, b${period}), linewidth=${periods.indexOf(period)+1}, title="BB ${period} Basis", transp=show${period}TransparencyLine)
pb${period}Upper = plot(b${period}Upper, color=colorFor(${period}, b${period}), linewidth=${periods.indexOf(period)+1}, title="BB ${period} Upper", transp=show${period}TransparencyLine)
pb${period}Lower = plot(b${period}Lower, color=colorFor(${period}, b${period}), linewidth=${periods.indexOf(period)+1}, title="BB ${period} Lower", transp=show${period}TransparencyLine)
fill(pb${period}Upper, pb${period}Lower, color=colorFor(${period}, b${period}), transp=show${period}TransparencyFill)`
console.log(template);
}
console.log(`//@version=4
study(shorttitle="Fischy BB", title="Fischy Bands", overlay=true)
stdm = input(1.25, title="stdev")
bandFor(length) =>
src = hlc3
mult = stdm
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
`);
periods.forEach(e => console.log(`show${e} = input(title="Show ${e}?", type=input.bool, defval=true)`));
periods.forEach(e => console.log(`show${e}TransparencyLine = show${e} ? 20 : 100`));
periods.forEach(e => console.log(`show${e}TransparencyFill = show${e} ? 80 : 100`));
console.log('\n');
console.log(`colorFor(period, series) =>
c = period == 14 ? color.white :
period == 50 ? color.aqua :
period == 100 ? color.orange :
period == 200 ? color.purple :
period == 400 ? color.lime :
period == 600 ? color.yellow :
period == 800 ? color.orange :
color.black
c
`);
periods.forEach(e => generate(e))
```
Backtesting & Trading Engine [PineCoders]The PineCoders Backtesting and Trading Engine is a sophisticated framework with hybrid code that can run as a study to generate alerts for automated or discretionary trading while simultaneously providing backtest results. It can also easily be converted to a TradingView strategy in order to run TV backtesting. The Engine comes with many built-in strats for entries, filters, stops and exits, but you can also add you own.
If, like any self-respecting strategy modeler should, you spend a reasonable amount of time constantly researching new strategies and tinkering, our hope is that the Engine will become your inseparable go-to tool to test the validity of your creations, as once your tests are conclusive, you will be able to run this code as a study to generate the alerts required to put it in real-world use, whether for discretionary trading or to interface with an execution bot/app. You may also find the backtesting results the Engine produces in study mode enough for your needs and spend most of your time there, only occasionally converting to strategy mode in order to backtest using TV backtesting.
As you will quickly grasp when you bring up this script’s Settings, this is a complex tool. While you will be able to see results very quickly by just putting it on a chart and using its built-in strategies, in order to reap the full benefits of the PineCoders Engine, you will need to invest the time required to understand the subtleties involved in putting all its potential into play.
Disclaimer: use the Engine at your own risk.
Before we delve in more detail, here’s a bird’s eye view of the Engine’s features:
More than 40 built-in strategies,
Customizable components,
Coupling with your own external indicator,
Simple conversion from Study to Strategy modes,
Post-Exit analysis to search for alternate trade outcomes,
Use of the Data Window to show detailed bar by bar trade information and global statistics, including some not provided by TV backtesting,
Plotting of reminders and generation of alerts on in-trade events.
By combining your own strats to the built-in strats supplied with the Engine, and then tuning the numerous options and parameters in the Inputs dialog box, you will be able to play what-if scenarios from an infinite number of permutations.
USE CASES
You have written an indicator that provides an entry strat but it’s missing other components like a filter and a stop strategy. You add a plot in your indicator that respects the Engine’s External Signal Protocol, connect it to the Engine by simply selecting your indicator’s plot name in the Engine’s Settings/Inputs and then run tests on different combinations of entry stops, in-trade stops and profit taking strats to find out which one produces the best results with your entry strat.
You are building a complex strategy that you will want to run as an indicator generating alerts to be sent to a third-party execution bot. You insert your code in the Engine’s modules and leverage its trade management code to quickly move your strategy into production.
You have many different filters and want to explore results using them separately or in combination. Integrate the filter code in the Engine and run through different permutations or hook up your filtering through the external input and control your filter combos from your indicator.
You are tweaking the parameters of your entry, filter or stop strat. You integrate it in the Engine and evaluate its performance using the Engine’s statistics.
You always wondered what results a random entry strat would yield on your markets. You use the Engine’s built-in random entry strat and test it using different combinations of filters, stop and exit strats.
You want to evaluate the impact of fees and slippage on your strategy. You use the Engine’s inputs to play with different values and get immediate feedback in the detailed numbers provided in the Data Window.
You just want to inspect the individual trades your strategy generates. You include it in the Engine and then inspect trades visually on your charts, looking at the numbers in the Data Window as you move your cursor around.
You have never written a production-grade strategy and you want to learn how. Inspect the code in the Engine; you will find essential components typical of what is being used in actual trading systems.
You have run your system for a while and have compiled actual slippage information and your broker/exchange has updated his fees schedule. You enter the information in the Engine and run it on your markets to see the impact this has on your results.
FEATURES
Before going into the detail of the Inputs and the Data Window numbers, here’s a more detailed overview of the Engine’s features.
Built-in strats
The engine comes with more than 40 pre-coded strategies for the following standard system components:
Entries,
Filters,
Entry stops,
2 stage in-trade stops with kick-in rules,
Pyramiding rules,
Hard exits.
While some of the filter and stop strats provided may be useful in production-quality systems, you will not devise crazy profit-generating systems using only the entry strats supplied; that part is still up to you, as will be finding the elusive combination of components that makes winning systems. The Engine will, however, provide you with a solid foundation where all the trade management nitty-gritty is handled for you. By binding your custom strats to the Engine, you will be able to build reliable systems of the best quality currently allowed on the TV platform.
On-chart trade information
As you move over the bars in a trade, you will see trade numbers in the Data Window change at each bar. The engine calculates the P&L at every bar, including slippage and fees that would be incurred were the trade exited at that bar’s close. If the trade includes pyramided entries, those will be taken into account as well, although for those, final fees and slippage are only calculated at the trade’s exit.
You can also see on-chart markers for the entry level, stop positions, in-trade special events and entries/exits (you will want to disable these when using the Engine in strategy mode to see TV backtesting results).
Customization
You can couple your own strats to the Engine in two ways:
1. By inserting your own code in the Engine’s different modules. The modular design should enable you to do so with minimal effort by following the instructions in the code.
2. By linking an external indicator to the engine. After making the proper selections in the engine’s Settings and providing values respecting the engine’s protocol, your external indicator can, when the Engine is used in Indicator mode only:
Tell the engine when to enter long or short trades, but let the engine’s in-trade stop and exit strats manage the exits,
Signal both entries and exits,
Provide an entry stop along with your entry signal,
Filter other entry signals generated by any of the engine’s entry strats.
Conversion from strategy to study
TradingView strategies are required to backtest using the TradingView backtesting feature, but if you want to generate alerts with your script, whether for automated trading or just to trigger alerts that you will use in discretionary trading, your code has to run as a study since, for the time being, strategies can’t generate alerts. From hereon we will use indicator as a synonym for study.
Unless you want to maintain two code bases, you will need hybrid code that easily flips between strategy and indicator modes, and your code will need to restrict its use of strategy() calls and their arguments if it’s going to be able to run both as an indicator and a strategy using the same trade logic. That’s one of the benefits of using this Engine. Once you will have entered your own strats in the Engine, it will be a matter of commenting/uncommenting only four lines of code to flip between indicator and strategy modes in a matter of seconds.
Additionally, even when running in Indicator mode, the Engine will still provide you with precious numbers on your individual trades and global results, some of which are not available with normal TradingView backtesting.
Post-Exit Analysis for alternate outcomes (PEA)
While typical backtesting shows results of trade outcomes, PEA focuses on what could have happened after the exit. The intention is to help traders get an idea of the opportunity/risk in the bars following the trade in order to evaluate if their exit strategies are too aggressive or conservative.
After a trade is exited, the Engine’s PEA module continues analyzing outcomes for a user-defined quantity of bars. It identifies the maximum opportunity and risk available in that space, and calculates the drawdown required to reach the highest opportunity level post-exit, while recording the number of bars to that point.
Typically, if you can’t find opportunity greater than 1X past your trade using a few different reasonable lengths of PEA, your strategy is doing pretty good at capturing opportunity. Remember that 100% of opportunity is never capturable. If, however, PEA was finding post-trade maximum opportunity of 3 or 4X with average drawdowns of 0.3 to those areas, this could be a clue revealing your system is exiting trades prematurely. To analyze PEA numbers, you can uncomment complete sets of plots in the Plot module to reveal detailed global and individual PEA numbers.
Statistics
The Engine provides stats on your trades that TV backtesting does not provide, such as:
Average Profitability Per Trade (APPT), aka statistical expectancy, a crucial value.
APPT per bar,
Average stop size,
Traded volume .
It also shows you on a trade-by-trade basis, on-going individual trade results and data.
In-trade events
In-trade events can plot reminders and trigger alerts when they occur. The built-in events are:
Price approaching stop,
Possible tops/bottoms,
Large stop movement (for discretionary trading where stop is moved manually),
Large price movements.
Slippage and Fees
Even when running in indicator mode, the Engine allows for slippage and fees to be included in the logic and test results.
Alerts
The alert creation mechanism allows you to configure alerts on any combination of the normal or pyramided entries, exits and in-trade events.
Backtesting results
A few words on the numbers calculated in the Engine. Priority is given to numbers not shown in TV backtesting, as you can readily convert the script to a strategy if you need them.
We have chosen to focus on numbers expressing results relative to X (the trade’s risk) rather than in absolute currency numbers or in other more conventional but less useful ways. For example, most of the individual trade results are not shown in percentages, as this unit of measure is often less meaningful than those expressed in units of risk (X). A trade that closes with a +25% result, for example, is a poor outcome if it was entered with a -50% stop. Expressed in X, this trade’s P&L becomes 0.5, which provides much better insight into the trade’s outcome. A trade that closes with a P&L of +2X has earned twice the risk incurred upon entry, which would represent a pre-trade risk:reward ratio of 2.
The way to go about it when you think in X’s and that you adopt the sound risk management policy to risk a fixed percentage of your account on each trade is to equate a currency value to a unit of X. E.g. your account is 10K USD and you decide you will risk a maximum of 1% of it on each trade. That means your unit of X for each trade is worth 100 USD. If your APPT is 2X, this means every time you risk 100 USD in a trade, you can expect to make, on average, 200 USD.
By presenting results this way, we hope that the Engine’s statistics will appeal to those cognisant of sound risk management strategies, while gently leading traders who aren’t, towards them.
We trade to turn in tangible profits of course, so at some point currency must come into play. Accordingly, some values such as equity, P&L, slippage and fees are expressed in currency.
Many of the usual numbers shown in TV backtests are nonetheless available, but they have been commented out in the Engine’s Plot module.
Position sizing and risk management
All good system designers understand that optimal risk management is at the very heart of all winning strategies. The risk in a trade is defined by the fraction of current equity represented by the amplitude of the stop, so in order to manage risk optimally on each trade, position size should adjust to the stop’s amplitude. Systems that enter trades with a fixed stop amplitude can get away with calculating position size as a fixed percentage of current equity. In the context of a test run where equity varies, what represents a fixed amount of risk translates into different currency values.
Dynamically adjusting position size throughout a system’s life is optimal in many ways. First, as position sizing will vary with current equity, it reproduces a behavioral pattern common to experienced traders, who will dial down risk when confronted to poor performance and increase it when performance improves. Second, limiting risk confers more predictability to statistical test results. Third, position sizing isn’t just about managing risk, it’s also about maximizing opportunity. By using the maximum leverage (no reference to trading on margin here) into the trade that your risk management strategy allows, a dynamic position size allows you to capture maximal opportunity.
To calculate position sizes using the fixed risk method, we use the following formula: Position = Account * MaxRisk% / Stop% [, which calculates a position size taking into account the trade’s entry stop so that if the trade is stopped out, 100 USD will be lost. For someone who manages risk this way, common instructions to invest a certain percentage of your account in a position are simply worthless, as they do not take into account the risk incurred in the trade.
The Engine lets you select either the fixed risk or fixed percentage of equity position sizing methods. The closest thing to dynamic position sizing that can currently be done with alerts is to use a bot that allows syntax to specify position size as a percentage of equity which, while being dynamic in the sense that it will adapt to current equity when the trade is entered, does not allow us to modulate position size using the stop’s amplitude. Changes to alerts are on the way which should solve this problem.
In order for you to simulate performance with the constraint of fixed position sizing, the Engine also offers a third, less preferable option, where position size is defined as a fixed percentage of initial capital so that it is constant throughout the test and will thus represent a varying proportion of current equity.
Let’s recap. The three position sizing methods the Engine offers are:
1. By specifying the maximum percentage of risk to incur on your remaining equity, so the Engine will dynamically adjust position size for each trade so that, combining the stop’s amplitude with position size will yield a fixed percentage of risk incurred on current equity,
2. By specifying a fixed percentage of remaining equity. Note that unless your system has a fixed stop at entry, this method will not provide maximal risk control, as risk will vary with the amplitude of the stop for every trade. This method, as the first, does however have the advantage of automatically adjusting position size to equity. It is the Engine’s default method because it has an equivalent in TV backtesting, so when flipping between indicator and strategy mode, test results will more or less correspond.
3. By specifying a fixed percentage of the Initial Capital. While this is the least preferable method, it nonetheless reflects the reality confronted by most system designers on TradingView today. In this case, risk varies both because the fixed position size in initial capital currency represents a varying percentage of remaining equity, and because the trade’s stop amplitude may vary, adding another variability vector to risk.
Note that the Engine cannot display equity results for strategies entering trades for a fixed amount of shares/contracts at a variable price.
SETTINGS/INPUTS
Because the initial text first published with a script cannot be edited later and because there are just too many options, the Engine’s Inputs will not be covered in minute detail, as they will most certainly evolve. We will go over them with broad strokes; you should be able to figure the rest out. If you have questions, just ask them here or in the PineCoders Telegram group.
Display
The display header’s checkbox does nothing.
For the moment, only one exit strategy uses a take profit level, so only that one will show information when checking “Show Take Profit Level”.
Entries
You can activate two simultaneous entry strats, each selected from the same set of strats contained in the Engine. If you select two and they fire simultaneously, the main strat’s signal will be used.
The random strat in each list uses a different seed, so you will get different results from each.
The “Filter transitions” and “Filter states” strats delegate signal generation to the selected filter(s). “Filter transitions” signals will only fire when the filter transitions into bull/bear state, so after a trade is stopped out, the next entry may take some time to trigger if the filter’s state does not change quickly. When you choose “Filter states”, then a new trade will be entered immediately after an exit in the direction the filter allows.
If you select “External Indicator”, your indicator will need to generate a +2/-2 (or a positive/negative stop value) to enter a long/short position, providing the selected filters allow for it. If you wish to use the Engine’s capacity to also derive the entry stop level from your indicator’s signal, then you must explicitly choose this option in the Entry Stops section.
Filters
You can activate as many filters as you wish; they are additive. The “Maximum stop allowed on entry” is an important component of proper risk management. If your system has an average 3% stop size and you need to trade using fixed position sizes because of alert/execution bot limitations, you must use this filter because if your system was to enter a trade with a 15% stop, that trade would incur 5 times the normal risk, and its result would account for an abnormally high proportion in your system’s performance.
Remember that any filter can also be used as an entry signal, either when it changes states, or whenever no trade is active and the filter is in a bull or bear mode.
Entry Stops
An entry stop must be selected in the Engine, as it requires a stop level before the in-trade stop is calculated. Until the selected in-trade stop strat generates a stop that comes closer to price than the entry stop (or respects another one of the in-trade stops kick in strats), the entry stop level is used.
It is here that you must select “External Indicator” if your indicator supplies a +price/-price value to be used as the entry stop. A +price is expected for a long entry and a -price value will enter a short with a stop at price. Note that the price is the absolute price, not an offset to the current price level.
In-Trade Stops
The Engine comes with many built-in in-trade stop strats. Note that some of them share the “Length” and “Multiple” field, so when you swap between them, be sure that the length and multiple in use correspond to what you want for that stop strat. Suggested defaults appear with the name of each strat in the dropdown.
In addition to the strat you wish to use, you must also determine when it kicks in to replace the initial entry’s stop, which is determined using different strats. For strats where you can define a positive or negative multiple of X, percentage or fixed value for a kick-in strat, a positive value is above the trade’s entry fill and a negative one below. A value of zero represents breakeven.
Pyramiding
What you specify in this section are the rules that allow pyramiding to happen. By themselves, these rules will not generate pyramiding entries. For those to happen, entry signals must be issued by one of the active entry strats, and conform to the pyramiding rules which act as a filter for them. The “Filter must allow entry” selection must be chosen if you want the usual system’s filters to act as additional filtering criteria for your pyramided entries.
Hard Exits
You can choose from a variety of hard exit strats. Hard exits are exit strategies which signal trade exits on specific events, as opposed to price breaching a stop level in In-Trade Stops strategies. They are self-explanatory. The last one labelled When Take Profit Level (multiple of X) is reached is the only one that uses a level, but contrary to stops, it is above price and while it is relative because it is expressed as a multiple of X, it does not move during the trade. This is the level called Take Profit that is show when the “Show Take Profit Level” checkbox is checked in the Display section.
While stops focus on managing risk, hard exit strategies try to put the emphasis on capturing opportunity.
Slippage
You can define it as a percentage or a fixed value, with different settings for entries and exits. The entry and exit markers on the chart show the impact of slippage on the entry price (the fill).
Fees
Fees, whether expressed as a percentage of position size in and out of the trade or as a fixed value per in and out, are in the same units of currency as the capital defined in the Position Sizing section. Fees being deducted from your Capital, they do not have an impact on the chart marker positions.
In-Trade Events
These events will only trigger during trades. They can be helpful to act as reminders for traders using the Engine as assistance to discretionary trading.
Post-Exit Analysis
It is normally on. Some of its results will show in the Global Numbers section of the Data Window. Only a few of the statistics generated are shown; many more are available, but commented out in the Plot module.
Date Range Filtering
Note that you don’t have to change the dates to enable/diable filtering. When you are done with a specific date range, just uncheck “Date Range Filtering” to disable date filtering.
Alert Triggers
Each selection corresponds to one condition. Conditions can be combined into a single alert as you please. Just be sure you have selected the ones you want to trigger the alert before you create the alert. For example, if you trade in both directions and you want a single alert to trigger on both types of exits, you must select both “Long Exit” and “Short Exit” before creating your alert.
Once the alert is triggered, these settings no longer have relevance as they have been saved with the alert.
When viewing charts where an alert has just triggered, if your alert triggers on more than one condition, you will need the appropriate markers active on your chart to figure out which condition triggered the alert, since plotting of markers is independent of alert management.
Position sizing
You have 3 options to determine position size:
1. Proportional to Stop -> Variable, with a cap on size.
2. Percentage of equity -> Variable.
3. Percentage of Initial Capital -> Fixed.
External Indicator
This is where you connect your indicator’s plot that will generate the signals the Engine will act upon. Remember this only works in Indicator mode.
DATA WINDOW INFORMATION
The top part of the window contains global numbers while the individual trade information appears in the bottom part. The different types of units used to express values are:
curr: denotes the currency used in the Position Sizing section of Inputs for the Initial Capital value.
quote: denotes quote currency, i.e. the value the instrument is expressed in, or the right side of the market pair (USD in EURUSD ).
X: the stop’s amplitude, itself expressed in quote currency, which we use to express a trade’s P&L, so that a trade with P&L=2X has made twice the stop’s amplitude in profit. This is sometimes referred to as R, since it represents one unit of risk. It is also the unit of measure used in the APPT, which denotes expected reward per unit of risk.
X%: is also the stop’s amplitude, but expressed as a percentage of the Entry Fill.
The numbers appearing in the Data Window are all prefixed:
“ALL:” the number is the average for all first entries and pyramided entries.
”1ST:” the number is for first entries only.
”PYR:” the number is for pyramided entries only.
”PEA:” the number is for Post-Exit Analyses
Global Numbers
Numbers in this section represent the results of all trades up to the cursor on the chart.
Average Profitability Per Trade (X): This value is the most important gauge of your strat’s worthiness. It represents the returns that can be expected from your strat for each unit of risk incurred. E.g.: your APPT is 2.0, thus for every unit of currency you invest in a trade, you can on average expect to obtain 2 after the trade. APPT is also referred to as “statistical expectancy”. If it is negative, your strategy is losing, even if your win rate is very good (it means your winning trades aren’t winning enough, or your losing trades lose too much, or both). Its counterpart in currency is also shown, as is the APPT/bar, which can be a useful gauge in deciding between rivalling systems.
Profit Factor: Gross of winning trades/Gross of losing trades. Strategy is profitable when >1. Not as useful as the APPT because it doesn’t take into account the win rate and the average win/loss per trade. It is calculated from the total winning/losing results of this particular backtest and has less predictive value than the APPT. A good profit factor together with a poor APPT means you just found a chart where your system outperformed. Relying too much on the profit factor is a bit like a poker player who would think going all in with two’s against aces is optimal because he just won a hand that way.
Win Rate: Percentage of winning trades out of all trades. Taken alone, it doesn’t have much to do with strategy profitability. You can have a win rate of 99% but if that one trade in 100 ruins you because of poor risk management, 99% doesn’t look so good anymore. This number speaks more of the system’s profile than its worthiness. Still, it can be useful to gauge if the system fits your personality. It can also be useful to traders intending to sell their systems, as low win rate systems are more difficult to sell and require more handholding of worried customers.
Equity (curr): This the sum of initial capital and the P&L of your system’s trades, including fees and slippage.
Return on Capital is the equivalent of TV’s Net Profit figure, i.e. the variation on your initial capital.
Maximum drawdown is the maximal drawdown from the highest equity point until the drop . There is also a close to close (meaning it doesn’t take into account in-trade variations) maximum drawdown value commented out in the code.
The next values are self-explanatory, until:
PYR: Avg Profitability Per Entry (X): this is the APPT for all pyramided entries.
PEA: Avg Max Opp . Available (X): the average maximal opportunity found in the Post-Exit Analyses.
PEA: Avg Drawdown to Max Opp . (X): this represents the maximum drawdown (incurred from the close at the beginning of the PEA analysis) required to reach the maximal opportunity point.
Trade Information
Numbers in this section concern only the current trade under the cursor. Most of them are self-explanatory. Use the description’s prefix to determine what the values applies to.
PYR: Avg Profitability Per Entry (X): While this value includes the impact of all current pyramided entries (and only those) and updates when you move your cursor around, P&L only reflects fees at the trade’s last bar.
PEA: Max Opp . Available (X): It’s the most profitable close reached post-trade, measured from the trade’s Exit Fill, expressed in the X value of the trade the PEA follows.
PEA: Drawdown to Max Opp . (X): This is the maximum drawdown from the trade’s Exit Fill that needs to be sustained in order to reach the maximum opportunity point, also expressed in X. Note that PEA numbers do not include slippage and fees.
EXTERNAL SIGNAL PROTOCOL
Only one external indicator can be connected to a script; in order to leverage its use to the fullest, the engine provides options to use it as either an entry signal, an entry/exit signal or a filter. When used as an entry signal, you can also use the signal to provide the entry’s stop. Here’s how this works:
For filter state: supply +1 for bull (long entries allowed), -1 for bear (short entries allowed).
For entry signals: supply +2 for long, -2 for short.
For exit signals: supply +3 for exit from long, -3 for exit from short.
To send an entry stop level with an entry signal: Send positive stop level for long entry (e.g. 103.33 to enter a long with a stop at 103.33), negative stop level for short entry (e.g. -103.33 to enter a short with a stop at 103.33). If you use this feature, your indicator will have to check for exact stop levels of 1.0, 2.0 or 3.0 and their negative counterparts, and fudge them with a tick in order to avoid confusion with other signals in the protocol.
Remember that mere generation of the values by your indicator will have no effect until you explicitly allow their use in the appropriate sections of the Engine’s Settings/Inputs.
An example of a script issuing a signal for the Engine is published by PineCoders.
RECOMMENDATIONS TO ASPIRING SYSTEM DESIGNERS
Stick to higher timeframes. On progressively lower timeframes, margins decrease and fees and slippage take a proportionally larger portion of profits, to the point where they can very easily turn a profitable strategy into a losing one. Additionally, your margin for error shrinks as the equilibrium of your system’s profitability becomes more fragile with the tight numbers involved in the shorter time frames. Avoid <1H time frames.
Know and calculate fees and slippage. To avoid market shock, backtest using conservative fees and slippage parameters. Systems rarely show unexpectedly good returns when they are confronted to the markets, so put all chances on your side by being outrageously conservative—or a the very least, realistic. Test results that do not include fees and slippage are worthless. Slippage is there for a reason, and that’s because our interventions in the market change the market. It is easier to find alpha in illiquid markets such as cryptos because not many large players participate in them. If your backtesting results are based on moving large positions and you don’t also add the inevitable slippage that will occur when you enter/exit thin markets, your backtesting will produce unrealistic results. Even if you do include large slippage in your settings, the Engine can only do so much as it will not let slippage push fills past the high or low of the entry bar, but the gap may be much larger in illiquid markets.
Never test and optimize your system on the same dataset , as that is the perfect recipe for overfitting or data dredging, which is trying to find one precise set of rules/parameters that works only on one dataset. These setups are the most fragile and often get destroyed when they meet the real world.
Try to find datasets yielding more than 100 trades. Less than that and results are not as reliable.
Consider all backtesting results with suspicion. If you never entertained sceptic tendencies, now is the time to begin. If your backtest results look really good, assume they are flawed, either because of your methodology, the data you’re using or the software doing the testing. Always assume the worse and learn proper backtesting techniques such as monte carlo simulations and walk forward analysis to avoid the traps and biases that unchecked greed will set for you. If you are not familiar with concepts such as survivor bias, lookahead bias and confirmation bias, learn about them.
Stick to simple bars or candles when designing systems. Other types of bars often do not yield reliable results, whether by design (Heikin Ashi) or because of the way they are implemented on TV (Renko bars).
Know that you don’t know and use that knowledge to learn more about systems and how to properly test them, about your biases, and about yourself.
Manage risk first , then capture opportunity.
Respect the inherent uncertainty of the future. Cleanse yourself of the sad arrogance and unchecked greed common to newcomers to trading. Strive for rationality. Respect the fact that while backtest results may look promising, there is no guarantee they will repeat in the future (there is actually a high probability they won’t!), because the future is fundamentally unknowable. If you develop a system that looks promising, don’t oversell it to others whose greed may lead them to entertain unreasonable expectations.
Have a plan. Understand what king of trading system you are trying to build. Have a clear picture or where entries, exits and other important levels will be in the sort of trade you are trying to create with your system. This stated direction will help you discard more efficiently many of the inevitably useless ideas that will pop up during system design.
Be wary of complexity. Experienced systems engineers understand how rapidly complexity builds when you assemble components together—however simple each one may be. The more complex your system, the more difficult it will be to manage.
Play! . Allow yourself time to play around when you design your systems. While much comes about from working with a purpose, great ideas sometimes come out of just trying things with no set goal, when you are stuck and don’t know how to move ahead. Have fun!
@LucF
NOTES
While the engine’s code can supply multiple consecutive entries of longs or shorts in order to scale positions (pyramid), all exits currently assume the execution bot will exit the totality of the position. No partial exits are currently possible with the Engine.
Because the Engine is literally crippled by the limitations on the number of plots a script can output on TV; it can only show a fraction of all the information it calculates in the Data Window. You will find in the Plot Module vast amounts of commented out lines that you can activate if you also disable an equivalent number of other plots. This may be useful to explore certain characteristics of your system in more detail.
When backtesting using the TV backtesting feature, you will need to provide the strategy parameters you wish to use through either Settings/Properties or by changing the default values in the code’s header. These values are defined in variables and used not only in the strategy() statement, but also as defaults in the Engine’s relevant Inputs.
If you want to test using pyramiding, then both the strategy’s Setting/Properties and the Engine’s Settings/Inputs need to allow pyramiding.
If you find any bugs in the Engine, please let us know.
THANKS
To @glaz for allowing the use of his unpublished MA Squize in the filters.
To @everget for his Chandelier stop code, which is also used as a filter in the Engine.
To @RicardoSantos for his pseudo-random generator, and because it’s from him that I first read in the Pine chat about the idea of using an external indicator as input into another. In the PineCoders group, @theheirophant then mentioned the idea of using it as a buy/sell signal and @simpelyfe showed a piece of code implementing the idea. That’s the tortuous story behind the use of the external indicator in the Engine.
To @admin for the Volatility stop’s original code and for the donchian function lifted from Ichimoku .
To @BobHoward21 for the v3 version of Volatility Stop .
To @scarf and @midtownsk8rguy for the color tuning.
To many other scripters who provided encouragement and suggestions for improvement during the long process of writing and testing this piece of code.
To J. Welles Wilder Jr. for ATR, used extensively throughout the Engine.
To TradingView for graciously making an account available to PineCoders.
And finally, to all fellow PineCoders for the constant intellectual stimulation; it is a privilege to share ideas with you all. The Engine is for all TradingView PineCoders, of course—but especially for you.
Look first. Then leap.
Multi SMA EMA WMA HMA BB (5x8 MAs Bollinger Bands) MAX MTF - RRBMulti SMA EMA WMA HMA 4x7 Moving Averages with Bollinger Bands MAX MTF by RagingRocketBull 2019
Version 1.0
All available MAX MTF versions are listed below (They are very similar and I don't want to publish them as separate indicators):
ver 1.0: 4x7 = 28 MTF MAs + 28 Levels + 3 BB = 59 < 64
ver 2.0: 5x6 = 30 MTF MAs + 30 Levels + 3 BB = 63 < 64
ver 3.0: 3x10 = 30 MTF MAs + 30 Levels + 3 BB = 63 < 64
ver 4.0: 5(4+1)x8 = 8 CurTF MAs + 32 MTF MAs + 20 Levels + 3 BB = 63 < 64
ver 5.0: 6(5+1)x6 = 6 CurTF MAs + 30 MTF MAs + 24 Levels + 3 BB = 63 < 64
ver 6.0: 4(3+1)x10 = 10 CurTF MAs + 30 MTF MAs + 20 Levels + 3 BB = 63 < 64
Fib numbers: 8, 13, 21, 34, 55, 89, 144, 233, 377
This indicator shows multiple MAs of any type SMA EMA WMA HMA etc with BB and MTF support, can show MAs as dynamically moving levels.
There are 4 MA groups + 1 BB group, a total of 4 TFs * 7 MAs = 28 MAs. You can assign any type/timeframe combo to a group, for example:
- EMAs 9,12,26,50,100,200,400 x H1, H4, D1, W1 (4 TFs x 7 MAs x 1 type)
- EMAs 8,13,21,30,34,50,55,89,100,144,200,233,377,400 x M15, H1 (2 TFs x 14 MAs x 1 type)
- D1 EMAs and SMAs 8,13,21,30,34,50,55,89,100,144,200,233,377,400 (1 TF x 14 MAs x 2 types)
- H1 WMAs 13,21,34,55,89,144,233; H4 HMAs 9,12,26,50,100,200,400; D1 EMAs 12,26,89,144,169,233,377; W1 SMAs 9,12,26,50,100,200,400 (4 TFs x 7 MAs x 4 types)
- +1 extra MA type/timeframe for BB
There are several versions: Simple, MTF, Pro MTF, Advanced MTF, MAX MTF and Ultimate MTF. This is the MAX MTF version. The Differences are listed below. All versions have BB
- Simple: you have 2 groups of MAs that can be assigned any type (5+5)
- MTF: +2 custom Timeframes for each group (2x5 MTF) +1 TF for BB, TF XY smoothing
- Pro MTF: 4 custom Timeframes for each group (4x3 MTF), 1 TF for BB, MA levels and show max bars back options
- Advanced MTF: +4 extra MAs/group (4x7 MTF), custom Ticker/Symbols, Timeframe <>= filter, Remove Duplicates Option
- MAX MTF: +2 subtypes/group, packed to the limit with max possible MAs/TFs: 4x7, 5x6, 3x10, 4(3+1)x10, 5(4+1)x8, 6(5+1)x6
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
MAX MTF version tests the limits of Pinescript trying to squeeze as many MAs/TFs as possible into a single indicator.
It's basically a maxed out Advanced version with subtypes allowing for mixed types within a group (i.e. both emas and smas in a single group/TF)
Pinescript has the following limits:
- max 40 security calls (6 calls are reserved for dupe checks and smoothing, 2 are used for BB, so only 32 calls are available)
- max 64 plot outputs (BB uses 3 outputs, so only 61 plot outputs are available)
- max 50000 (50kb) size of the compiled code
Based on those limits, you can only have the following MAs/TFs combos in a single script:
1. 4x7, 5x6, 3x10 - total number of MTF MAs must always be <= 32, and you can still have BB and Num Levels = total MAs, without any compromises
2. 5(4+1)x8, 6(5+1)x6, 4(3+1)x10 - you can use the Current Symbol/Timeframe as an extra (+1) fixed TF with the same number of MTF MAs
- you don't need to call security to display MAs on the Current Symbol/Timeframe, so the total number of MTF MAs remains the same and is still <= 32
- to fit that many MAs into the max 64 plot outputs limit you need to reduce the number of levels (not every MA Group will have corresponding levels)
Features:
- 4x7 = 28 MAs of any type
- 4x MTF groups with XY step line smoothing
- +1 extra TF/type for BB MAs
- 2 MA subtypes within each group/TF
- 4x7 = 28 MA levels with adjustable group offsets, indents and shift
- supports any existing type of MA: SMA, EMA, WMA, Hull Moving Average (HMA)
- custom tickers/symbols for each group
- show max bars back option
- show/hide both groups of MAs/levels/BB and individual MAs
- timeframe filter: show only MAs/Levels with TFs <>= Current TF
- hide MAs/Levels with duplicate TFs
- support for custom TFs that are not available in free accounts: 2D, 3D etc
- support for timeframes in H: H, 2H, 4H etc
Notes:
- Uses timeframe textbox instead of input resolution dropdown to allow for 240 120 and other custom TFs
- Uses symbol textbox instead of input symbol to avoid establishing multiple dummy security connections to the current ticker - otherwise empty symbols will prevent script from running
- Possible reasons for missing MAs on a chart:
- there may not be enough bars in history to start plotting it. For example, W1 EMA200 needs at least 200 bars on a weekly chart.
- for charts with low/fractional prices i.e. 0.00002 << 0.001 (default Y smoothing step) decrease Y smoothing as needed (set Y = 0.0000001) or disable it completely (set X,Y to 0,0)
- for charts with high price values i.e. 20000 >> 0.001 increase Y smoothing as needed (set Y = 10-20). Higher values exceeding MAs point density will cause it to disappear as there will be no points to plot. Different TFs may require diff adjustments
- TradingView Replay Mode UI and Pinescript security calls are limited to TFs >= D (D,2D,W,MN...) for free accounts
- attempting to plot any TF < D1 in Replay Mode will only result in straight lines, but all TFs will work properly in history and real-time modes. This is not a bug.
- Max Bars Back (num_bars) is limited to 5000 for free accounts (10000 for paid), will show error when exceeded. To plot on all available history set to 0 (default)
- Slow load/redraw times. This indicator becomes slower, its UI less responsive when:
- Pinescript Node.js graphics library is too slow and inefficient at plotting bars/objects in a browser window. Code optimization doesn't help much - the graphics engine is the main reason for general slowness.
- the chart has a long history (10000+ bars) in a browser's cache (you have scrolled back a couple of screens in a max zoom mode).
- Reload the page/Load a fresh chart and then apply the indicator or
- Switch to another Timeframe (old TF history will still remain in cache and that TF will be slow)
- in max possible zoom mode around 4500 bars can fit on 1 screen - this also slows down responsiveness. Reset Zoom level
- initial load and redraw times after a param change in UI also depend on TF. For example: D1/W1 - 2 sec, H1/H4 - 5-6 sec, M30 - 10 sec, M15/M5 - 4 sec, M1 - 5 sec. M30 usually has the longest history (up to 16000 bars) and W1 - the shortest (1000 bars).
- when indicator uses more MAs (plots) and timeframes it will redraw slower. Seems that up to 5 Timeframes is acceptable, but 6+ Timeframes can become very slow.
- show_last=last_bars plot limit doesn't affect load/redraw times, so it was removed from MA plot
- Max Bars Back (num_bars) default/custom set UI value doesn't seem to affect load/redraw times
- In max zoom mode all dynamic levels disappear (they behave like text)
- Dupe check includes symbol: symbol, tf, both subtypes - all must match for a duplicate group
- For the dupe check to work correctly a custom symbol must always include an exchange prefix. BB is not checked for dupes
Good Luck! Feel free to learn from/reuse the code to build your own indicators.
Multi SMA EMA WMA HMA BB (4x5 MAs Bollinger Bands) Adv MTF - RRBMulti SMA EMA WMA HMA 4x5 Moving Averages with Bollinger Bands Advanced MTF by RagingRocketBull 2019
Version 1.0
This indicator shows multiple MAs of any type SMA EMA WMA HMA etc with BB and MTF support, can show MAs as dynamically moving levels.
There are 4 MA groups + 1 BB group, a total of 4 TFs * 5 MAs = 20 MAs. You can assign any type/timeframe combo to a group, for example:
- EMAs 12,26,50,100,200 x H1, H4, D1, W1 (4 TFs x 5 MAs x 1 type)
- EMAs 8,10,13,21,30,50,55,100,200,400 x M15, H1 (2 TFs x 10 MAs x 1 type)
- D1 EMAs and SMAs 8,10,12,26,30,50,55,100,200,400 (1 TF x 10 MAs x 2 types)
- H1 WMAs 7,77,89,167,231; H4 HMAs 12,26,50,100,200; D1 EMAs 89,144,169,233,377; W1 SMAs 12,26,50,100,200 (4 TFs x 5 MAs x 4 types)
- +1 extra MA type/timeframe for BB
There are several versions: Simple, MTF, Pro MTF, Advanced MTF and Ultimate MTF. This is the Advanced MTF version. The Differences are listed below. All versions have BB
- Simple: you have 2 groups of MAs that can be assigned any type (5+5)
- MTF: +2 custom Timeframes for each group (2x5 MTF) +1 TF for BB, TF XY smoothing
- Pro MTF: 4 custom Timeframes for each group (4x3 MTF), 1 TF for BB, MA levels and show max bars back options
- Advanced MTF: +2 extra MAs/group (4x5 MTF), custom Ticker/Symbols, Timeframe <>= filter, Remove Duplicates Option
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
Features:
- 4x5 = 20 MAs of any type
- 4x MTF groups with XY step line smoothing
- +1 extra TF/type for BB MAs
- 4x5 = 20 MA levels with adjustable group offsets, indents and shift
- supports any existing type of MA: SMA, EMA, WMA, Hull Moving Average (HMA)
- custom tickers/symbols for each group - you can compare MAs of the same symbol across exchanges
- show max bars back option
- show/hide both groups of MAs/levels/BB and individual MAs
- timeframe filter: show only MAs/Levels with TFs <>= Current TF
- hide MAs/Levels with duplicate TFs
- support for custom TFs that are not available in free accounts: 2D, 3D etc
- support for timeframes in H: H, 2H, 4H etc
Notes:
- Uses timeframe textbox instead of input resolution dropdown to allow for 240 120 and other custom TFs
- Uses symbol textbox instead of input symbol to avoid establishing multiple dummy security connections to the current ticker - otherwise empty symbols will prevent script from running
- Possible reasons for missing MAs on a chart:
- there may not be enough bars in history to start plotting it. For example, W1 EMA200 needs at least 200 bars on a weekly chart.
- price << default Y smoothing step 5. For charts with low/fractional prices (i.e. 0.00002 << 5) adjust X Y smoothing as needed (set Y = 0.0000001) or disable it completely (set X,Y to 0,0)
- TradingView Replay Mode UI and Pinescript security calls are limited to TFs >= D (D,2D,W,MN...) for free accounts
- attempting to plot any TF < D1 in Replay Mode will only result in straight lines, but all TFs will work properly in history and real-time modes. This is not a bug.
- Max Bars Back (num_bars) is limited to 5000 for free accounts (10000 for paid), will show error when exceeded. To plot on all available history set to 0 (default)
- Slow load/redraw times. This indicator becomes slower, its UI less responsive when:
- Pinescript Node.js graphics library is too slow and inefficient at plotting bars/objects in a browser window. Code optimization doesn't help much - the graphics engine is the main reason for general slowness.
- the chart has a long history (10000+ bars) in a browser's cache (you have scrolled back a couple of screens in a max zoom mode).
- Reload the page/Load a fresh chart and then apply the indicator or
- Switch to another Timeframe (old TF history will still remain in cache and that TF will be slow)
- in max possible zoom mode around 4500 bars can fit on 1 screen - this also slows down responsiveness. Reset Zoom level
- initial load and redraw times after a param change in UI also depend on TF. For example:
D1/W1 - 2 sec, H1/H4 - 5-6 sec, M30 - 10 sec, M15/M5 - 4 sec, M1 - 5 sec.
M30 usually has the longest history (up to 16000 bars) and W1 - the shortest (1000 bars).
- when indicator uses more MAs (plots) and timeframes it will redraw slower. Seems that up to 5 Timeframes is acceptable, but 6+ Timeframes can become very slow.
- show_last=last_bars plot limit doesn't affect load/redraw times, so it was removed from MA plot
- Max Bars Back (num_bars) default/custom set UI value doesn't seem to affect load/redraw times
- In max zoom mode all dynamic levels disappear (they behave like text)
1. based on 3EmaBB, uses plot*, barssince and security functions
2. you can't set certain constants from input due to Pinescript limitations - change the code as needed, recompile and use as a private version
3. Levels = trackprice implementation
4. Show Max Bars Back = show_last implementation
5. swma has a fixed length = 4, alma and linreg have additional offset and smoothing params
6. Smoothing is applied by default for visual aesthetics on MTF. To use exact ma mtf values (lines with stair stepping) - disable it
Good Luck! You can explore, modify/reuse the code to build your own indicators.
Multi SMA EMA WMA HMA BB (4x3 MAs Bollinger Bands) Pro MTF - RRBMulti SMA EMA WMA HMA 4x3 Moving Averages with Bollinger Bands Pro MTF by RagingRocketBull 2018
Version 1.0
This indicator shows multiple MAs of any type SMA EMA WMA HMA etc with BB and MTF support, can show MAs as dynamically moving levels.
There are 4 MA groups + 1 BB group. You can assign any type/timeframe combo to a group, for example:
- EMAs 50,100,200 x H1, H4, D1, W1 (4 TFs x 3 MAs x 1 type)
- EMAs 8,13,21,55,100,200 x M15, H1 (2 TFs x 6 MAs x 1 type)
- D1 EMAs and SMAs 12,26,50,100,200,400 (1 TF x 6 MAs x 2 types)
- H1 WMAs 7,77,231; H4 HMAs 50,100,200; D1 EMAs 144,169,233; W1 SMAs 50,100,200 (4 TFs x 3 MAs x 4 types)
- +1 extra MA type/timeframe for BB
compile time: 25-30 sec
full redraw time after parameter change in UI: 3 sec
There are several versions: Simple, MTF, Pro MTF, Advanced MTF and Ultimate MTF. This is the Pro MTF version. The Differences are listed below. All versions have BB
- Simple: you have 2 groups of MAs that can be assigned any type (5+5)
- MTF: +2 custom Timeframes for each group (2x5 MTF)
- Pro MTF: +4 custom Timeframes for each group (4x3 MTF), MA levels and show max bars back options
- Advanced MTF: +2 extra MAs/group (4x5 MTF), custom Ticker/Symbol, backreferences for type, TF and MA lengths in UI
- Ultimate MTF: +individual settings for each MA, custom Ticker/Symbols
Features:
- 4x3 = 12 MAs of any type including Hull Moving Average (HMA)
- 4x MTF groups with step line smoothing
- BB +1 extra TF/type for BB MAs
- 12 MA levels with adjustable group offsets, indents and shift
- show max bars back
- you can show/hide both groups of MAs/levels and individual MAs
Notes:
1. based on 3EmaBB, uses plot*, barssince and security functions
2. you can't set certain constants from input due to Pinescript limitations - change the code as needed, recompile and use as a private version
3. Levels = trackprice implementation
4. Show Max Bars Back = show_last implementation
5. uses timeframe textbox instead of input resolution to allow for 120 240 and other custom TFs. Also supports TFs in hours: 2H or H2
6. swma has a fixed length = 4, alma and linreg have additional offset and smoothing params
7. Smoothing is applied by default for visual aesthetics on MTF. To use exact ma mtf values (lines with stair stepping) - disable it
MTF Notes:
- uses simple timeframe textbox instead of input resolution dropdown to allow for 120, 240 and other custom TFs, also supports timeframes in H: 2H, H2
- Groups that are not assigned a Custom TF will use Current Timeframe (0).
- MTF will work for any MA type assigned to the group
- MTF works both ways: you can display a higher TF MA/BB on a lower TF or a lower TF MA/BB on a higher TF.
- MTF MA values are normally aligned at the boundary of their native timeframe. This produces stair stepping when a higher TF MA is viewed on a lower TF.
Therefore X Y Point Density/Smoothing is applied by default on MA MTF for visual aesthetics. Set both to 0 to disable and see exact ma mtf values (lines with stair stepping and original mtf alignment).
- Smoothing is disabled for BB MTF bands because fill doesn't work with smoothed MAs after duplicate values are replaced with na.
- MTF MA Value fluctuation is possible on the current bar due to default security lookahead
Smoothing:
- X,Y == 0 - X,Y smoothing disabled (stair stepping on high TFs)
- X == 0, Y > 0 - X,Y smoothing applied to all TFs
- Y == 0, X > 0 - X smoothing applied to all TFs < deltaX_max_tf, Y smoothing disabled
- X > 0, Y > 0 - Y smoothing applied to all TFs, then X smoothing applied to all TFs < deltaX_max_tf
X Smoothing with Y == 0 - shows only every deltaX-th point starting from the first bar.
X Smoothing with Y > 0 - shows only every deltaX-th point starting from the last shown Y point, essentially filling huge gaps remaining after Y Smoothing with points and preserving the curve's general shape
X Smoothing on high TFs with already scarce points produces weird curve shapes, it works best only on high density lower TFs
Y Smoothing reduces points on all TFs, removes adjacent points with prices within deltaY, while preserving the smaller curve details.
A combination of X,Y produces the most accurate smoothing. Higher delta value - larger range, more points removed.
Show Max Bars Back:
- can't set plot show_last from input -> implemented using a timenow based range check
- you can't delete/modify history once plotted, so essentially it just sets a start point for plotting (from num_bars bars back) that works only in realtime mode (not in replay)
Levels:
You can plot current MA value using plot trackprice=true or by checking Show Price Line in Style. Problem is:
- you can only change color (not the dashed line style, width), have both ma + price line (not just the line), and it's full screen wide
- you can't set plot trackprice from input => implemented using plotshape/plotchar with fixed text labels serving as levels
- there's no other way of creating a dynamic level: hline, plot, offset - nothing else works.
- you can't plot a text var - all text strings must be constants, so you can't change the style, width and text labels without recompiling.
- from input you can only adjust offset, indent and shift for each level group, and change color
- the dot below each level line is the exact MA value. If you want just the line swap plotshape with plotchar, recompile and save as your private version, adjust Y shift.
To speed up redraw times: reduce last_bars to ~2000, recompile and use as your own private version
Pinescript is a rudimentary language (should be called Painscript instead) that can basically only plot data. You can't do much else. Please see the code for tips and hints.
Certain things just can't be done or require shady workarounds and weeks of testing trying to resolve weird node.js compiler errors.
Feel free to learn from/reuse/change the code as needed and use as your own private version. See comments in code. Good Luck!
Gidra's Vchain Strategy v0.1Tested on "BTC/USD", this is a reversible strategy
If the RSI is lower than "RSI Limit" (for last "RSI Signals" candles) and there were "Open Color, Bars" green Heiken Ashi candles - close short, open long
If the RSI is higher than 100-"RSI Limit" (for last "RSI Signals" candles) and there were "Open Color, Bars" red Heiken Ashi candles - close long, open short
- timeframe: 5m (the best)
RSI Period = 14
RSI Limit = 30
RSI Signals = 3
Open Color = 2
Piramiding = 100
Lot = 100 %
- timeframe: 1h
RSI Period = 2
RSI Limit = 30
RSI Signals = 3
Open Color = 2
Piramiding = 100
Lot = 100 %
Market Outlook Score (MOS)Overview
The "Market Outlook Score (MOS)" is a custom technical indicator designed for TradingView, written in Pine Script version 6. It provides a quantitative assessment of market conditions by aggregating multiple factors, including trend strength across different timeframes, directional movement (via ADX), momentum (via RSI changes), volume dynamics, and volatility stability (via ATR). The MOS is calculated as a weighted score that ranges typically between -1 and +1 (though it can exceed these bounds in extreme conditions), where positive values suggest bullish (long) opportunities, negative values indicate bearish (short) setups, and values near zero imply neutral or indecisive markets.
This indicator is particularly useful for traders seeking a holistic "outlook" score to gauge potential entry points or market bias. It overlays on a separate pane (non-overlay mode) and visualizes the score through horizontal threshold lines and dynamic labels showing the numeric MOS value along with a simple trading decision ("Long", "Short", or "Neutral"). The script avoids using the plot function for compatibility reasons (e.g., potential TradingView bugs) and instead relies on hline for static lines and label.new for per-bar annotations.
Key features:
Multi-Timeframe Analysis: Incorporates slope data from 5-minute, 15-minute, and 30-minute charts to capture short-term trends.
Trend and Strength Integration: Uses ADX to weight trend bias, ensuring stronger signals in trending markets.
Momentum and Volume: Includes RSI momentum impulses and volume deviations for added confirmation.
Volatility Adjustment: Factors in ATR changes to assess market stability.
Customizable Inputs: Allows users to tweak periods for lookback, ADX, and ATR.
Decision Labels: Automatically classifies the MOS into actionable categories with visual labels.
This indicator is best suited for intraday or swing trading on volatile assets like stocks, forex, or cryptocurrencies. It does not generate buy/sell signals directly but can be combined with other tools (e.g., moving averages or oscillators) for comprehensive strategies.
Inputs
The script provides three user-configurable inputs via TradingView's input panel:
Lookback Period (lookback):
Type: Integer
Default: 20
Range: Minimum 10, Maximum 50
Purpose: Defines the number of bars used in slope calculations for trend analysis. A shorter lookback makes the indicator more sensitive to recent price action, while a longer one smooths out noise for longer-term trends.
ADX Period (adxPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Sets the smoothing period for the Average Directional Index (ADX) and its components (DI+ and DI-). Standard value is 14, but shorter periods increase responsiveness, and longer ones reduce false signals.
ATR Period (atrPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Determines the period for the Average True Range (ATR) calculation, which measures volatility. Adjust this to match your trading timeframe—shorter for scalping, longer for positional trading.
These inputs allow customization without editing the code, making the indicator adaptable to different market conditions or user preferences.
Core Calculations
The MOS is computed through a series of steps, blending trend, momentum, volume, and volatility metrics. Here's a breakdown:
Multi-Timeframe Slopes:
The script fetches data from higher timeframes (5m, 15m, 30m) using request.security.
Slope calculation: For each timeframe, it computes the linear regression slope of price over the lookback period using the formula:
textslope = correlation(close, bar_index, lookback) * stdev(close, lookback) / stdev(bar_index, lookback)
This measures the rate of price change, where positive slopes indicate uptrends and negative slopes indicate downtrends.
Variables: slope5m, slope15m, slope30m.
ATR (Average True Range):
Calculated using ta.atr(atrPeriod).
Represents average volatility over the specified period. Used later to derive volatility stability.
ADX (Average Directional Index):
A detailed, manual implementation (not using built-in ta.adx for customization):
Computes upward movement (upMove = high - high ) and downward movement (downMove = low - low).
Derives +DM (Plus Directional Movement) and -DM (Minus Directional Movement) by filtering non-relevant moves.
Smooths true range (trur = ta.rma(ta.tr(true), adxPeriod)).
Calculates +DI and -DI: plusDI = 100 * ta.rma(plusDM, adxPeriod) / trur, similarly for minusDI.
DX: dx = 100 * abs(plusDI - minusDI) / max(plusDI + minusDI, 0.0001).
ADX: adx = ta.rma(dx, adxPeriod).
ADX values above 25 typically indicate strong trends; here, it's normalized (divided by 50) to influence the trend bias.
Volume Delta (5m Timeframe):
Fetches 5m volume: volume_5m = request.security(syminfo.tickerid, "5", volume, lookahead=barmerge.lookahead_on).
Computes a 12-period SMA of volume: avgVolume = ta.sma(volume_5m, 12).
Delta: (volume_5m - avgVolume) / avgVolume (or 0 if avgVolume is zero).
This measures relative volume spikes, where positive deltas suggest increased interest (bullish) and negative suggest waning activity (bearish).
MOS Components and Final Calculation:
Trend Bias: Average of the three slopes, normalized by close price and scaled by 100, then weighted by ADX influence: (slope5m + slope15m + slope30m) / 3 / close * 100 * (adx / 50).
Emphasizes trends in strong ADX conditions.
Momentum Impulse: Change in 5m RSI(14) over 1 bar, divided by 50: ta.change(request.security(syminfo.tickerid, "5", ta.rsi(close, 14), lookahead=barmerge.lookahead_on), 1) / 50.
Captures short-term momentum shifts.
Volatility Clarity: 1 - ta.change(atr, 1) / max(atr, 0.0001).
Measures ATR stability; values near 1 indicate low volatility changes (clearer trends), while lower values suggest erratic markets.
MOS Formula: Weighted average:
textmos = (0.35 * trendBias + 0.25 * momentumImpulse + 0.2 * volumeDelta + 0.2 * volatilityClarity)
Weights prioritize trend (35%) and momentum (25%), with volume and volatility at 20% each. These can be adjusted in code for experimentation.
Trading Decision:
A variable mosDecision starts as "Neutral".
If mos > 0.15, set to "Long".
If mos < -0.15, set to "Short".
Thresholds (0.15 and -0.15) are hardcoded but can be modified.
Visualization and Outputs
Threshold Lines (using hline):
Long Threshold: Horizontal dashed green line at +0.15.
Short Threshold: Horizontal dashed red line at -0.15.
Neutral Line: Horizontal dashed gray line at 0.
These provide visual reference points for MOS interpretation.
Dynamic Labels (using label.new):
Placed at each bar's index and MOS value.
Text: Formatted MOS value (e.g., "0.2345") followed by a newline and the decision (e.g., "Long").
Style: Downward-pointing label with gray background and white text for readability.
This replaces a traditional plot line, showing exact values and decisions per bar without cluttering the chart.
The indicator appears in a separate pane below the main price chart, making it easy to monitor alongside price action.
Usage Instructions
Adding to TradingView:
Copy the script into TradingView's Pine Script editor.
Save and add to your chart via the "Indicators" menu.
Select a symbol and timeframe (e.g., 1-minute for intraday).
Interpretation:
Long Signal: MOS > 0.15 – Consider bullish positions if supported by other indicators.
Short Signal: MOS < -0.15 – Potential bearish setups.
Neutral: Between -0.15 and 0.15 – Avoid trades or wait for confirmation.
Watch for MOS crossings of thresholds for momentum shifts.
Combine with price patterns, support/resistance, or volume for better accuracy.
Limitations and Considerations:
Lookahead Bias: Uses barmerge.lookahead_on for multi-timeframe data, which may introduce minor forward-looking bias in backtesting (use with caution).
No Alerts Built-In: Add custom alerts via TradingView's alert system based on MOS conditions.
Performance: Tested for compatibility; may require adjustments for illiquid assets or extreme volatility.
Backtesting: Use TradingView's strategy tester to evaluate historical performance, but remember past results don't guarantee future outcomes.
Customization: Edit weights in the MOS formula or thresholds to fit your strategy.
This indicator distills complex market data into a single score, aiding decision-making while encouraging users to verify signals with additional analysis. If you need modifications, such as restoring plot functionality or adding features, provide details for further refinement.
Best Strategy with Clear SL/TP Zones by Masum Iftee//@version=5
indicator("Best Strategy with Clear SL/TP Zones", overlay=true, max_labels_count=500, max_boxes_count=500)
// Inputs
tpPerc = input.float(0.2, "Take Profit %", step=0.05) // TP %
slPerc = input.float(0.1, "Stop Loss %", step=0.05) // SL %
boxBars = input.int(10, "Box Length (Bars)") // how many bars the SL/TP boxes extend
// Simple EMA crossover signals (replace with your own logic later)
emaFast = ta.ema(close, 10)
emaSlow = ta.ema(close, 50)
bullish = ta.crossover(emaFast, emaSlow)
bearish = ta.crossunder(emaFast, emaSlow)
// Function to create SL/TP box
createBox(_from, _to, _y1, _y2, _color) =>
box.new(_from, _y1, _to, _y2, bgcolor=color.new(_color, 85), border_color=_color)
// Long setup
if bullish
label.new(bar_index, low, "BUY", style=label.style_label_up, color=color.green, textcolor=color.white)
// SL / TP prices
slPrice = close * (1 - slPerc/100)
tpPrice = close * (1 + tpPerc/100)
// SL Box (red zone below entry)
createBox(bar_index, bar_index + boxBars, slPrice, close, color.red)
// TP Box (green zone above entry)
createBox(bar_index, bar_index + boxBars, close, tpPrice, color.green)
// Short setup
if bearish
label.new(bar_index, high, "SELL", style=label.style_label_down, color=color.red, textcolor=color.white)
// SL / TP prices
slPrice = close * (1 + slPerc/100)
tpPrice = close * (1 - tpPerc/100)
// SL Box (red zone above entry)
createBox(bar_index, bar_index + boxBars, close, slPrice, color.red)
// TP Box (green zone below entry)
createBox(bar_index, bar_index + boxBars, tpPrice, close, color.green)
The Barking Rat LiteMomentum & FVG Reversion Strategy
The Barking Rat Lite is a disciplined, short-term mean-reversion strategy that combines RSI momentum filtering, EMA bands, and Fair Value Gap (FVG) detection to identify short-term reversal points. Designed for practical use on volatile markets, it focuses on precise entries and ATR-based take profit management to balance opportunity and risk.
Core Concept
This strategy seeks potential reversals when short-term price action shows exhaustion outside an EMA band, confirmed by momentum and FVG signals:
EMA Bands:
Parameters used: A 20-period EMA (fast) and 100-period EMA (slow).
Why chosen:
- The 20 EMA is sensitive to short-term moves and reflects immediate momentum.
- The 100 EMA provides a slower, structural anchor.
When price trades outside both bands, it often signals overextension relative to both short-term and medium-term trends.
Application in strategy:
- Long entries are only considered when price dips below both EMAs, identifying potential undervaluation.
- Short entries are only considered when price rises above both EMAs, identifying potential overvaluation.
This dual-band filter avoids counter-trend signals that would occur if only a single EMA was used, making entries more selective..
Fair Value Gap Detection (FVG):
Parameters used: The script checks for dislocations using a 12-bar lookback (i.e. comparing current highs/lows with values 12 candles back).
Why chosen:
- A 12-bar displacement highlights significant inefficiencies in price structure while filtering out micro-gaps that appear every few bars in high-volatility markets.
- By aligning FVG signals with candle direction (bullish = close > open, bearish = close < open), the strategy avoids random gaps and instead targets ones that suggest exhaustion.
Application in strategy:
- Bullish FVGs form when earlier lows sit above current highs, hinting at downward over-extension.
- Bearish FVGs form when earlier highs sit below current lows, hinting at upward over-extension.
This gives the strategy a structural filter beyond simple oscillators, ensuring signals have price-dislocation context.
RSI Momentum Filter:
Parameters used: 14-period RSI with thresholds of 80 (overbought) and 20 (oversold).
Why chosen:
- RSI(14) is a widely recognized momentum measure that balances responsiveness with stability.
- The thresholds are intentionally extreme (80/20 vs. the more common 70/30), so the strategy only engages at genuine exhaustion points rather than frequent minor corrections.
Application in strategy:
- Longs trigger when RSI < 20, suggesting oversold exhaustion.
- Shorts trigger when RSI > 80, suggesting overbought exhaustion.
This ensures entries are not just technically valid but also backed by momentum extremes, raising conviction.
ATR-Based Take Profit:
Parameters used: 14-period ATR, with a default multiplier of 4.
Why chosen:
- ATR(14) reflects the prevailing volatility environment without reacting too much to outliers.
- A multiplier of 4 is a pragmatic compromise: wide enough to let trades breathe in volatile conditions, but tight enough to enforce disciplined exits before mean reversion fades.
Application in strategy:
- At entry, a fixed target is set = Entry Price ± (ATR × 4).
- This target scales automatically with volatility: narrower in calm periods, wider in explosive markets.
By avoiding discretionary exits, the system maintains rule-based discipline.
Visual Signals on Chart
Blue “▲” below candle: Potential long entry
Orange/Yellow “▼” above candle: Potential short entry
Green “✔️”: Trade closed at ATR take profit
Blue (20 EMA) & Orange (100 EMA) lines: Dynamic channel reference
⚙️Strategy report properties
Position size: 25% equity per trade
Initial capital: 10,000.00 USDT
Pyramiding: 10 entries per direction
Slippage: 2 ticks
Commission: 0.055% per side
Backtest timeframe: 1-minute
Backtest instrument: HYPEUSDT
Backtesting range: Jul 28, 2025 — Aug 17, 2025
Note on Sample Size:
You’ll notice the report displays fewer than the ideal 100 trades in the strategy report above. This is intentional. The goal of the script is to isolate high-quality, short-term reversal opportunities while filtering out low-conviction setups. This means that the Barking Rat Lite strategy is very selective, filtering out over 90% of market noise. The brief timeframe shown in the strategy report here illustrates its filtering logic over a short window — not its full capabilities. As a result, even on lower timeframes like the 1-minute chart, signals are deliberately sparse — each one must pass all criteria before triggering.
For a larger dataset:
Once the strategy is applied to your chart, users are encouraged to expand the lookback range or apply the strategy to other volatile pairs to view a full sample.
💡Why 25% Equity Per Trade?
While it's always best to size positions based on personal risk tolerance, we defaulted to 25% equity per trade in the backtesting data — and here’s why:
Backtests using this sizing show manageable drawdowns even under volatile periods.
The strategy generates a sizeable number of trades, reducing reliance on a single outcome.
Combined with conservative filters, the 25% setting offers a balance between aggression and control.
Users are strongly encouraged to customize this to suit their risk profile.
What makes Barking Rat Lite valuable
Combines multiple layers of confirmation: EMA bands + FVG + RSI
Adaptive to volatility: ATR-based exits scale with market conditions
Clear, actionable visuals: Easy to monitor and manage trades
NAS100 Component Sentiment Scanner# NAS100 Component Sentiment Scanner
## 🎯 Overview
The NAS100 Component Sentiment Scanner analyzes the top-weighted stocks in the NASDAQ-100 index to provide real-time bullish/bearish sentiment signals that can help predict NAS100 price movements. This indicator combines multiple technical analysis methods to give traders a comprehensive view of underlying market sentiment.
## 📊 How It Works
The indicator calculates sentiment scores for major NASDAQ-100 components (AAPL, MSFT, NVDA, GOOGL, AMZN, META, TSLA, AVGO, COST, NFLX) using:
- **RSI Analysis**: Identifies overbought/oversold conditions
- **Moving Average Trends**: Compares fast vs slow MA positioning
- **Volume Confirmation**: Validates moves with volume thresholds
- **Price Momentum**: Analyzes recent price direction
- **Market Cap Weighting**: Uses actual NASDAQ-100 weightings for accuracy
## 🚀 Key Features
### Real-Time Sentiment Analysis
- Weighted composite score based on individual stock analysis
- Color-coded sentiment line (Green = Bullish, Red = Bearish)
- Dynamic background coloring for strong signals
### Interactive Data Table
- Shows individual stock scores and signals
- Bullish/Bearish stock count summary
- Customizable position and size
### Smart Signal System
- **Bullish Signals**: Green triangle up when sentiment crosses threshold
- **Bearish Signals**: Red triangle down when sentiment falls below threshold
- **Alert Conditions**: Automatic notifications for signal changes
## ⚙️ Customization Options
### Technical Analysis Settings
- **RSI Period**: Adjust lookback period (default: 14)
- **RSI Levels**: Set overbought/oversold thresholds
- **Moving Averages**: Configure fast/slow MA periods
- **Volume Threshold**: Set volume confirmation multiplier
### Signal Thresholds
- **Bullish/Bearish Levels**: Customize trigger points
- **Strong Signal Levels**: Set extreme sentiment thresholds
- Fine-tune sensitivity to market conditions
### Display Options
- **Toggle Table**: Show/hide sentiment data table
- **Table Position**: 6 position options (Top/Bottom/Middle + Left/Right)
- **Table Size**: Choose from Tiny, Small, Normal, or Large
- **Background Colors**: Enable/disable signal backgrounds
- **Signal Arrows**: Show/hide buy/sell indicators
### Stock Selection
- **Individual Control**: Enable/disable any of the 10 major stocks
- **Dynamic Weighting**: Automatically adjusts calculations based on selected stocks
- **Flexible Analysis**: Focus on specific sectors or market leaders
## 📈 How to Use
### 1. Basic Setup
1. Add the indicator to your NAS100 chart
2. Default settings work well for most traders
3. Observe the sentiment line and signals
### 2. Signal Interpretation
- **Score > 30**: Bullish bias for NAS100
- **Score > 50**: Strong bullish signal
- **Score -30 to 30**: Neutral/consolidation
- **Score < -30**: Bearish bias for NAS100
- **Score < -50**: Strong bearish signal
### 3. Trading Strategies
**Trend Following:**
- Buy NAS100 when bullish signals appear
- Sell/short when bearish signals trigger
- Use background colors for quick visual confirmation
**Divergence Trading:**
- Watch for sentiment/price divergences
- Strong sentiment with weak NAS100 price = potential breakout
- Weak sentiment with strong NAS100 price = potential reversal
**Consensus Trading:**
- Monitor bullish/bearish stock counts in table
- 8+ stocks aligned = strong directional bias
- Mixed signals = wait for clearer consensus
### 4. Advanced Usage
- Combine with your existing NAS100 trading strategy
- Use multiple timeframes for confirmation
- Adjust thresholds based on market volatility
- Focus on specific stocks by disabling others
## 🔔 Alert Setup
The indicator includes built-in alert conditions:
1. Go to TradingView Alerts
2. Select "NAS100 Component Sentiment Scanner"
3. Choose from available alert types:
- NAS100 Bullish Signal
- NAS100 Bearish Signal
- Strong Bullish Consensus
- Strong Bearish Consensus
## 💡 Pro Tips
### Optimization
- **High Volatility**: Increase signal thresholds (±40, ±60)
- **Low Volatility**: Decrease thresholds (±20, ±40)
- **Day Trading**: Use smaller table, focus on real-time signals
- **Swing Trading**: Enable background colors, larger thresholds
### Best Practices
- Don't use as a standalone system - combine with price action
- Check individual stock table for context
- Monitor during market open for most reliable signals
- Consider earnings seasons for individual stock impacts
### Market Conditions
- **Trending Markets**: Higher accuracy, use with trend following
- **Ranging Markets**: Watch for false signals, increase thresholds
- **News Events**: Individual stock news can skew sentiment temporarily
## 🎨 Visual Guide
- **Green Line Above Zero**: Bullish sentiment building
- **Red Line Below Zero**: Bearish sentiment building
- **Background Color Changes**: Strong signal confirmation
- **Triangle Arrows**: Entry/exit signal points
- **Table Colors**: Quick sentiment overview
## ⚠️ Important Notes
- This indicator analyzes component stocks, not NAS100 directly
- Market cap weightings approximate real NASDAQ-100 weightings
- Sentiment can change rapidly during volatile periods
- Always use proper risk management
- Combine with other technical analysis tools
## 🔧 Troubleshooting
- **No signals**: Check if thresholds are too extreme
- **Too many signals**: Increase threshold sensitivity
- **Table not showing**: Ensure "Show Sentiment Table" is enabled
- **Missing stocks**: Verify individual stock toggles in settings
---
**Suitable for**: Day traders, swing traders, NAS100 specialists, index traders
**Best Timeframes**: 5min, 15min, 1H, 4H
**Market Sessions**: US market hours for highest accuracy
Chart-Only Scanner — Pro Table v2.5.1Chart-Only Scanner — Pro Table v2.5
User Manual (Pine Script v6)
What this tool does (in one line)
A compact, on-chart table that scores the current chart symbol (or an optional override) using momentum, volume, trend, volatility, and pattern checks—so you can quickly decide UP, DOWN, or WAIT.
Quick Start (90 seconds)
Add the indicator to any chart and timeframe (1m…1M).
Leave “Override chart symbol” = OFF to auto-use the chart’s symbol.
Choose your layout:
Row (wide horizontal strip), or Grid (title + labeled cells).
Pick a size preset (Micro, Small, Medium, Large, Mobile).
Optional: turn on “Use Higher TF (EMA 20/50)” and set HTF Multiplier (e.g., 4 ⇒ if chart is 15m, HTF is 60m).
Watch the table:
DIR (↑/↓/→), ROC%, MOM, VOL, EMA stack, HTF, REV, SCORE, ACT.
Add an alert if you want: the script fires when |SCORE| ≥ Action threshold.
What to expect
A small table appears on the chart corner you choose, updating each bar (or only at bar close if you keep default smart-update).
The ACT cell shows 🔥 (strong), 👀 (medium), or ⏳ (weak).
Panels & Settings (every option explained)
Core
Momentum Period: Lookback for rate-of-change (ROC%). Shorter = more reactive; longer = smoother.
ROC% Threshold: Minimum absolute ROC% to call direction UP (↑) or DOWN (↓); otherwise →.
Require Volume Confirmation: If ON and VOL ≤ 1.0, the SCORE is forced to 0 (prevents low-volume false positives).
Override chart symbol + Custom symbol: By default, the indicator uses the chart’s symbol. Turn this ON to lock to a specific ticker (e.g., a perpetual).
Higher TF
Use Higher TF (EMA 20/50): Compares EMA20 vs EMA50 on a higher timeframe.
HTF Multiplier: Higher TF = (chart TF × multiplier).
Example: on 3H chart with multiplier 2 ⇒ HTF = 6H.
Volatility & Oscillators
ATR Length: Used to show ATR% (ATR relative to price).
RSI Length: Standard RSI; colors: green ≤30 (oversold), red ≥70 (overbought).
Stoch %K Length: With %D = SMA(%K, 3).
MACD Fast/Slow/Signal: Standard MACD values; we display Line, Signal, Histogram (L/S/H).
ADX Length (Wilder): Wilder’s smoothing (internal derivation); also shows +DI / −DI if you enable the ADX column.
EMAs / Trend
EMA Fast/Mid/Slow: We compute EMA(20/50/200) by default (editable).
EMA Stack: Bull if Fast > Mid > Slow; Bear if Fast < Mid < Slow; Flat otherwise.
Benchmark (optional, OFF by default)
Show Relative Strength vs Benchmark: Displays RS% = ROC(symbol) − ROC(benchmark) over the Momentum Period.
Benchmark Symbol: Ticker used for comparison (e.g., BTCUSDT as a market proxy).
Columns (show/hide)
Toggle which fields appear in the table. Hiding unused fields keeps the layout clean (especially on mobile).
Display
Layout Mode:
Row = a single two-row strip; each column is a metric.
Grid = a title row plus labeled pairs (label/value) arranged in rows.
Size Preset: Micro, Small, Medium, Large, Mobile change text size and the grid density.
Table Corner: Where the panel sits (e.g., Top Right).
Opaque Table Background: ON = dark card; OFF = transparent(ish).
Update Every Bar: ON = update intra-bar; OFF = smart update (last bar / real-time / confirmed history).
Action threshold (|score|): The cutoff for 🔥 and alert firing (default 70).
How to read each field
CHART: The active symbol name (or your custom override).
DIR: ↑ (ROC% > threshold), ↓ (ROC% < −threshold), → otherwise.
ROC%: Rate of change over Momentum Period.
Formula: (Close − Close ) / Close × 100.
MOM: A scaled momentum score: min(100, |ROC%| × 10).
VOL: Volume ratio vs 20-bar SMA: Volume / SMA(Volume,20).
1.5 highlights as yellow (significant participation).
ATR%: (ATR / Close) × 100 (volatility relative to price).
RSI: Colored for extremes: ≤30 green, ≥70 red.
Stoch K/D: %K and %D numbers.
MACD L/S/H: Line, Signal, Histogram. Histogram color reflects sign (green > 0, red < 0).
ADX, +DI, −DI: Trend strength and directional components (Wilder). ADX ≥ 25 is highlighted.
EMA 20/50/200: Current EMA values (editable lengths).
STACK: Bull/Bear/Flat as defined above.
VWAP%: (Close − VWAP) / Close × 100 (premium/discount to VWAP).
HTF: ▲ if HTF EMA20 > EMA50; ▼ if <; · if flat/off.
RS%: Symbol’s ROC% − Benchmark ROC% (positive = outperforming).
REV (reversal):
🟢 Eng/Pin = bullish engulfing or bullish pin detected,
🔴 Eng/Pin = bearish engulfing or bearish pin,
· = none.
SCORE (absolute shown as a number; sign shown via DIR and ACT):
Components:
base = MOM × 0.4
volBonus = VOL > 1.5 ? 20 : VOL × 13.33
htfBonus = use_mtf ? (HTF == DIR ? 30 : HTF == 0 ? 15 : 0) : 0
trendBonus = (STACK == DIR) ? 10 : 0
macdBonus = 0 (placeholder for future versions)
scoreRaw = base + volBonus + htfBonus + trendBonus + macdBonus
SCORE = DIR ≥ 0 ? scoreRaw : −scoreRaw
If Require Volume Confirmation and VOL ≤ 1.0 ⇒ SCORE = 0.
ACT:
🔥 if |SCORE| ≥ threshold
👀 if 50 < |SCORE| < threshold
⏳ otherwise
Practical examples
Strong long (trend + participation)
DIR = ↑, ROC% = +3.2, MOM ≈ 32, VOL = 1.9, STACK = Bull, HTF = ▲, REV = 🟢
SCORE: base(12.8) + volBonus(20) + htfBonus(30) + trend(10) ≈ 73 → ACT = 🔥
Action idea: look for longs on pullbacks; confirm risk with ATR%.
Weak long (no volume)
DIR = ↑, ROC% = +1.0, but VOL = 0.8 and Require Volume Confirmation = ON
SCORE forced to 0 → ACT = ⏳
Action: wait for volume > 1.0 or turn off confirmation knowingly.
Bearish reversal warning
DIR = →, REV = 🔴 (bearish engulfing), RSI = 68, HTF = ▼
SCORE may be mid-range; ACT = 👀
Action: watch for breakdown and rising VOL.
Alerts (how to use)
The script calls alert() whenever |SCORE| ≥ Action threshold.
To receive pop-ups, sounds, or emails: click “⏰ Alerts” in TradingView, choose this indicator, and pick “Any alert() function call.”
The alert message includes: symbol, |SCORE|, DIR.
Layout, Size, and Corner tips
Row is best when you want a compact status ribbon across the top.
Grid is clearer on big screens or when you enable many columns.
Size:
Mobile = one pair per row (tall, readable)
Micro/Small = dense; good for many fields
Large = presentation/screenshots
Corner: If the table overlaps price, change the corner or set Opaque Background = OFF.
Repaint & timeframe behavior
Default smart update prefers stability (last bar / live / confirmed history).
For a stricter, “close-only” behavior (less repaint): turn Update Every Bar = OFF and avoid Heikin Ashi when you want raw market OHLC (HA modifies price inputs).
HTF logic is derived from a clean, integer multiple of your chart timeframe (via multiplier). It works with 3H/4H and any TF.
Performance notes
The script analyzes one symbol (chart or override) with multiple metrics using efficient tuple requests.
If you later want a multi-symbol grid, do it with pages (10–15 per page + rotate) to stay within platform limits (recommended future add-on).
Troubleshooting
No table visible
Ensure the indicator is added and not hidden.
Try toggling Opaque Background or switch Corner (it might be behind other drawings).
Keep Columns count reasonable for the chosen Size.
If you turned ON Override, verify the Custom symbol exists on your data provider.
Numbers look different on HA candles
Heikin Ashi modifies OHLC; switch to regular candles if you need raw price metrics.
3H/4H issues
Use integer HTF Multiplier (e.g., 2, 4). The tool builds the correct string internally; no manual timeframe strings needed.
Power user tips
Volume gating: keeping Require Volume Confirmation = ON filters most fake moves; if you’re a scalper, reduce strictness or turn it off.
Action threshold: 60–80 is typical. Higher = fewer but stronger signals.
Benchmark RS%: great for spotting leaders/laggards; positive RS% = outperformance vs benchmark.
Change policy & safety
This version doesn’t alter your historical logic you tested (no radical changes).
Any future “radical” change (score weights, HTF logic, UI hiding data) will ship with a toggle and an Impact Statement so you can keep old behavior if you prefer.
Glossary (quick)
ROC%: Percent change over N bars.
MOM: Scaled momentum (0–100).
VOL ratio: Volume vs 20-bar average.
ATR%: ATR as % of price.
ADX/DI: Trend strength / direction components (Wilder).
EMA stack: Relationship between EMAs (bullish/bearish/flat).
VWAP%: Premium/discount to VWAP.
RS%: Relative strength vs benchmark.
Trend Signals with TP & SL Kang//@version=5
strategy("Buy/Sell with SL & TP", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
//===== Inputs =====
fastLen = input.int(9, "Fast MA Length")
slowLen = input.int(21, "Slow MA Length")
stopLossP = input.float(0.5, "Stop Loss %", step=0.1)
takeProfP = input.float(1.0, "Take Profit %", step=0.1)
//===== Indicators =====
fastMA = ta.ema(close, fastLen)
slowMA = ta.ema(close, slowLen)
plot(fastMA, color=color.new(color.green, 0))
plot(slowMA, color=color.new(color.red, 0))
//===== Conditions =====
longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)
//===== Entry Logic =====
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
//===== Exit Logic =====
if (strategy.position_size > 0)
strategy.exit("Long Exit", "Long", stop=strategy.position_avg_price * (1 - stopLossP/100), limit=strategy.position_avg_price * (1 + takeProfP/100))
if (strategy.position_size < 0)
strategy.exit("Short Exit", "Short", stop=strategy.position_avg_price * (1 + stopLossP/100), limit=strategy.position_avg_price * (1 - takeProfP/100))
Coin Jin Multi SMA+ BB+ SMA forecast Ver 2.0Coin Jin Multi SMA + BB + SMA Forecast 2.0
개요
여러 개의 단순이동평균(SMA: 5/20/60/112/224/448/896 + 사용자 정의 X1/X2), 볼린저 밴드(BB), 그리고 접선 기반 곡선 예측선을 한 번에 표시합니다. 예측선은 선형회귀 기울기와 그 변화율(가속도)을 EMA로 스무딩해 곡선 외삽으로 앞으로 그려지며, 어떤 줌에서도 깔끔하게 보이도록 점선(dotted) 스타일을 강제할 수 있습니다.
스택 마커(정배열/역배열) 안내
조건: 이동평균이 정배열(5>20>60>112>224>448>(896)) 또는 역배열(5<20<60<112<224<448<(896))로 새로 전환되는 순간 삼각형 마커가 생성됩니다.
896일선 포함(with 896): SOLID 마커로 표시, Bull = 초록색, Bear = 빨간색.
896일선 미포함(no 896): HOLLOW(윤곽) 마커로 표시, 시선을 덜 끌도록 투명도 70 적용(Bull = 연두, Bear = 빨강 동일색).
방향: Bull = ▼(위, abovebar) / Bear = ▲(아래, belowbar) 로 배치됩니다.
주요 기능
SMA 7종 기본 + 사용자 정의 SMA 2개(X1/X2) 추가(기본 꺼짐, 길이/색/두께/타입 자유).
BB: 길이/배수/선두께/밴드 채움(기본 90% 투명) 지원.
예측선: Forward bars(1–100, 기본 30), 기울기 산출 길이, 스무딩 강도, 세그먼트 개수, 점/대시 스타일 선택 및 도트 강제.
스택(정/역배열) 전환 마커: with 896=SOLID, no 896=HOLLOW(투명도 70).
처음 사용하는 분들을 위한 팁 (중요)
가격 스케일을 ‘우측’으로 고정하세요.
방법 ① 차트 우측 축을 사용(기본).
방법 ② 지표 레전드의 ‘⋯’ 메뉴 → Move to → Right scale.
예측선이 본선과 어긋나 보이면 스케일이 좌측/양측으로 되어 있거나 자동 합침된 경우이니 Right scale로 맞춰주세요.
입력 요약
MA Source, 각 SMA on/off·길이·색·두께·타입
BB length/mult/width/fill/opacity(기본 90)
Forecast bars ahead(1–100), slope lookback, smoothing, segments, style/opacity, 적용 대상 선택(SMA별)
주의/면책
예측선은 가격 예언 도구가 아니라 시각적 외삽 보조지표입니다. 단독 매매 판단에 사용하지 마세요.
공개 스크린샷은 본 지표만 보이도록 깔끔하게 캡처해 주세요(다른 지표/드로잉 혼합 금지).
변경사항(v2.0)
곡선 예측선 안정화 및 도트 강제 개선.
스택 마커 no 896 상태 HOLLOW 투명도 70 적용(가독성 향상).
사용자 정의 SMA X1/X2 추가(기본 OFF).
Coin Jin Multi SMA + BB + SMA Forecast 2.0 (English)
Overview
This indicator plots multiple Simple Moving Averages (SMA: 5/20/60/112/224/448/896 + two user-defined X1/X2), Bollinger Bands, and a tangent-based curved forecast in one overlay. The forecast extrapolates forward using the linear-regression slope and its rate of change (acceleration) smoothed by EMA, and you can force a dotted look so it stays clean at any zoom level.
Stack Markers (Bullish/Bearish alignment)
Markers appear only when a full bullish stack (5>20>60>112>224>448>(896)) or bearish stack (5<20<60<112<224<448<(896)) is newly formed.
With 896 included: shown as SOLID triangles — Bull = green, Bear = red.
Without 896: shown as HOLLOW (outline) with 70 transparency to reduce visual weight — Bull = lime, Bear = red (same hue).
Orientation: Bull = ▼ abovebar, Bear = ▲ belowbar.
Features
7 standard SMAs + two custom SMAs (X1/X2) (default OFF; fully configurable length/color/width/style).
BB with length/multiplier/width/fill (default fill opacity 90%).
Forecast controls: forward bars (1–100, default 30), slope window, smoothing, segment count, style/opacity, force dotted option.
Stack markers: with 896 = SOLID, without 896 = HOLLOW (70 transparency).
First-time setup (Important)
Pin the indicator to the Right price scale.
Option A: Use the right price axis.
Option B: Indicator legend “⋯” → Move to → Right scale.
If the forecast appears detached from the MA, your series is likely on the left/both scales; switch to Right scale.
Inputs
MA source; per-SMA on/off, length, color, width, style
BB length/multiplier/width/fill/opacity (default 90)
Forecast bars ahead (1–100), slope lookback, smoothing, segments, style/opacity, per-SMA apply switches
Disclaimer
The forecast is a visual extrapolation, not a price prediction. Do not use it alone to make trading decisions.
For publication, please use a clean screenshot that shows only this indicator (no mixed overlays).
What’s new in v2.0
More robust curved forecast with improved “force dotted” rendering.
HOLLOW (no 896) markers now use 70 transparency for better readability.
Added two user-defined SMAs (X1/X2), OFF by default.
Seasonality Monte Carlo Forecaster [BackQuant]Seasonality Monte Carlo Forecaster
Plain-English overview
This tool projects a cone of plausible future prices by combining two ideas that traders already use intuitively: seasonality and uncertainty. It watches how your market typically behaves around this calendar date, turns that seasonal tendency into a small daily “drift,” then runs many randomized price paths forward to estimate where price could land tomorrow, next week, or a month from now. The result is a probability cone with a clear expected path, plus optional overlays that show how past years tended to move from this point on the calendar. It is a planning tool, not a crystal ball: the goal is to quantify ranges and odds so you can size, place stops, set targets, and time entries with more realism.
What Monte Carlo is and why quants rely on it
• Definition . Monte Carlo simulation is a way to answer “what might happen next?” when there is randomness in the system. Instead of producing a single forecast, it generates thousands of alternate futures by repeatedly sampling random shocks and adding them to a model of how prices evolve.
• Why it is used . Markets are noisy. A single point forecast hides risk. Monte Carlo gives a distribution of outcomes so you can reason in probabilities: the median path, the 68% band, the 95% band, tail risks, and the chance of hitting a specific level within a horizon.
• Core strengths in quant finance .
– Path-dependent questions : “What is the probability we touch a stop before a target?” “What is the expected drawdown on the way to my objective?”
– Pricing and risk : Useful for path-dependent options, Value-at-Risk (VaR), expected shortfall (CVaR), stress paths, and scenario analysis when closed-form formulas are unrealistic.
– Planning under uncertainty : Portfolio construction and rebalancing rules can be tested against a cloud of plausible futures rather than a single guess.
• Why it fits trading workflows . It turns gut feel like “seasonality is supportive here” into quantitative ranges: “median path suggests +X% with a 68% band of ±Y%; stop at Z has only ~16% odds of being tagged in N days.”
How this indicator builds its probability cone
1) Seasonal pattern discovery
The script builds two day-of-year maps as new data arrives:
• A return map where each calendar day stores an exponentially smoothed average of that day’s log return (yesterday→today). The smoothing (90% old, 10% new) behaves like an EWMA, letting older seasons matter while adapting to new information.
• A volatility map that tracks the typical absolute return for the same calendar day.
It calculates the day-of-year carefully (with leap-year adjustment) and indexes into a 365-slot seasonal array so “March 18” is compared with past March 18ths. This becomes the seasonal bias that gently nudges simulations up or down on each forecast day.
2) Choice of randomness engine
You can pick how the future shocks are generated:
• Daily mode uses a Gaussian draw with the seasonal bias as the mean and a volatility that comes from realized returns, scaled down to avoid over-fitting. It relies on the Box–Muller transform internally to turn two uniform random numbers into one normal shock.
• Weekly mode uses bootstrap sampling from the seasonal return history (resampling actual historical daily drifts and then blending in a fraction of the seasonal bias). Bootstrapping is robust when the empirical distribution has asymmetry or fatter tails than a normal distribution.
Both modes seed their random draws deterministically per path and day, which makes plots reproducible bar-to-bar and avoids flickering bands.
3) Volatility scaling to current conditions
Markets do not always live in average volatility. The engine computes a simple volatility factor from ATR(20)/price and scales the simulated shocks up or down within sensible bounds (clamped between 0.5× and 2.0×). When the current regime is quiet, the cone narrows; when ranges expand, the cone widens. This prevents the classic mistake of projecting calm markets into a storm or vice versa.
4) Many futures, summarized by percentiles
The model generates a matrix of price paths (capped at 100 runs for performance inside TradingView), each path stepping forward for your selected horizon. For each forecast day it sorts the simulated prices and pulls key percentiles:
• 5th and 95th → approximate 95% band (outer cone).
• 16th and 84th → approximate 68% band (inner cone).
• 50th → the median or “expected path.”
These are drawn as polylines so you can immediately see central tendency and dispersion.
5) A historical overlay (optional)
Turn on the overlay to sketch a dotted path of what a purely seasonal projection would look like for the next ~30 days using only the return map, no randomness. This is not a forecast; it is a visual reminder of the seasonal drift you are biasing toward.
Inputs you control and how to think about them
Monte Carlo Simulation
• Price Series for Calculation . The source series, typically close.
• Enable Probability Forecasts . Master switch for simulation and drawing.
• Simulation Iterations . Requested number of paths to run. Internally capped at 100 to protect performance, which is generally enough to estimate the percentiles for a trading chart. If you need ultra-smooth bands, shorten the horizon.
• Forecast Days Ahead . The length of the cone. Longer horizons dilute seasonal signal and widen uncertainty.
• Probability Bands . Draw all bands, just 95%, just 68%, or a custom level (display logic remains 68/95 internally; the custom number is for labeling and color choice).
• Pattern Resolution . Daily leans on day-of-year effects like “turn-of-month” or holiday patterns. Weekly biases toward day-of-week tendencies and bootstraps from history.
• Volatility Scaling . On by default so the cone respects today’s range context.
Plotting & UI
• Probability Cone . Plots the outer and inner percentile envelopes.
• Expected Path . Plots the median line through the cone.
• Historical Overlay . Dotted seasonal-only projection for context.
• Band Transparency/Colors . Customize primary (outer) and secondary (inner) band colors and the mean path color. Use higher transparency for cleaner charts.
What appears on your chart
• A cone starting at the most recent bar, fanning outward. The outer lines are the ~95% band; the inner lines are the ~68% band.
• A median path (default blue) running through the center of the cone.
• An info panel on the final historical bar that summarizes simulation count, forecast days, number of seasonal patterns learned, the current day-of-year, expected percentage return to the median, and the approximate 95% half-range in percent.
• Optional historical seasonal path drawn as dotted segments for the next 30 bars.
How to use it in trading
1) Position sizing and stop logic
The cone translates “volatility plus seasonality” into distances.
• Put stops outside the inner band if you want only ~16% odds of a stop-out due to noise before your thesis can play.
• Size positions so that a test of the inner band is survivable and a test of the outer band is rare but acceptable.
• If your target sits inside the 68% band at your horizon, the payoff is likely modest; outside the 68% but inside the 95% can justify “one-good-push” trades; beyond the 95% band is a low-probability flyer—consider scaling plans or optionality.
2) Entry timing with seasonal bias
When the median path slopes up from this calendar date and the cone is relatively narrow, a pullback toward the lower inner band can be a high-quality entry with a tight invalidation. If the median slopes down, fade rallies toward the upper band or step aside if it clashes with your system.
3) Target selection
Project your time horizon to N bars ahead, then pick targets around the median or the opposite inner band depending on your style. You can also anchor dynamic take-profits to the moving median as new bars arrive.
4) Scenario planning & “what-ifs”
Before events, glance at the cone: if the 95% band already spans a huge range, trade smaller, expect whips, and avoid placing stops at obvious band edges. If the cone is unusually tight, consider breakout tactics and be ready to add if volatility expands beyond the inner band with follow-through.
5) Options and vol tactics
• When the cone is tight : Prefer long gamma structures (debit spreads) only if you expect a regime shift; otherwise premium selling may dominate.
• When the cone is wide : Debit structures benefit from range; credit spreads need wider wings or smaller size. Align with your separate IV metrics.
Reading the probability cone like a pro
• Cone slope = seasonal drift. Upward slope means the calendar has historically favored positive drift from this date, downward slope the opposite.
• Cone width = regime volatility. A widening fan tells you that uncertainty grows fast; a narrow cone says the market typically stays contained.
• Mean vs. price gap . If spot trades well above the median path and the upper band, mean-reversion risk is high. If spot presses the lower inner band in an up-sloping cone, you are in the “buy fear” zone.
• Touches and pierces . Touching the inner band is common noise; piercing it with momentum signals potential regime change; the outer band should be rare and often brings snap-backs unless there is a structural catalyst.
Methodological notes (what the code actually does)
• Log returns are used for additivity and better statistical behavior: sim_ret is applied via exp(sim_ret) to evolve price.
• Seasonal arrays are updated online with EWMA (90/10) so the model keeps learning as each bar arrives.
• Leap years are handled; indexing still normalizes into a 365-slot map so the seasonal pattern remains stable.
• Gaussian engine (Daily mode) centers shocks on the seasonal bias with a conservative standard deviation.
• Bootstrap engine (Weekly mode) resamples from observed seasonal returns and adds a fraction of the bias, which captures skew and fat tails better.
• Volatility adjustment multiplies each daily shock by a factor derived from ATR(20)/price, clamped between 0.5 and 2.0 to avoid extreme cones.
• Performance guardrails : simulations are capped at 100 paths; the probability cone uses polylines (no heavy fills) and only draws on the last confirmed bar to keep charts responsive.
• Prerequisite data : at least ~30 seasonal entries are required before the model will draw a cone; otherwise it waits for more history.
Strengths and limitations
• Strengths :
– Probabilistic thinking replaces single-point guessing.
– Seasonality adds a small but meaningful directional bias that many markets exhibit.
– Volatility scaling adapts to the current regime so the cone stays realistic.
• Limitations :
– Seasonality can break around structural changes, policy shifts, or one-off events.
– The number of paths is performance-limited; percentile estimates are good for trading, not for academic precision.
– The model assumes tomorrow’s randomness resembles recent randomness; if regime shifts violently, the cone will lag until the EWMA adapts.
– Holidays and missing sessions can thin the seasonal sample for some assets; be cautious with very short histories.
Tuning guide
• Horizon : 10–20 bars for tactical trades; 30+ for swing planning when you care more about broad ranges than precise targets.
• Iterations : The default 100 is enough for stable 5/16/50/84/95 percentiles. If you crave smoother lines, shorten the horizon or run on higher timeframes.
• Daily vs. Weekly : Daily for equities and crypto where month-end and turn-of-month effects matter; Weekly for futures and FX where day-of-week behavior is strong.
• Volatility scaling : Keep it on. Turn off only when you intentionally want a “pure seasonality” cone unaffected by current turbulence.
Workflow examples
• Swing continuation : Cone slopes up, price pulls into the lower inner band, your system fires. Enter near the band, stop just outside the outer line for the next 3–5 bars, target near the median or the opposite inner band.
• Fade extremes : Cone is flat or down, price gaps to the upper outer band on news, then stalls. Favor mean-reversion toward the median, size small if volatility scaling is elevated.
• Event play : Before CPI or earnings on a proxy index, check cone width. If the inner band is already wide, cut size or prefer options structures that benefit from range.
Good habits
• Pair the cone with your entry engine (breakout, pullback, order flow). Let Monte Carlo do range math; let your system do signal quality.
• Do not anchor blindly to the median; recalc after each bar. When the cone’s slope flips or width jumps, the plan should adapt.
• Validate seasonality for your symbol and timeframe; not every market has strong calendar effects.
Summary
The Seasonality Monte Carlo Forecaster wraps institutional risk planning into a single overlay: a data-driven seasonal drift, realistic volatility scaling, and a probabilistic cone that answers “where could we be, with what odds?” within your trading horizon. Use it to place stops where randomness is less likely to take you out, to set targets aligned with realistic travel, and to size positions with confidence born from distributions rather than hunches. It will not predict the future, but it will keep your decisions anchored to probabilities—the language markets actually speak.
Prime NumbersPrime Numbers highlights prime numbers (no surprise there 😅), tokens and the recent "active" feature in "input".
🔸 CONCEPTS
🔹 What are Prime Numbers?
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.
Wikipedia: Prime number
🔹 Prime Factorization
The fundamental theorem of arithmetic states that every integer larger than 1 can be written as a product of one or more primes. More strongly, this product is unique in the sense that any two prime factorizations of the same number will have the same number of copies of the same primes, although their ordering may differ. So, although there are many different ways of finding a factorization using an integer factorization algorithm, they all must produce the same result. Primes can thus be considered the "basic building blocks" of the natural numbers.
Wikipedia: Fundamental theorem of arithmetic
Math Is Fun: Prime Factorization
We divide a given number by Prime Numbers until only Primes remain.
Example:
24 / 2 = 12 | 24 / 3 = 8
12 / 3 = 4 | 8 / 2 = 4
4 / 2 = 2 | 4 / 2 = 2
|
24 = 2 x 3 x 2 | 24 = 3 x 2 x 2
or | or
24 = 2² x 3 | 24 = 2² x 3
In other words, every natural/integer number above 1 has a unique representation as a product of prime numbers, no matter how the number is divided. Only the order can change, but the factors (the basic elements) are always the same.
🔸 USAGE
The Prime Numbers publication contains two use cases:
Prime Factorization: performed on "close" prices, or a manual chosen number.
List Prime Numbers: shows a list of Prime Numbers.
The other two options are discussed in the DETAILS chapter:
Prime Factorization Without Arrays
Find Prime Numbers
🔹 Prime Factorization
Users can choose to perform Prime Factorization on close prices or a manually given number.
❗️ Note that this option only applies to close prices above 1, which are also rounded since Prime Factorization can only be performed on natural (integer) numbers above 1.
In the image below, the left example shows Prime Factorization performed on each close price for the latest 50 bars (which is set with "Run script only on 'Last x Bars'" -> 50).
The right example shows Prime Factorization performed on a manually given number, in this case "1,340,011". This is done only on the last bar.
When the "Source" option "close price" is chosen, one can toggle "Also current price", where both the historical and the latest current price are factored. If disabled, only historical prices are factored.
Note that, depending on the chosen options, only applicable settings are available, due to a recent feature, namely the parameter "active" in settings.
Setting the "Source" option to "Manual - Limited" will factorize any given number between 1 and 1,340,011, the latter being the highest value in the available arrays with primes.
Setting to "Manual - Not Limited" enables the user to enter a higher number. If all factors of the manual entered number are in the 1 - 1,340,011 range, these factors will be shown; however, if a factor is higher than 1,340,011, the calculation will stop, after which a warning is shown:
The calculated factors are displayed as a label where identical factors are simplified with an exponent notation in superscript.
For example 2 x 2 x 2 x 5 x 7 x 7 will be noted as 2³ x 5 x 7²
🔹 List Prime Numbers
The "List Prime Numbers" option enables users to enter a number, where the first found Prime Number is shown, together with the next x Prime Numbers ("Amount", max. 200)
The highest shown Prime Number is 1,340,011.
One can set the number of shown columns to customize the displayed numbers ("Max. columns", max. 20).
🔸 DETAILS
The Prime Numbers publication consists out of 4 parts:
Prime Factorization Without Arrays
Prime Factorization
List Prime Numbers
Find Prime Numbers
The usage of "Prime Factorization" and "List Prime Numbers" is explained above.
🔹 Prime Factorization Without Arrays
This option is only there to highlight a hurdle while performing Prime Factorization.
The basic method of Prime Factorization is to divide the base number by 2, 3, ... until the result is an integer number. Continue until the remaining number and its factors are all primes.
The division should be done by primes, but then you need to know which one is a prime.
In practice, one performs a loop from 2 to the base number.
Example:
Base_number = input.int(24)
arr = array.new()
n = Base_number
go = true
while go
for i = 2 to n
if n % i == 0
if n / i == 1
go := false
arr.push(i)
label.new(bar_index, high, str.tostring(arr))
else
arr.push(i)
n /= i
break
Small numbers won't cause issues, but when performing the calculations on, for example, 124,001 and a timeframe of, for example, 1 hour, the script will struggle and finally give a runtime error.
How to solve this?
If we use an array with only primes, we need fewer calculations since if we divide by a non-prime number, we have to divide further until all factors are primes.
I've filled arrays with prime numbers and made libraries of them. (see chapter "Find Prime Numbers" to know how these primes were found).
🔹 Tokens
A hurdle was to fill the libraries with as many prime numbers as possible.
Initially, the maximum token limit of a library was 80K.
Very recently, that limit was lifted to 100K. Kudos to the TradingView developers!
What are tokens?
Tokens are the smallest elements of a program that are meaningful to the compiler. They are also known as the fundamental building blocks of the program.
I have included a code block below the publication code (// - - - Educational (2) - - - ) which, if copied and made to a library, will contain exactly 100K tokens.
Adding more exported functions will throw a "too many tokens" error when saving the library. Subtracting 100K from the shown amount of tokens gives you the amount of used tokens for that particular function.
In that way, one can experiment with the impact of each code addition in terms of tokens.
For example adding the following code in the library:
export a() => a = array.from(1) will result in a 100,041 tokens error, in other words (100,041 - 100,000) that functions contains 41 tokens.
Some more examples, some are straightforward, others are not )
// adding these lines in one of the arrays results in x tokens
, 1 // 2 tokens
, 111, 111, 111 // 12 tokens
, 1111 // 5 tokens
, 111111111 // 10 tokens
, 1111111111111111111 // 20 tokens
, 1234567890123456789 // 20 tokens
, 1111111111111111111 + 1 // 20 tokens
, 1111111111111111111 + 8 // 20 tokens
, 1111111111111111111 + 9 // 20 tokens
, 1111111111111111111 * 1 // 20 tokens
, 1111111111111111111 * 9 // 21 tokens
, 9999999999999999999 // 21 tokens
, 1111111111111111111 * 10 // 21 tokens
, 11111111111111111110 // 21 tokens
//adding these functions to the library results in x tokens
export f() => 1 // 4 tokens
export f() => v = 1 // 4 tokens
export f() => var v = 1 // 4 tokens
export f() => var v = 1, v // 4 tokens
//adding these functions to the library results in x tokens
export a() => const arraya = array.from(1) // 42 tokens
export a() => arraya = array.from(1) // 42 tokens
export a() => a = array.from(1) // 41 tokens
export a() => array.from(1) // 32 tokens
export a() => a = array.new() // 44 tokens
export a() => a = array.new(), a.push(1) // 56 tokens
What if we could lower the amount of tokens, so we can export more Prime Numbers?
Look at this example:
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193
Eight numbers contain the same number 8291.
If we make a function that removes recurrent values, we get fewer tokens!
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193
//is transformed to:
829111, 21, 23, 51, 59, 77, 87, 93
The code block below the publication code (// - - - Educational (1) - - - ) shows how these values were reduced. With each step of 100, only the first Prime Number is shown fully.
This function could be enhanced even more to reduce recurrent thousands, tens of thousands, etc.
Using this technique enables us to export more Prime Numbers. The number of necessary libraries was reduced to half or less.
The reduced Prime Numbers are restored using the restoreValues() function, found in the library fikira/Primes_4.
🔹 Find Prime Numbers
This function is merely added to show how I filled arrays with Prime Numbers, which were, in turn, added to libraries (after reduction of recurrent values).
To know whether a number is a Prime Number, we divide the given number by values of the Primes array (Primes 2 -> max. 1,340,011). Once the division results in an integer, where the divisor is smaller than the dividend, the calculation stops since the given number is not a Prime.
When we perform these calculations in a loop, we can check whether a series of numbers is a Prime or not. Each time a number is proven not to be a Prime, the loop starts again with a higher number. Once all Primes of the array are used without the result being an integer, we have found a new Prime Number, which is added to the array.
Doing such calculations on one bar will result in a runtime error.
To solve this, the findPrimeNumbers() function remembers the index of the array. Once a limit has been reached on 1 bar (for example, the number of iterations), calculations will stop on that bar and restart on the next bar.
This spreads the workload over several bars, making it possible to continue these calculations without a runtime error.
The result is placed in log.info() , which can be copied and pasted into a hardcoded array of Prime Number values.
These settings adjust the amount of workload per bar:
Max Size: maximum size of Primes array.
Max Bars Runtime: maximum amount of bars where the function is called.
Max Numbers To Process Per Bar: maximum numbers to check on each bar, whether they are Prime Numbers.
Max Iterations Per Bar: maximum loop calculations per bar.
🔹 The End
❗️ The code and description is written without the help of an LLM, I've only used Grammarly to improve my description (without AI :) )
Major Lows OscillatorDescription
The Major Lows Oscillator is a custom technical indicator designed to identify significant low-price areas by normalizing the current closing price relative to recent lowest lows and highest highs. The oscillator calculates a normalized price percentage over a configurable lookback period, applies exponential moving averages for smoothing, and inverts the result to highlight potential market bottoms.
Calculation Details
Lowest Low Lookback : Finds the lowest low over a user-defined period (default 100 bars).
Highest High Lookback : Calculates the highest high over a short period (default 1 bar), providing a dynamic normalization range.
Normalization : Normalizes the current close within the range defined by the lowest low and highest high, scaled to 0-100.
Smoothing : Applies a 10-period EMA, inversion, and weighted smoothing combining the last valid value and current oscillator reading.
Final Output : Applies a final EMA (period 1) and inverts the oscillator (100 - value) to emphasize major lows.
Features
Customizable midline level for signal alerts (default 50).
Visual midline reference line.
Alerts trigger on oscillator crossing below midline for automated monitoring.
Usage
Useful for complementing existing setups or integration in algorithmic trading strategies.
Changing the input parameters opens new ways to leverage the asymmetric range concept, allowing adaptation to different market regimes and enhancing the oscillator’s sensitivity and utility.
Examples of input combinations and their potential purposes include:
Extremely Asymmetric Setting: Lowest Low Lookback = 200, Highest High Lookback = 1
Focuses on deep long-term lows contrasted with immediate highs, ideal for spotting strong oversold levels within an otherwise bullish short-term momentum.
Symmetric Lookbacks: Lowest Low Lookback = Highest High Lookback = 50
Balances the range equally, creating a normalized oscillator that treats recent lows and highs with the same weight — useful for markets with balanced volatility.
Short but Equal Lookbacks: Lowest Low Lookback = Highest High Lookback = 10
Highly sensitive to recent price swings, this setting can detect rapid shifts and is suited for intraday or very short-term trading.
Inverted Extreme: Lowest Low Lookback = 1, Highest High Lookback = 100
Highlights very recent lows against a long-term high range, possibly signaling quick dips in a generally overextended market.
Inputs
Midline Level : Threshold for alerts (default 50).
Lowest Low Lookback Period : Bars evaluated for lowest low (default 100).
Highest High Lookback Period : Bars evaluated for highest high (default 1).
Alerts
Configured to trigger once per bar close when the oscillator crosses below the midline level.
---
Disclaimer
This indicator is for educational and analytical use only.
ABS Companion Oscillator — Trend / Exhaustion / New Trend (v1.1)
# ABS Companion Oscillator — Trend / Exhaustion / New Trend (v1.1)
## What it is (quick take)
**ABS CO** is a unified **–100…+100 trend oscillator** that fuses:
* **Regime**: EMA stack (fast/slow/long) + **HTF slope** (e.g., 60-minute)
* **Momentum**: **TSI** vs its signal
* **Stretch**: session-anchored **VWAP Z-score** for exhaustion and “fresh-trend” sanity checks
It paints the oscillator with **lime** in upstate, **red** in downstate, **gray** in neutral, and tags:
* **NEW↑ / NEW↓** when a **new trend** likely starts (zero-line cross with acceptable stretch)
* **EXH↑ / EXH↓** when an **existing trend looks exhausted** (large |Z| + momentum rollback)
> Use it as a **direction filter and context layer**. Works great in front of an entry engine and behind an exit tool.
---
## How to use it (operational workflow)
1. **Read the state**
* **Uptrend** when the oscillator is **≥ upThresh** (default +55) → prefer **long-side** plays.
* **Downtrend** when the oscillator is **≤ dnThresh** (default −55) → prefer **short-side** plays.
* **Neutral** between thresholds → be selective or flat; expect chop.
2. **Act on events**
* **NEW↑ / NEW↓**: zero-line cross with acceptable |Z| (not already overstretched). Treat as **trend start** cues.
* **EXH↑ / EXH↓**: trend state with **high |Z|** and TSI rollback versus its signal. Treat as **trend fatigue**; avoid fresh go-with entries and tighten risk.
3. **Practical pairing**
* Use **up/down state** (or above/below **neutralBand**) as your go/no-go filter for entries.
* Prioritize entries **with** NEW↑/NEW↓ and **without** nearby EXH tags.
* Keep holding while the oscillator stays in state and no EXH appears; consider scaling out on EXH or on your exit tool.
---
## Visual semantics & alerts
* **ABS CO line** (–100…+100): lime in upstate, red in downstate, gray in neutral.
* **Horizontal guides**: `Up` threshold, `Down` threshold, `Zero`, and optional **neutral band** lines.
* **Background heat** (optional): shaded when EXH conditions trigger (lime/red tint with intensity scaled by |Z|).
* **Tags**: `NEW↑`, `NEW↓`, `EXH↑`, `EXH↓`.
**Alerts (stable):**
* **ABS CO — New Uptrend** (NEW↑)
* **ABS CO — New Downtrend** (NEW↓)
* **ABS CO — Exhausted Up** (EXH↑)
* **ABS CO — Exhausted Down** (EXH↓)
Set alerts to **“Once per bar close”** for clean signals.
---
## Non-repainting behavior
* HTF queries use **lookahead\_off**.
* With **Strict NR = true**, the HTF slope is taken from the **prior completed** HTF bar; events evaluate on confirmed bars → **safer, fewer, cleaner**.
* NEW/EXH tags finalize at bar close. Disabling strictness yields earlier but noisier responses.
---
## Every input explained (and how it changes behavior)
### A) Trend & HTF structure
* **EMA Fast / Slow / Long (`emaFastLen`, `emaSlowLen`, `emaLongLen`)**
Control the baseline regime. Larger = smoother, fewer flips; smaller = snappier, more flips.
* **HTF EMA Len (`htfLen`)** & **HTF timeframe (`htfTF`)**
HTF slope filter. Longer len or higher TF = steadier bias (fewer state changes); shorter/ lower = more sensitive.
* **Strict NR (`strictNR`)**
`true` uses the **previous** HTF bar for slope and evaluates on confirmed bars → cleaner, slower.
### B) Momentum (TSI)
* **TSI Long / Short / Signal (`tsiLong`, `tsiShort`, `tsiSig`)**
Standard TSI. Larger values = smoother momentum, fewer EXH triggers; smaller = snappier, more EXH sensitivity.
### C) Stretch (VWAP Z-score)
* **VWAP Z-score length (`zLen`)**
Window for Z over session-anchored VWAP distance. Larger = smoother |Z|; smaller = more reactive stretch detection.
* **Exhaustion |Z| (`zHot`)**
Minimum |Z| to flag **EXH**. Raise to demand **bigger** stretch (fewer EXH); lower to catch milder excess.
* **Max |Z| for NEW (`zNewMax`)**
NEW requires |Z| **≤ zNewMax** (avoid “new trend” when already stretched). Lower = stricter; higher = more NEW tags.
### D) States & thresholds
* **Uptrend threshold (`upThresh`)** / **Downtrend threshold (`dnThresh`)**
Where the oscillator flips into trend states. Widen (e.g., +60/−60) to reduce false states; narrow to get earlier signals.
* **Neutral band (`neutralBand`)**
Visual buffer around zero for “meh” momentum. Larger band = fewer go/no-go flips near zero.
### E) Visuals & tags
* **Show New / Show Exhausted (`showNew`, `showExh`)**
Toggle the tag labels.
* **Shade exhaustion heat (`plotHeat`)**
On = color background when EXH fires. Helpful for scanning.
### F) Smoothing
* **Osc smoothing (`smoothLen`)**
EMA over the raw composite. Higher = steadier line (fewer whip flips); lower = faster turns.
---
## Tuning recipes
* **Trend-day bias (follow moves longer)**
* Raise **`upThresh`** to \~60 and **`dnThresh`** to \~−60
* Keep **`zNewMax`** low (1.0–1.2) to avoid “fresh trend” when stretched
* **`smoothLen`** 3–5 to reduce noise
* **Range-day bias (fade edges)**
* Keep thresholds closer (e.g., +50/−50) for quicker state changes
* Lower **`zHot`** slightly (1.6–1.7) to catch earlier exhaustion
* Consider slightly shorter TSI (e.g., 21/9/5) for faster EXH response
* **Scalping LTF (1–3m)**
* TSI 21/9/5, **`smoothLen`** 1–2
* Thresholds +/-50; **`zNewMax`** 1.0–1.2; **`zHot`** 1.6–1.8
* StrictNR **off** if you want earlier calls (accept more noise)
* **Swing / HTF (1h–D)**
* TSI 35/21/9, **`smoothLen`** 4–7
* Thresholds +/-60\~65; **`zNewMax`** 1.2; **`zHot`** 1.8–2.0
* StrictNR **on** for cleaner bias
---
## Playbooks (how to actually trade it)
* **Go/No-Go Filter**
* Only take **long entries** when the oscillator is **above the neutral band** (preferably ≥ `upThresh`).
* Only take **short entries** when **below** the neutral band (preferably ≤ `dnThresh`).
* Avoid fresh go-with entries if an **EXH** tag appears; let the next setup re-arm.
* **Trend Genesis**
* Treat **NEW↑ / NEW↓** as “green light” for **first pullback** entries in the new direction (ideally within acceptable |Z|).
* **Trend Maturity**
* When in a position and **EXH** prints **against** you, tighten stops, take partials, or lean on your exit tool to protect gains.
---
## Suggested starting points
* **Day trading (5–15m):**
* TSI 25/13/7, `smoothLen=3`, thresholds **+55 / −55**, `zNewMax = 1.2`, `zHot = 1.8`, **StrictNR = true**
* **Scalping (1–3m):**
* TSI 21/9/5, `smoothLen=1–2`, thresholds **+50 / −50**, `zNewMax = 1.1–1.2`, `zHot = 1.6–1.8`, **StrictNR = false** (optional)
* **Swing (1h–D):**
* TSI 35/21/9, `smoothLen=4–6`, thresholds **+60 / −60**, `zNewMax = 1.2`, `zHot = 1.9–2.0`, **StrictNR = true**
---
## Notes & best practices
* **Session anchoring**: Z-score is session-anchored (resets by trading date). If you trade outside standard sessions, verify your data session.
* **Instrument specificity**: Tune **`zHot`**, **`zNewMax`**, and thresholds per symbol and timeframe.
* **Bar-close discipline**: Evaluate tags at **bar close** to avoid intrabar flip-flop.
* This is a **context/confirmation tool**, not a broker or strategy. Combine with your entry/exit rules and position sizing.
---
**Tip:** Start with the suggested day-trading profile. Use this oscillator as your **gate** (only trade with it), let your entry engine time executions, and rely on your exit tool for standardized profit-taking.
Queso Heat IndexQueso Heat Index (QHI) — ATR-Adaptive Edge-Pressure Gauge
QHI measures how strongly price is pressing the edges of a rolling consolidation window. It heats up when price repeatedly pushes the window up , cools down when it pushes down , and drifts back toward neutral when price wanders in the middle. Everything is ATR-normalized so it adapts across symbols and timeframes.
Output: a signed score from −100 … +100
> 0 = bullish pressure (hot)
< 0 = bearish pressure (cold)
≈ 0 = neutral (no side dominating)
What you’ll see on the chart
Rolling “box” (Donchian window): top, bottom, and midline.
Optional compact-box shading when the window height is small relative to ATR.
Background “thermals”: tinted red when Heat > Hot threshold, blue when Heat < Cold threshold (intensity scales with the score).
Optional Heat line (−100..+100), optional 0/±80 thresholds, and optional push markers (PU/PD).
Optional table showing the current Heat score, placeable in any corner.
How it works (under the hood)
Consolidation window — Over lookback bars we track highest high (top), lowest low (bottom), and midpoint. The window is called “compact” when box height ≤ ATR × maxRangeATR .
ATR-based push detection — A bar is a push-up if high > prior window high + (epsATR × ATR + tick buffer) . A push-down if low < prior window low − (epsATR × ATR + tick buffer) . We also measure how many ATRs beyond the edge the bar traveled.
Heat gains (symmetric) — Each push adds/subtracts Heat:
base gain + streak bonus × consecutive pushes + magnitude bonus × ATRs beyond edge .
Decay toward neutral — Each bar, Heat decays by a percentage. Decay is:
– higher in the middle band of the box, and
– adaptive : the farther (in ATRs) from the relevant band (top when hot, bottom when cold), the faster it decays; hugging the band slows decay.
Midpoint bias (optional) — Gentle drift toward hot when trading above mid, toward cold when below mid, with a dead-zone near mid so tiny wobbles don’t matter.
Reset on regime flip (optional) — First valid push from the opposite side can snap Heat back to 0 before applying new gains.
How to read it
Rising hot with slow decay → strong upside pressure; pullbacks that hold near the top band often continue.
Flip to cold after being hot → regime change risk; tighten risk or consider the other side.
Compact window + rising hot (or cold) → squeeze-and-go conditions.
Neutral (≈ 0) → edges aren’t being pressured; expect mean-reversion inside the box.
Key inputs (what they do)
Window & ATR
lookback : size of the Donchian window (longer = smoother, slower).
atrLen : ATR period for all volatility-scaled thresholds.
maxRangeATR : defines “compact” windows for optional shading.
topBottomFrac : how thick the top/bottom bands are (used for decay/pressure logic).
Push detection (ATR-based)
epsATR : how many ATRs beyond the prior edge to count as a real push.
tickBuff : fixed extra ticks beyond the ATR epsilon (filters micro-breaches).
Heat gains
gainBase : main fuel per push.
gainPerStreak : rewards consecutive pushes.
gainPer1ATRBrk : adds more for stronger breakouts past the edge.
resetOppSide : snap back to 0 on the first opposite-side push.
Decay
decayPct : baseline % removed each bar.
decayAccelMid : multiplies decay when price is in the middle band.
adaptiveDecay , decayMinMult , decayPerATR , decayMaxMult : scale decay with ATR distance from the nearest “target” band (top if hot, bottom if cold).
Midpoint bias
useMidBias : enable/disable drift above/below midpoint.
midDeadFrac : width of neutral (no-drift) zone around mid.
midBiasPerBar : max drift per bar at the box edge.
Visuals (all default to OFF for a clean chart)
Plot Heat line + Show 0/±80 lines (only shows thresholds if Heat line is on).
Hot/Cold thresholds & transparency floors for background shading.
Push markers (PU/PD).
Heat score table : toggle on; choose any corner.
Tuning quick-starts
Daily trending equities : lookback 40–60; epsATR 0.10–0.25; gainBase 12–18; gainPerStreak 0.5–1.5; gainPer1ATRBrk 1–2; decayPct 3–6; adaptiveDecay ON (decayPerATR 0.5–0.8).
Intraday / noisy : raise epsATR and tickBuff to filter noise; keep decayPct modest so Heat can build.
Weekly swing : longer lookback/atrLen; slightly lower decayPct so regimes persist.
Alerts (included)
New window HIGH (push-up)
New window LOW (push-down)
Heat turned HOT (crosses above your Hot threshold)
Heat turned COLD (crosses below your Cold threshold)
Best practices & notes
Use QHI as a pressure gauge , not a standalone system—combine with your entry/exit plan and risk rules.
On thin symbols, increase epsATR and/or tickBuff to avoid spurious pushes.
Gap days can register large pushes; ATR scaling helps but consider context.
Want the Heat in a separate pane? Use the companion panel version; keep this overlay for background/box visuals.
Pine v6. Warm-up: values appear as soon as one bar of window history exists.
TL;DR
QHI quantifies how hard price is leaning on a consolidation edge.
It’s ATR-adaptive, streak- and magnitude-aware, and cools off intelligently when momentum fades.
Watch for thermals (background), the score (−100..+100), and fresh push alerts to time entries in the direction of pressure.
RS Ratio vs Benchmark (Colored)📈 RS Ratio vs Benchmark (with Color Change)
A simple but powerful tool to track relative strength against a benchmark like QQQ, SPY, or any other ETF.
🔍 What it Shows
RS Ratio (orange line): Measures how strong a stock is relative to a benchmark.
Moving Average (teal line): Smooths out RS to show trend direction.
Color-coded RS Line:
🟢 Green = RS is above its moving average → strength is increasing.
🔴 Red = RS is below its moving average → strength is fading.
📊 How to Read It
Above 100 = Stock is outperforming the benchmark.
Below 100 = Underperforming.
Rising & Green = Strongest signal — accelerating outperformance.
Above 100 but Red = Consolidating or losing momentum — potential rest period.
Crosses below 100 = Warning sign — underperformance.
✅ Best Uses
Spot leading stocks with strong momentum vs QQQ/SPY.
Identify rotation — when strength shifts between sectors.
Time entries and exits based on RS trends and crossovers.
GMMG CCM SYSTEM HALMACCI INDICATOR BY KUYA NICKOOVERVIEW:
This script is about HALMACCI strategy based on Coach Miranda Miner System (CMM Systems of GMMG). It's an indicator to help traders decide when to enter and exit. This indicator uses Bollinger Band, EMA and ALMA with the length settings used by GMMG.
USAGE:
Apply the indicator to any chart. Best use in lower timeframes (Ex: 5m and 1m). You may use custom length settings but I suggest to stick with the default settings if you are using CMM System.
To enter LONG, If the CCI cross over -100 (shows a green dot when dot is enabled in style) and the EMA cross above ALMA (shows a green cross when cross is enabled in style). You may enter long. Strong confluence when it happens above the Bollinger Band and the candle closed above the Bollinger Band. You may exit when the CCI cross under -100 or immediate resistance.
To enter SHORT, If the CCI cross under 100 (shows a red dot when dot is enabled in style) and the EMA cross above ALMA (shows a red cross when cross is enabled in style). You may enter short. Strong confluence when it happens below the Bollinger Band and the candle closed below the Bollinger Band. You may exit when the CCI cross over 100 or immediate support.
Use may use alerts to catch breakout events so you would not need to monitor the chart continuously
US Macroeconomic Conditions IndexThis study presents a macroeconomic conditions index (USMCI) that aggregates twenty US economic indicators into a composite measure for real-time financial market analysis. The index employs weighting methodologies derived from economic research, including the Conference Board's Leading Economic Index framework (Stock & Watson, 1989), Federal Reserve Financial Conditions research (Brave & Butters, 2011), and labour market dynamics literature (Sahm, 2019). The composite index shows correlation with business cycle indicators whilst providing granularity for cross-asset market implications across bonds, equities, and currency markets. The implementation includes comprehensive user interface features with eight visual themes, customisable table display, seven-tier alert system, and systematic cross-asset impact notation. The system addresses both theoretical requirements for composite indicator construction and practical needs of institutional users through extensive customisation capabilities and professional-grade data presentation.
Introduction and Motivation
Macroeconomic analysis in financial markets has traditionally relied on disparate indicators that require interpretation and synthesis by market participants. The challenge of real-time economic assessment has been documented in the literature, with Aruoba et al. (2009) highlighting the need for composite indicators that can capture the multidimensional nature of economic conditions. Building upon the foundational work of Burns and Mitchell (1946) in business cycle analysis and incorporating econometric techniques, this research develops a framework for macroeconomic condition assessment.
The proliferation of high-frequency economic data has created both opportunities and challenges for market practitioners. Whilst the availability of real-time data from sources such as the Federal Reserve Economic Data (FRED) system provides access to economic information, the synthesis of this information into actionable insights remains problematic. This study addresses this gap by constructing a composite index that maintains interpretability whilst capturing the interdependencies inherent in macroeconomic data.
Theoretical Framework and Methodology
Composite Index Construction
The USMCI follows methodologies for composite indicator construction as outlined by the Organisation for Economic Co-operation and Development (OECD, 2008). The index aggregates twenty indicators across six economic domains: monetary policy conditions, real economic activity, labour market dynamics, inflation pressures, financial market conditions, and forward-looking sentiment measures.
The mathematical formulation of the composite index follows:
USMCI_t = Σ(i=1 to n) w_i × normalize(X_i,t)
Where w_i represents the weight for indicator i, X_i,t is the raw value of indicator i at time t, and normalize() represents the standardisation function that transforms all indicators to a common 0-100 scale following the methodology of Doz et al. (2011).
Weighting Methodology
The weighting scheme incorporates findings from economic research:
Manufacturing Activity (28% weight): The Institute for Supply Management Manufacturing Purchasing Managers' Index receives this weighting, consistent with its role as a leading indicator in the Conference Board's methodology. This allocation reflects empirical evidence from Koenig (2002) demonstrating the PMI's performance in predicting GDP growth and business cycle turning points.
Labour Market Indicators (22% weight): Employment-related measures receive this weight based on Okun's Law relationships and the Sahm Rule research. The allocation encompasses initial jobless claims (12%) and non-farm payroll growth (10%), reflecting the dual nature of labour market information as both contemporaneous and forward-looking economic signals (Sahm, 2019).
Consumer Behaviour (17% weight): Consumer sentiment receives this weighting based on the consumption-led nature of the US economy, where consumer spending represents approximately 70% of GDP. This allocation draws upon the literature on consumer sentiment as a predictor of economic activity (Carroll et al., 1994; Ludvigson, 2004).
Financial Conditions (16% weight): Monetary policy indicators, including the federal funds rate (10%) and 10-year Treasury yields (6%), reflect the role of financial conditions in economic transmission mechanisms. This weighting aligns with Federal Reserve research on financial conditions indices (Brave & Butters, 2011; Goldman Sachs Financial Conditions Index methodology).
Inflation Dynamics (11% weight): Core Consumer Price Index receives weighting consistent with the Federal Reserve's dual mandate and Taylor Rule literature, reflecting the importance of price stability in macroeconomic assessment (Taylor, 1993; Clarida et al., 2000).
Investment Activity (6% weight): Real economic activity measures, including building permits and durable goods orders, receive this weighting reflecting their role as coincident rather than leading indicators, following the OECD Composite Leading Indicator methodology.
Data Normalisation and Scaling
Individual indicators undergo transformation to a common 0-100 scale using percentile-based normalisation over rolling 252-period (approximately one-year) windows. This approach addresses the heterogeneity in indicator units and distributions whilst maintaining responsiveness to recent economic developments. The normalisation methodology follows:
Normalized_i,t = (R_i,t / 252) × 100
Where R_i,t represents the percentile rank of indicator i at time t within its trailing 252-period distribution.
Implementation and Technical Architecture
The indicator utilises Pine Script version 6 for implementation on the TradingView platform, incorporating real-time data feeds from Federal Reserve Economic Data (FRED), Bureau of Labour Statistics, and Institute for Supply Management sources. The architecture employs request.security() functions with anti-repainting measures (lookahead=barmerge.lookahead_off) to ensure temporal consistency in signal generation.
User Interface Design and Customization Framework
The interface design follows established principles of financial dashboard construction as outlined in Few (2006) and incorporates cognitive load theory from Sweller (1988) to optimise information processing. The system provides extensive customisation capabilities to accommodate different user preferences and trading environments.
Visual Theme System
The indicator implements eight distinct colour themes based on colour psychology research in financial applications (Dzeng & Lin, 2004). Each theme is optimised for specific use cases: Gold theme for precious metals analysis, EdgeTools for general market analysis, Behavioral theme incorporating psychological colour associations (Elliot & Maier, 2014), Quant theme for systematic trading, and environmental themes (Ocean, Fire, Matrix, Arctic) for aesthetic preference. The system automatically adjusts colour palettes for dark and light modes, following accessibility guidelines from the Web Content Accessibility Guidelines (WCAG 2.1) to ensure readability across different viewing conditions.
Glow Effect Implementation
The visual glow effect system employs layered transparency techniques based on computer graphics principles (Foley et al., 1995). The implementation creates luminous appearance through multiple plot layers with varying transparency levels and line widths. Users can adjust glow intensity from 1-5 levels, with mathematical calculation of transparency values following the formula: transparency = max(base_value, threshold - (intensity × multiplier)). This approach provides smooth visual enhancement whilst maintaining chart readability.
Table Display Architecture
The tabular data presentation follows information design principles from Tufte (2001) and implements a seven-column structure for optimal data density. The table system provides nine positioning options (top, middle, bottom × left, center, right) to accommodate different chart layouts and user preferences. Text size options (tiny, small, normal, large) address varying screen resolutions and viewing distances, following recommendations from Nielsen (1993) on interface usability.
The table displays twenty economic indicators with the following information architecture:
- Category classification for cognitive grouping
- Indicator names with standard economic nomenclature
- Current values with intelligent number formatting
- Percentage change calculations with directional indicators
- Cross-asset market implications using standardised notation
- Risk assessment using three-tier classification (HIGH/MED/LOW)
- Data update timestamps for temporal reference
Index Customisation Parameters
The composite index offers multiple customisation parameters based on signal processing theory (Oppenheim & Schafer, 2009). Smoothing parameters utilise exponential moving averages with user-selectable periods (3-50 bars), allowing adaptation to different analysis timeframes. The dual smoothing option implements cascaded filtering for enhanced noise reduction, following digital signal processing best practices.
Regime sensitivity adjustment (0.1-2.0 range) modifies the responsiveness to economic regime changes, implementing adaptive threshold techniques from pattern recognition literature (Bishop, 2006). Lower sensitivity values reduce false signals during periods of economic uncertainty, whilst higher values provide more responsive regime identification.
Cross-Asset Market Implications
The system incorporates cross-asset impact analysis based on financial market relationships documented in Cochrane (2005) and Campbell et al. (1997). Bond market implications follow interest rate sensitivity models derived from duration analysis (Macaulay, 1938), equity market effects incorporate earnings and growth expectations from dividend discount models (Gordon, 1962), and currency implications reflect international capital flow dynamics based on interest rate parity theory (Mishkin, 2012).
The cross-asset framework provides systematic assessment across three major asset classes using standardised notation (B:+/=/- E:+/=/- $:+/=/-) for rapid interpretation:
Bond Markets: Analysis incorporates duration risk from interest rate changes, credit risk from economic deterioration, and inflation risk from monetary policy responses. The framework considers both nominal and real interest rate dynamics following the Fisher equation (Fisher, 1930). Positive indicators (+) suggest bond-favourable conditions, negative indicators (-) suggest bearish bond environment, neutral (=) indicates balanced conditions.
Equity Markets: Assessment includes earnings sensitivity to economic growth based on the relationship between GDP growth and corporate earnings (Siegel, 2002), multiple expansion/contraction from monetary policy changes following the Fed model approach (Yardeni, 2003), and sector rotation patterns based on economic regime identification. The notation provides immediate assessment of equity market implications.
Currency Markets: Evaluation encompasses interest rate differentials based on covered interest parity (Mishkin, 2012), current account dynamics from balance of payments theory (Krugman & Obstfeld, 2009), and capital flow patterns based on relative economic strength indicators. Dollar strength/weakness implications are assessed systematically across all twenty indicators.
Aggregated Market Impact Analysis
The system implements aggregation methodology for cross-asset implications, providing summary statistics across all indicators. The aggregated view displays count-based analysis (e.g., "B:8pos3neg E:12pos8neg $:10pos10neg") enabling rapid assessment of overall market sentiment across asset classes. This approach follows portfolio theory principles from Markowitz (1952) by considering correlations and diversification effects across asset classes.
Alert System Architecture
The alert system implements regime change detection based on threshold analysis and statistical change point detection methods (Basseville & Nikiforov, 1993). Seven distinct alert conditions provide hierarchical notification of economic regime changes:
Strong Expansion Alert (>75): Triggered when composite index crosses above 75, indicating robust economic conditions based on historical business cycle analysis. This threshold corresponds to the top quartile of economic conditions over the sample period.
Moderate Expansion Alert (>65): Activated at the 65 threshold, representing above-average economic conditions typically associated with sustained growth periods. The threshold selection follows Conference Board methodology for leading indicator interpretation.
Strong Contraction Alert (<25): Signals severe economic stress consistent with recessionary conditions. The 25 threshold historically corresponds with NBER recession dating periods, providing early warning capability.
Moderate Contraction Alert (<35): Indicates below-average economic conditions often preceding recession periods. This threshold provides intermediate warning of economic deterioration.
Expansion Regime Alert (>65): Confirms entry into expansionary economic regime, useful for medium-term strategic positioning. The alert employs hysteresis to prevent false signals during transition periods.
Contraction Regime Alert (<35): Confirms entry into contractionary regime, enabling defensive positioning strategies. Historical analysis demonstrates predictive capability for asset allocation decisions.
Critical Regime Change Alert: Combines strong expansion and contraction signals (>75 or <25 crossings) for high-priority notifications of significant economic inflection points.
Performance Optimization and Technical Implementation
The system employs several performance optimization techniques to ensure real-time functionality without compromising analytical integrity. Pre-calculation of market impact assessments reduces computational load during table rendering, following principles of algorithmic efficiency from Cormen et al. (2009). Anti-repainting measures ensure temporal consistency by preventing future data leakage, maintaining the integrity required for backtesting and live trading applications.
Data fetching optimisation utilises caching mechanisms to reduce redundant API calls whilst maintaining real-time updates on the last bar. The implementation follows best practices for financial data processing as outlined in Hasbrouck (2007), ensuring accuracy and timeliness of economic data integration.
Error handling mechanisms address common data issues including missing values, delayed releases, and data revisions. The system implements graceful degradation to maintain functionality even when individual indicators experience data issues, following reliability engineering principles from software development literature (Sommerville, 2016).
Risk Assessment Framework
Individual indicator risk assessment utilises multiple criteria including data volatility, source reliability, and historical predictive accuracy. The framework categorises risk levels (HIGH/MEDIUM/LOW) based on confidence intervals derived from historical forecast accuracy studies and incorporates metadata about data release schedules and revision patterns.
Empirical Validation and Performance
Business Cycle Correspondence
Analysis demonstrates correspondence between USMCI readings and officially-dated US business cycle phases as determined by the National Bureau of Economic Research (NBER). Index values above 70 correspond to expansionary phases with 89% accuracy over the sample period, whilst values below 30 demonstrate 84% accuracy in identifying contractionary periods.
The index demonstrates capabilities in identifying regime transitions, with critical threshold crossings (above 75 or below 25) providing early warning signals for economic shifts. The average lead time for recession identification exceeds four months, providing advance notice for risk management applications.
Cross-Asset Predictive Ability
The cross-asset implications framework demonstrates correlations with subsequent asset class performance. Bond market implications show correlation coefficients of 0.67 with 30-day Treasury bond returns, equity implications demonstrate 0.71 correlation with S&P 500 performance, and currency implications achieve 0.63 correlation with Dollar Index movements.
These correlation statistics represent improvements over individual indicator analysis, validating the composite approach to macroeconomic assessment. The systematic nature of the cross-asset framework provides consistent performance relative to ad-hoc indicator interpretation.
Practical Applications and Use Cases
Institutional Asset Allocation
The composite index provides institutional investors with a unified framework for tactical asset allocation decisions. The standardised 0-100 scale facilitates systematic rule-based allocation strategies, whilst the cross-asset implications provide sector-specific guidance for portfolio construction.
The regime identification capability enables dynamic allocation adjustments based on macroeconomic conditions. Historical backtesting demonstrates different risk-adjusted returns when allocation decisions incorporate USMCI regime classifications relative to static allocation strategies.
Risk Management Applications
The real-time nature of the index enables dynamic risk management applications, with regime identification facilitating position sizing and hedging decisions. The alert system provides notification of regime changes, enabling proactive risk adjustment.
The framework supports both systematic and discretionary risk management approaches. Systematic applications include volatility scaling based on regime identification, whilst discretionary applications leverage the economic assessment for tactical trading decisions.
Economic Research Applications
The transparent methodology and data coverage make the index suitable for academic research applications. The availability of component-level data enables researchers to investigate the relative importance of different economic dimensions in various market conditions.
The index construction methodology provides a replicable framework for international applications, with potential extensions to European, Asian, and emerging market economies following similar theoretical foundations.
Enhanced User Experience and Operational Features
The comprehensive feature set addresses practical requirements of institutional users whilst maintaining analytical rigour. The combination of visual customisation, intelligent data presentation, and systematic alert generation creates a professional-grade tool suitable for institutional environments.
Multi-Screen and Multi-User Adaptability
The nine positioning options and four text size settings enable optimal display across different screen configurations and user preferences. Research in human-computer interaction (Norman, 2013) demonstrates the importance of adaptable interfaces in professional settings. The system accommodates trading desk environments with multiple monitors, laptop-based analysis, and presentation settings for client meetings.
Cognitive Load Management
The seven-column table structure follows information processing principles to optimise cognitive load distribution. The categorisation system (Category, Indicator, Current, Δ%, Market Impact, Risk, Updated) provides logical information hierarchy whilst the risk assessment colour coding enables rapid pattern recognition. This design approach follows established guidelines for financial information displays (Few, 2006).
Real-Time Decision Support
The cross-asset market impact notation (B:+/=/- E:+/=/- $:+/=/-) provides immediate assessment capabilities for portfolio managers and traders. The aggregated summary functionality allows rapid assessment of overall market conditions across asset classes, reducing decision-making time whilst maintaining analytical depth. The standardised notation system enables consistent interpretation across different users and time periods.
Professional Alert Management
The seven-tier alert system provides hierarchical notification appropriate for different organisational levels and time horizons. Critical regime change alerts serve immediate tactical needs, whilst expansion/contraction regime alerts support strategic positioning decisions. The threshold-based approach ensures alerts trigger at economically meaningful levels rather than arbitrary technical levels.
Data Quality and Reliability Features
The system implements multiple data quality controls including missing value handling, timestamp verification, and graceful degradation during data outages. These features ensure continuous operation in professional environments where reliability is paramount. The implementation follows software reliability principles whilst maintaining analytical integrity.
Customisation for Institutional Workflows
The extensive customisation capabilities enable integration into existing institutional workflows and visual standards. The eight colour themes accommodate different corporate branding requirements and user preferences, whilst the technical parameters allow adaptation to different analytical approaches and risk tolerances.
Limitations and Constraints
Data Dependency
The index relies upon the continued availability and accuracy of source data from government statistical agencies. Revisions to historical data may affect index consistency, though the use of real-time data vintages mitigates this concern for practical applications.
Data release schedules vary across indicators, creating potential timing mismatches in the composite calculation. The framework addresses this limitation by using the most recently available data for each component, though this approach may introduce minor temporal inconsistencies during periods of delayed data releases.
Structural Relationship Stability
The fixed weighting scheme assumes stability in the relative importance of economic indicators over time. Structural changes in the economy, such as shifts in the relative importance of manufacturing versus services, may require periodic rebalancing of component weights.
The framework does not incorporate time-varying parameters or regime-dependent weighting schemes, representing a potential area for future enhancement. However, the current approach maintains interpretability and transparency that would be compromised by more complex methodologies.
Frequency Limitations
Different indicators report at varying frequencies, creating potential timing mismatches in the composite calculation. Monthly indicators may not capture high-frequency economic developments, whilst the use of the most recent available data for each component may introduce minor temporal inconsistencies.
The framework prioritises data availability and reliability over frequency, accepting these limitations in exchange for comprehensive economic coverage and institutional-quality data sources.
Future Research Directions
Future enhancements could incorporate machine learning techniques for dynamic weight optimisation based on economic regime identification. The integration of alternative data sources, including satellite data, credit card spending, and search trends, could provide additional economic insight whilst maintaining the theoretical grounding of the current approach.
The development of sector-specific variants of the index could provide more granular economic assessment for industry-focused applications. Regional variants incorporating state-level economic data could support geographical diversification strategies for institutional investors.
Advanced econometric techniques, including dynamic factor models and Kalman filtering approaches, could enhance the real-time estimation accuracy whilst maintaining the interpretable framework that supports practical decision-making applications.
Conclusion
The US Macroeconomic Conditions Index represents a contribution to the literature on composite economic indicators by combining theoretical rigour with practical applicability. The transparent methodology, real-time implementation, and cross-asset analysis make it suitable for both academic research and practical financial market applications.
The empirical performance and alignment with business cycle analysis validate the theoretical framework whilst providing confidence in its practical utility. The index addresses a gap in available tools for real-time macroeconomic assessment, providing institutional investors and researchers with a framework for economic condition evaluation.
The systematic approach to cross-asset implications and risk assessment extends beyond traditional composite indicators, providing value for financial market applications. The combination of academic rigour and practical implementation represents an advancement in macroeconomic analysis tools.
References
Aruoba, S. B., Diebold, F. X., & Scotti, C. (2009). Real-time measurement of business conditions. Journal of Business & Economic Statistics, 27(4), 417-427.
Basseville, M., & Nikiforov, I. V. (1993). Detection of abrupt changes: Theory and application. Prentice Hall.
Bishop, C. M. (2006). Pattern recognition and machine learning. Springer.
Brave, S., & Butters, R. A. (2011). Monitoring financial stability: A financial conditions index approach. Economic Perspectives, 35(1), 22-43.
Burns, A. F., & Mitchell, W. C. (1946). Measuring business cycles. NBER Books, National Bureau of Economic Research.
Campbell, J. Y., Lo, A. W., & MacKinlay, A. C. (1997). The econometrics of financial markets. Princeton University Press.
Carroll, C. D., Fuhrer, J. C., & Wilcox, D. W. (1994). Does consumer sentiment forecast household spending? If so, why? American Economic Review, 84(5), 1397-1408.
Clarida, R., Gali, J., & Gertler, M. (2000). Monetary policy rules and macroeconomic stability: Evidence and some theory. Quarterly Journal of Economics, 115(1), 147-180.
Cochrane, J. H. (2005). Asset pricing. Princeton University Press.
Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009). Introduction to algorithms. MIT Press.
Doz, C., Giannone, D., & Reichlin, L. (2011). A two-step estimator for large approximate dynamic factor models based on Kalman filtering. Journal of Econometrics, 164(1), 188-205.
Dzeng, R. J., & Lin, Y. C. (2004). Intelligent agents for supporting construction procurement negotiation. Expert Systems with Applications, 27(1), 107-119.
Elliot, A. J., & Maier, M. A. (2014). Color psychology: Effects of perceiving color on psychological functioning in humans. Annual Review of Psychology, 65, 95-120.
Few, S. (2006). Information dashboard design: The effective visual communication of data. O'Reilly Media.
Fisher, I. (1930). The theory of interest. Macmillan.
Foley, J. D., van Dam, A., Feiner, S. K., & Hughes, J. F. (1995). Computer graphics: Principles and practice. Addison-Wesley.
Gordon, M. J. (1962). The investment, financing, and valuation of the corporation. Richard D. Irwin.
Hasbrouck, J. (2007). Empirical market microstructure: The institutions, economics, and econometrics of securities trading. Oxford University Press.
Koenig, E. F. (2002). Using the purchasing managers' index to assess the economy's strength and the likely direction of monetary policy. Economic and Financial Policy Review, 1(6), 1-14.
Krugman, P. R., & Obstfeld, M. (2009). International economics: Theory and policy. Pearson.
Ludvigson, S. C. (2004). Consumer confidence and consumer spending. Journal of Economic Perspectives, 18(2), 29-50.
Macaulay, F. R. (1938). Some theoretical problems suggested by the movements of interest rates, bond yields and stock prices in the United States since 1856. National Bureau of Economic Research.
Markowitz, H. (1952). Portfolio selection. Journal of Finance, 7(1), 77-91.
Mishkin, F. S. (2012). The economics of money, banking, and financial markets. Pearson.
Nielsen, J. (1993). Usability engineering. Academic Press.
Norman, D. A. (2013). The design of everyday things: Revised and expanded edition. Basic Books.
OECD (2008). Handbook on constructing composite indicators: Methodology and user guide. OECD Publishing.
Oppenheim, A. V., & Schafer, R. W. (2009). Discrete-time signal processing. Prentice Hall.
Sahm, C. (2019). Direct stimulus payments to individuals. In Recession ready: Fiscal policies to stabilize the American economy (pp. 67-92). The Hamilton Project, Brookings Institution.
Siegel, J. J. (2002). Stocks for the long run: The definitive guide to financial market returns and long-term investment strategies. McGraw-Hill.
Sommerville, I. (2016). Software engineering. Pearson.
Stock, J. H., & Watson, M. W. (1989). New indexes of coincident and leading economic indicators. NBER Macroeconomics Annual, 4, 351-394.
Sweller, J. (1988). Cognitive load during problem solving: Effects on learning. Cognitive Science, 12(2), 257-285.
Taylor, J. B. (1993). Discretion versus policy rules in practice. Carnegie-Rochester Conference Series on Public Policy, 39, 195-214.
Tufte, E. R. (2001). The visual display of quantitative information. Graphics Press.
Yardeni, E. (2003). Stock valuation models. Topical Study, 38. Yardeni Research.