Moving Average Divergence For ThinkOrSwim

UPDATED VERSION 07/02/23: https://usethinkscript.com/threads/moving-average-divergence-for-thinkorswim.15650/post-127623


This is the Simple Moving Average Divergence indicator. The grey line is the SMA and when divergence is triggered. A green or Red line will be plotted to signal the bullish or bearish reversal. Enjoy! I will be working on more neat indicators that you can implement into your strategies.

Code:
# Moving Average Divergence Study for Thinkorswim

input length = 20;
input divergenceThreshold = 0.001;

def price = close;
def sma = Average(price, length);

def bullishDivergence = price[1] < price and sma[1] > sma;
def bearishDivergence = price[1] > price and sma[1] < sma;

def divergence = if bullishDivergence then 1 else if bearishDivergence then -1 else Double.NaN;

plot BullishLine = if bullishDivergence then low else Double.NaN;
BullishLine.SetDefaultColor(Color.GREEN);
BullishLine.SetStyle(Curve.SHORT_DASH);

plot BearishLine = if bearishDivergence then high else Double.NaN;
BearishLine.SetDefaultColor(Color.RED);
BearishLine.SetStyle(Curve.SHORT_DASH);

# Plotting the Moving Average for reference
plot MovingAvg = sma;
MovingAvg.SetDefaultColor(Color.gray);
 
Last edited:
Divergence is a concept widely used in trading strategies, particularly in technical analysis. It refers to a situation where the price of an asset and an indicator used to analyze that asset's price movement are moving in opposite directions, indicating a potential change in trend.

There are two main types of divergence: bullish and bearish.

Bullish Divergence: Bullish divergence occurs when the price of an asset forms lower lows, but the indicator shows higher lows. It suggests that the downward momentum is weakening, and a potential upward reversal may be imminent. Traders often interpret this as a buying signal, indicating that the price may soon start to rise.

Bearish Divergence: Bearish divergence occurs when the price of an asset forms higher highs, but the indicator shows lower highs. It suggests that the upward momentum is weakening, and a potential downward reversal may occur. Traders often interpret this as a selling signal, indicating that the price may soon start to decline.

Traders use divergence in various ways within their trading strategies. Here are a few common approaches:

Trend Reversal Confirmation: Divergence can be used as a confirmation tool to identify potential trend reversals. Traders may look for divergences between the price and indicators like the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), or Stochastic Oscillator to validate a change in trend and enter trades accordingly.

Entry and Exit Points: Divergence can be used to determine entry and exit points for trades. For example, if a trader identifies bullish divergence, they may enter a long position with the expectation that the price will reverse and move upward. Similarly, bearish divergence can be used to identify potential short-selling opportunities.

Risk Management: Divergence can also be used as a risk management tool. If a trader identifies a divergence that contradicts their current position, it may indicate a potential weakening of the trend and prompt them to consider adjusting their stop-loss levels or taking profits.

@papix
 
Last edited:
Fixed a few errors and added a Fibonacci-levels feature for guidance.
When the price reaches a Fibonacci level, the labels added by the script serve as visual indicators to highlight the specific Fibonacci level that has been reached. Here's what the labels do in that case:

  1. Highlighting the Fibonacci Level:
    • The labels are placed at the corresponding Fibonacci levels on the chart.
    • When the price reaches a Fibonacci level, the label associated with that level will appear at the price level on the chart.
    • This visual indicator helps to easily identify when the price has reached a specific Fibonacci level.
  2. Providing Information:
    • The labels display the name of the Fibonacci level (e.g., "Fib Level 0", "Fib Level 1") and its corresponding percentage value.
    • This information helps you understand which Fibonacci level the price has reached and the extent of the retracement or extension.
By having the labels displayed when the price reaches a Fibonacci level, you can quickly identify and track these key levels on the chart. It allows you to monitor price movements in relation to the Fibonacci levels and potentially make trading decisions based on the interaction between the price and the Fibonacci levels.
Ruby:
#Moving Average Divergence 1.2 modified by Trader4TOS 07/02/23



input length = 20;
input divergenceThreshold = 0.001;
input lineSize = 5; # Size of the divergence lines

def price = close;
def sma = Average(price, length);

def bullishDivergence = price[1] < price and sma[1] > sma;
def bearishDivergence = price[1] > price and sma[1] < sma;

def divergence = if bullishDivergence then 1 else if bearishDivergence then -1 else Double.NaN;

plot BullishLine = if divergence == 1 then low else Double.NaN;
BullishLine.SetDefaultColor(Color.DARK_GREEN);
BullishLine.SetStyle(Curve.SHORT_DASH);
BullishLine.SetLineWeight(lineSize);

plot BearishLine = if divergence == -1 then high else Double.NaN;
BearishLine.SetDefaultColor(Color.DARK_RED);
BearishLine.SetStyle(Curve.SHORT_DASH);
BearishLine.SetLineWeight(lineSize);

# Plotting the Moving Average for reference
plot MovingAvg = sma;
MovingAvg.SetDefaultColor(Color.GRAY);

