Line breakI decided to help TradingView programmers and wrote code that converts a standard candles / bars to a line break chart. The built-in linebreak() and security() functions for constructing a Linear Break chart are bad, the chart is not built correctly, and does not correspond to the Line Breakout chart built into TradingView. I’m talking about simulating the Linear Break lines using the plotcandle() annotation, because these are the same candles without shadows. When you try to use the market simulator, when the gaps are turned on in the security() function, nothing is added to the chart, and when turned off, a completely different line break chart is drawn. Do not try to write strategies based on the built-in linebreak() function! The developers write in the manual: "Please note that you cannot plot Line Break boxes from Pine script exactly as they look. You can only get a series of numbers similar to OHLC values for Line Break charts and use them in your algorithms." However, it is possible to build a “Linear Breakthrough” chart exactly like the “Linear Breakthrough" chart built into TradingView. Personally, I had enough Pine Script functionality.
For a complete understanding of how such a graph is built, you can refer to Steve Nison's book “BEYOND JAPANESE CANDLES” and see the instructions for creating a “Three-Line Breakthrough” chart (the number of lines for a breakthrough is three):
Rule 1: if today's price is above the base price (closing the first candle), draw a white line from the base price to the new maximum price (before closing).
or Rule 2: if today's price is below the base price, draw a black line from the base price to the new low of prices (before closing).
Rule 3: if today's price is no different from the base, do not draw any line.
Rule 4: if today's price rises above the maximum of the first line, shift to the column to the right and draw a new white line from the previous maximum to the new maximum of prices.
Rule 5: if the price is below the low of the first line, move one column to the right and draw a new black line down from the previous low to the new low of prices.
Rule 6: if the price is kept in the range of the first line, nothing is applied to the chart.
Rule 7: if the market reaches a new maximum, surpassing the maximum of previous lines, move to the column to the right and draw a new white line up to a new maximum.
Rule 8: if today's price is below the low of previous lines (i.e. there is a new low), move to the right column and draw a new black line down to a new low.
Rule 9: if the price is in the range of the first two lines, nothing is applied to the chart.
Rule 10: if there is a series of three white lines, a new white line is drawn when a new maximum is reached (even if it is only one tick higher than the old one). Under the same conditions, for drawing a black reversal line, the price should fall below the minimum of the series of the last three white lines. Such a black line is called a black reversal line. It runs from the base of the highest white line to a new low of price.
Rule 11: if there is a series of three black lines, a new black line is drawn when a new minimum is reached. Under the same conditions, for drawing a white line, called a white reversal line, the price must exceed the maximum of the previous three black lines. This line is drawn from the top of the lowest black line to a new high of the price.
So, the script was not small, but the idea is extremely simple: if you need to break n lines to build a line, then among these n lines (or less, if this is the beginning of the chart), the maximum or minimum of closures and openings will be searched. If the current candles closed above or below these highs or lows, then a new line is added to the chart on the current candles (trend or breakout). According to my observations, this script draws a chart that is completely identical to the Line Breakout chart built into TradingView, but of course with gaps, as there is time in the candles / bar chart. I stuffed all the logic into a wrapper in the form of the get_linebreak() function, which returns a tuple of OHLC values. And these series with the help of the plotcandle() annotation can be converted to the "Linear Breakthrough" chart. I also want to note that with a large number of candles on the chart, outrages about the buffer size uncertainty are heard from the TradingView black box. Because of this, in the annotation study() set the value to the max_bars_back parameter.
In general, use it (for example, to write strategies)!
Recherche dans les scripts pour "algo"
REVEREVE is abbreviation from Range Extension Volume Expansion. This indicator shows these against a background of momentum. The histogram and columns for the range and volume rises ara calculated with the same algorithm as I use in the Volume Range Events indicator, which I published before. Because this algorithm uses the same special function to assess 'normal' levels for volume and range and uses the same calculation for depicting the rises on a scale of zero through 100, it becomes possible to compare volume and range rises in the same chart panel and come to meaningful conclusions. Different from VolumeRangeEvents is that I don't attempt to show direction of the bars and columns by actually pointing up or down. However I did color the bars for range events according to direction if Close jumps more than 20 percent of ATR up or down either blue or red. If the wider range leads to nothing, i.e. a smaller jump than 20 percent, the color is black. You can teak this in the inputs. The volume colums ar colored according to two criteria, resulting in four colors (orange, blue, maroon, green). The first criterium is whether the expansion is climactic (orange, blue) or moderate (maroon, green). I assume that climactic (i.e. more than twice as much) volume marks the beginning or end of a trend. The second criterium looks at the range event that goes together with the volume event. If lots of volume lead to little change in range (blue, green), I assume that this volume originates from institutional traders who are accumulating or distributing. If wild price jumps occur with comparatively little volume (orange, maroon, or even no volume event) I assume that opportunistic are active, some times attributing to more volume.
For the background I use the same colors calculated with the same algorithm as in the Hull Agreement Indicator, which I published before. This way I try to predict trend changes by observation of REVE.
T3 ICL MACD STRATEGY
Backtested manually and received approx 60% winrate. Tradingview strategy tester is skewed because this program does not specify when to sell at profit target or at a stop loss.
Uses 1 min for entry and a longer time frame for confirmation (5,10,15, etc..) (Not sure what the yellow arrows are in the picture but they can be ignored)
Ideal Long Entry - The algo uses T3 moving average (T3) and the Ichimoku Conversion Line (ICL) to determine when to enter a long or short position. In this case we are going to showcase what causes the algo to alert long. It first checks to see if the the ICL is greater than T3. Once that condition is met T3 must be green in order to enter long and finally the last closing price has to be greater than the ICL. You can use the MACD to further verify a long trend as well!
Ideal Short Entry - The algo uses T3 moving average (T3) and the Ichimoku Conversion Line (ICL) to determine when to enter a long or short position. In this case we are going to showcase what causes the algo to alert short. It first checks to see if the the ICL is less than T3. Once that condition is met T3 must be red in order to enter short and finally the last closing price has to be less than the ICL. You can use the MACD to further verify a long trend as well!
[PX] Moon PhaseHello guys,
while scrolling through the public library, I was surprised that there was no Open-Source version of the Moon Phase indicator. All moon phase indicators in the public library were either protected or not exactly what I was looking for. There is a built-in "Moon Phase" indicator, but even for this one, we can't access its source code.
Therefore, I started searching for an algorithm that I could implement into PineScript.
So here we go, an Open-Source Moon Phase indicator. It comes with the option to color the background based on the recent moon. Compared to the built-in indicator, the moon is slightly shifted, because it is centered on the candle and not plotted between two candles like the built-in indicator is doing it.
Feel free to use the indicator for your analysis or build on top of it in an open-source fashion.
Happy trading,
paaax :)
Reference: This indicator is a converted and simplified version of the original javascript algorithm, which can be found here .
SMU Quantum Thermo BallsThis script is the enhanced version of Market Thermometer with one difference. This one has Quantum Thermo balls shooting out of the thermometer tube when overheated. Quantum psychology, Quantum observation, call it what you like
My scripts are designed to beat ALGO, so the behavior of indicators is not like traditional indicators. Don't try to overthink it and compare it to other established functions.
If you knew ALGo as much as I do, then you would also ditch old indicators and design your own weird scripts to match the ALGO's personality. Oh yes, each AlGo for each stock has its own programming personality. Most my scripts are tuned to beat SPX ALGO meniac
Enjoy and think outside the box, the only way to beat the ALGO
BERLIN Renegade - Baseline & RangeThis is the baseline and range candles part of a larger algorithm called the "BERLIN Renegade". It is based on the NNFX way of trading, with some modifications.
The baseline is used for price crossover signals, and consists of the LSMA. When price is below the baseline, the background turns red, and when it is above the baseline, the background turns green.
It also includes a modified version of the Range Identifier by LazyBear. This version calculates the same, but draws differently. It remove the baseline signal color if the Range Identifier signals there is a possible trading range forming.
The main way of identifying ranges is using the BERLIN Range Index. A panel version of this indicator is included in another part of the algorithm, but the bar color version is included here, to make the ranges even more visible and easier to avoid.
Low Frequency Fourier TransformThis Study uses the Real Discrete Fourier Transform algorithm to generate 3 sinusoids possibly indicative of future price.
I got information about this RDFT algorithm from "The Scientist and Engineer's Guide to Digital Signal Processing" By Steven W. Smith, Ph.D.
It has not been tested thoroughly yet, but it seems that that the RDFT isn't suited for predicting prices as the Frequency Domain Representation shows that the signal is similar to white noise, showing no significant peaks, indicative of very low periodicity of price movements.
Correlation MATRIX (Flexible version)Hey folks
A quick unrelated but interesting foreword
Hope you're all good and well and tanned
Me? I'm preparing the opening of my website where we're going to offer the Algorithm Builder Single Trend, Multiple Trends, Multi-Timeframe and plenty of others across many platforms (TradingView, FXCM, MT4, PRT). While others are at the beach and tanning (Yes I'm jealous, so what !?!), we're working our a** off to deliver an amazing looking website and great indicators and strategies for you guys.
Today I worked in including the Trade Manager Pro version and the Risk/Reward Pro version into all our Algorithm Builders. Here's a teaser
We're going to have a few indicators/strategies packages and subscriptions will open very soon.
The website should open in a few weeks and we still have loads to do ... (#no #summer #holidays #for #dave)
I see every message asking me to allow access to my Algorithm Builders but with the website opening shortly, it will be better for me to manage the trials from there - otherwise, it's duplicated and I can't follow all those requests
As you can probably all understand, it becomes very challenging to publish once a day with all that workload so I'll probably slow down (just a bit) and maybe posting once every 2/3 days until the website will be over (please forgive me for failing you). But once it will open, the daily publishing will resume again :) (here's when you're supposed to be clapping guys....)
While I'm so honored by all the likes, private messages and comments encouraging me, you have to realize that a script always takes me about 2/3 hours of work (with research, coding, debugging) but I'm doing it because I like it. Only pushing the brake a bit because of other constraints
INDICATOR OF THE DAY
I made a more flexible version of my Correlation Matrix .
You can now select the symbols you want and the matrix will update automatically !!! Let me repeat it once more because this is very cool... You can now select the symbols you want and the matrix will update automatically :)
Actually, I have nothing more to say about it... that's all :) Ah yes, I added a condition to detect negative correlation and they're being flagged with a black dot
Definition : Negative correlation or inverse correlation is a relationship between two variables whereby they move in opposite directions.
A negative correlation is a key concept in portfolio construction, as it enables the creation of diversified portfolios that can better withstand portfolio volatility and smooth out returns.
Correlation between two variables can vary widely over time. Stocks and bonds generally have a negative correlation, but in the decade to 2018, their correlation has ranged from -0.8 to 0.2. (Source : www.investopedia.com
See you maybe tomorrow or in a few days for another script/idea.
Be sure to hit the thumbs up to cheer me up as your likes will be the only sunlight I'll get for the next weeks.... because working on building a great offer for you guys.
Dave
____________________________________________________________
- I'm an officially approved PineEditor/LUA/MT4 approved mentor on codementor. You can request a coaching with me if you want and I'll teach you how to build kick-ass indicators and strategies
Jump on a 1 to 1 coaching with me
- You can also hire for a custom dev of your indicator/strategy/bot/chrome extension/python
SMA/pivot/Bollinger/MACD/RSI en pantalla gráficoMulti-indicador con los indicadores que empleo más pero sin añadir ventanas abajo.
Contiene:
Cruce de 3 medias móviles
La idea es no tenerlas en pantalla, pero están dibujadas también. Yo las dejo ocultas salvo que las quiera mirar para algo.
Lo que presento en pantalla es la media lenta con verde si el cruce de las 3 marca alcista, amarillo si no está claro y rojo si marca bajista.
Pivot
Normalmente los tengo ocultos pero los muestro cuando me interesa. Están todos aunque aparezcan 2 seguidos.
Bandas de Bollinger
No dibujo la línea central porque empleo la media como tal.
Parabollic SAR
Lo empleo para dibujar las ondas de Elliott como postula Matías Menéndez Larre en el capítulo 11 de su libro "Las ondas de Elliott". Así que, aunque se puede mostrar, lo mantengo oculto y lo que muestro es dónde cambia (SAR cambio).
MACD
No está dibujado porque necesitaría sacarlo del gráfico.
Marco en la parte superior cuándo la señal sobrepasa al MACD hacia arriba o hacia abajo con un flecha indicando el sentido de esta señal.
RSI
Similar al MACD pero en la parte inferior.
Probablemente, programe otro indicador para visualizar en una ventanita MACD, RSI y volumen todo junto. El volumen en la principal hay veces que no te permite ver bien alguna sombra y los otros 2 te quitan mucho espacio para graficar si los tienes permanentemente en 2 ventanas separadas.
DFT - Dominant Cycle Period 8-50 bars - John EhlerThis is the translation of discret cosine tranform (DCT) usage by John Ehler for finding dominant cycle period (DC).
The price is first filtered to remove aliasing noise(bellow 8 bars) and trend informations(above 50 bars), then the power is computed.
The trick here is to use a normalisation against the maximum power in order to get a good frequency resolution.
Current limitation in tradingview does not allow to display all of the periods, still the DC period is plot after beeing computed based on the center of gravity algo.
The DC period can be used to tune all of the indicators based on the cycles of the markets. For instance one can use this (DC period)/2 as an input for RSI.
Hope you find this of some interrest.
[naoligo] Simple ADXI'm publishing this indicator just for study purposes, because the result is exactly the same as DMI without the smoothing factor. It is exactly the same as ADX Wilder from MT5.
I was looking for the algorithm all over and it was a pain to find the right formula, meaning: one that would match with the built-in ones. After several study and comparison, I still didn't find the algorithm that match with the MT5's built-in simple ADX ...
Enjoy!
Patrones de entrada/salida V.1.0 -BETA-Este algoritmo intenta identificar patrones o fractales dentro de los movimientos de precios para dar señales de compra o venta de activos.
Zero Lag MACD Enhanced - Version 1.1ENHANCED ZERO LAG MACD
Version 1.1
Based on ZeroLag EMA - see Technical Analysis of Stocks and Commodities, April 2000
Original version by user Glaz. Thanks !
Ideas and code from @yassotreyo version.
Tweaked by Albert Callisto (AC)
New features:
Added original signal line formula
Added optional EMA on MACD
Added filling between the MACD and signal line
I looked at other versions of the zero lag and noticed that the histogram was slightly different. After looking at other zero lags on TV, I noticed that the algorithm implementation of Glanz generated a modified signal line. I decided to add the old version to be compliant with the original algorithm that you will find in other platforms like MT4, FXCM, etc.
So now you can choose if you want the original algorithm or Glanz version. It's up to you then to choose which one you prefer. I also added an extra EMA applied on the MACD. This is used in a system I am currently studying and can be of some interest to filter out false signals.
Acc/Dist. Cloud with Fractal Deviation Bands by @XeL_ArjonaACCUMULATION / DISTRIBUTION CLOUD with MORPHIC DEVIATION BANDS
Ver. 2.0.beta.23:08:2015
by Ricardo M. Arjona @XeL_Arjona
DISCLAIMER
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The embedded code and ideas within this work are FREELY AND PUBLICLY available on the Web for NON LUCRATIVE ACTIVITIES and must remain as is.
Pine Script code MOD's and adaptations by @XeL_Arjona with special mention in regard of:
Buy (Bull) and Sell (Bear) "Power Balance Algorithm by Vadim Gimelfarb published at Stocks & Commodities V. 21:10 (68-72).
Custom Weighting Coefficient for Exponential Moving Average (nEMA) adaptation work by @XeL_Arjona with contribution help from @RicardoSantos at TradingView @pinescript chat room.
Morphic Numbers (PHI & Plastic) Pine Script adaptation from it's algebraic generation formulas by @XeL_Arjona
Fractal Deviation Bands idea by @XeL_Arjona
CHANGE LOG:
ACCUMULATION / DISTRIBUTION CLOUD: I decided to change it's name from the Buy to Sell Pressure. The code is essentially the same as older versions and they are the center core (VORTEX?) of all derived New stuff which are:
MORPHIC NUMBERS: The "Golden Ratio" expressed by the result of the constant "PHI" and the newer and same in characteristics "Plastic Number" expressed as "PN". For more information about this regard take a look at: HERE!
CUSTOM(K) EXPONENTIAL MOVING AVERAGE: Some code has cleaned from last version to include as custom function the nEMA , which use an additional input (K) to customise the way the "exponentially" is weighted from the custom array. For the purpose of this indicator, I implement a volatility algorithm using the Average True Range of last 9 periods multiplied by the morphic number used in the fractal study. (Golden Ratio as default) The result is very similar in response to classic EMA but tend to accelerate or decelerate much more responsive with wider bars presented in trending average.
FRACTAL DEVIATION BANDS: The main idea is based on the so useful Standard Deviation process to create Bands in favor of a multiplier (As John Bollinger used in it's own bands) from a custom array, in which for this case is the "Volume Pressure Moving Average" as the main Vortex for the "Fractallitly", so then apply as many "Child bands" using the older one as the new calculation array using the same morphic constant as multiplier (Like Fibonacci but with other approach rather than %ratios). Results are AWSOME! Market tend to accelerate or decelerate their Trend in favor of a Fractal approach. This bands try to catch them, so please experiment and feedback me your own observations.
EXTERNAL TICKER FOR VOLUME DATA: I Added a way to input volume data for this kind of study from external tickers. This is just a quicky-hack given that currently TradingView is not adding Volume to their Indexes so; maybe this is temporary by now. It seems that this part of the code is conflicting with intraday timeframes, so You are advised.
This CODE is versioned as BETA FOR TESTING PROPOSES. By now TradingView Admins are changing lot's of things internally, so maybe this could conflict with correct rendering of this study with special tickers or timeframes. I will try to code by itself just the core parts of this study in order to use them at discretion in other areas. ALL NEW IDEAS OR MODIFICATIONS to these indicator(s) are Welcome in favor to deploy a better and more accurate readings. I will be very glad to be notified at Twitter or TradingView accounts at: @XeL_Arjona
AlphaStrike: Zen ModeDescription:
1. The Philosophy: Reducing Cognitive Load Modern charts are often cluttered with dozens of noisy lines (Bollinger Bands, Moving Averages, Oscillators) that lead to "Analysis Paralysis." This script is designed with a "Zen" philosophy: P rocess the complexity in the background, but display only the decision.
This is not a simple indicator overlay. It is a Risk-Based Trading Engine that runs multiple validation checks (Momentum, Volatility, and Price Action) simultaneously but hides the underlying calculations to keep the chart clean. It focuses the trader's attention on the two things that matter most: Trend Direction and Position Sizing.
2. The "Invisible" Technical Engine The script operates on a Dual-State Logic system that adapts to market conditions. It uses standard indicators as filters, not just visuals.
A. Trend State (The Backbone) The script calculates a volatility-adjusted Trend Baseline (SuperTrend).
Green State: The market is in a markup phase. The script looks for continuation.
Red State: The market is in a markdown phase. The script looks for defense.
B. The "Confluence" Reversal Logic Instead of cluttering the screen with Bollinger Bands and RSI windows, the script performs these checks internally:
Condition 1 (Volatility): Is price extending beyond the 2.0 Standard Deviation (Bollinger Lower/Upper)?
Condition 2 (Momentum): Is RSI overextended (<35 or >65)?
Condition 3 (Price Action): Is there a specific Pin Bar candle pattern (Long wick rejection)?
Result: Only when all three conditions align does the script print a "Reversal Circle." This filters out weak signals that usually occur in strong trends.
3. The Risk Management Calculator (Key Feature) Most traders fail not because of bad entries, but because of inconsistent sizing. This script features a built-in Dynamic Position Sizing Dashboard located in the bottom right.
Adaptive Stop Loss:
In a Trend: The Stop Loss is automatically set to the Trend Line (SuperTrend).
In a Reversal: The script internally scans for the nearest Swing Low/High (using hidden Pivot calculations) and sets the Stop Loss there.
Position Sizing Math: The dashboard reads your Account Size and Risk % inputs. It instantly calculates the "Max Size" (contract/share amount) allowed for the current trade.
Formula: Position Size = (Account Value * Risk %) / Distance to Stop.
Benefit: This ensures you risk the exact same dollar amount on every trade, whether the stop loss is 1% away or 10% away.
4. How to Read the Signals
Triangles (Breakouts): These represent a shift in the dominant trend direction.
Green Triangle: Bullish Trend Start.
Red Triangle: Bearish Trend Start.
Circles (Mean Reversion): These are high-probability counter-trend plays.
Blue Circle: Buy Reversal (Oversold + Pinbar + Bollinger Support).
Orange Circle: Sell Reversal (Overbought + Pinbar + Bollinger Resistance).
5. Settings
Trend Settings: Adjust the ATR Period and Factor to change the sensitivity of the trend line.
Reversal Settings: Tweak the RSI and Bollinger thresholds to filter out more/less signals.
Risk Management: Input your total Account Size and desired Risk Per Trade (e.g., 1%) to calibrate the Dashboard.
Disclaimer This tool provides algorithmic analysis and risk calculations. It does not guarantee profits or provide financial advice. Always verify position sizes before executing.
TREND FLOW CANDLES - [EntryLab]Trend Flow Candles was created for the community to clearly visualize the flow of trend on any token. It provides a simple, clean, and visually pleasing way to identify overall trend bias at a glance. Using proprietary algorithmic logic developed specifically to assist traders, the candles dynamically reflect trend strength and direction to help with higher-timeframe confluence.
This indicator has been back-tested with strong accuracy and is designed to be easy to use, quick to set up, and practical in real trading conditions. Trend Flow Candles works best as a directional bias tool, helping traders stay aligned with the dominant trend while making clearer, more confident decisions. It is a powerful addition to any indicator arsenal when you need reliable trend context without clutter.
Regards,
ENTRYLAB
Dip Buy/Sell Signals (Vix Fix + MA Deviation + TRMAD) [DotGain]Dip Buy/Sell Signals (Vix Fix + MA Deviation + TRMAD)
This indicator combines three proven market stress and mean-reversion components to identify potential buy and sell opportunities during extended market conditions.
────────────────────
📌 Included Components
1️⃣ Volatility-Based Stress Filter (Vix Fix)
Detects short-term market panic using relative price movement.
Signals are generated only during periods of elevated volatility or market stress.
2️⃣ Moving Average Deviation (MA Deviation)
Identifies overbought and oversold conditions based on the percentage deviation from a selected moving average.
Supported MA types:
• EMA
• SMA
• RMA
• VWMA
• WMA
• TEMA
3️⃣ TRMAD (True Range Mean Absolute Deviation)
Measures the distance of price from its mean relative to current volatility.
Useful for filtering extreme price moves and reducing false signals.
────────────────────
📈 Trading Signals
Buy Signal:
• Elevated market volatility
• Price significantly below the moving average
• TRMAD below the defined threshold
Sell Signal:
• Elevated market volatility
• Price significantly above the moving average
• TRMAD above the defined threshold
Signals are visualized directly on the chart:
• Buy: green label below the candle
• Sell: red label above the candle
────────────────────
⚙️ Settings & Customization
All components are fully adjustable:
• Lookback periods
• Moving average types and lengths
• Volatility and threshold levels
This makes the indicator suitable for:
• Intraday trading
• Swing trading
• Crypto, Forex, indices, and equities
────────────────────
Disclaimer
This "Dip Buy/Sell Signals (Vix Fix + MA Deviation + TRMAD)" (DipSig) 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") 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.
4 Bar Sequential Counter (9 to 13) [DotGain]4-Bar Sequential Counter (Seq4)
This indicator identifies potential trend exhaustion phases using a strict sequential count
based on the relationship between the current closing price and the closing price four bars earlier.
How it works
• A bullish sequence is counted as long as the current close remains below the close from 4 bars ago.
• A bearish sequence is counted as long as the current close remains above the close from 4 bars ago.
• The count resets immediately if the respective condition is no longer met.
• The sequence counts up to a maximum of 13 , after which it resets and a new sequence may begin.
Visualization
• Only counts from 9 to 13 are displayed on the chart.
• Bullish sequences are plotted below price bars.
• Bearish sequences are plotted above price bars.
• The minimalist design keeps the chart clean and focused on potentially relevant exhaustion zones.
Interpretation
• A count of 9 may indicate an early sign of market overextension.
• A count of 13 represents a more advanced sequence and a higher probability
of consolidation or corrective price action.
• This indicator is not a standalone trading system and should be used in combination
with trend analysis, volume, and support/resistance levels.
Alerts
• Bullish sequence at 9
• Bullish sequence at 13
• Bearish sequence at 9
• Bearish sequence at 13
Disclaimer
This "4-Bar Sequential Counter (9–13)" (Seq4) indicator is provided for informational and educational purposes only. It does not, and should not be construed as, financial, investment, or trading advice.
This indicator is an independent implementation of a sequential counting method and is not affiliated with, or endorsed by any trademarked trading concepts or methodologies.
The signals generated by this tool (Green and Red) 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 a substantial risk of loss. You can lose all of your invested capital.
Past performance does not guarantee future results.
This indicator highlights sequential price exhaustion patterns and may generate false, lagging, or incomplete signals. Markets can remain unpredictable longer than you can remain solvent.
The creator DotGain assumes no liability for any financial losses or damages you may incur, directly or indirectly, as a result of using this indicator or the information it provides.
You are solely responsible for your own trading and investment decisions. Always conduct your own research (DYOR), validate signals with other methods, and consider your personal risk tolerance before entering any trade.
RSI & BB Oversold Scalper with MACD Confirmation [DotGain]RSI & BB Oversold Scalper with MACD Confirmation
The RSI & BB Oversold Scalper is a mean reversion / dip-buying indicator designed for traders who want to combine oversold conditions with momentum confirmation .
It uses a multi-step logic: first detect an oversold setup, then wait for a MACD confirmation within a defined time window before issuing a buy signal.
---
Core Concept
1. Detect an oversold setup using Bollinger Bands %b, RSI and an optional DSS filter
2. Keep the setup active for a limited number of candles
3. Trigger the entry using a MACD bullish crossover
4. Reset after entry to avoid multiple signals from the same setup
---
Buy Signal Logic
A buy signal is generated when the following conditions are met:
1. Oversold Setup (filters can be enabled/disabled individually)
• Bollinger Bands %b Oversold (Lookback-based)
The price has traded below the lower Bollinger Band at least once within the last `lookbackBB` candles.
• RSI Oversold (Lookback-based)
The RSI has dropped below 30 at least once within the last `lookbackRSI` candles.
• DSS (Double Smoothed Stochastic) Reversal Filter
A bullish crossover of the DSS line above its signal line while the DSS value is below 20 , indicating a potential momentum reversal from oversold conditions.
Note:
BB %b and RSI are lookback filters , while the DSS condition is a single-bar crossover event .
---
2. MACD Confirmation (Entry Timing)
After the setup becomes active, the indicator waits for a bullish MACD crossover (`MACD line crosses above Signal line`) within a user-defined time window (`validWindow` candles).
If the MACD confirmation occurs within this window, a buy signal is printed.
If the window expires without confirmation, the setup is discarded automatically.
---
Reset Logic
• After a buy signal, the setup is reset immediately
• Only one signal is allowed per setup
• No late entries after the time window expires
---
Inputs & Customization
• Enable or disable BB, RSI and DSS filters individually
• Adjust lookback periods to control how recent oversold conditions must be
• Tune the MACD confirmation window to balance early vs. conservative entries
Smaller windows = faster, more aggressive entries
Larger windows = fewer but more confirmed signals
Recommended Markets & Timeframes
• Cryptocurrencies, Forex, Indices, liquid stocks
• Best suited for 1m – 15m scalping
• Also usable on 15m – 1h for slower mean-reversion trades
Visuals
• Buy signals are displayed as labels below the price candles
Important Notes
• This indicator is a signal and timing tool , not a complete trading system
• Always combine with higher-timeframe trend, support/resistance or volume analysis
• Backtesting and paper trading are strongly recommended
Disclaimer:
This "RSI & BB Oversold Scalper with MACD Confirmation" (Oversold Scalper) indicator is provided for informational and educational purposes only. It does not, and should not be construed as, financial, investment, or trading advice.
The signal generated by this tool (Green) is the result of a specific set of algorithmic conditions. They are not a direct recommendation to buy or sell any asset. The indicator's purpose is to highlight possible weakness in the markets, not to provide infallible trade signals.
All trading and investing in financial markets involves a substantial risk of loss. You can lose all of your invested capital.
Past performance is not indicative of future results. Even an indicator designed to filter out "chop" may produce false, lagging, or losing signals. Markets can remain unpredictable longer than you can remain solvent.
The creator DotGain assumes no liability for any financial losses or damages you may incur, directly or indirectly, as a result of using this indicator or the information it provides.
You are solely responsible for your own trading and investment decisions. Always conduct your own research (DYOR), validate signals with other methods, and consider your personal risk tolerance before entering any trade.
TA Confluence Scanner v2.9 | Mint_Algo📘 TA Confluence Scanner
Introduction
The TA Confluence Scanner is a multi-factor trend system designed to filter market noise and identify high-probability trade setups. By combining adaptive algorithms (KAMA) with Price Action methodologies (SMC, Breakouts, Fractals), this indicator operates on the principle of Confluence : a signal is only valid when multiple independent tools agree on the direction.
Instead of relying on a single lagging indicator (like just MA fast and slow crossover), this script acts as a "Scanner," evaluating the market state through Volatility, Trend Structure, and Equilibrium.
───────────────────────────────────────────────────
Important Note
To make this "Plug & Play," I have included optimized presets in the settings for different timeframes (1m/15m-1h/4h-1D) and trading styles (Scalper, Intraday, Swing, Investor) tested on symbols:
FX:EURUSD
IG:NASDAQ
BITSTAMP:BTCUSD
BINANCE:ETHUSD
CAPITALCOM:US500
OANDA:XAUUSD
NASDAQ:AAPL
NASDAQ:TSLA
BUT default settings already include a good preset which excludes most of the noise and grabs the trend better (fewer entries, but quality is higher).
Check the presets at the bottom 👇
───────────────────────────────────────────────────
Core Features
Adaptive Trend Filter (KAMA): Adjusts to market volatility to distinguish between chop and true trends.
SMC Equilibrium (EQ) Fans: A three-tiered dynamic structure (Fast, Medium, Slow) for trailing stops and targets.
Confluence Counter: Visually displays the strength of a signal (e.g., "Strong 4/6") based on how many factors align.
Re-Entry Logic: Identifies low-risk entry points within an existing trend.
Automated S/R & Breakouts: Detects key pivot levels and structural breaks.
───────────────────────────────────────────────────
Settings & Components Breakdown
1. KAMA (Primary Trend Filter)
The backbone of the system. It calculates the Efficiency Ratio (ER) of price movement.
How it works: If the ER is high (strong trend), KAMA follows price closely. If ER is low (ranging), KAMA flattens out to prevent false signals.
Tuning:
Fast (ER ~100/5/60): For Scalping.
Smooth: Default settings are optimized for a balance between lag and noise reduction.
2. SMC Equilibrium (EQ Structure)
Based on the HL2 formula (High+Low / 2), this creates a "fan" of three lines:
EQ1 (Fast): The aggressive line. Used for early exits or scalping stops.
EQ2 (Medium): The baseline trend structure.
EQ3 (Slow): The major trend container. Used for position trading.
Usage: Use these lines to gauge how far price has deviated from its "fair value."
3. Breakout & Internal Trend
Lookback Period: Defines the range for a valid breakout. A lower lookback (e.g., 10) gives earlier signals but more noise; a higher lookback (e.g., 20-30) confirms significant structural breaks.
Internal Trend: A simplified SMA check to ensure immediate momentum aligns with the macro trend.
4. Signal Strength (The Confluence Meter)
The indicator counts active signals from: KAMA, Internal Trend, S/R, FVG, Breakout, and EQ.
Strong Signal: When the count hits your threshold (e.g., 4/6 ). This suggests a high-probability reversal or breakout.
Medium Signal (Triangles): These appear when the trend is active but not all filters align. These are excellent continuation/re-entry points.
───────────────────────────────────────────────────
How to Trade (Strategy Guide)
🎯 The Entry
Wait for a Strong Signal (Large Label). This confirms that volatility, structure, and momentum have aligned.
Conservative: Wait for the candle to close.
Aggressive: Enter on the breakout of the KAMA line.
🔄 Re-Entry & Continuation
Markets rarely move in a straight line.
Scenario: You missed the initial "Strong" entry, or you took profit and want to re-enter.
The Signal: Look for the small Triangles (Medium signals). These often appear after a pullback when price resumes the main trend.
Logic: If the main KAMA trend is still green/red, but the "Strong" signal isn't firing, a Triangle indicates a safe place to add to a position.
⚠️ Pyramiding & Risk Management (Advanced)
The EQ Lines (Fast/Medium/Slow) are designed for a tiered position management strategy:
Entry: Open position (e.g., 0.03 lots).
First Take Profit: When price extends far beyond EQ1 (Fast) , lock in partial profits.
Trailing Stop: Move your Stop Loss to trace the EQ2 (Medium) line.
Trend Riding: Hold the "Runner" portion of your position until price closes back under EQ3 (Slow) or the KAMA line.
Tip: Use William Fractals (Period 2) to pinpoint exact swing highs/lows for tightening stops.
───────────────────────────────────────────────────
Presets & Optimized Settings
To make this "Plug & Play," I have included optimized presets in the settings for different trading styles.
(If you don't see some parameters, that means they are turned off in trading mode)
⚡ SCALPER (1m - 5m)
KAMA:
ER: 100
Fast Length: 15
Slow Length: 30
FVG:
Size %: 0.01
Trend Detection:
Length: 20
Breakout:
Lookback Period: 10
S/R Detection:
Pivot Length: 10
Tolerance: 0.3
SMC EQ:
Default: 10
EQ1: 10
EQ2 (Main): 30
EQ3: 120
Signal Strength:
Strong: 4
Medium: 3
📊 INTRADAY (15m - 1H)
KAMA:
ER: 100
Fast Length: 5
Slow Length: 30
Trend Detection:
Length: 100
Breakout:
Lookback Period: 30
S/R Detection:
Pivot Length: 20
Tolerance: 0.5
SMC EQ:
Default: 10
EQ1: 10
EQ2 (Main): 40
EQ3: 80
Signal Strength:
Strong: 4
Medium: 3
📈 SWING (4H - 1D)
KAMA:
ER: 30
Fast Length: 4
Slow Length: 30
Trend Detection:
Length: 50
Breakout:
Lookback Period: 20
S/R Detection:
Pivot Length: 30
Tolerance: 0.7
SMC EQ:
Default: 10
EQ1: 10
EQ2: 50
EQ3 (Main): 60
Signal Strength:
Strong: 4
Medium: 3
💼 INVESTOR (4H - 1D+)
KAMA:
ER: 30
Fast Length: 5
Slow Length: 10
Trend Detection:
Length: 100
Breakout:
Lookback Period: 50
S/R Detection:
Pivot Length: 30
Tolerance: 0.7
SMC EQ:
Default: 10
EQ1: 10
EQ2: 50
EQ3 (Main): 100
Signal Strength:
Strong: 4
Medium: 3
───────────────────────────────────────────────────
Notes
FVG (Fair Value Gaps): Optional. Enable if you trade volatile assets like Crypto/Gold where imbalances are common.
Support/Resistance: The built-in Pivot system is optional. Disable it if you prefer drawing your own levels to keep the chart clean.
Recommended Pairing:
For best results, pair this with a momentum oscillator like RSI to detect the range regime of a trend. Or DI+ and DI- (when it crosses over each other, that means the "range of possible" regime change of a trend).
───────────────────────────────────────────────────
Disclaimer:
This tool is for informational purposes only. "Confluence" increases probability but does not guarantee results. Always manage your risk.
PAE - Price Action Essential**PAE - Price Action Essential** indicator.
This system is engineered to provide high-fidelity market structure readings, blending moving average harmony with algorithmic volume analysis at critical turning points.
---
## 1. Indicator Philosophy
**PAE** operates under the **"Signal over Noise"** principle. Its goal is to declutter the chart of visual distractions, highlighting only the areas where true confluence exists between price action and institutional effort (volume).
---
## 2. Moving Average Dynamics & Action Zone
The system utilizes a hierarchy of four moving averages to segment market flow:
### A. The Action Zone (Short-Term)
This is generated via a dynamic shading between the **Fast MA (9)** and the **Base MA (20)**.
* **Configuration:** Allows the user to select the calculation type (EMA, SMA, WMA, HMA) for both averages simultaneously.
* **Fast MA Colors:**
* `#a5d6a7` (Soft Green) during ascending values.
* `#faa1a4` (Soft Red) during descending values.
* **Purpose:** The shaded area acts as a "value band." Pullbacks into this zone during defined trends often offer the highest probability entry opportunities.
### B. Structural MAs (Mid & Long-Term)
These averages are fixed to **SMA** type to maintain stability in trend analysis:
* **Medium SMA (40):** Uses vibrant colors (**#3179f5** Blue / **#ffee58** Yellow) to clearly mark the primary direction of the current swing.
* **Slow SMA (200):** Uses pastel tones (**#90bff9** / **#fff9c4**) and a dotted style to define the long-term institutional bias.
---
## 3. Pivot Analysis with Smart Volume
**PAE** identifies fractals (Highs and Lows) and automatically classifies them based on their **Relative Volume** compared to the previous 20 candles.
### Visual Classification by Color
To ensure rapid interpretation, labels are set to **Tiny** size, with color serving as the primary data indicator:
| Pivot Type | Color | Volume Condition | Interpretation |
| --- | --- | --- | --- |
| **Strength (MAX)** | `#ff001e` (Bright Red) | `> 160%` of Avg | High-conviction resistance. |
| **Strength (MIN)** | `#0fa600` (Bright Green) | `> 160%` of Avg | High-conviction support. |
| **Base (MAX)** | `#f1adad` (Soft Rose) | Between `30%` - `160%` | Standard market structure. |
| **Base (MIN)** | `#bee7c0` (Soft Mint) | Between `30%` - `160%` | Standard market structure. |
| **Noise** | `#ffffff` (White 67% Transp.) | `< 30%` of Avg | Weak pivots or lack of interest. |
---
## 4. Contextual Information (Tooltips)
Every Pivot label is interactive. By hovering the cursor over the triangles, the trader obtains precise data:
* **Price:** Indicates the exact **Closing** value of the candle that triggered the pivot (MAX or Min).
* **Vol:** Displays the exact percentage of relative volume. For example, a value of **200%** confirms that the candle had double the average volume, validating the strength of that support or resistance level.
---
## 5. Recommended Configuration Parameters
* **Left/Right Bars (3):** The ideal balance between early detection and swing confirmation.
* **Strength Factor (1.60):** Filters for movements backed by professional intent.
* **Noise Factor (0.30):** Identifies exhaustion or lack of participation.
---
### Operational Summary
The **PAE** helps traders stop guessing. If the price reaches the **Action Zone** (shading) and coincides with a **Strength Pivot** (bright color), the probability of a reaction in favor of the trend is significantly high. It is a precision tool designed for traders seeking absolute clarity in their decision-making process.
Smart Divergence [Reason Edition]Stop trading divergences "in thin air". Start trading structural confluence.
Most divergence indicators fail for one reason: they signal reversals based solely on oscillator math (RSI vs. Price), ignoring the chart's structure. This leads to costly entries against strong trends.
Smart Divergence solves this by applying an Institutional Context Filter. It does not simply alert you of a divergence; it validates the signal against key market structures ("Walls") and—crucially—tells you exactly why the signal appeared directly on the label.
🚀 How It Works: The "Smart Filter" Logic
This script operates on a strict rule: "No Structure, No Signal."
For a Bullish or Bearish divergence to be valid, price must not only diverge from RSI but also physically touch or react to one of four key structural levels:
BB (Bollinger Bands): Rejection due to volatility extension (2.0 StdDev).
KC (Keltner Channels): Rejection due to average range deviation (1.5 ATR).
Pivots (S1/R1): Rejection at standard daily algorithmic levels.
VWAP: Rejection at the institutional average price (Volume Weighted Average Price).
🏷️ Dynamic "Reason" Labels
This is the core feature of this edition. The label on your chart adapts dynamically to show the specific confluence behind the trade.
Examples you will see:
SMART BULL (BB) → The divergence is valid because price hit the Bollinger Band.
SMART BULL (VWAP) → The divergence is valid because price bounced off the VWAP.
SMART BULL (BB VWAP) → High Probability: Price hit the Bollinger Band AND the VWAP simultaneously.
The Logic: The more "Reasons" (acronyms) appear inside the label, the stronger the structural wall, and the higher the probability of a reversal.
🛠️ Settings & Features
🛡️ Smart Filter (Toggle):
ON (Default): Only shows high-quality signals that occur at Support/Resistance zones.
OFF: Shows all raw technical divergences (standard mode).
Alerts Included: Setup custom alerts for "Smart Bull" (Buys) and "Smart Bear" (Sells).
Zero Repainting: Signals are confirmed upon candle close/pivot confirmation.
📋 How to Trade It
Wait for the Label: Do not guess. Wait for the SMART label to appear.
Check the Reason: Look at the text in parenthesis (...).
Single reason (e.g., KC) is a valid setup.
Cluster reasons (e.g., BB S1 VWAP) represent a "Concrete Wall" and are ideal for aggressive entries.
Context: Works best on Intraday timeframes (1m, 5m, 15m) for scalping, and Daily timeframe for Swing Trading bottoms/tops.
Disclaimer: This tool is for educational purposes and technical analysis assistance. Past performance does not guarantee future results. Manage your risk.
DeeptestDeeptest: Quantitative Backtesting Library for Pine Script
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ OVERVIEW
Deeptest is a Pine Script library that provides quantitative analysis tools for strategy backtesting. It calculates over 100 statistical metrics including risk-adjusted return ratios (Sharpe, Sortino, Calmar), drawdown analysis, Value at Risk (VaR), Conditional VaR, and performs Monte Carlo simulation and Walk-Forward Analysis.
█ WHY THIS LIBRARY MATTERS
Pine Script is a simple yet effective coding language for algorithmic and quantitative trading. Its accessibility enables traders to quickly prototype and test ideas directly within TradingView. However, the built-in strategy tester provides only basic metrics (net profit, win rate, drawdown), which is often insufficient for serious strategy evaluation.
Due to this limitation, many traders migrate to alternative backtesting platforms that offer comprehensive analytics. These platforms require other language programming knowledge, environment setup, and significant time investment—often just to test a simple trading idea.
Deeptest bridges this gap by bringing institutional-level quantitative analytics directly to Pine Script. Traders can now perform sophisticated analysis without leaving TradingView or learning complex external platforms. All calculations are derived from strategy.closedtrades.* , ensuring compatibility with any existing Pine Script strategy.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ ORIGINALITY AND USEFULNESS
This library is original work that adds value to the TradingView community in the following ways:
1. Comprehensive Metric Suite: Implements 112+ statistical calculations in a single library, including advanced metrics not available in TradingView's built-in tester (p-value, Z-score, Skewness, Kurtosis, Risk of Ruin).
2. Monte Carlo Simulation: Implements trade-sequence randomization to stress-test strategy robustness by simulating 1000+ alternative equity curves.
3. Walk-Forward Analysis: Divides historical data into rolling in-sample and out-of-sample windows to detect overfitting by comparing training vs. testing performance.
4. Rolling Window Statistics: Calculates time-varying Sharpe, Sortino, and Expectancy to analyze metric consistency throughout the backtest period.
5. Interactive Table Display: Renders professional-grade tables with color-coded thresholds, tooltips explaining each metric, and period analysis cards for drawdowns/trades.
6. Benchmark Comparison: Automatically fetches S&P 500 data to calculate Alpha, Beta, and R-squared, enabling objective assessment of strategy skill vs. passive investing.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ KEY FEATURES
Performance Metrics
Net Profit, CAGR, Monthly Return, Expectancy
Profit Factor, Payoff Ratio, Sample Size
Compounding Effect Analysis
Risk Metrics
Sharpe Ratio, Sortino Ratio, Calmar Ratio (MAR)
Martin Ratio, Ulcer Index
Max Drawdown, Average Drawdown, Drawdown Duration
Risk of Ruin, R-squared (equity curve linearity)
Statistical Distribution
Value at Risk (VaR 95%), Conditional VaR
Skewness (return asymmetry)
Kurtosis (tail fatness)
Z-Score, p-value (statistical significance testing)
Trade Analysis
Win Rate, Breakeven Rate, Loss Rate
Average Trade Duration, Time in Market
Consecutive Win/Loss Streaks with Expected values
Top/Worst Trades with R-multiple tracking
Advanced Analytics
Monte Carlo Simulation (1000+ iterations)
Walk-Forward Analysis (rolling windows)
Rolling Statistics (time-varying metrics)
Out-of-Sample Testing
Benchmark Comparison
Alpha (excess return vs. benchmark)
Beta (systematic risk correlation)
Buy & Hold comparison
R-squared vs. benchmark
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK START
Basic Usage
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as *
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ METRIC EXPLANATIONS
The Deeptest table displays 23 metrics across the main row, with 23 additional metrics in the complementary row. Each metric includes detailed tooltips accessible by hovering over the value.
Main Row — Performance Metrics (Columns 0-6)
Net Profit — (Final Equity - Initial Capital) / Initial Capital × 100
— >20%: Excellent, >0%: Profitable, <0%: Loss
— Total return percentage over entire backtest period
Payoff Ratio — Average Win / Average Loss
— >1.5: Excellent, >1.0: Good, <1.0: Losses exceed wins
— Average winning trade size relative to average losing trade. Breakeven win rate = 100% / (1 + Payoff)
Sample Size — Count of closed trades
— >=30: Statistically valid, <30: Insufficient data
— Number of completed trades. Includes 95% confidence interval for win rate in tooltip
Profit Factor — Gross Profit / Gross Loss
— >=1.5: Excellent, >1.0: Profitable, <1.0: Losing
— Ratio of total winnings to total losses. Uses absolute values unlike payoff ratio
CAGR — (Final / Initial)^(365.25 / Days) - 1
— >=10%: Excellent, >0%: Positive growth
— Compound Annual Growth Rate - annualized return accounting for compounding
Expectancy — Sum of all returns / Trade count
— >0.20%: Excellent, >0%: Positive edge
— Average return per trade as percentage. Positive expectancy indicates profitable edge
Monthly Return — Net Profit / (Months in test)
— >0%: Profitable month average
— Average monthly return. Geometric monthly also shown in tooltip
Main Row — Trade Statistics (Columns 7-14)
Avg Duration — Average time in position per trade
— Mean holding period from entry to exit. Influenced by timeframe and trading style
Max CW — Longest consecutive winning streak
— Maximum consecutive wins. Expected value = ln(trades) / ln(1/winRate)
Max CL — Longest consecutive losing streak
— Maximum consecutive losses. Important for psychological risk tolerance
Win Rate — Wins / Total Trades
— Higher is better
— Percentage of profitable trades. Breakeven win rate shown in tooltip
BE Rate — Breakeven Trades / Total Trades
— Lower is better
— Percentage of trades that broke even (neither profit nor loss)
Loss Rate — Losses / Total Trades
— Lower is better
— Percentage of unprofitable trades. Together with win rate and BE rate, sums to 100%
Frequency — Trades per month
— Trading activity level. Displays intelligently (e.g., "12/mo", "1.5/wk", "3/day")
Exposure — Time in market / Total time × 100
— Lower = less risk
— Percentage of time the strategy had open positions
Main Row — Risk Metrics (Columns 15-22)
Sharpe Ratio — (Return - Rf) / StdDev × sqrt(Periods)
— >=3: Excellent, >=2: Good, >=1: Fair, <1: Poor
— Measures risk-adjusted return using total volatility. Annualized using sqrt(252) for daily
Sortino Ratio — (Return - Rf) / DownsideDev × sqrt(Periods)
— >=2: Excellent, >=1: Good, <1: Needs improvement
— Similar to Sharpe but only penalizes downside volatility. Can be higher than Sharpe
Max DD — (Peak - Trough) / Peak × 100
— <5%: Excellent, 5-15%: Moderate, 15-30%: High, >30%: Severe
— Largest peak-to-trough decline in equity. Critical for risk tolerance and position sizing
RoR — Risk of Ruin probability
— <1%: Excellent, 1-5%: Acceptable, 5-10%: Elevated, >10%: Dangerous
— Probability of losing entire trading account based on win rate and payoff ratio
R² — R-squared of equity curve vs. time
— >=0.95: Excellent, 0.90-0.95: Good, 0.80-0.90: Moderate, <0.80: Erratic
— Coefficient of determination measuring linearity of equity growth
MAR — CAGR / |Max Drawdown|
— Higher is better, negative = bad
— Calmar Ratio. Reward relative to worst-case loss. Negative if max DD exceeds CAGR
CVaR — Average of returns below VaR threshold
— Lower absolute is better
— Conditional Value at Risk (Expected Shortfall). Average loss in worst 5% of outcomes
p-value — Binomial test probability
— <0.05: Significant, 0.05-0.10: Marginal, >0.10: Likely random
— Probability that observed results are due to chance. Low p-value means statistically significant edge
Complementary Row — Extended Metrics
Compounding — (Compounded Return / Total Return) × 100
— Percentage of total profit attributable to compounding (position sizing)
Avg Win — Sum of wins / Win count
— Average profitable trade return in percentage
Avg Trade — Sum of all returns / Total trades
— Same as Expectancy (Column 5). Displayed here for convenience
Avg Loss — Sum of losses / Loss count
— Average unprofitable trade return in percentage (negative value)
Martin Ratio — CAGR / Ulcer Index
— Similar to Calmar but uses Ulcer Index instead of Max DD
Rolling Expectancy — Mean of rolling window expectancies
— Average expectancy calculated across rolling windows. Shows consistency of edge
Avg W Dur — Avg duration of winning trades
— Average time from entry to exit for winning trades only
Max Eq — Highest equity value reached
— Peak equity achieved during backtest
Min Eq — Lowest equity value reached
— Trough equity point. Important for understanding worst-case absolute loss
Buy & Hold — (Close_last / Close_first - 1) × 100
— >0%: Passive profit
— Return of simply buying and holding the asset from backtest start to end
Alpha — Strategy CAGR - Benchmark CAGR
— >0: Has skill (beats benchmark)
— Excess return above passive benchmark. Positive alpha indicates genuine value-added skill
Beta — Covariance(Strategy, Benchmark) / Variance(Benchmark)
— <1: Less volatile than market, >1: More volatile
— Systematic risk correlation with benchmark
Avg L Dur — Avg duration of losing trades
— Average time from entry to exit for losing trades only
Rolling Sharpe/Sortino — Dynamic based on win rate
— >2: Good consistency
— Rolling metric across sliding windows. Shows Sharpe if win rate >50%, Sortino if <=50%
Curr DD — Current drawdown from peak
— Lower is better
— Present drawdown percentage. Zero means at new equity high
DAR — CAGR adjusted for target DD
— Higher is better
— Drawdown-Adjusted Return. DAR^5 = CAGR if max DD = 5%
Kurtosis — Fourth moment / StdDev^4 - 3
— ~0: Normal, >0: Fat tails, <0: Thin tails
— Measures "tailedness" of return distribution (excess kurtosis)
Skewness — Third moment / StdDev^3
— >0: Positive skew (big wins), <0: Negative skew (big losses)
— Return distribution asymmetry
VaR — 5th percentile of returns
— Lower absolute is better
— Value at Risk at 95% confidence. Maximum expected loss in worst 5% of outcomes
Ulcer — sqrt(mean(drawdown^2))
— Lower is better
— Ulcer Index - root mean square of drawdowns. Penalizes both depth AND duration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ MONTE CARLO SIMULATION
Purpose
Monte Carlo simulation tests strategy robustness by randomizing the order of trades while keeping trade returns unchanged. This simulates alternative equity curves to assess outcome variability.
Method
Extract all historical trade returns
Randomly shuffle the sequence (1000+ iterations)
Calculate cumulative equity for each shuffle
Build distribution of final outcomes
Output
The stress test table shows:
Median Outcome: 50th percentile result
5th Percentile: Worst 5% of outcomes
95th Percentile: Best 95% of outcomes
Success Rate: Percentage of simulations that were profitable
Interpretation
If 95% of simulations are profitable: Strategy is robust
If median is far from actual result: High variance/unreliability
If 5th percentile shows large loss: High tail risk
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ WALK-FORWARD ANALYSIS
Purpose
Walk-Forward Analysis (WFA) is the gold standard for detecting strategy overfitting. It simulates real-world trading by dividing historical data into rolling "training" (in-sample) and "validation" (out-of-sample) periods. A strategy that performs well on unseen data is more likely to succeed in live trading.
Method
The implementation uses a non-overlapping window approach following AmiBroker's gold standard methodology:
Segment Calculation: Total trades divided into N windows (default: 12), IS = ~75%, OOS = ~25%, Step = OOS length
Window Structure: Each window has IS (training) followed by OOS (validation). Each OOS becomes the next window's IS (rolling forward)
Metrics Calculated: CAGR, Sharpe, Sortino, MaxDD, Win Rate, Expectancy, Profit Factor, Payoff
Aggregation: IS metrics averaged across all IS periods, OOS metrics averaged across all OOS periods
Output
IS CAGR: In-sample annualized return
OOS CAGR: Out-of-sample annualized return ( THE key metric )
IS/OOS Sharpe: In/out-of-sample risk-adjusted return
Success Rate: % of OOS windows that were profitable
Interpretation
Robust: IS/OOS CAGR gap <20%, OOS Success Rate >80%
Some Overfitting: CAGR gap 20-50%, Success Rate 50-80%
Severe Overfitting: CAGR gap >50%, Success Rate <50%
Key Principles:
OOS is what matters — Only OOS predicts live performance
Consistency > Magnitude — 10% IS / 9% OOS beats 30% IS / 5% OOS
Window count — More windows = more reliable validation
Non-overlapping OOS — Prevents data leakage
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ TABLE DISPLAY
Main Table — Organized into three sections:
Performance Metrics (Cols 0-6): Net Profit, Payoff, Sample Size, Profit Factor, CAGR, Expectancy, Monthly
Trade Statistics (Cols 7-14): Avg Duration, Max CW, Max CL, Win, BE, Loss, Frequency, Exposure
Risk Metrics (Cols 15-22): Sharpe, Sortino, Max DD, RoR, R², MAR, CVaR, p-value
Color Coding
🟢 Green: Excellent performance
🟠 Orange: Acceptable performance
⚪ Gray: Neutral / Fair
🔴 Red: Poor performance
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ IMPLEMENTATION NOTES
Data Source: All metrics calculated from strategy.closedtrades , ensuring compatibility with any Pine Script strategy
Calculation Timing: All calculations occur on barstate.islastconfirmedhistory to optimize performance
Limitations: Requires at least 1 closed trade for basic metrics, 30+ trades for reliable statistical analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK NOTES
➙ This library has been developed and refined over two years of real-world strategy testing. Every calculation has been validated against industry-standard quantitative finance references.
➙ The entire codebase is thoroughly documented inline. If you are curious about how a metric is calculated or want to understand the implementation details, dive into the source code -- it is written to be read and learned from.
➙ This description focuses on usage and concepts rather than exhaustively listing every exported type and function. The library source code is thoroughly documented inline -- explore it to understand implementation details and internal logic.
➙ All calculations execute on barstate.islastconfirmedhistory to minimize runtime overhead. The library is designed for efficiency without sacrificing accuracy.
➙ Beyond analysis, this library serves as a learning resource. Study the source code to understand quantitative finance concepts, Pine Script advanced techniques, and proper statistical methodology.
➙ Metrics are their own not binary good/bad indicators. A high Sharpe ratio with low sample size is misleading. A deep drawdown during a market crash may be acceptable. Study each function and metric individually -- evaluate your strategy contextually, not by threshold alone.
➙ All strategies face alpha decay over time. Instead of over-optimizing a single strategy on one timeframe and market, build a diversified portfolio across multiple markets and timeframes. Deeptest helps you validate each component so you can combine robust strategies into a trading portfolio.
➙ Screenshots shown in the documentation are solely for visual representation to demonstrate how the tables and metrics will be displayed. Please do not compare your strategy's performance with the metrics shown in these screenshots -- they are illustrative examples only, not performance targets or benchmarks.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW-TO
Using Deeptest is intentionally straightforward. Just import the library and call DT.runDeeptest() at the end of your strategy code in main scope. .
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as DT
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
And yes... it's compatible with any TradingView Strategy! 🪄
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ CREDITS
Author: @Fractalyst
Font Library: by @fikira - @kaigouthro - @Duyck
Community: Inspired by the @PineCoders community initiative, encouraging developers to contribute open-source libraries and continuously enhance the Pine Script ecosystem for all traders.
if you find Deeptest valuable in your trading journey, feel free to use it in your strategies and give a shoutout to @Fractalyst -- Your recognition directly supports ongoing development and open-source contributions to Pine Script.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ DISCLAIMER
This library is provided for educational and research purposes. Past performance does not guarantee future results. Always test thoroughly and use proper risk management. The author is not responsible for any trading losses incurred through the use of this code.






















