• Get $40 off VIP by signing up for a free account! Sign Up

Bayesian Trend Indicator [ChartPrime] for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
AuazwWw.png

Author Message:
Overview:
In probability theory and statistics, Bayes' theorem (alternatively Bayes' law or Bayes' rule), named after Thomas Bayes, describes the probability of an event, based on prior knowledge of conditions that might be related to the event.

The "Bayesian Trend Indicator" is a sophisticated technical analysis tool designed to assess the direction of price trends in financial markets. It combines the principles of Bayesian probability theory with moving average analysis to provide traders with a comprehensive understanding of market sentiment and potential trend reversals.

At its core, the indicator utilizes multiple moving averages, including the Exponential Moving Average (EMA), Simple Moving Average (SMA), Double Exponential Moving Average (DEMA), and Volume Weighted Moving Average (VWMA). These moving averages are calculated based on user-defined parameters such as length and gap length, allowing traders to customize the indicator to suit their trading strategies and preferences.
find more: https://www.tradingview.com/v/rVEhAQDO/

CODE:

CSS:
#// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL
#// © ChartPrime
#gap_length = "Determines the difference in lengths between the slow and fast moving averages. A higher gap length will increase the difference, potentially identifying stronger trend signals"
#gap = "Defines the gap used for the smoothed gradient signal function. This parameter affects the sensitivity of the trend signals by setting the number of bars used in the signal calculations."
#indicator('Bayesian Trend Indicator [ChartPrime]', shorttitle = "Bayesian Trend [ChartPrime]", overlay=
# Converted by Sam4Cok@Samer800    - 06/2024
input colorBars = yes;
input showProbabilityOnBar = yes;
input labelOptions = {Default "Summary", "Detailed", "Show All", "Don't Show Label"};
input source = hlc3; #, title='Source', group = "Settings")
input movAvgLength = 60; #, title="MA's Length", group = "Settings")
input gapLength = 20; #, "Gap Length Between Fast And Slow MA's",
input gapSignals = 10; #, "Gap Signals", minval = 10,

input ProbValueToShowBack = 100;

def na = Double.NaN;
def labUp = labelOptions==labelOptions."Summary" or labelOptions==labelOptions."Show All";
def labMa = labelOptions==labelOptions."Detailed" or labelOptions==labelOptions."Show All";
def gap = Max(GapSignals, 10);
#vwma(source, length)
script VWMA {
    input src = close;
    input len = 60;
    input vol = volume;
    def nom = Average(src * vol, len);
    def den = Average(vol, len);
    def VWMA = nom / den;
    plot result = VWMA;
}
Script f_Dema {
input source = close;
input length = 60;
    def ema1 = ExpAverage(source, length);
    def ema2 = ExpAverage(ema1, length);
    def ema3 = 2 * ema1 - ema2;
    def dema = ExpAverage(ema3, length);
    plot out = dema;
}
#// Smoothed Gradient Signal Function
script sig {
    input source = close;
    input src = close;
    input gap = 10;
    def calcSrc =
     if source >= src[gap]   then 1   else
     if source >= src[gap - 1] then 0.9 else
     if source >= src[gap - 2] then 0.8 else
     if source >= src[gap - 3] then 0.7 else
     if source >= src[gap - 4] then 0.6 else
     if source >= src[gap - 5] then 0.5 else
     if source >= src[gap - 6] then 0.4 else
     if source >= src[gap - 7] then 0.3 else
     if source >= src[gap - 8] then 0.2 else
     if source >= src[gap - 9] then 0.1 else 0;
    def sig = ExpAverage(calcSrc, 4);
    plot out = sig;
}

#// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
#// Calculate moving averages
def ema_  = ExpAverage(source, movAvgLength);
def sma_  = Average(source, movAvgLength);
def dema_ = f_Dema(source, movAvgLength);
def vwma_ = vwma(source, movAvgLength);

#// Calculate faster moving averages with lower length
def ema_fast  = ExpAverage(source, movAvgLength - gapLength);
def sma_fast  = Average(source, movAvgLength - gapLength);
def dema_fast = f_Dema(source, movAvgLength - gapLength);
def vwma_fast = vwma(source, movAvgLength - gapLength);

#// Calculate trend for each faster moving average
def ema_trend_fast  = sig(source, ema_fast, gap);
def sma_trend_fast  = sig(source, sma_fast, gap);
def dema_trend_fast = sig(source, dema_fast, gap);
def vwma_trend_fast = sig(source, vwma_fast, gap);

#// Calculate trend for each moving average
def ema_trend       = sig(source, ema_, gap);
def sma_trend       = sig(source, sma_, gap);
def dema_trend      = sig(source, dema_, gap);
def vwma_trend      = sig(source, vwma_, gap);

#// Define prior probabilities using moving averages
def prior_up   = (ema_trend + sma_trend + dema_trend + vwma_trend) / 4;
def prior_down = 1 - prior_up;

#// Define likelihoods using faster moving averages
def likelihood_up   = (ema_trend_fast + sma_trend_fast + dema_trend_fast + vwma_trend_fast) / 4;
def likelihood_down = 1 - likelihood_up;

