0% found this document useful (0 votes)
2 views9 pages

New Text Document (2) (1)

The document is a Pine Script code for a custom trading indicator called the 'Bayesian Trend Indicator with Custom Keltner Channels'. It includes user inputs for various parameters, calculations for moving averages, trend signals, and Heikin Ashi candles, as well as visualizations and alert conditions for bullish and bearish trends. The script aims to provide traders with insights into market trends and potential entry/exit signals based on Bayesian probabilities.

Uploaded by

Aj Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

New Text Document (2) (1)

The document is a Pine Script code for a custom trading indicator called the 'Bayesian Trend Indicator with Custom Keltner Channels'. It includes user inputs for various parameters, calculations for moving averages, trend signals, and Heikin Ashi candles, as well as visualizations and alert conditions for bullish and bearish trends. The script aims to provide traders with insights into market trends and potential entry/exit signals based on Bayesian probabilities.

Uploaded by

Aj Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

//@version=5

indicator('Bayesian Trend Indicator with Custom Keltner Channels', shorttitle =


"Bayesian Trend & Keltner", overlay=true, max_labels_count = 500)

//
-----------------------------------------------------------------------------------

// 𝙐𝙎𝙀𝙍 𝙄𝙉𝙋𝙐𝙏𝙎
----------------------------------}