# Fibonacci Levels
def fibLevel0 = price;
def fibLevel1 = price + (price - sma) * 0.382;
def fibLevel2 = price + (price - sma) * 0.618;
def fibLevel3 = price + (price - sma) * 1.0;
def fibLevel4 = price + (price - sma) * 1.618;

# Labels for Fibonacci Levels
AddLabel(yes, "Fib Level 0: " + AsPercent(fibLevel0), Color.GRAY);
AddLabel(yes, "Fib Level 1: " + AsPercent(fibLevel1), Color.GRAY);
AddLabel(yes, "Fib Level 2: " + AsPercent(fibLevel2), Color.GRAY);
AddLabel(yes, "Fib Level 3: " + AsPercent(fibLevel3), Color.GRAY);
AddLabel(yes, "Fib Level 4: " + AsPercent(fibLevel4), Color.GRAY);

# Hiding Labels
BullishLine.HideBubble();
BearishLine.HideBubble();
MovingAvg.HideBubble();
 
Last edited by a moderator:
Fixed a few errors and added a Fibonacci-levels feature for guidance.
When the price reaches a Fibonacci level, the labels added by the script serve as visual indicators to highlight the specific Fibonacci level that has been reached. Here's what the labels do in that case:

  1. Highlighting the Fibonacci Level:
    • The labels are placed at the corresponding Fibonacci levels on the chart.
    • When the price reaches a Fibonacci level, the label associated with that level will appear at the price level on the chart.
    • This visual indicator helps to easily identify when the price has reached a specific Fibonacci level.
  2. Providing Information:
    • The labels display the name of the Fibonacci level (e.g., "Fib Level 0", "Fib Level 1") and its corresponding percentage value.
    • This information helps you understand which Fibonacci level the price has reached and the extent of the retracement or extension.
By having the labels displayed when the price reaches a Fibonacci level, you can quickly identify and track these key levels on the chart. It allows you to monitor price movements in relation to the Fibonacci levels and potentially make trading decisions based on the interaction between the price and the Fibonacci levels.
Ruby:
#Moving Average Divergence 1.2 modified by Trader4TOS 07/02/23



input length = 20;
input divergenceThreshold = 0.001;
input lineSize = 5; # Size of the divergence lines

def price = close;
def sma = Average(price, length);

def bullishDivergence = price[1] < price and sma[1] > sma;
def bearishDivergence = price[1] > price and sma[1] < sma;

def divergence = if bullishDivergence then 1 else if bearishDivergence then -1 else Double.NaN;

plot BullishLine = if divergence == 1 then low else Double.NaN;
BullishLine.SetDefaultColor(Color.DARK_GREEN);
BullishLine.SetStyle(Curve.SHORT_DASH);
BullishLine.SetLineWeight(lineSize);

plot BearishLine = if divergence == -1 then high else Double.NaN;
BearishLine.SetDefaultColor(Color.DARK_RED);
BearishLine.SetStyle(Curve.SHORT_DASH);
BearishLine.SetLineWeight(lineSize);

# Plotting the Moving Average for reference
plot MovingAvg = sma;
MovingAvg.SetDefaultColor(Color.GRAY);

# Fibonacci Levels
def fibLevel0 = price;
def fibLevel1 = price + (price - sma) * 0.382;
def fibLevel2 = price + (price - sma) * 0.618;
def fibLevel3 = price + (price - sma) * 1.0;
def fibLevel4 = price + (price - sma) * 1.618;

# Labels for Fibonacci Levels
AddLabel(yes, "Fib Level 0: " + AsPercent(fibLevel0), Color.GRAY);
AddLabel(yes, "Fib Level 1: " + AsPercent(fibLevel1), Color.GRAY);
AddLabel(yes, "Fib Level 2: " + AsPercent(fibLevel2), Color.GRAY);
AddLabel(yes, "Fib Level 3: " + AsPercent(fibLevel3), Color.GRAY);
AddLabel(yes, "Fib Level 4: " + AsPercent(fibLevel4), Color.GRAY);

# Hiding Labels
BullishLine.HideBubble();
BearishLine.HideBubble();
MovingAvg.HideBubble();
FIB LABELS.png

Please provide a clearer explanation of your indicator. Relatively new to options trading, just not fully comprehending its function. Familiar with Fib. Just not seeing how this is "easier". I see the different "price points" within the levels. Not sure why you have them as as percentages to the tens of thousands %???? To have to decipher the % and convert it into price in a split second when you're in the middle of trading?? Thank you in advance for your help....
 
View attachment 19115
Please provide a clearer explanation of your indicator. Relatively new to options trading, just not fully comprehending its function. Familiar with Fib. Just not seeing how this is "easier". I see the different "price points" within the levels. Not sure why you have them as as percentages to the tens of thousands %???? To have to decipher the % and convert it into price in a split second when you're in the middle of trading?? Thank you in advance for your help....
Sorry for the later response. Work has been overwhelming as of late.
Let's explain how the Moving Average Divergence indicator works and how you can use it in your trading analysis.

How the Moving Average Divergence Indicator Works:The Moving Average Divergence indicator is designed to identify bullish and bearish divergences between the price and a simple moving average (SMA). It calculates the SMA based on the selected input (e.g., closing price) and a specified length (e.g., 20 periods). Then, it compares the price with the SMA to detect divergences.

