Divergence Toolkit (Real-Time)The Divergence Toolkit is designed to automatically detect divergences between the price of an underlying asset and any other @TradingView built-in or community-built indicator or script. This algorithm provides a comprehensive solution for identifying both regular and hidden divergences, empowering traders with valuable insights into potential trend reversals.
🔲 Methodology
Divergences occur when there is a disagreement between the price action of an asset and the corresponding indicator. Let's review the conditions for regular and hidden divergences.
Regular divergences indicate a potential reversal in the current trend.
Regular Bullish Divergence
Price Action - Forms a lower low.
Indicator - Forms a higher low.
Interpretation - Suggests that while the price is making new lows, the indicator is showing increasing strength, signaling a potential upward reversal.
Regular Bearish Divergence
Price Action - Forms a higher high.
Indicator - Forms a lower high.
Interpretation - Indicates that despite the price making new highs, the indicator is weakening, hinting at a potential downward reversal.
Hidden divergences indicate a potential continuation of the existing trend.
Hidden Bullish Divergence
Price Action - Forms a higher low.
Indicator - Forms a lower low.
Interpretation - Suggests that even though the price is retracing, the indicator shows increasing strength, indicating a potential continuation of the upward trend.
Hidden Bearish Divergence
Price Action - Forms a lower high.
Indicator - Forms a higher high.
Interpretation - Indicates that despite a retracement in price, the indicator is still strong, signaling a potential continuation of the downward trend.
In both regular and hidden divergences, the key is to observe the relationship between the price action and the indicator. Divergences can provide valuable insights into potential trend reversals or continuations.
The methodology employed in this script involves the detection of divergences through conditional price levels rather than relying on detected pivots. Traditionally, divergences are created by identifying pivots in both the underlying asset and the oscillator. However, this script employs a trailing stop on the oscillator to detect potential swings, providing a real-time approach to identifying divergences, you may find more info about it here (SuperTrend Toolkit) . We detect swings or pivots simply by testing for crosses between the indicator and its trailing stop.
type oscillator
float o = Oscillator Value
float s = Trailing Stop Value
oscillator osc = oscillator.new()
bool l = ta.crossunder(osc.o, osc.s) => Utilized as a formed high
bool h = ta.crossover (osc.o, osc.s) => Utilized as a formed low
// Note: these conditions alone could cause repainting when they are met but canceled at a later time before the bar closes. Hence, we wait for a confirmed bar.
// The script also includes the option to immediately alert when the conditions are met, if you choose so.
By testing for conditional price levels, the script achieves similar outcomes without the delays associated with pivot-based methods.
type bar
float o = open
float h = high
float l = low
float c = close
bar b = bar.new()
bool hi = b.h < b.h => A higher price level has been created
bool lo = b.l > b.l => A lower price level has been created
// Note: These conditions do not check for certain price swings hence they may seldom result in inaccurate detection.
🔲 Setup Guide
A simple example on one of my public scripts, Standardized MACD
🔲 Utility
We may auto-detect divergences to spot trend reversals & continuations.
🔲 Settings
Source - Choose an oscillator source of which to base the Toolkit on.
Zeroing - The Mid-Line value of the oscillator, for example RSI & MFI use 50.
Sensitivity - Calibrates the sensitivity of which Divergencies are detected, higher values result in more detections but less accuracy.
Lifetime - Maximum timespan to detect a Divergence.
Repaint - Switched on, the script will trigger Divergencies as they happen in Real-Time, could cause repainting when the conditions are met but canceled at a later time before bar closes.
🔲 Alerts
Bearish Divergence
Bullish Divergence
Bearish Hidden Divergence
Bullish Hidden Divergence
As well as the option to trigger 'any alert' call.
The Divergence Toolkit provides traders with a dynamic tool for spotting potential trend reversals and continuations. Its innovative approach to real-time divergence detection enhances the timeliness of identifying market opportunities.
Divergenceindicator
Momentum Oscillator, Divergences & Signals [TrendAlpha]The "Momentum, Real Time Divergences & Signals " indicator is designed to provide traders with insights into market momentum, identify potential divergences, and generate buy and sell signals. It offers a comprehensive set of features to assist traders in making informed trading decisions.
The indicator starts by calculating the momentum oscillator based on user-defined parameters.
- Traders can adjust the "Length" parameter to customize the sensitivity of the oscillator. The default value is set to 7, but it can be modified according to individual preferences.
- The "Source" parameter allows traders to select the input source for the oscillator calculation, with the default being the closing price of the asset.
- Traders have the option to display divergence lines by switching on the "Show Lines" parameter. This feature helps identify potential divergences between the oscillator and the price.
The oscillator is calculated using a two-step process. First, a smoothing function is applied to the source data using the "sma" (simple moving average) function. Then, the rate of change is computed over the specified length using the "mom" (momentum) function. Positive oscillator values indicate upward momentum, while negative values indicate downward momentum.
The indicator also generates buy and sell signals by identifying bullish and bearish divergences. A bullish divergence occurs when the oscillator is negative and crosses above zero, while a bearish divergence occurs when the oscillator is positive and crosses below zero. The indicator checks for specific conditions to confirm the divergences, such as comparing the current oscillator value with the previous value and validating the corresponding price action.
When a bullish or bearish divergence is detected, the indicator plots circles to highlight these signals on the chart. A green circle indicates a bullish signal, suggesting a potential buying opportunity, while a red circle indicates a bearish signal, suggesting a potential selling opportunity. In addition to circles, the indicator also displays labels to provide further clarity on the signals. A "Buy" label is shown for bullish signals, and a "Sell" label is shown for bearish signals.
To visually represent the divergences, the indicator plots lines connecting the corresponding points on the oscillator. A green line is drawn for bullish divergences, while a red line is drawn for bearish divergences. Traders can easily observe the divergence patterns and their relationships with the price action, aiding them in making trading decisions.
- The indicator also includes alert conditions for both bullish and bearish divergences. Traders can set up alerts to receive notifications when potential divergences occur, allowing them to take timely action.
XPrecisionSwing (XPS)* XPrecisionSwing (XPS) Indicator *
Is a visual representation of the Forces of Supply / Demand in the markets in the form of UP and DOWN waves. The Supply / Demand (denoted by a number on top or below the wave line) is computed using the *MBox Precision Supply / Demand* algorithm. These numbers diligently show the forces of Supply and Demand moving price in the markets. The algorithm for computing the numbers on the top and bottom of the wave lines measures the strength of the Supply / Demand. It is this algorithm that makes this indicator unique as it gives an accurate representation of the forces pulling the market up and down. When forces oppose each other, meaning when the direction of price does not agree with the direction of the Supply or Demand it creates a divergence and an opportunity in the markets. These situations are called BUY / SELL Imbalances. Explanation about this below.
* WHAT THE SCRIPT DOES *
The XPrecisionSwing indicator draws swing waves lines going up and down. These waves lines are representative of Supply and Demand. Waves going up are Demand, while waves going down are Supply. The strength of the Supply / Demand corresponds to the number drawn either on top of the wave line or below it. The numbers drawn on the chart are powered by the *MBox Precision Supply / Demand* algorithm, which are representative of the Forces of Supply / Demand in the markets. This is not just volume added up like in a regular zig zag indicator, since volume alone does not show Supply / Demand, and regular volume will not show BUY / SELL Imbalances as depicted by XPrecisionSwing. Volume summated will not show both positive and negative numbers on the chart. Having Supply / Demand split into both positive and negative numbers allows us to see BUY / SELL Imbalances, which can be a very powerful divergence. Information on how these numbers are computed are in the "HOW IT WORKS" section.
The numbers drawn on the chart can be either negative or positive. Positive relates to Demand, while negative relates to Supply. In this manner the strength of Supply and Demand can be gauged in each wave. If the price goes up but the number is negative (More Supply) it is a divergence and called a SELL Imbalance. This means there was more Supply even though price went up. It is important to pay attention to these scenarios, as often it can be indicative of NO DEMAND. Conversely. if the price goes down but the number is positive (No Demand) it is a divergence and is called a BUY Imbalance. This means there was more Demand even though price went down. This is indicative of NO SUPPLY. As such, it now becomes possible to know when there is a sign of Supply, Demand, No Supply, No Demand, Supply Exhaustion, and Demand exhaustion. Supply occurs when the negative numbers on the charts begin to increase (more negatively). Demand occurs when the positive numbers on the chart begin to increase (more positively). A Supply Exhaustion pattern happens when the price is starting to move down more slowly, while Supply is decreasing, and Demand is increasing. This means that the behavior of the market is changing and also a signal to look to reverse positions. A Demand Exhaustion pattern happens when the price is starting to move up more slowly, while Demand is decreasing, and Supply is increasing. The behavior of the market here is also changing.
* HOW IT WORKS *
- Technical Details for the Numbers on the Swing -
The numbers on the chart represent Supply / Demand. Supply or Demand is determined by analyzing the movement of price and quantity of volume.
When price goes up and is combined with an increase in volume it is Expansion of Demand.
(Positive Numbers get larger)
However if price goes up and is combined with a decrease in volume it is Contraction of Demand.
(Positive Numbers get smaller)
When price goes down and is combined with an increase in volume it is Expansion of Supply.
(Negative Numbers get larger)
However if price goes down and is combined with a decrease in volume it is Contraction of Supply.
(Negative Numbers get smaller)
- Technical Details for the Swing -
The way XPrecisionSwing draws the swings is fractal in nature, which make it very convenient and easier to use over the traditional zig zag indicator. The traditional zig zag indicator uses a tick reversal which needs to be adjusted every time you change time frames. However, with XPrecisionSwing you do not have to change any settings every time you load a different time frame since it will adjust to any time frame you are loading. How the swing is drawn is explained below.
XPrecisionSwing uses 3 bars (by default) to define a swing
This parameter can be adjusted. Can be 1, 2, 4 bars, etc...
Swings are always drawn using High / Low of the bar
- Rules -
To start upswing, bar high needs to be higher than previous 3 candle highs
To start downswing, bar low needs to be lower than previous 3 candle lows
If in upswing, a higher high will continue the upswing
if in downswing, a lower low will continue the downswing
- Exceptions -
If outside bar (both high and low exceeds previous 3 bars) swing will continue in current direction
- Swing Confirmation -
Swing wave line in progress (unconfirmed) is denoted by a brown box around the swing number
Once the brown box disappears, that swing wave and number is confirmed
* HOW TO USE IT *
As the numbers on the down waves increase (negatively), this shows that the bears have taken control of the markets. Conversely, as the numbers on the up waves increase (positively), this shows the bulls have taken control of the markets. Whoever is in control is the direction you generally want to place your trades in. When you see an increase in Supply (numbers on down wave) accompanied with a decrease in Demand (numbers on up wave) this shows a Supply + Demand Exhaustion Pattern. This is stronger than if you only see an increase in Supply without a decrease in Demand.
- The Buy / Sell Imbalances -
If you see a positive blue number on the bottom of a DOWN Wave, this means that there was more buying than selling even though price moved down.
If you see a negative red number on the top of an UP Wave, this means that there was more selling than buying even though price moved up.
Both of these cases signify and imbalance and a divergence.
* EXAMPLE AND USE CASES *
- Sell Imbalance Example -
If you see a large negative number with a lower low on a down wave, and then the next up wave is a lower high also with a negative number it shows that there is only Supply flooding the market and no sign of Demand. This is a very powerful combo.
- Buy Imbalance Example -
If you see a large positive number with a higher high on an up wave, and then the next down wave is a higher low also with a positive number it shows that there is only Demand flooding the market and no sign of Supply. This is a very powerful combo.
- Supply Exhaustion example -
If you see price movement struggling to make newer lows and the Supply numbers on the down waves are decreasing, while the Demand numbers on the up waves are increasing this is indicative of a *Change of Behavior*, and that the market is showing signs of reversal.
- Break out on Demand example -
If you see price has been ranging and now the numbers on the UP waves begin to increase while breaking out of a previous area of resistance, it is a good sign that the movement is backed by the strength coming from the Demand.
* BUY / SELL IMBALANCE ALERTS *
The Green / Red crosses on the chart show exactly where the Buy / Sell Imbalance Alerts trigger.
These will NEVER repaint! The crosses can be hidden in Styles if you wish to.
Alerts can be set very easily with the instructions below.
1. Right Click Chart -> Add Alert...
(Ignore Caution Warning. These alerts will *ONLY* trigger on Confirmed BUY / SELL Imbalances and will NOT repaint)
2. Select Condition to be "XPrecisionSwing"
3. Select "Buy Imbalance" or "Sell Imbalance"
4. Select "Greater Than" with Value = 0
5. Options set "Once Per Bar"
6. Customize Any other Alert Options you want
* WHAT MAKES IT ORIGINAL *
XPrecisionSwing gives an inside look into the markets by showing price movements as a series of waves going up and down with their corresponding Supply / Demand numbers associated with each wave. Reading the numbers shows the strength of Supply / Demand. The bigger the number the stronger the Supply / Demand is. The smaller the number the weaker the Supply / Demand is. It becomes possible to see where Supply / Demand comes in, along with Exhaustion of Supply / Demand to spot opportunities to place trades. The Buy / Sell Imbalances show imbalances where price movement and the direction of the Supply / Demand diverge to create potential opportunities as well.
* AUTHOR *
This script is published by MBoxWave LLC
The Divergent LibraryLibrary "TheDivergentLibrary"
The Divergent Library is only useful when combined with the Pro version of The Divergent - Advanced divergence indicator . This is because the Basic (free) version of The Divergent does not expose the "Divergence Signal" value.
Usage instructions:
1. Create a new chart
2. Add The Divergent (Pro) indicator to your chart
3. Create a new strategy, import this library, add a "source" input, link it to "The Divergent: Divergence Signal", and use the library to decode the divergence signals from The Divergent (You can find example strategy code published in our profile)
4. Act on the divergences signalled by The Divergent
---
isRegularBullishEnabled(context) Returns a boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
isHiddenBullishEnabled(context) Returns a boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
isRegularBearishEnabled(context) Returns a boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
isHiddenBearishEnabled(context) Returns a boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
getPivotDetectionSource(context) Returns the 'Pivot Detection Source' setting of The Divergent. The returned value can be either "Oscillator" or "Price".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Oscillator" or "Price".
getPivotDetectionMode(context) Returns the 'Pivot Detection Mode' setting of The Divergent. The returned value can be either "Bodies" or "Wicks".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Bodies" or "Wicks".
isLinked(context) Returns a boolean value indicating the link status to The Divergent indicator.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating the link status to The Divergent indicator.
init(firstBarSignal, displayLinkStatus, debug) Initialises The Divergent Library's context with the signal produced by The Divergent on the first bar. The value returned from this function is called the "context of The Divergent Library". Some of the other functions of this library requires you to pass in this context.
Parameters:
firstBarSignal : The signal from The Divergent indicator on the first bar.
displayLinkStatus : A boolean value indicating whether the Link Status window should be displayed in the bottom left corner of the chart. Defaults to true.
debug : A boolean value indicating whether the Link Status window should display debug information. Defaults to false.
Returns: A bool array containing the context of The Divergent Library.
processSignal(signal) Processes a signal from The Divergent and returns a 5-tuple with the decoded signal: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. `divergenceType` can be one of the following values: na → No divergence was detected, 1 → Regular Bullish, 2 → Regular Bullish early, 3 → Hidden Bullish, 4 → Hidden Bullish early, 5 → Regular Bearish, 6 → Regular Bearish early, 7 → Hidden Bearish, 8 → Hidden Bearish early.
Parameters:
signal : The signal from The Divergent indicator.
Returns: A 5-tuple with the following values: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd].