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.
Поиск скриптов по запросу "信达股份40周年"
rainbow ema갤럭시님 이평선 토대로 JB가 에디트한 지수이평선 모음입니다. 편집하시면 일반 이평선으로도 사용이 가능합니다.
하나의 지표 추가 만으로 여러개의 지수이평선을 사용하실 수 있고, 제가 자주 사용하는 7,14,21,28,40,60,120,200,300선 넣어 놨습니다.
"Galaxy" made, JB edited EMA script. Editing is free for use if you swap ema to ma as a base setting.
You can use several ema lines by adding one indicator only, and I put 7,14,21,28,40,60,120,200,300 as a threshold which I frequently use.
It is made as an open source at any time possible, so that you are free for playing with it.
Gazua!!!!
Aggregate RSIAggregate RSI of the top 40 coins listed on CoinMarketCap.com on 25th of February, 2019, on USD or USDT pairs.
Because of requesting info about the prices of 40 coins using security(), this script is SLOW.
ADX +- DiThis Adx +-Di is just a complete version of what the ADX is supposed to signal.
So you have:
15 (contraction), 20 (threshold), 30 (expansion), 40 (resistance) levels.
Below 20 the price is not trending
Above 30 the price is trending
Below 15 price has been in contraction for too long
Between 20 and 30 price is in a "transition zone".
I finally added a "Resistance" level (40), which has to be adapted to best represent the historical levels where price usually encounters resistance, and where the price can be declared "overtrending", which means a return to lower levels is likely to happen.
I've chosen mild colors, and set the Adx Color to White, because I use black background, you can easily change that.
Enjoy
-Maurice
RSI|The Wave PrincipleThe Wave Principle | Modified RSI
30 green | 70 red = Strong Movement (Possible Impulse)
20 cyan | 80 Yellow = Strongest Movement
Support and Resistance Level (Trend Continuation)
Uptrend= 40
Downtrend = 60
Break+Retest = BR
Div = Divergence (Change in trend)
--------------------------------------------
This indicator has been modified from original RSI to fit Wave Principle characteristics:
Uptrend Impulsive Wave over 70 RSI it changes color to red, and > 80 yellow stronger impulse | Usually means continuation, at least once more.
Downtrend Impulsive Wave under 30 RSI it changes color to green, and < 20 cyan stronger impulse | Usually means continuation, at least once more.
Once RSI reached these levels, it doesn't mean trend reversal but a correction is expected. If it shows divergence along with an Ending Diagonal, it's a confirmation for trend reversal.
In a corrective wave, levels 40-60 represents support and resistance levels where price won't go further. Indicating Corrective Waves, not as strong as Impulsives.
Prices can breakout RSI trend lines and retest from the other side before continue the new trend as also described in the Wave Principle.
--------------------------------------------
breakout and swingA Price Action system that use swing point and breakout
above the black line (breakout) is long, below short
swing/support/resistance points (blue circles) are displayed after a top or botton, breaking it means an inversion
red circles try to guest a target after a top/bottom or after a swing break.
the main trend is made by the black line that is set on Day period suitable for 1h to 15m time frame , for small TF you can set a smaller period from setting command
By default a set a 40 period channel high/low (the highest and lowest 40 bar back) that is ok for 1 h or smaller tf , but look to long for daily tf, adjust it yourself
Net XMR Margin PositionTotal XMR Longs minus XMR Shorts in order to give you the total outstanding XMR margin debt.
ie: If 50,000 XMR has been longed, and 40,000 XMR has been shorted, then 50,000 has been bought, and 40,000 sold, leaving us with 10,000 XMR (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
Net BTC Margin PositionTotal BTCUSDLONGS minus the BTCUSDSHORTS in order to give you the total outstanding BTC margin debt.
ie: If there are 50,000 BTC longs, and 40,000 BTC shorts, then 50,000 has been bought, and 40,000 sold, leaving us with 10,000 BTC net remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
(Anyone know what category this script should be in?)
Accumulation/Distribution Percentage (ADP) [Cyrus c|:D]Accumulation/Distribution Percentage ( ADP ) is used to measure money flow similar to Chaikin Money Flow ( CMF ) and Money Flow. It is the range-bound version of my previous indicator ADMF. This indicator can be used for analyzing momentum, buy/sell pressure, and overbought/oversold conditions. I believe that this indicator is more accurate than CMF and MFI (I will publish a TA about it one day!).
What to look for:
- When this indicator moves up, it means buy pressure is increasing and the other way around for sell pressure. Crossing 0 means that trend has changed in the given period (it is best to look for confirmation of buy/sell pressure in larger TFs)
- Overbought above 40 and oversold below -40 (these numbers vary depending on the security. Look for historical levels to determine overbought and oversold conditions of each security)
- Regular divergence shows that momentum of a trend is declining. Hidden divergence implies continuation of a trend. The non-bound mode should be more accurate for identifying divergence.
- Failure swings can detect potential reversals.
Please read Relative Strength Index and Money Flow for more information and similar disclaimers.
Recommendations:
- hlc3 (AKA typical price) as input source might be better than "close" as it captures more information. If you use hlc3 as a source, then change the chart type to line and set hlc3 as the source for identifying divergence.
- Use hybrid tickers e.g.(BITFINEX:BTCUSD+COINBASE:BTCUSD+BITSTAMP:BTCUSD)/3. Volume-based indicators are susceptible to wash trading/volume printing and hybrid tickers mitigate this issue.
- In non-bound mode, small TFs with longer length should be more accurate than larger TFs with standard length (same is true for many other indicators)
Background:
I have developed 4 indicators based on a simple but elegant concept of A/D ratio. A/D ratio is equal to (current close - previous close)/True Range (when there are no price gaps, True Range = High - Low)
1) What you see on ADV indicator as darker green and red is equal to A/D ratio x volume.
2) ADL indicator shows the summation of ADV
3) ADMF (or ADP in non-bound mode) shows Moving Average of ADV
4) ADP shows relative accumulation strength which is calculated as RMA (accumulations)/RMA(accumulation + distribution). ADP equation is based on RSI equation which is RMA(gains)/RMA(gains + losses). That is why these two indicators look quite similar.
PS: Please leave a like if you find these indicators useful. I am working on improvements on these and other indicators. I am trying my best to keep them as simple as possible. Please let me know in the comments if you want me to make future indicators even simpler.
--------
Complementary indicators based on the same concept:
ADL: a replacement for Chaikin's Accum/Dist, On Balance Volume, and Price Volume Trend
ADV: a replacement for regular volume indicator
ADP also has a scaled RSI and ADMF built in (ie ADMF is obsolete).
Better RSI with bullish / bearish market cycle indicator This script improves the default RSI. First. it identifies regions of the RSI which are oversold and overbought by changing the color of RSI from white to red. Second, it adds additional reference lines at 20,40,50,60, and 80 to better gauge the RSI value. Finally, the coolest feature, the middle 50 line is used to indicate which cycle the price is currently at. A green color at the 50 line indicates a bullish cycle, a red color indicators a bearish cycle, and a white color indicates a neutral cycle.
The cycles are determined using the RSI as follows:
if RSI is overbought, cycle switches to bullish until RSI falls below 40, at which point it becomes neutral
if RSI is oversold, cycle switches bearish until RSI rises above 60, at which point it becomes neutral
a neutral cycle is exited at either overbought or oversold conditions
Very useful, please give it a try and let me know what you think
Volume Range EventsChanges in the feelings (positive, negative, neutral) in the market concerning the valuation of an instrument are often preceded with sudden outbursts of buying and selling frenzies. The aim of this indicator is to report such outbursts. We can see them as expansions of volume, sometimes 10 times more than usual. and as extensions of the trading range, also sometimes 10 times more than usual (e.g. usual range is 10 cent suddenly a whole dollar.) The changes are calculated in such a way that these fit between plus and minus 100 percent, the bars are scaled in some sort of logarithmic way. The Emoline is the same as the one in the True Balance of Power indicator, which I already published
ONLY RISES ARE EVENTS
Sometimes analysts are tempted to give meaning to low volume or small ranges. These simply mean that the market has little interest in trading this instrument. I believe that in such cases the trader needs to wait for expansion and extension events to happen, then he can make a better guess of where the market is heading. As events often mark the beginning or ending of a trend, this indicator provides an early and clear signal, because it doesn’t bother us about non-events.
WHAT IS USUAL?
If the algorithm would use an average as a normal to scale volume or range events, then previous peaks will act as spoilers by making the average so high that a following peak is scaled too small. I developed a function, usual() , that kicks out all extremes of a ‘population of values’ and which returns the average of the non-extreme values. It can be called with any serial. This function is called by both algorithms that report volume and range peaks, which guarantees that the results are really comparable. As this function has a fixed look back of 8 periods, we might state that ‘usual’ is a short lived relative value. I think this doesn’t matter for the practical use of the indicator.
COLORING AND INTERPRETATION
I follow the categories in the ‘Better Volume Indicator’, published by LeazyBear, these are:
1. Climactic Volumes, event >40 % (this means peak is 1.5 X usual)
LIME: Climax Buying Volume, direction up, range event also > 30 %
RED: Climax Selling Volume, direction down, range event also > 30 %
AQUA: Climax Churning Volume, both directions, range event < 30%
2. Smaller Volumes, event <40 %
GREEN: Supportive Volume, both directions, if combined with range event
BLUE: Churning Volume, both directions, if not combined with range event (Professional Trading)
3. Just Range Events
BLACK histogram bars (Amateurish Trading)
RSI in Bull and Bear Market V2.0RSI oversold at 60/40 in bullish market
And Overbought at 40/60 in Bearish market
for more info of this Strategy
PyraTime: Tesla Trinity [LITE] | 3-6-9 Time CyclesThe Algorithm of the Universe
"If you knew the magnificence of the 3, 6, and 9, you would have a key to the universe." — Nikola Tesla
Most traders analyze Price (the Y-axis) but completely ignore the most critical dimension: Time (the X-axis).
PyraTime: Tesla Trinity is a harmonic time projector. It moves beyond standard technical analysis by translating the ancient Solfeggio Frequencies directly into time cycles on your chart.
How It Works
This indicator projects the 9 core Solfeggio frequencies as specific time intervals anchored to a user-defined "Origin Pivot." When these invisible time harmonics align, they create "Time Clusters"—high-probability zones where market energy is likely to pivot, reverse, or expand.
The 3-6-9 Sequences
The indicator visualizes three distinct energy groups:
🔴 The Grounding Trinity (174Hz - 396Hz): Foundation & Stability.
🟢 The Transformation Trinity (417Hz - 639Hz): Change & Acceleration.
🔵 The Awakening Trinity (741Hz - 963Hz): Spiritual Peak & Completion.
How to Use (LITE Version)
Find the Origin: Identify a major market structure point (e.g., a Swing High or Low).
Set the Anchor: In the settings, input the exact time of that pivot into the "Origin Pivot" field.
Watch the Clusters: Look for areas where multiple frequency lines converge.
Example: A Grounding line (Red) and an Awakening line (Blue) overlapping often signals a trend reversal.
Included in LITE Version
✅ 1-Minute Fractals: For scalping and micro-cycle analysis.
✅ 15-Minute Fractals: For intraday trend identification.
✅ Full Harmonic Spectrum: All 9 Solfeggio frequencies included.
Want the Master Edition?
The Master Edition unlocks the "Hidden Fractals" used by institutional harmonic traders:
🔓 The "4x" Suite: 4-minute, 40-minute, and 4-hour projection cycles.
🔓 Macro Cycles: Hourly and Daily projections for Swing Trading.
🔓 Golden Anchor: Advanced precision tools.
"Search 'PyraTime' for the Master Edition."
Disclaimer: This tool is for educational and experimental purposes only. Trading involves risk.
Micro Pullback Entry SystemMicro Pullback Entry System - Quick Reference
The Pattern
▲ ENTRY (first green to break high)
│
┌──┴───┐
│ 1-3 │ ← PULLBACK (red candles)
│ red │ Stop = Low of this zone
└──────┘
│
┌──┴───┐
│ 3+ │ ← THE MOVE (green candles)
│green │ Strong momentum
└──────┘
Pattern Checklist
Requirement: Why It Matters
3+ green candlesConfirms momentum
1-3 red pullback Brief = momentum intact< 50% retracementShallow = buyers in controlVolume on entryConfirms breakout Above EMA Trend support
Status Flow
Scanning... → 📈 TRENDING → 👀 WATCHING → ⏳ FORMING → 🎯 ENTRY!
StatusMeaningActionScanningLooking for setupWait📈 TRENDINGGreen streak buildingMonitor👀 WATCHINGPullback startedPrepare⏳ FORMINGValid pullback readyGet ready!🎯 ENTRY!Signal triggeredExecute
Entry/Stop/Target
LevelLine ColorHow to SetEntryLime solidClose of signal candleStopRed dashedLow of pullbackTarget 1Aqua dottedEntry + (2 × Risk)Target 2Yellow dottedEntry + (3 × Risk)
Example
Entry: $5.00
Stop: $4.80
Risk: $0.20
Target 1 (2R): $5.00 + $0.40 = $5.40
Target 2 (3R): $5.00 + $0.60 = $5.60
Quality Grades
GradeScoreActionA+5/5 ✓Best setup - full sizeA4/5 ✓Good setup - standard sizeB3/5 ✓Average - reduced sizeC2/5 ✓Weak - skip or tiny size
Scoring Factors
✓ Green streak met minimum
✓ Pullback length valid (1-3)
✓ Retracement shallow (<50%)
✓ Volume confirmed
✓ Above EMA
Trade Execution
Entry
Wait for "⏳ FORMING" status
Watch for green candle forming
Entry triggers when green candle closes above pullback high
Enter at market or small limit above current price
Stop Loss
Set at pullback low (red dashed line)
Non-negotiable - this is your max risk
Trade Management
If no immediate follow-through → exit early
Take 50% off at Target 1 (aqua line)
Move stop to breakeven
Let remainder run to Target 2
Settings Guide
Default (Recommended)
Min Green Candles: 3
Min Pullback: 1
Max Pullback: 3
Max Retracement: 50%
Volume Multiplier: 1.2x
EMA Filter: ON (20)
Conservative (Fewer, Better)
Min Green Candles: 4
Min Pullback: 2
Max Pullback: 3
Max Retracement: 40%
Volume Multiplier: 1.5x
EMA Filter: ON (20)
Aggressive (More Signals)
Min Green Candles: 2
Min Pullback: 1
Max Pullback: 4
Max Retracement: 60%
Volume Multiplier: 1.0x
EMA Filter: OFF
Common Mistakes
❌ Entering before signal
Wait for green triangle
"FORMING" ≠ "ENTRY"
❌ Wide stop
Stop must be at pullback low
If too wide, skip the trade
❌ Ignoring volume
Low volume entries fail more often
Look for ✓ in volume row
❌ Fighting trend
Check EMA status
Should show "Above ✓"
❌ Chasing after entry
If you miss entry by 3+ candles, wait for next setup
Don't chase extended moves
Best Setups
A+ Quality Setup ✓
4-5 green candles (strong move)
2 candle pullback (brief)
25-35% retracement (shallow)
2x+ volume on entry
Well above EMA
Stock already up 5%+ on day
Avoid These ✗
Only 2 green candles
4+ candle pullback (losing momentum)
50%+ retracement (too deep)
Below average volume
Below or at EMA
Against market direction
Timeframe Guide
TFSignalsQualityBest For1mMostLowerScalping5mBalancedGoodDay trading15mFewestHigherSwing entries
Quick Decision Tree
1. Status showing "FORMING"?
NO → Wait
YES → Continue
2. Quality grade A or better?
NO → Skip or small size
YES → Continue
3. Volume confirmed (✓)?
NO → Caution, reduce size
YES → Continue
4. Above EMA (✓)?
NO → Skip
YES → Continue
5. Risk acceptable? (Stop not too wide)
NO → Skip
YES → TAKE THE TRADE
Alert Setup
Essential Alert
"Micro Pullback Entry" - Main signal
How to Set
Right-click chart → Add Alert
Condition: Micro Pullback Entry System
Select "Micro Pullback Entry"
Set notification preferences
Combining with Other Indicators
IndicatorHow to Use5 PillarsFind stocks meeting criteria firstGap & GoLook for micro pullbacks after gap breakoutsR2G TrackerConfirm stock is green before enteringFloat RotationHigh rotation + micro pullback = best setupsBull FlagMicro pullback is a "mini" bull flag
Example Trade
Stock: XYZ
Pre-market: Gapped up 15%
9:35 - 9:38: 4 green candles (move from $4.50 to $5.00)
9:39 - 9:40: 2 red candles (pullback to $4.85)
9:41: Green candle breaks $4.90 (pullback high)
ENTRY: $4.92
STOP: $4.82 (pullback low)
RISK: $0.10
TARGET 1: $5.12 (+$0.20 = 2R)
TARGET 2: $5.22 (+$0.30 = 3R)
Result: Hit Target 2 by 9:55 → +$0.30 per share
Key Takeaways
Micro = 1-3 candles - Brief pullback
Entry = First green to break high - Specific trigger
Stop = Pullback low - Tight risk
Quality matters - Focus on A/A+ setups
Breakout or bailout - Exit if no follow-through
SPX AbuBasel Scalping PRO – Stable//@version=5
indicator("SPX AbuBasel Scalping PRO – Stable", overlay=true, precision=2)
// ==== Inputs ====
lenRSI = input.int(7, "RSI Length")
tp1ATR = input.float(0.35, "TP1 ATR Factor", step=0.05)
tp2ATR = input.float(0.70, "TP2 ATR Factor", step=0.05)
tp3ATR = input.float(1.00, "TP3 ATR Factor", step=0.05)
slATR = input.float(0.45, "SL ATR Factor", step=0.05)
useVol = input.bool(true, "Use Volume Filter")
// ==== Indicators ====
rsi = ta.rsi(close, lenRSI)
vwap = ta.vwap
atr = ta.atr(14)
// Bollinger Bands
basis = ta.sma(close, 20)
dev = 2.0 * ta.stdev(close, 20)
upper = basis + dev
lower = basis - dev
// Volume filter
volOK = volume > ta.sma(volume, 20)
// Divergence
bullDiv = low < low and rsi > rsi
bearDiv = high > high and rsi < rsi
// Reversal candles
bullCandle = close > open and close > high
bearCandle = close < open and close < low
// VWAP slope
trendUp = vwap > vwap
trendDown = vwap < vwap
// ==== Entry Conditions ====
buySig = bullDiv and bullCandle and close > vwap and trendUp and (not useVol or volOK) and close < lower
sellSig = bearDiv and bearCandle and close < vwap and trendDown and (not useVol or volOK) and close > upper
// ==== Targets ====
tp1 = buySig ? close + atr * tp1ATR : sellSig ? close - atr * tp1ATR : na
tp2 = buySig ? close + atr * tp2ATR : sellSig ? close - atr * tp2ATR : na
tp3 = buySig ? close + atr * tp3ATR : sellSig ? close - atr * tp3ATR : na
sl = buySig ? close - atr * slATR : sellSig ? close + atr * slATR : na
// ==== Plot Signals ====
plotshape(buySig, title="BUY", style=shape.labelup, color=color.green, text="BUY", size=size.small)
plotshape(sellSig, title="SELL", style=shape.labeldown, color=color.red, text="SELL", size=size.small)
// ==== Draw Levels ====
if buySig or sellSig
line.new(bar_index, tp1, bar_index + 1, tp1, extend=extend.right, color=color.new(color.green, 0))
line.new(bar_index, tp2, bar_index + 1, tp2, extend=extend.right, color=color.new(color.lime, 0))
line.new(bar_index, tp3, bar_index + 1, tp3, extend=extend.right, color=color.new(color.green, 40))
line.new(bar_index, sl, bar_index + 1, sl, extend=extend.right, color=color.new(color.red, 0))
// ==== Alerts ====
alertcondition(buySig, "SPX BUY", "AbuBasel PRO: BUY Signal")
alertcondition(sellSig, "SPX SELL", "AbuBasel PRO: SELL Signal")
Debt-Cycle vs Bitcoin-CycleDebt-Cycle vs Bitcoin-Cycle Indicator
The Debt-Cycle vs Bitcoin-Cycle indicator is a macro-economic analysis tool that compares traditional financial market cycles (debt/credit cycles) against Bitcoin market cycles. It uses Z-score normalization to track the relative positioning of global financial conditions versus cryptocurrency market sentiment, helping identify potential turning points and divergences between traditional finance and digital assets.
Key Features
Dual-Cycle Analysis: Simultaneously tracks traditional financial cycles and Bitcoin-specific cycles
Z-Score Normalization: Standardizes diverse data sources for meaningful comparison
Multi-Asset Coverage: Analyzes currencies, commodities, bonds, monetary aggregates, and on-chain metrics
Divergence Detection: Identifies when Bitcoin cycles move independently from traditional finance
21-Day Timeframe: Optimized for Long-term cycle analysis
What It Measures
Finance-Cycle (White Line)
Tracks traditional financial market health through:
Currencies: USD strength (DXY), global currency weights (USDWCU, EURWCU)
Commodities: Oil, gold, natural gas, agricultural products, and Bitcoin price
Corporate Bonds: Investment-grade spreads, high-yield spreads, credit conditions
Monetary Aggregates: M2 money supply, foreign exchange reserves (weighted by currency)
Treasury Bonds: Yield curve (2Y/10Y, 3M/10Y), term premiums, long-term rates
Bitcoin-Cycle (Orange Line)
Tracks Bitcoin market positioning through:
On-Chain Metrics:
MVRV Ratio (Market Value to Realized Value)
NUPL (Net Unrealized Profit/Loss)
Profit/Loss Address Distribution
Technical Indicators:
Bitcoin price Z-score
Moving average deviation
Relative Strength:
ETH/BTC ratio (altcoin strength indicator)
Visual Elements
White Line: Finance-Cycle indicator (positive = expansionary conditions, negative = contractionary)
Orange Line: Bitcoin-Cycle indicator (positive = bullish positioning, negative = bearish)
Zero Line: Neutral reference point
Interpretation
Cycle Alignment
Both positive: Risk-on environment, favorable for crypto
Both negative: Risk-off environment, caution warranted
Divergence: Potential opportunities or warning signals
Divergence Signals
Finance positive, Bitcoin negative: Bitcoin may be undervalued relative to macro conditions
Finance negative, Bitcoin positive: Bitcoin may be overextended or decoupling from traditional finance
Important Limitations
This indicator uses some technical and macro data but still has significant gaps:
⚠️ Limited monetary data - missing:
Funding rates (repo, overnight markets)
Comprehensive bond spread analysis
Collateral velocity and quality metrics
Central bank balance sheet details
⚠️ Basic economic coverage - missing:
GDP growth rates
Inflation expectations
Employment data
Manufacturing indices
Consumer confidence
⚠️ Simplified on-chain analysis - missing:
Exchange flow data
Whale wallet movements
Mining difficulty adjustments
Hash rate trends
Network fee dynamics
⚠️ No sentiment data - missing:
Fear & Greed Index
Options positioning
Futures open interest
Social media sentiment
The indicator provides a high-level cycle comparison but should be combined with comprehensive fundamental analysis, detailed on-chain research, and proper risk management.
Settings
Offset: Adjust the horizontal positioning of the indicators (default: 0)
Timeframe: Fixed at 21 days for optimal cycle detection
Use Cases
Macro-crypto correlation analysis: Understand when Bitcoin moves with or against traditional markets
Cycle timing: Identify potential tops and bottoms in both cycles
Risk assessment: Gauge overall market conditions across asset classes
Divergence trading: Spot opportunities when cycles diverge significantly
Portfolio allocation: Balance traditional and crypto assets based on cycle positioning
Technical Notes
Uses Z-score normalization with varying lookback periods (40-60 bars)
Applies HMA (Hull Moving Average) smoothing to reduce noise
Asymmetric multipliers for upside/downside movements in certain metrics
Requires access to FRED economic data, Glassnode, CoinMetrics, and IntoTheBlock feeds
21-day timeframe optimized for cycle analysis
Strategy Applications
This indicator is particularly useful for:
Cross-asset allocation - Decide between traditional finance and crypto exposure
Cycle positioning - Identify where we are in credit/debt cycles vs. Bitcoin cycles
Regime changes - Detect shifts in market leadership and correlation patterns
Risk management - Reduce exposure when both cycles turn negative
Disclaimer: This indicator is a cycle analysis tool and should not be used as the sole basis for investment decisions. It has limited coverage of monetary conditions, economic fundamentals, and on-chain metrics. The indicator provides directional insight but cannot predict exact timing or magnitude of market moves. Always conduct thorough research, consider multiple data sources, and maintain proper risk management in all investment decisions.
Smart RSI Composite [DotGain]Summary
Do you want to know the "True Direction" of the market without getting distracted by noise on a single timeframe?
The Smart RSI Composite simplifies market analysis by aggregating momentum data from 10 different timeframes (5m to 12M) into a single, easy-to-read Histogram.
Instead of looking at 10 separate charts or dots, this indicator calculates the Average RSI of the entire market structure. It answers one simple question: "Is the market predominantly Bullish or Bearish right now?"
⚙️ Core Components and Logic
This indicator works like a consensus mechanism for momentum:
Data Aggregation: It pulls RSI values from 10 customizable slots (Default: 5m, 15m, 1h, 4h, 1D, 1W, 1M, 3M, 6M, 12M). All slots are enabled by default.
Smart Averaging: It calculates the arithmetic mean of all active timeframes. If the 5m chart is bearish but the Monthly chart is bullish, this indicator balances them out to show you the net result.
Histogram Visualization: The result is plotted as a histogram centered around the 50-line (Neutral).
🚦 How to Read the Histogram
The histogram bars indicate the aggregate strength of the trend based on the Average RSI:
🟩 DARK GREEN (Strong Bullish)
Condition: Average RSI > 60.
Meaning: The market is in a strong uptrend across most timeframes. Momentum is firmly on the buyers' side.
🟢 LIGHT GREEN (Weak Bullish)
Condition: Average RSI between 50 and 60.
Meaning: Slight bullish bias. The bulls are in control, but momentum is not yet extreme.
🔴 LIGHT RED (Weak Bearish)
Condition: Average RSI between 40 and 50.
Meaning: Slight bearish bias. The bears are taking control.
🟥 DARK RED (Strong Bearish)
Condition: Average RSI < 40.
Meaning: The market is in a strong downtrend across most timeframes. Momentum is firmly on the sellers' side.
Visual Elements
Center Line (50): This acts as the Zero-Line. Above 50 is bullish, below 50 is bearish.
Zone Lines (30/70): Dashed lines indicate the traditional Overbought/Oversold levels applied to the aggregate average.
Key Benefit
The Smart RSI Composite acts as a powerful Macro Trend Filter .
Pro Tip: Never go long if the Histogram is Dark Red, and avoid shorting when it is Dark Green. Use this tool to align your trades with the overall market momentum.
Have fun :)
Disclaimer
This "Smart RSI Composite" indicator is provided for informational and educational purposes only. It does not, and should not be construed as, financial, investment, or trading advice.
The signals generated by this tool (both "Buy" and "Sell" indications) are the result of a specific set of algorithmic conditions. They are not a direct recommendation to buy or sell any asset. All trading and investing in financial markets involves substantial risk of loss. You can lose all of your invested capital.
Past performance is not indicative of future results. The signals generated may produce false or losing trades. The creator (© DotGain) assumes no liability for any financial losses or damages you may incur as a result of using this indicator.
You are solely responsible for your own trading and investment decisions. Always conduct your own research (DYOR) and consider your personal risk tolerance before making any trades.
Smart RSI MTF Matrix [DotGain]Summary
Are you tired of trading trend signals, only to miss the bigger picture because you are focused on a single timeframe?
The Smart RSI MTF Matrix is the ultimate "Cockpit View" for momentum traders. Unlike chart overlays that can sometimes clutter your price action, this indicator organizes RSI conditions across 10 different timeframes simultaneously into a clean, separate Heatmap pane.
It monitors everything from the 5-minute chart all the way up to the 12-Month view , giving you a complete X-ray vision of the market's momentum structure instantly.
⚙️ Core Components and Logic
The Smart RSI MTF Matrix relies on a sophisticated hierarchy to deliver clear, actionable context:
Multi-Timeframe Engine: The script runs 10 independent RSI calculations in the background, organized in rows from bottom (Short Term) to top (Long Term).
Classic RSI Thresholds:
Overbought (> 70): Indicates price may be extended to the upside.
Oversold (< 30): Indicates price may be extended to the downside.
Smart Visibility System (The "Secret Sauce"): Not all signals are equal. A 5-minute signal is "noise" compared to a Yearly signal. This indicator automatically applies Transparency to differentiate importance. The visibility increases by 10% for each higher timeframe slot (Row).
🚦 How to Read the Matrix
The indicator plots dots in 10 stacked rows. The position and opacity tell you the direction and significance:
🟥 RED DOTS (Overbought Condition)
Trigger: RSI is above 70 on that specific timeframe.
Meaning: Potential bearish reversal or pullback.
🟩 GREEN DOTS (Oversold Condition)
Trigger: RSI is below 30 on that specific timeframe.
Meaning: Potential bullish reversal or bounce.
⚪ GRAY DOTS (Neutral)
Trigger: RSI is between 30 and 70.
Meaning: No extreme momentum present.
👻 TRANSPARENCY (Signal Strength)
The visibility of the dot tells you exactly which Timeframe (Row) is triggered. The higher the row, the more solid the color:
Faint (10-30% Visibility): Rows 1-3 (5m, 15m, 1h). Used for scalping entries.
Medium (40-60% Visibility): Rows 4-6 (4h, 1D, 1W). Used for swing trading context.
Solid (70-100% Visibility): Rows 7-10 (1M, 3M, 6M, 12M). Used for identifying major macro cycles.
Visual Elements
Structure: Row 1 (Bottom) represents the 5-minute timeframe. Row 10 (Top) represents the 12-Month timeframe.
Vertical Alignment: If you see a vertical column of Red or Green dots, it indicates Multi-Timeframe Confluence —a highly probable reversal point.
Key Benefit
The goal of the Smart RSI MTF Matrix is to keep your main chart clean while providing maximum information. You can instantly see if a short-term pullback (Faint Green Dot) is happening within a long-term uptrend (Solid Gray/Red Dot), allowing for precision entries.
Have fun :)
Disclaimer
This "Smart RSI MTF Matrix" indicator is provided for informational and educational purposes only. It does not, and should not be construed as, financial, investment, or trading advice.
The signals generated by this tool (both "Buy" and "Sell" indications) are the result of a specific set of algorithmic conditions. They are not a direct recommendation to buy or sell any asset. All trading and investing in financial markets involves substantial risk of loss. You can lose all of your invested capital.
Past performance is not indicative of future results. The signals generated may produce false or losing trades. The creator (© DotGain) assumes no liability for any financial losses or damages you may incur as a result of using this indicator.
You are solely responsible for your own trading and investment decisions. Always conduct your own research (DYOR) and consider your personal risk tolerance before making any trades.
RSI Regime & Reversals (Leading) — Bull/Bear Trend Finder📈 RSI Regime & Reversals (Leading) — Bull/Bear Trend Finder
This advanced RSI-based tool helps identify bullish and bearish market trends before they happen — combining classic RSI analysis with Cardwell-style reversals and range shift detection to act as a leading indicator rather than a lagging one.
🧠 Core Concept
The script detects when RSI behavior “shifts ranges,” a signature of trend changes:
• Bull Regime — RSI pullbacks hold above ~40 (momentum stays strong)
• Bear Regime — RSI rallies stall below ~60 (momentum weakens)
It then looks for leading clues inside those regimes:
• ✅ Positive Reversal: Price makes a higher low while RSI makes a lower low — a bullish continuation or early trend reversal signal.
• ❌ Negative Reversal: Price makes a lower high while RSI makes a higher high — an early warning of weakness.
• 🔁 Classic Divergences: Confirms reversals when RSI and price diverge at pivot points.
🎯 Signals
• Green “▲ Bull lead” — bullish reversal or divergence detected.
• Red “▼ Bear lead” — bearish reversal or divergence detected.
• Optional background shading:
• 🟩 Teal = Bullish regime
• 🟥 Red = Bearish regime
⚙️ Customization
• Regime sensitivity — Adjust RSI floor/ceiling for your asset’s volatility.
• Pivot sensitivity — Tune pivot lookback (L/R bars) for faster or slower signals.
• RSI smoothing — Filters noise without losing responsiveness.
• Alerts included — Trigger TradingView alerts for bullish or bearish leading signals.
🕵️♂️ Why it’s different
Unlike standard RSI divergences (which confirm after the move), this indicator uses positive/negative reversals to identify potential trend shifts early — a technique favored by Andrew Cardwell’s RSI analysis.
📊 Works great for:
• Swing trading and trend detection
• Spotting momentum regime shifts
• Stocks, crypto, FX, indices
Smart Money Flow - Exchange & TVL Composite# Smart Money Flow - Exchange & TVL Composite Indicator
## Overview
The **Smart Money Flow (SMF)** indicator combines two powerful on-chain metrics - **Exchange Flows** and **Total Value Locked (TVL)** - to create a composite index that tracks institutional and "smart money" movement in the cryptocurrency market. This indicator helps traders identify accumulation and distribution phases by analyzing where capital is flowing.
## What It Does
This indicator normalizes and combines:
- **Exchange Net Flow** (from IntoTheBlock): Tracks Bitcoin/Ethereum movement to and from exchanges
- **Total Value Locked** (from DefiLlama): Measures capital locked in DeFi protocols
The composite index is displayed on a 0-100 scale with clear zones for overbought/oversold conditions.
## Core Concept
### Exchange Flows
- **Negative Flow (Outflows)** = Bullish Signal
- Coins moving OFF exchanges → Long-term holding/accumulation
- Indicates reduced selling pressure
- **Positive Flow (Inflows)** = Bearish Signal
- Coins moving TO exchanges → Preparation for selling
- Indicates potential distribution phase
### Total Value Locked (TVL)
- **Rising TVL** = Bullish Signal
- Capital flowing into DeFi protocols
- Increased ecosystem confidence
- **Falling TVL** = Bearish Signal
- Capital exiting DeFi protocols
- Decreased ecosystem confidence
### Combined Signals
**🟢 Strong Bullish (70-100):**
- Exchange outflows + Rising TVL
- Smart money accumulating and deploying capital
**🔴 Strong Bearish (0-30):**
- Exchange inflows + Falling TVL
- Smart money preparing to sell and exiting positions
**⚪ Neutral (40-60):**
- Mixed or balanced flows
## Key Features
### ✅ Auto-Detection
- Automatically detects chart symbol (BTC/ETH)
- Uses appropriate exchange flow data for each asset
### ✅ Weighted Composite
- Customizable weights for Exchange Flow and TVL components
- Default: 50/50 balance
### ✅ Normalized Scale
- 0-100 index scale
- Configurable lookback period for normalization (default: 90 days)
### ✅ Signal Zones
- **Overbought**: 70+ (Strong bullish pressure)
- **Oversold**: 30- (Strong bearish pressure)
- **Extreme**: 85+ / 15- (Very strong signals)
### ✅ Clean Interface
- Minimal visual clutter by default
- Only main index line and MA visible
- Optional elements can be enabled:
- Background color zones
- Divergence signals
- Trend change markers
- Info table with detailed metrics
### ✅ Divergence Detection
- Identifies when price diverges from smart money flows
- Potential reversal warning signals
### ✅ Alerts
- Extreme overbought/oversold conditions
- Trend changes (crossing 50 line)
- Bullish/bearish divergences
## How to Use
### 1. Trend Confirmation
- Index above 50 = Bullish trend
- Index below 50 = Bearish trend
- Use with price action for confirmation
### 2. Reversal Signals
- **Extreme readings** (>85 or <15) suggest potential reversal
- Look for divergences between price and indicator
### 3. Accumulation/Distribution
- **70+**: Accumulation phase - smart money buying/holding
- **30-**: Distribution phase - smart money selling
### 4. DeFi Health
- Monitor TVL component for DeFi ecosystem strength
- Combine with exchange flows for complete picture
## Settings
### Data Sources
- **Exchange Flow**: IntoTheBlock real-time data
- **TVL**: DefiLlama aggregated DeFi TVL
- **Manual Mode**: For testing or custom data
### Indicator Settings
- **Smoothing Period (MA)**: Default 14 periods
- **Normalization Lookback**: Default 90 days
- **Exchange Flow Weight**: Adjustable 0-100%
- **Overbought/Oversold Levels**: Customizable thresholds
### Visual Options
- Show/Hide Moving Average
- Show/Hide Zone Lines
- Show/Hide Background Colors
- Show/Hide Divergence Signals
- Show/Hide Trend Markers
- Show/Hide Info Table
## Data Requirements
⚠️ **Important Notes:**
- Uses **daily data** from IntoTheBlock and DefiLlama
- Works on any chart timeframe (data updates daily)
- Auto-switches between BTC and ETH based on chart
- All other crypto charts default to BTC exchange flow data
## Best Practices
1. **Use on Daily+ Timeframes**
- On-chain data is daily, most effective on D/W/M charts
2. **Combine with Price Action**
- Use as confirmation, not standalone signals
3. **Watch for Divergences**
- Price making new highs while indicator falling = warning
4. **Monitor Extreme Zones**
- Sustained readings >85 or <15 indicate strong conviction
5. **Context Matters**
- Consider broader market conditions and fundamentals
## Calculation
1. **Exchange Net Flow** = Inflows - Outflows (inverted for index)
2. **TVL Rate of Change** = % change over smoothing period
3. **Normalize** both metrics to 0-100 scale
4. **Composite Index** = (ExchangeFlow × Weight) + (TVL × Weight)
5. **Smooth** with moving average
## Disclaimer
This indicator uses on-chain data for analysis. While valuable, it should not be used as the sole basis for trading decisions. Always combine with other technical analysis tools, fundamental analysis, and proper risk management.
On-chain data reflects blockchain activity but may lag price action. Use this indicator as part of a comprehensive trading strategy.
---
## Credits
**Data Sources:**
- IntoTheBlock: Exchange flow metrics
- DefiLlama: Total Value Locked data
**Indicator by:** @iCD_creator
**Version:** 1.0
**Pine Script™ Version:** 6
---
## Updates & Support
For questions, suggestions, or bug reports, please comment below or message the author.
**Like this indicator? Leave a 👍 and share your feedback!**
XAUUSD Multi-Timeframe Bias Scanner🎯 Purpose & Overview
This is a sophisticated trading indicator that analyzes XAUUSD (Gold) across 5 different timeframes simultaneously to determine market bias and trend direction.
⚙️ Core Components
2. Bias Calculation Engine
The heart of the indicator uses 5 technical factors to score each timeframe:
Technical Factors (Weighted):
Moving Average Alignment (30 points)
Bullish: EMA(9) > EMA(21) > EMA(50)
Bearish: EMA(9) < EMA(21) < EMA(50)
Price vs MA Position (20 points)
Score increases when price above MAs
Score decreases when price below MAs
RSI Momentum (20 points)
Bullish: RSI > 60 or > 50
Bearish: RSI < 40 or < 50
MACD Signals (15 points)
Bullish: MACD line > Signal line AND > 0
Bearish: MACD line < Signal line AND < 0
Volume Confirmation (15 points)
Volume spikes with price movement add confirmation
📊 Timeframe Analysis
Five Timeframes Monitored:
5-minute - Short-term noise (10% weight)
15-minute - Intraday direction (15% weight)
1-hour - Key intraday bias (25% weight)
4-hour - Primary directional bias (30% weight)
1-day - Overall trend context (20% weight)
Bias Scoring System:
0-100 Scale (50 = Neutral)
STRONG BULLISH: ≥70 (Green)
BULLISH: 55-69 (Lime)
NEUTRAL: 46-54 (Gray)
BEARISH: 31-45 (Orange)
STRONG BEARISH: ≤30 (Red)
🎨 Visual Features
1. Comprehensive Table Display
pinescript
var table biasTable = table.new(position.top_right, 3, 7, ...)
Shows a color-coded table with:
Timeframe name
Numerical bias score (0-100)
Strength description with color coding
2. Chart Visual Indicators
Background coloring based on overall bias
Label markers for strong bullish/bearish conditions
Real-time label showing all timeframe scores
3. Alert System
Triggers when overall bias crosses 70 (bullish) or 30 (bearish)
Configurable with sound options
🔄 How It Processes Data
Data Flow:
Requests security data for each timeframe using request.security()
Calculates technical indicators for each TF separately
Scores each TF based on 5 technical factors
Computes weighted overall bias
Updates visual displays and checks alert conditions
💡 Trading Applications
Bullish Scenarios:
Multiple timeframes show bullish alignment
Higher timeframe bias supports lower timeframe direction
Overall score > 70 indicates strong bullish conviction
Bearish Scenarios:
Multiple timeframes show bearish alignment
Higher timeframe bias confirms lower timeframe moves
Overall score < 30 indicates strong bearish conviction
Conflict Detection:
When timeframes show conflicting biases
Caution required - market may be consolidating
Wait for alignment before taking trades
🎚️ Customization Options
Users can modify:
Timeframe weights
Technical indicator parameters
Alert thresholds
Visual display preferences
Scoring sensitivity
📈 XAUUSD Specific Optimizations
The indicator considers Gold's unique characteristics:
High volatility periods
ATR-based volatility adjustments
Volume confirmation for breakouts
Multiple timeframe confirmation for trend reliability
This creates a powerful tool for identifying high-probability trade setups in XAUUSD by ensuring traders have a complete multi-timeframe perspective before entering positions.
3-EMA Ribbon Scalping System 3-EMA Ribbon Scalping System V2 - Trading Guide
Overview
This indicator combines a triple EMA ribbon with VWAP, RSI, and volume analysis to catch high-probability scalping setups for short pip hunting on highly liquid Forex pairs such as EUR/USD
The Core Strategy
The system waits for three conditions to align before firing a signal:
1. EMA Stack** - The 8/13/21 EMAs must be properly stacked (bullish: 8>13>21, bearish: 8<13<21)
2. VWAP Position** - Price needs to be on the right side of VWAP for the trade direction
3. Pullback Entry** - Price pulls back to test the fast EMA while maintaining the trend structure
When these line up with proper RSI readings and a volume spike, you get your entry signal.
Reading the Signals
LONG Entries
Triggered when:
- EMAs are bullishly stacked (green background)
- Price is above VWAP
- We get a pullback to the 8 EMA that holds
- RSI is between 40-70 (momentum present but not overbought)
- Volume exceeds the 20-period average by 1.2x
SHORT Entries
Mirror opposite conditions:
- Bearish EMA stack (red background)
- Price below VWAP
- Rejection at the 8 EMA
- RSI between 30-60
- Volume confirmation present
Risk Management Built In (freely adjustable to match your own approach when it comes to taking risk)
Each signal automatically calculates:
- Stop Loss: 1x ATR from entry
- Target 1: 1:1 risk/reward ratio
- *arget 2: 2:1 risk/reward ratio
You can display these as lines or labels, or turn them off entirely if you prefer your own levels.
Quick Setup Tips
Start with the default settings - they work well on most timeframes from 1-minute to 1-hour charts. The sweet spot for scalping is typically the 3-minute or 5-minute timeframe.
The info panel in the top right gives you a quick market snapshot without cluttering your chart:
- Trend direction
- VWAP position
- RSI value
- Volume status
- Current signal state
If you're getting too many signals, increase the "Min Bars Between Signals" to filter out choppy action. For cleaner charts during analysis, you can toggle off individual components like the ribbon, backgrounds, or signals.
Tips for Live Trading
1. Don't chase - Wait for price to come to the 8 EMA, not the other way around
2. Volume matters - That volume spike filter catches the moves with real momentum behind them
3. Respect the trend - The EMA stack keeps you trading with the flow, not against it
4. Use multiple timeframes - Check a higher timeframe for overall bias before taking signals
The indicator includes alerts that fire with exact entry, stop, and target levels - perfect for quick execution or logging trades.
Remember, this is a scalping system designed for active trading. It works best in trending markets with good volatility. During ranging or low-volume periods, consider sitting on your hands or reducing position size. Trade at your own risk, I created this solely for educational purposes!
Customization Options
Display Settings
- Show/hide EMA ribbon
- Toggle entry signals
- Background colors with adjustable opacity
- Info panel size options
- VWAP visibility
Technical Parameters
- EMA Settings: Adjustable lengths for fast (8), medium (13), and slow (21) EMAs
- RSI Settings: Customizable overbought/oversold levels and momentum thresholds
- Volume Settings: Multiplier for volume confirmation and MA length
- Risk Management: ATR multiplier for stops, customizable R:R ratios
Nearly everything is adjustable, but the defaults are solid. Focus on reading the market structure first before tweaking settings.
Visual Features
Background Colors
- Green: Bullish trend (EMAs stacked bullishly)
- Red: Bearish trend (EMAs stacked bearishly)
- Gray: Neutral/choppy conditions
Signal Styles
Choose between:
- Text labels
- Arrow markers
- Both combined
Stop Loss & Take Profit Display
Three modes available:
- None: No SL/TP visualization
- Current: Shows lines for active trade
- Labels: Displays small labels at price levels
Best Markets & Timeframes
Optimal Markets:
- Forex pairs (especially majors)
- Stock indices
- Liquid cryptocurrencies
- High-volume stocks
Alert System
Comprehensive alerts include:
- Entry signal notification
- Exact entry price
- Stop loss level with pip distance
- Take profit levels with pip distances
- Trade direction and symbol
Important Notes
- This is a "momentum-based scalping system" - not suitable for ranging markets
- Best results come from pairing with your understanding of key levels and market context
- The volume filter helps avoid false signals during low-liquidity periods
- Consider overall market conditions and news events before trading
Version Info
3-EMA Ribbon Scalping System
- Refined entry logic
- Improved visual clarity
- Enhanced risk management tools
- Optimized performance tracking
Mancini Levels (with alerts, majors only option)This indicator displays Support and Resistance levels on ES or MES (E-mini and Micro E-mini S&P 500 Index Futures) charts by parsing text copied and pasted by the user.
(The levels displayed on the chart above are not valid, they are for illustration only)
Features
Option to display only the major levels
The chart on the left displays both major and minor levels, distinguished by color and line style. The chart on the right shows only the major levels; minor levels are disabled:
Alert function for when the price approaches a major level or zone (within a customizable distance).
The script provides a trigger for alerts. When creating an alert, you can then choose your desired frequency (Only once/Once per bar/Once per bar close/Once per minute) from the TradingView alert pop-up.
The alert message contains the current price and the approached major level price.
Customizable Lookback Period
Set how many days into the past the lines should appear (Subject to a maximum of 5000 bars).
To display lines for the current day only, set this value to 1.
Functions only on ES or MES (E-mini and Micro E-mini S&P 500 Index Futures) charts, as the text format is intended for these instruments.
How to Use
Copy and paste the support and resistance levels into the indicator's "Supports" and "Resistances" input fields.
Format Example:
For the "Supports" input: 6772-6770 (major), 6764 (major), 6757, 6751-54
For the "Resistances" input: 6799 (major), 6814, 6828-30, 6839-40 (major)
The indicator supports the display of zone levels in multiple formats
(e.g., 6235-45 and 6235-6245 and 6245-6235 are all valid).
For hundred- or thousand-point rollovers, please use only the full number format: 5995-6005.
The indicator includes an error-checking system to help you troubleshoot common setup issues.
An on-chart error label will be displayed on the chart if:
The chart instrument is not ES or MES.
The "Supports" and "Resistances" fields are both empty.
A data formatting error is detected (e.g., non-numeric characters, incomplete zones, etc.).
How It Works
For optimal resource efficiency and performance, the script executes all computationally intensive tasks only once, on the very first bar when the chart loads (if barstate.isfirst).
One-time Parsing: The parsing, splitting, and conversion of the text (string) formatted levels, which are provided in the settings, occurs only once.
Persistent Objects: The lines (line.new), fills (linefill.new), and price labels (label.new) that mark the levels are all persistent graphical objects. The script creates these on the first bar and stores their references in arrays declared with the var keyword.
No Redrawing: On subsequent bars, the indicator does not delete and redraw these objects. It merely updates the x-axis position of the existing lines and labels (line.set_x1, line.set_x2, label.set_x) on the last bar (if barstate.islast), ensuring they always remain on the right edge of the chart, following the formation of new bars.
By default, TradingView charts have a limit of 50 lines and 50 labels. Given that the number of levels often exceeds this, the script's drawing logic is as follows:
The number of displayable lines and labels has been increased (to 500) in the indicator's declaration line.
The script applies a prioritized order when drawing levels and labels. Major levels have priority over minor levels during drawing.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice.
Trading involves substantial risk of loss and is not suitable for every investor. Past performance shown in examples is not indicative of future results.
The indicator provides signals and calculations, but trading decisions are solely your responsibility. Always:
Test strategies on paper before using real money
Never risk more than you can afford to lose
Understand that all trading involves risk
Consider seeking advice from a licensed financial advisor
The publisher makes no guarantees regarding accuracy, profitability, or performance. Use at your own risk.






