#// Calculate posterior probabilities using 𝘽𝙖𝙮𝙚𝙨❜ 𝙩𝙝𝙚𝙤𝙧𝙚𝙢
def posteriorUp = prior_up * likelihood_up / (prior_up * likelihood_up + prior_down * likelihood_down);
def posterior_up = if IsNaN(posteriorUp) then 0 else posteriorUp;

#// 𝙑𝙄𝙎𝙐𝘼𝙇𝙄𝙕𝘼𝙏𝙄𝙊𝙉
#// Bar Color Trend
def col = posterior_up * 100 * 2.55;
#def trend_col = if posterior_up < 0.48 then if
# ? color.from_gradient(posterior_up, 0, 0.48, colorDn, color.new(chart.bg_color, 20))
# : posterior_up > 0.52 ? color.from_gradient(posterior_up, 0.52, 1, color.new(chart.bg_color, 20), colorUp)
# : chart.bg_color

#// Probability Labels   FROM 0 TO 1 (0%-100%)
def n = BarNumber();
def bar = if !isNaN(close) then BarNumber() else bar[1];

def cond = n >= (highestAll(bar) - ProbValueToShowBack);
def rndProp = Round(posterior_up, 2);
plot PropUp = if !showProbabilityOnBar then na else if cond and posterior_up > 0.5 then rndProp else na; #? high : low,
plot PropDn = if !showProbabilityOnBar then na else if !cond or posterior_up > 0.5 then na else rndProp; #? high : low,
PropUp.SetPaintingStrategy(PaintingStrategy.VALUES_ABOVE);
PropDn.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);
PropUp.AssignValueColor(CreateColor(255 - col, col, 0));
PropDn.AssignValueColor(CreateColor(255 - col, col, 0));

#// Signals
def sigUp = (posterior_up Crosses Above 0.5);
def sigDn = (posterior_up Crosses Below 0.5);

plot probUp = if sigUp then low else na;
plot probDn = if sigDn then high else na;
probUp.SetLineWeight(2);
probDn.SetLineWeight(2);
probUp.SetDefaultColor(Color.CYAN);
probDn.SetDefaultColor(Color.MAGENTA);
probUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
probDn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);

#-- bar color
AssignPriceColor(if !colorBars then Color.CURRENT else CreateColor(255 - col, col, 0));

#-- label
def prpRnd = Round(posterior_up * 100, 2);
def smaS = Round(sma_trend, 2);
def smaF = Round(sma_trend_fast, 2);
def emaS = Round(ema_trend, 2);
def emaF = Round(ema_trend_fast, 2);
def dmaS = Round(dema_trend, 2);
def dmaF = Round(dema_trend_fast, 2);
def vmaS = Round(vwma_trend, 2);
def vmaF = Round(vwma_trend_fast, 2);

AddLabel(labUp,"Prob. of UpTrend (" + prpRnd + "%)", CreateColor(255 - prpRnd * 2.55, prpRnd * 2.55, 0));
AddLabel(labMa,"SMA(Slow," + smaS + ")", CreateColor(255 - smaS * 255, smaS * 255, 0));
AddLabel(labMa,"(Fast," + smaF + ")",    CreateColor(255 - smaF * 255, smaF * 255, 0));
AddLabel(labMa,"EMA(Slow," + emaS + ")", CreateColor(255 - emaS * 255, emaS * 255, 0));
AddLabel(labMa,"(Fast," + emaF + ")",    CreateColor(255 - emaF * 255, emaF * 255, 0));
AddLabel(labMa,"DEMA(Slow," + dmaS + ")",CreateColor(255 - dmaS * 255, dmaS * 255, 0));
AddLabel(labMa,"(Fast," + dmaF + ")",    CreateColor(255 - dmaF * 255, dmaF * 255, 0));
AddLabel(labMa,"VWMA(Slow," + vmaS + ")",CreateColor(255 - vmaS * 255, vmaS * 255, 0));
AddLabel(labMa,"(Fast," + vmaF + ")",    CreateColor(255 - vmaF * 255, vmaF * 255, 0));

#-- END of CODE
 

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

is there a scan for color/trend change? (from red to green or green to red)

There is no color/trend change. This script works on a gradient of color.
With various shades of orange, pink, purple before changing completely over from red to green or green to red.

However, there are cyan and magenta wedges which signal that the probabilities are over or under 50%
Ruby:
#// Signals
def sigUp = (posterior_up Crosses Above 0.5);
def sigDn = (posterior_up Crosses Below 0.5);

plot probUp = if sigUp then low else na;
plot probDn = if sigDn then high else na;
probUp.SetLineWeight(2);
probDn.SetLineWeight(2);
probUp.SetDefaultColor(Color.CYAN);
probDn.SetDefaultColor(Color.MAGENTA);
probUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
probDn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);

To scan on the probabilities, your filters would be:
probUP is true
or
probDN is true

For a tutorial on how to set up your filters in the ToS Scan Hacker:
https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
353 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