Trend Trader-Remastered StrategyOfficial Strategy for Trend Trader - Remastered
Indicator: Trend Trader-Remastered (TTR)
Overview:
The Trend Trader-Remastered is a refined and highly sophisticated implementation of the Parabolic SAR designed to create strategic buy and sell entry signals, alongside precision take profit and re-entry signals based on marked Bill Williams (BW) fractals. Built with a deep emphasis on clarity and accuracy, this indicator ensures that only relevant and meaningful signals are generated, eliminating any unnecessary entries or exits.
Please check the indicator details and updates via the link above.
Important Disclosure:
My primary objective is to provide realistic strategies and a code base for the TradingView Community. Therefore, the default settings of the strategy version of the indicator have been set to reflect realistic world trading scenarios and best practices.
Key Features:
Strategy execution date&time range.
Take Profit Reduction Rate: The percentage of progressive reduction on active position size for take profit signals.
Example:
TP Reduce: 10%
Entry Position Size: 100
TP1: 100 - 10 = 90
TP2: 90 - 9 = 81
Re-Entry When Rate: The percentage of position size on initial entry of the signal to determine re-entry.
Example:
RE When: 50%
Entry Position Size: 100
Re-Entry Condition: Active Position Size < 50
Re-Entry Fill Rate: The percentage of position size on initial entry of the signal to be completed.
Example:
RE Fill: 75%
Entry Position Size: 100
Active Position Size: 50
Re-Entry Order Size: 25
Final Active Position Size:75
Important: Even RE When condition is met, the active position size required to drop below RE Fill rate to trigger re-entry order.
Key Points:
'Process Orders on Close' is enabled as Take Profit and Re-Entry signals must be executed on candle close.
'Calculate on Every Tick' is enabled as entry signals are required to be executed within candle time.
'Initial Capital' has been set to 10,000 USD.
'Default Quantity Type' has been set to 'Percent of Equity'.
'Default Quantity' has been set to 10% as the best practice of investing 10% of the assets.
'Currency' has been set to USD.
'Commission Type' has been set to 'Commission Percent'
'Commission Value' has been set to 0.05% to reflect the most realistic results with a common taker fee value.
Cerca negli script per "fractals"
SMA RSI Fractal Strategy V4 Edit 1Made from RSI, SMA, and fractals. With the bands and signals for buy and sell entry. The colors are of opposite.
Support & Resistance ZonesTitle: A Comprehensive Guide to the Support & Resistance Zones Indicator
Introduction
In the world of technical analysis, the Support & Resistance Zones indicator plays a crucial role in identifying potential trading opportunities. These zones are essential for traders looking to capitalize on bounces or break and retests. In this article, we will delve into the specifics of the Support & Resistance Zones indicator, outlining how it works, how it finds and marks zones, and the various options available for traders.
What the indicator is about
The Support & Resistance Zones indicator, developed by @HarryCTC, is a powerful tool for detecting areas of potential price reversal or consolidation in a financial market. These zones are significant as they can act as a guide for traders to make informed decisions on entering or exiting positions. Specifically, the indicator helps identify:
1. Support Zones: Areas where the price has a tendency to bounce back up after falling, indicating a potential buying opportunity.
2. Resistance Zones: Areas where the price has a tendency to reverse after rising, indicating a potential selling opportunity.
How the indicator finds its zones
The Support & Resistance Zones indicator utilizes pivot points to identify potential support and resistance levels. By analyzing the fractal structure of the price chart, the indicator identifies key turning points, known as bull and bear fractals. The bull fractal is a high pivot point, while the bear fractal is a low pivot point.
The fractal structure is determined by the 'Switch Zone Period' input, which can be adjusted to suit the trader's preferences. A higher value will result in fewer zones being identified, while a lower value will result in more zones.
How it marks zones and why it marks zones
The indicator marks the support and resistance zones by creating rectangular boxes around the identified fractal points. The zones are extended horizontally from the fractal point, allowing traders to visualize the potential areas of price reversal.
The zones are marked for the following reasons:
1. To provide a clear visual representation of potential support and resistance levels.
2. To help traders identify potential entry and exit points based on the price's reaction to these zones.
3. To serve as a reference for stop-loss and take-profit levels when planning trades.
The indicator's for traders trading bounces or break and retests
Traders who focus on trading bounces or break and retests can benefit immensely from the Support & Resistance Zones indicator. By providing a visual representation of key support and resistance levels, the indicator enables traders to:
1. Identify potential buying opportunities at support zones where the price is likely to bounce back up.
2. Identify potential selling opportunities at resistance zones where the price is likely to reverse after rising.
3. Make informed decisions on stop-loss and take-profit levels based on the price's proximity to support and resistance zones.
4. Monitor the market for potential breakouts or breakdowns when the price breaches these zones.
Indicator options
The Support & Resistance Zones indicator offers several customizable options to suit the trader's preferences. These options include:
1. Switch Zone Period: Adjusts the number of periods used to calculate the fractal structure, influencing the number of identified zones.
2. No. of Displayed Zones: Determines the maximum number of zones displayed on the chart, ranging from 1 to 8.
3. Zone Extension: Adjusts the horizontal extension of the support and resistance zones.
4. Resistance Zone Color: Customizes the color of the resistance zone boxes.
5. Support Zone Color: Customizes the color of the support zone boxes.
6. Zone Border Color: Customizes the color of the zone box borders.
Conclusion
The Support & Resistance Zones indicator is a valuable tool for traders looking to identify potential trading opportunities based on the price's interaction with support and resistance levels. By providing a clear visual representation of these zones, the
indicator allows traders to make informed decisions on entry and exit points, stop-loss, and take-profit levels. With customizable options, the indicator can be tailored to suit individual trading preferences and strategies.
Trading ChannelTrading Channel aims to be a canvas on which to develop any strategy that the user feels comfortable with.
The greatest utility of the script lies in the fact that it plots a channel over the price action, as a support and resistance pivot, within which the price action develops.
It is a script of maximum simplicity in concept and development, but at the same time presents robust support to the price action and a quick visual aid complementary to any indicators that the user works with, feels comfortable with, and uses as a basis for their strategies.
The script includes the following features (most of them disabled by default, available for potential use without the need to add additional indicators):
Fast SMA
Medium SMA
Slow SMA (disabled)
Fast EMA (disabled)
Medium EMA (disabled)
Slow EMA (disabled)
Pivot
Pivot SMA
P Multiplier
Set of resistance and support pivots according to the studies of John L. Person (R3, R2, R1, S1, S2, S3 and midpoints) (disabled by default)
Channel for the current time period in use
Channels for extended time periods (disabled by default)
Various trend, momentum, and overbought/oversold indicating labels (note that the calculations for their representation are based on SMA's even though EMA's are visualized).
SMA's/EMA's
Both are available as both are used as basic indicators for different types of strategies. The default selection of SMA's in this case is based on the fact that the script development is largely based on the studies shared by John L. Person in the area of pivots and by Bill Williams in the area of fractals. Note also that for that same reason the various trend, momentum, and overbought/oversold indicating labels are calculated based on them.
Set of resistance and support pivots
They are included as a consultation tool especially for the higher time periods. They can be used to mark the most interesting supports/resistances and not lose sight of them while operating in lower time periods. Marking monthly, weekly, and daily pivots can be very useful. Additionally, marking S1 and R2 for bullish trends, S1 and R1 for ranges, and S2 and R1 for bearish trends can provide an even more precise framework to work on.
P Multiplier
It is set by default at 4, and is the basis for being able to consider during the use of a specific time frame, the price action with respect to higher time frames. It is the multiplier used for the generation of channels for extended time periods.
Channel for the current time period in use
It is a channel formed by the maximum and minimum closing of the last 21 periods. This value is modifiable and its adjustment depends on the asset under study. 24/7 markets show good results with this adjustment (in the case of BTC really good).
This channel represents a pivot in the form of a yellow middle line, with its support and resistance extremes on the upper green and lower red lines. The same green and red lines, referenced this time to the maximum, are added and serve as possible stop-loss marks.
Channels for extended time periods
Enabling the maximum and minimum channels for extended periods can provide a better idea of the price situation (it is recommended to disable the channel in use and enable the upper one for consultation, it provides a better vision).
Identifying labels:
Following a summary explanation for possible long entries, the same but opposite should be considered for possible short entries:
Small green arrow under candle: indicates possible upward trend (pivot above pivot SMA)
Large green arrow under candle: indicates upward trend (pivot above pivot SMA and above fast SMA)
Green triangle over candle: indicates channel breakout, possible upward momentum (represented as a fractal as its concept is the same)
Green/red arrows at the bottom of the chart: intended to confirm the validity of a signal (should doubt green indications with red lower arrow and vice versa)
Green/red dots at the bottom of the chart: red represents areas of strong resistance and green signals of strong support (with red dots, proceed with caution despite green signals, and vice versa)
Comments
It is emphasized that the basic and most useful functionality of this script is to provide a reliable base on which to develop any strategy, as a framework for working.
If the identifying labels are used, it should be taken into account that the earliest will always be the most reliable and valuable, but their confirmation will always depend on the user's strategy.
Its use in conjunction with the "Pivot Position for Trading Channel" indicator can serve as a base for the development of different strategies, by providing indication of the relative position of the price within the channel.
This script is just a consultation tool with didactic goals, it should not be used as an investment recommendation and the information provided should not be relied upon as such.
------------------------
Trading Channel pretende ser un lienzo sobre el que desarrollar cualquiera que sea la estrategia con la que el usuario se sienta más cómodo.
La mayor utilidad del script radica en que se traza sobre la acción del precio un canal, a modo de pivotes de soporte y resistencia, dentro del cual se desarrolla la acción del precio.
Se trata de un script de máxima sencillez en concepto y desarrollo, pero que a la vez presenta un soporte robusto a la acción del precio y una ayuda rápida visual complementaria a cualquieras que sean los indicadores con los que el usuario trabaje, se sienta más cómodo y utilice como base de sus estrategias.
El script incluye las siguientes funcionalidades (la mayoría desactivadas por defecto, disponibles para su potencial uso sin necesidad de añadir indicadores adicionales):
- SMA rápida
- SMA media
- SMA lenta (desactivada)
- EMA rápida (desactivada)
- EMA media (desactivada)
- EMA lenta (desactivada)
- Pivote
- SMA de pivote
- Multiplicador de P
- Conjunto de pivotes resistencia y soporte de acuerdo a los estudios de John L. Person (R3, R2, R1, S1, S2, S3 y puntos medios) (desactivados por defecto)
- Canal para el periodo temporal en uso
- Canales para periodos temporales extendidos (desactivados por defecto)
- Diversas etiquetas indicativas de cambios de tendencia, de impulso y de sobrecompra y sobreventa (nótese que los cálculos para su representación están basados en SMA's aunque se visualicen EMA's).
SMA's/EMA's
Ambas disponibles pues tanto unas como otras son utilizadas como indicadores básicos para diferentes tipos de estrategias. La selección de SMA's por defecto en este caso se basa en que las bases para desarrollo del script son en gran medida los estudios compartidos por John L. Person en el área de pivotes y de Bill Williams en el área de los fractales. Nótese también que por esa misma razón las diversas etiquetas indicativas de cambios de tendencia, impulso y sobrecompra/sobreventa se calculan en base a ellas.
Conjunto de pivotes resistencia y soporte
Se incluyen como herramienta de consulta sobre todo para los periodos temporales más altos. Pueden utilizarse para marcar los soportes/resistencias de más interés y no perderlos de vista mientras se opera en periodos de tiempo más bajos. De acuerdo a los estudios de John L. Person, marcarse los pivotes mensuales, semanales y diarios puede resultar de mucha utilidad. Adicionalmente, marcar S1 y R2 para tendencias alcistas, S1 y R1 para rangos, y S2 y R1 para tendencias bajistas puede proporcionar un marco aún más preciso sobre el que trabajar.
Multiplicador de p
Está fijado por defecto en 4, y es la base para poder considerar durante el uso de una franja temporal concreta, la acción del precio respecto a franjas temporales superiores. Es el multiplicador utilizado para la generación de los canales para periodos temporales extendidos.
Canal para el periodo temporal en uso
Se trata de un canal conformado por los cierres máximos y mínimos de los últimos 21 periodos. Este valor es modificable y su ajuste depende del activo en estudio. Mercados 24/7 muestran buenos resultados con este ajuste (en el caso de BTC realmente buenos).
Este canal representa en cierta manera un pivote en forma de línea intermedia amarilla, con sus extremos de soporte y resistencia en las líneas verdes superior y roja inferior. Se añaden las mismas líneas verdes y rojas, referenciadas esta vez a los máximos, que sirven como posibles marcas de stop-loss.
Canales para periodos temporales extendidos
Habilitar los máximos y mínimos de canales de periodos extendidos puede proporcionar una mejor idea de la situación del precio (se recomienda deshabilitar el canal en uso y habilitar el superior para consulta, proporciona una mejor visión).
Etiquetas identificativas:
A continuación explicación resumida para posibles entradas en largo, lo mismo pero de modo opuesto debería considerarse para posibles entradas en corto:
Flecha verde pequeña bajo vela: indica inicio de tendencia en alza (pivote por encima de SMA de pivote y ambos por encima de SMA rápida)
Flecha verde grande bajo vela: indica tendencia en alza (pivote por encima de SMA de pivote y ambos por encima de SMA rápida y media)
Triángulo verde sobre vela: indica rotura de canal, posible impulso al alza (representado a modo de fractal pues su concepto es el mismo)
Flechas verdes/rojas a pie de gráfico: pretenden confirmar la validez de una señal (debería dudarse de las indicaciones verdes con flecha inferior roja y viceversa)
Puntos verdes/rojos a pie de gráfico: los rojos representan áreas de fuerte resistencia y los verdes de fuerte soporte (con puntos rojos, proceder con cautela pese a señales verdes, y viceversa)
Comentarios
Se insiste en que la funcionalidad básica y de mayor utilidad de este script es proporcionar una base confiable sobre la que desarrollar cualquier estrategia, a modo de marco de trabajo.
Si se hace uso de las etiquetas identificativas, debe tenerse en cuenta que las más prematuras siempre serán las más confiables y valiosas, pero que su confirmación siempre dependerá de la estrategia por parte del usuario.
Su uso en conjunción al indicador "Pivot Position for Trading Channel" puede servir de base para el desarrollo de diferentes estrategias, al proporcionar indicación de la posición relativa del precio dentro del canal.
Este script es solo una herramienta de consulta con objetivos didácticos, no debe ser utilizado como recomendación de inversión y no se debe confiar en ella como tal.
PivotThis library was designed to create three different datasets using Bill Williams fractals. The goal is to spot trends in reversal data and ultimately use these datasets to help predict future price reversals.
First, the pivot() function is used to initialize and populate three separate arrays (high pivot , low pivot , all pivots ). Since each high/low price depends on the bar_index, the bar_index, pivot direction(high/low), and high/low values are compressed into a string to maintain the data's integrity ("__"). Once each string array is populated and organized by bar_index, all three are returned inside a tuple. The return value must be deconstructed H,L,A =pivot() for each array's values to be accessed using getPivot() . This boilerplate allows for data to be accessed more efficiently in a recursive environment. getPivot() was designed to be used inside of a for or while block to populate matrices for further analyses. Again, getPivot() return values must be exposed through deconstruction. x,d,y =getPivot(). See code for more details.
pivot(int XLR) initializes and populates arrays
Parameters
XLR - number of bars to the left and right that must be lower for a high to be considered a pivotHigh, or vice versa. This number will drastically change the size and scope of the returned datasets. smaller values will produce much larger datasets, which might model short term price activity well. In contrast, larger values will produce smaller datasets which might model longer term price activity well.
Returns - tuple [string ]
getPivot(string arrayID, int index) accesses array data
Parameters
arrayID - the variable name for one of the three arrays returned by pivot().
index - the index of the provided array, with 0 being the most recent pivot point. can be set to " i " in a loop to access values recursively
Returns - tuple
Support & Ressistance by @kaleboraciy [REUPLOAD]█ OVERVIEW
Support & Resistance levels are important in trading as we all know.
█ WARNING
This version is beta, maybe sometimes it will plot wrong levels, but i will try to to eliminate these issues. And please note, that you should find your own ideal settings for every ticker you use.
█ FEATURES
This is the first script in Pine Community which plots levels using the last two points/ pivots /fractals.
It also stops plotting levels when there is a breakout on the particular level.
█ SETTINGS
1. Pivot Points Length - defines pivot points length. Using to find points where market is reversed. If you set lower value, there will be more points but less useful. As I said you should find your optimal parameters.
2. Inaccuracy in % - defines maximal possible inaccuracy between 2 pivot points .
3. Linewidth - width of line(level)
4. Start Calculations from - if you use low timeframe (1m - 30m) there are a lot of calculations, and PineScript can't process it. This parameter defines start date of calculations and now there are less data and Pine can process it better.
█ HOW IT WORKS
When a new pivot appears, it draws invisible line starting in this pivot . when the second pivots gets created, it checks all lines in array. When inaccuracy is smaller than defined, the line becomes visible.
If price breaks trough the pivots , the lines stop and a new cycle begins.
I hope that this script will be helpful in your trading🙂
taLibrary "ta"
█ OVERVIEW
This library holds technical analysis functions calculating values for which no Pine built-in exists.
Look first. Then leap.
█ FUNCTIONS
cagr(entryTime, entryPrice, exitTime, exitPrice)
It calculates the "Compound Annual Growth Rate" between two points in time. The CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It only takes into account the prices of the two end points — not drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two instruments. Because it annualizes values, the function requires a minimum of one day between the two end points (annualizing returns over smaller periods of times doesn't produce very meaningful figures).
Parameters:
entryTime : The starting timestamp.
entryPrice : The starting point's price.
exitTime : The ending timestamp.
exitPrice : The ending point's price.
Returns: CAGR in % (50 is 50%). Returns `na` if there is not >=1D between `entryTime` and `exitTime`, or until the two time points have not been reached by the script.
█ v2, Mar. 8, 2022
Added functions `allTimeHigh()` and `allTimeLow()` to find the highest or lowest value of a source from the first historical bar to the current bar. These functions will not look ahead; they will only return new highs/lows on the bar where they occur.
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `high`.
Returns: (float) The highest value tracked.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `low`.
Returns: (float) The lowest value tracked.
█ v3, Sept. 27, 2022
This version includes the following new functions:
aroon(length)
Calculates the values of the Aroon indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the Aroon-Up and Aroon-Down values.
coppock(source, longLength, shortLength, smoothLength)
Calculates the value of the Coppock Curve indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
longLength (simple int) : (simple int) Number of bars for the fast ROC value (length).
shortLength (simple int) : (simple int) Number of bars for the slow ROC value (length).
smoothLength (simple int) : (simple int) Number of bars for the weigted moving average value (length).
Returns: (float) The oscillator value.
dema(source, length)
Calculates the value of the Double Exponential Moving Average (DEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `source`.
dema2(src, length)
An alternate Double Exponential Moving Average (Dema) function to `dema()`, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `src`.
dm(length)
Calculates the value of the "Demarker" indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
ema2(src, length)
An alternate ema function to the `ta.ema()` built-in, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Number of bars (length).
Returns: (float) The exponentially weighted moving average of the `src`.
eom(length, div)
Calculates the value of the Ease of Movement indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
div (simple int) : (simple int) Divisor used for normalzing values. Optional. The default is 10000.
Returns: (float) The oscillator value.
frama(source, length)
The Fractal Adaptive Moving Average (FRAMA), developed by John Ehlers, is an adaptive moving average that dynamically adjusts its lookback period based on fractal geometry.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The fractal adaptive moving average of the `source`.
ft(source, length)
Calculates the value of the Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
ht(source)
Calculates the value of the Hilbert Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
ichimoku(conLength, baseLength, senkouLength)
Calculates values of the Ichimoku Cloud indicator, including tenkan, kijun, senkouSpan1, senkouSpan2, and chikou. NOTE: offsets forward or backward can be done using the `offset` argument in `plot()`.
Parameters:
conLength (int) : (series int) Length for the Conversion Line (Tenkan). The default is 9 periods, which returns the mid-point of the 9 period Donchian Channel.
baseLength (int) : (series int) Length for the Base Line (Kijun-sen). The default is 26 periods, which returns the mid-point of the 26 period Donchian Channel.
senkouLength (int) : (series int) Length for the Senkou Span 2 (Leading Span B). The default is 52 periods, which returns the mid-point of the 52 period Donchian Channel.
Returns: ( [float, float, float, float, float ]) A tuple of the Tenkan, Kijun, Senkou Span 1, Senkou Span 2, and Chikou Span values. NOTE: by default, the senkouSpan1 and senkouSpan2 should be plotted 26 periods in the future, and the Chikou Span plotted 26 days in the past.
ift(source)
Calculates the value of the Inverse Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
kvo(fastLen, slowLen, trigLen)
Calculates the values of the Klinger Volume Oscillator.
Parameters:
fastLen (simple int) : (simple int) Length for the fast moving average smoothing parameter calculation.
slowLen (simple int) : (simple int) Length for the slow moving average smoothing parameter calculation.
trigLen (simple int) : (simple int) Length for the trigger moving average smoothing parameter calculation.
Returns: ( [float, float ]) A tuple of the KVO value, and the trigger value.
pzo(length)
Calculates the value of the Price Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
rms(source, length)
Calculates the Root Mean Square of the `source` over the `length`.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The RMS value.
rwi(length)
Calculates the values of the Random Walk Index.
Parameters:
length (simple int) : (simple int) Lookback and ATR smoothing parameter length.
Returns: ( [float, float ]) A tuple of the `rwiHigh` and `rwiLow` values.
stc(source, fast, slow, cycle, d1, d2)
Calculates the value of the Schaff Trend Cycle indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
fast (simple int) : (simple int) Length for the MACD fast smoothing parameter calculation.
slow (simple int) : (simple int) Length for the MACD slow smoothing parameter calculation.
cycle (simple int) : (simple int) Number of bars for the Stochastic values (length).
d1 (simple int) : (simple int) Length for the initial %D smoothing parameter calculation.
d2 (simple int) : (simple int) Length for the final %D smoothing parameter calculation.
Returns: (float) The oscillator value.
stochFull(periodK, smoothK, periodD)
Calculates the %K and %D values of the Full Stochastic indicator.
Parameters:
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
stochRsi(lengthRsi, periodK, smoothK, periodD, source)
Calculates the %K and %D values of the Stochastic RSI indicator.
Parameters:
lengthRsi (simple int) : (simple int) Length for the RSI smoothing parameter calculation.
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
source (float) : (series int/float) Series of values to process. Optional. The default is `close`.
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
supertrend(factor, atrLength, wicks)
Calculates the values of the SuperTrend indicator with the ability to take candle wicks into account, rather than only the closing price.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is false.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
szo(source, length)
Calculates the value of the Sentiment Zone Oscillator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
t3(source, length, vf)
Calculates the value of the Tilson Moving Average (T3).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
t3Alt(source, length, vf)
An alternate Tilson Moving Average (T3) function to `t3()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
tema(source, length)
Calculates the value of the Triple Exponential Moving Average (TEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
tema2(source, length)
An alternate Triple Exponential Moving Average (TEMA) function to `tema()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
trima(source, length)
Calculates the value of the Triangular Moving Average (TRIMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `source`.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a "series int" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `src`.
trix(source, length, signalLength, exponential)
Calculates the values of the TRIX indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
signalLength (simple int) : (simple int) Length for smoothing the signal line.
exponential (simple bool) : (simple bool) Condition to determine whether exponential or simple smoothing is used. Optional. The default is `true` (exponential smoothing).
Returns: ( [float, float, float ]) A tuple of the TRIX value, the signal value, and the histogram.
uo(fastLen, midLen, slowLen)
Calculates the value of the Ultimate Oscillator.
Parameters:
fastLen (simple int) : (series int) Number of bars for the fast smoothing average (length).
midLen (simple int) : (series int) Number of bars for the middle smoothing average (length).
slowLen (simple int) : (series int) Number of bars for the slow smoothing average (length).
Returns: (float) The oscillator value.
vhf(source, length)
Calculates the value of the Vertical Horizontal Filter.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
vi(length)
Calculates the values of the Vortex Indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the viPlus and viMinus values.
vzo(length)
Calculates the value of the Volume Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
williamsFractal(period)
Detects Williams Fractals.
Parameters:
period (int) : (series int) Number of bars (length).
Returns: ( [bool, bool ]) A tuple of an up fractal and down fractal. Variables are true when detected.
wpo(length)
Calculates the value of the Wave Period Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
█ v7, Nov. 2, 2023
This version includes the following new and updated functions:
atr2(length)
An alternate ATR function to the `ta.atr()` built-in, which allows a "series float" `length` argument.
Parameters:
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The ATR value.
changePercent(newValue, oldValue)
Calculates the percentage difference between two distinct values.
Parameters:
newValue (float) : (series int/float) The current value.
oldValue (float) : (series int/float) The previous value.
Returns: (float) The percentage change from the `oldValue` to the `newValue`.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
highestSince(cond, source)
Tracks the highest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the highest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `high`.
Returns: (float) The highest `source` value since the last time the `cond` was `true`.
lowestSince(cond, source)
Tracks the lowest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the lowest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `low`.
Returns: (float) The lowest `source` value since the last time the `cond` was `true`.
relativeVolume(length, anchorTimeframe, isCumulative, adjustRealtime)
Calculates the volume since the last change in the time value from the `anchorTimeframe`, the historical average volume using bars from past periods that have the same relative time offset as the current bar from the start of its period, and the ratio of these volumes. The volume values are cumulative by default, but can be adjusted to non-accumulated with the `isCumulative` parameter.
Parameters:
length (simple int) : (simple int) The number of periods to use for the historical average calculation.
anchorTimeframe (simple string) : (simple string) The anchor timeframe used in the calculation. Optional. Default is "D".
isCumulative (simple bool) : (simple bool) If `true`, the volume values will be accumulated since the start of the last `anchorTimeframe`. If `false`, values will be used without accumulation. Optional. The default is `true`.
adjustRealtime (simple bool) : (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the data since the last `anchor` condition. Optional. The default is `false`.
Returns: ( [float, float, float ]) A tuple of three float values. The first element is the current volume. The second is the average of volumes at equivalent time offsets from past anchors over the specified number of periods. The third is the ratio of the current volume to the historical average volume.
rma2(source, length)
An alternate RMA function to the `ta.rma()` built-in, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The rolling moving average of the `source`.
supertrend2(factor, atrLength, wicks)
An alternate SuperTrend function to `supertrend()`, which allows a "series float" `atrLength` argument.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is `false`.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
vStop(source, atrLength, atrFactor)
Calculates an ATR-based stop value that trails behind the `source`. Can serve as a possible stop-loss guide and trend identifier.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
vStop2(source, atrLength, atrFactor)
An alternate Volatility Stop function to `vStop()`, which allows a "series float" `atrLength` argument.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
Removed Functions:
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a
"series int" length argument.
Support & Resistance LevelsPlots support and resistance levels based on occurrence of fractals.
Line width indicates historical significance of the level.
Decreasing the proximity multiplier input increases the sensitivity/ increases the frequency of level changes.
If price closes above a resistance level, the level becomes a support level and its color on the chart changes to green (& vice-versa).
Quadratic SemaphoreThe quadratic semaphore indicator is an indicator that find confirmed market u-turn with the help of 2 quadratic regression calculated with Highs and Lows over the last “length” periods.
- “p” setting is candlesticks quantity to confirmed the quadratic regression has formed a High or Low parabola, such as Fractals. Consecutive same signals can happen due to the use of different price values for upper and lower semaphore.
- Adjust the settings to your instrument and time frame.
- Alerts included.
Success with your trade¡¡
Support-Resistance breakoutStrategy based on longing resistance breakout and shorting support breakout.
It defines highs and lows using fractal with 2 bars for confirming high/lows. So it has 2 bars lag.
It calculates the difference between sma with defined length (21 by default) of highs and of lows and uses it as alt SR level. This idea I took from synapticEx's indicator Nebula-Advanced-Dynamic-Support-Resistance.
Position enter is the breakout of SR, defined by fractals.
Position exit is: bar change in opposite to position direction > difference is sma of highs and of lows.
Highs&LowsShows Higher Highs, Higher Lows, Lower Lows & Lower Highs based off of Bill Williams fractals.
I use this mainly by shorting a break of the higher lows marked in yellow.
A long signal would be a candle close above a lower high (less reliable)
Alerts can be set with the secondary indicator below the chart.
Higher Lows / Lower Highs Alerts -https://www.tradingview.com/script/Ka1yXqRj-Higher-Lows-Lower-Highs-Alerts/
Guerrilla AdvancedThis indicator was designed with people without Pro License in mind (Including many of my close friends).
Basically, you will get a combo of few different tools in one box, with ability to turn them on and off with a single check mark, also, you have total control over the input numbers that was used in calculations if you so want to, for example, sometimes when i see a massive bullish up trend, i reduce the short rally from 12 to 8 even 6 to get faster signal for selling the trend.
So, what will you get in this pack?
1- Ichimoko. Yes, you heard it right, although we have it in the default tools but hey, it will use one indicator slot and if you don't have a pro license, you will use that slot
2- Rally. This is an old yet very powerful system for getting buy or sell signals, basically, you get two lines and for making the life easier i draw a cloud between them. when the trend passes above the cloud and it was bellow it in past, right after the very first candle that gets above the cloud you can put the buy order, and vice versa, the moment a candle body enters the cloud, if you want an aggressive signal, you can sell, if not, you may want to wait to see if the candles drop bellow the cloud or not then decide.
3- Resistance Support Cloud. Most of us always heard about resistance and support "lines" but many of us don't know that, in each trend, the trend line itself is a resistance or support line, and when you are going in a bullish or bearish tunnel, the floor and roof of tunnels are again resistance and supports, using this part of the tool, just like rally, you get a cloud that shows you the resistance / support "zone"
4- William Fractals. To be honest, I got this part of the code from another source available around. Why? looking at those fractal indicators, you can easily eyeball the trend line or existence of a tunnel.
5- Different EMA lines. If you are one of those people that use EMA lines for their trading, have fun with them, there are few different standard ones and even a custom one that you can put your desired number for it.
Current Fractal High/Low (Dynamic)
This indicator dynamically tracks the most recent confirmed Fractal High and Fractal Low across any timeframe using custom left/right bar configurations.
🔍 Key Features:
Detects Fractal Highs and Lows based on user-defined pivot settings.
Draws a green line and label ("FH") at the most recent Fractal High.
Draws a red line and label ("FL") at the most recent Fractal Low.
All lines extend from the confirmation bar to the current candle.
Automatically removes old lines and labels for a clean, uncluttered chart.
🛠️ Customizable Inputs:
Left & Right bars for pivot sensitivity
Line width for visibility
📌 Use Cases:
Identifying structure shifts
Recognizing key swing points
Supporting liquidity and breakout strategies
💡 Fractals are confirmed only after the full formation of the pattern (left and right bars). This ensures reliability over reactivity.
This script is designed for intraday to swing traders who want a reliable way to visualize market turning points with minimal noise.
Ultimate Adaptive Multi-Regime Trading System🧩 What is the UA-MTS Indicator?
UA-MTS is an intelligent trading indicator built for scalping, day trading, and adaptive decision-making. It analyzes price action, trend, volatility, volume, and patterns across multiple timeframes to give traders clear, context-aware buy and sell signals.
It’s like having a smart assistant on your chart that tells you:
What kind of market you’re in (trend, range, volatility, etc.)
What patterns are forming and how reliable they are
When a high-confidence trade opportunity appears
How far price might go next (via projection lines)
⚙️ What Does It Do?
Detects Market Regime
Identifies whether the market is Trending, Ranging, Volatile, Accumulating, or Distributing
Adjusts strategy logic based on the regime
Scans for Patterns
Finds smart price patterns (like engulfing, divergences, fractals, head & shoulders)
Evaluates pattern quality and importance
Uses AI-like Logic
Includes a mini neural network that digests market data and projects price movement
Confirms with Volume and Volatility
Filters out weak signals based on how strong the volume and volatility are
Gives Trade Signals
Shows Buy or Sell markers with scores and confidence %
Highlights high-quality trades with a star (★)
Visual Tools
Confidence bands (projected price range)
Prediction lines
Color-coded market regime
🕹 How to Use It (in TradingView)
Use the Regime Label
Bottom of chart will say "Regime: Trending (80%)" or similar
Trust trend signals more in Trending regime, reversal patterns more in Ranging
Enable Multi-Timeframe Analysis (optional)
It blends data from multiple timeframes (like 1m + 5m + 15m) to sharpen signal logic
Confirm Before Entering
Look at the Score and Confidence %
Use it with other tools like support/resistance or price structure for even better entries
📈 Best Use Cases
Scalping on 1m/5m/15m charts
Day trading breakouts or reversals
Filtering trades during sideways markets
Avoiding traps in high volatility
Projecting short-term price direction
Advanced SMC
//@version=5
indicator("Advanced SMC", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 1000)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
length = input.int(5, minval = 3)
//Colors
showBull = input(true, 'Bullish Structures', inline = 'bull', group = 'Style')
bullCss = input.color(#089981, '', inline = 'bull', group = 'Style')
showBear = input(true, 'Bearish Structures', inline = 'bear', group = 'Style')
bearCss = input.color(#f23645, '', inline = 'bear', group = 'Style')
showSupport = input(false, 'Support', inline = 's', group = 'Style')
supCss = input.color(#089981, '', inline = 's', group = 'Style')
showResistance = input(false, 'Resistance', inline = 'r', group = 'Style')
resCss = input.color(#f23645, '', inline = 'r', group = 'Style')
//Dashboard
showDash = input(false, 'Show Dashboard' , group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = , group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = , group = 'Dashboard')
//-----------------------------------------------------------------------------}
//Types
//-----------------------------------------------------------------------------{
type fractal
float value
int loc
bool iscrossed
//-----------------------------------------------------------------------------}
//Fractal Detection
//-----------------------------------------------------------------------------{
var p = int(length/2)
n = bar_index
dh = math.sum(math.sign(high - high ), p)
dl = math.sum(math.sign(low - low ), p)
bullf = dh == -p and dh == p and high == ta.highest(length)
bearf = dl == p and dl == -p and low == ta.lowest(length)
bullf_count = ta.cum(bullf ? 1 : 0)
bearf_count = ta.cum(bearf ? 1 : 0)
//-----------------------------------------------------------------------------}
//Bullish market structure
//-----------------------------------------------------------------------------{
var upper = fractal.new()
var line lower_lvl = na
var label ms_lbl = na
var bull_ms_count = 0
var broken_sup = false
var os = 0
if bullf
upper.value := high
upper.loc := n-p
upper.iscrossed := false
if ta.crossover(close, upper.value) and not upper.iscrossed
line.new(upper.loc, upper.value, n, upper.value, color = showBull ? bullCss : na)
ms_lbl := label.new(int(math.avg(n, upper.loc)), upper.value, os == -1 ? 'ChoCH' : 'BOS'
, color = color(na)
, textcolor = showBull ? bullCss : na
, style = label.style_label_down
, size = size.tiny)
//Set support
k = 2
min = low
for i = 2 to (n - upper.loc)-1
min := math.min(low , min)
k := low == min ? i : k
if showSupport
lower_lvl := line.new(n-k, min, n, min, color = bullCss, style = line.style_dashed)
broken_sup := false
upper.iscrossed := true
bull_ms_count += 1
os := 1
else if showSupport and not broken_sup
lower_lvl.set_x2(n)
if close < lower_lvl.get_y2()
broken_sup := true
//-----------------------------------------------------------------------------}
//Bearish market structure
//-----------------------------------------------------------------------------{
var lower = fractal.new()
var line upper_lvl = na
var broken_res = false
var bear_ms_count = 0
if bearf
lower.value := low
lower.loc := n-p
lower.iscrossed := false
if ta.crossunder(close, lower.value) and not lower.iscrossed
line.new(lower.loc, lower.value, n, lower.value, color = showBear ? bearCss : na)
label.new(int(math.avg(n, lower.loc)), lower.value, os == 1 ? 'ChoCH' : 'BOS'
, color = color(na)
, textcolor = showBear ? bearCss : na
, style = label.style_label_up
, size = size.tiny)
//Set resistance
k = 2
max = high
for i = 2 to (n - lower.loc)-1
max := math.max(high , max)
k := high == max ? i : k
if showResistance
upper_lvl := line.new(n-k, max, n, max, color = bearCss, style = line.style_dashed)
broken_res := false
lower.iscrossed := true
bear_ms_count += 1
os := -1
else if showResistance and not broken_res
upper_lvl.set_x2(n)
if close > upper_lvl.get_y2()
broken_res := true
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 2, 3
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if showDash
if barstate.isfirst
tb.cell(0, 0, 'Structure To Fractal %', text_color = color.white, text_size = table_size)
tb.merge_cells(0,0,1,0)
tb.cell(0, 1, 'Bullish', text_color = #089981, text_size = table_size)
tb.cell(1, 1, 'Bearish', text_color = #f23645, text_size = table_size)
if barstate.islast
tb.cell(0, 2, str.tostring(bull_ms_count / bullf_count * 100, format.percent), text_color = #089981, text_size = table_size)
tb.cell(1, 2, str.tostring(bear_ms_count / bearf_count * 100, format.percent), text_color = #f23645, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot(broken_res and not broken_res ? low : na, 'Resistance Breakout', #089981, 2, plot.style_circles)
plot(broken_sup and not broken_sup ? high : na, 'Support Breakout', #f23645, 2, plot.style_circles)
//-----------------------------------------------------------------------------}
numDays = input.int(7, "number of days lookback")
showUP = input.bool(true, "'UP' FVGs:", inline ='1')
colUp = input.color(color.new(#2195f3, 95), "", inline ='1')
showDN = input.bool(true, "'DOWN' FVGs:", inline ='2')
colDn = input.color(color.new(#ff9900, 95), "", inline ='2')
showCE = input.bool(true, "show CE", inline ='3')
ceCol = input.color(color.new(#363a45, 95), "| color:", inline ='3')
ceStyle = input.string(line.style_dotted, "| style:", options= , inline ='3')
deleteFilledBoxes = input.bool(true, "delete filled boxes & lines")
CEcond = input.bool (true, "Use CE (as opposed to Full Fill)", group = 'conditions/alerts', tooltip = "If toggled OFF, FVGs and CEs will paint until FVG has been completely filled.\n\nThis threshold is used for Above/Below threshold Alert conditions too (but does not effect the IOFED alerts):\ni.e. this will determine if your 'ABOVE threshold' alert fires when price hits latest active FVG CE ABOVE or latest active FVG Full Fill ABOVE\n\nAlerts are set by clicking the three dots on the indicator display line.")
colorNone = color.new(color.white, 100)
_day = 24*3600*1000
var box bxUp = na, var box bxDn = na, var line lnUp = na, var line lnDn = na
var array bxUpArr = array.new(0), var array lnUpArr = array.new(0)
var array bxDnArr = array.new(0), var array lnDnArr = array.new(0)
dnCE = high + (low -high )/2
upCE = low - (low -high )/2
if low > high and time> timenow- numDays*_day and showDN
bxDnArr.push(box.new(bar_index-3, low , bar_index, high , bgcolor = colDn, border_color = colorNone))
lnDnArr.push(line.new(bar_index-3, dnCE, bar_index, dnCE, color = showCE?ceCol:colorNone, style =ceStyle))
if high < low and time> timenow- numDays*_day and showUP
bxUpArr.push(box.new(bar_index-3, low , bar_index, high , bgcolor = colUp, border_color = colorNone))
lnUpArr.push(line.new(bar_index-3, upCE, bar_index, upCE, color = showCE?ceCol:colorNone, style =ceStyle))
var array _countArr =array.new(0)
var array _countArrIOFED =array.new(0)
//modified form of @Bjorgum's looping function. This stops boxes/lines painting when price passes to or through them
extendAndRemoveBx(array boxArray, array lineArray, array countArr1, array countArr2, simple bool isBull, int maxSize) =>
if boxArray.size() > 0
for i = boxArray.size() -1 to 0
line ln = lineArray.get(i)
box bx = boxArray.get(i)
bx.set_right(bar_index)
ln.set_x2(bar_index)
float price = CEcond?ln.get_price(bar_index):(isBull?bx.get_top():bx.get_bottom())
float price_IOFED = isBull?bx.get_bottom():bx.get_top()
int m = isBull ? 1 : -1
float hiLo = isBull ? high : low
if hiLo * m > price * m
boxArray.remove(i)
lineArray.remove(i)
countArr1.push(isBull?1:-1) //for 'above/below threshold alerts; counter sum will decrement 1 on lower threshold hit, increment 1 on upper threshold hit
if deleteFilledBoxes
bx.set_bgcolor(colorNone)
ln.set_color(colorNone)
if hiLo*m>price_IOFED*m
countArr2.push(isBull?1:-1)
if boxArray.size() > maxSize
box.delete(boxArray.shift())
line.delete(lineArray.shift())
extendAndRemoveBx(bxDnArr,lnDnArr,_countArr,_countArrIOFED, true, 12) //12 should be good for around 2200 bars of history
extendAndRemoveBx(bxUpArr, lnUpArr,_countArr,_countArrIOFED, false, 12)
upThresholdLst = array.sum(_countArr)>array.sum(_countArr)
dnThresholdLst = array.sum(_countArr)array.sum(_countArrIOFED)
dnIOFEDlast= array.sum(_countArrIOFED) nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
pos = 0
iff_3 = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? -1 : nz(pos , 0)
pos := src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? 1 : iff_3
xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue
ema = ta.ema(src, 1)
above = ta.crossover(ema, xATRTrailingStop)
below = ta.crossover(xATRTrailingStop, ema)
buy = src > xATRTrailingStop and above
sell = src < xATRTrailingStop and below
barbuy = src > xATRTrailingStop
barsell = src < xATRTrailingStop
plotshape(buy, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(sell, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)
barcolor(barbuy ? color.green : na)
barcolor(barsell ? color.red : na)
alertcondition(buy, 'UT Long', 'UT Long')
alertcondition(sell, 'UT Short', 'UT Short')
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
bullCss1 = input.color(color.teal, 'FVG Level' , inline = 'bull')
bullAreaCss = input.color(color.new(color.teal, 50), 'Area' , inline = 'bull')
bullMitigatedCss = input.color(color.new(color.teal, 80), 'Mitigated', inline = 'bull')
bearCss1 = input.color(color.red, 'FVG Level' , inline = 'bear')
bearAreaCss = input.color(color.new(color.red, 50), 'Area' , inline = 'bear')
bearMitigatedCss = input.color(color.new(color.red, 80), 'Mitigated' , inline = 'bear')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type fvg
float top
float btm
bool mitigated
bool isnew
bool isbull
line lvl
box area
type session_range
line max
line min
//-----------------------------------------------------------------------------}
//Methods
//-----------------------------------------------------------------------------{
nl = bar_index
//Method for setting fair value gaps
method set_fvg(fvg id, offset, bg_css, l_css)=>
avg = math.avg(id.top, id.btm)
area = box.new(nl - offset, id.top, nl, id.btm, na, bgcolor = bg_css)
avg_l = line.new(nl - offset, avg, nl, avg, color = l_css, style = line.style_dashed)
id.lvl := avg_l
id.area := area
//Method for setting session range maximum/minimum
method set_range(session_range id)=>
max = math.max(high, id.max.get_y2())
min = math.min(low, id.min.get_y2())
id.max.set_xy2(nl, max)
id.max.set_y1(max)
id.min.set_xy2(nl, min)
id.min.set_y1(min)
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var chartCss = color.new(chart.fg_color, 50)
var fvg sfvg = fvg.new(na, na, na, true, na)
var session_range sesr = na
var box area = na
var line avg = na
bull_fvg = low > high and close > high
bear_fvg = high < low and close < low
//Alert conditions
bull_isnew = false
bear_isnew = false
bull_mitigated = false
bear_mitigated = false
within_bull_fvg = false
within_bear_fvg = false
//-----------------------------------------------------------------------------}
//New session
//-----------------------------------------------------------------------------{
dtf = timeframe.change('D')
//On new session
if dtf
//Set delimiter
line.new(nl, high + syminfo.mintick
, nl, low - syminfo.mintick
, color = chartCss
, style = line.style_dashed
, extend = extend.both)
//Set new range
sesr := session_range.new(
line.new(nl, high, nl, high, color = chartCss)
, line.new(nl, low, nl, low, color = chartCss))
sfvg.isnew := true
//Set prior session fvg right coordinates
if not na(sfvg.lvl)
sfvg.lvl.set_x2(nl-2)
sfvg.area.set_right(nl-2)
//Set range
else if not na(sesr)
sesr.set_range()
//Set range lines color
sesr.max.set_color(sfvg.isbull ? bullCss1 : bearCss1)
sesr.min.set_color(sfvg.isbull ? bullCss1 : bearCss1)
//-----------------------------------------------------------------------------}
//Set FVG
//-----------------------------------------------------------------------------{
//New session bullish fvg
if bull_fvg and sfvg.isnew
sfvg := fvg.new(low, high , false, false, true)
sfvg.set_fvg(2, bullAreaCss, bullCss1)
bull_isnew := true
//New session bearish fvg
else if bear_fvg and sfvg.isnew
sfvg := fvg.new(low , high, false, false, false)
sfvg.set_fvg(2, bearAreaCss, bearCss1)
bear_isnew := true
//Change object transparencies if mitigated
if not sfvg.mitigated
//If session fvg is bullish
if sfvg.isbull and close < sfvg.btm
sfvg.set_fvg(1, bullMitigatedCss, bullCss1)
sfvg.mitigated := true
bull_mitigated := true
//If session fvg is bearish
else if not sfvg.isbull and close > sfvg.top
sfvg.set_fvg(1, bearMitigatedCss, bearCss1)
sfvg.mitigated := true
bear_mitigated := true
//Set fvg right coordinates to current bar
if not sfvg.isnew
sfvg.lvl.set_x2(nl)
sfvg.area.set_right(nl)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//On new session fvg
alertcondition(bull_isnew, 'Bullish FVG', 'New session bullish fvg')
alertcondition(bear_isnew, 'Bearish FVG', 'New session bearish fvg')
//On fvg mitigation
alertcondition(bull_mitigated, 'Mitigated Bullish FVG', 'Session bullish fvg has been mitigated')
alertcondition(bear_mitigated, 'Mitigated Bearish FVG', 'Session bearish fvg has been mitigated')
//If within fvg
alertcondition(close >= sfvg.btm and close <= sfvg.top and sfvg.isbull and not sfvg.isnew
, 'Price Within Bullish FVG'
, 'Price is within bullish fvg')
alertcondition(close >= sfvg.btm and close <= sfvg.top and not sfvg.isbull and not sfvg.isnew
, 'Price Within Bearish FVG'
, 'Price is within bearish fvg')
//On fvg average cross
alertcondition(ta.cross(close, math.avg(sfvg.top, sfvg.btm)) and sfvg.isbull and not sfvg.isnew
, 'Bullish FVG AVG Cross'
, 'Price crossed bullish fvg average')
alertcondition(ta.cross(close, math.avg(sfvg.top, sfvg.btm)) and not sfvg.isbull and not sfvg.isnew
, 'Bearish FVG AVG Cross'
, 'Price crossed bearish fvg average')
//-----------------------------------------------------------------------------}
//INPUTS
cooldownPeriod = input.int(10,title="Cooldown Period", minval=0, group = "Settings")
lbLeft = 20
lbRight = 20
showSwing = input.bool(true,title="Show Swings?", inline="s_1", group = 'Swing Detaction')
swingClr = input.color(color.new(color.orange, 0), title='', inline="s_1", group = 'Swing Detaction')
bullWidth = input.int(1, title='Line Width:', group='Bullish Sweep')
bullStyle = input.string('Dashed', title='Line Style:', options= , group='Bullish Sweep')
bullColor = input.color(color.new(color.teal, 0), title='Bullish Color:', group='Bullish Sweep')
bearWidth = input.int(1, title='Line Width:', group='Bearish Sweep')
bearStyle = input.string('Dashed', title='Line Style:', options= , group='Bearish Sweep')
bearColor = input.color(color.new(color.maroon, 0), title='Bearish Color:', group='Bearish Sweep')
//FUNCTIONS
lineStyle(s) =>
if s == 'Solid'
line.style_solid
else if s == 'Dotted'
line.style_dotted
else
line.style_dashed
//VARS
var int bullSignalIndex = 0
var int bearSignalIndex = 0
var line bullLine = na
var line bearLine = na
var line highLine = na
var line lowLine = na
var label swingHighLbl = na
var label swingLowLbl = na
var label swingHighLblTxt = na
var label swingLowLblTxt = na
var float swingLowVal = na
var float swingHighVal = na
//CALCULATIONS
pLow = ta.pivotlow(low, lbLeft, lbRight)
pHigh = ta.pivothigh(high, lbLeft, lbRight)
pLowVal = ta.valuewhen(not na(pLow), low , 0)
pHighVal = ta.valuewhen(not na(pHigh), high , 0)
prevLowIndex = ta.valuewhen(not na(pLow), bar_index , 0)
prevHighIndex = ta.valuewhen(not na(pHigh), bar_index , 0)
lp = ta.lowest(low, lbLeft)
hp = ta.highest(high, lbLeft)
highestClose = ta.highest(close, lbLeft)
lowestClose = ta.lowest(close, lbLeft)
bullishSFP = low < pLowVal and close > pLowVal and open > pLowVal and low == lp and lowestClose >= pLowVal
bearishSFP = high > pHighVal and close < pHighVal and open < pHighVal and high == hp and highestClose <= pHighVal
bullCond = bullishSFP and (close > pLowVal) and (close > pLowVal ) and (close > pLowVal ) and bar_index >= bullSignalIndex + cooldownPeriod
bearCond = bearishSFP and (close < pHighVal) and (close < pHighVal ) and (close < pHighVal ) and bar_index >= bearSignalIndex + cooldownPeriod
//Check Swing H/L Stopper
var int swingLowCounter = 0
var int swingHighCounter = 0
var bool isSwingLowCheck = false
var bool isSwingHighCheck = false
var bool stopPrintingLow = false
var bool stopPrintingHigh = false
if high < swingLowVal and isSwingLowCheck
swingLowCounter := swingLowCounter+1
if low > swingHighVal and isSwingHighCheck
swingHighCounter := swingHighCounter+1
if ta.crossunder(close, swingLowVal) and isSwingLowCheck == false
isSwingLowCheck := true
swingLowCounter := 1
if ta.crossover(close, swingHighVal) and isSwingHighCheck == false
isSwingHighCheck := true
swingHighCounter := 1
if swingLowCounter == 5 and isSwingLowCheck
stopPrintingLow := true
isSwingLowCheck := false
line.set_x2(lowLine,bar_index )
if swingHighCounter == 5 and isSwingHighCheck
stopPrintingHigh := true
isSwingHighCheck := false
line.set_x2(highLine,bar_index )
//Draw sweep lines
if bullCond
bullSignalIndex := bar_index
bullLine := line.new(prevLowIndex, pLowVal, bar_index-3, pLowVal, color=bullColor, width=bullWidth, style=lineStyle(bullStyle))
if bearCond
bearSignalIndex := bar_index
bearLine := line.new(prevHighIndex, pHighVal, bar_index-3, pHighVal, color=bearColor, width=bearWidth, style=lineStyle(bearStyle))
var swingHighArr = array.new_label(0)
var swingHighTextArr = array.new_label(0)
var swingLowArr = array.new_label(0)
var swingLowTextArr = array.new_label(0)
if array.size(swingHighArr) >= 3
label.delete(array.shift(swingHighArr))
label.delete(array.shift(swingHighTextArr))
if array.size(swingLowArr) >= 3
label.delete(array.shift(swingLowArr))
label.delete(array.shift(swingLowTextArr))
//Draw range lines
if showSwing
if stopPrintingHigh == false
line.set_x2(highLine,bar_index+5)
if stopPrintingLow == false
line.set_x2(lowLine,bar_index+5)
if showSwing and not na(pHigh) and bearishSFP == false
stopPrintingHigh := false
swingHighVal := high
line.delete(highLine)
highLine := line.new(bar_index , high , bar_index+10, high , color = swingClr, width = 2)
swingHighLbl := label.new(bar_index , high , text="", yloc=yloc.abovebar, color = swingClr, textcolor = swingClr, style = label.style_triangledown, size = size.auto)
swingHighLblTxt := label.new(bar_index , high , text="Swing\nH", yloc=yloc.abovebar, color = swingClr, textcolor = swingClr, style = label.style_none, size = size.small)
array.push(swingHighArr, swingHighLbl)
array.push(swingHighTextArr, swingHighLblTxt)
if showSwing and not na(pLow) and bullishSFP == false
stopPrintingLow := false
swingLowVal := low
line.delete(lowLine)
lowLine := line.new(bar_index , low , bar_index+10, low , color = swingClr, width = 2)
swingLowLbl := label.new(bar_index , low , text="", yloc=yloc.belowbar, color = swingClr, textcolor = swingClr, style = label.style_triangleup, size = size.auto)
swingLowLblTxt := label.new(bar_index , low , text="Swing\nL", yloc=yloc.belowbar, color = swingClr, textcolor = swingClr, style = label.style_none, size = size.small)
array.push(swingLowArr, swingLowLbl)
array.push(swingLowTextArr, swingLowLblTxt)
//PLOTS
plotshape(bullCond, text='Sweep', color=bullColor, textcolor=bullColor, location=location.belowbar, offset = -3)
plotshape(bearCond, text='Sweep', color=bearColor, textcolor=bearColor, location=location.abovebar, offset = -3)
//ALERTS
alertcondition(bullishSFP, title='Bullish Sweep', message='{{ticker}} Bullish Sweep, Price:{{close}}')
alertcondition(bearishSFP, title='Bearish Sweep', message='{{ticker}} Bearish Sweep, Price:{{close}}')
//------------------------------------------------------------------------------
length1 = input(100)
extend = input(true,'Extend To Last Bar')
show_ext = input(true,'Show Extremities')
show_labels = input(true,'Show Labels')
//Style
upcol = input(#ff1100,'Upper Extremity Color',group='Style')
midcol = input(#ff5d00,'Zig Zag Color',group='Style')
dncol = input(#2157f3,'Lower Extremity Color',group='Style')
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
liqGrp = 'Liquidity Detection'
liqLen = input.int (7, title = 'Detection Length', minval = 3, maxval = 13, inline = 'LIQ', group = liqGrp)
liqMar = 10 / input.float (6.9, 'Margin', minval = 4, maxval = 9, step = 0.1, inline = 'LIQ', group = liqGrp)
liqBuy = input.bool (true, 'Buyside Liquidity Zones, Margin', inline = 'Buyside', group = liqGrp)
marBuy = input.float(2.3, '', minval = 1.5, maxval = 10, step = .1, inline = 'Buyside', group = liqGrp)
cLIQ_B = input.color (color.new(#4caf50, 0), '', inline = 'Buyside', group = liqGrp)
liqSel = input.bool (true, 'Sellside Liquidity Zones, Margin', inline = 'Sellside', group = liqGrp)
marSel = input.float(2.3, '', minval = 1.5, maxval = 10, step = .1, inline = 'Sellside', group = liqGrp)
cLIQ_S = input.color (color.new(#f23645, 0), '', inline = 'Sellside', group = liqGrp)
lqVoid = input.bool (false, 'Liquidity Voids, Bullish', inline = 'void', group = liqGrp)
cLQV_B = input.color (color.new(#4caf50, 0), '', inline = 'void', group = liqGrp)
cLQV_S = input.color (color.new(#f23645, 0), 'Bearish', inline = 'void', group = liqGrp)
lqText = input.bool (false, 'Label', inline = 'void', group = liqGrp)
mode = input.string('Present', title = 'Mode', options = , inline = 'MOD', group = liqGrp)
visLiq = input.int (3, ' # Visible Levels', minval = 1, maxval = 50, inline = 'MOD', group = liqGrp)
//-----------------------------------------------------------------------------}
//General Calculations
//-----------------------------------------------------------------------------{
maxSize = 50
atr = ta.atr(10)
atr200 = ta.atr(200)
per = mode == 'Present' ? last_bar_index - bar_index <= 500 : true
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
// @type used to store pivot high/low data
//
// @field d (array) The array where the trend direction is to be maintained
// @field x (array) The array where the bar index value of pivot high/low is to be maintained
// @field y (array) The array where the price value of pivot high/low is to be maintained
type ZZ
int d
int x
float y
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
int i = bar_index
// @type liquidity object definition
//
// @field bx (box) box maitaing the liquity level margin extreme levels
// @field bxz (box) box maitaing the liquity zone margin extreme levels
// @field bxt (box) box maitaing the labels
// @field brZ (bool) mainains broken zone status
// @field brL (bool) mainains broken level status
// @field ln (line) maitaing the liquity level line
// @field lne (line) maitaing the liquity extended level line
type liq
box bx
box bxz
box bxt
bool brZ
bool brL
line ln
line lne
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var ZZ aZZ = ZZ.new(
array.new (maxSize, 0),
array.new (maxSize, 0),
array.new (maxSize, na)
)
bar b = bar.new()
var liq b_liq_B = array.new (1, liq.new(box(na), box(na), box(na), false, false, line(na), line(na)))
var liq b_liq_S = array.new (1, liq.new(box(na), box(na), box(na), false, false, line(na), line(na)))
var b_liq_V = array.new_box()
var int dir = na, var int x1 = na, var float y1 = na, var int x2 = na, var float y2 = na
//-----------------------------------------------------------------------------}
//Functions/methods
//-----------------------------------------------------------------------------{
// @function maintains arrays
// it prepends a `value` to the arrays and removes their oldest element at last position
// @param aZZ (UDT, array, array>) The UDT obejct of arrays
// @param _d (array) The array where the trend direction is maintained
// @param _x (array) The array where the bar index value of pivot high/low is maintained
// @param _y (array) The array where the price value of pivot high/low is maintained
//
// @returns none
method in_out(ZZ aZZ, int _d, int _x, float _y) =>
aZZ.d.unshift(_d), aZZ.x.unshift(_x), aZZ.y.unshift(_y), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
// @function (build-in) sets the maximum number of bars that is available for historical reference
max_bars_back(time, 1000)
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
x2 := b.i - 1
ph = ta.pivothigh(liqLen, 1)
pl = ta.pivotlow (liqLen, 1)
if ph
dir := aZZ.d.get(0)
x1 := aZZ.x.get(0)
y1 := aZZ.y.get(0)
y2 := nz(b.h )
if dir < 1
aZZ.in_out(1, x2, y2)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if per
count = 0
st_P = 0.
st_B = 0
minP = 0.
maxP = 10e6
for i = 0 to maxSize - 1
if aZZ.d.get(i) == 1
if aZZ.y.get(i) > ph + (atr / liqMar)
break
else
if aZZ.y.get(i) > ph - (atr / liqMar) and aZZ.y.get(i) < ph + (atr / liqMar)
count += 1
st_B := aZZ.x.get(i)
st_P := aZZ.y.get(i)
if aZZ.y.get(i) > minP
minP := aZZ.y.get(i)
if aZZ.y.get(i) < maxP
maxP := aZZ.y.get(i)
if count > 2
getB = b_liq_B.get(0)
if st_B == getB.bx.get_left()
getB.bx.set_top(math.avg(minP, maxP) + (atr / liqMar))
getB.bx.set_rightbottom(b.i + 10, math.avg(minP, maxP) - (atr / liqMar))
else
b_liq_B.unshift(
liq.new(
box.new(st_B, math.avg(minP, maxP) + (atr / liqMar), b.i + 10, math.avg(minP, maxP) - (atr / liqMar), bgcolor=color(na), border_color=color(na)),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
box.new(st_B, st_P, b.i + 10, st_P, text = 'Buyside liquidity', text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_bottom, text_color = color.new(cLIQ_B, 25), bgcolor = color(na), border_color = color(na)),
false,
false,
line.new(st_B , st_P, b.i - 1, st_P, color = color.new(cLIQ_B, 0)),
line.new(b.i - 1, st_P, na , st_P, color = color.new(cLIQ_B, 0), style = line.style_dotted))
)
alert('buyside liquidity level detected/updated for ' + syminfo.ticker)
if b_liq_B.size() > visLiq
getLast = b_liq_B.pop()
getLast.bx.delete()
getLast.bxz.delete()
getLast.bxt.delete()
getLast.ln.delete()
getLast.lne.delete()
if pl
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(b.l )
if dir > -1
aZZ.in_out(-1, x2, y2)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if per
count = 0
st_P = 0.
st_B = 0
minP = 0.
maxP = 10e6
for i = 0 to maxSize - 1
if aZZ.d.get(i) == -1
if aZZ.y.get(i) < pl - (atr / liqMar)
break
else
if aZZ.y.get(i) > pl - (atr / liqMar) and aZZ.y.get(i) < pl + (atr / liqMar)
count += 1
st_B := aZZ.x.get(i)
st_P := aZZ.y.get(i)
if aZZ.y.get(i) > minP
minP := aZZ.y.get(i)
if aZZ.y.get(i) < maxP
maxP := aZZ.y.get(i)
if count > 2
getB = b_liq_S.get(0)
if st_B == getB.bx.get_left()
getB.bx.set_top(math.avg(minP, maxP) + (atr / liqMar))
getB.bx.set_rightbottom(b.i + 10, math.avg(minP, maxP) - (atr / liqMar))
else
b_liq_S.unshift(
liq.new(
box.new(st_B, math.avg(minP, maxP) + (atr / liqMar), b.i + 10, math.avg(minP, maxP) - (atr / liqMar), bgcolor=color(na), border_color=color(na)),
box.new(na, na, na, na, bgcolor=color(na), border_color=color(na)),
box.new(st_B, st_P, b.i + 10, st_P, text = 'Sellside liquidity', text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_top, text_color = color.new(cLIQ_S, 25), bgcolor=color(na), border_color=color(na)),
false,
false,
line.new(st_B , st_P, b.i - 1, st_P, color = color.new(cLIQ_S, 0)),
line.new(b.i - 1, st_P, na , st_P, color = color.new(cLIQ_S, 0), style = line.style_dotted))
)
alert('sellside liquidity level detected/updated for ' + syminfo.ticker)
if b_liq_S.size() > visLiq
getLast = b_liq_S.pop()
getLast.bx.delete()
getLast.bxz.delete()
getLast.bxt.delete()
getLast.ln.delete()
getLast.lne.delete()
for i = 0 to b_liq_B.size() - 1
x = b_liq_B.get(i)
if not x.brL
x.lne.set_x2(b.i)
if b.h > x.bx.get_top()
x.brL := true
x.brZ := true
alert('buyside liquidity level breached for ' + syminfo.ticker)
x.bxz.set_lefttop(b.i - 1, math.min(x.ln.get_y1() + marBuy * (atr), b.h))
x.bxz.set_rightbottom(b.i + 1, x.ln.get_y1())
x.bxz.set_bgcolor(color.new(cLIQ_B, liqBuy ? 73 : 100))
else if x.brZ
if b.l > x.ln.get_y1() - marBuy * (atr) and b.h < x.ln.get_y1() + marBuy * (atr)
x.bxz.set_right(b.i + 1)
x.bxz.set_top(math.max(b.h, x.bxz.get_top()))
if liqBuy
x.lne.set_x2(b.i + 1)
else
x.brZ := false
for i = 0 to b_liq_S.size() - 1
x = b_liq_S.get(i)
if not x.brL
x.lne.set_x2(b.i)
if b.l < x.bx.get_bottom()
x.brL := true
x.brZ := true
alert('sellside liquidity level breached for ' + syminfo.ticker)
x.bxz.set_lefttop(b.i - 1, x.ln.get_y1())
x.bxz.set_rightbottom(b.i + 1, math.max(x.ln.get_y1() - marSel * (atr), b.l))
x.bxz.set_bgcolor(color.new(cLIQ_S, liqSel ? 73 : 100))
else if x.brZ
if b.l > x.ln.get_y1() - marSel * (atr) and b.h < x.ln.get_y1() + marSel * (atr)
x.bxz.set_rightbottom(b.i + 1, math.min(b.l, x.bxz.get_bottom()))
if liqSel
x.lne.set_x2(b.i + 1)
else
x.brZ := false
if lqVoid and per
bull = b.l - b.h > atr200 and b.l > b.h and b.c > b.h
bear = b.l - b.h > atr200 and b.h < b.l and b.c < b.l
if bull
l = 13
if bull
st = math.abs(b.l - b.l ) / l
for i = 0 to l - 1
array.push(b_liq_V, box.new(b.i - 2, b.l + i * st, b.i, b.l + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
else
st = math.abs(b.l - b.h ) / l
for i = 0 to l - 1
if lqText and i == 0
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_bottom, text_color = na, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
else
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
if bear
l = 13
if bear
st = math.abs(b.h - b.h) / l
for i = 0 to l - 1
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
else
st = math.abs(b.l - b.h) / l
for i = 0 to l - 1
if lqText and i == l - 1
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_top, text_color = na, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
else
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
if b_liq_V.size() > 0
qt = b_liq_V.size()
for bn = qt - 1 to 0
if bn < b_liq_V.size()
cb = b_liq_V.get(bn)
ba = math.avg(cb.get_bottom(), cb.get_top())
if math.sign(b.c - ba) != math.sign(b.c - ba) or math.sign(b.c - ba) != math.sign(b.l - ba) or math.sign(b.c - ba) != math.sign(b.h - ba)
b_liq_V.remove(bn)
else
cb.set_right(b.i + 1)
if b.i - cb.get_left() > 21
cb.set_text_color(color.new(color.gray, 25))
//-----------------------------------------------------------------------------}
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi > C_BodyHi and C_BodyLo < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
patternLabelPosLow = low - (ta.atr(30) * 0.6)
patternLabelPosHigh = high + (ta.atr(30) * 0.6)
label_color_bearish = input(color.rgb(255, 82, 82, 90), "Label Color Bearish")
label_color_bullish = input(color.rgb(33, 149, 243, 90), "Label Color Bullish")
C_MarubozuBlackBearishNumberOfCandles = 1
C_MarubozuWhiteBullishNumberOfCandles = 1
C_MarubozuShadowPercentBearish = 5.0
C_MarubozuShadowPercentWhite = 5.0
C_MarubozuBlackBearish = C_BlackBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentBearish/100*C_Body and C_DnShadow <= C_MarubozuShadowPercentBearish/100*C_Body and C_BlackBody
C_MarubozuWhiteBullish = C_WhiteBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentWhite/100*C_Body and C_DnShadow <= C_MarubozuShadowPercentWhite/100*C_Body and C_WhiteBody
combined_alert_condition = C_MarubozuBlackBearish or C_MarubozuWhiteBullish
alertcondition(combined_alert_condition, title = "Marubozu Pattern Detected", message = "A Marubozu pattern has been detected!")
if C_MarubozuBlackBearish
var ttBearishMarubozuBlack = "Marubozu Black\nThis is a candlestick that has no shadow, which extends from the red-bodied candle at the open, the close, or even at both. In Japanese, the name means “close-cropped” or “close-cut.” The candlestick can also be referred to as Bald or Shaven Head."
label.new(bar_index, patternLabelPosHigh, text="MB", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishMarubozuBlack)
if C_MarubozuWhiteBullish
var ttBullishMarubozuWhite = "Marubozu White\nA Marubozu White Candle is a candlestick that does not have a shadow that extends from its candle body at either the open or the close. Marubozu is Japanese for “close-cropped” or “close-cut.” Other sources may call it a Bald or Shaven Head Candle."
label.new(bar_index, patternLabelPosLow, text="MW", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishMarubozuWhite)
//--------------//
C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options= )
if trendRule == trendRule1
priceAvg = ta.sma(close, 50)
C_DownTrend := close < priceAvg
C_UpTrend := close > priceAvg
if trendRule == trendRule2
sma200 = ta.sma(close, 200)
sma50 = ta.sma(close, 50)
C_DownTrend := close < sma50 and sma50 < sma200
C_UpTrend := close > sma50 and sma50 > sma200
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody and C_SmallBody and close >= open and open <= close and ( close > open or open < close )
alertcondition(C_EngulfingBullish, title = "New pattern detected", message = "New Engulfing – Bullish pattern detected")
if C_EngulfingBullish
var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_UpTrend and C_BlackBody and C_LongBody and C_WhiteBody and C_SmallBody and close <= open and open >= close and ( close < open or open > close )
alertcondition(C_EngulfingBearish, title = "New pattern detected", message = "New Engulfing – Bearish pattern detected")
if C_EngulfingBearish
var ttBearishEngulfing = "Engulfing\nAt the end of a given uptrend, a reversal pattern will most likely appear. During the first day, this candlestick pattern uses a small body. It is then followed by a day where the candle body fully overtakes the body from the day before it and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to fully overtake the range (high to low), rather only the open and the close."
label.new(bar_index, patternLabelPosHigh, text="BE", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEngulfing)
//--------------//
// EMA 20 50 200
//-----------------------------------------------------------------------------{
shortest = ta.ema(close, 20)
short = ta.ema(close, 50)
long = ta.ema(close, 200)
color c0 = color.new(color.orange, 50)
color c1 = color.new(color.red, 80)
color c2 = color.new(color.blue, 80)
color c3 = color.new(#2195f3, 30)
plot(shortest, color = c0)
plot(short, color = c1)
plot(long, color = c2)
plot(ta.cross(short, long) ? short : na, style = plot.style_cross, linewidth = 4,color = c3)
//------------------------------------------------------------------------------
// Nadaraya-Watson Envelope
//-----------------------------------------------------------------------------{
length2 = input.float(500,'Window Size',maxval=500,minval=0)
h1 = input.float(10.,'Bandwidth')
mult = input.float(3.)
srcUpperBand = input.source(low,'Source Upper Band')
src1 = input.source(high,'Source Lower Band')
up_col = input.color(#ff1100,'Colors',inline='col')
dn_col = input.color(#39ff14,'',inline='col')
show_bands = input(false, 'Show Bands')
show_sma_7_low_1 = input(false, 'Show SMA 7 LOW +1')
show_sma_7_low_7 = input(false, 'Show SMA 7 LOW -7')
show_sma_30_high = input(false, 'Show SMA 30 HIGH')
//----
var k = 2
var upper1 = array.new_line(0)
var lower1 = array.new_line(0)
sma7_low = ta.sma(low, 7)
sma30_high = ta.sma(high, 30)
strDownArrows = "↓▼↓"
strUpArrows = "↑▲↑"
RoundUp(number, decimals) =>
factor = math.pow(10, decimals)
math.ceil(number * factor) / factor
plot(show_sma_7_low_1?sma7_low:na, color=color.rgb(255, 235, 59, 81), title="SMA 7 LOW +1", offset=+1, linewidth=1)
plot(show_sma_7_low_7?sma7_low:na, color=color.rgb(255, 235, 59, 81), title="7 sma", offset=-7, linewidth=1)
plot(show_sma_30_high ? sma30_high:na, color=color.purple, title="SMA 30 High", linewidth=1)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length2/k-1
array.push(upper1,line.new(na,na,na,na))
array.push(lower1,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
yUpper = array.new_float(0)
sum_upper_e = 0.
sum_e = 0.
for i = 0 to length2-1
sum_upper = 0.
sumw_upper = 0.
sum = 0.
sumw = 0.
for j = 0 to length2-1
w = math.exp(-(math.pow(i-j,2)/(h1*h1*2)))
sum_upper += srcUpperBand *w
sum += src1 *w
sumw += w
y_upper_2 = sum_upper/sumw
sum_upper_e += math.abs(srcUpperBand - y_upper_2)
array.push(yUpper,y_upper_2)
y2 = sum/sumw
sum_e += math.abs(src1 - y2)
array.push(y,y2)
mae_upper = sum_upper_e/length2*mult
mae = sum_e/length2*mult
for i = 1 to length2-1
upper_y2 = array.get(yUpper,i)
upper_y1 = array.get(yUpper,i-1)
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper1,i/k)
dn := array.get(lower1,i/k)
//draw borders bands
if show_bands
lset(up,n-i+1,upper_y1 + mae_upper,n-i,upper_y2 + mae_upper,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
//draw fractals
//if src > y1 + mae and src < y1 + mae
// label.new(n-i,src ,strDownArrows,color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
//if src < y1 - mae and src > y1 - mae
// label.new(n-i,src ,strUpArrows,color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
//draw sma 30 high signals
if sma30_high > upper_y1 + mae_upper and sma30_high < upper_y2 + mae_upper
label.new(n-i,srcUpperBand +mae_upper,strDownArrows,color=#00000000,style=label.style_label_down,textcolor=#ec0505,textalign=text.align_center)
//if sma30_high < y1 - mae and sma30_high > y2 - mae
// label.new(n-i,src ,strUpArrows,color=#00000000,style=label.style_label_down,textcolor=#ec05af,textalign=text.align_center)
//draw sma 7 low signals
if sma7_low > upper_y1 + mae_upper and sma7_low < upper_y2 + mae_upper
label.new(n-i,src1 ,strDownArrows,color=#00000000,style=label.style_label_down,textcolor=color.orange,textalign=text.align_center)
if sma7_low < y1 - mae and sma7_low > y2 - mae
label.new(n-i,src1 -mae,strUpArrows,color=#00000000,style=label.style_label_up,textcolor=color.rgb(16, 177, 4),textalign=text.align_center)
cross_up := array.get(yUpper,0) + mae_upper
cross_dn := array.get(y,0) - mae
sma7_crossover = ta.crossover(sma7_low,cross_up)
sma7_crossunder = ta.crossunder(sma7_low,cross_dn)
sma30_crossover = ta.crossover(sma30_high,cross_up)
sma30_crossunder = ta.crossunder(sma30_high,cross_dn)
alertcondition(sma30_crossunder or sma7_crossunder,title="LONG", message='LONG: {{ticker}}/{{interval}} at price {{close}} on {{exchange}}' )
alertcondition(sma7_crossover or sma30_crossover,title="SHORT", message='SHORT: {{ticker}}/{{interval}} at price {{close}} on {{exchange}}' )
//------------------------------------------------------------------------------
//SMT Divergences
//-----------------------------------------------------------------------------{
length3 = input.int(3, 'Pivot Lookback', minval = 2)
//Symbol A
useSym1 = input(true, 'Comparison Symbol', inline = 'symA')
sym1 = input.symbol('CME_MINI_DL:ES1!', '', inline = 'symA')
//Symbol B
useSym2 = input(true, 'Comparison Symbol', inline = 'symB')
sym2 = input.symbol('CBOT_MINI_DL:YM1!', '', inline = 'symB')
//Style
bullDivCss = input.color(#ff110082, 'Swing High', group = 'Style')
bearDivCss = input.color(#2156f380, 'Swing Low', group = 'Style')
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
get_hl() =>
//Swing highs divergences
get_divergence(ph1, y2, sym_y2, css)=>
var float y1 = na
var float sym_y1 = na
var int x1 = na
var smt = 0
if y2 != y2 and sym_y2 != sym_y2
//Test for SMT
if (y2 - y1) * (sym_y2 - sym_y1) < 0
line.new(n , y2, x1, y1, color = css)
smt += 1
sym_y1 := sym_y2
y1 := y2
x1 := n
else if (ph1 and y2 > y2 ) or (not ph1 and y2 < y2 )
sym_y1 := na
y1 := y2
x1 := n
smt
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
var phN = 0, var plN = 0
var ph_smt1 = 0.
var pl_smt1 = 0.
var ph_smt2 = 0.
var pl_smt2 = 0.
ticker1 = syminfo.ticker(sym1)
ticker2 = syminfo.ticker(sym2)
//-----------------------------------------------------------------------------}
//Detect swing highs/lows and divergences
//-----------------------------------------------------------------------------{
ph1 = fixnan(ta.pivothigh(length3, length3))
pl1 = fixnan(ta.pivotlow(length3, length3))
phN += ph1 != ph1 ? 1 : 0
plN += pl1 != pl1 ? 1 : 0
//Comparison symbol pivots
= request.security(sym1, timeframe.period, get_hl())
= request.security(sym2, timeframe.period, get_hl())
//Detect swing high divergences
if useSym1
sym_ph1 = fixnan(ta.pivothigh(h11, length3, length3))
sym_pl1 = fixnan(ta.pivotlow(l1, length3, length3))
ph_smt1 := get_divergence(true, ph1, sym_ph1, bullDivCss)
pl_smt1 := get_divergence(false, pl1, sym_pl1, bearDivCss)
if useSym2
sym_ph2 = fixnan(ta.pivothigh(h21, length3, length3))
sym_pl2 = fixnan(ta.pivotlow(l2, length3, length3))
ph_smt2 := get_divergence(true, ph1, sym_ph2, bullDivCss)
pl_smt2 := get_divergence(false, pl1, sym_pl2, bearDivCss)
txt = ''
if ph1 != ph1
if ph_smt1 > ph_smt1
txt += ticker1
if ph_smt2 > ph_smt2
txt += txt != '' ? ' | ' : ''
txt += ticker2
if txt != ''
label.new(n , ph1, txt
, color = bullDivCss
, style = label.style_label_down
, textcolor = color.white
, size = size.tiny)
else
if pl_smt1 > pl_smt1
txt += ticker1
if pl_smt2 > pl_smt2
txt += txt != '' ? ' | ' : ''
txt += ticker2
if txt != ''
label.new(n , pl1, txt
, color = bearDivCss
, style = label.style_label_up
, textcolor = color.white
, size = size.tiny)
//-----------------------------------------------------------------------------}
//Tables
//-----------------------------------------------------------------------------{
if barstate.isfirst and showDash
tb.cell(1, 0, 'Swing High', text_color = color.white)
tb.cell(2, 0, 'Swing Low', text_color = color.white)
tb.cell(0, 1, ticker1, text_color = color.white)
tb.cell(0, 2, ticker2, text_color = color.white)
if barstate.islast and showDash
//Symbol 1
tb.cell(1, 1, str.format('{0} ({1, number, percent})', ph_smt1, ph_smt1 / phN)
, text_color = bullDivCss)
tb.cell(2, 1, str.format('{0} ({1, number, percent})', pl_smt1, pl_smt1 / plN)
, text_color = bearDivCss)
//Symbol 2
tb.cell(1, 2, str.format('{0} ({1, number, percent})', ph_smt2, ph_smt2 / phN)
, text_color = bullDivCss)
tb.cell(2, 2, str.format('{0} ({1, number, percent})', pl_smt2, pl_smt2 / plN)
, text_color = bearDivCss)
//-----------------------------------------------------------------------------
// Imbalance Finder With Pip Target Box
//-----------------------------------------------------------------------------{
showema = input(defval=false, title='Show all EMAs', group='Plot EMA ')
Overridetargetsize = input(defval=false, title='Change Standard Target Size', group='Targets')
Targetssize = input.float(title='Pips for Target', defval=0.0001, minval=0.0001, group = 'Targets')
color black100 = color.new(color.black,100)
color green75 = color.new(color.green,75)
color green0 = color.new(#4caf4f, 10)
color aqua0 = color.new(color.aqua, 0)
color black0 = color.new(color.black, 0)
color blue0 = color.new(#0F52BA, 0)
color gray0 = color.new(#787b86, 100)
color orange0 = color.new(#ff8c00, 10)
color red0 = color.new(#ff5252, 10)
color red75 = color.new(color.red,75)
color white0 = color.new(color.white, 0)
color yellow0 = color.new(#fff700, 100)
bool showgreydiamond = input(defval=false, title='Show Diamond For Back Testing' ,group='=== Information ===')
LabelDigitDisplay =
syminfo.ticker == 'AUDCAD' == true ? '#.#####' : syminfo.ticker == 'AUDCHF' == true ? '#.#####' : syminfo.ticker == 'AUDJPY' == true ? '#.###' : syminfo.ticker == 'AUDNZD' == true ? '#.#####' :
syminfo.ticker == 'AUDUSD' == true ? '#.#####' : syminfo.ticker == 'CADCHF' == true ? '#.#####' : syminfo.ticker == 'CADJPY' == true ? '#.###' : syminfo.ticker == 'CHFJPY' == true ? '#.###' :
syminfo.ticker == 'EURAUD' == true ? '#.#####' : syminfo.ticker == 'EURCAD' == true ? '#.#####' : syminfo.ticker == 'EURCHF' == true ? '#.#####' : syminfo.ticker == 'EURGBP' == true ? '#.#####' :
syminfo.ticker == 'EURJPY' == true ? '#.###' : syminfo.ticker == 'EURNZD' == true ? '#.#####' : syminfo.ticker == 'EURUSD' == true ? '#.#####' : syminfo.ticker == 'GBPAUD' == true ? '#.#####' :
syminfo.ticker == 'GBPCAD' == true ? '#.#####' : syminfo.ticker == 'GBPCHF' == true ? '#.#####' : syminfo.ticker == 'GBPJPY' == true ? '#.###' : syminfo.ticker == 'GBPNZD' == true ? '#.#####' :
syminfo.ticker == 'GBPUSD' == true ? '#.#####' : syminfo.ticker == 'NZDCAD' == true ? '#.#####' : syminfo.ticker == 'NZDCHF' == true ? '#.#####' : syminfo.ticker == 'NZDJPY' == true ? '#.###':
syminfo.ticker == 'NZDUSD' == true ? '#.#####' : syminfo.ticker == 'USDCAD' == true ? '#.#####' : syminfo.ticker == 'USDCHF' == true ? '#.#####' : syminfo.ticker == 'USDJPY' == true ? '#.###':
syminfo.ticker == 'GOLD' == true ? '#.##' : syminfo.ticker == 'US100' == true ? '#.##' : syminfo.ticker == 'US30' == true ? '#.##' : syminfo.ticker == 'US500' == true ? '#.##' : syminfo.ticker == 'DE40' == true ? '#.##' : '#.#####'
PipsMultiplier =
syminfo.ticker == 'AUDCAD' == true ? 0.00050 : syminfo.ticker == 'AUDCHF' == true ? 0.00050 : syminfo.ticker == 'AUDJPY' == true ? 00.050 : syminfo.ticker == 'AUDNZD' == true ? 0.00050 :
syminfo.ticker == 'AUDUSD' == true ? 0.00050 : syminfo.ticker == 'CADCHF' == true ? 0.00050 : syminfo.ticker == 'CADJPY' == true ? 00.050 : syminfo.ticker == 'CHFJPY' == true ? 00.050:
syminfo.ticker == 'EURAUD' == true ? 0.00050 : syminfo.ticker == 'EURCAD' == true ? 0.00050 : syminfo.ticker == 'EURCHF' == true ? 0.00050 : syminfo.ticker == 'EURGBP' == true ? 0.00050 :
syminfo.ticker == 'EURJPY' == true ? 00.050 : syminfo.ticker == 'EURNZD' == true ? 0.00050 : syminfo.ticker == 'EURUSD' == true ? 0.00050 : syminfo.ticker == 'GBPAUD' == true ? 0.00050 :
syminfo.ticker == 'GBPCAD' == true ? 0.00050 : syminfo.ticker == 'GBPCHF' == true ? 0.00050 : syminfo.ticker == 'GBPJPY' == true ? 00.050 : syminfo.ticker == 'GBPNZD' == true ? 0.00050 :
syminfo.ticker == 'GBPUSD' == true ? 0.00050 : syminfo.ticker == 'NZDCAD' == true ? 0.00050 : syminfo.ticker == 'NZDCHF' == true ? 0.00050 : syminfo.ticker == 'NZDJPY' == true ? 00.050:
syminfo.ticker == 'NZDUSD' == true ? 0.00050 : syminfo.ticker == 'USDCAD' == true ? 0.00050 : syminfo.ticker == 'USDCHF' == true ? 0.00050 : syminfo.ticker == 'USDJPY' == true ? 00.050:
syminfo.ticker == 'GOLD' == true ? 1.5 : syminfo.ticker == 'US100' == true ? 10 : syminfo.ticker == 'US30' == true ? 25 : syminfo.ticker == 'US500' == true ? 10 : syminfo.ticker == 'DE40' == true ? 10 : 1
Targettouse = Overridetargetsize ? Targetssize : PipsMultiplier
Imbcol = input.color(yellow0, 'Imbalance Colour', inline="1" ,group='=== Information ===')
Dimcol = input.color(gray0, 'Imbalance Colour', inline="1" ,group='=== Information ===')
TopImbalance = low <= open and high >= close
TopImbalancesize = low - high
if TopImbalance and TopImbalancesize > 0
BOX1 = box.new(left=bar_index , top=low , right=bar_index , bottom=high )
box.set_bgcolor(BOX1, Imbcol )
box.set_border_color(BOX1, Imbcol )
BottomInbalance = high >= open and low <= close
BottomInbalancesize = low - high
if BottomInbalance and BottomInbalancesize > 0
BOX2 = box.new(left=bar_index , top=low , right=bar_index , bottom=high )
box.set_bgcolor(BOX2, Imbcol )
box.set_border_color(BOX2, Imbcol )
DownImbalance = TopImbalance and TopImbalancesize > 0
plotshape(DownImbalance and showgreydiamond, style=shape.diamond, location=location.abovebar, color=Dimcol, size=size.tiny)
UpImbalance = BottomInbalance and BottomInbalancesize > 0
plotshape(UpImbalance and showgreydiamond, style=shape.diamond, location=location.belowbar, color=Dimcol, size=size.tiny)
DownSell = close >open and closeopen
boxcolourtop = UpBuy ? green0 : black100
boxcolourbottom = DownSell ? red0 : black100
boxcolourtopfill = UpBuy ? green75 : black100
boxcolourbottomfill = DownSell ? red75 : black100
BottomLabel = label.new(x=bar_index, y=high+(Targettouse/3), xloc=xloc.bar_index)
label.set_text(BottomLabel, text
= "\n \n Entry = " + str.tostring(close,LabelDigitDisplay)
+ "\n Stop Loss = " + str.tostring(high,LabelDigitDisplay)
+ "\n Take Profit = " + str.tostring(close-PipsMultiplier,LabelDigitDisplay)
+ "\n Target Size = " + str.tostring(PipsMultiplier,LabelDigitDisplay))
label.set_textalign(BottomLabel, text.align_left)
label.set_style(BottomLabel, label.style_label_left)
label.set_color(BottomLabel, black100)
label.set_textcolor(BottomLabel, boxcolourbottom)
label.delete(BottomLabel )
Bottom = box.new(left=bar_index , top=low, right=bar_index , bottom=low-Targettouse, xloc=xloc.bar_index)
box.set_right(Bottom,right=box.get_right(id=Bottom)+10)
box.set_bgcolor(Bottom , color=boxcolourbottomfill )
box.set_border_color(Bottom , color=boxcolourbottom)
box.delete(Bottom )
TopLabel = label.new(x=bar_index, y=low-(Targettouse/3), xloc=xloc.bar_index)
label.set_text(TopLabel, text
= "\n \n Entry = " + str.tostring(close,LabelDigitDisplay)
+ "\n Stop Loss = " + str.tostring(low,LabelDigitDisplay)
+ "\n Take Profit = " + str.tostring(close+Targettouse,LabelDigitDisplay)
+ "\n Target Size = " + str.tostring(PipsMultiplier,LabelDigitDisplay))
label.set_textalign(TopLabel, text.align_left)
label.set_style(TopLabel, label.style_label_left)
label.set_color(TopLabel, black100)
label.set_textcolor(TopLabel, boxcolourtop )
label.delete(TopLabel )
Top = box.new(left=bar_index , top=high+Targettouse, right=bar_index , bottom=high, xloc=xloc.bar_index)
box.set_right(Top,right=box.get_right(id=Top)+10)
box.set_bgcolor(Top , color=boxcolourtopfill )
box.set_border_color(Top, color=boxcolourtop )
box.delete(Top )
ema13colour = showema ? red0 : black100
ema35colour = showema ? orange0 : black100
ema50colour = showema ? aqua0 : black100
offset = input.int(title='Offset', defval=0, minval=-500, maxval=500)
emalen1513 =26 //input.int(13, minval=1, title='Length 13 EMA 15 Min', group='=== EMA Information ===')
emasrc1513 = close
EMA13 = request.security(syminfo.tickerid, '1', ta.ema(emasrc1513, emalen1513))
plot(EMA13, title='EMA 13 15 Min', color=ema13colour, linewidth=1, offset=offset)
emalen1535 = 63 //input.int(35, minval=1, title='Length 35 EMA 15 Min', group='=== EMA Information ===')
emasrc1535 = close
EMA35 = request.security(syminfo.tickerid, '1', ta.ema(emasrc1535, emalen1535))
plot(EMA35, title='EMA 35 15 Min', color=ema35colour, linewidth=1, offset=offset)
emalen1550 = 100 //input.int(50, minval=1, title='Length 50 EMA 15 Min', group='=== EMA Information ===')
emasrc1550 = close
EMA50 = request.security(syminfo.tickerid, '1', ta.ema(emasrc1550, emalen1550))
plot(EMA50, title='EMA 50 15 Min', color=ema50colour, linewidth=2, offset=offset)
Up = EMA13 > EMA35 and EMA35 > EMA50
Down = EMA13 < EMA35 and EMA35 < EMA50
plotshape(Up , title='Up', style=shape.square, location=location.bottom, color=green0, size=size.tiny)
plotshape(Down , title='Down', style=shape.square, location=location.bottom, color=red0, size=size.tiny)
plotshape(not Down and not Up , title='Warning', style=shape.square, location=location.bottom, color=orange0, size=size.tiny)
alertcondition(Up and not Up , title='Buy Switch On', message='Buy Switch On')
alertcondition(Down and not Down , title='Sell Switch On', message='Sell Switch On')
alertcondition(Up and not Up , title='Warning Stop any More Buys', message='Warning Stop any More Buys')
alertcondition(Down and not Down, title='Warning Stop any More Sells', message='Warning Stop any More Sells')
alertcondition(open > close or close <= open , title='Every Bar Alert', message='Every Bar Alert')
//-----------------------------------------------------------------------------}
//SUPLLY AND DEMAND
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------}
//SUPPORT AND RESISTANCE MTF
//-----------------------------------------------------------------------------{
const bool DEBUG = false
const int timeframeCount = 3
const float touchATR = 1.0 / 30.0
const float retestATR = 1.0 / 30.0
const float labelOffsetY = 1.5
const int labelOffsetsXIndex = 30
const int maxPivotsBackSR = 15
const int retestLabelEveryXBars = 3
const int maxTraverse = 250 // Affects bar history limit. Default value 250.
const int maxRetestLabels = 100
const int maxSupports = 3
const int maxResistances = 3
const int debug_maxPivotLabels = 25
// _____ INPUTS _____
resistanceSupportCount = input.int(3, "Support & Resistance Count", options = , group = "General Configuration", display = display.none)
pivotRange = input.int(15, "Pivot Range", options = , tooltip = "Increase for more general pivots, decrease for more private pivots.", group = "General Configuration", display = display.none)
strength = input.int(1, "Strength", options = , tooltip = "X many times price touched relative price area in order to be considered a support/resistance zone.", group = "General Configuration", display = display.none)
expandLines = input.bool(true,"Expand Lines & Zones", group = "General Configuration", display = display.none)
enableZones = input.bool(false, "Enable Zones", group = "Support & Resistance Zones", display = display.none)
zoneWidthType = input.string("Dynamic", "Zone Width Type", options = , group = "Support & Resistance Zones", display = display.none)
zoneWidth = input.int(1, "Fixed Zone Width", options = , group = "Support & Resistance Zones", display = display.none)
timeframe1Enabled = input.bool(true, title = "", group = "Timeframes", inline = "timeframe1", display = display.none)
timeframe1 = input.timeframe("", title = "", group = "Timeframes", inline = "timeframe1", display = display.none)
timeframe2Enabled = input.bool(true, title = "", group = "Timeframes", inline = "timeframe2", display = display.none)
timeframe2 = input.timeframe("240", title = "", group = "Timeframes", inline = "timeframe2", display = display.none)
timeframe3Enabled = input.bool(false, title = "", group = "Timeframes", inline = "timeframe3", display = display.none)
timeframe3 = input.timeframe("30", title = "", group = "Timeframes", inline = "timeframe3", display = display.none)
showBreaks = input.bool(true,"Show Breaks", group = "Breaks & Retests", inline = "ShowBR", display = display.none)
showRetests = input.bool(true,"Show Retests", group = "Breaks & Retests", inline = "ShowBR", display = display.none)
avoidFalseBreaks = input.bool(true, "Avoid False Breaks", group = "Breaks & Retests", display = display.none)
falseBreakoutVolumeThresholdOpt = input.float(0.3, "Break Volume Threshold", minval=0.1, maxval=1.0, step=0.1, group = "Breaks & Retests", tooltip = "Only taken into account if Avoid False Breakouts is enabled.\nHigher values mean it's less likely to be a break.", display = display.none)
inverseBrokenLineColor = input.bool(true, "Inverse Color After Broken", tooltip = "Needs Show Breaks & Expand Lines option enabled.", group = "Breaks & Retests", display = display.none)
falseBreakoutVolumeThreshold = falseBreakoutVolumeThresholdOpt * 100.0
lineStyle = input.string("....", "Line Style", , group = "Style", display = display.none)
lineWidth = input.int(1, "Line Width", minval = 1, group = "Style", display = display.none)
supportColor = input.color(#08998180, "Support Color", group = "Style", inline = "RScolors", display = display.none)
resistanceColor = input.color(#f2364580, "Resistance Color", group = "Style", inline = "RScolors", display = display.none)
textColor = input.color(#11101051, "Text Color", group = "Style", inline = "RScolors", display = display.none)
labelsAlign = input.string("Right", "Align Labels", options = , group = "Style", tooltip = "Will only work when zones are disabled.", display = display.none)
enableRetestAlerts = input.bool(true, "Enable Retest Alerts", tooltip = "Needs Show Retests option enabled.", group = "Alerts", display = display.none)
enableBreakAlerts = input.bool(true, "Enable Break Alerts", group = "Alerts", display = display.none)
memoryOptimizatonEnabled = input.bool(true, "Enable Memory Optimization", tooltip = "Enable this option if you encounter memory errors.", group = "Advanced", display = display.none)
// _____ INPUTS END _____
// _____ DEBUG OPTIONS _____
debug_labelPivots = not DEBUG ? "None" : input.string("None", title = " Label Pivots", group = "DEBUG", options = , tooltip = "All -> Debugs all pivot labels.\nRS -> Debugs RS pivot labels.\nNone -> Debugs none of the last R&S; pivots.")
debug_pivotLabelText = not DEBUG ? false : input.bool(false, title = " Pivot Label Text", group = "DEBUG")
debug_showBrokenOnLabel = not DEBUG ? false : input.bool(false, " Show Broken Text On Label", group = "DEBUG")
debug_removeDuplicateRS = not DEBUG ? true : input.bool(true, " Remove Duplicate RS", group = "DEBUG")
debug_lastXResistances = not DEBUG ? 3 : input.int(3, " Show Last X Resistances", minval = 0, maxval = maxResistances, group = "DEBUG")
debug_lastXSupports = not DEBUG ? 3 : input.int(3, " Show Last X Supports", minval = 0, maxval = maxSupports, group = "DEBUG")
debug_enabledHistory = not DEBUG ? true : input.bool(true, " Enable History", group = "DEBUG")
debug_maxHistoryRecords = not DEBUG ? 10 : input.int(10, " Max History Records", options = , group = "DEBUG")
// _____ DEBUG OPTIONS END _____
atr1 = ta.atr(30)
createRSLine (color) =>
line.new(na, na, na, na, extend = expandLines ? extend.both : extend.none, xloc=xloc.bar_time, color = color, width = lineWidth, style = lineStyle == "----" ? line.style_dashed : lineStyl
Combined Indicator: SMMA+Fractals+SessionsJust a combination of 3 main indicator; 5SMMA + Fractal + Session. Feel free to use it.
Williams Fractals + Horizontal Linethe breakthrough of the nearest fractal by the body of the candle is highlighted by a segment
Stoch_RSI_ChartEnhanced Stochastic RSI Divergence Indicator with VWAP Filter for Charts
This custom indicator builds upon the classic Stochastic RSI to automatically detect both regular and hidden divergences. It’s designed to help traders spot potential market reversals or continuations using two methods for divergence detection (fractal‑ and pivot‑based) while offering optional VWAP filtering for confirmation.
Key Features
Stoch RSI Calculation
The indicator computes a smoothed Stoch RSI using configurable parameters for RSI length, stochastic length, and smoothing periods. An option to average the K and D lines provides a cleaner momentum view.
Divergence Detection via Fractals & Pivots
Fractal-Based Divergences:
Looks for 4-candle patterns to identify higher-highs or lower-lows in the price that are not confirmed by the oscillator, signaling potential reversals.
Pivot-Based Divergences:
Utilizes TradingView’s built-in pivot functions to find divergence conditions over adjustable pivot ranges.
Regular vs. Hidden Divergences:
Regular Divergence: Occurs when price makes a new extreme (higher high or lower low) while the Stoch RSI fails to follow suit.
Hidden Divergence: Indicates potential trend continuations when the oscillator diverges against the established price trend.
Optional VWAP Filtering
The script includes two optional VWAP filters that work as follows:
VWAP Filter on Regular Divergences:
Only confirms regular divergence signals if the current price satisfies the VWAP condition (e.g., price is above VWAP for bullish signals, below VWAP for bearish signals).
VWAP Filter on Hidden Divergences:
Similarly, hidden divergence signals are validated only when the price meets specific VWAP conditions, adding an extra layer of trend confirmation.
Customizable Alerts and Visual Labels
Easily configure divergence labels (“B” for bullish, “S” for bearish) and enable up to four alert conditions for real‑time notifications when a divergence occurs.
Credits & History:
Log RSI by @fskrypt
Divergence Detection originally by @RicardoSantos (with edits from @JustUncleL)
Further Edits by @NeoButane on August 8, 2018
Latest Edits by @FYMD on June 1, 2024
Stoch_RSIStochastic RSI – Advanced Divergence Indicator
This custom indicator is an advanced version of the Stochastic RSI that not only smooths and refines the classic RSI input but also automatically detects both regular and hidden divergences using two powerful methods: fractal-based and pivot-based detection. Originally inspired by contributions from @fskrypt, @RicardoSantos, and later improved by developers like @NeoButane and @FYMD, this script has been fully refined for clarity and ease-of-use.
Key Features:
Dual Divergence Detection:
Fractal-Based Divergence: Uses a four-candle pattern to confirm top and bottom fractals for bullish and bearish divergences.
Pivot-Based Divergence: Employs TradingView’s built-in pivot functions for an alternate view of divergence conditions.
Customizable Settings:
The inputs are organized into logical groups (Stoch RSI settings, Divergence Options, Labels, and Market Open Settings) allowing you to adjust smoothing periods, RSI and Stochastic lengths, and divergence thresholds with a user-friendly interface.
Visual Enhancements:
Plots & Fills: The indicator plots both the K and D lines with corresponding fills and horizontal bands for quick visual reference.
Divergence Markers: Diamond shapes and labeled markers indicate regular and hidden divergences on the chart.
Market Open Highlighting: Optional histogram plots highlight the market open candle based on different timeframes for stocks versus non-forex symbols.
Accumulation-Distribution CandlesThis structural visualization tool maps each candle through the lens of Effort vs. Result, blending Volume, Range, and closing bias into a normalized pressure score. Candle bodies are dynamically color-coded using a five-tier system—from heavy accumulation to heavy distribution—revealing where energy is building, dispersing, or neutral. This helps to visually isolate Markup, Markdown, Re-accumulation, and Distribution at a glance.
The indicator calculates a strength score by multiplying price result (close minus open) by effort (volume or price range), smoothing this raw value using a Fibonacci-based EMA. (34 for standard, 55 for crypto; the higher crypto value acknowledges that 24/7 trading offers more hours per week or month than trad markets.) The result is standardized against its rolling deviation and clamped to a range. This score determines the visual tier:
• 💙 Dark Blue = heavy Accumulation (strong upward result on strong effort)
• 🩵 Pale Blue = mild Accumulation
• 🌚 Gray = neutral (low conviction or balance)
• 💛 Pale Yellow = mild Distribution
• 🧡 Deep Yellow = heavy Distribution (strong downward result on strong effort)
The tool is optimized for the 1D chart, where Wyckoff phases are most clearly expressed. However, it adapts well to lower timeframes when used selectively. Traders may hide the body coloring and enable only zone highlighting to preserve other candle overlays such as SUPeR TReND 2.718, which offers directional clarity and trend duration. This combination is especially useful on intraday charts (15m–1H) where microstructure matters but visual clutter must be avoided.
When used alongside other Volume overlays (such as the OBVX Conviction Bias) or Volatility indicators (such as the Asymmetric Turbulence Ribbon (ATR)), this indicator adds confluence to directional setups by contextualizing pressure with Volatility. For example: compression zones marked by ATR may align with persistent pale blue candles—indicating quiet Accumulation before expansion.
Optional Overlays:
Normally ON -
• 📌 Pin Bars , filtered by volume, to isolate wick-dominant reversals from key zones
• 💪🏻 Strong-Body Candles — fuchsia candles w/ high body-to-range ratio reflect conviction
• 🧯 Wick Absorption Candles — red candles w/ long wicks and low closing strength indicate failed pushes or absorbed breakouts
• 🟦/🟧 Zone Highlighting for candles above a defined Accumulation/Distribution threshold
Normally OFF -
• 🔺 Fractals (5-bar) to map swing pivots by underlying pressure tier (normally OFF)
• 🟥/🟩 Engulfing patterns, filtered by directional conviction (normally OFF)
The Pin Bar strategy benefits most from the zone logic—when a bullish pin bar appears in an Accumulation zone (esp. pale or dark blue), and Volume exceeds its rolling average, it may mark a spring or failed breakdown. Conversely, bearish pins in Distribution zones can mark rejection or resistance.
This is not a signal engine—it’s a narrative filter designed to slot cleanly into a multi-layered workflow of visual structure and informed execution. Use it to identify bias and phase. Then deploy trade triggers from tools like SUPeR TReND 2.718, or the liquidity flows shown the The Silver Lining or the AltSeasonality - MTF indicators, for example. The candle colors tell you who’s in control—the other tools tell you when to act.
Hull Moving Average Adaptive RSI (Ehlers)Hull Moving Average Adaptive RSI (Ehlers)
The Hull Moving Average Adaptive RSI (Ehlers) is an enhanced trend-following indicator designed to provide a smooth and responsive view of price movement while incorporating an additional momentum-based analysis using the Adaptive RSI.
Principle and Advantages of the Hull Moving Average:
- The Hull Moving Average (HMA) is known for its ability to track price action with minimal lag while maintaining a smooth curve.
- Unlike traditional moving averages, the HMA significantly reduces noise and responds faster to market trends, making it highly effective for detecting trend direction and changes.
- It achieves this by applying a weighted moving average calculation that emphasizes recent price movements while smoothing out fluctuations.
Why the Adaptive RSI Was Added:
- The core HMA line remains the foundation of the indicator, but an additional analysis using the Adaptive RSI has been integrated to provide more meaningful insights into momentum shifts.
- The Adaptive RSI is a modified version of the traditional Relative Strength Index that dynamically adjusts its sensitivity based on market volatility.
- By incorporating the Adaptive RSI, the HMA visually represents whether momentum is strengthening or weakening, offering a complementary layer of analysis.
How the Adaptive RSI Influences the Indicator:
- High Adaptive RSI (above 65): The market may be overbought, or bullish momentum could be fading. The HMA turns shades of red, signaling a possible exhaustion phase or potential reversals.
- Neutral Adaptive RSI (around 50): The market is in a balanced state, meaning neither buyers nor sellers are in clear control. The HMA takes on grayish tones to indicate this consolidation.
- Low Adaptive RSI (below 35): The market may be oversold, or bearish momentum could be weakening. The HMA shifts to shades of blue, highlighting potential recovery zones or trend slowdowns.
Why This Combination is Powerful:
- While the HMA excels in tracking trends and reducing lag, it does not provide information about momentum strength on its own.
- The Adaptive RSI bridges this gap by adding a clear visual layer that helps traders assess whether a trend is likely to continue, consolidate, or reverse.
- This makes the indicator particularly useful for spotting trend exhaustion and confirming momentum shifts in real-time.
Best Use Cases:
- Works effectively on timeframes from 1 hour (1H) to 1 day (1D), making it suitable for swing trading and position trading.
- Particularly useful for trading indices (SPY), stocks, forex, and cryptocurrencies, where momentum shifts are frequent.
- Helps identify not just trend direction but also whether that trend is gaining or losing strength.
Recommended Complementary Indicators:
- Adaptive Trend Finder: Helps identify the dominant long-term trend.
- Williams Fractals Ultimate: Provides key reversal points to validate trend shifts.
- RVOL (Relative Volume): Confirms significant moves based on volume strength.
This enhanced HMA with Adaptive RSI provides a powerful, intuitive visual tool that makes trend analysis and momentum interpretation more effective and efficient.
This indicator is for educational and informational purposes only. It should not be considered financial advice or a guarantee of performance. Always conduct your own research and use proper risk management when trading. Past performance does not guarantee future results.
BB ATR Fractal MMThe Bollinger Bands + ATR with Fractal indicator is a powerful combination of Bollinger Bands, ATR (Average True Range), and Fractal to help identify market volatility and potential entry/exit points on the chart.
Bollinger Bands help to assess the market’s volatility by calculating upper and lower bands based on the simple moving average (SMA) and standard deviation. It’s an excellent tool for identifying overbought and oversold conditions.
ATR (Average True Range) is used to measure market volatility. It helps determine how much the price is moving, and it can be used to adjust the Bollinger Bands, creating bands that reflect the current volatility more accurately.
Fractal helps to identify peaks and troughs in the market, supporting decision-making by highlighting potential reversal points. Fractals mark regions where price may reverse direction, making it easier to spot possible trade opportunities.
How to Use:
Bollinger Bands Upper and Lower Bands: These bands help to identify overbought or oversold conditions. If the price breaks above the upper band, the market may be overbought. If the price breaks below the lower band, the market may be oversold.
ATR: It indicates the volatility level of the market. When the market shows large volatility (ATR increases), the Bollinger Bands expand to reflect higher price swings.
Fractal: Arrows appear at the market’s peaks and troughs, helping identify entry points for buying (at fractal lows) or selling (at fractal highs). These signals can help you make trading decisions based on potential price reversals.
Adaptive Fractal Grid Scalping StrategyThis Pine Script v6 component implements an "Adaptive Fractal Grid Scalping Strategy" with an added volatility threshold feature.
Here's how it works:
Fractal Break Detection: Uses ta.pivothigh and ta.pivotlow to identify local highs and lows.
Volatility Clustering: Measures volatility using the Average True Range (ATR).
Adaptive Grid Levels: Dynamically adjusts grid levels based on ATR and user-defined multipliers.
Directional Bias Filter: Uses a Simple Moving Average (SMA) to determine trend direction.
Volatility Threshold: Introduces a new input to specify a minimum ATR value required to activate the strategy.
Trade Execution Logic: Places limit orders at grid levels based on trend direction and fractal levels, but only when ATR exceeds the volatility threshold.
Profit-Taking and Stop-Loss: Implements profit-taking at grid levels and a trailing stop-loss based on ATR.
How to Use
Inputs: Customize the ATR length, SMA length, grid multipliers, trailing stop multiplier, and volatility threshold through the input settings.
Visuals: The script plots fractal points and grid levels on the chart for easy visualization.
Trade Signals: The strategy automatically places buy/sell orders based on the detected fractals, trend direction, and volatility threshold.
Profit and Risk Management: The script includes logic for taking profits and setting stop-loss levels to manage trades effectively.
This strategy is designed to capitalize on micro-movements during high volatility and avoid overtrading during low-volatility trends. Adjust the input parameters to suit your trading style and market conditions.