Farley's Accumulation-Distribution Accelerator (ADA)Farley's ADA (From The Master Swing Trader)
What it is :
ADA is designed to track volume oscillations in the market and reduce the impact of shock events.
It observes the supply-demand dynamics within the market, which can trigger natural levels of price reversals.
How It Works
Volume and Price Relationship: ADA measures the lag between price and volume movements. It highlights when volume leads or lags behind price changes, helping traders identify potential reversals or trends.
Signal Generation: ADA can generate faster and cleaner signals compared to traditional indicators like On-Balance Volume (OBV).
Usage
Support and Resistance: ADA formations can help identify support and resistance levels and trendlines.
detect natural levels where price reversals might occur.
Trend Identification: Look for significant divergences between ADA and price action to identify potential trend reversals.
Volume Analysis: Use ADA to anticipate pauses in price movements when volume leads, and expect dynamic trends when ADA significantly moves ahead of price action.
ابحث في النصوص البرمجية عن "TRENDLINES"
[DarkTrader] Intersection Level & PredictionLinear Regression Function Reference by @RicardoSantos :
The Intersection Level Calculation process identifies critical price levels where significant market reactions are expected. It starts by analyzing historical price action and technical indicators to pinpoint key support and resistance levels.
Price Forecast Min represents the predicted lowest price level that the asset might reach, while Price Forecast Max indicates the anticipated highest price level. These projections are calculated using statistical methods and historical price patterns, allowing traders to anticipate potential support and resistance zones. By providing these forecasts, traders can better manage their risk and set more informed entry and exit points based on projected price movements.
Example Of Prediction (Before & After)
Predicting Future Price Movements :
Once the intersection levels are identified, the indicator uses various predictive models to forecast what price might do next when it approaches these levels. Here’s a breakdown of how it achieves this :
Price Reaction Analysis: The indicator assesses how price has historically reacted to similar intersection levels. For instance, if price has reversed from a certain support level multiple times, the indicator can predict a potential reversal or bounce when price approaches that level again.
Trend Continuation or Reversal: It examines the strength of the current trend by analyzing momentum indicators, volume, and the angle or direction of trendlines. Based on this, it can predict whether price is likely to break through an intersection level, signaling trend continuation, or bounce off it, indicating a potential reversal.
Confluence of Factors: The prediction mechanism becomes more accurate when multiple factors converge at the same intersection level. For example, if a trendline, moving average, and support zone all intersect at the same price point, the indicator predicts a stronger likelihood of significant price movement.
Market Volatility and Momentum: The indicator also considers current market volatility and momentum in its prediction. For example, if price approaches an intersection level with high momentum, it might predict a breakout, whereas low momentum might suggest consolidation or a weaker price reaction.
In this indicator, I utilize Linear Regression to forecast price movements by analyzing historical data trends. Linear Regression involves fitting a straight line to past price data, enabling me to model and project future price levels based on identified trends. This method calculates a trend line that best represents the historical price behavior, providing a foundation for predicting future price points. By extending this trend line, I can estimate where prices might move, incorporating a range to account for potential deviations. This approach helps in identifying both minimum and maximum forecasted prices, offering valuable insights into potential market directions.
Power Trends [UkutaLabs]█ OVERVIEW
The Power Trends Indicator is a versatile trading toolkit that offers unique insight into key price levels in the market. This script uses currently relevant price-action information to automatically detect pivot levels and use them to create powerful trendlines.
The aim of this script is to improve the trading experience of users by offering a versatile toolkit that can be used in a wide variety of trading strategies to help simplify the complexities of the market.
█ USAGE
The Power Trends Indicator will automatically identify pivot points in real-time using recent price-action information to ensure that all points being identified are relevant. Using these pivot points, the script then draws powerful trend lines that can be used as levels of resistance and support.
To ensure that only the most relevant information is being presented, only the most recent trend lines will be displayed on the user’s charts. As new trend lines are being drawn, older trend lines will become thinner so that traders can identify the most relevant lines at a glance.
The price of the most recent high and low pivot points will also be displayed on the chart and can be used as further levels of resistance and support.
When a recent pivot level is broken, it will be identified as a Break of Structure. This signifies that there may have been a change in market strength.
The Power Trends Indicator also supports multiple time frame mapping, allowing you to mirror the trend lines that would be drawn on higher time frame charts onto lower time frame charts. This feature allows traders to be aware of the market structure of multiple charts at a glance from a single chart.
When mirroring some higher time frame trend lines, lines may appear to not align properly with current time frame bars. This is done intentionally to ensure lines are being drawn accurately to their position on the higher time frame charts.
█ SETTINGS
Current Time Frame
• Display (On/Off): Determines whether or not trend lines are drawn from the current time frame.
• High Color: Determines the color of trend lines drawn on high pivots.
• Low Color: Determines the color of trend lines drawn on low pivots.
5 Minute (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the 5 minute higher time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the 5 minute higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the 5 minute higher time frame.
15 Minute (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the 15 minute higher time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the 15 minute higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the 15 minute higher time frame.
30 Minute (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the 30 minute higher time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the 30 minute higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the 30 minute higher time frame.
60 Minute (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the 60 minute higher time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the 60 minute higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the 60 minute higher time frame.
240 Minute (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the 240 minute higher time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the 240 minute higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the 240 minute higher time frame.
Daily (Higher Time Frame)
• Display (On/Off): Determines whether or not trend lines are drawn from the daily time frame.
• High Color: Determines the color of trend lines drawn on high pivots from the daily higher time frame.
• Low Color: Determines the color of trend lines drawn on low pivots from the daily higher time frame.
Universal RPPI Equities [SS Premium]Introducing the RPPI for Equities indicator.
Like its companion the RPPI for futures and indices, the RPPI for Equities is a compendium indicator of sorts, containing multiple different math based models for various equities tickers.
However, unlike the RPPI for futures and indices, the RPI for equities also has the ability to autogenerate a model that is tailored to the volatility of equities, if a base model does not exist within its compendium.
How Does it work and what does it do?
The RPPI contains multiple models that have been developed and corrected by myself, an example of which can be visualized in the above chart for the NYSE:DIS ticker. These models aim to forecast intraday, weekly and monthly price movements and help you to ascertain target prices that are realistic and achievable within your desired timeframe.
Which timeframes are availabe?
The indicator supports the following timeframes:
1. Daily
2. Weekly
3. Monthly
4. 3 Hour
5. 3 Month
What are some of the features?
So in addition to forecasting on the various timeframes, there are some innate functionalities and capabilities that have been programmed into the RPPI, in the same way they have been programmed into the futures version. These include:
1. Displaying Range Accumulation Zones & Standard Deviation
2. Performing autoregression assessments to help ascertain likely trajectory
3. Running Probability assessments on all timeframes
4. Displaying model performance via the demographic function.
While these features may not be new to you, I will go over them briefly below.
Displaying Range Accumulation Zones:
In the above example, you can see NVDA on the daily timeframe. The accumulation zones are displayed in blue and as a percentage value. We can see that the majority of the accumulation rested to the upside.
The prevailing theory with price accumulation is a ticker will frequently retrace and revisit areas of high accumulation, as these represent areas of demand and high volume.
Performing Autoregression Assessment
When you toggle on the autoregression assessment, you will get 3, trendlines. These represent the projected trajectory of the high, low and close. You can set your forecast length out as long or as short as you want.
The indicator will auto-select the best length and plot out the hypothesized trajectory based on the strongest identified trend.
Running Probabilities
To run probabilities, it is important to remember to be on the timeframe you wish to run the probabilities for. So, if you wish to run them on the daily timeframe, make sure your chart is on the daily and the indicator is set to "Daily" timeframe.
Once toggled on, you will get an assessment that looks like this:
This will display a breakdown of all previous instances of similar setups, and it will show you how many times each target were hit and give you an overall assessment of the likely sentiment, as well as the backtest results.
There are two types of probability options, "Momentum" and "Z-Score". The momentum is based on the underlying technicals, such as RSI and Stochastics; whereas, z-score is an assessment of standard deviation. If you want to know which one is "Best", you simply need look at the backtest results.
Displaying Model Performance:
To display model performance, go into the settings menu and select "Demographic Data".
As with the probabilities, please make sure you are set to the appropriate chart timeframe. If you are not, you will get an error message telling you to modify your timeframe.
This will break down how many times a ticker closes above or below its range, how many times the retracement target (GT) is hit and how many times, on average, a ticker hits the second high or second low target. This gives you some very useful stats to help you with your assessment (i.e. the TSLA example shows that, on the weekly timeframe, closing the week outside of the range only happens 11% of the time, so if we make a run outside of the range on a Monday or Tuesday, you know a good setup could be to short it and vice versa to the downside).
Warnings and Messages
This is not so much a feature of the indicator but just a reference to be aware of. In the settings menu, there is an option to "Show Warnings". This will prompt you with any warnings that exist on any ticker model. For example, if we look at the warnings for TSLA:
And AAPL:
Not all tickers have warnings, but the ones that you need to be aware of are programmed into the indicator for your reference.
Which models does this contain?
This contains over 30 different stock models, from LMT, BA, CSCO and GE to TSLA, NVDA, AAPL, GOOG, PCAR, META, ADBE and the list goes on.
As stated previously, it does have the ability to autofit.
WARNING
As a general warning, do not use this indicator to autofit to indices or futures. The parameters are set to what I find works best for equities and heightened volatility, it will not work great for indices. Please refer to other resources, such as the Universal Forecaster for such things as the equities RPPI will provide unreliable results if you are trying to cross use between different types of unintended equities (i.e. CFDs, Futures or Indicies)! I
As always, leave your questions and comments below.
Please be sure to read the instructions above the adding to favorites regarding how to access the indicator.
Thanks for reading and safe trades as always!
Fibonacci internal Break of Range PinescriptlabsThe uniqueness of this script lies in the synergy and dynamic interaction resulting from the advanced combination of key elements of technical analysis in the way it strategically merges Fibonacci Levels with the Linear Regression Channel and the internal price structure, creating a highly synergistic market analysis system.
The Linear Regression Channel, drawn from price regression and its standard deviation over a defined number of bars, offers a graphical representation of the prevailing market trend. The combination of this channel with Fibonacci Levels is deliberate and critical: the levels serve as additional filters to validate range breakouts within the channel, and vice versa, channel breakouts enhance the importance of Fibonacci levels by adjusting to the market context, represented by the specific length and displacement within the chart.
Fibonacci levels are updated with each new bar, and the detection of Break of Range (BoR) is integrated with the Fibonacci level plot to highlight significant breakout points. A unique aspect of this script is the way breakouts are identified not only by the price crossing certain Fibonacci levels but also by volume context and candlestick patterns, such as Engulfing patterns, which signal potential changes in market trends.
This interaction between the Linear Regression Channel and Fibonacci Levels, for example, a bullish price breakout above the upper channel boundary simultaneously crossing a significant Fibonacci level, suggests not only a possible continuation of the uptrend but also a strong support level established. Similarly, a bearish price breakout below the lower channel boundary, coinciding with a Fibonacci level, may signal a trend reversal confirmation and a new resistance level.
This script delves further into signal convergence, where the interaction between Break of Range and Fibonacci levels marks bullish and bearish breakouts, respectively, and when these signals coincide with breakouts of any Fibonacci level, they provide cross-confirmation that increases confidence in the generated signal. "BoR+Fib🔼" and "BoR+Fib🔽."
Additionally, the script introduces an innovative implementation of the Linear Regression Channel, which uses a customizable period and standard deviation to plot upper and lower trendlines. This approach allows traders to anticipate potential re-entry points after a breakout, as prices often retest the channel edges, providing low and high entry confirmation opportunities.
A differentiating technical aspect is the conditional logic implemented for bullish and bearish trend signal confirmation. For example, the script calibrates signals based on the intersection of price action with critical Fibonacci levels and confirmed candlestick patterns, enhancing signal reliability compared to using these indicators in isolation.
Key Features:
1. Dynamic calculation of Fibonacci levels.
2. Detection of internal price range breakouts (Break of Range).
3. Linear Regression Channel.
4. Detection of candlestick patterns (Engulfing Patterns).
Dynamic Fibonacci Level Calculation and Internal Range Breakout Detection (Break of Range):
The fusion of Fibonacci levels with the detection of internal range breakouts is crucial because it allows for precise identification of market turning points. Fibonacci levels act as initial filters, indicating potential support and resistance zones. When the price crosses a key Fibonacci level, especially in conjunction with an internal range breakout, the resulting signal is stronger and more reliable. This confluence significantly increases the probability of sustainable price movement.
Broken:
Function: The code identifies breakouts when the price crosses a key Fibonacci level (0%, 100%). A breakout is significant if the price crosses and holds beyond these levels.
Interaction: Breakouts validate Fibonacci levels. For example, a breakout above the 0% Fibonacci level can confirm an uptrend.
Structure Change:
Function: In the code, Structure Change can be interpreted through the detection of pivot patterns and price structure change signals, which we identify as Break of Range.
Interaction: This component acts as confirmation for range breakouts and Fibonacci levels. For example, if a range breakout is followed by a change in price structure (such as the formation of a new higher high), it strengthens the validity of the range breakout signal.
"BoR+Fib🔽": Indicates a bearish range breakout that has also crossed a Fibonacci level downward. This can be interpreted as a sell signal or a bearish trend indication.
"BoR+Fib🔼": Represents a bullish range breakout that has also crossed a Fibonacci level upward. It can be interpreted as a buy signal or a bullish trend indication.
Linear Regression Channel:
Function: The Linear Regression Channel is calculated and drawn using a defined number of bars to establish the overall market trend. Calculations involve summing and averaging closing prices and their products with the time index to calculate the regression line and its standard deviation. The script uses this channel to contextualize Fibonacci signals and range breakouts, with breakouts occurring in the direction of the channel's trend.
Interaction: Provides context to Fibonacci signals and range breakouts. For example, if a range breakout occurs in the same direction as indicated by the Linear Regression Channel, this adds credibility to the signal.
Integration Benefit: The Linear Regression Channel provides an overall trend context. When a range breakout signal and a Fibonacci level coincide within the direction indicated by the channel, the signal's validity is strengthened.
Signal Convergence: An ideal scenario occurs when all elements converge. For example, a good entry point could be when the price experiences a range breakout from a significant Fibonacci level, there is a change in price structure in the same direction, and all of this aligns with the trend indicated by the Linear Regression Channel.
Dynamic Volatility Visualization: Adjusts the width of the Linear Regression Channel based on market volatility.
Validation and Entry Confirmation after Linear Regression Channel Breakout:
Breakout Validation: The Linear Regression Channel breakout is validated not only by price crossing but also by an increase in volume, suggesting a significant breakout rather than a temporary fluctuation.
Entry Confirmation ('Low and High Entry Confirmation'):
Confirmation Bars: A specific number of bars (configurable entry) closing outside the channel are required to confirm an entry. This reduces the risk of false signals.
Channel Re-Test: After the breakout, the price often retests the channel's edge. An entry is confirmed if the price bounces from this area, validating the initial breakout.
Auxiliary Indicators: Oscillators or momentum indicators are used to confirm trend strength after the breakout.
Candlestick Pattern Detection (Engulfing Patterns):
Engulfing Pattern Identification: bullishEngulfing is activated in a bullish pattern with a previous bearish trend and a specific bullish candle. bearishEngulfing is activated in a bearish pattern with a previous bullish trend and a specific bearish candle.
Special Trend Signals:
Bullish signals are displayed as blue circles with "⬆️," while bearish signals are displayed as red circles with "⬇️."
Bullish Signals: Indicate that the price has crossed above certain Fibonacci levels, and the current trend is considered bullish, as the most recent closing price is higher than the closing price of a specific bar in the past.
Bearish Signals: Indicate that the price has crossed below certain Fibonacci levels, and the current trend is considered bearish, as the most recent closing price is lower than the closing price of a specific bar in the past.
Integration with 3Commas for Automation:
Signal Automation: The ability to integrate with platforms like 3Commas allows for the automatic execution of
strategies based on the script's signals, where a bot could execute trades based on the chart-generated signals, facilitating more efficient trading, reducing reaction time, and as an automated script, we only need to input our short Bot Id or our Long Bot ID into the previously loaded message alert.
Español:
La singularidad de este script radica en la sinergia y la interacción dinámica que resulta de la combinación avanzada de elementos clave del análisis técnico en la forma en que fusiona estratégicamente los Niveles de Fibonacci con el Canal de Regresión Lineal y la estructura interna del precio creando un sistema de análisis de mercado altamente sinérgico.
El Canal de Regresión Lineal, dibujado a partir de la regresión de precios y su desviación estándar sobre un número definido de barras, ofrece una representación gráfica de la tendencia predominante del mercado. La combinación de este canal con los Niveles de Fibonacci es deliberada y crítica: los niveles sirven como filtros adicionales para validar las rupturas de rango dentro del canal, y viceversa, las rupturas del canal potencian la importancia de los niveles de Fibonacci ajustándose al contexto del mercado, representado por la longitud y desplazamiento específicos dentro del gráfico.
Los niveles de Fibonacci se actualizan con cada nueva barra, La detección de rupturas de rango (Break of Range) se integra con la trama de niveles de Fibonacci para destacar los puntos de ruptura significativos. Un enfoque único de este script es la manera en que las rupturas no solo se identifican por el cruce de precios de ciertos niveles de Fibonacci sino también por el contexto de volumen y patrones de velas, como los patrones Engulfing, que señalan cambios potenciales en la tendencia del mercado.
Esta interacción entre el Canal de Regresión Lineal y los Niveles de Fibonacci Por ejemplo: una ruptura alcista del precio a través del límite superior del canal al mismo tiempo que cruza un nivel de Fibonacci significativo sugiere no solo una posible continuación de la tendencia alcista sino también un fuerte nivel de soporte establecido. Similarmente, una ruptura bajista del precio a través del límite inferior del canal, coincidiendo con un nivel de Fibonacci, puede señalar una confirmación de cambio de tendencia y un nuevo nivel de resistencia.
Este script profundiza aún más en la confluencia de señales, donde la interacción entre Break of Range y los niveles de Fibonacci marcan rupturas alcistas y bajistas respectivamente, y cuando estas señales coinciden con rupturas del de cualquier nivel de Fibonacci, proporcionan una confirmación cruzada que aumenta la confianza en la señal generada. "BoR+Fib🔼" y "BoR+Fib🔽"
Además, el script presenta una innovadora implementación de Canal de Regresión Lineal, que utiliza un periodo personalizable y una desviación estándar para trazar las líneas de tendencia superior e inferior. Este enfoque permite a los traders anticipar posibles puntos de reentrada después de una ruptura, con el precio a menudo retestando los bordes del canal, proporcionando así oportunidades de confirmación de entrada baja y alta.
Un aspecto técnico diferenciador es la lógica condicional implementada para la confirmación de señales de tendencia alcista y bajista. Por ejemplo, el script calibra señales basadas en la intersección de la acción del precio con los niveles críticos de Fibonacci y los patrones de velas confirmados, mejorando la confiabilidad de las señales en comparación con el uso de estos indicadores de forma aislada.
Características Principales:
1. Cálculo dinámico de niveles de Fibonacci.
2. Detección de rupturas internas del rango de precios (Break of Range).
3. Canal de regresión lineal.
4. Detección de patrones de velas (Patrones Engulfing).
Cálculo Dinámico de Niveles de Fibonacci y Detección de Rupturas Internas (Break of Range):
La fusión de los niveles de Fibonacci con la detección de rupturas internas del rango es crucial porque permite identificar con precisión los puntos de inflexión del mercado. Los niveles de Fibonacci funcionan como filtros iniciales, indicando potenciales zonas de soporte y resistencia. Cuando el precio cruza un nivel clave de Fibonacci, especialmente en conjunto con una ruptura interna del rango, la señal resultante es más robusta y fiable. Esta confluencia incrementa significativamente la probabilidad de que el movimiento del precio sea sostenible
Broken:
Función: El código identifica las rupturas cuando el precio cruza un nivel de Fibonacci clave (0%, 100%). Una ruptura es significativa si el precio cruza y se mantiene más allá de estos niveles.
Interacción: Las rupturas validan los niveles de Fibonacci. Por ejemplo, una ruptura por encima del nivel de Fibonacci del 0% puede confirmar una tendencia alcista.
Cambio de Estructura:
Función: En el código, el Cambio de Estructura se puede interpretar a través de la detección de patrones de pivote y señales de cambio en la estructura de precios, que identificamos como Break of Range.
Interacción: Este componente actúa como una confirmación de las rupturas de rango y los niveles de Fibonacci. Por ejemplo, si una ruptura de rango es seguida por un cambio en la estructura de precios (como la formación de un nuevo máximo más alto), esto refuerza la validez de la señal de ruptura de rango.
"BoR+Fib🔽": Indica una ruptura bajista del rango que también ha cruzado un nivel de Fibonacci hacia abajo. Esto puede interpretarse como una señal de venta o una indicación de tendencia bajista.
"BoR+Fib🔼": Representa una ruptura alcista del rango que también ha cruzado un nivel de Fibonacci hacia arriba. Puede interpretarse como una señal de compra o una indicación de tendencia alcista.
Canal de Regresión Lineal:
Función: El Canal de Regresión Lineal se calcula y dibuja utilizando un número definido de barras para establecer la tendencia general del mercado. Los cálculos involucran la suma y el promedio de los precios de cierre y sus productos con el índice de tiempo, para calcular la línea de regresión y su desviación estándar, el script utiliza este canal para contextualizar las señales de Fibonacci y las rupturas de rango, con rupturas que ocurren en la dirección de la tendencia del canal.
Interacción: Proporciona contexto a las señales de Fibonacci y rupturas de rango. Por ejemplo, si una ruptura de rango ocurre en la misma dirección que la tendencia indicada por el Canal de Regresión Lineal, esto añade credibilidad a la señal.
Beneficio de la Integración:El Canal de Regresión Lineal proporciona un contexto de tendencia general. Cuando una señal de ruptura de rango y un nivel de Fibonacci coinciden dentro de la dirección de la tendencia indicada por el canal, se fortalece la validez de la señal.
Convergencia de Señales: Un escenario ideal ocurre cuando todos los elementos convergen. Por ejemplo, un buen punto de entrada podría ser cuando el precio experimenta una ruptura de rango desde un nivel de Fibonacci importante, hay un cambio de estructura en la misma dirección, y todo esto ocurre en línea con la tendencia indicada por el Canal de Regresión Lineal.
Visualización de Volatilidad Dinámica: Ajusta el ancho del canal de regresión lineal en función de la volatilidad del mercado.
Validación y Confirmación de la Entrada después de la Ruptura del Canal de Regresión:
Confirmación de Ruptura: La ruptura del canal de regresión se valida no solo por el cruce del precio, sino también por un aumento en el volumen, lo que sugiere una ruptura significativa en lugar de una fluctuación temporal.
Confirmación de Entrada ('Confirmación de Entrada Baja y Alta'):
Barras de Confirmación: Se requiere un número específico de barras (entrada configurable) que cierren fuera del canal para confirmar una entrada. Esto reduce el riesgo de señales falsas.
Re-Test del Canal: Después de la ruptura, el precio a menudo vuelve a probar el borde del canal. Una entrada se confirma si el precio rebota desde esta área, validando la ruptura inicial.
Indicadores Auxiliares: Se utilizan osciladores o indicadores de impulso para confirmar la fuerza de la tendencia después de la ruptura.
Detección de Patrones de Velas (Patrones Engulfing):
Identificación de Patrones Engulfing: bullishEngulfing se activa en un patrón alcista con una tendencia bajista previa y una vela alcista específica. bearishEngulfing se activa en un patrón bajista con una tendencia alcista previa y una vela bajista específica.
Señales Especiales de Tendencia:
Las señales alcistas se muestran como círculos azules con "⬆️", mientras que las señales bajistas se muestran como círculos rojos "⬇️".
Señales Alcistas: Indican que el precio ha cruzado por encima de ciertos niveles de Fibonacci y la tendencia actual se considera alcista, ya que el precio de cierre más reciente es mayor que el precio de cierre de una barra específica en el pasado.
Señales Bajistas: Indican que el precio ha cruzado por debajo de ciertos niveles de Fibonacci y la tendencia actual se considera bajista, ya que el precio de cierre más reciente es menor que el precio de cierre de una barra específica en el pasado.
Integración con 3Commas para Automatización:
Automatización de Señales: La capacidad de integrar con plataformas como 3Commas permite la ejecución automática de estrategias basadas en las señales del script donde un bot podría ejecutar operaciones basadas en las señales generadas por el gráfico., facilitando un trading más eficiente y reduciendo el tiempo de reacción y como un script automatizado solo necesitamos poner en la alerta del mensaje previamente cargado nuestro short Bot Id o nuestro Long Bot ID.
RSI 11 IndicatorThis script explains how RSI can be used to catch market moves in trend, reversal or sideways market.
What is RSI indicator:-
RSI is a momentum oscillator which measures the speed and change of price movements. RSI moves up and down (oscillates) between ZERO and 100. Generally RSI above 70 is considered overbought and below 30 is considered oversold. Some traders may use a setting of 20 and 80 for oversold and overbought conditions respectively. However this may reduce the number of signals. You can also use RSI to identify divergences, strength, reversals, general trend etc.
Calculation:-
There are three basic components in the RSI - Avg Gain, Avg Loss & RS.
Avg Gain = Average of Upward Price Change
Avg Loss = Average of Downward Price Change
RS = (Avg Gain)/(Avg Loss)
RSI = 100 – (100 / (1 +RS ))
First Calculation:-
RSI calculation is based on default 14 periods.
Average gain and Average loss are simple 14 period averages.
Average Loss equals the sum of the losses divided by 14 for the first calculation.
Average Gain equals the sum of the Gains divided by 14 for the first calculation.
First Average Gain = Sum of Gains over the past 14 periods / 14.
First Average Loss = Sum of Losses over the past 14 periods / 14.
The formula uses a positive value for the average loss.
RS values are smoothed after the first calculation.
Second Calculation:-
Subsequent calculations multiply the prior value by 13, add the most recent value, and divide the total by 14.
Average Gain = / 14.
Average Loss = / 14.
if
Average Loss = 0, RSI = 100 (means there were no losses to measure).
Average Gain = 0, RSI = 0 (means there were no gains to measure).
Logic of this indicator:-
RSI is an oscillator that fluctuates between zero and 100 which makes it easy to use for many traders.
Its easy to identify extremes because RSI is range-bound.
But remember that RSI works best in range bound market and is less trustworthy in trending markets.
A new trader need to be cautious because during strong trends in the market/security, RSI may remain in overbought or oversold for extended periods.
Chart Timeframe:-
RSI indicator works well on all timeframes.
Timeframe depends on which strategy or settings are you using.
Generally a lower timeframe like 1 min, 3 min, 5 min, 15 min, 30 min, 1 Hr etc is used for intraday trades or short duration trades
and higher timeframes like 1 day, 1 week, 1 month are used for positional or long term trades.
Please Read the Idea "Mastering RSI with 11 Strategies" to understand this indicator better.
Indicator 1
Basis Strategy of Overbought and Oversold
Usually an asset with RSI reading of 70 or above indicates a bullish and an overbought situation.
overbought can be seen as trading at a higher price than it should.
traders may expect a price correction or trend reversal and sell the security.
but RSI indicator can stay in the overbought for a long time when the stock is in uptrend - This may trap an immature trader.
an Immature trader will enter a sell position when RSI become overbought (70), whereas a mature trader will enter sell position when RSI line crosses below the overbought line (70).
An asset with RSI reading of 30 or below indicates a bearish and an oversold condition.
oversold can be seen as trading at a lower price than it should.
traders may expect a price correction or trend reversal and buy the security.
but RSI indicator can stay in the oversold for a long time when the stock is in downtrend - This may trap an immature trader.
an Immature trader will enter a buy position when RSI become oversold (30), whereas a mature trader will enter buy position when RSI line crosses above the oversold line (30).
Center dotted Mid line is RSI 50.
Chart RSI is shown in yellow colour.
Red shaded area above the red horizontal line shows the stock or security has entered overbought condition. "R" signal in red shows a likely downside reversal, means it may be a likely Selling opportunity.
Green shaded area below the green horizontal line shows the stock or security has entered oversold condition. "R" signal in green shows a likely upside reversal, means it may be a likely Buying opportunity.
Note:-
so its better to wait for reversal signal.
traders may use 20 instead of 30 as oversold level and 80 instead of 70 as overbought level.
new traders may learn to use the indicator as per the prevailing trend to get better results.
false signals may be avoided by using bullish signals in bullish trend and bearish signals in bearish trend.
Indicator 2
RSI Strength Crossing 50
RSI crossing centreline 50 in the below chart showing strength and buy/sell signal.
Centre line is at RSI 50.
if RSI is above 50 its considered bullish trend. (increasing strength)
if RSI is below 50 its considered bearish trend. (decreasing strength)
RSI crossing centre line (50) upside may be a buy signal.
RSI crossing centre line (50) downside may be a sell signal.
"B" signal in green colour shows that RSI is crossing above Mid 50 horizontal line, which may be a likely Buy signal.
"S" signal in red colour shows that RSI is crossing below Mid 50 horizontal line, which may be a likely Sell signal.
Indicator 3
RSI 40 and RSI 60 Support and Resistance
RSI 40 acting as support in the below chart
In an uptrend RSI tends to remain in the 40 to 90 range with 40 as support (buying opportunity at support).
RSI 60 acting as resistance in the below chart
In a downtrend RSI tends to remain in 10 to 60 range with 60 as resistance (selling opportunity at resistance).
"40" signal in green colour shows that RSI is crossing above 40 horizontal line, which may be a likely Support in making and a Buy signal.
"60" signal in red colour shows that RSI is crossing below 60 horizontal line, which may be a likely Resistance in making and a Sell signal.
Note:-
These ranges may change depending on RSI settings and change in the market trend.
Indicator 4
RSI Divergence
Below chart shows a simple example of Bullish Divergence and Bearish Divergence.
An RSI divergence occurs when price moves in the opposite direction of the RSI.
A bullish divergence is when price is falling but RSI is rising. which means RSI making higher lows and price making lower lows (buy signal).
A bearish divergence is when price is rising but RSI is falling. which means RSI making lower high and price making higher highs (sell signal).
Divergences are more strong when appear in an overbought or oversold condition.
There may be many false signals during a strong uptrend or strong downtrend.
In a strong uptrend, RSI may show many false bearish divergences before finally reversing down.
same way in a strong downtrend, RSI may show many false bullish divergences before finally reversing up.
"Bull Div" signal along with divergence line in green colour shows Bullish Divergence, which may be a likely Buy signal.
"Bear Div" signal along with divergence line in red colour shows Bearish Divergence, which may be a likely Sell signal.
Indicator 5
Double Top & Double Bottom
Double Bottom = RSI goes below oversold (30). RSI comes back above 30. RSI falls back again towards 30 and again rise making a Double bottom. its a signal of buying and likely upside reversal.
Double Top = RSI goes above overbought (70). RSI comes back below 70. RSI rises back again towards 70 and again fall making a Double top. its a signal of selling and likely downside reversal.
Double Bottom is shown with Green Dashed line joining two low's of RSI indicating a likely Buy Signal.
Double Top is shown with Red Dashed line joining two High's of RSI indicating a likely Sell Signal.
Indicator 6
Trendline Support and Resistance
Below chart shows RSI Trendline Resistance and Support
RSI resistance trendline = Connect three or more points on the RSI line as it falls to draw a RSI downtrend line (RSI resistance trendline).
Everytime it takes resistance from a RSI downtrend line its a selling opportunity.
RSI support trendline = Connect three or more points on the RSI line as it rises to draw a RSI uptrend line (RSI support trendline).
Everytime it takes support on a RSI uptrend line its a buying opportunity.
RSI Resistance trendline shown in Red colour indicating a likely fall again after rejection from this Red trendline till the time RSI breaks above it to change the trend from Bearsih to Bullish.
RSI support trendline shown in Green colour indicating a likely Rise again after support from this Green trendline till the time RSI breaks below it to change the trend from Bullish to Bearish.
Indicator 7
Trendline Breakout and Breakdown
Below chart shows RSI Trendline Breakout and Breakdown
RSI resistance trendline Breakout = Connect three or more points on the RSI line as it falls to draw a RSI downtrend line (RSI resistance trendline).
Whenever it breakout above RSI resistance trendline its a buying opportunity.
RSI support trendline Breakdown = Connect three or more points on the RSI line as it rises to draw a RSI uptrend line (RSI support trendline).
Whenever it breakdown below RSI support trendline its a selling opportunity.
Note:-
Correlate both the RSI and the closing price to ensure proper breakout or breakdown.
Challenge is to correctly identify if a breakout or breakdown is sustainable or its a false signal.
Indicator 8
RSI Crossover same timeframe
RSI with two different RSI length crossing each other on same timeframe.
when lower RSI length crossing above higher RSI length its a buy signal.
when lower RSI length crossing below higher RSI length its a sell signal.
for example RSI with length 7 & length 14 on 15 Minutes timeframe.
Green Cross shows that Fast RSI is crossing above Slow RSI on the same timeframe with different RSI length Settings, which means it may be a likely Buy Signal.
Red Cross shows that Fast RSI is crossing below Slow RSI on the same timeframe with different RSI length Settings, which means it may be a likely Sell Signal.
Indicator 9
RSI Crossover Multi timeframe
RSI with same RSI length but on two different timeframes crossing each.
when lower timeframe RSI crossing above higher timeframe RSI its a buy signal.
when lower timeframe RSI crossing below higher timeframe RSI its a sell signal.
for example RSI with length 14 on 5 Minutes and 1 Hr timeframes.
Green Cross shows that Lower Timeframe RSI is crossing above Higher Timeframe RSI with same RSI length Settings, which means it may be a likely Buy Signal.
Red Cross shows that Lower Timeframe RSI is crossing below Higher Timeframe RSI with same RSI length Settings, which means it may be a likely Sell Signal.
Indicator 10
RSI EMA/WMA/SMA Crossover
when RSI crossing above EMA/WMA/SMA its a buy signal.
when RSI crossing below EMA/WMA/SMA its a sell signal.
Green Circle shows that RSI is crossing above EMA/WMA/SMA etc, which means it may be a likely Buy Signal.
Red Circle shows that RSI is crossing below EMA/WMA/SMA etc, which means it may be a likely Sell Signal.
Indicator 11
RSI with Bollinger bands
Bollinger bands and RSI complimenting each other and giving a Buy and Sell signal in below chart
if a security price reaches upper band of a Bollinger Band channel and also the RSI is above 70 (overbought), a trader can look for selling opportunities (reversal) (sell).
but in case price reaches upper band of a Bollinger Band channel but RSI is not above 70 (overbought), there may be chance that security remains in an uptrend, so a trader may wait before entering a sell position.
if a security price reaches lower band of a Bollinger Band channel and also the RSI is below 30 (oversold), a trader can look for buying opportunities (reversal) (buy).
but in case price reaches lower band of a Bollinger Band channel but RSI is not below 30 (oversold), there may be chance that security remains in an downtrend, so a trader may wait before entering a buy position.
so bollinger band with RSI can give a double confirmation on a reversal.
Buy Signal = If the RSI is below Green Horizontal line (Oversold zone) and also below Lower Bollinger Band it indicates that an upside reversal may come, which means that it may be a likely Buy Signal.
Sell Signal = If the RSI is above Red Horizontal line (Overbought zone) and also above Upper Bollinger Band it indicates that an Downside reversal may come, which means that it may be a likely Sell Signal.
Special Thanks to //© HoanGhetti for RSI Trendlines.
Limitations of the RSI:-
RSI works best in range bound market and is less trustworthy in trending markets.
So new traders may get trapped in an uptrend or a downtrend if they forget to see the overall long term trend of that security.
Traders should set stop loss and take profit levels as per risk reward ratio.
Note:
Don't confuse RSI and relative strength. RSI is changes in the price momentum of a security.
whereas relative strength compares the price performance of two or more securities.
Like other technical indicators, RSI also is not a holy grail. It can only assist you in building a good strategy. You can only succeed with proper position sizing, risk management and following correct trading Psychology (No overtrade, No greed, No revenge trade etc).
THIS INDICATOR OF RSI IS FOR EDUCATIONAL PURPOSE AND PAPER TRADING ONLY. YOU MAY PAPER TRADE TO GAIN CONFIDENCE AND BUILD FURTHER ON THESE. PLEASE CONSULT YOUR FINANCIAL ADVISOR BEFORE INVESTING. WE ARE NOT SEBI REGISTERED.
Hope you all like it
happy learning.
GT-FibThis code is declaring the script as an indicator named "GT-Fib" to be plotted on the main chart. The maximum number of lines it can create is limited to 500.
The indicator calculates Fibo using trend breaks. If the trend is not broken and the old trend continues, Fibo continues. However, sometimes you will witness that it does not draw Fibo. Indicates that there is no trend break yet. If current Fibo levels are behind us, it may be wise to wait for a trend change. For trend breaks, I partially benefited from the Lux team's trend lines with break indicator. For your information...
Settings:
A set of user inputs is defined to allow customization. These include lookback period, coefficient, calculation method, and an option to enable/disable backpainting. These inputs help the trader to adapt the script to different market conditions or trading strategies.
Style:
Colors and visual styles for the indicator are defined here, such as the colors for uptrends and downtrends.
Variables Initialization:
Various variables are initialized here. This section prepares the script for further calculations. Key concepts include the initialization of upper and lower boundaries, pivot highs (ph), pivot lows (pl), and a few other variables to track peaks and troughs for trendlines.
Trendline Peaks and Troughs:
The script identifies pivot highs and lows. Whenever a pivot high/low is found, it updates the trendline_top and trendline_bottom respectively.
Calculation Method:
Based on the user's choice, the script calculates a "cycle" value using one of three methods: ATR, Stdev, or Linreg.
Extended Lines:
These are dashed lines that get drawn when a pivot high or pivot low is identified. These lines can be used to visualize potential support or resistance areas.
plotFibRetracement Function:
This function is designed to draw Fibonacci retracement levels between the identified trendline top and bottom. The Fibonacci levels provide potential support and resistance levels that traders often use to make trading decisions.
Plotting Fibonacci using Trendline Peaks and Troughs:
If both trendline_top and trendline_bottom are not 'na' (not available), the script will draw the Fibonacci retracement using the defined function.
How to Use:
The script identifies and displays potential support and resistance zones using Fibonacci retracement levels based on the trendline peaks and troughs. Here's a suggested way to use it:
Adjust Settings: Depending on the instrument you're trading and the timeframe, you might want to adjust the lookback period, coefficient, and calculation method to fine-tune the script to your needs.
Identify Trends: Observe where the pivot highs and lows are formed. The presence of consecutive pivot highs or pivot lows can indicate a prevailing trend.
Use Fibonacci Levels: The Fibonacci retracement levels can act as potential support and resistance. For instance:
During an uptrend, if prices retract and approach a Fibonacci level, it might act as a support level where price could bounce back.
During a downtrend, Fibonacci levels might act as resistance where price could reverse downwards.
Combine with Other Indicators: For a more comprehensive analysis and to increase the reliability of trading signals, you can use this script in conjunction with other technical indicators.
Remember, like all trading tools and techniques, this script should be used in conjunction with proper risk management. It's also a good idea to test any strategy or tool in a demo environment before applying it to a live account.
TrendGuard Flag Finder - Strategy [presentTrading]
Introduction and How It Is Different
In the vast world of trading strategies, the TrendGuard Flag Finder stands out as a unique blend of traditional flag pattern detection and the renowned SuperTrend indicator.
- A significant portion of the Flag Pattern detection is inspired by the "Flag Finder" code by @Amphibiantrading, which serves as one of foundational element of this strategy.
- While many strategies focus on either trend-following or pattern recognition, this strategy harmoniously combines both, offering traders a more holistic view of the market.
- The integration of the SuperTrend indicator not only provides a clear direction of the prevailing trend but also offers potential stop-loss levels, enhancing the strategy's risk management capabilities.
AAPL 1D chart
ETHBTC 6hr chart
Strategy: How It Works
The TrendGuard Flag Finder is primarily built on two pillars:
1. Flag Pattern Detection : At its core, the strategy identifies flag patterns, which are continuation patterns suggesting that the prevailing trend will resume after a brief consolidation. The strategy meticulously detects both bullish and bearish flags, ensuring traders can capitalize on opportunities in both rising and falling markets.
What is a Flag Pattern? A flag pattern consists of two main components:
1.1 The Pole : This is the initial strong price move, which can be either upwards (for bullish flags) or downwards (for bearish flags). The pole represents a strong surge in price in a particular direction, driven by significant buying or selling momentum.
1.2 The Flag : Following the pole, the price starts consolidating, moving against the initial trend. This consolidation forms a rectangular shape and is characterized by parallel trendlines. In a bullish flag, the consolidation will have a slight downward tilt, while in a bearish flag, it will have a slight upward tilt.
How the Strategy Detects Flags:
Identifying the Pole: The strategy first identifies a strong price movement over a user-defined number of bars. This movement should meet a certain percentage change to qualify as a pole.
Spotting the Flag: After the pole is identified, the strategy looks for a consolidation phase. The consolidation should be counter to the prevailing trend and should be contained within parallel lines. The depth (for bullish flags) or rally (for bearish flags) of this consolidation is calculated to ensure it meets user-defined criteria.
2. SuperTrend Integration : The SuperTrend indicator, known for its simplicity and effectiveness, is integrated into the strategy. It provides a dynamic line on the chart, signaling the prevailing trend. When prices are above the SuperTrend line, it's an indication of an uptrend, and vice versa. This not only confirms the flag pattern's direction but also offers a potential stop-loss level for trades.
When combined, these components allow traders to identify potential breakout (for bullish flags) or breakdown (for bearish flags) scenarios, backed by the momentum indicated by the SuperTrend.
Usage
To use the SuperTrend Enhanced Flag Finder:
- Inputs : Begin by setting the desired parameters. The strategy offers a range of user-controlled settings, allowing for customization based on individual trading preferences and risk tolerance.
- Visualization : Once the parameters are set, the strategy will identify and visually represent flag patterns on the chart. Bullish flags are represented in green, while bearish flags are in red.
- Trade Execution : When a breakout or breakdown is identified, the strategy provides entry signals. It also offers exit signals based on the SuperTrend, ensuring that traders can capitalize on the momentum while managing risk.
Default Settings
The strategy comes with a set of default settings optimized for general use:
- SuperTrend Parameters: Length set to 10 and Factor set to 5.0.
- Bull Flag Criteria: Max Flag Depth at 7, Max Flag Length at 10 bars, Min Flag Length at 3 bars, Prior Uptrend Minimum at 9%, and Flag Pole Length between 7 to 13 bars.
- Bear Flag Criteria: Similar settings adjusted for bearish patterns.
- Display Options: By default, both bullish and bearish flags are displayed, with breakout and breakdown points highlighted.
GKD-C Adaptive-Lookback Stochastic [Loxx]Giga Kaleidoscope GKD-C Adaptive-Lookback Stochastic is a Metamorphosis module included in Loxx's "Giga Kaleidoscope Modularized Trading System".
█ GKD-C Adaptive-Lookback Stochastic
The Adaptive-Lookback Stochastic uses a swing pivot lookback algorithm to adjust the periiod input bar-bar-bar thereby converting the regular Stochasitc oscillator into an adaptive Stochatic oscillator.
What is the Adaptive Lookback Period?
The adaptive lookback period is a technique used in technical analysis to adjust the period of an indicator based on changes in market conditions. This technique is particularly useful in volatile or rapidly changing markets where a fixed period may not be optimal for detecting trends or signals.
The concept of the adaptive lookback period is relatively simple. By adjusting the lookback period based on changes in market conditions, traders can more accurately identify trends and signals. This can help traders to enter and exit trades at the right time and improve the profitability of their trading strategies.
The adaptive lookback period works by identifying potential swing points in the market. Once these points are identified, the lookback period is calculated based on the number of swings and a speed parameter. The swing count parameter determines the number of swings that must occur before the lookback period is adjusted. The speed parameter controls the rate at which the lookback period is adjusted, with higher values indicating a more rapid adjustment.
The adaptive lookback period can be applied to a wide range of technical indicators, including moving averages, oscillators, and trendlines. By adjusting the period of these indicators based on changes in market conditions, traders can reduce the impact of noise and false signals, leading to more profitable trades.
The adaptive lookback period is a powerful technique for traders and analysts looking to optimize their technical indicators. By adjusting the period based on changes in market conditions, traders can more accurately identify trends and signals, leading to more profitable trades. While there are various ways to implement the adaptive lookback period, the basic concept remains the same, and traders can adapt and customize the technique to suit their individual needs and trading styles.
What is the Stochastic Oscillator?
The Stochastic Oscillator is a popular technical analysis indicator developed by George Lane in the 1950s. It is a momentum indicator that compares a security's closing price to its price range over a specified period. The main idea behind the Stochastic Oscillator is that, in an upward trending market, prices tend to close near their high, while in a downward trending market, prices tend to close near their low. The Stochastic Oscillator ranges from 0 to 100 and is primarily used to identify overbought and oversold conditions or potential trend reversals.
The Stochastic Oscillator is calculated using the following formula:
%K = ((C - L14) / (H14 - L14)) * 100
Where:
%K: The Stochastic Oscillator value.
C: The most recent closing price.
L14: The lowest price of the last 14 periods (or any other chosen period).
H14: The highest price of the last 14 periods (or any other chosen period).
Additionally, a moving average of %K, called %D, is calculated to provide a signal line:
%D = Simple Moving Average of %K over 'n' periods
The Stochastic Oscillator generates signals based on the following conditions:
1. Overbought and Oversold Levels: The Stochastic Oscillator typically uses 80 and 20 as overbought and oversold levels, respectively. When the oscillator is above 80, it is considered overbought, indicating that the market may be overvalued and a price decline is possible. When the oscillator is below 20, it is considered oversold, indicating that the market may be undervalued and a price rise is possible.
2. Bullish and Bearish Divergences: A bullish divergence occurs when the price makes a lower low, but the Stochastic Oscillator makes a higher low, suggesting a potential trend reversal to the upside. A bearish divergence occurs when the price makes a higher high, but the Stochastic Oscillator makes a lower high, suggesting a potential trend reversal to the downside.
3. Crosses: Buy signals are generated when %K crosses above %D, indicating upward momentum. Sell signals are generated when %K crosses below %D, indicating downward momentum.
The Stochastic Oscillator is commonly used in combination with other technical analysis tools to confirm signals and improve the accuracy of predictions.
When using the Stochastic Oscillator, it's important to consider a few best practices and additional insights:
1. Confirmation with other indicators: While the Stochastic Oscillator can provide valuable insights into potential trend reversals and overbought/oversold conditions, it is generally more effective when used in conjunction with other technical indicators, such as moving averages, RSI (Relative Strength Index), or MACD (Moving Average Convergence Divergence). This can help confirm signals and reduce the chances of false signals or whipsaws.
2. Timeframes: The Stochastic Oscillator can be applied to various timeframes, such as daily, weekly, or intraday charts. Adjusting the lookback period for the calculation can also alter the sensitivity of the indicator. A shorter lookback period will make the oscillator more sensitive to price movements, while a longer lookback period will make it less sensitive. Traders should choose a timeframe and lookback period that aligns with their trading strategy and risk tolerance.
3. Variations: There are two primary variations of the Stochastic Oscillator: Fast Stochastic and Slow Stochastic. The Fast Stochastic uses the original %K and %D calculations, while the Slow Stochastic smooths %K with an additional moving average and uses this smoothed %K as the new %D. The Slow Stochastic is generally considered to generate fewer false signals due to the additional smoothing.
4. Overbought and Oversold: It's important to remember that overbought and oversold conditions can persist for an extended period, especially during strong trends. This means that the Stochastic Oscillator alone should not be relied upon as a definitive buy or sell signal. Instead, traders should wait for additional confirmation from other indicators or price action before entering or exiting a trade.
The Stochastic Oscillator is a valuable momentum indicator that helps traders identify potential trend reversals and overbought/oversold conditions in the market. However, it is most effective when used in combination with other technical analysis tools and should be adapted to suit the specific needs of the individual trader's strategy and risk tolerance.
█ Giga Kaleidoscope Modularized Trading System
Core components of an NNFX algorithmic trading strategy
The NNFX algorithm is built on the principles of trend, momentum, and volatility. There are six core components in the NNFX trading algorithm:
1. Volatility - price volatility; e.g., Average True Range, True Range Double, Close-to-Close, etc.
2. Baseline - a moving average to identify price trend
3. Confirmation 1 - a technical indicator used to identify trends
4. Confirmation 2 - a technical indicator used to identify trends
5. Continuation - a technical indicator used to identify trends
6. Volatility/Volume - a technical indicator used to identify volatility/volume breakouts/breakdown
7. Exit - a technical indicator used to determine when a trend is exhausted
8. Metamorphosis - a technical indicator that produces a compound signal from the combination of other GKD indicators*
*(not part of the NNFX algorithm)
What is Volatility in the NNFX trading system?
In the NNFX (No Nonsense Forex) trading system, ATR (Average True Range) is typically used to measure the volatility of an asset. It is used as a part of the system to help determine the appropriate stop loss and take profit levels for a trade. ATR is calculated by taking the average of the true range values over a specified period.
True range is calculated as the maximum of the following values:
-Current high minus the current low
-Absolute value of the current high minus the previous close
-Absolute value of the current low minus the previous close
ATR is a dynamic indicator that changes with changes in volatility. As volatility increases, the value of ATR increases, and as volatility decreases, the value of ATR decreases. By using ATR in NNFX system, traders can adjust their stop loss and take profit levels according to the volatility of the asset being traded. This helps to ensure that the trade is given enough room to move, while also minimizing potential losses.
Other types of volatility include True Range Double (TRD), Close-to-Close, and Garman-Klass
What is a Baseline indicator?
The baseline is essentially a moving average, and is used to determine the overall direction of the market.
The baseline in the NNFX system is used to filter out trades that are not in line with the long-term trend of the market. The baseline is plotted on the chart along with other indicators, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR).
Trades are only taken when the price is in the same direction as the baseline. For example, if the baseline is sloping upwards, only long trades are taken, and if the baseline is sloping downwards, only short trades are taken. This approach helps to ensure that trades are in line with the overall trend of the market, and reduces the risk of entering trades that are likely to fail.
By using a baseline in the NNFX system, traders can have a clear reference point for determining the overall trend of the market, and can make more informed trading decisions. The baseline helps to filter out noise and false signals, and ensures that trades are taken in the direction of the long-term trend.
What is a Confirmation indicator?
Confirmation indicators are technical indicators that are used to confirm the signals generated by primary indicators. Primary indicators are the core indicators used in the NNFX system, such as the Average True Range (ATR), the Moving Average (MA), and the Relative Strength Index (RSI).
The purpose of the confirmation indicators is to reduce false signals and improve the accuracy of the trading system. They are designed to confirm the signals generated by the primary indicators by providing additional information about the strength and direction of the trend.
Some examples of confirmation indicators that may be used in the NNFX system include the Bollinger Bands, the MACD (Moving Average Convergence Divergence), and the MACD Oscillator. These indicators can provide information about the volatility, momentum, and trend strength of the market, and can be used to confirm the signals generated by the primary indicators.
In the NNFX system, confirmation indicators are used in combination with primary indicators and other filters to create a trading system that is robust and reliable. By using multiple indicators to confirm trading signals, the system aims to reduce the risk of false signals and improve the overall profitability of the trades.
What is a Continuation indicator?
In the NNFX (No Nonsense Forex) trading system, a continuation indicator is a technical indicator that is used to confirm a current trend and predict that the trend is likely to continue in the same direction. A continuation indicator is typically used in conjunction with other indicators in the system, such as a baseline indicator, to provide a comprehensive trading strategy.
What is a Volatility/Volume indicator?
Volume indicators, such as the On Balance Volume (OBV), the Chaikin Money Flow (CMF), or the Volume Price Trend (VPT), are used to measure the amount of buying and selling activity in a market. They are based on the trading volume of the market, and can provide information about the strength of the trend. In the NNFX system, volume indicators are used to confirm trading signals generated by the Moving Average and the Relative Strength Index. Volatility indicators include Average Direction Index, Waddah Attar, and Volatility Ratio. In the NNFX trading system, volatility is a proxy for volume and vice versa.
By using volume indicators as confirmation tools, the NNFX trading system aims to reduce the risk of false signals and improve the overall profitability of trades. These indicators can provide additional information about the market that is not captured by the primary indicators, and can help traders to make more informed trading decisions. In addition, volume indicators can be used to identify potential changes in market trends and to confirm the strength of price movements.
What is an Exit indicator?
The exit indicator is used in conjunction with other indicators in the system, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR), to provide a comprehensive trading strategy.
The exit indicator in the NNFX system can be any technical indicator that is deemed effective at identifying optimal exit points. Examples of exit indicators that are commonly used include the Parabolic SAR, the Average Directional Index (ADX), and the Chandelier Exit.
The purpose of the exit indicator is to identify when a trend is likely to reverse or when the market conditions have changed, signaling the need to exit a trade. By using an exit indicator, traders can manage their risk and prevent significant losses.
In the NNFX system, the exit indicator is used in conjunction with a stop loss and a take profit order to maximize profits and minimize losses. The stop loss order is used to limit the amount of loss that can be incurred if the trade goes against the trader, while the take profit order is used to lock in profits when the trade is moving in the trader's favor.
Overall, the use of an exit indicator in the NNFX trading system is an important component of a comprehensive trading strategy. It allows traders to manage their risk effectively and improve the profitability of their trades by exiting at the right time.
What is an Metamorphosis indicator?
The concept of a metamorphosis indicator involves the integration of two or more GKD indicators to generate a compound signal. This is achieved by evaluating the accuracy of each indicator and selecting the signal from the indicator with the highest accuracy. As an illustration, let's consider a scenario where we calculate the accuracy of 10 indicators and choose the signal from the indicator that demonstrates the highest accuracy.
The resulting output from the metamorphosis indicator can then be utilized in a GKD-BT backtest by occupying a slot that aligns with the purpose of the metamorphosis indicator. The slot can be a GKD-B, GKD-C, or GKD-E slot, depending on the specific requirements and objectives of the indicator. This allows for seamless integration and utilization of the compound signal within the GKD-BT framework.
How does Loxx's GKD (Giga Kaleidoscope Modularized Trading System) implement the NNFX algorithm outlined above?
Loxx's GKD v2.0 system has five types of modules (indicators/strategies). These modules are:
1. GKD-BT - Backtesting module (Volatility, Number 1 in the NNFX algorithm)
2. GKD-B - Baseline module (Baseline and Volatility/Volume, Numbers 1 and 2 in the NNFX algorithm)
3. GKD-C - Confirmation 1/2 and Continuation module (Confirmation 1/2 and Continuation, Numbers 3, 4, and 5 in the NNFX algorithm)
4. GKD-V - Volatility/Volume module (Confirmation 1/2, Number 6 in the NNFX algorithm)
5. GKD-E - Exit module (Exit, Number 7 in the NNFX algorithm)
6. GKD-M - Metamorphosis module (Metamorphosis, Number 8 in the NNFX algorithm, but not part of the NNFX algorithm)
(additional module types will added in future releases)
Each module interacts with every module by passing data to A backtest module wherein the various components of the GKD system are combined to create a trading signal.
That is, the Baseline indicator passes its data to Volatility/Volume. The Volatility/Volume indicator passes its values to the Confirmation 1 indicator. The Confirmation 1 indicator passes its values to the Confirmation 2 indicator. The Confirmation 2 indicator passes its values to the Continuation indicator. The Continuation indicator passes its values to the Exit indicator, and finally, the Exit indicator passes its values to the Backtest strategy.
This chaining of indicators requires that each module conform to Loxx's GKD protocol, therefore allowing for the testing of every possible combination of technical indicators that make up the six components of the NNFX algorithm.
What does the application of the GKD trading system look like?
Example trading system:
Backtest: Full GKD Backtest
Baseline: Hull Moving Average
Volatility/Volume: Hurst Exponent
Confirmation 1: Composite RSI
Confirmation 2: uf2018
Continuation: Vortex
Exit: Rex Oscillator
Metamorphosis: Fisher Transform, Universal Oscillator, Aroon, Vortex .. combined
Each GKD indicator is denoted with a module identifier of either: GKD-BT, GKD-B, GKD-C, GKD-V, GKD-M, or GKD-E. This allows traders to understand to which module each indicator belongs and where each indicator fits into the GKD system.
█ Giga Kaleidoscope Modularized Trading System Signals
Standard Entry
1. GKD-C Confirmation gives signal
2. Baseline agrees
3. Price inside Goldie Locks Zone Minimum
4. Price inside Goldie Locks Zone Maximum
5. Confirmation 2 agrees
6. Volatility/Volume agrees
1-Candle Standard Entry
1a. GKD-C Confirmation gives signal
2a. Baseline agrees
3a. Price inside Goldie Locks Zone Minimum
4a. Price inside Goldie Locks Zone Maximum
Next Candle
1b. Price retraced
2b. Baseline agrees
3b. Confirmation 1 agrees
4b. Confirmation 2 agrees
5b. Volatility/Volume agrees
Baseline Entry
1. GKD-B Basline gives signal
2. Confirmation 1 agrees
3. Price inside Goldie Locks Zone Minimum
4. Price inside Goldie Locks Zone Maximum
5. Confirmation 2 agrees
6. Volatility/Volume agrees
7. Confirmation 1 signal was less than 'Maximum Allowable PSBC Bars Back' prior
1-Candle Baseline Entry
1a. GKD-B Baseline gives signal
2a. Confirmation 1 agrees
3a. Price inside Goldie Locks Zone Minimum
4a. Price inside Goldie Locks Zone Maximum
5a. Confirmation 1 signal was less than 'Maximum Allowable PSBC Bars Back' prior
Next Candle
1b. Price retraced
2b. Baseline agrees
3b. Confirmation 1 agrees
4b. Confirmation 2 agrees
5b. Volatility/Volume agrees
Volatility/Volume Entry
1. GKD-V Volatility/Volume gives signal
2. Confirmation 1 agrees
3. Price inside Goldie Locks Zone Minimum
4. Price inside Goldie Locks Zone Maximum
5. Confirmation 2 agrees
6. Baseline agrees
7. Confirmation 1 signal was less than 7 candles prior
1-Candle Volatility/Volume Entry
1a. GKD-V Volatility/Volume gives signal
2a. Confirmation 1 agrees
3a. Price inside Goldie Locks Zone Minimum
4a. Price inside Goldie Locks Zone Maximum
5a. Confirmation 1 signal was less than 'Maximum Allowable PSVVC Bars Back' prior
Next Candle
1b. Price retraced
2b. Volatility/Volume agrees
3b. Confirmation 1 agrees
4b. Confirmation 2 agrees
5b. Baseline agrees
Confirmation 2 Entry
1. GKD-C Confirmation 2 gives signal
2. Confirmation 1 agrees
3. Price inside Goldie Locks Zone Minimum
4. Price inside Goldie Locks Zone Maximum
5. Volatility/Volume agrees
6. Baseline agrees
7. Confirmation 1 signal was less than 7 candles prior
1-Candle Confirmation 2 Entry
1a. GKD-C Confirmation 2 gives signal
2a. Confirmation 1 agrees
3a. Price inside Goldie Locks Zone Minimum
4a. Price inside Goldie Locks Zone Maximum
5a. Confirmation 1 signal was less than 'Maximum Allowable PSC2C Bars Back' prior
Next Candle
1b. Price retraced
2b. Confirmation 2 agrees
3b. Confirmation 1 agrees
4b. Volatility/Volume agrees
5b. Baseline agrees
PullBack Entry
1a. GKD-B Baseline gives signal
2a. Confirmation 1 agrees
3a. Price is beyond 1.0x Volatility of Baseline
Next Candle
1b. Price inside Goldie Locks Zone Minimum
2b. Price inside Goldie Locks Zone Maximum
3b. Confirmation 1 agrees
4b. Confirmation 2 agrees
5b. Volatility/Volume agrees
Continuation Entry
1. Standard Entry, 1-Candle Standard Entry, Baseline Entry, 1-Candle Baseline Entry, Volatility/Volume Entry, 1-Candle Volatility/Volume Entry, Confirmation 2 Entry, 1-Candle Confirmation 2 Entry, or Pullback entry triggered previously
2. Baseline hasn't crossed since entry signal trigger
4. Confirmation 1 agrees
5. Baseline agrees
6. Confirmation 2 agrees
█ Connecting to Backtests
All GKD indicators are chained indicators meaning you export the value of the indicators to specialized backtest to creat your GKD trading system. Each indicator contains a proprietary signal generation algo that will only work with GKD backtests. You can find these backtests using the links below.
GKD-BT Giga Confirmation Stack Backtest:
GKD-BT Giga Stacks Backtest:
GKD-BT Full Giga Kaleidoscope Backtest:
GKD-BT Solo Confirmation Super Complex Backtest:
GKD-BT Solo Confirmation Complex Backtest:
GKD-BT Solo Confirmation Simple Backtest:
GKD-C Adaptive-Lookback Variety RSI [Loxx]Giga Kaleidoscope GKD-C Adaptive-Lookback Variety RSI is a Confirmation module included in Loxx's "Giga Kaleidoscope Modularized Trading System".
█ GKD-C Adaptive-Lookback Variety RSI
What is the Adaptive Lookback Period?
The adaptive lookback period is a technique used in technical analysis to adjust the period of an indicator based on changes in market conditions. This technique is particularly useful in volatile or rapidly changing markets where a fixed period may not be optimal for detecting trends or signals.
The concept of the adaptive lookback period is relatively simple. By adjusting the lookback period based on changes in market conditions, traders can more accurately identify trends and signals. This can help traders to enter and exit trades at the right time and improve the profitability of their trading strategies.
The adaptive lookback period works by identifying potential swing points in the market. Once these points are identified, the lookback period is calculated based on the number of swings and a speed parameter. The swing count parameter determines the number of swings that must occur before the lookback period is adjusted. The speed parameter controls the rate at which the lookback period is adjusted, with higher values indicating a more rapid adjustment.
The adaptive lookback period can be applied to a wide range of technical indicators, including moving averages, oscillators, and trendlines. By adjusting the period of these indicators based on changes in market conditions, traders can reduce the impact of noise and false signals, leading to more profitable trades.
In summary, the adaptive lookback period is a powerful technique for traders and analysts looking to optimize their technical indicators. By adjusting the period based on changes in market conditions, traders can more accurately identify trends and signals, leading to more profitable trades. While there are various ways to implement the adaptive lookback period, the basic concept remains the same, and traders can adapt and customize the technique to suit their individual needs and trading styles.
This indicator includes 10 types of RSI
1. Regular RSI
2. Slow RSI
3. Ehlers Smoothed RSI
4. Cutler's RSI
5. Rapid RSI
6. Harris' RSI
7. RSI DEMA
8. RSI TEMA
9. RSI T3
10. Jurik RSX
Regular RSI
The Relative Strength Index (RSI) is a widely used technical indicator in the field of financial market analysis. Developed by J. Welles Wilder Jr. in 1978, the RSI is a momentum oscillator that measures the speed and change of price movements. It helps traders identify potential trend reversals, overbought, and oversold conditions in a market.
The RSI is calculated based on the average gains and losses of an asset over a specified period, typically 14 days. The formula for calculating the RSI is as follows:
RSI = 100 - (100 / (1 + RS))
Where:
RS (Relative Strength) = Average gain over the specified period / Average loss over the specified period
The RSI ranges from 0 to 100, with values above 70 generally considered overbought (potentially indicating that the asset is overvalued and may experience a price decline) and values below 30 considered oversold (potentially indicating that the asset is undervalued and may experience a price increase).
Slow RSI
Slow RSI is a modified version of the Relative Strength Index (RSI) indicator that aims to provide a smoother, more consistent signal than the traditional RSI. The Slow RSI is designed to be less sensitive to sudden price movements, which can cause false signals.
To calculate Slow RSI, we first calculate the up and down values, just like in traditional RSI and Ehlers RSI. The up and down values are calculated by comparing the current price to the previous price, and then adding up the positive and negative differences.
Next, we calculate the Slow RSI value using the formula:
SlowRSI = 100 * up / (up + dn)
where "up" and "dn" are the total positive and negative differences, respectively.
This formula is similar to the one used in traditional RSI, but the dynamic lookback period based on the average of the up and down values is used to smooth out the signal.
Finally, we apply smoothing to the Slow RSI value by taking an exponential moving average (EMA) of the Slow RSI values over a specified period. This EMA helps to reduce the impact of sudden price movements and provide a smoother, more consistent signal over time.
Ehler's Smoothed RSI
Ehlers RSI is a modified version of the Relative Strength Index (RSI) indicator created by John Ehlers, a well-known technical analyst and author. The purpose of Ehlers RSI is to reduce lag and improve the responsiveness of the traditional RSI indicator.
To calculate Ehlers RSI, we first smooth the prices by taking a weighted average of the current price and the two previous prices. This smoothing helps to reduce noise in the data and produce a more accurate signal.
Next, we calculate the up and down values differently than in traditional RSI. In traditional RSI, the up and down values are based on the difference between the current price and the previous price. In Ehlers RSI, the up and down values are based on the difference between the current price and the price two bars ago. This approach helps to reduce lag and produce a more responsive indicator.
Finally, we calculate Ehlers RSI using the formula:
EhlersRSI = 50 * (up - down) / (up + down) + 50
The result is a more timely signal that can help traders identify potential trends and reversals in the market. However, as with any technical indicator, Ehlers RSI should be used in conjunction with other analysis tools and should not be relied on as the sole basis for trading decisions.
Cutler's RSI
Cutler's RSI (Relative Strength Index) is a variation of the traditional RSI, a popular technical analysis indicator used to measure the speed and change of price movements. The main difference between Cutler's RSI and the traditional RSI is the calculation method used to smooth the data. While the traditional RSI uses an exponential moving average (EMA) to smooth the data, Cutler's RSI uses a simple moving average (SMA).
Here's the formula for Cutler's RSI:
1. Calculate the price change: Price Change = Current Price - Previous Price
2. Calculate the average gain and average loss over a specified period (usually 14 days):
If Price Change > 0, add it to the total gains.
If Price Change < 0, add the absolute value to the total losses.
3. Calculate the average gain and average loss by dividing the totals by the specified period: Average Gain = Total Gains / Period, Average Loss = Total Losses / Period
4. Calculate the Relative Strength (RS): RS = Average Gain / Average Loss
5. Calculate Cutler's RSI: Cutler's RSI = 100 - (100 / (1 + RS))
Cutler's RSI is not necessarily better than the regular RSI; it's just a different variation of the traditional RSI that uses a simple moving average (SMA) instead of an exponential moving average (EMA) quantifiedstrategies.com. The main advantage of Cutler's RSI is that it is not data length dependent, meaning it returns consistent results regardless of the length of the period, or the starting point within a data file quantifiedstrategies.com.
However, it's worth noting that Cutler's RSI does not necessarily outperform the traditional RSI. In fact, backtests reveal that Cutler's RSI is no improvement compared to Wilder's RSI quantifiedstrategies.com. Additionally, using an SMA instead of an EMA in Cutler's RSI may result in the loss of the "believed" advantage of weighting the most recent price action aaii.com.
Both Cutler's RSI and the traditional RSI can be used to identify overbought/oversold levels, support and resistance, spot divergences for possible reversals, and confirm the signals from other indicators investopedia.com. Ultimately, the choice between Cutler's RSI and the traditional RSI depends on personal preference and the specific trading strategy being employed.
Rapid RSI
Rapid RSI is a technical analysis indicator that is a modified version of the Relative Strength Index (RSI). It was developed by Andrew Cardwell and was first introduced in the October 2006 issue of Technical Analysis of Stocks & Commodities magazine.
The Rapid RSI improves upon the regular RSI by modifying the way the average gains and losses are calculated. Here's a general breakdown of the Rapid RSI calculation:
1. Calculate the upward change (when the price has increased) and the downward change (when the price has decreased) for each period.
2. Calculate the simple moving average (SMA) of the upward changes and the SMA of the downward changes over the specified period.
3. Divide the SMA of the upward changes by the SMA of the downward changes to get the relative strength (RS).
4. Calculate the Rapid RSI by transforming the relative strength (RS) into a value ranging from 0 to 100.
By using the simple moving average (SMA) instead of the slow exponential moving average (RMA) as in the regular RSI, the Rapid RSI tends to be more responsive to recent price changes. This can help traders identify overbought and oversold conditions more quickly, potentially leading to earlier entry and exit points. However, it is important to note that a faster indicator may also produce more false signals.
Harris' RSI
Harris RSI (Relative Strength Index) is a technical indicator used in financial analysis to measure the strength or weakness of a security over time. It was developed by Larry Harris in 1986 as an alternative to the traditional RSI, which measures the price change of a security over a given period.
The Harris RSI uses a slightly different formula from the traditional RSI, but it is based on the same principles. It calculates the ratio of the average gain to the average loss over a specified period, typically 14 days. The result is then plotted on a scale of 0 to 100, with high values indicating overbought conditions and low values indicating oversold conditions.
The Harris RSI is believed to be more responsive to short-term price movements than the traditional RSI, making it useful for traders who are looking for quick trading opportunities. However, like any technical indicator, it should be used in conjunction with other forms of analysis to make informed trading decisions.
The calculation of the Harris RSI involves several steps:
1. Calculate the price change over the specified period (usually 14 days) using the following formula:
Price Change = Close Price - Prior Close Price
2. Calculate the average gain and average loss over the same period, using separate formulas for each:
Average Gain = (Sum of Gains over the Period) / Period
Average Loss = (Sum of Losses over the Period) / Period
Gains are calculated as the sum of all positive price changes over the period, while losses are calculated as the sum of all negative price changes over the period.
3. Calculate the Relative Strength (RS) as the ratio of the Average Gain to the Average Loss:
RS = Average Gain / Average Loss
4. Calculate the Harris RSI using the following formula:
Harris RSI = 100 - (100 / (1 + RS))
The resulting Harris RSI value is a number between 0 and 100, which is plotted on a chart to identify overbought or oversold conditions in the security. A value above 70 is generally considered overbought, while a value below 30 is generally considered oversold.
DEMA RSI
DEMA RSI is a variation of the Relative Strength Index (RSI) technical indicator that incorporates the Double Exponential Moving Average (DEMA) for smoothing. Like the regular RSI, the DEMA RSI is a momentum oscillator used to measure the speed and change of price movements, and it ranges from 0 to 100. Readings below 30 typically indicate oversold conditions, while readings above 70 indicate overbought conditions.
The DEMA RSI aims to improve upon the regular RSI by addressing its limitations, such as lag and false signals. By using the DEMA, a more responsive and faster RSI can be achieved. Here's a general breakdown of the DEMA RSI calculation:
1. Calculate the price change for each period, as well as the absolute value of the change.
2. Apply the DEMA smoothing technique to both the price change and its absolute value, separately. This involves calculating two sets of exponential moving averages and combining them to create a double-weighted moving average with reduced lag.
3. Divide the smoothed price change by the smoothed absolute value of the price change.
4. Transform the result into a value ranging from 0 to 100 to obtain the DEMA RSI.
The DEMA RSI is considered an improvement over the regular RSI because it provides faster and more responsive signals. This can help traders identify overbought and oversold conditions more accurately and potentially avoid false signals.
In summary, the main advantages of these RSI variations over the regular RSI are their ability to reduce noise, provide smoother lines, and be more responsive to price changes. This can lead to more accurate signals and fewer false positives in different market conditions.
TEMA RSI
TEMA RSI is a variation of the Relative Strength Index (RSI) technical indicator that incorporates the Triple Exponential Moving Average (TEMA) for smoothing. Like the regular RSI, the TEMA RSI is a momentum oscillator used to measure the speed and change of price movements, and it ranges from 0 to 100. Readings below 30 typically indicate oversold conditions, while readings above 70 indicate overbought conditions.
The TEMA RSI aims to improve upon the regular RSI by addressing its limitations, such as lag and false signals. By using the TEMA, a more responsive and faster RSI can be achieved. Here's a general breakdown of the TEMA RSI calculation:
1. Calculate the price change for each period, as well as the absolute value of the change.
2. Apply the TEMA smoothing technique to both the price change and its absolute value, separately. This involves calculating two sets of exponential moving averages and combining them to create a double-weighted moving average with reduced lag.
3. Divide the smoothed price change by the smoothed absolute value of the price change.
4. Transform the result into a value ranging from 0 to 100 to obtain the TEMA RSI.
The TEMA RSI is considered an improvement over the regular RSI because it provides faster and more responsive signals. This can help traders identify overbought and oversold conditions more accurately and potentially avoid false signals.
T3 RSI
T3 RSI is a variation of the Relative Strength Index (RSI) technical indicator that incorporates the Tilson T3 for smoothing. Like the regular RSI, the T3 RSI is a momentum oscillator used to measure the speed and change of price movements, and it ranges from 0 to 100. Readings below 30 typically indicate oversold conditions, while readings above 70 indicate overbought conditions.
The T3 RSI aims to improve upon the regular RSI by addressing its limitations, such as lag and false signals. By using the T3, a more responsive and faster RSI can be achieved. Here's a general breakdown of the T3 RSI calculation:
1. Calculate the price change for each period, as well as the absolute value of the change.
2. Apply the T3 smoothing technique to both the price change and its absolute value, separately. This involves calculating two sets of exponential moving averages and combining them to create a double-weighted moving average with reduced lag.
3. Divide the smoothed price change by the smoothed absolute value of the price change.
4. Transform the result into a value ranging from 0 to 100 to obtain the T3 RSI.
The T3 RSI is considered an improvement over the regular RSI because it provides faster and more responsive signals. This can help traders identify overbought and oversold conditions more accurately and potentially avoid false signals.
Jurik RSX
The Jurik RSX is a technical indicator developed by Mark Jurik to measure the momentum and strength of price movements in financial markets, such as stocks, commodities, and currencies. It is an advanced version of the traditional Relative Strength Index (RSI), designed to offer smoother and less lagging signals compared to the standard RSI.
The main advantage of the Jurik RSX is that it provides more accurate and timely signals for traders and analysts, thanks to its improved calculation methods that reduce noise and lag in the indicator's output. This enables better decision-making when analyzing market trends and potential trading opportunities.
What is Adaptive-Lookback Variety RSI
This indicator allows the user to select from 9 different RSI types and 33 source types. The various RSI types is enhanced by injecting an adaptive lookback period into the caculation making the RSI able to adaptive to differing market conditions.
Additional Features
This indicator allows you to select from 33 source types. They are as follows:
Close
Open
High
Low
Median
Typical
Weighted
Average
Average Median Body
Trend Biased
Trend Biased (Extreme)
HA Close
HA Open
HA High
HA Low
HA Median
HA Typical
HA Weighted
HA Average
HA Average Median Body
HA Trend Biased
HA Trend Biased (Extreme)
HAB Close
HAB Open
HAB High
HAB Low
HAB Median
HAB Typical
HAB Weighted
HAB Average
HAB Average Median Body
HAB Trend Biased
HAB Trend Biased (Extreme)
What are Heiken Ashi "better" candles?
Heiken Ashi "better" candles are a modified version of the standard Heiken Ashi candles, which are a popular charting technique used in technical analysis. Heiken Ashi candles help traders identify trends and potential reversal points by smoothing out price data and reducing market noise. The "better formula" was proposed by Sebastian Schmidt in an article published by BNP Paribas in Warrants & Zertifikate, a German magazine, in August 2004. The aim of this formula is to further improve the smoothing of the Heiken Ashi chart and enhance its effectiveness in identifying trends and reversals.
Standard Heiken Ashi candles are calculated using the following formulas:
Heiken Ashi Close = (Open + High + Low + Close) / 4
Heiken Ashi Open = (Previous Heiken Ashi Open + Previous Heiken Ashi Close) / 2
Heiken Ashi High = Max (High, Heiken Ashi Open, Heiken Ashi Close)
Heiken Ashi Low = Min (Low, Heiken Ashi Open, Heiken Ashi Close)
The "better formula" modifies the standard Heiken Ashi calculation by incorporating additional smoothing, which can help reduce noise and make it easier to identify trends and reversals. The modified formulas for Heiken Ashi "better" candles are as follows:
Better Heiken Ashi Close = (Open + High + Low + Close) / 4
Better Heiken Ashi Open = (Previous Better Heiken Ashi Open + Previous Better Heiken Ashi Close) / 2
Better Heiken Ashi High = Max (High, Better Heiken Ashi Open, Better Heiken Ashi Close)
Better Heiken Ashi Low = Min (Low, Better Heiken Ashi Open, Better Heiken Ashi Close)
Smoothing Factor = 2 / (N + 1), where N is the chosen period for smoothing
Smoothed Better Heiken Ashi Open = (Better Heiken Ashi Open * Smoothing Factor) + (Previous Smoothed Better Heiken Ashi Open * (1 - Smoothing Factor))
Smoothed Better Heiken Ashi Close = (Better Heiken Ashi Close * Smoothing Factor) + (Previous Smoothed Better Heiken Ashi Close * (1 - Smoothing Factor))
The smoothed Better Heiken Ashi Open and Close values are then used to calculate the smoothed Better Heiken Ashi High and Low values, resulting in "better" candles that provide a clearer representation of the market trend and potential reversal points.
It's important to note that, like any other technical analysis tool, Heiken Ashi "better" candles are not foolproof and should be used in conjunction with other indicators and analysis techniques to make well-informed trading decisions.
Heiken Ashi "better" candles, as mentioned previously, provide a clearer representation of market trends and potential reversal points by reducing noise and smoothing out price data. When using these candles in conjunction with other technical analysis tools and indicators, traders can gain valuable insights into market behavior and make more informed decisions.
To effectively use Heiken Ashi "better" candles in your trading strategy, consider the following tips:
Trend Identification: Heiken Ashi "better" candles can help you identify the prevailing trend in the market. When the majority of the candles are green (or another color, depending on your chart settings) and there are no or few lower wicks, it may indicate a strong uptrend. Conversely, when the majority of the candles are red (or another color) and there are no or few upper wicks, it may signal a strong downtrend.
Trend Reversals: Look for potential trend reversals when a change in the color of the candles occurs, especially when accompanied by longer wicks. For example, if a green candle with a long lower wick is followed by a red candle, it could indicate a bearish reversal. Similarly, a red candle with a long upper wick followed by a green candle may suggest a bullish reversal.
Support and Resistance: You can use Heiken Ashi "better" candles to identify potential support and resistance levels. When the candles are consistently moving in one direction and then suddenly change color with longer wicks, it could indicate the presence of a support or resistance level.
Stop-Loss and Take-Profit: Using Heiken Ashi "better" candles can help you manage risk by determining optimal stop-loss and take-profit levels. For instance, you can place your stop-loss below the low of the most recent green candle in an uptrend or above the high of the most recent red candle in a downtrend.
Confirming Signals: Heiken Ashi "better" candles should be used in conjunction with other technical indicators, such as moving averages, oscillators, or chart patterns, to confirm signals and improve the accuracy of your analysis.
In this implementation, you have the choice of AMA, KAMA, or T3 smoothing. These are as follows:
Kaufman Adaptive Moving Average (KAMA)
The Kaufman Adaptive Moving Average (KAMA) is a type of adaptive moving average used in technical analysis to smooth out price fluctuations and identify trends. The KAMA adjusts its smoothing factor based on the market's volatility, making it more responsive in volatile markets and smoother in calm markets. The KAMA is calculated using three different efficiency ratios that determine the appropriate smoothing factor for the current market conditions. These ratios are based on the noise level of the market, the speed at which the market is moving, and the length of the moving average. The KAMA is a popular choice among traders who prefer to use adaptive indicators to identify trends and potential reversals.
Adaptive Moving Average
The Adaptive Moving Average (AMA) is a type of moving average that adjusts its sensitivity to price movements based on market conditions. It uses a ratio between the current price and the highest and lowest prices over a certain lookback period to determine its level of smoothing. The AMA can help reduce lag and increase responsiveness to changes in trend direction, making it useful for traders who want to follow trends while avoiding false signals. The AMA is calculated by multiplying a smoothing constant with the difference between the current price and the previous AMA value, then adding the result to the previous AMA value.
T3
The T3 moving average is a type of technical indicator used in financial analysis to identify trends in price movements. It is similar to the Exponential Moving Average (EMA) and the Double Exponential Moving Average (DEMA), but uses a different smoothing algorithm.
The T3 moving average is calculated using a series of exponential moving averages that are designed to filter out noise and smooth the data. The resulting smoothed data is then weighted with a non-linear function to produce a final output that is more responsive to changes in trend direction.
The T3 moving average can be customized by adjusting the length of the moving average, as well as the weighting function used to smooth the data. It is commonly used in conjunction with other technical indicators as part of a larger trading strategy.
█ Giga Kaleidoscope Modularized Trading System
Core components of an NNFX algorithmic trading strategy
The NNFX algorithm is built on the principles of trend, momentum, and volatility. There are six core components in the NNFX trading algorithm:
1. Volatility - price volatility; e.g., Average True Range, True Range Double, Close-to-Close, etc.
2. Baseline - a moving average to identify price trend
3. Confirmation 1 - a technical indicator used to identify trends
4. Confirmation 2 - a technical indicator used to identify trends
5. Continuation - a technical indicator used to identify trends
6. Volatility/Volume - a technical indicator used to identify volatility/volume breakouts/breakdown
7. Exit - a technical indicator used to determine when a trend is exhausted
What is Volatility in the NNFX trading system?
In the NNFX (No Nonsense Forex) trading system, ATR (Average True Range) is typically used to measure the volatility of an asset. It is used as a part of the system to help determine the appropriate stop loss and take profit levels for a trade. ATR is calculated by taking the average of the true range values over a specified period.
True range is calculated as the maximum of the following values:
-Current high minus the current low
-Absolute value of the current high minus the previous close
-Absolute value of the current low minus the previous close
ATR is a dynamic indicator that changes with changes in volatility. As volatility increases, the value of ATR increases, and as volatility decreases, the value of ATR decreases. By using ATR in NNFX system, traders can adjust their stop loss and take profit levels according to the volatility of the asset being traded. This helps to ensure that the trade is given enough room to move, while also minimizing potential losses.
Other types of volatility include True Range Double (TRD), Close-to-Close, and Garman-Klass
What is a Baseline indicator?
The baseline is essentially a moving average, and is used to determine the overall direction of the market.
The baseline in the NNFX system is used to filter out trades that are not in line with the long-term trend of the market. The baseline is plotted on the chart along with other indicators, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR).
Trades are only taken when the price is in the same direction as the baseline. For example, if the baseline is sloping upwards, only long trades are taken, and if the baseline is sloping downwards, only short trades are taken. This approach helps to ensure that trades are in line with the overall trend of the market, and reduces the risk of entering trades that are likely to fail.
By using a baseline in the NNFX system, traders can have a clear reference point for determining the overall trend of the market, and can make more informed trading decisions. The baseline helps to filter out noise and false signals, and ensures that trades are taken in the direction of the long-term trend.
What is a Confirmation indicator?
Confirmation indicators are technical indicators that are used to confirm the signals generated by primary indicators. Primary indicators are the core indicators used in the NNFX system, such as the Average True Range (ATR), the Moving Average (MA), and the Relative Strength Index (RSI).
The purpose of the confirmation indicators is to reduce false signals and improve the accuracy of the trading system. They are designed to confirm the signals generated by the primary indicators by providing additional information about the strength and direction of the trend.
Some examples of confirmation indicators that may be used in the NNFX system include the Bollinger Bands, the MACD (Moving Average Convergence Divergence), and the MACD Oscillator. These indicators can provide information about the volatility, momentum, and trend strength of the market, and can be used to confirm the signals generated by the primary indicators.
In the NNFX system, confirmation indicators are used in combination with primary indicators and other filters to create a trading system that is robust and reliable. By using multiple indicators to confirm trading signals, the system aims to reduce the risk of false signals and improve the overall profitability of the trades.
What is a Continuation indicator?
In the NNFX (No Nonsense Forex) trading system, a continuation indicator is a technical indicator that is used to confirm a current trend and predict that the trend is likely to continue in the same direction. A continuation indicator is typically used in conjunction with other indicators in the system, such as a baseline indicator, to provide a comprehensive trading strategy.
What is a Volatility/Volume indicator?
Volume indicators, such as the On Balance Volume (OBV), the Chaikin Money Flow (CMF), or the Volume Price Trend (VPT), are used to measure the amount of buying and selling activity in a market. They are based on the trading volume of the market, and can provide information about the strength of the trend. In the NNFX system, volume indicators are used to confirm trading signals generated by the Moving Average and the Relative Strength Index. Volatility indicators include Average Direction Index, Waddah Attar, and Volatility Ratio. In the NNFX trading system, volatility is a proxy for volume and vice versa.
By using volume indicators as confirmation tools, the NNFX trading system aims to reduce the risk of false signals and improve the overall profitability of trades. These indicators can provide additional information about the market that is not captured by the primary indicators, and can help traders to make more informed trading decisions. In addition, volume indicators can be used to identify potential changes in market trends and to confirm the strength of price movements.
What is an Exit indicator?
The exit indicator is used in conjunction with other indicators in the system, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR), to provide a comprehensive trading strategy.
The exit indicator in the NNFX system can be any technical indicator that is deemed effective at identifying optimal exit points. Examples of exit indicators that are commonly used include the Parabolic SAR, the Average Directional Index (ADX), and the Chandelier Exit.
The purpose of the exit indicator is to identify when a trend is likely to reverse or when the market conditions have changed, signaling the need to exit a trade. By using an exit indicator, traders can manage their risk and prevent significant losses.
In the NNFX system, the exit indicator is used in conjunction with a stop loss and a take profit order to maximize profits and minimize losses. The stop loss order is used to limit the amount of loss that can be incurred if the trade goes against the trader, while the take profit order is used to lock in profits when the trade is moving in the trader's favor.
Overall, the use of an exit indicator in the NNFX trading system is an important component of a comprehensive trading strategy. It allows traders to manage their risk effectively and improve the profitability of their trades by exiting at the right time.
How does Loxx's GKD (Giga Kaleidoscope Modularized Trading System) implement the NNFX algorithm outlined above?
Loxx's GKD v1.0 system has five types of modules (indicators/strategies). These modules are:
1. GKD-BT - Backtesting module (Volatility, Number 1 in the NNFX algorithm)
2. GKD-B - Baseline module (Baseline and Volatility/Volume, Numbers 1 and 2 in the NNFX algorithm)
3. GKD-C - Confirmation 1/2 and Continuation module (Confirmation 1/2 and Continuation, Numbers 3, 4, and 5 in the NNFX algorithm)
4. GKD-V - Volatility/Volume module (Confirmation 1/2, Number 6 in the NNFX algorithm)
5. GKD-E - Exit module (Exit, Number 7 in the NNFX algorithm)
(additional module types will added in future releases)
Each module interacts with every module by passing data between modules. Data is passed between each module as described below:
GKD-B => GKD-V => GKD-C(1) => GKD-C(2) => GKD-C(Continuation) => GKD-E => GKD-BT
That is, the Baseline indicator passes its data to Volatility/Volume. The Volatility/Volume indicator passes its values to the Confirmation 1 indicator. The Confirmation 1 indicator passes its values to the Confirmation 2 indicator. The Confirmation 2 indicator passes its values to the Continuation indicator. The Continuation indicator passes its values to the Exit indicator, and finally, the Exit indicator passes its values to the Backtest strategy.
This chaining of indicators requires that each module conform to Loxx's GKD protocol, therefore allowing for the testing of every possible combination of technical indicators that make up the six components of the NNFX algorithm.
What does the application of the GKD trading system look like?
Example trading system:
Backtest: Strategy with 1-3 take profits, trailing stop loss, multiple types of PnL volatility, and 2 backtesting styles
Baseline: Hull Moving Average
Volatility/Volume: Hurst Exponent
Confirmation 1: Adaptive-Lookback Variety RSI as shown on the chart above
Confirmation 2: Williams Percent Range
Continuation: Adaptive-Lookback Variety RSI
Exit: Rex Oscillator
Each GKD indicator is denoted with a module identifier of either: GKD-BT, GKD-B, GKD-C, GKD-V, or GKD-E. This allows traders to understand to which module each indicator belongs and where each indicator fits into the GKD protocol chain.
Giga Kaleidoscope Modularized Trading System Signals (based on the NNFX algorithm)
Standard Entry
1. GKD-C Confirmation 1 Signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Continuation Entry
1. Standard Entry, Baseline Entry, or Pullback; entry triggered previously
2. GKD-B Baseline hasn't crossed since entry signal trigger
3. GKD-C Confirmation Continuation Indicator signals
4. GKD-C Confirmation 1 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 2 agrees
1-Candle Rule Standard Entry
1. GKD-C Confirmation 1 signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
1-Candle Rule Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume Agrees
1-Candle Rule Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close)
2. GKD-B Volatility/Volume agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
PullBack Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is beyond 1.0x Volatility of Baseline
Next Candle:
1. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
2. GKD-C Confirmation 1 agrees
3. GKD-C Confirmation 2 agrees
4. GKD-V Volatility/Volume Agrees
]█ Setting up the GKD
The GKD system involves chaining indicators together. These are the steps to set this up.
Use a GKD-C indicator alone on a chart
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
Use a GKD-V indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Use a GKD-B indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Baseline (Baseline, Backtest)
1. Import the GKD-B Baseline into the GKD-BT Backtest: "Input into Volatility/Volume or Backtest (Baseline testing)"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline"
Volatility/Volume (Volatility/Volume, Backte st)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Solo"
2. Inside the GKD-V indicator, change the "Signal Type" setting to "Crossing" (neither traditional nor both can be backtested)
3. Import the GKD-V indicator into the GKD-BT Backtest: "Input into C1 or Backtest"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Volatility/Volume"
5. Inside the GKD-BT Backtest, a) change the setting "Backtest Type" to "Trading" if using a directional GKD-V indicator; or, b) change the setting "Backtest Type" to "Full" if using a directional or non-directional GKD-V indicator (non-directional GKD-V can only test Longs and Shorts separately)
6. If "Backtest Type" is set to "Full": Inside the GKD-BT Backtest, change the setting "Backtest Side" to "Long" or "Short
7. If "Backtest Type" is set to "Full": To allow the system to open multiple orders at one time so you test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Solo Confirmation Simple (Confirmation, Backtest)
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
1. Import the GKD-C indicator into the GKD-BT Backtest: "Input into Backtest"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Solo Confirmation Simple"
Solo Confirmation Complex without Exits (Baseline, Volatility/Volume, Confirmation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
6. Import the GKD-C into the GKD-BT Backtest: "Input into Exit or Backtest"
Solo Confirmation Complex with Exits (Baseline, Volatility/Volume, Confirmation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Import the GKD-C indicator into the GKD-E indicator: "Input into Exit"
6. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
7. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Full GKD without Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
9. Import the GKD-E into the GKD-BT Backtest: "Input into Exit or Backtest"
Full GKD with Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Import the GKD-C Continuation indicator into the GKD-E indicator: "Input into Exit"
9. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
10. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Baseline + Volatility/Volume (Baseline, Volatility/Volume, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Baseline + Volatility/Volume"
2. Inside the GKD-V indicator, make sure the "Signal Type" setting is set to "Traditional"
3. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline + Volatility/Volume"
5. Import the GKD-V into the GKD-BT Backtest: "Input into C1 or Backtest"
6. Inside the GKD-BT Backtest, change the setting "Backtest Type" to "Full". For this backtest, you must test Longs and Shorts separately
7. To allow the system to open multiple orders at one time so you can test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Requirements
Inputs
Confirmation 1: GKD-V Volatility / Volume indicator
Confirmation 2: GKD-C Confirmation indicator
Continuation: GKD-C Confirmation indicator
Solo Confirmation Simple: GKD-B Baseline
Solo Confirmation Complex: GKD-V Volatility / Volume indicator
Solo Confirmation Super Complex: GKD-V Volatility / Volume indicator
Stacked 1: None
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 1
Outputs
Confirmation 1: GKD-C Confirmation 2 indicator
Confirmation 2: GKD-C Continuation indicator
Continuation: GKD-E Exit indicator
Solo Confirmation Simple: GKD-BT Backtest
Solo Confirmation Complex: GKD-BT Backtest or GKD-E Exit indicator
Solo Confirmation Super Complex: GKD-C Continuation indicator
Stacked 1: GKD-C, GKD-V, or GKD-B Stacked 2+
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 2+ or GKD-BT Backtest
Additional features will be added in future releases.
RSI based support resistance levelsThis indicator draws support line and resistance lines in the price chart.
How ?
For drawing the support/resistance line we need to first determine the demand and supply.
We are using too-familiar indicator RSI to determine when the script is oversold and overbought.
Now oversold (in RSI) is not a point, it’s a zone. The RSI indicator comes below 30, stays there and goes up above 30. Similarly for overbought.
Now if you carefully look at the oversold region – the lowest point of the oversold region is the place where the demand came (for surety) and push the indicator (and price) up.
Similarly: the highest point of overbought is the place where (for surety) the supply came and push the indicator (and price) down.
So that’ the supply / demand line (for surety).
In this indicator, based on the RSI we are just drawing support and resistance lines in the chat. That’s all.
What is unique ?
Trendline concept is not new. RSI is not new. RSI overbought/oversold is not new.
There are indicators exist to draw trendlines. Some of them works beautifully.
However, none of these, we are aware of, uses RSI to determine it. And, we believe, the most logical way to determine support/resistance is RSI.
Note: We are not responsible for any trading/investment decision you are taking out of the outcome of this indicator.
Pivot TrendLineThe simplest version of the indicator automatically draws trendLine on your charts, with build-in functions only.
You can change the looking back length settings to get more proper lines you want.
There is also a switch to turn off the historical trendlines.
You can use this to build more advanced indicators or strategies.
Prophit Ninja: Katana DojoMaster the art of trend reading with “Prophit Ninja: Katana Dojo”.
Our dojo will set up sparring matches for you to improve your in-battle techniques without you having to track down the fight yourself. Find the strike, dodge and parry you are best at, or keep yourself well rounded to handle any environment by selecting any or all of the possible signal/alert outputs.
═════════════════════════════════════════════════════════════════════════
█ INTERPRETATION
Quickly and easily find/spot chart setups with custom pre-built signals and alerts. Sit back and allow the market to find the set-ups for you.
═════════════════════════════════════════════════════════════════════════
█ OVERVIEW
Fully adaptable multi time frame signals and alerts based on your Katana settings for:
1 — Three customizable MA lengths with 12 formula variations and an average MA of the three; each one with the ability to toggle on or off not only itself- but an adaptive glow to filter out volatility, as well as a no lag feature that removes inherit lag that exists in all moving averages.
2 — A toggle-able fibonacci adapted formula based on ichimoku cloud.
3 — A toggle-able fibonacci adapted formula based on ssl channel.
4 — A toggle-able auto fibonacci retracement with a customizable golden pocket level.
5 — A fibonacci adapted formula based on bollinger bands.
6 — A fibonacci adapted formula based on keltner channels.
7 — Adaptive Pivot Point Labels.
8 — A fibonacci adapted formula based on chandelier stops.
9 — A fibonacci adapted formula based on parabolic stop and reverses.
10 — Fibonacci based auto support and resistance levels.
11 — Fibonacci based adaptive auto trendlines.
( Included free with “ Prophit Ninja: Katana ”.)
═════════════════════════════════════════════════════════════════════════
█ EASY CUSTOMIZATION
i.imgur.com
With a fully customizable and easy-to-use input menu, this indicator gives you the ability to tailor your trading experience to your needs and see as much (or as little) information as you want to; presented in the manner you deem most viable with the following options in just a few clicks:
Color Theme- There are four color themes available which include original, colorful, monochrome and solid. These not only allow you a quick and easy way to change the colors to suit your style; they also make it so you can challenge your bias in an instant by viewing the data in a completely different way.
Attack Mode- Whether you’re a scalper, day trader, swing trader, or investor; this option allows you to see the chart based on four different risk tolerance/time expectancy mentalities in just two clicks. Investors can see what the scalpers are thinking and vice/versa to broaden their decision making and/or hone in when optimal.
Sharpness Level- This algorithm allows the user to display the data on five different smoothness levels without suffering the inherent lag that accompanies most other indicators. Whether you like to see every tick of a choppy movement, or filter out the false signals into smooth readings, you can do so at any moment.
═════════════════════════════════════════════════════════════════════════
█ PRE-BUILT ALERTS
With Prophit Ninja: Katana Dojo’s built-in alerts you can enable alerts for any piece of the Katana in just a few clicks. These alerts are way more specific and optimized than you can possibly achieve with the custom alert settings. Each checking for multiple possible activation triggers instead of one and populating the message field automatically so you can just click create.
═════════════════════════════════════════════════════════════════════════
As you can see; this dojo has the ability to adapt to any ninja and give those in control of its power the upper hand. Any mode of battle, any opponent, any circumstance- "Prophit Ninja: Katana Dojo" was built by our finest architects to improve any trainee and make sure they know when to attack, defend or simply allow the fight to play out by its easy-to-read coloring system. As long as you show up for the matches you'll have a much better chance of finding sparring matches than when you didn't.
This state-of-the-art add-on is great for experienced traders, those who just started learning to trade, or anyone in between- truly made to suit the needs of any trader, in any moment, with any mindset (along with the other indicators in our Prophit Ninja bundle) you'll notice an immediate improvement in your Prophit Ninja: Katana skill after acquiring it.
═════════════════════════════════════════════════════════════════════════
*everything displayed is part of the Prophit Ninja indicator bundle; this is an otherwise blank chart*
Pivot Point SupertrendHello All,
There are many types of SuperTrend around. Recently I thought about a Supertrend based on Pivot Points then I wrote "Pivot Point SuperTrend" script. It looks it has better performance on keeping you in the trend more.
The idea is behind this script is finding pivot point, calculating average of them and like in supertrend creating higher/lower bands by ATR. As you can see in the algorithm the script gives weigth to past pivot points, this is done for smoothing it a bit.
As I wrote above it may keep you in the trend more, lets see an example:
As an option the script can show main center line and I realized that when you are in a position, this line can be used as early exit points. (maybe half of the position size)
While using Pivot Points, I added support resistance lines by using Pivot Point, as an option the script can show S/R lines:
And also it can show Pivot Points:
When you changed Pivot Point Period you can see its reaction, in following example PP period is 4 (default value is 2). Smaller PP periods more sensitive trendlines.
Alerts added for Buy/Sell entries and Trend Reversals. (when you set alerts use the option " Once Per Bar Close ")
ENJOY!
Trend signal with AlertHello traders,
I updated the Trend signal indicator from @riffster21 () and added alerts to it.
Nothing fancy but still extremely useful
How to use the Trend signal with alerts indicator
In this screenshot, I didn't select the most optimal timeframe, neither the most optimal input for the indicator. I just wanted to explain with a very simple example, how it works and how to use it
Basically, it's being used to simulate obliques trendlines. I draw that one in pink to highligh what is the trendline simulated by the indicator
For Which timeframe ?
It's working for all timeframes.
Recommended input for the indicator ?
The greater the timeframe, the lesser the input should be. Which makes sense because setting a high value period on a weekly chart will give entry/exit signals way too late
On the contrary, on a m5 chart, setting a low value period will give too many fake signals and you'll get angry. I don't want that to happen :)
For crypto intraday trading (meaning m5 to H4), I feel the sweet spot is between 7 and 14 for the indicator input.
For crypto Swing trading (meaning H8 to weekly), an input between 3 and 5 is best
I can only strongly encourage you to apply it on a newly created chart without any other indicator and try to find the best input for the asset. Please note the ideal input might change between assets (example: BTC/USD vs ETH/BTC)
Drawing the corresponding oblique is very important the first time setting them on a chart to find the best setup
Please let me know in the comments section if you have any question
Good luck folks
Dave
trendline function - JD!EXPERIMENTAL!
As TV doesn't provide a function to draw lines between points, I wrote a function to do this in one my own indicators.
The function itself however can be applied/modified for different use cases, eg. drawing trendlines.
In this (proof of concept) example I used it to draw lines based on past high/low pivot points.
The inputs required:
* an INPUT FUNCTION (in this form, its designed to work with functions that have occasional values and na-values between them, it then connects the non-zero values to form a line)
* a BOOL (to indicate if you want to draw only the rising or falling lines)
* a DELAY (in this case this is the lookback period for the pivot-points function, this is to compensate the calculation of the past and realtime points)
The function returns:
* the function to draw the extension from the BASE-LINE to the current time (here this is the connection of the last pivot-point to the current point to bridge the gap of the lookback period, this is NOT REALTIME!)
* the function to draw the extension for the current time (here this is the continuation of the line until a new pivot-point is valid, this is DRAWN IN REALTIME!!)
* the color of the lines (in this case the lines are only colored (lime or fuchsia) if they either go up or down, else they are invisible, this is to clean up the invalid lines)
these output functions can then simply be plotted using the 'plot' function.
JD.
[LAVA] Relative Price DifferenceThis script shows the relative price difference based off the last high and low, so many bars ago. Bollinger bands are also included by default for closer inspection on the intensity of the movement or the lack thereof. Bollinger bands will follow the smoothed line which will allow the reactionary line to cross the boundary during an intense movement. With the colors selected, a gray color will appear after the color to the zero line to announce a deep correction is possible. Buy/Sell indicators show up as crosses to indicate when the price is moving in a certain direction. Sideways stagnation will have several crosses due to the close proximity to the zero line.
I use 21 in the demo here without the bollinger bands or buy/sell indicators to show the power of the script to identify bottoms and tops using the tips and hand drawn trendlines.
(This script is actually the same script as before, but listed here as the final version. Hopefully this will be my last update with this script.)
If you use and enjoy this script, please like it!
Algorithm Predator - ML-liteAlgorithm Predator - ML-lite
This indicator combines four specialized trading agents with an adaptive multi-armed bandit selection system to identify high-probability trade setups. It is designed for swing and intraday traders who want systematic signal generation based on institutional order flow patterns , momentum exhaustion , liquidity dynamics , and statistical mean reversion .
Core Architecture
Why These Components Are Combined:
The script addresses a fundamental challenge in algorithmic trading: no single detection method works consistently across all market conditions. By deploying four independent agents and using reinforcement learning algorithms to select or blend their outputs, the system adapts to changing market regimes without manual intervention.
The Four Trading Agents
1. Spoofing Detector Agent 🎭
Detects iceberg orders through persistent volume at similar price levels over 5 bars
Identifies spoofing patterns via asymmetric wick analysis (wicks exceeding 60% of bar range with volume >1.8× average)
Monitors order clustering using simplified Hawkes process intensity tracking (exponential decay model)
Signal Logic: Contrarian—fades false breakouts caused by institutional manipulation
Best Markets: Consolidations, institutional trading windows, low-liquidity hours
2. Exhaustion Detector Agent ⚡
Calculates RSI divergence between price movement and momentum indicator over 5-bar window
Detects VWAP exhaustion (price at 2σ bands with declining volume)
Uses VPIN reversals (volume-based toxic flow dissipation) to identify momentum failure
Signal Logic: Counter-trend—enters when momentum extreme shows weakness
Best Markets: Trending markets reaching climax points, over-extended moves
3. Liquidity Void Detector Agent 💧
Measures Bollinger Band squeeze (width <60% of 50-period average)
Identifies stop hunts via 20-bar high/low penetration with immediate reversal and volume spike
Detects hidden liquidity absorption (volume >2× average with range <0.3× ATR)
Signal Logic: Breakout anticipation—enters after liquidity grab but before main move
Best Markets: Range-bound pre-breakout, volatility compression zones
4. Mean Reversion Agent 📊
Calculates price z-scores relative to 50-period SMA and standard deviation (triggers at ±2σ)
Implements Ornstein-Uhlenbeck process scoring (mean-reverting stochastic model)
Uses entropy analysis to detect algorithmic trading patterns (low entropy <0.25 = high predictability)
Signal Logic: Statistical reversion—enters when price deviates significantly from statistical equilibrium
Best Markets: Range-bound, low-volatility, algorithmically-dominated instruments
Adaptive Selection: Multi-Armed Bandit System
The script implements four reinforcement learning algorithms to dynamically select or blend agents based on performance:
Thompson Sampling (Default - Recommended):
Uses Bayesian inference with beta distributions (tracks alpha/beta parameters per agent)
Balances exploration (trying underused agents) vs. exploitation (using proven winners)
Each agent's win/loss history informs its selection probability
Lite Approximation: Uses pseudo-random sampling from price/volume noise instead of true random number generation
UCB1 (Upper Confidence Bound):
Calculates confidence intervals using: average_reward + sqrt(2 × ln(total_pulls) / agent_pulls)
Deterministic algorithm favoring agents with high uncertainty (potential upside)
More conservative than Thompson Sampling
Epsilon-Greedy:
Exploits best-performing agent (1-ε)% of the time
Explores randomly ε% of the time (default 10%, configurable 1-50%)
Simple, transparent, easily tuned via epsilon parameter
Gradient Bandit:
Uses softmax probability distribution over agent preference weights
Updates weights via gradient ascent based on rewards
Best for Blend mode where all agents contribute
Selection Modes:
Switch Mode: Uses only the selected agent's signal (clean, decisive)
Blend Mode: Combines all agents using exponentially weighted confidence scores controlled by temperature parameter (smooth, diversified)
Lock Agent Feature:
Optional manual override to force one specific agent
Useful after identifying which agent dominates your specific instrument
Only applies in Switch mode
Four choices: Spoofing Detector, Exhaustion Detector, Liquidity Void, Mean Reversion
Memory System
Dual-Layer Architecture:
Short-Term Memory: Stores last 20 trade outcomes per agent (configurable 10-50)
Long-Term Memory: Stores episode averages when short-term reaches transfer threshold (configurable 5-20 bars)
Memory Boost Mechanism: Recent performance modulates agent scores by up to ±20%
Episode Transfer: When an agent accumulates sufficient results, averages are condensed into long-term storage
Persistence: Manual restoration of learned parameters via input fields (alpha, beta, weights, microstructure thresholds)
How Memory Works:
Agent generates signal → outcome tracked after 8 bars (performance horizon)
Result stored in short-term memory (win = 1.0, loss = 0.0)
Short-term average influences agent's future scores (positive feedback loop)
After threshold met (default 10 results), episode averaged into long-term storage
Long-term patterns (weighted 30%) + short-term patterns (weighted 70%) = total memory boost
Market Microstructure Analysis
These advanced metrics quantify institutional order flow dynamics:
Order Flow Toxicity (Simplified VPIN):
Measures buy/sell volume imbalance over 20 bars: |buy_vol - sell_vol| / (buy_vol + sell_vol)
Detects informed trading activity (institutional players with non-public information)
Values >0.4 indicate "toxic flow" (informed traders active)
Lite Approximation: Uses simple open/close heuristic instead of tick-by-tick trade classification
Price Impact Analysis (Simplified Kyle's Lambda):
Measures market impact efficiency: |price_change_10| / sqrt(volume_sum_10)
Low values = large orders with minimal price impact ( stealth accumulation )
High values = retail-dominated moves with high slippage
Lite Approximation: Uses simplified denominator instead of regression-based signed order flow
Market Randomness (Entropy Analysis):
Counts unique price changes over 20 bars / 20
Measures market predictability
High entropy (>0.6) = human-driven, chaotic price action
Low entropy (<0.25) = algorithmic trading dominance (predictable patterns)
Lite Approximation: Simple ratio instead of true Shannon entropy H(X) = -Σ p(x)·log₂(p(x))
Order Clustering (Simplified Hawkes Process):
Tracks self-exciting event intensity (coordinated order activity)
Decays at 0.9× per bar, spikes +1.0 when volume >1.5× average
High intensity (>0.7) indicates clustering (potential spoofing/accumulation)
Lite Approximation: Simple exponential decay instead of full λ(t) = μ + Σ α·exp(-β(t-tᵢ)) with MLE
Signal Generation Process
Multi-Stage Validation:
Stage 1: Agent Scoring
Each agent calculates internal score based on its detection criteria
Scores must exceed agent-specific threshold (adjusted by sensitivity multiplier)
Agent outputs: Signal direction (+1/-1/0) and Confidence level (0.0-1.0)
Stage 2: Memory Boost
Agent scores multiplied by memory boost factor (0.8-1.2 based on recent performance)
Successful agents get amplified, failing agents get dampened
Stage 3: Bandit Selection/Blending
If Adaptive Mode ON:
Switch: Bandit selects single best agent, uses only its signal
Blend: All agents combined using softmax-weighted confidence scores
If Adaptive Mode OFF:
Traditional consensus voting with confidence-squared weighting
Signal fires when consensus exceeds threshold (default 70%)
Stage 4: Confirmation Filter
Raw signal must repeat for consecutive bars (default 3, configurable 2-4)
Minimum confidence threshold: 0.25 (25%) enforced regardless of mode
Trend alignment check: Long signals require trend_score ≥ -2, Short signals require trend_score ≤ 2
Stage 5: Cooldown Enforcement
Minimum bars between signals (default 10, configurable 5-15)
Prevents over-trading during choppy conditions
Stage 6: Performance Tracking
After 8 bars (performance horizon), signal outcome evaluated
Win = price moved in signal direction, Loss = price moved against
Results fed back into memory and bandit statistics
Trading Modes (Presets)
Pre-configured parameter sets:
Conservative: 85% consensus, 4 confirmations, 15-bar cooldown
Expected: 60-70% win rate, 3-8 signals/week
Best for: Swing trading, capital preservation, beginners
Balanced: 70% consensus, 3 confirmations, 10-bar cooldown
Expected: 55-65% win rate, 8-15 signals/week
Best for: Day trading, most traders, general use
Aggressive: 60% consensus, 2 confirmations, 5-bar cooldown
Expected: 50-58% win rate, 15-30 signals/week
Best for: Scalping, high-frequency trading, active management
Elite: 75% consensus, 3 confirmations, 12-bar cooldown
Expected: 58-68% win rate, 5-12 signals/week
Best for: Selective trading, high-conviction setups
Adaptive: 65% consensus, 2 confirmations, 8-bar cooldown
Expected: Varies based on learning
Best for: Experienced users leveraging bandit system
How to Use
1. Initial Setup (5 Minutes):
Select Trading Mode matching your style (start with Balanced)
Enable Adaptive Learning (recommended for automatic agent selection)
Choose Thompson Sampling algorithm (best all-around performance)
Keep Microstructure Metrics enabled for liquid instruments (>100k daily volume)
2. Agent Tuning (Optional):
Adjust Agent Sensitivity multipliers (0.5-2.0):
<0.8 = Highly selective (fewer signals, higher quality)
0.9-1.2 = Balanced (recommended starting point)
1.3 = Aggressive (more signals, lower individual quality)
Monitor dashboard for 20-30 signals to identify dominant agent
If one agent consistently outperforms, consider using Lock Agent feature
3. Bandit Configuration (Advanced):
Blend Temperature (0.1-2.0):
0.3 = Sharp decisions (best agent dominates)
0.5 = Balanced (default)
1.0+ = Smooth (equal weighting, democratic)
Memory Decay (0.8-0.99):
0.90 = Fast adaptation (volatile markets)
0.95 = Balanced (most instruments)
0.97+ = Long memory (stable trends)
4. Signal Interpretation:
Green triangle (▲): Long signal confirmed
Red triangle (▼): Short signal confirmed
Dashboard shows:
Active agent (highlighted row with ► marker)
Win rate per agent (green >60%, yellow 40-60%, red <40%)
Confidence bars (█████ = maximum confidence)
Memory size (short-term buffer count)
Colored zones display:
Entry level (current close)
Stop-loss (1.5× ATR)
Take-profit 1 (2.0× ATR)
Take-profit 2 (3.5× ATR)
5. Risk Management:
Never risk >1-2% per signal (use ATR-based stops)
Signals are entry triggers, not complete strategies
Combine with your own market context analysis
Consider fundamental catalysts and news events
Use "Confirming" status to prepare entries (not to enter early)
6. Memory Persistence (Optional):
After 50-100 trades, check Memory Export Panel
Record displayed alpha/beta/weight values for each agent
Record VPIN and Kyle threshold values
Enable "Restore From Memory" and input saved values to continue learning
Useful when switching timeframes or restarting indicator
Visual Components
On-Chart Elements:
Spectral Layers: EMA8 ± 0.5 ATR bands (dynamic support/resistance, colored by trend)
Energy Radiance: Multi-layer glow boxes at signal points (intensity scales with confidence, configurable 1-5 layers)
Probability Cones: Projected price paths with uncertainty wedges (15-bar projection, width = confidence × ATR)
Connection Lines: Links sequential signals (solid = same direction continuation, dotted = reversal)
Kill Zones: Risk/reward boxes showing entry, stop-loss, and dual take-profit targets
Signal Markers: Triangle up/down at validated entry points
Dashboard (Configurable Position & Size):
Regime Indicator: 4-level trend classification (Strong Bull/Bear, Weak Bull/Bear)
Mode Status: Shows active system (Adaptive Blend, Locked Agent, or Consensus)
Agent Performance Table: Real-time win%, confidence, and memory stats
Order Flow Metrics: Toxicity and impact indicators (when microstructure enabled)
Signal Status: Current state (Long/Short/Confirming/Waiting) with confirmation progress
Memory Panel (Configurable Position & Size):
Live Parameter Export: Alpha, beta, and weight values per agent
Adaptive Thresholds: Current VPIN sensitivity and Kyle threshold
Save Reminder: Visual indicator if parameters should be recorded
What Makes This Original
This script's originality lies in three key innovations:
1. Genuine Meta-Learning Framework:
Unlike traditional indicator mashups that simply display multiple signals, this implements authentic reinforcement learning (multi-armed bandits) to learn which detection method works best in current conditions. The Thompson Sampling implementation with beta distribution tracking (alpha for successes, beta for failures) is statistically rigorous and adapts continuously. This is not post-hoc optimization—it's real-time learning.
2. Episodic Memory Architecture with Transfer Learning:
The dual-layer memory system mimics human learning patterns:
Short-term memory captures recent performance (recency bias)
Long-term memory preserves historical patterns (experience)
Automatic transfer mechanism consolidates knowledge
Memory boost creates positive feedback loops (successful strategies become stronger)
This architecture allows the system to adapt without retraining , unlike static ML models that require batch updates.
3. Institutional Microstructure Integration:
Combines retail-focused technical analysis (RSI, Bollinger Bands, VWAP) with institutional-grade microstructure metrics (VPIN, Kyle's Lambda, Hawkes processes) typically found in academic finance literature and professional trading systems, not standard retail platforms. While simplified for Pine Script constraints, these metrics provide insight into informed vs. uninformed trading , a dimension entirely absent from traditional technical analysis.
Mashup Justification:
The four agents are combined specifically for risk diversification across failure modes:
Spoofing Detector: Prevents false breakout losses from manipulation
Exhaustion Detector: Prevents chasing extended trends into reversals
Liquidity Void: Exploits volatility compression (different regime than trending)
Mean Reversion: Provides mathematical anchoring when patterns fail
The bandit system ensures the optimal tool is automatically selected for each market situation, rather than requiring manual interpretation of conflicting signals.
Why "ML-lite"? Simplifications and Approximations
This is the "lite" version due to necessary simplifications for Pine Script execution:
1. Simplified VPIN Calculation:
Academic Implementation: True VPIN uses volume bucketing (fixed-volume bars) and tick-by-tick buy/sell classification via Lee-Ready algorithm or exchange-provided trade direction flags
This Implementation: 20-bar rolling window with simple open/close heuristic (close > open = buy volume)
Impact: May misclassify volume during ranging/choppy markets; works best in directional moves
2. Pseudo-Random Sampling:
Academic Implementation: Thompson Sampling requires true random number generation from beta distributions using inverse transform sampling or acceptance-rejection methods
This Implementation: Deterministic pseudo-randomness derived from price and volume decimal digits: (close × 100 - floor(close × 100)) + (volume % 100) / 100
Impact: Not cryptographically random; may have subtle biases in specific price ranges; provides sufficient variation for agent selection
3. Hawkes Process Approximation:
Academic Implementation: Full Hawkes process uses maximum likelihood estimation with exponential kernels: λ(t) = μ + Σ α·exp(-β(t-tᵢ)) fitted via iterative optimization
This Implementation: Simple exponential decay (0.9 multiplier) with binary event triggers (volume spike = event)
Impact: Captures self-exciting property but lacks parameter optimization; fixed decay rate may not suit all instruments
4. Kyle's Lambda Simplification:
Academic Implementation: Estimated via regression of price impact on signed order flow over multiple time intervals: Δp = λ × Δv + ε
This Implementation: Simplified ratio: price_change / sqrt(volume_sum) without proper signed order flow or regression
Impact: Provides directional indicator of impact but not true market depth measurement; no statistical confidence intervals
5. Entropy Calculation:
Academic Implementation: True Shannon entropy requires probability distribution: H(X) = -Σ p(x)·log₂(p(x)) where p(x) is probability of each price change magnitude
This Implementation: Simple ratio of unique price changes to total observations (variety measure)
Impact: Measures diversity but not true information entropy with probability weighting; less sensitive to distribution shape
6. Memory System Constraints:
Full ML Implementation: Neural networks with backpropagation, experience replay buffers (storing state-action-reward tuples), gradient descent optimization, and eligibility traces
This Implementation: Fixed-size array queues with simple averaging; no gradient-based learning, no state representation beyond raw scores
Impact: Cannot learn complex non-linear patterns; limited to linear performance tracking
7. Limited Feature Engineering:
Advanced Implementation: Dozens of engineered features, polynomial interactions (x², x³), dimensionality reduction (PCA, autoencoders), feature selection algorithms
This Implementation: Raw agent scores and basic market metrics (RSI, ATR, volume ratio); minimal transformation
Impact: May miss subtle cross-feature interactions; relies on agent-level intelligence rather than feature combinations
8. Single-Instrument Data:
Full Implementation: Multi-asset correlation analysis (sector ETFs, currency pairs, volatility indices like VIX), lead-lag relationships, risk-on/risk-off regimes
This Implementation: Only OHLCV data from displayed instrument
Impact: Cannot incorporate broader market context; vulnerable to correlated moves across assets
9. Fixed Performance Horizon:
Full Implementation: Adaptive horizon based on trade duration, volatility regime, or profit target achievement
This Implementation: Fixed 8-bar evaluation window
Impact: May evaluate too early in slow markets or too late in fast markets; one-size-fits-all approach
Performance Impact Summary:
These simplifications make the script:
✅ Faster: Executes in milliseconds vs. seconds (or minutes) for full academic implementations
✅ More Accessible: Runs on any TradingView plan without external data feeds, APIs, or compute servers
✅ More Transparent: All calculations visible in Pine Script (no black-box compiled models)
✅ Lower Resource Usage: <500 bars lookback, minimal memory footprint
⚠️ Less Precise: Approximations may reduce statistical edge by 5-15% vs. academic implementations
⚠️ Limited Scope: Cannot capture tick-level dynamics, multi-order-book interactions, or cross-asset flows
⚠️ Fixed Parameters: Some thresholds hardcoded rather than dynamically optimized
When to Upgrade to Full Implementation:
Consider professional Python/C++ versions with institutional data feeds if:
Trading with >$100K capital where precision differences materially impact returns
Operating in microsecond-competitive environments (HFT, market making)
Requiring regulatory-grade audit trails and reproducibility
Backtesting with tick-level precision for strategy validation
Need true real-time adaptation with neural network-based learning
For retail swing/day trading and position management, these approximations provide sufficient signal quality while maintaining usability, transparency, and accessibility. The core logic—multi-agent detection with adaptive selection—remains intact.
Technical Notes
All calculations use standard Pine Script built-in functions ( ta.ema, ta.atr, ta.rsi, ta.bb, ta.sma, ta.stdev, ta.vwap )
VPIN and Kyle's Lambda use simplified formulas optimized for OHLCV data (see "Lite" section above)
Thompson Sampling uses pseudo-random noise from price/volume decimal digits for beta distribution sampling
No repainting: All calculations use confirmed bar data (no forward-looking)
Maximum lookback: 500 bars (set via max_bars_back parameter)
Performance evaluation: 8-bar forward-looking window for reward calculation (clearly disclosed)
Confidence threshold: Minimum 0.25 (25%) enforced on all signals
Memory arrays: Dynamic sizing with FIFO queue management
Limitations and Disclaimers
Not Predictive: This indicator identifies patterns in historical data. It cannot predict future price movements with certainty.
Requires Human Judgment: Signals are entry triggers, not complete trading strategies. Must be confirmed with your own analysis, risk management rules, and market context.
Learning Period Required: The adaptive system requires 50-100 bars minimum to build statistically meaningful performance data for bandit algorithms.
Overfitting Risk: Restoring memory parameters from one market regime to a drastically different regime (e.g., low volatility to high volatility) may cause poor initial performance until system re-adapts.
Approximation Limitations: Simplified calculations (see "Lite" section) may underperform academic implementations by 5-15% in highly efficient markets.
No Guarantee of Profit: Past performance, whether backtested or live-traded, does not guarantee future performance. All trading involves risk of loss.
Forward-Looking Bias: Performance evaluation uses 8-bar forward window—this creates slight look-ahead for learning (though not for signals). Real-time performance may differ from indicator's internal statistics.
Single-Instrument Limitation: Does not account for correlations with related assets or broader market regime changes.
Recommended Settings
Timeframe: 15-minute to 4-hour charts (sufficient volatility for ATR-based stops; adequate bar volume for learning)
Assets: Liquid instruments with >100k daily volume (forex majors, large-cap stocks, BTC/ETH, major indices)
Not Recommended: Illiquid small-caps, penny stocks, low-volume altcoins (microstructure metrics unreliable)
Complementary Tools: Volume profile, order book depth, market breadth indicators, fundamental catalysts
Position Sizing: Risk no more than 1-2% of capital per signal using ATR-based stop-loss
Signal Filtering: Consider external confluence (support/resistance, trendlines, round numbers, session opens)
Start With: Balanced mode, Thompson Sampling, Blend mode, default agent sensitivities (1.0)
After 30+ Signals: Review agent win rates, consider increasing sensitivity of top performers or locking to dominant agent
Alert Configuration
The script includes built-in alert conditions:
Long Signal: Fires when validated long entry confirmed
Short Signal: Fires when validated short entry confirmed
Alerts fire once per bar (after confirmation requirements met)
Set alert to "Once Per Bar Close" for reliability
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
神奇9转Indicator Name: 9 Countdown
Author: Lao Seng on Gold (Laoseng Lunjin)
Indicator Description:
This indicator is based on the “Setup” phase logic from DM technical framework. It automatically tracks consecutive upward or downward closes and clearly highlights key potential turning points at the 5th, 7th, 9th, 13th, 19th, and 21st candles.
Core Logic:
If the current close is higher than the close 4 bars earlier → count as one step in an upward sequence.
If the current close is lower than the close 4 bars earlier → count as one step in a downward sequence.
The sequence resets when the condition is broken.
Important observation levels are highlighted at bars 5/7/9/13/19/21 within each sequence.
How to Use:
Applicable to multiple timeframes. Recommended to combine with trendlines and support/resistance zones.
The 9th bar signal is often monitored as a potential reversal zone.
It does not imply an immediate buy or sell; it is used to assess sentiment and timing windows.
Tips:
Can be used as a timing and rhythm tool for swing trading.
Suitable for gold (XAUUSD), indices, and major FX pairs.
Disclaimer:
This script is for research and educational purposes only and does not constitute investment advice. Please use it in conjunction with your own strategy and risk management.
指标名称:德马克9转
作者:老僧论金
指标简介:
本指标基于德马克技术理论中的“计数(Setup)”阶段逻辑,自动追踪价格连续上涨/下跌的天数,并在图表中清晰标出关键转折点(第5、7、9、13、19、21根K线)。
核心逻辑:
如果当前收盘价高于4根K线前的收盘价 → 连续上涨记1次
如果低于4根K线前 → 连续下跌记1次
连续统计,遇中断重置
在图表中标记:5/7/9/13/19/21 为重要观察节点
使用方法:
适用于各周期,建议搭配趋势线与支撑阻力位共同使用
第9根信号常用于潜在反转区域判断
不代表立即买卖,仅作情绪与时间窗口判断
小贴士:
可作为波段交易辅助节奏工具
可叠加在黄金(XAUUSD)、指数、外汇品种中使用
免责声明:
该脚本仅供研究学习使用,不构成投资建议。请结合自身策略和风险控制使用。翻译成英文
Multi EMA + Indicators + Mini-Dashboard + Reversals v6📘 Multi EMA + Indicators + Mini-Dashboard + Reversals v6
🧩 Overview
This indicator is a multi-EMA setup that combines trend, momentum, and reversal analysis in a single visual framework.
It integrates four exponential moving averages (EMAs), key oscillators (RSI, MACD, Stochastic, CCI), volatility filtering (ATR), and a dynamic mini-dashboard that summarizes all signals in real time.
Its purpose is to help traders visually confirm trend alignment, filter valid entries, and identify possible trend continuation or reversal points.
It can display buy/sell arrows, detect reversal candles, and issue alerts when trading conditions are met.
⚙️ Core Components
1. Moving Averages (EMA Setup)
EMA1 (fast) and EMA2 (medium) define the short-term trend and trigger bias.
When the price is above both EMAs → bullish bias.
When below → bearish bias.
EMA3 and EMA4 act as trend filters. Their slopes (up or down) confirm overall momentum and help validate signals.
Each EMA has customizable lengths, sources, and colors for up/down trends.
This “EMA stack” is the foundation of the setup — a structured trend-following framework that adapts to market speed and volatility.
2. Momentum and Confirmation Filters
Each indicator can be individually enabled or disabled for flexibility.
RSI: confirms direction (above/below 50).
MACD: detects momentum crossover (MACD > Signal for bullish confirmation).
Stochastic: identifies trend continuation (K > D for longs, K < D for shorts).
CCI: adds trend bias above/below a threshold.
ATR Filter: filters out small, low-volatility candles to reduce noise.
You can activate only the filters that fit your trading plan — for instance, trend traders often use RSI and MACD, while scalpers may rely on Stochastic and ATR.
3. Reversal Detection
The indicator includes an optional Reversal Section that independently detects potential turning points.
It combines multiple configurable criteria:
Candlestick patterns (Bullish Hammer, Shooting Star).
Large Candle filter — detects unusually large bars (relative to close).
Price-to-EMA distance — identifies overextended moves that might revert.
RSI Divergence — detects potential momentum shifts.
RSI Overbought/Oversold zones (70/30 by default).
Doji Candles — sign of indecision.
A bullish or bearish reversal signal appears when enough selected criteria are met.
All sub-modules can be toggled on/off individually, giving you full control over sensitivity.
4. Signal Logic
Buy and sell signals are triggered when EMA alignment and the chosen confirmations agree:
Buy Signal
→ Price above EMA1 & EMA2
→ Confirmations (RSI/MACD/Stoch/CCI/ATR) pass
→ Trend filters (EMA3/EMA4) point upward
Sell Signal
→ Price below EMA1 & EMA2
→ Confirmations align bearishly
→ Trend filters (EMA3/EMA4) slope downward
Reversal signals can appear independently, even against the current EMA trend, depending on your settings.
5. Visual Dashboard
A mini-dashboard appears near the chart showing:
Current trade bias (LONG / SHORT / NEUTRAL)
EMA3 and EMA4 trend directions (↑ / ↓)
Quick visual bars (🟩 / 🟥) for each filter: RSI, MACD, Stoch, ATR, CCI, EMA filters
Reversal criteria status (Doji, RSI divergence, candle size, etc.)
This panel gives you a compact overview of all indicator states at a glance.
The color of the panel changes dynamically — green for bullish, red for bearish, gray for neutral.
6. Alerts
Built-in alerts allow automation or notifications:
Buy Alert
Sell Alert
Reversal Buy
Reversal Sell
You can connect these alerts to TradingView notifications or external bots for semi-automated execution.
💡 How to Use
✅ Trend-Following Setup
Focus on trades in the direction of EMA1 & EMA2.
Confirm with EMA3 & EMA4 trending in the same direction.
Use RSI/MACD/Stoch filters to ensure momentum supports the trade.
Avoid entries when ATR filter indicates low volatility.
🔄 Reversal Setup
Enable the Reversal section for potential tops/bottoms.
Look for reversal buy signals near support zones or after strong downtrends.
Use RSI divergence or Doji + Hammer signals as confirmation.
Combine with key chart areas (supply/demand or previous swing levels).
⚖️ Combination Approach
Trade continuation signals when all EMAs are aligned and filters are green.
Trade reversals only when at a key area (support/resistance) and confirmed by reversal conditions.
Always check higher-timeframe bias before entering a trade.
🧭 Practical Tips
Use different EMA sets for different timeframes:
9/21/50/100 for swing or trend trades.
5/13/34/89 for intraday scalping.
Turn off filters you don’t use to reduce lag.
Always validate signals with price structure, not just indicator alignment.
Practice in replay mode before live trading.
🗺️ Key Chart Confluence (Highly Recommended)
Although the indicator provides structured signals, its best use is in confluence with:
Support and resistance levels
Supply/demand zones
Trendlines and channels
Liquidity pools
Volume clusters
Signals aligned with strong key areas on the chart tend to have greater reliability than isolated indicator triggers.
I use EMA 1 - 20 Open ; EMA 2 - 20 Close ; EMA 3 - 50 ; EMA 4 - 200 or 100 , but that's me...
⚠️ Important Disclaimer
This indicator is a technical tool, not a guarantee of results.
Trading involves risk, and no signal is ever 100% accurate.
Every trader should develop a personal strategy, use proper risk management, and adapt settings to their instrument and timeframe.
Always combine indicator signals with key chart areas, higher-timeframe context, and your own analysis before taking a trade.
vip//@version=5
indicator(" fmfm1 ", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=500)
// ==============================
// | الإعدادات الأساسية
// ==============================
atrPeriod = input.int(10, "ATR Period", minval=1, group="Supertrend")
factor = input.float(3.0, "Supertrend Multiplier", minval=0.1, step=0.1, group="Supertrend")
rsiLength = input.int(14, "RSI Length", minval=2, group="RSI")
macdFast = input.int(12, "MACD Fast Length", minval=1, group="MACD")
macdSlow = input.int(26, "MACD Slow Length", minval=1, group="MACD")
macdSig = input.int(9, "MACD Signal Length", minval=1, group="MACD")
emaLen1 = input.int(20, "EMA 20 Length", group="EMA")
emaLen2 = input.int(50, "EMA 50 Length", group="EMA")
tablePos = input.string("top_right", "Table Position",
options= , group="Display")
// إعدادات الصناديق
showBoxes = input.bool(true, "إظهار صناديق الإشارات", group="صناديق الإشارات")
boxTransparency = input.int(70, "شفافية الصندوق", minval=0, maxval=100, group="صناديق الإشارات")
boxHeight = input.float(0.15, "ارتفاع الصندوق %", minval=0.05, maxval=1.0, step=0.05, group="صناديق الإشارات")
// فلتر الشركات
enableFilter = input.bool(false, "تفعيل فلتر الشركات", group="فلتر الشركات")
symbol1 = input.string("", "الشركة 1", group="فلتر الشركات")
symbol2 = input.string("", "الشركة 2", group="فلتر الشركات")
symbol3 = input.string("", "الشركة 3", group="فلتر الشركات")
symbol4 = input.string("", "الشركة 4", group="فلتر الشركات")
symbol5 = input.string("", "الشركة 5", group="فلتر الشركات")
symbol6 = input.string("", "الشركة 6", group="فلتر الشركات")
// التنبيهات
enableAlerts = input.bool(true, "تفعيل التنبيهات", group="التنبيهات")
alertOnCall = input.bool(true, "تنبيه عند CALL", group="التنبيهات")
alertOnPut = input.bool(true, "تنبيه عند PUT", group="التنبيهات")
// إعدادات مناطق العرض والطلب
zigzagLen = input.int(9, 'ZigZag Length', group = 'Order Block Settings')
numberObShow = input.int(1, 'عدد مناطق العرض والطلب المعروضة', group = 'Order Block Settings', minval = 1, maxval = 10)
bearishOrderblockColor = input.color(color.new(#dc1515, 18), title = 'لون منطقة العرض', group = 'Order Block Settings')
bullishOrderblockColor = input.color(color.new(#58bd0f, 10), title = 'لون منطقة الطلب', group = 'Order Block Settings')
// إعدادات نسبة القوة
showStrengthLabels = input.bool(true, 'عرض نسبة القوة', group = 'Strength Settings')
strengthThreshold = input.int(60, 'حد التنبيه', group = 'Strength Settings', minval = 50, maxval = 90)
enableStrengthAlert = input.bool(true, 'تفعيل تنبيهات القوة', group = 'Strength Settings')
// ==============================
// | حسابات Supertrend و المؤشرات
// ==============================
atrValue = ta.atr(atrPeriod)
hl2Value = (high + low) / 2
upperBand = hl2Value - factor * atrValue
lowerBand = hl2Value + factor * atrValue
var float trendLine = na
trendLine := close > nz(trendLine , hl2Value) ? math.max(upperBand, nz(trendLine , upperBand)) : math.min(lowerBand, nz(trendLine , lowerBand))
bull = close > trendLine
bear = close < trendLine
buySignal = ta.crossover(close, trendLine)
sellSignal = ta.crossunder(close, trendLine)
ema20 = ta.ema(close, emaLen1)
ema50 = ta.ema(close, emaLen2)
emaBull = ema20 > ema50
emaBear = ema20 < ema50
rsi = ta.rsi(close, rsiLength)
rsiBull = rsi > 50
rsiBear = rsi < 50
macd = ta.ema(close, macdFast) - ta.ema(close, macdSlow)
signal = ta.ema(macd, macdSig)
macdBull = macd > signal
macdBear = macd < signal
vwapValue = ta.vwap(close)
vwapBull = close > vwapValue
vwapBear = close < vwapValue
// الإشارات النهائية
allBull = (bull and rsiBull and macdBull and emaBull and vwapBull)
allBear = (bear and rsiBear and macdBear and emaBear and vwapBear)
finalSignal = allBull ? "CALL " : allBear ? "PUT " :" NEUTRAL"
finalBg = allBull ? color.new(color.green, 0) : allBear ? color.new(color.red, 0) : color.new(color.orange, 0)
// حفظ الحالة السابقة للإشارات
var bool wasCall = false
var bool wasPut = false
// اكتشاف إشارة CALL جديدة
newCallSignal = allBull and not wasCall
// اكتشاف إشارة PUT جديدة
newPutSignal = allBear and not wasPut
// تحديث الحالة
wasCall := allBull
wasPut := allBear
// ==============================
// | Labels للإشارات الجديدة - تم تعطيلها
// ==============================
// تم إزالة Labels CALL/PUT من فوق وتحت الشموع
// ==============================
// | التنبيهات
// ==============================
if enableAlerts
if alertOnCall and newCallSignal
alert("🔔 إشارة CALL على " + syminfo.ticker + " | السعر: " + str.tostring(close, format.mintick), alert.freq_once_per_bar)
if alertOnPut and newPutSignal
alert("🔔 إشارة PUT على " + syminfo.ticker + " | السعر: " + str.tostring(close, format.mintick), alert.freq_once_per_bar)
// ==============================
// | لوحة المعلومات
// ==============================
var table dash = table.new(position=tablePos, columns=2, rows=9, border_width=1)
if barstate.islast
table.cell(dash, 0, 0, "Ind", text_color=color.white, bgcolor=color.blue, text_size=size.tiny)
table.cell(dash, 1, 0, "Sig", text_color=color.white, bgcolor=color.blue, text_size=size.tiny)
table.cell(dash, 0, 1, "Sup", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 1, buySignal ? "BUY" : sellSignal ? "SELL" : bull ? "UP" : "DN",
text_color=color.white,
bgcolor= buySignal ? color.new(color.green, 0) : sellSignal ? color.new(color.red, 0) : bull ? color.new(color.green, 0) : color.new(color.red, 0),
text_size=size.tiny)
table.cell(dash, 0, 2, "EMA", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 2, emaBull ? "UP" : "DN", text_color=color.white,
bgcolor=emaBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)
table.cell(dash, 0, 3, "RSI", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 3, rsiBull ? "UP" : "DN", text_color=color.white,
bgcolor=rsiBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)
table.cell(dash, 0, 4, "MACD", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 4, macdBull ? "UP" : "DN", text_color=color.white,
bgcolor=macdBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)
table.cell(dash, 0, 5, "VWAP", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 5, vwapBull ? "UP" : "DN", text_color=color.white,
bgcolor=vwapBull ? color.new(color.green, 0) : color.new(color.red, 0), text_size=size.tiny)
table.cell(dash, 0, 6, "دخول", text_color=color.yellow, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 6, finalSignal, text_color=color.white, bgcolor=finalBg, text_size=size.tiny)
table.cell(dash, 0, 7, "Price", text_color=color.white, bgcolor=color.black, text_size=size.tiny)
table.cell(dash, 1, 7, str.tostring(close, format.mintick), text_color=color.white, bgcolor=color.gray, text_size=size.tiny)
// ==============================
// | رسم المؤشرات
// ==============================
plot(trendLine, "Supertrend", color=bull ? color.green : color.red, linewidth=2)
plot(ema20, "EMA 20", color=color.blue, linewidth=1)
// ==============================
// | مناطق العرض والطلب
// ==============================
// أنواع البيانات
type orderblock
float value
int barStart
int barEnd
box block
bool broken
label supplyLabel
label demandLabel
// المصفوفات
var array bullishOrderblock = array.new()
var array bearishOrderblock = array.new()
var array highValIndex = array.new()
var array lowValIndex = array.new()
var array highVal = array.new_float()
var array lowVal = array.new_float()
// المتغيرات
var bool drawUp = false
var bool drawDown = false
var string lastState = na
var bool to_up = false
var bool to_down = false
var int trendZZ = 1
atrOB = ta.atr(14)
// حساب الاتجاه
to_up := high >= ta.highest(high, zigzagLen)
to_down := low <= ta.lowest(low, zigzagLen)
trendZZ := trendZZ == 1 and to_down ? -1 : trendZZ == -1 and to_up ? 1 : trendZZ
// تحديد تغيير الاتجاه للأعلى
if ta.change(trendZZ) != 0 and trendZZ == 1
array.push(highValIndex, time )
array.push(highVal, high )
if array.size(lowVal) > 1
drawUp := false
// تحديد تغيير الاتجاه للأسفل
if ta.change(trendZZ) != 0 and trendZZ == -1
array.push(lowValIndex, time )
array.push(lowVal, low )
if array.size(highVal) > 1
drawDown := false
// دالة حساب نسبة القوة
calculateStrengthRatio() =>
float supplyStrength = 0.0
float demandStrength = 0.0
int supplyTouches = 0
for i = 1 to 20
if i < bar_index
if close < open
supplyTouches += 1
int demandTouches = 0
for i = 1 to 20
if i < bar_index
if close > open
demandTouches += 1
float avgVolume = ta.sma(volume, 20)
float volumeRatio = volume / avgVolume
float rsiValue = ta.rsi(close, 14)
if rsiValue > 50
demandStrength := rsiValue
supplyStrength := 100 - rsiValue
else
supplyStrength := 100 - rsiValue
demandStrength := rsiValue
// إنشاء منطقة عرض (Bearish Order Block)
if array.size(lowVal) > 1 and drawDown == false
if close < array.get(lowVal, array.size(lowVal) - 1)
drawDown := true
lastState := 'down'
orderblock newOrderblock = orderblock.new()
float max = 0
int bar = na
for i = (time - array.get(lowValIndex, array.size(lowValIndex) - 1) - (time - time )) / (time - time ) to 0 by 1
if high > max
max := high
bar := time
newOrderblock.barStart := bar
newOrderblock.barEnd := time
newOrderblock.broken := false
newOrderblock.value := max
newOrderblock.block := box.new(
left = newOrderblock.barStart,
top = newOrderblock.value,
right = newOrderblock.barEnd,
bottom = newOrderblock.value - atrOB * 0.30,
xloc = xloc.bar_time,
bgcolor = bearishOrderblockColor,
border_width = 1,
border_color = color.new(#cd1212, 0))
= calculateStrengthRatio()
newOrderblock.supplyLabel := na
newOrderblock.demandLabel := na
if showStrengthLabels
newOrderblock.supplyLabel := label.new(
x = time,
y = newOrderblock.value + atrOB * 0.5,
text = "عرض: " + str.tostring(supplyStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = supplyStr >= strengthThreshold ? color.new(color.red, 0) : color.new(color.orange, 0),
textcolor = color.white,
style = label.style_label_down,
size = size.tiny)
newOrderblock.demandLabel := label.new(
x = time,
y = newOrderblock.value - atrOB * 0.5,
text = "طلب: " + str.tostring(demandStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = color.new(color.gray, 30),
textcolor = color.white,
style = label.style_label_up,
size = size.tiny)
if enableStrengthAlert and supplyStr >= strengthThreshold
alert("تنبيه: قوة العرض " + str.tostring(supplyStr, "#") + "% - تجاوزت " + str.tostring(strengthThreshold) + "%", alert.freq_once_per_bar)
array.push(bearishOrderblock, newOrderblock)
if array.size(bearishOrderblock) > 20
oldBlock = array.shift(bearishOrderblock)
if not na(oldBlock.supplyLabel)
label.delete(oldBlock.supplyLabel)
if not na(oldBlock.demandLabel)
label.delete(oldBlock.demandLabel)
// إنشاء منطقة طلب (Bullish Order Block)
if array.size(highVal) > 1 and drawUp == false
if close > array.get(highVal, array.size(highVal) - 1)
drawUp := true
lastState := 'up'
orderblock newOrderblock = orderblock.new()
float min = 999999999
int bar = na
for i = (time - array.get(highValIndex, array.size(highValIndex) - 1) - (time - time )) / (time - time ) to 0 by 1
if low < min
min := low
bar := time
newOrderblock.barStart := bar
newOrderblock.barEnd := time
newOrderblock.broken := false
newOrderblock.value := min
newOrderblock.block := box.new(
left = newOrderblock.barStart,
top = newOrderblock.value + atrOB * 0.12,
right = newOrderblock.barEnd,
bottom = newOrderblock.value,
xloc = xloc.bar_time,
bgcolor = bullishOrderblockColor,
border_width = 1,
border_color = color.new(#52ae10, 0))
= calculateStrengthRatio()
newOrderblock.supplyLabel := na
newOrderblock.demandLabel := na
if showStrengthLabels
newOrderblock.demandLabel := label.new(
x = time,
y = newOrderblock.value - atrOB * 0.5,
text = "طلب: " + str.tostring(demandStr, "#") + "%",
xloc = xloc.bar_time,
yloc = yloc.price,
color = demandStr >= strengthThreshold ? color.new(color.green, 0) : color.new(color.blue, 0),
textcolor = color.white,
style = label.style_label_up,
size = size.tiny)
if enableStrengthAlert and demandStr >= strengthThreshold
alert("تنبيه: قوة الطلب " + str.tostring(demandStr, "#") + "% - تجاوزت " + str.tostring(strengthThreshold) + "%", alert.freq_once_per_bar)
array.push(bullishOrderblock, newOrderblock)
if array.size(bullishOrderblock) > 20
oldBlock = array.shift(bullishOrderblock)
if not na(oldBlock.supplyLabel)
label.delete(oldBlock.supplyLabel)
if not na(oldBlock.demandLabel)
label.delete(oldBlock.demandLabel)
// متغيرات العداد
var int activeBullishCount = 0
var int activeBearishCount = 0
// تحديث مناطق الطلب
if array.size(bullishOrderblock) > 0
orderblock testOrderblock = na
int counter = 0
activeBullishCount := 0
for i = array.size(bullishOrderblock) - 1 to 0 by 1
testOrderblock := array.get(bullishOrderblock, i)
if counter < numberObShow
testOrderblock.block.set_right(time)
= calculateStrengthRatio()
if showStrengthLabels
if not na(testOrderblock.demandLabel)
label.set_x(testOrderblock.demandLabel, time)
label.set_text(testOrderblock.demandLabel, "طلب: " + str.tostring(demandStr, "#") + "%")
label.set_color(testOrderblock.demandLabel, demandStr >= strengthThreshold ? color.new(color.green, 0) : color.new(color.blue, 0))
if not na(testOrderblock.supplyLabel)
label.set_x(testOrderblock.supplyLabel, time)
label.set_text(testOrderblock.supplyLabel, "عرض: " + str.tostring(supplyStr, "#") + "%")
if close < testOrderblock.value
testOrderblock.block.delete()
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
array.remove(bullishOrderblock, i)
else
activeBullishCount += 1
counter := counter + 1
else
testOrderblock.block.set_right(testOrderblock.barStart)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
// تحديث مناطق العرض
if array.size(bearishOrderblock) > 0
orderblock testOrderblock = na
int counter = 0
activeBearishCount := 0
for i = array.size(bearishOrderblock) - 1 to 0 by 1
testOrderblock := array.get(bearishOrderblock, i)
if counter < numberObShow
testOrderblock.block.set_right(time)
= calculateStrengthRatio()
if showStrengthLabels
if not na(testOrderblock.supplyLabel)
label.set_x(testOrderblock.supplyLabel, time)
label.set_text(testOrderblock.supplyLabel, "عرض: " + str.tostring(supplyStr, "#") + "%")
label.set_color(testOrderblock.supplyLabel, supplyStr >= strengthThreshold ? color.new(color.red, 0) : color.new(color.orange, 0))
if not na(testOrderblock.demandLabel)
label.set_x(testOrderblock.demandLabel, time)
label.set_text(testOrderblock.demandLabel, "طلب: " + str.tostring(demandStr, "#") + "%")
if close > testOrderblock.value
testOrderblock.block.delete()
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
array.remove(bearishOrderblock, i)
else
activeBearishCount += 1
counter := counter + 1
else
testOrderblock.block.set_right(testOrderblock.barStart)
if not na(testOrderblock.supplyLabel)
label.delete(testOrderblock.supplyLabel)
if not na(testOrderblock.demandLabel)
label.delete(testOrderblock.demandLabel)
// ================= SETTINGS =================
paint_bars = input.bool(false, "Paint bars?", group="Bars Settings")
catch_flat = input.bool(false, "Try to catch flat?", group="Bars Settings")
uptrend_colour = input.color(color.rgb(13,247,20), "Uptrend colour", group="Bars Settings")
downtrend_colour = input.color(color.rgb(250,10,10), "Downtrend colour", group="Bars Settings")
neutraltrend_colour = input.color(color.rgb(245,252,252), "Neutral colour", group="Bars Settings")
// ================= TABLE SETTINGS =================
show_header = input(false, "Show header?", group="Table Settings")
show_ema_value = input(false, "Show EMA value?", group="Table Settings")
dashboard_position = input.string("Middle right", "Position", options= , group="Table Settings")
text_color = input.color(color.white, "Text colour", group="Table Settings")
table_color = input.color(color.rgb(240,249,250), "Border colour", group="Table Settings")
uptrend_indicator = input.string("🟢", "Uptrend indicator", group="Table Settings")
downtrend_indicator = input.string("🔴", "Downtrend indicator", group="Table Settings")
neutraltrend_indicator = input.string("🟡", "Neutral indicator", group="Table Settings")
header_bg_color = input.color(color.rgb(18,18,18,75), "Header background", group="Table Settings")
uptrend_bg_color = input.color(color.new(color.green,90), "Up BG", group="Table Settings")
downtrend_bg_color = input.color(color.new(color.red,90), "Down BG", group="Table Settings")
neutraltrend_bg_color = input.color(color.new(color.yellow,90), "Neutral BG", group="Table Settings")
// ================= EMA SETTINGS =================
trend_identification_approach = input.string("Direction of a single EMA", "Trend approach", options= , group="EMA Settings")
ema1_length = input.int(50, "EMA length", minval=1, maxval=800, group="EMA Settings")
ema2_length = input.int(200, "Additional EMA length", minval=20, maxval=800, group="EMA Settings")
// ================= TIMEFRAMES =================
show_3m = input(true, "Show 3m", group="Timeframe Settings")
show_5m = input(true, "Show 5m", group="Timeframe Settings")
show_15m = input(true, "Show 15m", group="Timeframe Settings")
show_1h = input(true, "Show 1h", group="Timeframe Settings")
show_4h = input(true, "Show 4h", group="Timeframe Settings")
// ================= TABLE CREATION =================
var table_position = switch dashboard_position
"Top left" => position.top_left
"Top right" => position.top_right
"Bottom left" => position.bottom_left
"Bottom right" => position.bottom_right
"Top center" => position.top_center
"Bottom center" => position.bottom_center
"Middle right" => position.middle_right
=> position.middle_right
// جدول صغير جدًا جدًا
var t = table.new(position=table_position, columns=3, rows=20, frame_color=table_color, frame_width=0, border_color=table_color, border_width=0)
// ================= FUNCTIONS =================
calc_smma(src, len) =>
var float smma = na
smma := na(smma) ? ta.sma(src, len) : (smma * (len - 1) + src) / len
smma
calc_zlema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema1 + (ema1 - ema2)
check_impulse() =>
hi = calc_smma(high, 34)
lo = calc_smma(low, 34)
mi = calc_zlema(hlc3, 34)
md = (mi > hi ? mi - hi : mi < lo ? mi - lo : 0)
sb = ta.sma(md, 9)
sh = md - sb
sh != 0
get_trend_status() =>
impulse = catch_flat ? check_impulse() : true
ema1_current = ta.ema(close, ema1_length)
ema1_prev = ema1_current
ema2_current = ta.ema(close, ema2_length)
ema2_prev = ema2_current
if trend_identification_approach == "Direction of a single EMA"
bg = not impulse ? neutraltrend_bg_color : ema1_current > ema1_prev ? uptrend_bg_color : ema1_current < ema1_prev ? downtrend_bg_color : neutraltrend_bg_color
ind = not impulse ? neutraltrend_indicator : ema1_current > ema1_prev ? uptrend_indicator : ema1_current < ema1_prev ? downtrend_indicator : neutraltrend_indicator
else
bg = not impulse ? neutraltrend_bg_color : ema1_current > ema2_current ? uptrend_bg_color : ema1_current < ema2_current ? downtrend_bg_color : neutraltrend_bg_color
ind = not impulse ? neutraltrend_indicator : ema1_current > ema2_current ? uptrend_indicator : ema1_current < ema2_current ? downtrend_indicator : neutraltrend_indicator
// ================= TREND REQUESTS =================
= request.security(syminfo.tickerid, "3", get_trend_status())
= request.security(syminfo.tickerid, "5", get_trend_status())
= request.security(syminfo.tickerid, "15", get_trend_status())
= request.security(syminfo.tickerid, "60", get_trend_status())
= request.security(syminfo.tickerid, "240", get_trend_status())
// ================= SMALL TABLE =================
if barstate.islast
tiny = size.tiny
if show_header
table.cell(t, 0, 0, "TF", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)
table.cell(t, 1, 0, "Trend", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)
if show_ema_value
table.cell(t, 2, 0, "EMA", text_color=text_color, text_size=tiny, bgcolor=header_bg_color)
if show_3m
table.cell(t, 0, 1, "3m", text_color=text_color, text_size=tiny, bgcolor=bg_3m)
table.cell(t, 1, 1, ind_3m, text_color=text_color, text_size=tiny, bgcolor=bg_3m)
if show_5m
table.cell(t, 0, 2, "5m", text_color=text_color, text_size=tiny, bgcolor=bg_5m)
table.cell(t, 1, 2, ind_5m, text_color=text_color, text_size=tiny, bgcolor=bg_5m)
if show_15m
table.cell(t, 0, 3, "15m", text_color=text_color, text_size=tiny, bgcolor=bg_15m)
table.cell(t, 1, 3, ind_15m, text_color=text_color, text_size=tiny, bgcolor=bg_15m)
if show_1h
table.cell(t, 0, 4, "1h", text_color=text_color, text_size=tiny, bgcolor=bg_1h)
table.cell(t, 1, 4, ind_1h, text_color=text_color, text_size=tiny, bgcolor=bg_1h)
if show_4h
table.cell(t, 0, 5, "4h", text_color=text_color, text_size=tiny, bgcolor=bg_4h)
table.cell(t, 1, 5, ind_4h, text_color=text_color, text_size=tiny, bgcolor=bg_4h)
// --- إعدادات الإدخال ---
string GRP_SETTINGS = "الإعدادات"
var bool showTable = input.bool(true, "إظهار جدول التحليل", group=GRP_SETTINGS)
var int lookbackPeriod = input.int(5, "فترة التحليل (أشرطة)", minval=5, maxval=100, group=GRP_SETTINGS)
var int maxBarsDisplay = input.int(5, "أقصى عدد أشرطة مرئية", minval=5, maxval=20, group=GRP_SETTINGS)
var color buyColor = input.color(color.new(#00C853, 0), "لون الشراء", group=GRP_SETTINGS)
var color sellColor = input.color(color.new(#FF1744, 0), "لون البيع", group=GRP_SETTINGS)
var string tablePosition = input.string("Top-Right", "موضع الجدول", options= , group=GRP_SETTINGS)
// --- متغيرات الحالة ---
var float volumes = array.new_float(0)
var float buyVolumes = array.new_float(0)
var float sellVolumes = array.new_float(0)
var float netFlows = array.new_float(0)
var float priceChanges = array.new_float(0)
var float highs = array.new_float(0)
var float lows = array.new_float(0)
var float opens = array.new_float(0)
var float closes = array.new_float(0)
var table trendTable = na
// --- دالة بناء الشريط البصري ---
f_buildBar(int filled, int total) =>
string result = ""
for i = 1 to total
result += i <= filled ? "█" : "░"
result
// --- جمع البيانات ---
if barstate.isconfirmed
float h = high
float l = low
float o = open
float c = close
float v = volume
float prevClose = nz(close , c)
float priceChange = c - prevClose
float priceRange = math.max(h - l, syminfo.mintick)
float buyV = v * (c - l) / priceRange
float sellV = v * (h - c) / priceRange
float netFlow = buyV - sellV
if array.size(volumes) >= lookbackPeriod
array.shift(volumes)
array.shift(buyVolumes)
array.shift(sellVolumes)
array.shift(netFlows)
array.shift(priceChanges)
array.shift(highs)
array.shift(lows)
array.shift(opens)
array.shift(closes)
array.push(volumes, v)
array.push(buyVolumes, buyV)
array.push(sellVolumes, sellV)
array.push(netFlows, netFlow)
array.push(priceChanges, priceChange)
array.push(highs, h)
array.push(lows, l)
array.push(opens, o)
array.push(closes, c)
// --- منطق الجدول ---
if showTable and array.size(volumes) >= lookbackPeriod
// === 1. الاتجاه ===
float totalVol = array.sum(volumes)
float totalBuyVol = array.sum(buyVolumes)
float totalSellVol = array.sum(sellVolumes)
float buyPerc = totalVol > 0 ? (totalBuyVol / totalVol) * 100 : 0
float sellPerc = totalVol > 0 ? (totalSellVol / totalVol) * 100 : 0
float diffPerc = buyPerc - sellPerc
string diffText = str.tostring(math.abs(diffPerc), "#.##") + "%"
int filledBars = int(math.round((math.abs(diffPerc) / 100) * maxBarsDisplay))
string visualBar = f_buildBar(filledBars, maxBarsDisplay)
color barColor = totalBuyVol > totalSellVol ? buyColor : sellColor
// === 2. الديناميكية ===
float meanFlow = array.avg(netFlows)
float stdFlow = array.stdev(netFlows)
float skew = 0.0
if stdFlow > 1e-10
for i = 0 to array.size(netFlows) - 1
float z = (array.get(netFlows, i) - meanFlow) / stdFlow
skew += math.pow(z, 3)
skew /= array.size(netFlows)
float skew_norm = math.max(-1, math.min(1, skew / 2))
float pBuy = totalBuyVol / totalVol
float pSell = totalSellVol / totalVol
pBuy := math.max(pBuy, 1e-10)
pSell := math.max(pSell, 1e-10)
float entropy = -(pBuy * math.log(pBuy) + pSell * math.log(pSell))
float normEntropy = entropy / math.log(2)
float entropy_score = 1 - normEntropy
float sumX = array.sum(priceChanges)
float sumY = array.sum(netFlows)
float sumXY = 0.0, sumX2 = 0.0, sumY2 = 0.0
int n = array.size(priceChanges)
for i = 0 to n - 1
float x = array.get(priceChanges, i)
float y = array.get(netFlows, i)
sumXY += x * y
sumX2 += x * x
sumY2 += y * y
float numerator = n * sumXY - sumX * sumY
float denominator = math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY))
float corr = denominator != 0 ? numerator / denominator : 0.0
float signal = math.abs(totalBuyVol - totalSellVol)
float noise = totalVol - signal
float snr = signal / (noise + 1e-10)
float snr_norm = math.min(1, snr / 3)
float dynamicScore = (skew_norm + entropy_score + corr + snr_norm) / 4
float finalPerc = (dynamicScore + 1) * 50
int filledDynamicBars = int(math.round(finalPerc / 100 * maxBarsDisplay))
string dynamicBar = f_buildBar(filledDynamicBars, maxBarsDisplay)
color dynamicColor = finalPerc > 50 ? buyColor : sellColor
// === 3. السلوك ===
float controlSum = 0.0
float reactionSum = 0.0
float closeDomSum = 0.0
int upBars = 0
int totalBars = array.size(closes)
for i = 0 to totalBars - 1
float h_i = array.get(highs, i)
float l_i = array.get(lows, i)
float o_i = array.get(opens, i)
float c_i = array.get(closes, i)
float v_i = array.get(volumes, i)
float range_i = math.max(h_i - l_i, syminfo.mintick)
controlSum += (c_i - l_i) / range_i
reactionSum += v_i / range_i
closeDomSum += math.abs(c_i - o_i) / range_i
if c_i > o_i
upBars += 1
float controlScore = controlSum / float(totalBars)
float volumeBiasScore = float(upBars) / float(totalBars)
float reactionAvg = reactionSum / float(totalBars)
float reactionScore = reactionAvg / math.max(ta.highest(reactionAvg, math.max(lookbackPeriod * 2, 10)), 1e-10)
reactionScore := math.min(1.0, reactionScore)
float closeDominanceScore = closeDomSum / float(totalBars)
float behaviorScore = (controlScore + volumeBiasScore + reactionScore + closeDominanceScore) / 4.0
float behaviorPerc = math.min(100.0, math.max(0.0, behaviorScore * 100.0))
int filledBehaviorBars = int(math.round(behaviorPerc / 100.0 * maxBarsDisplay))
string behaviorBar = f_buildBar(filledBehaviorBars, maxBarsDisplay)
color behaviorColor = behaviorPerc > 50 ? buyColor : sellColor
// === إنشاء الجدول (2 عمود، 4 صفوف) ===
if na(trendTable)
if tablePosition == "Top-Right"
trendTable := table.new(position.top_right, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else if tablePosition == "Top-Left"
trendTable := table.new(position.top_left, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else if tablePosition == "Bottom-Right"
trendTable := table.new(position.bottom_right, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
else
trendTable := table.new(position.bottom_left, 2, 4, bgcolor=color.new(#121212, 90), border_color=color.gray, border_width=1)
// === الصف 1: الاتجاه ===
table.cell(trendTable, 0, 1, "الاتجاه", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 1, diffText + " | " + visualBar, text_color=barColor, bgcolor=color.new(barColor, 80))
// === الصف 2: الديناميكية ===
table.cell(trendTable, 0, 2, "الديناميكية", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 2, str.tostring(finalPerc, "#.##") + "% | " + dynamicBar, text_color=dynamicColor, bgcolor=color.new(dynamicColor, 80))
// === الصف 3: السلوك ===
table.cell(trendTable, 0, 3, "السلوك", text_color=color.white, bgcolor=color.new(color.gray, 90))
table.cell(trendTable, 1, 3, str.tostring(behaviorPerc, "#.##") + "% | " + behaviorBar, text_color=behaviorColor, bgcolor=color.new(behaviorColor, 80))
FPeriod = input(35, title='Fibo Period')
plotF1618 = input(title='Plot 1.618 Level?', defval=true)
Fhigh = ta.highest(FPeriod)
Flow = ta.lowest(FPeriod)
FH = ta.highestbars(high, FPeriod)
FL = ta.lowestbars(low, FPeriod)
downfibo = FH < FL
// تصغير حجم الإشارات مع الحفاظ على النص
plotshape(Flow, style=shape.labelup, location=location.absolute, size=size.tiny,
color=color.new(#000000, 40), textcolor=color.new(#c7c9d0, 0), show_last=1, text="🟢", offset=FL)
plotshape(Fhigh, style=shape.labeldown, location=location.absolute, size=size.tiny,
color=color.new(#000000, 30), textcolor=color.new(#e3e5e8, 0), show_last=1, text="🔴", offset=FH)
// === Inputs ===
trendLineLength = input.int(10, 'Trend Line Detection Sensitivity', minval=10)
upTlColor = input.color(color.new(color.teal, 15), title='Trend Line Colors', inline='tl')
downTlColor = input.color(color.new(color.red, 15), title=' ', inline='tl')
showTrendLines = input.bool(true, 'Show Trend Lines')
// === Helper Functions ===
extendTrendline(lineId, startIndex, startValue, endIndex, endValue) =>
slope = (endValue - startValue) / (endIndex - startIndex)
newEndIndex = bar_index
newEndValue = startValue + slope * (newEndIndex - startIndex)
line.set_x2(lineId, newEndIndex)
line.set_y2(lineId, newEndValue)
getSlope(startIndex, startValue, endIndex, endValue) =>
(endValue - startValue) / (endIndex - startIndex)
// === Trendlines Calculation ===
var line newBearishTrendline = na
var line newBullishTrendline = na
if showTrendLines
phTrend = ta.pivothigh(high, trendLineLength, trendLineLength)
plTrend = ta.pivotlow(low, trendLineLength, trendLineLength)
bullishTrendLineStart = ta.valuewhen(not na(plTrend), bar_index , 1)
bullishTrendLineEnd = ta.valuewhen(not na(plTrend), bar_index , 0)
bearishTrendLineStart = ta.valuewhen(not na(phTrend), bar_index , 1)
bearishTrendLineEnd = ta.valuewhen(not na(phTrend), bar_index , 0)
bullishTrendLineStartVal = ta.valuewhen(not na(plTrend), low , 1)
bullishTrendLineEndVal = ta.valuewhen(not na(plTrend), low , 0)
bearishTrendLineStartVal = ta.valuewhen(not na(phTrend), high , 1)
bearishTrendLineEndVal = ta.valuewhen(not na(phTrend), high , 0)
line.delete(newBearishTrendline)
line.delete(newBullishTrendline)
slopeBearish = getSlope(bearishTrendLineStart, bearishTrendLineStartVal, bearishTrendLineEnd, bearishTrendLineEndVal)
slopeBullish = getSlope(bullishTrendLineStart, bullishTrendLineStartVal, bullishTrendLineEnd, bullishTrendLineEndVal)
if slopeBearish < 0
newBearishTrendline := line.new(x1=bearishTrendLineStart, y1=bearishTrendLineStartVal, x2=bar_index, y2=bearishTrendLineEndVal, xloc=xloc.bar_index, color=downTlColor, width=2)
if slopeBullish > 0
newBullishTrendline := line.new(x1=bullishTrendLineStart, y1=bullishTrendLineStartVal, x2=bar_index, y2=bullishTrendLineEndVal, xloc=xloc.bar_index, color=upTlColor, width=2)
if not na(newBearishTrendline)
extendTrendline(newBearishTrendline, bearishTrendLineStart, bearishTrendLineStartVal, bearishTrendLineEnd, bearishTrendLineEndVal)
if not na(newBullishTrendline)
extendTrendline(newBullishTrendline, bullishTrendLineStart, bullishTrendLineStartVal, bullishTrendLineEnd, bullishTrendLineEndVal)
// ========== إعدادات FVG ==========
showFVG = input.bool(defval = true, title = "Show Fair Value Gaps", group = "FVG")
contract = input.bool(defval = false, title = "Contract Violated FVG", group = "FVG")
closeOnly = input.bool(defval = false, title = "Show Closest Up/Down FVG Only", group = "FVG")
fvgcol = input.color(defval = #f2da07, title = "FVG Color", group = "FVG")
fvgtra = input.int(defval = 30, minval = 0, maxval = 100, title = "FVG Transparency", group = "FVG")
// ========== دالة FVG ==========
fvg(direction) =>
var fvgMat = matrix.new(5)
var fvgDrawings = array.new()
fvgMat.add_col(0, array.from(math.sign(close - open), close, high, low, time))
if fvgMat.columns() > 3
fvgMat.remove_col(fvgMat.columns() - 1)
if fvgMat.row(0).sum() == direction
getDir = math.sign(direction)
= switch getDir
-1 =>
=>
col = switch closeOnly
true => #00000000
=> color.new(fvgcol, fvgtra)
fvgDrawings.push(
box.new(int(fvgMat.get(4, 1)), y, last_bar_time, y1, xloc = xloc.bar_time,
border_color = col, bgcolor = col)
)
fvgDrawings
// ========== تنفيذ FVG ==========
if showFVG
fvgDn = fvg(-3)
fvgUp = fvg(3)
// معالجة FVG الهابط
if fvgDn.size() > 0
for i = fvgDn.size() - 1 to 0
getfvg = fvgDn.get(i)
if high >= getfvg.get_top()
getfvg.delete()
fvgDn.remove(i)
else if contract
if high > getfvg.get_bottom()
getfvg.set_bottom(high)
// معالجة FVG الصاعد
if fvgUp.size() > 0
for i = fvgUp.size() - 1 to 0
getfvg = fvgUp.get(i)
if low <= getfvg.get_bottom()
getfvg.delete()
fvgUp.remove(i)
else if contract
if low < getfvg.get_top()
getfvg.set_top(low)
// إظهار أقرب FVG فقط
if closeOnly and barstate.islast
minDist = matrix.new(1, 2, 20e20)
if fvgDn.size() > 0
for i = fvgDn.size() - 1 to 0
getBottom = fvgDn.get(i).get_bottom()
minDist.set(0, 1, math.min(minDist.get(0, 1), math.abs(close - getBottom)))
if math.abs(close - getBottom) == minDist.get(0, 1)
minDist.set(0, 0, i)
fvgDn.get(i).set_right(fvgDn.get(i).get_left())
fvgDn.get(int(minDist.get(0, 0))).set_bgcolor(color.new(fvgcol, fvgtra))
fvgDn.get(int(minDist.get(0, 0))).set_border_color(color.new(fvgcol, fvgtra))
fvgDn.get(int(minDist.get(0, 0))).set_right(last_bar_time)
minDist.set(0, 0, 0)
minDist.set(0, 1, 20e20)
if fvgUp.size() > 0
for i = fvgUp.size() - 1 to 0
getTop = fvgUp.get(i).get_top()
minDist.set(0, 1, math.min(minDist.get(0, 1), math.abs(close - getTop)))
if math.abs(close - getTop) == minDist.get(0, 1)
minDist.set(0, 0, i)
fvgUp.get(i).set_right(fvgUp.get(i).get_left())
fvgUp.get(int(minDist.get(0, 0))).set_bgcolor(color.new(fvgcol, fvgtra))
fvgUp.get(int(minDist.get(0, 0))).set_border_color(color.new(fvgcol, fvgtra))
fvgUp.get(int(minDist.get(0, 0))).set_right(last_bar_time)
//----------------------------------------
// Key Levels - 4H Only
//----------------------------------------
Show_4H_Levels = input.bool(defval=true, title='عرض مستويات 4H', group='Key Levels')
Color_Resistance = input.color(title='لون المقاومة', defval=color.green, group='Key Levels', inline='colors')
Color_Support = input.color(title='لون الدعم', defval=color.red, group='Key Levels', inline='colors')
Style_4H_Levels = input.string('Dotted', 'نمط الخطوط', , group="Key Levels")
Text_4H_Levels = input.bool(defval=false, title='نص مختصر', group='Key Levels')
labelsize = input.string(defval='Medium', title='حجم النص', options= , group = "Key Levels")
// تعديل مستويات الدعم والمقاومة
Resistance_Offset = input.float(defval=0.0, title='تعديل المقاومة (نقاط)', step=0.01, group='تعديل المستويات', tooltip='رفع (+) أو خفض (-) مستوى المقاومة بالنقاط')
Support_Offset = input.float(defval=0.0, title='تعديل الدعم (نقاط)', step=0.01, group='تعديل المستويات', tooltip='رفع (+) أو خفض (-) مستوى الدعم بالنقاط')
// إعدادات خط المنتصف
Show_Middle_Line = input.bool(defval=true, title='عرض خط المنتصف', group='"0"')
Color_Middle = input.color(title='لون خط المنتصف', defval=color.blue, group='Key Levels')
//----------------------------------------
// Targets Settings
//----------------------------------------
Show_Targets = input.bool(defval=true, title='إظهار الأهداف', group='إعدادات الأهداف')
// أهداف صاعدة (بعد اختراق المقاومة)
Target1_Up_Distance = input.float(defval=0.5, title='المسافة للهدف الأول %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target1_Up = input.color(title='لون الهدف الأول', defval=color.new(color.lime, 40), group='أهداف الاختراق (صعود)')
Target2_Up_Distance = input.float(defval=1.0, title='المسافة للهدف الثاني %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target2_Up = input.color(title='لون الهدف الثاني', defval=color.new(color.lime, 20), group='أهداف الاختراق (صعود)')
Target3_Up_Distance = input.float(defval=1.5, title='المسافة للهدف الثالث %', minval=0.01, step=0.1, group='أهداف الاختراق (صعود)')
Color_Target3_Up = input.color(title='لون الهدف الثالث', defval=color.lime, group='أهداف الاختراق (صعود)')
// أهداف هابطة (بعد كسر الدعم)
Target1_Down_Distance = input.float(defval=0.5, title='المسافة للهدف الأول %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target1_Down = input.color(title='لون الهدف الأول', defval=color.new(color.fuchsia, 40), group='أهداف الكسر (هبوط)')
Target2_Down_Distance = input.float(defval=1.0, title='المسافة للهدف الثاني %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target2_Down = input.color(title='لون الهدف الثاني', defval=color.new(color.fuchsia, 20), group='أهداف الكسر (هبوط)')
Target3_Down_Distance = input.float(defval=1.5, title='المسافة للهدف الثالث %', minval=0.01, step=0.1, group='أهداف الكسر (هبوط)')
Color_Target3_Down = input.color(title='لون الهدف الثالث', defval=color.fuchsia, group='أهداف الكسر (هبوط)')
Style_Targets = input.string('Dashed', 'نمط خطوط الأهداف', , group="إعدادات الأهداف")
//----------------------------------------
// Signal Settings
//----------------------------------------
Show_Signals = input.bool(defval=true, title='إظهار إشارات البيع والشراء', group='إعدادات الإشارات')
Signal_Size = input.string(defval='Normal', title='حجم الإشارة', options= , group='إعدادات الإشارات')
Color_Buy_Signal = input.color(title='لون إشارة الشراء', defval=color.new(color.lime, 0), group='إعدادات الإشارات')
Color_Sell_Signal = input.color(title='لون إشارة البيع', defval=color.new(color.red, 0), group='إعدادات الإشارات')
//----------------------------------------
// FVG Settings
//----------------------------------------
Show_FVG = input.bool(defval=true, title='إظهار FVG', group='إعدادات FVG')
FVG_Lookback = input.int(defval=10, title='عدد الشموع للبحث عن FVG', minval=3, maxval=50, group='إعدادات FVG')
Color_Bullish_FVG = input.color(title='لون FVG الصاعد', defval=color.new(color.lime, 80), group='إعدادات FVG')
Color_Bearish_FVG = input.color(title='لون FVG الهابط', defval=color.new(color.red, 80), group='إعدادات FVG')
FVG_Border_Color = input.color(title='لون إطار FVG', defval=color.new(color.gray, 50), group='إعدادات FVG')
//========================================
// HELPER FUNCTIONS
//========================================
// Format price display
formatPrice(float price) =>
str.tostring(price, format.mintick)
// Get signal size
getSignalSize(string size_str) =>
switch size_str
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
=> size.normal
// Get line style
getLineStyle(string x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
=> line.style_solid
// Get font size
getFontSize(string size_str) =>
switch size_str
'Small' => size.small
'Medium' => size.normal
'Large' => size.large
=> size.normal
// Detect Bullish FVG
detectBullishFVG(int lookback) =>
float fvg_top = na
float fvg_bottom = na
int fvg_left = na
if bar_index >= 3
int max_bars = math.min(lookback, bar_index - 2)
for i = 1 to max_bars
if bar_index >= i + 1
if low > high
fvg_top := low
fvg_bottom := high
fvg_left := bar_index - i
break
// Detect Bearish FVG
detectBearishFVG(int lookback) =>
float fvg_top = na
float fvg_bottom = na
int fvg_left = na
if bar_index >= 3
int max_bars = math.min(lookback, bar_index - 2)
for i = 1 to max_bars
if bar_index >= i + 1
if high < low
fvg_top := low
fvg_bottom := high
fvg_left := bar_index - i
break
// Extend line to current bar
extendToCurrentBar(int offset_bars) =>
timenow + (time - time ) * offset_bars
//========================================
// MAIN CALCULATIONS
//========================================
// Get 4H levels
= request.security(syminfo.tickerid, '240', [time , high ], lookahead=barmerge.lookahead_on)
= request.security(syminfo.tickerid, '240', [time , low ], lookahead=barmerge.lookahead_on)
// Apply offsets to levels
float adjusted_resistance = intrah_value + Resistance_Offset
float adjusted_support = intral_value + Support_Offset
// Text labels
string resistance_text = Text_4H_Levels ? 'كول' : 'مقاومة'
string support_text = Text_4H_Levels ? 'بوت' : 'دعم'
// Style settings
int line_width = 1
string font_size = getFontSize(labelsize)
string line_style = getLineStyle(Style_4H_Levels)
string target_style = getLineStyle(Style_Targets)
int distance_right = 25
//========================================
// BREAKOUT DETECTION & TRACKING
//========================================
var bool resistance_broken = false
var bool support_broken = false
var float last_resistance = na
var float last_support = na
var int buy_signal_bar = na
var int sell_signal_bar = na
var float buy_signal_price = na
var float sell_signal_price = na
// Detect resistance breakout
if close > adjusted_resistance and not resistance_broken
resistance_broken := true
support_broken := false
last_resistance := adjusted_resistance
buy_signal_bar := bar_index
buy_signal_price := adjusted_resistance
// Detect support breakdown
if close < adjusted_support and not support_broken
support_broken := true
resistance_broken := false
last_support := adjusted_support
sell_signal_bar := bar_index
sell_signal_price := adjusted_support
// Cancel breakout if price returns
if close < adjusted_resistance and resistance_broken
resistance_broken := false
buy_signal_bar := na
buy_signal_price := na
if close > adjusted_support and support_broken
support_broken := false
sell_signal_bar := na
sell_signal_price := na
// Reset on new level formation
if adjusted_resistance != last_resistance
resistance_broken := false
last_resistance := adjusted_resistance
buy_signal_bar := na
buy_signal_price := na
if adjusted_support != last_support
support_broken := false
last_support := adjusted_support
sell_signal_bar := na
sell_signal_price := na
//========================================
// DRAWING - SUPPORT & RESISTANCE LEVELS
//========================================
if barstate.islast and Show_4H_Levels
int right_extension = extendToCurrentBar(distance_right)
// Draw Resistance Line
var line resistance_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Resistance, width=line_width, style=line_style)
line.set_xy1(resistance_line, intrah_time, adjusted_resistance)
line.set_xy2(resistance_line, right_extension, adjusted_resistance)
line.set_color(resistance_line, Color_Resistance)
var label resistance_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Resistance, size=font_size)
label.set_xy(resistance_label, right_extension, adjusted_resistance)
label.set_text(resistance_label, formatPrice(adjusted_resistance) + " " + resistance_text)
label.set_textcolor(resistance_label, Color_Resistance)
// Draw Support Line
var line support_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Support, width=line_width, style=line_style)
line.set_xy1(support_line, intral_time, adjusted_support)
line.set_xy2(support_line, right_extension, adjusted_support)
line.set_color(support_line, Color_Support)
var label support_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Support, size=font_size)
label.set_xy(support_label, right_extension, adjusted_support)
label.set_text(support_label, formatPrice(adjusted_support) + " " + support_text)
label.set_textcolor(support_label, Color_Support)
// Draw Middle Line
if Show_Middle_Line
float middle_price = (adjusted_resistance + adjusted_support) / 2
var line middle_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Middle, width=line_width, style=line_style)
line.set_xy1(middle_line, intrah_time, middle_price)
line.set_xy2(middle_line, right_extension, middle_price)
line.set_color(middle_line, Color_Middle)
var label middle_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Middle, size=font_size)
label.set_xy(middle_label, right_extension, middle_price)
label.set_text(middle_label, formatPrice(middle_price) +"0")
label.set_textcolor(middle_label, Color_Middle)
//========================================
// DRAWING - BULLISH TARGETS & SIGNALS
//========================================
if barstate.islast and Show_Targets and resistance_broken
int right_extension = extendToCurrentBar(distance_right)
// Buy Signal
if Show_Signals and not na(buy_signal_bar)
var label buy_label = label.new(na, na, text="شراء\nBUY", style=label.style_label_up, color=Color_Buy_Signal, textcolor=color.white, size=getSignalSize(Signal_Size))
label.set_xy(buy_label, buy_signal_bar, buy_signal_price)
label.set_color(buy_label, Color_Buy_Signal)
label.set_size(buy_label, getSignalSize(Signal_Size))
// Bullish FVG Box
if Show_FVG
= detectBullishFVG(FVG_Lookback)
if not na(bull_top) and not na(bull_bottom) and not na(bull_left)
var box bull_box = box.new(na, na, na, na, xloc=xloc.bar_index, bgcolor=Color_Bullish_FVG, border_color=FVG_Border_Color, border_width=1)
box.set_lefttop(bull_box, bull_left, bull_top)
box.set_rightbottom(bull_box, bar_index, bull_bottom)
box.set_bgcolor(bull_box, Color_Bullish_FVG)
box.set_border_color(bull_box, FVG_Border_Color)
// Calculate Target Prices
float target1_price = adjusted_resistance * (1 + Target1_Up_Distance / 100)
float target2_price = adjusted_resistance * (1 + Target2_Up_Distance / 100)
float target3_price = adjusted_resistance * (1 + Target3_Up_Distance / 100)
// Target 1
var line t1_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target1_Up, width=2, style=target_style)
line.set_xy1(t1_line, intrah_time, target1_price)
line.set_xy2(t1_line, right_extension, target1_price)
line.set_color(t1_line, Color_Target1_Up)
var label t1_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target1_Up, size=size.small)
label.set_xy(t1_label, right_extension, target1_price)
label.set_text(t1_label, formatPrice(target1_price) + " ⬆ T1")
label.set_textcolor(t1_label, Color_Target1_Up)
// Target 2
var line t2_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target2_Up, width=2, style=target_style)
line.set_xy1(t2_line, intrah_time, target2_price)
line.set_xy2(t2_line, right_extension, target2_price)
line.set_color(t2_line, Color_Target2_Up)
var label t2_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target2_Up, size=size.small)
label.set_xy(t2_label, right_extension, target2_price)
label.set_text(t2_label, formatPrice(target2_price) + " ⬆ T2")
label.set_textcolor(t2_label, Color_Target2_Up)
// Target 3
var line t3_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target3_Up, width=2, style=target_style)
line.set_xy1(t3_line, intrah_time, target3_price)
line.set_xy2(t3_line, right_extension, target3_price)
line.set_color(t3_line, Color_Target3_Up)
var label t3_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target3_Up, size=size.small)
label.set_xy(t3_label, right_extension, target3_price)
label.set_text(t3_label, formatPrice(target3_price) + " ⬆ T3")
label.set_textcolor(t3_label, Color_Target3_Up)
//========================================
// DRAWING - BEARISH TARGETS & SIGNALS
//========================================
if barstate.islast and Show_Targets and support_broken
int right_extension = extendToCurrentBar(distance_right)
// Sell Signal
if Show_Signals and not na(sell_signal_bar)
var label sell_label = label.new(na, na, text="بيع\nSELL", style=label.style_label_down, color=Color_Sell_Signal, textcolor=color.white, size=getSignalSize(Signal_Size))
label.set_xy(sell_label, sell_signal_bar, sell_signal_price)
label.set_color(sell_label, Color_Sell_Signal)
label.set_size(sell_label, getSignalSize(Signal_Size))
// Bearish FVG Box
if Show_FVG
= detectBearishFVG(FVG_Lookback)
if not na(bear_top) and not na(bear_bottom) and not na(bear_left)
var box bear_box = box.new(na, na, na, na, xloc=xloc.bar_index, bgcolor=Color_Bearish_FVG, border_color=FVG_Border_Color, border_width=1)
box.set_lefttop(bear_box, bear_left, bear_top)
box.set_rightbottom(bear_box, bar_index, bear_bottom)
box.set_bgcolor(bear_box, Color_Bearish_FVG)
box.set_border_color(bear_box, FVG_Border_Color)
// Calculate Target Prices
float target1_price = adjusted_support * (1 - Target1_Down_Distance / 100)
float target2_price = adjusted_support * (1 - Target2_Down_Distance / 100)
float target3_price = adjusted_support * (1 - Target3_Down_Distance / 100)
// Target 1
var line t1_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target1_Down, width=2, style=target_style)
line.set_xy1(t1_down_line, intral_time, target1_price)
line.set_xy2(t1_down_line, right_extension, target1_price)
line.set_color(t1_down_line, Color_Target1_Down)
var label t1_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target1_Down, size=size.small)
label.set_xy(t1_down_label, right_extension, target1_price)
label.set_text(t1_down_label, formatPrice(target1_price) + " ⬇ T1")
label.set_textcolor(t1_down_label, Color_Target1_Down)
// Target 2
var line t2_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target2_Down, width=2, style=target_style)
line.set_xy1(t2_down_line, intral_time, target2_price)
line.set_xy2(t2_down_line, right_extension, target2_price)
line.set_color(t2_down_line, Color_Target2_Down)
var label t2_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target2_Down, size=size.small)
label.set_xy(t2_down_label, right_extension, target2_price)
label.set_text(t2_down_label, formatPrice(target2_price) + " ⬇ T2")
label.set_textcolor(t2_down_label, Color_Target2_Down)
// Target 3
var line t3_down_line = line.new(na, na, na, na, xloc=xloc.bar_time, color=Color_Target3_Down, width=2, style=target_style)
line.set_xy1(t3_down_line, intral_time, target3_price)
line.set_xy2(t3_down_line, right_extension, target3_price)
line.set_color(t3_down_line, Color_Target3_Down)
var label t3_down_label = label.new(na, na, text="", xloc=xloc.bar_time, style=label.style_none, textcolor=Color_Target3_Down, size=size.small)
label.set_xy(t3_down_label, right_extension, target3_price)
label.set_text(t3_down_label, formatPrice(target3_price) + " ⬇ T3")
label.set_textcolor(t3_down_label, Color_Target3_Down)
// ===== إعدادات =====
src = input.source(close, "Source")
anchor = input.string( "top_right", "موقع الجدول", options= )
v_step = input.int(0, "تحريك عمودي 0 أعلى .. 1 أسفل", minval=0, maxval=1)
h_step = input.int(0, "تحريك أفقي 0 يسار .. 1 يمين", minval=0, maxval=1)
size_step = input.int(1, "حجم الخط 0 صغير جدًا .. 5 كبير", minval=0, maxval=5)
show_table = input.bool(true, "إظهار الجدول؟")
// ===== حساب RSI =====
r = ta.rsi(src, rsiLength)
// ===== حساب Flow (عرض وطلب) كمثال =====
FlowUp = close > open
FlowDown = close < open
FlowText = FlowUp ? "🟢" : FlowDown ? "🔴" : "⚪"
// ===== ألوان RSI =====
bgColor = r > 56 ? color.green : (r < 44 ? color.red : color.gray)
numColor = color.white
// ===== حجم الخط =====
textSizes = array.from(size.tiny, size.small, size.normal, size.large, size.large, size.large)
tsize = array.get(textSizes, size_step)
// ===== إنشاء جدول مصغر جدًا 2x2 =====
var int grid = 2
pos = anchor == "top_right" ? position.top_right :
anchor == "top_left" ? position.top_left :
anchor == "bottom_right" ? position.bottom_right : position.bottom_left
var table tbl = table.new(pos, grid, grid, frame_width=0, frame_color=color.black)
// ===== تحديث الجدول =====
if show_table
cellText = "قوة:" + str.tostring(r, "#.0") + FlowText
for row = 0 to grid-1
for col = 0 to grid-1
if row == v_step and col == h_step
table.cell(tbl, row, col, text=cellText, text_color=numColor, bgcolor=bgColor, text_size=tsize)
// # ========================================================================= #
// # | Colors |
// # ========================================================================= #
//#region
// # Core -------------------------------------------------------------------- #
colors_orange = color.rgb(246, 255, 0)
colors_blue = color.rgb(243, 246, 246)
colors_aqua = color.rgb(237, 245, 12)
colors_red = color.red
colors_green = color.rgb(246, 246, 16)
colors_maroon = color.maroon
colors_purple = color.rgb(9, 94, 253)
colors_gray = color.rgb(250, 6, 6)
colors_transparent = color.new(color.white,100)
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Inputs |
// # ========================================================================= #
//#region
// # General ----------------------------------------------------------------- #
general_font = input.string("Monospace", "Text ", options = , inline = "5", group = "General")
general_text = input.string("Tiny", "", options = , inline = "5", group = "General", tooltip = "Customize global text size and style")
general_brand_show = input.bool(false, "Hide Brand", group = "General")
// # LKZ --------------------------------------------------------------------- #
hl_daily = input.bool(true, "Day ", inline = "1", group = "HTF Levels")
hl_weekly = input.bool(false, "Week ", inline = "2", group = "HTF Levels")
hl_monthly = input.bool(false, "Month ", inline = "3", group = "HTF Levels")
hl_quartely = input.bool(false, "Quarter ", inline = "4", group = "HTF Levels")
hl_yearly = input.bool(false, "Year ", inline = "5", group = "HTF Levels")
hl_css_daily = input.color(colors_blue, "", inline = "1", group = "HTF Levels")
hl_css_weekly = input.color(colors_green, "", inline = "2", group = "HTF Levels")
hl_css_monthly = input.color(colors_purple, "", inline = "3", group = "HTF Levels")
hl_css_quaterly = input.color(colors_maroon, "", inline = "4", group = "HTF Levels")
hl_css_yearly = input.color(colors_gray, "", inline = "5", group = "HTF Levels")
hl_line_daily = input.string('⎯⎯⎯', '', inline = '1', group = "HTF Levels", options = )
hl_line_weekly = input.string('⎯⎯⎯', '', inline = '2', group = "HTF Levels", options = )
hl_line_monthly = input.string('⎯⎯⎯', '', inline = '3', group = "HTF Levels", options = )
hl_line_quaterly = input.string('⎯⎯⎯', '', inline = '4', group = "HTF Levels", options = )
hl_line_yearly = input.string('⎯⎯⎯', '', inline = '5', group = "HTF Levels", options = )
hl_line_width_daily = input.int(1, '', inline = '1', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_weekly = input.int(1, '', inline = '2', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_monthly = input.int(1, '', inline = '3', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_quaterly = input.int(1, '', inline = '4', group = "HTF Levels", minval = 1, maxval = 5)
hl_line_width_yearly = input.int(1, '', inline = '5', group = "HTF Levels", minval = 1, maxval = 5)
hl_midline = input.bool(true, "Show Average ", inline = "6" , group = "HTF Levels")
hl_midline_css = input.color(colors_aqua, "", inline = "6", group = "HTF Levels")
hl_midline_type = input.string("----", "", inline = "6", group = "HTF Levels", options = , tooltip = "Show highs & lows mid-line")
hl_midline_width = input.int(1, "", inline = "6", group = "HTF Levels", tooltip = "Change mid-line highs & lows width")
hl_openline = input.bool(true, "Show Open ", inline = "7" , group = "HTF Levels")
hl_openline_css = input.color(colors_orange, "", inline = "7", group = "HTF Levels")
hl_openline_type = input.string("····", "", inline = "7", group = "HTF Levels", options = , tooltip = "Show highs & lows mid-line")
hl_openline_width = input.int(1, "", inline = "7", group = "HTF Levels", tooltip = "Change mid-line highs & lows width")
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | UDTs |
// # ========================================================================= #
//#region
type UDT_Store
line hl_ln
label hl_lbl
type UDT_MTF
int x1 = na
int x2 = na
float y1 = na
float y2 = na
type UDT_HTF_Candle
string tf
// real coordinates of HTF candle
float o
float c
float h
float l
int ot
int ct
int ht
int lt
bool bull
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Functions |
// # ========================================================================= #
//#region
method text_size(string size) =>
out = switch size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
out
method line_style(string line) =>
out = switch line
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
method font_style(string font) =>
out = switch font
'Default' => font.family_default
'Monospace' => font.family_monospace
shift_to_right(int current, int length, string tf) =>
current + timeframe.in_seconds(tf) * 1000 * (length + 1)
shift_to_left(int current, int prev, int length) =>
current - (current - prev) * length + 1
shift_bars_to_right(int bars) =>
bars + 20
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Store |
// # ========================================================================= #
//#region
var UDT_Store bin = UDT_Store.new(hl_ln = array.new(), hl_lbl = array.new())
method clean_hl(UDT_Store store) =>
for obj in store.hl_ln
obj.delete()
for obj in store.hl_lbl
obj.delete()
store.hl_ln.clear()
store.hl_lbl.clear()
//#endregion
// # ========================================================================= #
// # | End |
// # ========================================================================= #
// # ========================================================================= #
// # | Highs & Lows MTF |
// # ========================================================================= #
//#region
method draw_pivots_ol_line(UDT_MTF mtf) =>
ol = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = hl_openline_css
, style = line_style(hl_openline_type)
, width = hl_openline_width
)
bin.hl_ln.push(ol)
mtf
method draw_pivots_hl_line(UDT_MTF mtf, color css, string pdhl_style, int line_width) =>
hl = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = css
, style = line_style(pdhl_style)
, width = line_width
)
bin.hl_ln.push(hl)
mtf
method draw_pivots_mid_line(UDT_MTF mtf) =>
ml = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = hl_midline_css
, style = line_style(hl_midline_type)
, width = hl_midline_width
)
bin.hl_ln.push(ml)
mtf
method draw_pivots_ll_line(UDT_MTF mtf, color css, string pdhl_style, int line_width) =>
ll = line.new(
x1 = mtf.x1
, y1 = mtf.y1
, x2 = mtf.x2
, y2 = mtf.y2
, xloc = xloc.bar_time
, color = css
, style = line_style(pdhl_style)
, width = line_width
)
bin.hl_ln.push(ll)
mtf
method draw_pivots_label(UDT_MTF mtf, string fmt, string tf, color css) =>
lbl = label.new(
x = mtf.x2
, y = mtf.y2
, xloc = xloc.bar_time
, text = str.format(fmt, tf)
, color = colors_transparent
, textcolor = css
, size = text_size(general_text)
, style = label.style_label_left
, text_font_family = font_style(general_font)
)
bin.hl_lbl.push(lbl)
mtf
method mtf_pivots(UDT_HTF_Candle candle, tf, css
Smart VWAP FVG SystemSmart VWAP FVG System - Professional Multi-Filter Trading Indicator
📊 OVERVIEW
The Smart VWAP FVG System is an advanced multi-layered trading indicator that combines institutional volume analysis, multi-timeframe VWAP trend confirmation, and Fair Value Gap detection to identify high-probability trade entries. This indicator uses a sophisticated filtering mechanism where signals appear only when multiple independent confirmation criteria align simultaneously.
Recommended Timeframe: 5-minute (M5) or higher. The indicator works best on M5, M15, and M30 charts for intraday trading.
🎯 ORIGINALITY & PURPOSE
This indicator is original because it combines three distinct analytical methods into a unified decision-making system:
Market Profile Volume Analysis - Identifies institutional accumulation/distribution zones
Dual VWAP Filtering - Confirms trend direction using two independent VWAP calculations
Fair Value Gap Detection - Validates institutional interest through price inefficiency zones
The key innovation is the directional filter system: the primary Market Profile generates BUY-ONLY or SELL-ONLY states based on higher timeframe value area reversals, which then controls which signals from the main system are displayed. This creates a multi-timeframe confluence that significantly reduces false signals.
Unlike simple indicator mashups, each component serves a specific purpose:
Market Profile → Direction bias (trend filter)
Primary VWAP (Session) → Short-term trend confirmation
Secondary VWAP (Week) → Medium-term trend confirmation
FVG Detection → Institutional activity validation
🔧 HOW IT WORKS
1. Primary Market Profile Filter (Higher Timeframe)
The indicator calculates Market Profile on a higher timeframe (default: 1 hour) to determine the overall market structure:
Value Area High (VAH): Top 70% of volume distribution
Value Area Low (VAL): Bottom 70% of volume distribution
Point of Control (POC): Price level with highest volume
When price reaches VAH and reverses down → SELL-ONLY mode activated
When price reaches VAL and reverses up → BUY-ONLY mode activated
This higher timeframe filter ensures you're trading in the direction of institutional flow.
2. Dual VWAP System
Two independent VWAP calculations provide multi-timeframe trend confirmation:
Primary VWAP (Session-based): Resets daily, tracks intraday momentum
Secondary VWAP (Week-based): Resets weekly, confirms longer-term trend
Filter Logic:
BUY signals require: Price > Primary VWAP AND Price > Secondary VWAP
SELL signals require: Price < Primary VWAP AND Price < Secondary VWAP
This dual confirmation prevents counter-trend trades during ranging conditions.
3. Fair Value Gap (FVG) Detection
FVG zones identify price inefficiencies where institutional orders were executed rapidly:
Bullish FVG: Gap between candle .high and candle .low (upward imbalance)
Bearish FVG: Gap between candle .high and candle .low (downward imbalance)
The indicator monitors recent FVG formation (lookback: 50 bars) and requires:
Bullish FVG present for BUY signals
Bearish FVG present for SELL signals
FVG zones are displayed as colored boxes and automatically marked as "mitigated" when price fills the gap.
4. Main Trading Signal Logic
The secondary Market Profile (default: 1 hour) generates the actual trading signals:
BUY Signal Conditions:
Price reaches Value Area Low
Reversal pattern confirmed (minimum 1 bar)
Price > Primary VWAP
Price > Secondary VWAP (if filter enabled)
Recent Bullish FVG detected (if filter enabled)
Primary MP Filter = BUY-ONLY or NEUTRAL
SELL Signal Conditions:
Price reaches Value Area High
Reversal pattern confirmed (minimum 1 bar)
Price < Primary VWAP
Price < Secondary VWAP (if filter enabled)
Recent Bearish FVG detected (if filter enabled)
Primary MP Filter = SELL-ONLY or NEUTRAL
All conditions must be TRUE simultaneously for a signal to appear.
📈 VISUAL ELEMENTS
On Chart:
🟢 Green Triangle (▲) = BUY Signal
🔴 Red Triangle (▼) = SELL Signal
🟦 Blue horizontal lines = Value Area zones
🟡 Yellow line = Point of Control (POC)
🟩 Green boxes = Bullish FVG zones
🟥 Red boxes = Bearish FVG zones
🔵 Blue line = Primary VWAP (Session)
⚪ White line = Secondary VWAP (Week)
Info Panel (Top Right):
Real-time status display showing:
Filter Direction (BUY ONLY / SELL ONLY / NEUTRAL)
Active timeframes for both MP filters
FVG filter status and count
VWAP positions (ABOVE/BELOW)
Signal enablement status
Alert status
⚙️ KEY SETTINGS
MP/TPO Filter Settings (Primary Indicator)
MP Filter Time Frame: 60 minutes (controls directional bias)
Filter Value Area %: 70% (standard Market Profile calculation)
Filter Alert Distance: 1 bar
Filter Min Bars for Reversal: 1 bar
Filter Alert Zone Margin: 0.01 (1%)
FVG Filter Settings
Use FVG Filter: Enabled (toggle on/off)
FVG Timeframe: 60 minutes (1 hour)
FVG Filter Mode: Both (require bullish FVG for BUY, bearish for SELL)
FVG Lookback Period: 50 bars (how far back to search)
Show FVG Formation Signals: Optional visual markers
Max FVG on Chart: 50 zones
Show Mitigated FVG: Display filled gaps
Market Profile Settings
Higher Time Frame: 60 minutes (for main signals)
Percent for Value Area: 70%
Show POC Line: Enabled
Keep Old MPs: Enabled (maintain historical profiles)
Primary VWAP Filter
Use Primary VWAP Filter: Enabled
Primary VWAP Anchor Period: Session (resets daily)
Primary VWAP Source: HLC3 (typical price)
Secondary VWAP Filter
Use Secondary VWAP Filter: Enabled
Secondary VWAP Anchor Period: Week (resets weekly)
Secondary VWAP Filter Mode: Both
Secondary VWAP Line Color: White
Trading Signals
Show Trading Signals on Chart: Enabled
Show SELL Signals: Enabled
Show BUY Signals: Enabled
Alert Distance: 1 bar
Min Bars for Reversal: 1 bar
Alert Zone Margin: 0.01 (1%)
Retest Search Period: 20 bars
Min Bars Between Retests: 5 bars
Show Only Retests: Disabled
Alert Settings
Enable Trading Notifications: Enabled
VAH Reversal Alert: Enabled (SELL signals)
VAL Reversal Alert: Enabled (BUY signals)
Time Filter Settings
Filter Alerts By Time: Optional (exclude specific hours)
⚠️ IMPORTANT WARNINGS & LIMITATIONS
1. Repainting Behavior
CRITICAL: This indicator uses lookahead=barmerge.lookahead_on to access higher timeframe data immediately for FVG detection. This is necessary to provide real-time FVG zone visualization but has the following implications:
FVG zones may shift slightly until the higher timeframe candle closes
FVG detection signals are preliminary until HTF bar confirmation
The main trading signals (triangles) appear on confirmed bars and do not repaint
Best Practice: Always wait for the current timeframe bar to close before acting on signals. The filter status and FVG zones are informational but may adjust as new data arrives.
2. Minimum Timeframe
Do NOT use on timeframes below 5 minutes (M5)
Recommended: M5, M15, M30 for intraday trading
Higher timeframes (H1, H4) can also be used but will generate fewer signals
3. Multiple Filters Can Block Signals
By design, this indicator is conservative. When all filters are enabled:
Signals appear ONLY when all conditions align
You may see extended periods with no signals
This is intentional to reduce false positives
If you see no signals:
Check the Info Panel to see which filters are failing
Consider adjusting FVG lookback period
Temporarily disable FVG filter to test
Verify VWAP filters match current market trend
4. Market Profile Limitations
Market Profile requires sufficient volume data
Low-volume instruments may produce unreliable profiles
Value Areas update only on higher timeframe bar close
Works best on liquid markets (major forex pairs, indices, crypto)
📖 HOW TO USE
Step 1: Add to Chart
Apply indicator to M5 or higher timeframe chart
Ensure chart shows volume data
Use standard candles (NOT Heikin Ashi, Renko, etc.)
Step 2: Configure Settings
Primary MP Filter TF: Set to 60 (1 hour) minimum, or 240 (4 hour) for swing trading
Main MP TF: Set to 60 (1 hour) for intraday signals
FVG Timeframe: Match or exceed main MP timeframe
Leave other settings at default initially
Step 3: Understand the Info Panel
Monitor the top-right panel:
FILTER STATUS: Shows current directional bias
NEUTRAL = Both signals allowed
BUY ONLY = Only green triangles will appear
SELL ONLY = Only red triangles will appear
FVG Filter: Shows if bullish/bearish gaps detected recently
VWAP positions: Confirms trend alignment
Step 4: Take Signals
For BUY Signal (Green Triangle ▲):
Wait for green triangle to appear
Check Info Panel shows ✓ for BUY signals
Confirm current bar has closed
Enter long position
Stop loss: Below recent VAL or swing low
Target: Previous Value Area High or 1.5-2× risk
For SELL Signal (Red Triangle ▼):
Wait for red triangle to appear
Check Info Panel shows ✓ for SELL signals
Confirm current bar has closed
Enter short position
Stop loss: Above recent VAH or swing high
Target: Previous Value Area Low or 1.5-2× risk
Step 5: Risk Management
Risk per trade: Maximum 1-2% of account equity
Position sizing: Adjust based on stop loss distance
Avoid trading: During major news events or time filter periods
Multiple confirmations: Look for confluence with price action (support/resistance, trendlines)
🎓 UNDERLYING CONCEPTS
Market Profile Theory
Developed by J. Peter Steidlmayer in the 1980s, Market Profile organizes price and volume data to identify:
Value Areas: Where 70% of trading activity occurred
POC: Price level with highest acceptance (most volume)
Imbalances: When price moves away from value quickly
This indicator uses TPO (Time Price Opportunity) calculation method to build the volume profile distribution.
VWAP (Volume Weighted Average Price)
VWAP represents the average price weighted by volume, showing where institutional traders are positioned:
Price above VWAP = Bullish (institutions accumulated lower)
Price below VWAP = Bearish (institutions distributed higher)
Using dual VWAP (Session + Week) creates multi-timeframe trend alignment.
Fair Value Gaps (FVG)
Also known as "imbalance" or "inefficiency," FVG occurs when:
Price moves so rapidly that a gap forms in the candlestick structure
Indicates institutional order flow (large market orders)
Price often returns to "fill" these gaps (rebalance)
The 3-candle FVG pattern (gap between candle and candle ) is widely used in ICT (Inner Circle Trader) methodology and Smart Money Concepts.
🔍 CREDITS & CODE ATTRIBUTION
This indicator builds upon established technical analysis concepts and combines multiple methodologies:
1. Market Profile / TPO Calculation
Concept Origin: J. Peter Steidlmayer (Chicago Board of Trade, 1980s)
Code Inspiration: TradingView's public domain Market Profile examples
Modifications: Custom filtering logic for directional bias, dual timeframe implementation
2. VWAP Calculation
Concept Origin: Standard financial instrument (widely used since 1980s)
Code Base: TradingView built-in ta.vwap() function (public domain)
Modifications: Dual VWAP system with independent anchor periods, custom filtering modes
3. Fair Value Gap Detection
Concept Origin: Inner Circle Trader (ICT) / Smart Money Concepts methodology
Code Implementation: Original implementation based on 3-candle gap pattern
Features: Multi-timeframe detection, automatic mitigation tracking, visual zone display
4. Pine Script Framework
Language: Pine Script v6 (TradingView)
Built-in Functions Used:
ta.vwap() - Volume weighted average price
request.security() - Higher timeframe data access
ta.change() - Period detection
ta.cum() - Cumulative volume
time() - Timestamp functions
Note: All code is original implementation. While concepts are based on established trading methodologies, the combination, filtering logic, and execution are unique to this indicator.
📊 RECOMMENDED INSTRUMENTS
Best Performance:
Major Forex Pairs (EURUSD, GBPUSD, USDJPY)
Stock Indices (ES, NQ, SPX, DAX)
Major Cryptocurrencies (BTCUSD, ETHUSD)
Liquid Stocks (high daily volume)
Avoid:
Low-volume altcoins
Illiquid stocks
Exotic forex pairs with wide spreads
⚡ PERFORMANCE TIPS
Start Conservative: Enable all filters initially
Reduce Filters Gradually: If too few signals, disable Secondary VWAP filter first
Match Timeframes: Keep MP Filter TF and FVG TF at same value
Backtest First: Review historical performance on your preferred instrument/timeframe
Combine with Price Action: Look for support/resistance confluence
Use Time Filter: Avoid low-liquidity hours (optional setting)
🚫 WHAT THIS INDICATOR DOES NOT DO
Does not guarantee profits - No trading system is 100% accurate
Does not predict the future - Based on historical patterns
Does not replace risk management - Always use stop losses
Does not work on all instruments - Requires volume data and liquidity
Does not provide exact entry/exit prices - Signals are zones, not precise levels
Does not account for fundamentals - Purely technical analysis
📜 DISCLAIMER
This indicator is provided for educational and informational purposes only. It is not financial advice, and past performance does not guarantee future results.
Trading Risk Warning:
All trading involves risk of loss
You can lose more than your initial investment (leverage products)
Only trade with capital you can afford to lose
Always use appropriate position sizing and risk management
Consider seeking advice from a licensed financial advisor
Technical Limitations:
Indicator may repaint FVG zones until HTF bar closes
Signals are based on historical patterns that may not repeat
Market conditions change and no system works in all environments
Volume data quality varies by exchange/broker
By using this indicator, you acknowledge these risks and agree that the author bears no responsibility for trading losses.
📞 SUPPORT & UPDATES
Questions? Comment on this publication
Issues? Describe the problem with chart screenshot
Feature Requests? Suggest improvements in comments
Updates: Will be published as new versions using TradingView's update feature
📝 VERSION HISTORY
Version 1.0 (Current)
Initial public release
Multi-filter system: MP + Dual VWAP + FVG
Directional bias filter
Real-time info panel
Comprehensive alert system
Time-based filtering
Thank you for using Smart VWAP FVG System!
Happy Trading! 📈
Swing High Low ZigZag v3.0 BajaSwing High/Low Pivot - Designed to help easily spot peaks and bottoms for quicker drawing of trendlines and other drawings as well as alerts without needing to zoom in a whole lot.






