//
-----------------------------------------------------------------------------------
----------------------------------{
float source = input(hlc3, title='Source', group = "Settings")
int length = input.int(60, title="MA's Length", group = "Settings")

int gap_length = input.int(20, "Gap Length Between Fast And Slow MA's",
tooltip = "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"
)
int gap = input.int(10, "Gap Signals", minval = 10,
tooltip = "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."
)

color colorUp = #0fac16


color colorDn = #c51212

// FUNCTIONS
//@function This function forces the current timeframe on inputs that shouldn't
take lower timeframes
FORCE_CTF(str_tf) =>
i_tf_sec = timeframe.in_seconds(str_tf)
ctf_sec = timeframe.in_seconds('')

// Returns the CTF if the passed timeframe is lower


i_tf_sec < ctf_sec ? '' : str_tf
//

// INPUTS
ha_htf = FORCE_CTF(input.timeframe('', 'Timeframe', tooltip="This timeframe must be
equal to or greater than the chart's timeframe", group="HA Market Bias"))
ha_len = input(100, 'Period', group="HA Market Bias")
ha_len2 = input(100, 'Smoothing', group="HA Market Bias")

show_ha = input.bool(true, "Show HA Candles", inline='ha/mb display',


group='Display Settings')
show_mb = input.bool(true, "Show Market Bias", inline='ha/mb display',
group='Display Settings')
col_bull = input.color(color.lime, 'Color: Bullish', inline='bull/bear color',
group='Display Settings', display=display.none)
col_bear = input.color(color.red, 'Bearish', inline='bull/bear color',
group='Display Settings', display=display.none)

// These add an offset during data importation to avoid lookahead bias


indexHighTF = timeframe.in_seconds(ha_htf) == timeframe.in_seconds('') ? 0 :
barstate.isrealtime ? 1 : 0
indexCurrTF = timeframe.in_seconds(ha_htf) == timeframe.in_seconds('') ? 0 :
barstate.isrealtime ? 0 : 1

//@function Handles the import of data from other timeframes, while preventing
repainting
//@param _resolution (str) : This is the timeframe to import data from.
//@param _expression (float | int) : This is the data to be imported
f_no_repaint_request(string _resolution, _expression) =>
request.security(syminfo.tickerid, _resolution, _expression[indexHighTF])
[indexCurrTF]
//#endregion

//
-----------------------------------------------------------------------------------

// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
----------------------------------}

//
-----------------------------------------------------------------------------------
----------------------------------{
// Calculate moving averages
ema_ = ta.ema(source, length)
sma_ = ta.sma(source, length)
dema_ = ta.ema(2 * ta.ema(source, length) - ta.ema(ta.ema(source, length), length),
length)
vwma_ = ta.vwma(source, length)

// Calculate faster moving averages with lower length


ema_fast = ta.ema(source, length-gap_length)
sma_fast = ta.sma(source, length-gap_length)
dema_fast = ta.ema(2 * ema_fast - ta.ema(ema_fast, length-gap_length), length-
gap_length)
vwma_fast = ta.vwma(source, length-gap_length)

// Smoothed Gradient Signal Function


sig(float src, gap)=>
ta.ema(
source >= src[gap] ? 1 :
source >= src[gap-1] ? 0.9 :
source >= src[gap-2] ? 0.8 :
source >= src[gap-3] ? 0.7 :
source >= src[gap-4] ? 0.6 :
source >= src[gap-5] ? 0.5 :
source >= src[gap-6] ? 0.4 :
source >= src[gap-7] ? 0.3 :
source >= src[gap-8] ? 0.2 :
source >= src[gap-9] ? 0.1 :
0, 4
)

// Calculate trend for each faster moving average


ema_trend_fast = sig(ema_fast, gap)
sma_trend_fast = sig(sma_fast, gap)
dema_trend_fast = sig(dema_fast, gap)
vwma_trend_fast = sig(vwma_fast, gap)

// Calculate trend for each moving average


ema_trend = sig(ema_, gap)
sma_trend = sig(sma_, gap)
dema_trend = sig(dema_, gap)
vwma_trend = sig(vwma_, gap)

// Define prior probabilities using moving averages


prior_up = (ema_trend + sma_trend + dema_trend + vwma_trend) / 4
prior_down = 1 - prior_up

// Define likelihoods using faster moving averages


likelihood_up = (ema_trend_fast + sma_trend_fast + dema_trend_fast +
vwma_trend_fast) / 4
likelihood_down = 1 - likelihood_up

// Calculate posterior probabilities using 𝘽𝙖𝙮𝙚𝙨❜ 𝙩𝙝𝙚𝙤𝙧𝙚𝙢


posterior_up = prior_up * likelihood_up
/
(prior_up * likelihood_up + prior_down * likelihood_down)

if na(posterior_up)
posterior_up := 0

// Smoothen the OHLC values


o = ta.ema(open, ha_len)
c = ta.ema(close, ha_len)
h = ta.ema(high, ha_len)
l = ta.ema(low, ha_len)

// Calculate the Heikin Ashi OHLC values from it


haclose = f_no_repaint_request(ha_htf, (o + h + l + c) / 4)
xhaopen = f_no_repaint_request(ha_htf, (o + c) / 2)
haopen = na(xhaopen[1]) ? (o + c) / 2 : (xhaopen[1] + haclose[1]) / 2
hahigh = math.max(h, math.max(haopen, haclose))
halow = math.min(l, math.min(haopen, haclose))

// Smoothen the Heiken Ashi Candles


o2 = f_no_repaint_request(ha_htf, ta.ema(haopen, ha_len2))
c2 = f_no_repaint_request(ha_htf, ta.ema(haclose, ha_len2))
h2 = f_no_repaint_request(ha_htf, ta.ema(hahigh, ha_len2))
l2 = f_no_repaint_request(ha_htf, ta.ema(halow, ha_len2))

ha_avg = (h2 + l2) / 2

//TODO: Publish the Oscillator version of the indicator


// Oscillator {
osc_len = input.int(7, "Oscillator Period", group="HA Market Bias")

osc_bias = 100 * (c2 - o2)


osc_smooth = ta.ema(osc_bias, osc_len)

sigcolor = switch
(osc_bias > 0) and (osc_bias >= osc_smooth) => color.new(col_bull, 35)
(osc_bias > 0) and (osc_bias < osc_smooth) => color.new(col_bull, 75)
(osc_bias < 0) and (osc_bias <= osc_smooth) => color.new(col_bear, 35)
(osc_bias < 0) and (osc_bias > osc_smooth) => color.new(col_bear, 75)
=> color(na)
// }

//
-----------------------------------------------------------------------------------
----------------------------------}
// 𝙑𝙄𝙎𝙐𝘼𝙇𝙄𝙕𝘼𝙏𝙄𝙊𝙉
//
-----------------------------------------------------------------------------------
----------------------------------{
// Bar Color Trend
trend_col = posterior_up < 0.48
? 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

plotcandle(open, high, low, close,


color = trend_col,
bordercolor = trend_col,
wickcolor = trend_col
)
barcolor(trend_col)

// Plots
p_h = plot(h2, "Bias High", color=color(na), display=display.data_window,
editable=false)
p_l = plot(l2, "Bias Low", color=color(na), display=display.data_window,
editable=false)
p_avg = plot(ha_avg, "Bias Avergae", color=color(na), display=display.data_window,
editable=false)
fill(p_l, p_h, show_mb ? sigcolor : na)

col = o2 > c2 ? col_bear : col_bull


plotcandle(o2, h2, l2, c2, title='heikin smoothed', color=col, display=show_ha ?
display.pane : display.data_window, editable=false)

// Signals
plotchar(ta.crossover(posterior_up, 0.5),
char = "◆",
location = location.belowbar,
size = size.tiny,
color = color.new(colorUp, 5)
)
plotchar(ta.crossunder(posterior_up, 0.5),
char = "◆",
location = location.abovebar,
size = size.tiny,
color = color.new(colorDn, 5)
)

// Alerts
// Bullish Trend Switch (Bearish -> Bullish)
alertcondition(ta.change(ta.change(math.sign(osc_bias)) > 0),
'Bullish Trend Switch (Bearish -> Bullish)', '{{exchange}}:{{ticker}}: Trend is
now Bullish.')

// Bullish Trend Strengthens


alertcondition(osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0,
'Bullish Trend Strengthens', '{{exchange}}:{{ticker}}: Bullish Trend is now
Stronger.')

// Bullish Trend Weakens


alertcondition(osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0,
'Bullish Trend Weakens', '{{exchange}}:{{ticker}}: Bullish Trend is now Weaker.')

// Bearish Trend Switch (Bullish -> Bearish)


alertcondition(ta.change(ta.change(math.sign(osc_bias)) < 0),
'Bearish Trend Switch (Bullish -> Bearish)', '{{exchange}}:{{ticker}}: Trend is
now Bearish.')

// Bearish Trend Strengthens


alertcondition(osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0,
'Bearish Trend Strengthens', '{{exchange}}:{{ticker}}: Bearish Trend is now
Stronger.')

// Bearish Trend Weakens


alertcondition(osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0,
'Bearish Trend Weakens', '{{exchange}}:{{ticker}}: Bearish Trend is now Weaker.')
//#endregion

// CUSTOM ALERTS : To enable this functionality, Select and uncomment (Cmd (or
Ctrl) + /) the following code block, starting from the next line.
// // {
// use_custom_alerts = input.bool(false, 'Use Custom Alert Messages', group='Alert
Messages', display=display.none)
// i_alert_bull_trend_switch = input.text_area('New Bullish Trend', 'Bullish Trend
Switch', group='Alert Messages', display=display.none)
// i_alert_bull_trend_strengthen = input.text_area('New Strong Bullish Trend',
'Bullish Trend Strengthens', group='Alert Messages', display=display.none)
// i_alert_bull_trend_weaken = input.text_area('New Weak Bullish Trend', 'Bullish
Trend Weakens', group='Alert Messages', display=display.none)
// i_alert_bear_trend_switch = input.text_area('New Bearish Trend', 'Bearish Trend
Switch', group='Alert Messages', display=display.none)
// i_alert_bear_trend_strengthen = input.text_area('New Strong Bearish Trend',
'Bearish Trend Strengthens', group='Alert Messages', display=display.none)
// i_alert_bear_trend_weaken = input.text_area('New Weak Bearish Trend', 'Bearish
Trend Weakens', group='Alert Messages', display=display.none)

// // Bullish Trend Switch (Bearish -> Bullish)


// if (ta.change(ta.change(math.sign(osc_bias)) > 0))
// alert(i_alert_bull_trend_switch, alert.freq_once_per_bar)

// // Bullish Trend Strengthens


// if (osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0)
// alert(i_alert_bull_trend_strengthen, alert.freq_once_per_bar)

// // Bullish Trend Weakens


// if (osc_bias > 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0)
// alert(i_alert_bull_trend_weaken, alert.freq_once_per_bar)

// // Bearish Trend Switch (Bullish -> Bearish)


// if (ta.change(ta.change(math.sign(osc_bias)) < 0))
// alert(i_alert_bear_trend_switch, alert.freq_once_per_bar)

// // Bearish Trend Strengthens


// if (osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) < 0)
// alert(i_alert_bear_trend_strengthen, alert.freq_once_per_bar)

// // Bearish Trend Weakens


// if (osc_bias < 0 and ta.change(math.sign(osc_bias - osc_smooth)) > 0)
// alert(i_alert_bear_trend_weaken, alert.freq_once_per_bar)
// // }

//
-----------------------------------------------------------------------------------

// 𝙐𝙎𝙀𝙍 𝙄𝙉𝙋𝙐𝙏𝙎
---------------------------------}

//
-----------------------------------------------------------------------------------
---------------------------------{
int len = input.int(100, "Swing Length")
bool hide_h_l = input.bool(true, "Levels", inline = "lvl", group =
"Levels")
bool broken_levels = input.bool(false, "Broken Levels", inline = "lvl", group =
"Levels")
bool history_levels = input.bool(false, "History Levels", inline = "lvl", group
= "Levels")

bool shadow = input.bool(true, "Shadow", inline = "s", group = "Levels")


int shadow_width = input.int(8, "", inline = "s", group = "Levels")

color upper_col = input.color(#c424e0, "▽", inline = "cc")


color lower_col = input.color(#24e075, "△", inline = "cc")

// Declare variables
var int index_h = na
var int index_l = na
var bool trend = false

var line line_h = na


var line line_h1 = na
var line line_l = na
var line line_l1 = na
var line line_z = na

var line line_up = na


var line line_dn = na
var label lbl_h = na
var label lbl_l = na

// Global variables for ta.change() results


var bool change_upper = false
var bool change_lower = false

//
-----------------------------------------------------------------------------------

// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎 / 𝙑𝙄𝙎𝙐𝘼𝙇𝙄𝙕𝘼𝙏𝙄𝙊𝙉


---------------------------------}

//
-----------------------------------------------------------------------------------
---------------------------------{
float upper = ta.highest(len)
float lower = ta.lowest(len)

bool upper_trigger = high[1] == upper[1] and high < upper


bool lower_trigger = low[1] == lower[1] and low > lower

if upper_trigger
index_h := time[1]
if lower_trigger
index_l := time[1]

if high == upper
trend := true

if low == lower
trend := false

// Calculate ta.change() results


change_upper := ta.change(trend)
change_lower := ta.change(not trend)

if not trend and change_upper


line_h := line.new(index_h, upper, time, upper, color = hide_h_l ? upper_col :
na, width = 2, xloc = xloc.bar_time)
if shadow
line_h1 := line.new(index_h
, upper
, line_h.get_x2()
, upper
, color = hide_h_l ? color.new(upper_col, 70) : na
, width = shadow_width
, xloc = xloc.bar_time)

line_z := line.new(index_l, line_l.get_y1(), line_h.get_x1(), upper, color =


lower_col, xloc = xloc.bar_time)

if not history_levels
line.delete(line_h[1])
line.delete(line_h1[1])

if trend and change_lower


line_l := line.new(index_l, lower, time, lower, color = hide_h_l ? lower_col :
na, width = 2, xloc = xloc.bar_time)
if shadow
line_l1 := line.new(index_l
, lower
, time
, lower
, color = hide_h_l ? color.new(lower_col,70) : na
, width = shadow_width
, xloc = xloc.bar_time)

line_z := line.new(index_h, line_h.get_y1(), line_l.get_x1(), lower, color =


upper_col, xloc = xloc.bar_time)

if not history_levels
line.delete(line_l[1])
line.delete(line_l1[1])

line_z.set_style(line.style_dashed)

line_l.set_x2(time)
line_l1.set_x2(time)

line_h.set_x2(time)
line_h1.set_x2(time)
bool cross_over = ta.crossover(low, line_h.get_y1())
bool cross_under = ta.crossunder(high, line_l.get_y1())

if not (trend != trend[1]) and broken_levels


if cross_over
line_h.set_style(line.style_dashed)
line_h.set_width(1)

if cross_under and barstate.isconfirmed


line_l.set_style(line.style_dashed)
line_l.set_width(1)

if barstate.islast
if trend != trend[1]
line.delete(line_up)
line.delete(line_dn)
label.delete(lbl_h)
label.delete(lbl_l)

if not trend != trend[1]


if trend
line_up := line.new(index_l
, line_l.get_y1()
, index_h
, upper
, style = line.style_dashed
, color = lower_col
, xloc = xloc.bar_time)
if not trend
line_dn := line.new(index_h
, line_h.get_y1()
, index_l
, lower
, style = line.style_dashed
, color = upper_col
, xloc = xloc.bar_time)

if hide_h_l
lbl_h := label.new(bar_index
, line_h.get_y1()
, str.tostring(line_h.get_y1()
, "Swing H (#,###.####)")
, style = label.style_label_left
, color = color.new(upper_col, 50)
, textcolor = chart.fg_color)

lbl_l := label.new(bar_index
, line_l.get_y1()
, str.tostring(line_l.get_y1()
, "Swing L (#,###.####)")
, style = label.style_label_left
, color = color.new(lower_col, 50)
, textcolor = chart.fg_color)

label.delete(lbl_h[1])
label.delete(lbl_l[1])
line.delete(line_dn[1])
line.delete(line_up[1])
var tbl = table.new(position.top_right, 10, 10)
tbl.cell(0,0,"Swing Direction: ", text_color = chart.fg_color)
tbl.cell(1,0, (trend ? "⬈" : "⬊"), text_color = trend ? lower_col : upper_col,
text_size = size.huge)

if not hide_h_l
label.new(line_h.get_x1(), line_h.get_y2(), "", xloc = xloc.bar_time, color =
upper_col)
label.new(line_l.get_x1(), line_l.get_y2(), "", xloc = xloc.bar_time, style =
label.style_label_up, color = lower_col)

plot(na, editable = false)


//
-----------------------------------------------------------------------------------
---------------------------------}

// Custom Keltner Channels


k_length = 0.425
uphighColor = color.new(color.fuchsia, 90)
uplowColor = color.new(color.fuchsia, 70)
downhighColor = color.new(color.purple, 70)
downlowColor = color.new(color.purple, 90)

[middleKC1, upperKC1, lowerKC1] = ta.kc(close, 10, 10.5 * k_length)


[middleKC2, upperKC2, lowerKC2] = ta.kc(close, 10, 9.5 * k_length)
[middleKC3, upperKC3, lowerKC3] = ta.kc(close, 10, 8 * k_length)
[middleKC4, upperKC4, lowerKC4] = ta.kc(close, 10, 3 * k_length)

middleLineValue = ta.ema((upperKC1 + lowerKC1) / 2, 50)


middleLineColor = middleLineValue > middleLineValue[1] ? color.green : color.red
middleLine = plot(middleLineValue, "Middle Line", color=middleLineColor,
linewidth=2, editable=false)

k1 = plot(ta.ema(upperKC1, 50), display=display.none)


k2 = plot(ta.ema(upperKC2, 50), display=display.none)
k3 = plot(ta.ema(upperKC3, 50), display=display.none)
k4 = plot(ta.ema(upperKC4, 50), display=display.none)
k5 = plot(ta.ema(lowerKC4, 50), display=display.none)
k6 = plot(ta.ema(lowerKC3, 50), display=display.none)
k7 = plot(ta.ema(lowerKC2, 50), display=display.none)
k8 = plot(ta.ema(lowerKC1, 50), display=display.none)

fill(k1, k2, uphighColor, editable=false)


fill(k2, k3, uplowColor, editable=false)
// fill(k3, k4, color.new(color.red, 90), editable=false)
// fill(k5, k6, color.new(color.green, 90), editable=false)
fill(k6, k7, downlowColor, editable=false)
fill(k7, k8, downhighColor, editable=false)

You might also like