A bullish divergence occurs when the price makes a lower low, but the SMA makes a higher low. This suggests potential upward momentum in the price. Conversely, a bearish divergence occurs when the price makes a higher high, but the SMA makes a lower high, indicating potential downward momentum.

The indicator plots dashed lines (green for bullish divergence and red for bearish divergence) on the chart to highlight the occurrences of divergences. Additionally, it also plots the SMA and Fibonacci levels for reference.

How to Use the Moving Average Divergence Indicator:Here's how you can use the Moving Average Divergence indicator in your trading analysis:

  1. Identify Divergence Signals: Look for instances where the green (bullish) or red (bearish) dashed lines appear on the chart. These lines represent potential bullish or bearish divergence signals, respectively. When you see these lines, it suggests a potential change in the price direction.
  2. Confirm with Price Action: Always combine the divergence signals with other forms of technical analysis and price action. Look for additional confirmation signals such as trendline breaks, candlestick patterns, or support/resistance levels.
  3. Use Fibonacci Levels as Reference: The indicator plots Fibonacci levels based on the difference between the price and the SMA. These levels can act as support and resistance zones. Consider using these levels as potential price targets or areas to watch for price reactions.
  4. Set Stop Loss and Take Profit: When using the Moving Average Divergence indicator as part of your trading strategy, set appropriate stop-loss and take-profit levels. Managing risk is essential in trading, and stop-loss orders can help protect your capital from large losses.
  5. Backtest and Optimize: Before using the indicator in live trading, conduct backtesting using historical data to assess its performance and identify optimal settings. You can tweak the length of the SMA or the divergence threshold to suit your trading style and the specific market you're trading.
Remember that no indicator can guarantee accurate predictions in the market, and it's essential to use the Moving Average Divergence indicator in conjunction with other technical and fundamental analysis tools.
If you want it to display price not percentage then use this script:

#Moving Average Divergence 1.2a modified by Trader4TOS 07/31/23 ( added threshold feature and percentage changed to price display. divergenceThreshold parameter is likely to filter out minor divergences and focus on significant ones. Divergences that fall below the specified threshold value would be considered less relevant and might not trigger the indicator's signals.
For example, if the divergenceThreshold is set to 0.001, any divergence with a difference between the custom price and the SMA of less than 0.001 would not be considered significant enough to trigger a divergence signal (neither bullish nor bearish). Only divergences with a difference greater than or equal to the threshold would be considered valid.

However, in the provided script, the divergenceThreshold parameter is not used in any conditional statement to filter out divergences. As a result, all divergences, regardless of their magnitude, would be treated equally, and the indicator would plot divergence lines for all occurrences.)
Ruby:
input length = 20;
input divergenceThreshold = 0.001;
input lineSize = 5; # Size of the divergence lines

def customPrice = close; # Replace 'close' with your desired price input

def sma = Average(customPrice, length);

def bullishDivergence = customPrice[1] < customPrice and sma[1] > sma and AbsValue(customPrice[1] - sma[1]) >= divergenceThreshold;
def bearishDivergence = customPrice[1] > customPrice and sma[1] < sma and AbsValue(customPrice[1] - sma[1]) >= divergenceThreshold;

def divergence = if bullishDivergence then 1 else if bearishDivergence then -1 else Double.NaN;

plot BullishLine = if divergence == 1 then low else Double.NaN;
BullishLine.SetDefaultColor(Color.DARK_GREEN);
BullishLine.SetStyle(Curve.SHORT_DASH);
BullishLine.SetLineWeight(lineSize);

plot BearishLine = if divergence == -1 then high else Double.NaN;
BearishLine.SetDefaultColor(Color.DARK_RED);
BearishLine.SetStyle(Curve.SHORT_DASH);
BearishLine.SetLineWeight(lineSize);

# Plotting the Moving Average for reference
plot MovingAvg = sma;
MovingAvg.SetDefaultColor(Color.GRAY);

# Fibonacci Levels
def fibLevel0 = customPrice;
def fibLevel1 = customPrice + (customPrice - sma) * 0.382;
def fibLevel2 = customPrice + (customPrice - sma) * 0.618;
def fibLevel3 = customPrice + (customPrice - sma) * 1.0;
def fibLevel4 = customPrice + (customPrice - sma) * 1.618;

# Labels for Fibonacci Levels
AddLabel(yes, "Fib Level 0: " + Round(fibLevel0, 2), Color.GRAY);
AddLabel(yes, "Fib Level 1: " + Round(fibLevel1, 2), Color.GRAY);
AddLabel(yes, "Fib Level 2: " + Round(fibLevel2, 2), Color.GRAY);
AddLabel(yes, "Fib Level 3: " + Round(fibLevel3, 2), Color.GRAY);
AddLabel(yes, "Fib Level 4: " + Round(fibLevel4, 2), Color.GRAY);

# Hiding Labels
BullishLine.HideBubble();
BearishLine.HideBubble();
MovingAvg.HideBubble();
 
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
518 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top