ELMEHDI VIP (v4.0) ABO SALTAN //@version=5
indicator(title = 'ELMEHDI VIP (v4.0) ABO SALTAN ', shorttitle = 'EL MEHDI KHEYI(v4.0)', overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_bars_back = 500, max_polylines_count = 100)
bullcolor = #339b44
bearcolor = #af3232
ema150 = ta.ema(close, 150)
ema250 = ta.ema(close, 250)
gr_customalert = "Custom Alerts"
gr_signal = "General Configurations"
gr_PullBacksignal = "Trading Assistants"
gr_RiskManage = "Risk Management"
gr_dash = "Dashboard Configurations"
//symbol info
symInfoCheck = false
symInfo = syminfo.ticker + ' | ' + timeframe.period + (timeframe.isminutes ? 'M' : na)
date = str.tostring(dayofmonth(time_close)) + '/' + str.tostring(month(time_close)) + '/' + str.tostring(year(time_close))
//text positioning
textVPosition = 'middle'
textHPosition = 'center'
//symbol info positioning
symVPosition = 'top'
symHPosition = 'left'
//cell size
width = 0
height1 = 0
//title settings
c_title = #b2b5be80
s_title = 'large'
a_title = 'center'
//subtitle settings
c_subtitle = #b2b5be80
s_subtitle = 'normal'
a_subtitle = 'center'
c_bg = color.new(color.blue, 100)
// Get user input
showSignals = input(true, "Show Signal's", group=gr_signal)
//showSignals = true
sensitivity = input.float(2.4, "Sensitivity", 0.1, step=0.1, group=gr_signal)
STuner = input.int(10, "Signal Tuner(1-25)", minval = 1, maxval = 25, group=gr_signal)
Presets = "All Signals"
//Presets = input.string("All Signals", "Presets", , group=gr_signal)
filterstyle = input.string("Trending Signals ", "Signal Mode / Filters", ["Trending Signals ", "Contrarian Signals ", "High Volume ", "Strong ", "Swing ", "Smooth ", "Scalping ", "Scalping+ "], group=gr_signal)
//TextStyle = input.string("Minimal", "Signal Style", , group=gr_signal)
//periodTrendCloud = input.string("Smooth", "Trend Cloud Style", , group=gr_Other_Settings)
TextStyle = "Minimal"
consSignalsFilter = filterstyle == "Trending Signals " ? true : false
StrongSignalsOnly = filterstyle == "Strong " ? true : false
highVolSignals = filterstyle == "High Volume " ? true : false
signalsTrendCloud = (filterstyle == "Smooth ") ? true : (filterstyle == "Scalping ") ? true : (filterstyle == "Scalping+ ") ? true : (filterstyle == "Swing ") ? true : false
ContrarianOnly = filterstyle == "Contrarian Signals " ? true : false
TrendMap = 'Trend Gradient'
momentumCandles = false
assistantenable = input(true,'', group=gr_PullBacksignal, inline = 'sexyshit')
assistantmode = input.string('Trend Assistant', 'Assistant | Mode', , group = gr_PullBacksignal, inline = 'sexyshit')
Show_PR = input.bool(true, title="", group = gr_PullBacksignal , inline = "Features1")
MSTuner = input.int(8, "Reversal Dot | Tuner(2-30)", minval = 2, maxval = 30, group=gr_PullBacksignal, inline = "Features1")
LongTrendAverage = assistantmode == 'Trend Tracker' and assistantenable == true ? true : false
analyscloud = assistantmode == 'Trend Assistant' and assistantenable == true ? true : false
showTrendCloud = (filterstyle == "Smooth ") ? true : (filterstyle == "Scalping ") ? true : (filterstyle == "Scalping+ ") ? true : (filterstyle == "Swing ") ? true : false
periodTrendCloud = (filterstyle == "Smooth ") ? "Smooth" : (filterstyle == "Scalping ") ? "Scalping" : (filterstyle == "Scalping+ ") ? "Scalping+" : (filterstyle == "Swing ") ? "Swing" : na
//ScalpingPlus = input(false, "Fast trend cloud", group=gr_Other_Settings)
//fastTrendCloudLen = input.int(55, "Fast trend cloud", 2, group=gr_Other_Settings)
fill(plot(showTrendCloud and periodTrendCloud == "Smooth" ? na : assistantenable == true and assistantmode == 'Trend Tracker' ? ema150 : na, "", na, editable=false), plot(showTrendCloud and periodTrendCloud == "Smooth" ? na : assistantenable == true and assistantmode == 'Trend Tracker' ? ema250 : na, "", na, editable=false), ema150 > ema250 ? color.new(bullcolor, 70) : ema150 < ema250 ? color.new(bearcolor, 70) : na)
showDashboard = input(true, "Smart Panel", group = gr_dash , inline = "Features1")
locationDashboard = input.string("Bottom Right", "Dashboard Location", , group = gr_dash , tooltip="Smart Panel")
sizeDashboard = input.string("Small", "Dashboard Size", , group = gr_dash , tooltip="Smart Panel")
tpLabels = input(true, "Dynamic Take Profit Lables", group=gr_RiskManage)
ShowTpSlAreas = input(true, "Show take Profit/Stop-loss Area", group=gr_RiskManage)
ShowTrailingSL = input(false, "Show trailing Stop-loss", group=gr_RiskManage)
usePercSL = input(false, "SL/TRAILING", inline="1", group=gr_RiskManage)
percTrailingSL = input.float(1, "", 0, step=0.1, inline="1", group=gr_RiskManage)
useTP1 = input(true, "", inline="1", group=gr_RiskManage)
multTP1 = input.float(1, "TP 1", 0, inline="1", group=gr_RiskManage)
useTP2 = input(true, "", inline="4", group=gr_RiskManage)
multTP2 = input.float(2, "TP 2", 0, inline="4", group=gr_RiskManage)
useTP3 = input(true, "", inline="4", group=gr_RiskManage)
multTP3 = input.float(3, "TP 3", 0, inline="4", group=gr_RiskManage)
ShowSwings = input(false, "Show Market Structure", inline="3", group=gr_RiskManage)
periodSwings = input.int(10, "", 2, inline="3", group=gr_RiskManage)
//showTS = input(title='Show Trend Shifter', defval=false, group='Contrarian SIGNALS')
// showsignals = input(title='Show Signals', defval=false, group='Contrarian SIGNALS')
// Alerts Managemnt
Normalbuy_alert = input.bool(title='Buy Signal', defval=false, inline = "NB", group=gr_customalert)
Strongbuy_alert = input.bool(title='Strong Buy', defval=true, inline = "NB", group=gr_customalert)
Normalsell_alert = input.bool(title='Sell Signal', defval=false , inline = "NS", group=gr_customalert)
Strongsell_alert = input.bool(title='Strong Sell', defval=true , inline = "NS", group=gr_customalert)
slalert = input.bool(title='Stop-Loss', defval=true , inline = "SLTP1", group=gr_customalert)
tp1alert = input.bool(title='Target 1', defval=true , inline = "SLTP1", group=gr_customalert)
tp2alert = input.bool(title='Target 2', defval=true , inline = "TP2TP3", group=gr_customalert)
tp3alert = input.bool(title='Target 3', defval=true , inline = "TP2TP3", group=gr_customalert)
bullcrosscloud_alert = input.bool(title='Bullish Cloud', defval=false, inline = "CD", group=gr_customalert)
bearcrosscloud_alert = input.bool(title='Bearish Cloud', defval=false, inline = "CD", group=gr_customalert)
showCons = false
paintCons = false
// Signal Text
SimpleBuy = "Buy"
StrongB = "Strong Buy"
SimpleSell = "Sell"
StrongS = "Strong Sell"
if TextStyle == "Normal"
SimpleBuy := "Buy"
StrongB := "BUY"
SimpleSell:= "Sell"
StrongS := "Strong Sell"
if TextStyle == "Minimal"
SimpleBuy := "⬆️"
StrongB := "⬆️⬆️"
SimpleSell:= "⬇️"
StrongS := "⬇️⬇️"
// Signal Text Color
// bullsignalcolor = #ffffff
// bearsignalcolor = color.rgb(255, 255, 255)
// if TextStyle == "Normal"
// bullsignalcolor := color.rgb(255, 255, 255)
// bearsignalcolor := color.rgb(255, 255, 255)
// if TextStyle == "Minimal"
// bullsignalcolor := color.rgb(255, 255, 255)
// bearsignalcolor := color.rgb(255, 255, 255)
src = close
RSII = ta.ema(ta.rsi(src, 50), 30)
TR = math.abs(RSII - RSII )
wwalpha = 1 / 50
WWMA = 0.0
WWMA := wwalpha * TR + (1 - wwalpha) * nz(WWMA )
ATRRSI = 0.0
ATRRSI := wwalpha * WWMA + (1 - wwalpha) * nz(ATRRSI )
TsFast = ta.ema(ta.rsi(src, 50), 30)
TsUP = TsFast + ATRRSI * 4.236
TsDN = TsFast - ATRRSI * 4.236
textWatermark = table.new(textVPosition + '_' + textHPosition, 1, 3)
TsSlow = 0.0
TsSlow := TsUP < nz(TsSlow ) ? TsUP : TsFast > nz(TsSlow ) and TsFast < nz(TsSlow ) ? TsDN : TsDN > nz(TsSlow ) ? TsDN : TsDN < nz(TsSlow ) and TsFast > nz(TsSlow ) ? TsUP : nz(TsSlow )
Colorh = TsFast > 55 ? color.rgb(255, 0, 0) : TsFast < 45 ? color.rgb(0, 255, 8) : #ffffff
//QQF = plot(TsFast, 'TS FAST', color=color.new(color.maroon, 100), linewidth=2, display=display.none, editable = false)
//QQS = plot(TsSlow, 'TS SLOW', color=color.new(color.white, 100), linewidth=2, display=display.none , editable = false)
//plot(TsFast, color=Colorh, linewidth=2, style=plot.style_area, histbase=50)
//BearLimit = hline(60, color=color.gray, linestyle=hline.style_dashed)
//BullLimt = hline(40, color=color.gray, linestyle=hline.style_dashed)
bulllim = 45
bearlim = 55
BullSignalr = ta.crossover(TsFast, TsSlow) and TsFast < bulllim
BearSignallr = ta.crossunder(TsFast, TsSlow) and TsFast > bearlim
/////////////////////////////////////////////////////////
// Trap Detector
////////////////////////////////////////////////////////
// Functions
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
f_top_fractal(src) => src < src and src < src and src > src and src > src
f_bot_fractal(src) => src > src and src > src and src < src and src < src
f_fractalize (src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src >= topLimit ? src : na
fractalBot = f_fractalize(src) < 0 and src <= botLimit ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
// Get components
= wavetrend(close, 5*MSTuner, 10*MSTuner)
= f_findDivs(wt2, 10, -35)
= f_findDivs(wt2, 40, -70)
wtDivBull = wtDivBull1 or wtDivBull2
wtDivBear = wtDivBear1 or wtDivBear2
plotshape(ta.crossover(wt1, wt2) and Show_PR and wt2 <= -60)
plotshape(ta.crossunder(wt1, wt2) and Show_PR and wt2 >= 60)
rsi = ta.rsi(close ,14)
// Functions
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
atr(len) =>
tr = ta.tr
atr = 0.0
atr := nz(atr + (tr - atr ) / len, tr)
supertrend(src, factor, len) =>
atr = ta.atr(len)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or close < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend
if prevSuperTrend == prevUpperBand
direction := close > upperBand ? 1 : -1
else
direction := close < lowerBand ? -1 : 1
superTrend := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
dchannel(len)=>
hh = ta.highest(len)
ll = ta.lowest (len)
trend = 0
trend := close > hh ? 1 : close < ll ? -1 : nz(trend )
trendScalper(show, len1, len2, len3, colorBull, colorBear, colorBarBull, colorBarBear) =>
avgOC = math.avg(open, close)
ha_o = 0.0, ha_o := na(ha_o ) ? avgOC : (ha_o + ohlc4 ) / 2
ema1 = ta.ema(ha_o, len1), ema2 = ta.ema(ha_o, len2), ema3 = ta.ema(ha_o, len3)
ris1 = ema1 > ema1 , ris2 = ema2 > ema2 , ris3 = ema3 > ema3
fal1 = ema1 < ema1 , fal2 = ema2 < ema2 , fal3 = ema3 < ema3
colorEma1 = ris1 ? colorBull : fal1 ? colorBear : na, colorEma2 = ris2 ? colorBull : fal2 ? colorBear : na, colorEma3 = ris3 ? colorBull : fal3 ? colorBear : na
fillEma1 = avgOC > ema1 ? colorBull : avgOC < ema1 ? colorBear : na, fillEma2 = ema1 > ema2 ? colorBull : ema1 < ema2 ? colorBear : na, fillEma3 = ema2 > ema3 ? colorBull : ema2 < ema3 ? colorBear : na
colorBar = close < ema1 and close < ema2 ? colorBarBear : colorBarBull
candlesMom() =>
= ta.macd(close, 2, 4, 3)
(macd > 10 and macd > macd ) or (macd < 10 and macd < macd )
trailingSL(buy, sell, factor, len, usePerc, perc) =>
atr = atr(len)
upperBand = high + (usePerc ? high * (perc / 100) : factor * atr)
lowerBand = low - (usePerc ? low * (perc / 100) : factor * atr)
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or buy ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or sell ? upperBand : prevUpperBand
int direction = na
float stop = na
prevSuperTrend = stop
if prevSuperTrend == prevUpperBand
direction := buy ? 1 : -1
else
direction := sell ? -1 : 1
stop := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
add_to_zz(zz, val, bi) =>
array.unshift(zz, bi)
array.unshift(zz, val)
if array.size(zz) > 12
array.pop(zz)
update_zz(zz, val, bi, dir) =>
if array.size(zz) == 0
add_to_zz(zz, val, bi)
else
if dir == 1 and val > array.get(zz, 0) or dir == -1 and val < array.get(zz, 0)
array.set(zz, 0, val)
array.set(zz, 1, bi)
0
// Get components
vosc = ta.obv - ta.ema(ta.obv, 20)
bs = ta.ema(nz(math.abs((open - close) / (high - low) * 100)), 3)
ema = ta.ema(close, 200)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep(sym, res, src) =>
bool bull = na
bull := equal_tf(res) ? src : bull
bull := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_off) : bull
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull := array.pop(bull_array)
array.clear(bull_array)
bull
//TF1Bull = securityNoRep(syminfo.tickerid, "1" , emaBull)
//TF3Bull = securityNoRep(syminfo.tickerid, "3" , emaBull)
TF5Bull = securityNoRep(syminfo.tickerid, "5" , emaBull)
//TF10Bull = securityNoRep(syminfo.tickerid, "10" , emaBull)
TF15Bull = securityNoRep(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep(syminfo.tickerid, "60" , emaBull)
//TF120Bull = securityNoRep(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep(syminfo.tickerid, "240" , emaBull)
//TF720Bull = securityNoRep(syminfo.tickerid, "720" , emaBull)
//TFDBull = securityNoRep(syminfo.tickerid, "1440", emaBull)
hma55 = ta.hma(close, 55 )
= ta.macd(close, 12, 26, 9)
supertrend = supertrend(close, sensitivity, STuner)
maintrend = dchannel(30)
confBull = (ta.crossover (close, supertrend) or (ta.crossover (close, supertrend) and maintrend < 0)) and macd > 0 and macd > macd and ema150 > ema250 and hma55 > hma55 and maintrend > 0
confBear = (ta.crossunder(close, supertrend) or (ta.crossunder(close, supertrend) and maintrend > 0)) and macd < 0 and macd < macd and ema150 < ema250 and hma55 < hma55 and maintrend < 0
trendcloud = supertrend(ohlc4, periodTrendCloud == "Swing" ? 7 : 4, 10)
hma = periodTrendCloud == "Scalping+" ? ta.hma(close, 55) : na
none = close > 0
= ta.dmi(14, 14)
consFilter = adx > 20
ContBear = TsFast > 65
ContBull = TsFast < 35
StrongFilter = ta.ema(close, 200)
//volFilter = (ta.ema(volume, 25) - ta.ema(volume, 26)) / ta.ema(volume, 26) > 0
volFilter = (ta.ema(volume, 15) - ta.ema(volume, 20)) / ta.ema(volume, 25) > 0
trendFilter = trendcloud
bull = (Presets == "All Signals" ? ta.crossover (close, supertrend) : confBull and not confBull ) and Presets != "Trend Scalper" and (StrongSignalsOnly ? close > StrongFilter : none) and (ContrarianOnly ? ContBull : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "Smooth" ? ema150 > ema250 : close > trendFilter) : none)
bear = (Presets == "All Signals" ? ta.crossunder(close, supertrend) : confBear and not confBear ) and Presets != "Trend Scalper" and (StrongSignalsOnly ? close < StrongFilter : none) and (ContrarianOnly ? ContBear : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "Smooth" ? ema150 < ema250 : close < trendFilter) : none)
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
= trendScalper(Presets == "Trend Scalper" ? true : false, 5, 9, 21, bullcolor, bearcolor, bullcolor, bearcolor)
trailingStop = trailingSL(bull, bear, 2.2, 14, usePercSL, percTrailingSL)
float _ph = ta.highestbars(high, periodSwings) == 0 ? high : na
float _pl = ta.lowestbars (low, periodSwings) == 0 ? low : na
var _dir = 0, dir_ = _pl and na(_ph) ? -1 : _dir, _dir := _ph and na(_pl) ? 1 : dir_, dirChg = ta.change(_dir)
var zz = array.new_float(0), zzOld = array.copy(zz)
float zzLive = _ph or _pl ? (dirChg ? add_to_zz(zz, _dir == 1 ? _ph : _pl, bar_index) : update_zz(zz, _dir == 1 ? _ph : _pl, bar_index, _dir)) : na
float hb_ = ta.highestbars(10) == 0 ? high : na
float lb_ = ta.lowestbars (10) == 0 ? low : na
var int dir = 0
float zz_ = na
float pp = na
var int consCnt = 0
var float condHi = na
var float condLo = na
float H_ = ta.highest(5)
float L_ = ta.lowest (5)
var line lineUp = na
var line lineDn = na
bool breakUp = false
bool breakDn = false
var float pvh1_price = array.new_float(1000, na)
var int pvh1_time = array.new_int (1000, na)
var float pvl1_price = array.new_float(1000, na)
var int pvl1_time = array.new_int (1000, na)
var float pvh2_price = array.new_float(1000, na)
var int pvh2_time = array.new_int (1000, na)
var float pvl2_price = array.new_float(1000, na)
var int pvl2_time = array.new_int (1000, na)
var float htcmrll_price = na
var int htcmrll_time = na
var float ltcmrhh_price = na
var int ltcmrhh_time = na
var box long_boxes = array.new_box()
var box short_boxes = array.new_box()
var float temp_pv_0 = na
var float temp_pv_1 = na
var float temp_pv_2 = na
bool pvh = high < high and high > high
bool pvl = low > low and low < low
int pv1_time = bar_index
float pv1_high = high
float pv1_low = low
var buyBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(buyBars, i))
var sellBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(sellBars, i))
// Colors
green = bullcolor, green50 = color.new(green, 50), green20 = color.new(green, 80)
red = bearcolor, red50 = color.new(red, 50), red20 = color.new(red, 80)
silver = #B2B5BE, silver50 = color.new(silver, 50), silver20 = color.new(silver, 80)
// Plots
atrBand = usePercSL ? (trigger ? low : high) * (percTrailingSL / 100) : ta.atr(14) * 2.2
atrStop = trigger ? low - atrBand : high + atrBand
lastTrade(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade(close)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y-lastTrade(atrStop))*multTP1 + entry_y
tp2_y = (entry_y-lastTrade(atrStop))*multTP2 + entry_y
tp3_y = (entry_y-lastTrade(atrStop))*multTP3 + entry_y
labelTpSl(cond, y, txt, color) =>
label labelTpSl = ShowTpSlAreas and cond ? label.new(bar_index + 1, y, txt, xloc.bar_index, yloc.price, color, label.style_label_left, color.white, size.normal) : na
label.delete(labelTpSl )
labelTpSl(none, entry_y, "Entry : " + str.tostring(math.round_to_mintick(entry_y)), #089981)
labelTpSl(none, stop_y , "Stop loss : " + str.tostring(math.round_to_mintick(atrStop)), bearcolor)
labelTpSl(useTP1 and multTP1 != 0, tp1_y, "TP 1 : " + str.tostring(math.round_to_mintick(tp1_y)), #089981)
labelTpSl(useTP2 and multTP2 != 0, tp2_y, "TP 2 : " + str.tostring(math.round_to_mintick(tp2_y)), #089981)
labelTpSl(useTP3 and multTP3 != 0, tp3_y, "TP 3 : " + str.tostring(math.round_to_mintick(tp3_y)), #089981)
lineTpSl(cond, y, color, style) =>
line lineTpSl = ShowTpSlAreas and cond ? line.new(bar_index - (trigger ? countBull : countBear), y, bar_index + 1, y, xloc.bar_index, extend.none, color, style) : na
line.delete(lineTpSl )
lineTpSl(none, entry_y, #089981, line.style_dashed)
lineTpSl(none, stop_y , bearcolor , line.style_solid )
lineTpSl(useTP1 and multTP1 != 0, tp1_y, bullcolor, line.style_dotted)
lineTpSl(useTP2 and multTP2 != 0, tp2_y, bullcolor, line.style_dotted)
lineTpSl(useTP3 and multTP3 != 0, tp3_y, bullcolor, line.style_dotted)
//buy = showSignals and bull ? label.new(bar_index, low , close > StrongFilter ? StrongB : SimpleBuy , xloc.bar_index, yloc.belowbar, bullcolor, label.style_label_up , color.rgb(255, 255, 255), size.normal) : na
//sell = showSignals and bear ? label.new(bar_index, high, close < StrongFilter ? StrongS : SimpleSell , xloc.bar_index, yloc.abovebar, bearcolor , label.style_label_down, color.rgb(255, 255, 255), size.normal) : na
buy = (showSignals and bull ? label.new(bar_index, low , close > StrongFilter ? StrongB : SimpleBuy , xloc.bar_index, yloc.belowbar, bullcolor, label.style_label_up , color.rgb(255, 255, 255), size.normal) : na)
sell = showSignals and bear ? label.new(bar_index, high, close < StrongFilter ? StrongS : SimpleSell , xloc.bar_index, yloc.abovebar, bearcolor , label.style_label_down, color.rgb(255, 255, 255), size.normal) : na
tpLabels(tp) =>
tp1Bull = ta.crossover (rsi, 70), tp2Bull = ta.crossover (rsi, 75), tp3Bull = ta.crossover (rsi, 80)
tp1Bull := tp1Bull and (nz(ta.barssince(tp1Bull) , 9999) > countBull), tp2Bull := tp2Bull and (ta.barssince(tp1Bull) <= countBull), tp2Bull := tp2Bull and (nz(ta.barssince(tp2Bull) , 9999) > countBull), tp3Bull := tp3Bull and (ta.barssince(tp2Bull) <= countBull), tp3Bull := tp3Bull and (nz(ta.barssince(tp3Bull) , 9999) > countBull)
tp1Bear = ta.crossunder(rsi, 30), tp2Bear = ta.crossunder(rsi, 25), tp3Bear = ta.crossunder(rsi, 20)
tp1Bear := tp1Bear and (nz(ta.barssince(tp1Bear) , 9999) > countBear), tp2Bear := tp2Bear and (ta.barssince(tp1Bear) <= countBear), tp2Bear := tp2Bear and (nz(ta.barssince(tp2Bear) , 9999) > countBear), tp3Bear := tp3Bear and (ta.barssince(tp2Bear) <= countBear), tp3Bear := tp3Bear and (nz(ta.barssince(tp3Bear) , 9999) > countBear)
if Presets != "Trend Scalper" and tpLabels
trigger ? (tp == 1 ? tp1Bull : tp == 2 ? tp2Bull : tp3Bull) : (tp == 1 ? tp1Bear : tp == 2 ? tp2Bear : tp3Bear)
plotshape(tpLabels(1), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 1", trigger ? green : na , true)
plotshape(tpLabels(2), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 2", trigger ? green : na , false)
plotshape(tpLabels(3), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 3", trigger ? green : na , false)
plotshape(tpLabels(1), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 1", trigger ? na : red, true)
plotshape(tpLabels(2), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 2", trigger ? na : red, false)
plotshape(tpLabels(3), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 3", trigger ? na : red, false)
var label zzLabel = na
if array.size(zz) > 12 and ShowSwings
if array.get(zz, 0) != array.get(zzOld, 0) or array.get(zz, 1) != array.get(zzOld, 1)
if array.get(zz, 2) == array.get(zzOld, 2) and array.get(zz, 3) == array.get(zzOld, 3)
label.delete(zzLabel)
zzLabel := label.new(math.round(array.get(zz, 1)), array.get(zz, 0), _dir == 1 ? array.get(zz, 0) > array.get(zz, 4) ? ((array.get(zz, 4) < array.get(zz, 8)) ? "High" : "HH") : "LH" : array.get(zz, 0) < array.get(zz, 4) ? ((array.get(zz, 4) > array.get(zz, 8)) ? "Low" : "LL") : "HL", xloc.bar_index, yloc.price, color.new(color.white, 100), _dir == 1 ? label.style_label_down : label.style_label_up, _dir == 1 ? bullcolor : bearcolor)
if showCons and barstate.isconfirmed
dir := hb_ and na(lb_) ? 1 : lb_ and na(hb_) ? -1 : dir
if hb_ and lb_
if dir == 1
zz_ := hb_
else
zz_ := lb_
else
zz_ := hb_ ? hb_ : lb_ ? lb_ : na
for x = 0 to 1000
if na(close) or dir != dir
break
if zz_
if na(pp)
pp := zz_
else
if dir == 1 and zz_ > pp
pp := zz_
if dir == -1 and zz_ < pp
pp := zz_
if pp != pp
if consCnt > 5
if pp > condHi
breakUp := true
if pp < condLo
breakDn := true
if consCnt > 0 and pp <= condHi and pp >= condLo
consCnt += 1
else
consCnt := 0
else
consCnt += 1
if consCnt >= 5
if consCnt == 5
condHi := H_
condLo := L_
else
line.delete(lineUp)
line.delete(lineDn)
condHi := math.max(condHi, high)
condLo := math.min(condLo, low )
lineUp := line.new(bar_index, condHi , bar_index - consCnt, condHi , color=bearcolor , style=line.style_dashed)
lineDn := line.new(bar_index, condLo , bar_index - consCnt, condLo , color=color.lime, style=line.style_dashed)
fill(plot(condHi, "", na, 1, plot.style_stepline, editable=false), plot(condLo, "", na, 1, plot.style_stepline, editable=false), paintCons and consCnt > 5 ? color.white : na, "", false)
//buy_col = color.new(#0ac20a,0)
//sell_col = color.new(#fd1605,0)
//text_col = color.new(#FFFFFF,0)
// -------- Bearish trend (blue) color selection --------
// getSellColor(count) =>
// if count == 1
// color.new(#11e7f2,0)
// else
// if count == 2
// color.new(#11d9f2,0)
// else
// if count == 3
// color.new(#11cbf2,0)
// else
// if count == 4
// color.new(#11aff2,0)
// else
// if count == 5
// color.new(#1193f2,0)
// else
// if count == 6
// color.new(#1176f2,0)
// else
// if count == 7
// color.new(#105df4,0)
// else
// if count == 8
// color.new(#1051f5,0)
// else
// if count == 9
// color.new(#0f44f5,0)
// else
// if count == 10
// color.new(#0c3de0,0)
// else
// if count == 11
// color.new(#0935ca,0)
// else
// if count == 12
// color.new(#062eb4,0)
// else
// if count == 13
// color.new(#02269e,0)
// -------- Bullish trend (blue) color selection --------
// getBuyColor(count) =>
// if count == 1
// color.new(#eef211,0)
// else
// if count == 2
// color.new(#efdc11,0)
// else
// if count == 3
// color.new(#f0c511,0)
// else
// if count == 4
// color.new(#f1af11,0)
// else
// if count == 5
// color.new(#f29811,0)
// else
// if count == 6
// color.new(#f28811,0)
// else
// if count == 7
// color.new(#f27811,0)
// else
// if count == 8
// color.new(#f26811,0)
// else
// if count == 9
// color.new(#f25811,0)
// else
// if count == 10
// color.new(#ea420d,0)
// else
// if count == 11
// color.new(#e12c09,0)
// else
// if count == 12
// color.new(#d81605,0)
// else
// if count == 13
// color.new(#cf0000,0)
// -------- Calculate bearish trend sequence --------
buySetup = 0
buySetup := close < close ? buySetup == 13 ? 1 : buySetup + 1 : 0
// -------- Calculate bullish trend sequence --------
sellSetup = 0
sellSetup := close > close ? sellSetup == 13 ? 1 : sellSetup + 1 : 0
// -------- Paint bars --------
//barColour = buySetup >= 1 ? getBuyColor(buySetup) : sellSetup >= 1 ? getSellColor(sellSetup) : na
// Candle Coloring
// Input
FastteyLength = 12
SjlowLeyLength = 26
srrrc = close
signalXLength = 9
// Data reference
= ta.macd(srrrc, FastteyLength, SjlowLeyLength, signalXLength)
// 4 level of green
greenHigh = #7bff00
greenMidHigh = #7bff00
greenMidLow = #7bff00
greenLow = #7bff00
// Yellow
yellowLow = #693d8e
// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #ff0000
// Default color
candleBody = yellowLow
// Ranging trend
if histX > 0
if histX > histX and histX > 0
candleBody := greenLow
if histX < 0
if histX < histX and histX < 0
candleBody := redLow
// Bullish trend
if MacdX > 0 and histX > 0
candleBody := greenMidLow
if histX > histX and MacdX > 0 and histX > 0
candleBody := greenMidHigh
if histX > histX and MacdX > 0 and histX > 0
candleBody := greenHigh
// Bearish trend
if MacdX < 0 and histX < 0
candleBody := redMidLow
if histX < histX and MacdX < 0 and histX < 0
candleBody := redMidHigh
if histX < histX and MacdX < 0 and histX < 0
candleBody := redHigh
barcolor(candleBody)
//barcolor(TrendMap == 'RSI Gradient' ? barColour : na, title='Bar colors (heatmap)',editable=false)
//barcolor(momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false)
//plotcandle(open, high, low, close , color = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , wickcolor = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , bordercolor = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , editable = false)
fill(plot(showTrendCloud and periodTrendCloud == "Smooth" ? ema150 : na, "", na, editable=false), plot(showTrendCloud and periodTrendCloud == "Smooth" ? ema250 : na, "", na, editable=false), ema150 > ema250 ? color.new(bullcolor, 70) : ema150 < ema250 ? color.new(bearcolor, 70) : na)
plot(ShowTrailingSL and trigger and nz(ta.barssince(low < trailingStop), bar_index) > countBull ? trailingStop : na, "", green, 1, plot.style_linebr, editable=false)
plot(ShowTrailingSL and not trigger and nz(ta.barssince(high > trailingStop), bar_index) > countBear ? trailingStop : na, "", red , 1, plot.style_linebr, editable=false)
p0 = plot(avgOC, "", na , editable=false)
p1 = plot(ema5 , "", colorEma5 , editable=false)
p2 = plot(ema9 , "", colorEma9 , editable=false)
p3 = plot(ema21, "", colorEma21, editable=false)
plot(LongTrendAverage ? ta.ema(close, 250) : na, 'Trend Tracer', linewidth=2, color=close > ta.ema(close, 250) ? color.new(bullcolor, 45) : color.new(bearcolor, 45))
fill(p0, p1, fillEma5 )
fill(p1, p2, fillEma9 )
fill(p2, p3, fillEma21)
fill(plot(showTrendCloud and periodTrendCloud != "Smooth" and periodTrendCloud != "Scalping+" and trendcloud != 0 and close > trendcloud ? trendcloud : na, "", bullcolor, 1, plot.style_linebr, editable=false), p0, color.new(bullcolor, 90))
fill(plot(showTrendCloud and periodTrendCloud != "Smooth" and periodTrendCloud != "Scalping+" and trendcloud != 0 and close < trendcloud ? trendcloud : na, "", bearcolor , 1, plot.style_linebr, editable=false), p0, color.new(bearcolor , 90))
//fill(plot(hma, "", hma > hma ? green : hma < hma ? red : na, editable=false), plot(hma , "", hma > hma ? green : hma < hma ? red : na, editable=false), hma > hma ? green : hma < hma ? red : na)
////////////////////////////////////////////////////////////////////////////////////////////////
// Get user input
indicatorTF = "Chart"
// Functions
sqz(bbLen, bbMult, kcLen, kcMult, source) =>
upperBB = ta.sma(source, bbLen) + ta.stdev(source, bbLen) * bbMult
lowerBB = ta.sma(source, bbLen) - ta.stdev(source, bbLen) * bbMult
upperKC = ta.sma(source, kcLen) + ta.sma(ta.tr, kcLen) * kcMult
lowerKC = ta.sma(source, kcLen) - ta.sma(ta.tr, kcLen) * kcMult
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
qqe(rsiLen, rsiSmooth, factor, source, bbLen, bbMult) =>
rsiMa = ta.ema(ta.rsi(source, rsiLen), rsiSmooth)
delta = ta.ema(ta.ema(math.abs(ta.mom(rsiMa, 1)), rsiLen * 2 - 1), rsiLen * 2 - 1) * factor
longBand = 0.0, longBand := rsiMa > longBand and rsiMa > longBand ? math.max(longBand , rsiMa - delta) : rsiMa - delta
shortBand = 0.0, shortBand := rsiMa < shortBand and rsiMa < shortBand ? math.min(shortBand , rsiMa + delta) : rsiMa + delta
cross1 = ta.cross(rsiMa, shortBand )
cross2 = ta.cross(rsiMa, longBand )
trend = 0.0, trend := cross1 ? 1 : cross2 ? -1 : nz(trend , 1)
fastDelta = trend == 1 ? longBand : shortBand
_hist = rsiMa - 50
_line = fastDelta - 50
= ta.bb(_line, bbLen, bbMult)
// Get components
cond(_offset) =>
top = ta.highest(high, 10)
bot = ta.lowest(low, 10)
osc = ta.ema(hlc3, 5) - ta.ema(ohlc4, 20)
oscRis = osc > osc
oscFal = osc < osc
oscA0 = osc > 0
oscB0 = osc < 0
oscTop = oscFal and oscRis
oscBot = oscRis and oscFal
bullR = oscB0 and oscBot and ((osc > ta.valuewhen(oscB0 and oscBot, osc, 1) and bot < ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearR = oscA0 and oscTop and ((osc < ta.valuewhen(oscA0 and oscTop, osc, 1) and top > ta.valuewhen(oscA0 and oscTop, top, 1)))
bullH = oscB0 and oscBot and ((osc < ta.valuewhen(oscB0 and oscBot, osc, 1) and bot > ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearH = oscA0 and oscTop and ((osc > ta.valuewhen(oscA0 and oscTop, osc, 1) and top < ta.valuewhen(oscA0 and oscTop, top, 1)))
= sqz(20, 2, 20, 2, close)
= qqe(6, 6, 3, close, 50, 0.001)
= qqe(6, 5, 1.618, close, 50, 1)
= ta.dmi(14, 14)
[osc , oscRis , oscFal , oscA0 , oscB0 , oscTop , oscBot , bullR , bearR , bullH , bearH , sqzOn , sqzOff , _hist1 , upper1 , lower1 , _hist2 , _line2 , tvr ]
tf = indicatorTF == "Chart" ? timeframe.period : indicatorTF == "1 minute" ? "1" : indicatorTF == "3 minutes" ? "3" : indicatorTF == "5 minutes" ? "5" : indicatorTF == "10 minutes" ? "10" : indicatorTF == "15 minutes" ? "15" : indicatorTF == "30 minutes" ? "30" : indicatorTF == "45 minutes" ? "45" : indicatorTF == "1 hour" ? "60" : indicatorTF == "2 hours" ? "120" : indicatorTF == "3 hours" ? "180" : indicatorTF == "4 hours" ? "240" : indicatorTF == "12 hours" ? "720" : indicatorTF == "1 day" ? "1D" : indicatorTF == "1 week" ? "1W" : indicatorTF == "1 month" ? "1M" : na
= request.security(syminfo.tickerid, tf, cond(indicatorTF != "Chart" and barstate.isrealtime ? 1 : 0))
//colorTVR = tvr < 15 ? #F6525F : tvr > 15 and tvr < 25 ? #B2B5BE : #66BB6A
// Plots
//plot(Presets == "Money Moves TrendVR" ? tvr : na, "", colorTVR, editable=false)
TrendText = "Trending"
if tvr < 15 and tvr < 25
TrendText := "No trend"
if tvr > 15 and tvr < 25
TrendText := "Ranging"
//------------------------------------------------------------------------------------------------------- Volatitiry
//Calculates Volatility for Dashboard
atrr = 3 * ta.atr(10)
stdAtr = 2 * ta.stdev(atrr, 20)
smaAtr = ta.sma(atrr, 20)
topAtrDev = smaAtr + stdAtr
bottomAtrDev = smaAtr - stdAtr
calcDev = (atrr - bottomAtrDev) / (topAtrDev - bottomAtrDev)
percentVol = 40 * calcDev + 30
AvrLength = 21
PercentFilter = 144
xAavrVolume = ta.rma(volume, AvrLength)
nResLess = volume * 100 / xAavrVolume < PercentFilter ? 0 : volume
nRes = nResLess
clr = close < open ? #b2b5be : #00dbff
//plot(nRes, color=clr, style=plot.style_columns, title='Volume Filter', transp=20)
VolitiText = "Inactive"
if nRes
VolitiText := "Active"
//////////////////////////////////////////
ema69 = ta.ema(close, 9)
totalSentTxt = ema69 > ema69 ? 'Bullish' : ema69 < ema69 ? 'Bearish' : 'Flat'
// INputs
//Timezones
tz_incr = 0
use_exchange = false
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//Session A
NYSes = true
NYTxt = 'New York'
NYTime = '1300-2200'
//Session B
LDSes = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
//Session C
show_sesc = true
sesc_txt = 'Tokyo'
sesc_ses = '0000-0900'
//Session D
show_sesd = true
sesd_txt = 'Sydney'
sesd_ses = '2100-0600'
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tff = timeframe.period
var tz = use_exchange ? syminfo.timezone :
str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))
is_sesa = math.sign(nz(time(tff, NYTime, tz)))
is_sesb = math.sign(nz(time(tff, sesb_ses, tz)))
is_sesc = math.sign(nz(time(tff, sesc_ses, tz)))
is_sesd = math.sign(nz(time(tff, sesd_ses, tz)))
////////////////////////////////////////////
SessionText = "Default"
if is_sesd
SessionText := sesd_txt
if is_sesc
SessionText := sesc_txt
if is_sesb
SessionText := sesb_txt
if is_sesa
SessionText := NYTxt
if is_sesd and is_sesc
SessionText := "Sydney/Tokyo"
if is_sesb and is_sesc
SessionText := "Tokyo/London"
if is_sesb and is_sesa
SessionText := "London/Newyork"
if is_sesa and is_sesd
SessionText := "Newyork/Sydney"
//-----------------------------------------------------------------------------}
//Overlays color.green : color.red
//
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 3, 7, color.rgb(0, 0, 0, 60), #3d384300, 2, color.rgb(30, 34, 45 , 60), 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column, row, txt, 0, 0, signal ? #000000 : color.white, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
if barstate.islast and showDashboard
// MTF Trend
dashboard_cell(0, 0 , "MTF")
dashboard_cell(0, 2 , "M5") , dashboard_cell_bg(0, 2 , TF5Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 3 , "M15") , dashboard_cell_bg(0, 3 , TF15Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 4 , "M30") , dashboard_cell_bg(0, 4 , TF30Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 5 , "1H") , dashboard_cell_bg(0, 5 , TF60Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 6 , "4H") , dashboard_cell_bg(0, 6 , TF240Bull ? color.rgb(70, 153, 67) : #880000)
// Middel part
dashboard_cell(1, 0 , "PoseidonPips")
dashboard_cell(1, 2 , "Market State")
dashboard_cell(1, 3 , "Volatility")
dashboard_cell(1, 4 , "Institutional Activity")
dashboard_cell(1, 5 , "Current Session (UTC)")
dashboard_cell(1, 6 , "Trend Pressure")
// End part
dashboard_cell(2, 0 , "")
dashboard_cell(2, 2 , TrendText)
dashboard_cell(2, 3 , str.tostring(percentVol, '##.##') + '%')
dashboard_cell(2, 4 , VolitiText)
dashboard_cell(2, 5 , SessionText)
dashboard_cell(2, 6 , totalSentTxt)
// Alerts
// Cross Functions for SL and TP
f_sl_crossed() =>
ret = false
crossBull = low >= ta.lowest(low, 5) and low < ta.lowest(low, 5)
crossBear = high <= ta.highest(high, 5) and high > ta.highest(high, 5)
ret := trigger ? crossBull : crossBear
ret
f_tp_crossed(tp) =>
ret = false
crossBull = high <= tp and high > tp
crossBear = low >= tp and low < tp
ret := trigger ? crossBull : crossBear
ret
// Alert Conditions
alert04 = bull and close <= StrongFilter
alert07 = bull and close > StrongFilter
alert09 = f_sl_crossed()
alert11 = f_tp_crossed(60.0)
alert12 = f_tp_crossed(80.0)
alert13 = f_tp_crossed(100.0)
alert14 = periodTrendCloud == "Smooth" ? ta.crossunder(ema150, ema250) : (close < trendcloud) and (close > trendcloud )
alert15 = periodTrendCloud == "Smooth" ? ta.crossover(ema150, ema250) : (close > trendcloud) and (close < trendcloud )
// Signal Alerts
if alert04 and Normalbuy_alert
alert('Buy Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert07 and Strongbuy_alert
alert('Strong Buy Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if (bear and close >= StrongFilter) and Normalsell_alert
alert('Sell Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if (bear and close < StrongFilter) and Strongsell_alert
alert('Strong Sell Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Risk Management Alerts
if alert09 and slalert
alert('SL Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert11 and tp1alert
alert('Target 1 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert12 and tp2alert
alert('Target 2 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert13 and tp3alert
alert('Target 3 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Cloud Alerts
if alert15 and bullcrosscloud_alert
alert('Cloud Turned Bullish !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert14 and bearcrosscloud_alert
alert('Cloud Turned Bearish !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Alert Conditions for TradingView
alertcondition(alert04, "Normal Buy Alert", "Normal Buy Signal")
alertcondition(alert07, "Strong Buy Alert", "Strong Buy Signal")
alertcondition((bear and close >= StrongFilter), "Normal Sell Alert", "Normal Sell Signal")
alertcondition((bear and close < StrongFilter), "Strong Sell Alert", "Strong Sell Signal")
alertcondition(alert09, "SL Crossed Alert", "Stop Loss Crossed")
alertcondition(alert11, "TP1 Crossed Alert", "Target 1 Crossed")
alertcondition(alert12, "TP2 Crossed Alert", "Target 2 Crossed")
alertcondition(alert13, "TP3 Crossed Alert", "Target 3 Crossed")
// Input
fastLength = 12
slowLength = 26
srcceed = close
signalLength = 9
// Data reference
= ta.macd(srcceed, fastLength, slowLength, signalLength)
// 4 level of green
greenHighh = #7bff00
greenMidHighh = #7bff00
greenMidLowh = #7bff00
greenLowh = #7bff00
// Yellow
yellowLowh = #693d8e
// 4 level of red
redHighh = #ff0000
redMidHighh = #ff0000
redMidLowh = #ff0000
redLowh = #ff0000
// Default color
candleBodyd = yellowLowh
// Ranging trend
if hist > 0
if hist > hist and hist > 0
candleBodyd := greenLowh
if hist < 0
if hist < hist and hist < 0
candleBodyd := redLowh
// Bullish trend
if macdda > 0 and hist > 0
candleBodyd := greenMidLowh
if hist > hist and macd > 0 and hist > 0
candleBodyd := greenMidHighh
if hist > hist and macd > 0 and hist > 0
candleBodyd := greenHighh
// Bearish trend
if macdda < 0 and hist < 0
candleBodyd := redMidLowh
if hist < hist and macd < 0 and hist < 0
candleBodyd := redMidHighh
if hist < hist and macd < 0 and hist < 0
candleBodyd := redHighh
barcolor(candleBodyd) // Include suggestion by Shaheen204
//
tenkan_len = 365
tenkan_mult = 3
kijun_len = 365
kijun_mult = 7
spanB_len = 365
spanB_mult = 10
offset = 1
//------------------------------------------------------------------------------
avg(src,length,mult)=>
atr = ta.atr(50)*mult
up = hl2 + atr
dn = hl2 - atr
upper = 0.,lower = 0.
upper := src < upper ? math.min(up,upper ) : up
lower := src > lower ? math.max(dn,lower ) : dn
os = 0,max = 0.,min = 0.
os := src > upper ? 1 : src < lower ? 0 : os
spt = os == 1 ? lower : upper
max := ta.cross(src,spt) ? math.max(src,max ) : os == 1 ? math.max(src,max ) : spt
min := ta.cross(src,spt) ? math.min(src,min ) : os == 0 ? math.min(src,min ) : spt
math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Smart Money Concept
settings = "Settings"
zigzag_len = input.int(9, "ZigZag Length", group=settings)
show_zigzag = input.bool(false, "Show Zigzag", group=settings)
fib_factor = input.float(0.33, "Fib Factor for breakout confirmation", 0, 1, 0.01, group=settings)
text_size = input.string(size.tiny, "Text Size", , group=settings)
delete_boxes = input.bool(true, "Delete Old/Broken Boxes", group=settings)
bu_ob_inline_color = "Bu-OB Colors"
be_ob_inline_color = "Be-OB Colors"
bu_bb_inline_color = "Bu-BB Colors"
be_bb_inline_color = "Be-BB Colors"
bu_ob_display_settings = "Bu-OB Display Settings"
bu_ob_color = input.color(color.new(color.green, 70), "Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_border_color = input.color(color.green, "Border Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_text_color = input.color(color.green, "Text Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
be_ob_display_settings = "Be-OB Display Settings"
be_ob_color = input.color(color.new(color.red, 70), "Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_border_color = input.color(color.red, "Border Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_text_color = input.color(color.red, "Text Color", group=be_ob_display_settings, inline=be_ob_inline_color)
bu_bb_display_settings = "Bu-BB & Bu-MB Display Settings"
bu_bb_color = input.color(color.new(color.green, 70), "Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_border_color = input.color(color.green, "Border Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_text_color = input.color(color.green, "Text Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
be_bb_display_settings = "Be-BB & Be-MB Display Settings"
be_bb_color = input.color(color.new(color.red, 70), "Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_border_color = input.color(color.red, "Border Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_text_color = input.color(color.red, "Text Color", group=be_bb_display_settings, inline=be_bb_inline_color)
var float high_points_arr = array.new_float(5)
var int high_index_arr = array.new_int(5)
var float low_points_arr = array.new_float(5)
var int low_index_arr = array.new_int(5)
var box bu_ob_boxes = array.new_box(5)
var box be_ob_boxes = array.new_box(5)
var box bu_bb_boxes = array.new_box(5)
var box be_bb_boxes = array.new_box(5)
to_up = high >= ta.highest(zigzag_len)
to_down = low <= ta.lowest(zigzag_len)
trend = 1
trend := nz(trend , 1)
trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend
last_trend_up_since = ta.barssince(to_up )
low_val = ta.lowest(nz(last_trend_up_since > 0 ? last_trend_up_since : 1, 1))
low_index = bar_index - ta.barssince(low_val == low)
last_trend_down_since = ta.barssince(to_down )
high_val = ta.highest(nz(last_trend_down_since > 0 ? last_trend_down_since : 1, 1))
high_index = bar_index - ta.barssince(high_val == high)
if ta.change(trend) != 0
if trend == 1
array.push(low_points_arr, low_val)
array.push(low_index_arr, low_index)
if trend == -1
array.push(high_points_arr, high_val)
array.push(high_index_arr, high_index)
f_get_high(ind) =>
f_get_low(ind) =>
f_delete_box(box_arr) =>
if delete_boxes
box.delete(array.shift(box_arr))
else
array.shift(box_arr)
0
= f_get_high(0)
= f_get_high(1)
= f_get_low(0)
= f_get_low(1)
if ta.change(trend) != 0 and show_zigzag
if trend == 1
line.new(h0i, h0, l0i, l0)
if trend == -1
line.new(l0i, l0, h0i, h0)
market = 1
market := nz(market , 1)
// market := market == 1 and close < l0 and low < l0 - math.abs(h0 - l0) * fib_factor ? -1 : market == -1 and close > h0 and high > h0 + math.abs(h0 - l0) * fib_factor ? 1 : market
last_l0 = ta.valuewhen(ta.change(market) != 0, l0, 0)
last_h0 = ta.valuewhen(ta.change(market) != 0, h0, 0)
market := last_l0 == l0 or last_h0 == h0 ? market : market == 1 and l0 < l1 and l0 < l1 - math.abs(h0 - l1) * fib_factor ? -1 : market == -1 and h0 > h1 and h0 > h1 + math.abs(h1 - l0) * fib_factor ? 1 : market
bu_ob_index = bar_index
bu_ob_index := nz(bu_ob_index , bar_index)
for i=h1i to l0i
index = bar_index - i
if open > close
bu_ob_index := bar_index
bu_ob_since = bar_index - bu_ob_index
be_ob_index = bar_index
be_ob_index := nz(be_ob_index , bar_index)
for i=l1i to h0i
index = bar_index - i
if open < close
be_ob_index := bar_index
be_ob_since = bar_index - be_ob_index
be_bb_index = bar_index
be_bb_index := nz(be_bb_index , bar_index)
for i=h1i - zigzag_len to l1i
index = bar_index - i
if open > close
be_bb_index := bar_index
be_bb_since = bar_index - be_bb_index
bu_bb_index = bar_index
bu_bb_index := nz(bu_bb_index , bar_index)
for i=l1i - zigzag_len to h1i
index = bar_index - i
if open < close
bu_bb_index := bar_index
bu_bb_since = bar_index - bu_bb_index
if ta.change(market) != 0
if market == 1
line.new(h1i, h1, h0i, h1, color=color.green, width=1)
label.new(int(math.avg(h1i, l0i)), h1, "BoS", color=color.new(color.black, 100), style=label.style_label_down, textcolor=color.green, size=size.small)
bu_ob = box.new(bu_ob_index, high , bar_index + 10, low , bgcolor=bu_ob_color, border_color=bu_ob_border_color, text="Bu-OB", text_color=bu_ob_text_color, text_halign=text.align_right, text_size=text_size)
bu_bb = box.new(bu_bb_index, high , bar_index + 10, low , bgcolor=bu_bb_color, border_color=bu_bb_border_color, text=l0 < l1 ? "Bu-BB" : "Bu-MB", text_color=bu_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(bu_ob_boxes, bu_ob)
array.push(bu_bb_boxes, bu_bb)
if market == -1
line.new(l1i, l1, l0i, l1, color=color.red, width=1)
label.new(int(math.avg(l1i, h0i)), l1, "BoS", color=color.new(color.black, 100), style=label.style_label_up, textcolor=color.red, size=size.small)
be_ob = box.new(be_ob_index, high , bar_index + 10, low , bgcolor=be_ob_color, border_color=be_ob_border_color, text="Be-OB", text_color=be_ob_text_color, text_halign=text.align_right, text_size=text_size)
be_bb = box.new(be_bb_index, high , bar_index + 10, low , bgcolor=be_bb_color, border_color=be_bb_border_color, text=h0 > h1 ? "Be-BB" : "Be-MB", text_color=be_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(be_ob_boxes, be_ob)
array.push(be_bb_boxes, be_bb)
for bull_ob in bu_ob_boxes
bottom = box.get_bottom(bull_ob)
top = box.get_top(bull_ob)
if close < bottom
f_delete_box(bu_ob_boxes)
else if close < top
alert("Price in the BU-OB zone")
else
box.set_right(bull_ob, bar_index + 10)
for bear_ob in be_ob_boxes
top = box.get_top(bear_ob)
bottom = box.get_bottom((bear_ob))
if close > top
f_delete_box(be_ob_boxes)
if close > bottom
alert("Price in the BE-OB zone")
else
box.set_right(bear_ob, bar_index + 10)
for bear_bb in be_bb_boxes
top = box.get_top(bear_bb)
bottom = box.get_bottom(bear_bb)
if close > top
f_delete_box(be_bb_boxes)
else if close > bottom
alert("Price in the BE-BB zone")
else
box.set_right(bear_bb, bar_index + 10)
for bull_bb in bu_bb_boxes
bottom = box.get_bottom(bull_bb)
top = box.get_top(bull_bb)
if close < bottom
f_delete_box(bu_bb_boxes)
else if close < top
alert("Price in the BU-BB zone")
else
box.set_right(bull_bb, bar_index + 10)
alertcondition(ta.change(market) != 0, "MSB", "MSB")
enableAutoTrend = input(true, "Enable Auto Trendlines", group="AUTO TRENDLINES SETTINGS")
srcTrendChannel = input(close, "Trend channel source", group="AUTO TRENDLINES SETTINGS")
lenTrendChannel = input.int(50, "Trend channel loopback", 2, group="AUTO TRENDLINES SETTINGS")
a = ta.wma(srcTrendChannel, lenTrendChannel), b = ta.sma(srcTrendChannel, lenTrendChannel)
A = 4 * b - 3 * a, B = 3 * a - 2 * b
m = (A - B) / (lenTrendChannel - 1)
d = 0., for i = 0 to lenTrendChannel - 1 by 1
l = B + m * i
d += math.pow(srcTrendChannel - l, 2)
rmse = math.sqrt(d / (lenTrendChannel - 1)) * 2
l(css, k) =>
line lr = enableAutoTrend ? line.new(bar_index - lenTrendChannel + 1, A + k, bar_index, B + k, extend=extend.right, color=css) : na
line.delete(lr )
l(#808080, rmse), l(#808080, 0), l(#808080,-rmse)
// ==========================================================================================
// === Dashboard with Telegram Link ===
var table myTable = table.new(position.top_center, 1, 1, border_width=1, frame_color=color.black, bgcolor=color.white)
// Add Telegram Message to Dashboard
table.cell(myTable, 0, 0, "Join Telegram @KING OF BTC VIP", bgcolor=color.blue, text_color=color.white, text_size=size.normal)
Indicadores e estratégias
Algo Reverse This indicator is a robust trend-following strategy designed to filter out market noise and "falling knife" scenarios. It combines Heikin Ashi reversal signals with a strict Smoothed EMA Slope Filter and a Candle Body Size Filter to ensure high-quality entries.
Unlike standard strategies that simply check if the price is above/below the EMA, this script verifies the actual angle/slope of the EMA to ensure the trend has genuinely shifted direction.
Key Features:
🛡️ Smoothed EMA Slope Filter:
Most indicators trigger a BUY the moment price crosses the EMA, leading to losses during fakeouts.
This script checks the EMA value against its value X bars ago (Setting: Slope Lookback).
Benefit: Signals are generated only when the EMA line itself is physically rising (Green) for Longs or falling (Red) for Shorts. This prevents entering too early on a sharp reversal.
🕯️ Candle Body Filter:
Filters out low-quality candles (Dojis, Spinning Tops) with long wicks.
Logic: A signal is valid only if the candle body constitutes at least 70% (default) of the total candle range.
Benefit: Ensures entries are made on strong momentum candles, not on market indecision.
🔹 Heikin Ashi + ATR Impulse:
Uses Heikin Ashi logic to detect smooth trend reversals.
Validates the move with an ATR multiplier to ensure sufficient volatility.
Settings Guide:
Confirmation Bars: 1 (Recommended). Waits for the candle to close to confirm the signal.
EMA Slope Lookback: 5 (Default). Compares current EMA to EMA 5 bars ago. Increase for more stability, decrease for faster (but riskier) signals.
Min Candle Body: 0.7 (70%). Lower to 0.5 for more signals, raise to 0.8 for stricter filtering.
Этот индикатор представляет собой надежную трендовую стратегию, разработанную для фильтрации рыночного шума и предотвращения входов против сильного тренда («ловли ножей»). Он объединяет разворотные сигналы Heikin Ashi со строгим Фильтром Сглаженного Наклона EMA и Фильтром Размера Тела Свечи.
В отличие от стандартных стратегий, которые просто смотрят положение цены относительно EMA, этот скрипт проверяет реальный угол наклона линии, гарантируя, что тренд действительно развернулся.
Ключевые особенности:
🛡️ Сглаженный Фильтр Наклона EMA (Smoothed Slope):
Обычные индикаторы часто дают ложный BUY при резком пробое EMA, когда тренд все еще смотрит вниз.
Этот скрипт сравнивает текущую EMA с её значением X баров назад (Настройка: Сглаживание наклона).
Польза: Сигнал появляется только тогда, когда сама линия EMA окрашивается в Зеленый (растет) или Красный (падает). Это защищает от ложных пробоев.
🕯️ Фильтр Тела Свечи (Body Filter):
Отсеивает «мусорные» свечи (Доджи, Волчки) с длинными тенями и маленьким телом.
Логика: Сигнал валиден, только если тело свечи занимает минимум 70% (по умолчанию) от всей длины свечи.
Польза: Входы совершаются только на сильных, полнотелых свечах, подтверждающих намерение рынка.
🔹 Heikin Ashi + ATR Импульс:
Использует логику Heikin Ashi для определения плавного разворота.
Подтверждает вход множителем ATR, чтобы исключить входы на низкой волатильности.
Настройки:
Подтверждение входа: 1 (Рекомендуется). Ждет закрытия свечи для фиксации сигнала.
Сглаживание наклона (Lookback): 5. Сравнивает EMA с EMA 5 свечей назад. Увеличьте для надежности, уменьшите для более быстрой реакции.
Мин. тело свечи: 0.7 (70%). Уменьшите до 0.5 для большего количества сигналов, увеличьте до 0.8 для строгого отбора.
RA Renko Wave ParticipationOverview
RA Renko Wave Participation measures market participation per completed Renko wave, using a Weis-style wave construction adapted for synthetic Renko logic.
The indicator focuses on effort, not direction, and is designed to evaluate initiative versus corrective behavior during price movement.
This tool does not generate buy/sell signals.
It provides context for trade decisions derived from price structure, Renko transitions, and higher-level confluence.
Core Concept
Markets move through alternating phases of:
Initiative activity (strong participation driving price)
Corrective activity (low participation rotations)
This indicator answers one question:
How much participation was required to produce the current Renko wave compared to recent history?
How It Works
Synthetic Renko Waves
Renko state is reconstructed internally using:
Traditional brick size or
ATR-based adaptive brick size
Reversal requires a configurable number of bricks
Wave Participation Accumulation
Volume (or True Range if volume unavailable) is accumulated per wave
Accumulation resets only when a Renko wave flips
Bidirectional Histogram
Up waves: plotted above zero
Down waves: plotted below zero
Zero line represents neutral participation
Wave Participation Average (WPA)
Calculated from completed waves only
Uses absolute wave size
Represents expected participation for a typical wave
Displayed on the active side of zero for visual alignment
(magnitude is real; placement is contextual)
Participation Strength
Ratio of current wave effort to average wave effort
Values > 1.0 indicate above-normal participation
Values < 1.0 indicate corrective or weak participation
How to Read the Indicator
Histogram
Expanding bars → increasing participation
Contracting bars → diminishing participation
Sustained expansion → initiative behavior
Shallow waves → rotation or absorption
Wave Participation Average
Acts as a baseline, not a signal
Used for comparison only
Large waves relative to the average often precede:
Trend continuation
Exhaustion
Regime shifts
Strength Line
Confirms whether effort is meaningful or anemic
Useful for:
Pullback validation
Failed continuation detection
Late-trend exhaustion awareness
What This Indicator Is NOT
Not a momentum oscillator
Not a MACD variant
Not a volume delta tool
Not an entry/exit generator
Direction must always come from price structure, Renko transitions, and contextual confluence.
Best Use Cases
Evaluating pullback quality
Identifying initiative vs corrective waves
Confirming trend health
Detecting participation divergence
Filtering low-quality continuation attempts
Works best when combined with:
Renko price structure
Session context
Higher-timeframe bias
Support/resistance or value zones
Reset Behavior
Optional reset modes:
None (continuous session)
New trading day
Custom session window (timezone aware)
Resets affect wave accumulation only, not Renko structure.
Design Philosophy
This indicator is intentionally:
Non-repainting
Flip-confirmed
Structure-aligned
Effort-focused
It prioritizes interpretability and discipline over signal density.
Internal Disclaimer
This indicator provides analytical context only.
Trading decisions remain the responsibility of the user.
Past participation patterns do not guarantee future behavior.
4H Synced Direction Divergence Alert US100 US500 US30Overview
This script monitors three index symbols on a 4-hour (4H) basis and triggers an alert only when their last completed 4H candles are time-synchronized and their directions diverge (i.e., not all close in the same direction).
What it does
Compares the 4H candle direction (UP / DOWN / FLAT) across:
US100 (reference clock)
US500
US30
Sends an alert on the confirmed close of the 4H candle (not mid-candle).
Includes a detailed alert message showing:
the 4H close time
direction for each symbol
open, close, and the close-open delta
How it works (high level)
Reference clock (sync anchor):
The script uses Symbol 1 as the timing reference for 4H candle boundaries.
Strict bar synchronization:
It validates that all three symbols share the same 4H time_close before comparing directions.
If any symbol is missing that specific 4H bar (gap) or doesn’t align to the same close timestamp, no alert is triggered.
No repaint / no lookahead:
Data is requested without looking ahead, so the comparison is based on completed candles only.
Duplicate protection:
The script remembers the last fired 4H close time and prevents repeated alerts caused by recalculation.
How to use
Add the script to a clean chart.
Set your preferred symbols in the inputs (default: US100 / US500 / US30).
Create an alert:
Condition: select this script
Choose “Any alert() function call” (required, because the script uses alert() for detailed messages)
When a synchronized 4H close occurs and directions diverge, you will receive a detailed notification.
Inputs
Comparison TF: default 240 (4H)
Symbol 1 (Reference clock): default CAPITALCOM:US100
Symbol 2: default CAPITALCOM:US500
Symbol 3: default CAPITALCOM:US30
Timezone for alert message: controls only the displayed timestamp in the alert text
Notes / limitations
This script is designed for cross-symbol candle comparison, so alignment matters. If your symbols have different trading sessions, gaps, or data availability, the script may intentionally skip alerts when candles are not perfectly synchronized.
The script is an informational alert tool and is not a trading signal by itself. Always confirm context, liquidity, and market conditions.
A.I. Market Cipher Z [RubiXalgo]A.I. 👑 Market Cipher Z
"Rubik's Algo" – Where Ichimoku mathematics meets Rubik's Cube solving speed under machine-learning color control.
Imagine a speed-cuber solving a Rubik's Cube while juggling — fast, precise, seemingly chaotic yet perfectly aligned layers.
This indicator visualizes that same layered, adaptive intelligence in markets:
Core Visual Metaphor
• Fast Rubik → short-term VSQC Kalman matrix (dynamic 9–21 lookback)
• Slow Rubik → long-horizon dynamic matrix (≈188 base length)
• Sharkwave → higher-timeframe TTM Squeeze + wave-momentum cipher
• Color language → machine-learned gradients (k-NN + Kalman + LOWESS)
Main elements on chart
• Dynamic fast + slow trend lines with gradient fill (bull/bear strength)
• Multi-layer Sharkwave plot (WaveCrest, DeepOcean, Undertow currents)
• Volume Recovery Zones (green/red imbalance rectangles – optional)
• Wick-pressure Bounce Boxes (extreme OB/OS zones – optional)
• GannB-inspired Vxt3 sonar dots (volume-confirmed turning points)
• Two momentum power tables:
❖ Kalman Trend Filter % → overall trend strength
◆ Stochastic Money Flow % → momentum / OB-OS heat
Key Trading Intuition
Green table(s) + green dot + price near fast line = high-probability reversal / continuation long
Red table(s) + red dot + price near slow line = high-probability reversal / continuation short
Bright/dark gradients = conviction | yellow/neutral = wait or fade
Settings highlights
VSQC Dynamic Scaling Lookback 18 ← heartbeat speed (9–21 sweet spot)
Dynamic Maximum Length 188 ← memory horizon
A.I. Money Flow Momentum Window 18 ← core rhythm
Prediction neighbours (k) 63 ← pattern memory depth
Sharkwave timeframe 60 ← usually 4×–24× chart tf
Not financial advice. Trading involves substantial risk of loss.
Use only as one piece of your decision process. Past performance ≠ future results.
© Jesse_Geluk 2025 • Mozilla Public License 2.0
Educational / non-commercial reuse encouraged under CC BY-NC-SA 4.0
Current Fractal High/Low (Dynamic) v2.3# 📝 Current Fractal High/Low (Dynamic) v2.3 – Changelog
## ➕ Additions
- ✅ New option: **Enable Historical Fractals** – Displays past FH/FL levels using dashed lines.
- ✅ **Breakout Alert Conditions**: Alerts added for breakout of the most recent Fractal High and Low.
- ✅ **Inline Labels**: FH/FL labels now appear directly on the fractal lines.
- ✅ **Single Alert Toggle**: Option to trigger alerts only once per breakout.
- ✅ Codebase prepared for future features (e.g. fractal tagging, count limits).
## 🔧 Improvements
- 🔄 Fractal levels now update **only after a valid breakout**, not just when a new pivot is formed.
- 🧱 Improved variable scope handling (no redeclaration issues).
- 📦 Ready for migration to **Pine Script v6**.
## 🛠 Known Limitations / To-Do
- 🔹 No current option to limit historical fractals (e.g. show last 5 only).
- 🔹 FH/FL labels currently use text ("FH"/"FL") — numerical values may be added in a future update.
---
📌 Free to use with attribution. Developed by: (www.stairwaytoprofit.com)
Levels by @crypto.erkeI often use key levels to spot support/resistance zones, especially from higher timeframes like the previous month or week. I built this indicator to automatically plot the previous period's central level along with customizable bands (using std dev or percentage offsets) as horizontal lines on your chart. It helps visualize confluence areas for entries, stops, or targets without manual calculations.
Key Features:
Period Selection: Choose "Month" or "Week" to base levels on the previous full period's data.
Central Level Calculation: Uses HLC3 source by default (customizable), resetting at the start of each new period.
Bands Modes:
Standard Deviation: Bands at ±1σ, ±2σ, ±3σ (multipliers adjustable).
Percentage: Bands as % offsets from the central level.
Toggleable Bands: Show/hide each band pair (±1, ±2, ±3) individually.
Style Customization: Line widths, colors (e.g., blue for the central line, green/olive/teal for bands), and styles (solid, dotted, dashed).
Persistent Lines: Draws lines for the previous period's levels, extending them across the chart as new bars form. Limits to 500 lines for performance.
Real-Time Friendly: Works on any timeframe; ideal for intraday charts to overlay higher-period levels.
Why This Indicator?
Simplifies Analysis: Get instant access to previous month/week levels without switching charts or using multiple indicators.
Versatile for Strategies: Great for mean-reversion trades (bouncing off bands), breakouts (above/below the central line), or confirming trends. I use it daily in crypto for quick scalp setups.
Clean & Efficient: No fills or clutter—just clean lines that update dynamically. Switch to dotted/dashed for less visual noise.
Wick Fear ProjectionThis indicator focuses on trend quality, not just direction.
It combines HAP ARS momentum, wick-based EMA pressure, and a forward projection to reveal whether price movement is supported or blocked by market stress.
🔹 Core Logic
HAP ARS measures directional momentum based on candle body behavior, filtering indecision.
Wick EMA is calculated from upper and lower wicks and smoothed with EMA to represent hidden buying/selling pressure.
When HAP ARS direction and Wick EMA slope are parallel, the trend is considered healthy.
When they diverge, it signals weak continuation, exhaustion, or fake moves.
🔹 Parallel Projection
The Wick EMA is projected slightly forward based on its current slope.
This projection answers a simple question:
If current pressure continues, where will it block or support price next?
It is not a straight line, but a slope-aware extension.
🔹 Smart Filtering
To avoid noise:
A minimum slope threshold filters flat-market signals
A strength multiplier removes weak or accidental alignments
Only meaningful parallel structures remain.
🔹 What It Helps You See
Trend continuation vs. hidden resistance
Fake candles driven by wicks
Healthy pullbacks inside strong trends
Early signs of pressure before price reacts
🔹 Best Use Cases
Trend-following entries
Pullback confirmation
Breakout validation
Combined with ADX, RSI, or volatility tools
Current Fractal High/Low (Dynamic) v2.3📝 Current Fractal High/Low (Dynamic) v2.3 – Changelog
➕ Additions:
New option: Enable Historical Fractals – Displays historical FH/FL levels with dashed lines for backtesting or reference.
Alert Conditions: Added alerts for breakout of the most recent Fractal High and Fractal Low (Fractal High Breakout & Fractal Low Breakout).
Inline Labels: Fractal labels (“FH” / “FL”) are now drawn directly on the lines for cleaner visuals.
Single Alert Toggle: Option to trigger alerts only once per breakout move.
Codebase prepared for future extensions (e.g., fractal tagging, fractal count logic, etc.).
🔧 Improvements:
Fractal updates now occur only when the previous high or low is broken (true breakout logic), not just when a new pivot forms.
Better variable management and prevention of re-declaration issues.
Ready for migration to Pine Script v6.
🛠 Known Issues / To-Do:
No option yet to limit max fractal history or show only the last fractal.
Label values are currently fixed to “FH” / “FL”; displaying price value instead is planned for a future update.
The Fantastic 4 - Momentum Rotation StrategyOverview
The Fantastic 4 is a tactical momentum rotation indicator. It rotates capital monthly across four carefully selected assets based on their 75-day Rate of Change (ROC), allocating only to assets with positive momentum and proportionally weighting them by their momentum strength.
This indicator tracks the strategy's historical performance, displays current allocation recommendations, and sends monthly rebalance alerts so you can easily manage your portfolio. Simply set your capital amount and the indicator shows exactly how much to invest in each asset.
Why These Four Assets?
The selection of 20-year Bonds, Gold, Russell 2000, and Emerging Markets is based on their specific volatility and decorrelation characteristics, which allow the strategy to react quickly to market shifts while providing protection during downturns.
Russell 2000 (Small Caps)
Chosen over the S&P 500 because it is more "lively" and active (Nowadays you could use also the Nasdaq). Its trends are steeper and more vertical, making it easier for a momentum indicator to catch clear trends. While the S&P 500 has more inertia, the Russell 2000 develops faster, allowing the strategy to capture gains in shorter periods.
Emerging Markets
Included because they can act like a "rocket," offering explosive growth potential while maintaining high decorrelation from developed equity markets. When emerging markets trend, they trend hard.
20-Year Bonds
Selected because they are the most decorrelated asset from equities. When a stock market crash occurs, capital typically flows into fixed income, and long-term bonds (20-year) notice this influx the most, making their price reaction more significant and easier to trade. This is the strategy's primary "safe haven."
Gold
Along with bonds, gold serves as a defensive asset providing a "shield" for the portfolio when general market conditions deteriorate. It offers additional decorrelation and crisis protection.
How the Strategy Works
The 75-Day Momentum Engine
The strategy uses a 75-day momentum lookback (roughly 3.5 months), which is considered very "agile" compared to other models like Global Equity Momentum (GEM) that use 200-day periods. This shorter window allows the strategy to:
React quickly to changes in trend
Catch upward movements in volatile assets early
Exit quickly when trends break
Monthly Rebalancing Process
At the end of each month:
Step 1: Calculate 75-day ROC for each asset
Step 2: Filter out assets with negative momentum (they receive 0% allocation)
Step 3: Distribute capital proportionally based on momentum strength
Step 4: Apply 5% minimum threshold (smaller allocations become zero)
Step 5: Apply 80% maximum cap (no single asset exceeds 80%, remainder stays in cash)
The 80% Ceiling Rule
There is an 80% investment ceiling for any single asset to prevent over-exposure. If only one asset (like bonds) has positive momentum, 80% goes to that asset and 20% remains in cash/liquidity.
Behavior in Bearish Markets
When markets turn bearish, the strategy protects capital through several mechanisms:
Automatic Risk-Off
Because the strategy only invests in assets with positive momentum, it automatically moves away from crashing equities. If an asset's trend becomes negative, the strategy stays "on the sidelines" for that asset.
The Bond Haven
During prolonged bearish periods or sudden crashes (like COVID-19), the strategy typically shifts into 20-year bonds. During the COVID-19 crash in March 2020, while global markets were collapsing, strategies like this reportedly yielded positive returns by being positioned in bonds.
Full Liquidity Option
If no assets show positive momentum, the strategy moves to 100% cash. This is rare given the decorrelation between the four assets—when equities crash, bonds and gold typically rise.
What This Indicator Does
This is a tracking and alerting tool that:
Calculates the optimal allocation based on current momentum
Shows historical monthly performance of the strategy
Simulates portfolio equity growth from your specified starting capital
Displays exact dollar amounts to invest in each asset
Sends monthly rebalance alerts with complete instructions
Detects missing data to prevent false signals
Features
Dynamic allocation table showing weights, dollar amounts, and ROC values
Monthly returns history with color-coded performance
Data availability detection with visual status indicators
Configurable alerts for rebalancing, go-to-cash, and missing data
Simulated equity curve from initial capital
Settings Guide
Assets
Configure your four ETFs. The default European ETFs are:
Asset 1 - XETR:IS04: iShares 20+ Year Treasury Bond (Bonds)
Asset 2 - XETR:GZUR: Gold ETC
Asset 3 - XETR:XRS2: Xtrackers Russell 2000 (Small Caps)
Asset 4 - XETR:XMME: Xtrackers Emerging Markets (EM)
For US markets, consider: TLT (20-year bonds), GLD (Gold), IWM (Russell 2000), EEM (Emerging Markets)
Strategy Settings
ROC Period - Momentum lookback in daily bars. Default: 75 days (~3.5 months)
Max Allocation % - Maximum weight for any single asset. Default: 80%
Min Allocation % - Threshold below which allocation becomes zero. Default: 5%
Capital
Initial Capital - Your portfolio value. The indicator calculates exact amounts for each asset based on this. Default: $20,000
Display
Table Positions - Position the allocation and history tables on screen
Months of History - How many past months to display (3-24)
Alerts
Monthly Rebalance Alert - Sends complete allocation details at month end
Go-to-Cash Alert - Alerts when all assets have negative momentum
Missing Data Alert - Warns when asset data is unavailable
How to Use
Initial Setup
Add indicator to any chart and switch to MONTHLY timeframe
Configure your four ETF tickers
Set your portfolio capital amount
Position the tables where you prefer
Setting Up Alerts
Click Alert button or press Alt+A
Set Condition to "Fanta4"
Select "Any alert() function call"
Choose notification method (Email, Push, Webhook, etc.)
Set expiration to "Open-ended"
Monthly Workflow
Receive rebalance alert at the start of each month
Alert shows exact percentages AND dollar amounts for each asset
Adjust your portfolio accordingly
No action needed during the month
Reading the Tables
Green = positive returns/momentum
Red = negative returns/momentum
Orange "N/A" = missing data
Alloc column shows weight distribution (e.g., "45/35/20/—")
Alert Message Example
Monthly alerts include:
Target month for the new allocation
Current portfolio value
Each asset's percentage AND dollar amount
Each asset's momentum (ROC) value
Cash allocation if applicable
Total return since inception
Historical Context
This strategy combines elements of:
Dual Momentum (Gary Antonacci) - Relative and absolute momentum
Global Equity Momentum (GEM) - But with shorter 75-day vs 200-day lookback
Risk parity concepts - Decorrelated asset selection
The key innovation is the specific asset selection optimized for momentum trading and the agile 75-day lookback period that allows faster reactions to trend changes.
Data Requirements
The strategy activates only when all four assets have valid price data (minimum 75 days of history). The data status row shows checkmarks for available data. Note: Some ETFs have limited history (e.g., XMME data starts June 2017).
Limitations
This is a tracking indicator, not an automated trading system
Past performance is hypothetical and does not guarantee future results
Requires all four assets to have valid data; partial allocation not supported
Monthly rebalancing may miss shorter-term momentum shifts
Transaction costs, slippage, and taxes are not included in simulation
ETF availability and liquidity vary by region
The 75-day momentum may whipsaw in choppy, trendless markets
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice.
Version History
v1.0 - Initial release with momentum rotation, allocation tables, data validation, and monthly alerts
KJ Sessions (Today Only): Asia/London/US + OverlapKJ Sessions : Asia/London/US + Overlap.
best for people to clearly mark Asia, UK and US opening and closing timing.
ELMEHDI VIP (v4.0) ABO SALTAN //@version=5
indicator(title = 'ELMEHDI VIP (v4.0)', shorttitle = 'EL MEHDI KHEYI(v4.0)', overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_bars_back = 500, max_polylines_count = 100)
bullcolor = #339b44
bearcolor = #af3232
ema150 = ta.ema(close, 150)
ema250 = ta.ema(close, 250)
gr_customalert = "Custom Alerts"
gr_signal = "General Configurations"
gr_PullBacksignal = "Trading Assistants"
gr_RiskManage = "Risk Management"
gr_dash = "Dashboard Configurations"
//symbol info
symInfoCheck = false
symInfo = syminfo.ticker + ' | ' + timeframe.period + (timeframe.isminutes ? 'M' : na)
date = str.tostring(dayofmonth(time_close)) + '/' + str.tostring(month(time_close)) + '/' + str.tostring(year(time_close))
//text positioning
textVPosition = 'middle'
textHPosition = 'center'
//symbol info positioning
symVPosition = 'top'
symHPosition = 'left'
//cell size
width = 0
height1 = 0
//title settings
c_title = #b2b5be80
s_title = 'large'
a_title = 'center'
//subtitle settings
c_subtitle = #b2b5be80
s_subtitle = 'normal'
a_subtitle = 'center'
c_bg = color.new(color.blue, 100)
// Get user input
showSignals = input(true, "Show Signal's", group=gr_signal)
//showSignals = true
sensitivity = input.float(2.4, "Sensitivity", 0.1, step=0.1, group=gr_signal)
STuner = input.int(10, "Signal Tuner(1-25)", minval = 1, maxval = 25, group=gr_signal)
Presets = "All Signals"
//Presets = input.string("All Signals", "Presets", , group=gr_signal)
filterstyle = input.string("Trending Signals ", "Signal Mode / Filters", ["Trending Signals ", "Contrarian Signals ", "High Volume ", "Strong ", "Swing ", "Smooth ", "Scalping ", "Scalping+ "], group=gr_signal)
//TextStyle = input.string("Minimal", "Signal Style", , group=gr_signal)
//periodTrendCloud = input.string("Smooth", "Trend Cloud Style", , group=gr_Other_Settings)
TextStyle = "Minimal"
consSignalsFilter = filterstyle == "Trending Signals " ? true : false
StrongSignalsOnly = filterstyle == "Strong " ? true : false
highVolSignals = filterstyle == "High Volume " ? true : false
signalsTrendCloud = (filterstyle == "Smooth ") ? true : (filterstyle == "Scalping ") ? true : (filterstyle == "Scalping+ ") ? true : (filterstyle == "Swing ") ? true : false
ContrarianOnly = filterstyle == "Contrarian Signals " ? true : false
TrendMap = 'Trend Gradient'
momentumCandles = false
assistantenable = input(true,'', group=gr_PullBacksignal, inline = 'sexyshit')
assistantmode = input.string('Trend Assistant', 'Assistant | Mode', , group = gr_PullBacksignal, inline = 'sexyshit')
Show_PR = input.bool(true, title="", group = gr_PullBacksignal , inline = "Features1")
MSTuner = input.int(8, "Reversal Dot | Tuner(2-30)", minval = 2, maxval = 30, group=gr_PullBacksignal, inline = "Features1")
LongTrendAverage = assistantmode == 'Trend Tracker' and assistantenable == true ? true : false
analyscloud = assistantmode == 'Trend Assistant' and assistantenable == true ? true : false
showTrendCloud = (filterstyle == "Smooth ") ? true : (filterstyle == "Scalping ") ? true : (filterstyle == "Scalping+ ") ? true : (filterstyle == "Swing ") ? true : false
periodTrendCloud = (filterstyle == "Smooth ") ? "Smooth" : (filterstyle == "Scalping ") ? "Scalping" : (filterstyle == "Scalping+ ") ? "Scalping+" : (filterstyle == "Swing ") ? "Swing" : na
//ScalpingPlus = input(false, "Fast trend cloud", group=gr_Other_Settings)
//fastTrendCloudLen = input.int(55, "Fast trend cloud", 2, group=gr_Other_Settings)
fill(plot(showTrendCloud and periodTrendCloud == "Smooth" ? na : assistantenable == true and assistantmode == 'Trend Tracker' ? ema150 : na, "", na, editable=false), plot(showTrendCloud and periodTrendCloud == "Smooth" ? na : assistantenable == true and assistantmode == 'Trend Tracker' ? ema250 : na, "", na, editable=false), ema150 > ema250 ? color.new(bullcolor, 70) : ema150 < ema250 ? color.new(bearcolor, 70) : na)
showDashboard = input(true, "Smart Panel", group = gr_dash , inline = "Features1")
locationDashboard = input.string("Bottom Right", "Dashboard Location", , group = gr_dash , tooltip="Smart Panel")
sizeDashboard = input.string("Small", "Dashboard Size", , group = gr_dash , tooltip="Smart Panel")
tpLabels = input(true, "Dynamic Take Profit Lables", group=gr_RiskManage)
ShowTpSlAreas = input(true, "Show take Profit/Stop-loss Area", group=gr_RiskManage)
ShowTrailingSL = input(false, "Show trailing Stop-loss", group=gr_RiskManage)
usePercSL = input(false, "SL/TRAILING", inline="1", group=gr_RiskManage)
percTrailingSL = input.float(1, "", 0, step=0.1, inline="1", group=gr_RiskManage)
useTP1 = input(true, "", inline="1", group=gr_RiskManage)
multTP1 = input.float(1, "TP 1", 0, inline="1", group=gr_RiskManage)
useTP2 = input(true, "", inline="4", group=gr_RiskManage)
multTP2 = input.float(2, "TP 2", 0, inline="4", group=gr_RiskManage)
useTP3 = input(true, "", inline="4", group=gr_RiskManage)
multTP3 = input.float(3, "TP 3", 0, inline="4", group=gr_RiskManage)
ShowSwings = input(false, "Show Market Structure", inline="3", group=gr_RiskManage)
periodSwings = input.int(10, "", 2, inline="3", group=gr_RiskManage)
//showTS = input(title='Show Trend Shifter', defval=false, group='Contrarian SIGNALS')
// showsignals = input(title='Show Signals', defval=false, group='Contrarian SIGNALS')
// Alerts Managemnt
Normalbuy_alert = input.bool(title='Buy Signal', defval=false, inline = "NB", group=gr_customalert)
Strongbuy_alert = input.bool(title='Strong Buy', defval=true, inline = "NB", group=gr_customalert)
Normalsell_alert = input.bool(title='Sell Signal', defval=false , inline = "NS", group=gr_customalert)
Strongsell_alert = input.bool(title='Strong Sell', defval=true , inline = "NS", group=gr_customalert)
slalert = input.bool(title='Stop-Loss', defval=true , inline = "SLTP1", group=gr_customalert)
tp1alert = input.bool(title='Target 1', defval=true , inline = "SLTP1", group=gr_customalert)
tp2alert = input.bool(title='Target 2', defval=true , inline = "TP2TP3", group=gr_customalert)
tp3alert = input.bool(title='Target 3', defval=true , inline = "TP2TP3", group=gr_customalert)
bullcrosscloud_alert = input.bool(title='Bullish Cloud', defval=false, inline = "CD", group=gr_customalert)
bearcrosscloud_alert = input.bool(title='Bearish Cloud', defval=false, inline = "CD", group=gr_customalert)
showCons = false
paintCons = false
// Signal Text
SimpleBuy = "Buy"
StrongB = "Strong Buy"
SimpleSell = "Sell"
StrongS = "Strong Sell"
if TextStyle == "Normal"
SimpleBuy := "Buy"
StrongB := "BUY"
SimpleSell:= "Sell"
StrongS := "Strong Sell"
if TextStyle == "Minimal"
SimpleBuy := "⬆"
StrongB := "⬆⬆"
SimpleSell:= "⬇"
StrongS := "⬇⬇"
// Signal Text Color
// bullsignalcolor = #ffffff
// bearsignalcolor = color.rgb(255, 255, 255)
// if TextStyle == "Normal"
// bullsignalcolor := color.rgb(255, 255, 255)
// bearsignalcolor := color.rgb(255, 255, 255)
// if TextStyle == "Minimal"
// bullsignalcolor := color.rgb(255, 255, 255)
// bearsignalcolor := color.rgb(255, 255, 255)
src = close
RSII = ta.ema(ta.rsi(src, 50), 30)
TR = math.abs(RSII - RSII )
wwalpha = 1 / 50
WWMA = 0.0
WWMA := wwalpha * TR + (1 - wwalpha) * nz(WWMA )
ATRRSI = 0.0
ATRRSI := wwalpha * WWMA + (1 - wwalpha) * nz(ATRRSI )
TsFast = ta.ema(ta.rsi(src, 50), 30)
TsUP = TsFast + ATRRSI * 4.236
TsDN = TsFast - ATRRSI * 4.236
textWatermark = table.new(textVPosition + '_' + textHPosition, 1, 3)
TsSlow = 0.0
TsSlow := TsUP < nz(TsSlow ) ? TsUP : TsFast > nz(TsSlow ) and TsFast < nz(TsSlow ) ? TsDN : TsDN > nz(TsSlow ) ? TsDN : TsDN < nz(TsSlow ) and TsFast > nz(TsSlow ) ? TsUP : nz(TsSlow )
Colorh = TsFast > 55 ? color.rgb(255, 0, 0) : TsFast < 45 ? color.rgb(0, 255, 8) : #ffffff
//QQF = plot(TsFast, 'TS FAST', color=color.new(color.maroon, 100), linewidth=2, display=display.none, editable = false)
//QQS = plot(TsSlow, 'TS SLOW', color=color.new(color.white, 100), linewidth=2, display=display.none , editable = false)
//plot(TsFast, color=Colorh, linewidth=2, style=plot.style_area, histbase=50)
//BearLimit = hline(60, color=color.gray, linestyle=hline.style_dashed)
//BullLimt = hline(40, color=color.gray, linestyle=hline.style_dashed)
bulllim = 45
bearlim = 55
BullSignalr = ta.crossover(TsFast, TsSlow) and TsFast < bulllim
BearSignallr = ta.crossunder(TsFast, TsSlow) and TsFast > bearlim
/////////////////////////////////////////////////////////
// Trap Detector
////////////////////////////////////////////////////////
// Functions
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
f_top_fractal(src) => src < src and src < src and src > src and src > src
f_bot_fractal(src) => src > src and src > src and src < src and src < src
f_fractalize (src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src >= topLimit ? src : na
fractalBot = f_fractalize(src) < 0 and src <= botLimit ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
// Get components
= wavetrend(close, 5*MSTuner, 10*MSTuner)
= f_findDivs(wt2, 10, -35)
= f_findDivs(wt2, 40, -70)
wtDivBull = wtDivBull1 or wtDivBull2
wtDivBear = wtDivBear1 or wtDivBear2
plotshape(ta.crossover(wt1, wt2) and Show_PR and wt2 <= -60)
plotshape(ta.crossunder(wt1, wt2) and Show_PR and wt2 >= 60)
rsi = ta.rsi(close ,14)
// Functions
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
atr(len) =>
tr = ta.tr
atr = 0.0
atr := nz(atr + (tr - atr ) / len, tr)
supertrend(src, factor, len) =>
atr = ta.atr(len)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or close < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend
if prevSuperTrend == prevUpperBand
direction := close > upperBand ? 1 : -1
else
direction := close < lowerBand ? -1 : 1
superTrend := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
dchannel(len)=>
hh = ta.highest(len)
ll = ta.lowest (len)
trend = 0
trend := close > hh ? 1 : close < ll ? -1 : nz(trend )
trendScalper(show, len1, len2, len3, colorBull, colorBear, colorBarBull, colorBarBear) =>
avgOC = math.avg(open, close)
ha_o = 0.0, ha_o := na(ha_o ) ? avgOC : (ha_o + ohlc4 ) / 2
ema1 = ta.ema(ha_o, len1), ema2 = ta.ema(ha_o, len2), ema3 = ta.ema(ha_o, len3)
ris1 = ema1 > ema1 , ris2 = ema2 > ema2 , ris3 = ema3 > ema3
fal1 = ema1 < ema1 , fal2 = ema2 < ema2 , fal3 = ema3 < ema3
colorEma1 = ris1 ? colorBull : fal1 ? colorBear : na, colorEma2 = ris2 ? colorBull : fal2 ? colorBear : na, colorEma3 = ris3 ? colorBull : fal3 ? colorBear : na
fillEma1 = avgOC > ema1 ? colorBull : avgOC < ema1 ? colorBear : na, fillEma2 = ema1 > ema2 ? colorBull : ema1 < ema2 ? colorBear : na, fillEma3 = ema2 > ema3 ? colorBull : ema2 < ema3 ? colorBear : na
colorBar = close < ema1 and close < ema2 ? colorBarBear : colorBarBull
candlesMom() =>
= ta.macd(close, 2, 4, 3)
(macd > 10 and macd > macd ) or (macd < 10 and macd < macd )
trailingSL(buy, sell, factor, len, usePerc, perc) =>
atr = atr(len)
upperBand = high + (usePerc ? high * (perc / 100) : factor * atr)
lowerBand = low - (usePerc ? low * (perc / 100) : factor * atr)
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or buy ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or sell ? upperBand : prevUpperBand
int direction = na
float stop = na
prevSuperTrend = stop
if prevSuperTrend == prevUpperBand
direction := buy ? 1 : -1
else
direction := sell ? -1 : 1
stop := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
add_to_zz(zz, val, bi) =>
array.unshift(zz, bi)
array.unshift(zz, val)
if array.size(zz) > 12
array.pop(zz)
update_zz(zz, val, bi, dir) =>
if array.size(zz) == 0
add_to_zz(zz, val, bi)
else
if dir == 1 and val > array.get(zz, 0) or dir == -1 and val < array.get(zz, 0)
array.set(zz, 0, val)
array.set(zz, 1, bi)
0
// Get components
vosc = ta.obv - ta.ema(ta.obv, 20)
bs = ta.ema(nz(math.abs((open - close) / (high - low) * 100)), 3)
ema = ta.ema(close, 200)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep(sym, res, src) =>
bool bull = na
bull := equal_tf(res) ? src : bull
bull := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_off) : bull
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull := array.pop(bull_array)
array.clear(bull_array)
bull
//TF1Bull = securityNoRep(syminfo.tickerid, "1" , emaBull)
//TF3Bull = securityNoRep(syminfo.tickerid, "3" , emaBull)
TF5Bull = securityNoRep(syminfo.tickerid, "5" , emaBull)
//TF10Bull = securityNoRep(syminfo.tickerid, "10" , emaBull)
TF15Bull = securityNoRep(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep(syminfo.tickerid, "60" , emaBull)
//TF120Bull = securityNoRep(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep(syminfo.tickerid, "240" , emaBull)
//TF720Bull = securityNoRep(syminfo.tickerid, "720" , emaBull)
//TFDBull = securityNoRep(syminfo.tickerid, "1440", emaBull)
hma55 = ta.hma(close, 55 )
= ta.macd(close, 12, 26, 9)
supertrend = supertrend(close, sensitivity, STuner)
maintrend = dchannel(30)
confBull = (ta.crossover (close, supertrend) or (ta.crossover (close, supertrend) and maintrend < 0)) and macd > 0 and macd > macd and ema150 > ema250 and hma55 > hma55 and maintrend > 0
confBear = (ta.crossunder(close, supertrend) or (ta.crossunder(close, supertrend) and maintrend > 0)) and macd < 0 and macd < macd and ema150 < ema250 and hma55 < hma55 and maintrend < 0
trendcloud = supertrend(ohlc4, periodTrendCloud == "Swing" ? 7 : 4, 10)
hma = periodTrendCloud == "Scalping+" ? ta.hma(close, 55) : na
none = close > 0
= ta.dmi(14, 14)
consFilter = adx > 20
ContBear = TsFast > 65
ContBull = TsFast < 35
StrongFilter = ta.ema(close, 200)
//volFilter = (ta.ema(volume, 25) - ta.ema(volume, 26)) / ta.ema(volume, 26) > 0
volFilter = (ta.ema(volume, 15) - ta.ema(volume, 20)) / ta.ema(volume, 25) > 0
trendFilter = trendcloud
bull = (Presets == "All Signals" ? ta.crossover (close, supertrend) : confBull and not confBull ) and Presets != "Trend Scalper" and (StrongSignalsOnly ? close > StrongFilter : none) and (ContrarianOnly ? ContBull : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "Smooth" ? ema150 > ema250 : close > trendFilter) : none)
bear = (Presets == "All Signals" ? ta.crossunder(close, supertrend) : confBear and not confBear ) and Presets != "Trend Scalper" and (StrongSignalsOnly ? close < StrongFilter : none) and (ContrarianOnly ? ContBear : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "Smooth" ? ema150 < ema250 : close < trendFilter) : none)
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
= trendScalper(Presets == "Trend Scalper" ? true : false, 5, 9, 21, bullcolor, bearcolor, bullcolor, bearcolor)
trailingStop = trailingSL(bull, bear, 2.2, 14, usePercSL, percTrailingSL)
float _ph = ta.highestbars(high, periodSwings) == 0 ? high : na
float _pl = ta.lowestbars (low, periodSwings) == 0 ? low : na
var _dir = 0, dir_ = _pl and na(_ph) ? -1 : _dir, _dir := _ph and na(_pl) ? 1 : dir_, dirChg = ta.change(_dir)
var zz = array.new_float(0), zzOld = array.copy(zz)
float zzLive = _ph or _pl ? (dirChg ? add_to_zz(zz, _dir == 1 ? _ph : _pl, bar_index) : update_zz(zz, _dir == 1 ? _ph : _pl, bar_index, _dir)) : na
float hb_ = ta.highestbars(10) == 0 ? high : na
float lb_ = ta.lowestbars (10) == 0 ? low : na
var int dir = 0
float zz_ = na
float pp = na
var int consCnt = 0
var float condHi = na
var float condLo = na
float H_ = ta.highest(5)
float L_ = ta.lowest (5)
var line lineUp = na
var line lineDn = na
bool breakUp = false
bool breakDn = false
var float pvh1_price = array.new_float(1000, na)
var int pvh1_time = array.new_int (1000, na)
var float pvl1_price = array.new_float(1000, na)
var int pvl1_time = array.new_int (1000, na)
var float pvh2_price = array.new_float(1000, na)
var int pvh2_time = array.new_int (1000, na)
var float pvl2_price = array.new_float(1000, na)
var int pvl2_time = array.new_int (1000, na)
var float htcmrll_price = na
var int htcmrll_time = na
var float ltcmrhh_price = na
var int ltcmrhh_time = na
var box long_boxes = array.new_box()
var box short_boxes = array.new_box()
var float temp_pv_0 = na
var float temp_pv_1 = na
var float temp_pv_2 = na
bool pvh = high < high and high > high
bool pvl = low > low and low < low
int pv1_time = bar_index
float pv1_high = high
float pv1_low = low
var buyBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(buyBars, i))
var sellBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(sellBars, i))
// Colors
green = bullcolor, green50 = color.new(green, 50), green20 = color.new(green, 80)
red = bearcolor, red50 = color.new(red, 50), red20 = color.new(red, 80)
silver = #B2B5BE, silver50 = color.new(silver, 50), silver20 = color.new(silver, 80)
// Plots
atrBand = usePercSL ? (trigger ? low : high) * (percTrailingSL / 100) : ta.atr(14) * 2.2
atrStop = trigger ? low - atrBand : high + atrBand
lastTrade(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade(close)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y-lastTrade(atrStop))*multTP1 + entry_y
tp2_y = (entry_y-lastTrade(atrStop))*multTP2 + entry_y
tp3_y = (entry_y-lastTrade(atrStop))*multTP3 + entry_y
labelTpSl(cond, y, txt, color) =>
label labelTpSl = ShowTpSlAreas and cond ? label.new(bar_index + 1, y, txt, xloc.bar_index, yloc.price, color, label.style_label_left, color.white, size.normal) : na
label.delete(labelTpSl )
labelTpSl(none, entry_y, "Entry : " + str.tostring(math.round_to_mintick(entry_y)), #089981)
labelTpSl(none, stop_y , "Stop loss : " + str.tostring(math.round_to_mintick(atrStop)), bearcolor)
labelTpSl(useTP1 and multTP1 != 0, tp1_y, "TP 1 : " + str.tostring(math.round_to_mintick(tp1_y)), #089981)
labelTpSl(useTP2 and multTP2 != 0, tp2_y, "TP 2 : " + str.tostring(math.round_to_mintick(tp2_y)), #089981)
labelTpSl(useTP3 and multTP3 != 0, tp3_y, "TP 3 : " + str.tostring(math.round_to_mintick(tp3_y)), #089981)
lineTpSl(cond, y, color, style) =>
line lineTpSl = ShowTpSlAreas and cond ? line.new(bar_index - (trigger ? countBull : countBear), y, bar_index + 1, y, xloc.bar_index, extend.none, color, style) : na
line.delete(lineTpSl )
lineTpSl(none, entry_y, #089981, line.style_dashed)
lineTpSl(none, stop_y , bearcolor , line.style_solid )
lineTpSl(useTP1 and multTP1 != 0, tp1_y, bullcolor, line.style_dotted)
lineTpSl(useTP2 and multTP2 != 0, tp2_y, bullcolor, line.style_dotted)
lineTpSl(useTP3 and multTP3 != 0, tp3_y, bullcolor, line.style_dotted)
//buy = showSignals and bull ? label.new(bar_index, low , close > StrongFilter ? StrongB : SimpleBuy , xloc.bar_index, yloc.belowbar, bullcolor, label.style_label_up , color.rgb(255, 255, 255), size.normal) : na
//sell = showSignals and bear ? label.new(bar_index, high, close < StrongFilter ? StrongS : SimpleSell , xloc.bar_index, yloc.abovebar, bearcolor , label.style_label_down, color.rgb(255, 255, 255), size.normal) : na
buy = (showSignals and bull ? label.new(bar_index, low , close > StrongFilter ? StrongB : SimpleBuy , xloc.bar_index, yloc.belowbar, bullcolor, label.style_label_up , color.rgb(255, 255, 255), size.normal) : na)
sell = showSignals and bear ? label.new(bar_index, high, close < StrongFilter ? StrongS : SimpleSell , xloc.bar_index, yloc.abovebar, bearcolor , label.style_label_down, color.rgb(255, 255, 255), size.normal) : na
tpLabels(tp) =>
tp1Bull = ta.crossover (rsi, 70), tp2Bull = ta.crossover (rsi, 75), tp3Bull = ta.crossover (rsi, 80)
tp1Bull := tp1Bull and (nz(ta.barssince(tp1Bull) , 9999) > countBull), tp2Bull := tp2Bull and (ta.barssince(tp1Bull) <= countBull), tp2Bull := tp2Bull and (nz(ta.barssince(tp2Bull) , 9999) > countBull), tp3Bull := tp3Bull and (ta.barssince(tp2Bull) <= countBull), tp3Bull := tp3Bull and (nz(ta.barssince(tp3Bull) , 9999) > countBull)
tp1Bear = ta.crossunder(rsi, 30), tp2Bear = ta.crossunder(rsi, 25), tp3Bear = ta.crossunder(rsi, 20)
tp1Bear := tp1Bear and (nz(ta.barssince(tp1Bear) , 9999) > countBear), tp2Bear := tp2Bear and (ta.barssince(tp1Bear) <= countBear), tp2Bear := tp2Bear and (nz(ta.barssince(tp2Bear) , 9999) > countBear), tp3Bear := tp3Bear and (ta.barssince(tp2Bear) <= countBear), tp3Bear := tp3Bear and (nz(ta.barssince(tp3Bear) , 9999) > countBear)
if Presets != "Trend Scalper" and tpLabels
trigger ? (tp == 1 ? tp1Bull : tp == 2 ? tp2Bull : tp3Bull) : (tp == 1 ? tp1Bear : tp == 2 ? tp2Bear : tp3Bear)
plotshape(tpLabels(1), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 1", trigger ? green : na , true)
plotshape(tpLabels(2), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 2", trigger ? green : na , false)
plotshape(tpLabels(3), "", shape.xcross, location.abovebar, trigger ? green : na , 0, "TP 3", trigger ? green : na , false)
plotshape(tpLabels(1), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 1", trigger ? na : red, true)
plotshape(tpLabels(2), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 2", trigger ? na : red, false)
plotshape(tpLabels(3), "", shape.xcross, location.belowbar, trigger ? na : red, 0, "TP 3", trigger ? na : red, false)
var label zzLabel = na
if array.size(zz) > 12 and ShowSwings
if array.get(zz, 0) != array.get(zzOld, 0) or array.get(zz, 1) != array.get(zzOld, 1)
if array.get(zz, 2) == array.get(zzOld, 2) and array.get(zz, 3) == array.get(zzOld, 3)
label.delete(zzLabel)
zzLabel := label.new(math.round(array.get(zz, 1)), array.get(zz, 0), _dir == 1 ? array.get(zz, 0) > array.get(zz, 4) ? ((array.get(zz, 4) < array.get(zz, 8)) ? "High" : "HH") : "LH" : array.get(zz, 0) < array.get(zz, 4) ? ((array.get(zz, 4) > array.get(zz, 8)) ? "Low" : "LL") : "HL", xloc.bar_index, yloc.price, color.new(color.white, 100), _dir == 1 ? label.style_label_down : label.style_label_up, _dir == 1 ? bullcolor : bearcolor)
if showCons and barstate.isconfirmed
dir := hb_ and na(lb_) ? 1 : lb_ and na(hb_) ? -1 : dir
if hb_ and lb_
if dir == 1
zz_ := hb_
else
zz_ := lb_
else
zz_ := hb_ ? hb_ : lb_ ? lb_ : na
for x = 0 to 1000
if na(close) or dir != dir
break
if zz_
if na(pp)
pp := zz_
else
if dir == 1 and zz_ > pp
pp := zz_
if dir == -1 and zz_ < pp
pp := zz_
if pp != pp
if consCnt > 5
if pp > condHi
breakUp := true
if pp < condLo
breakDn := true
if consCnt > 0 and pp <= condHi and pp >= condLo
consCnt += 1
else
consCnt := 0
else
consCnt += 1
if consCnt >= 5
if consCnt == 5
condHi := H_
condLo := L_
else
line.delete(lineUp)
line.delete(lineDn)
condHi := math.max(condHi, high)
condLo := math.min(condLo, low )
lineUp := line.new(bar_index, condHi , bar_index - consCnt, condHi , color=bearcolor , style=line.style_dashed)
lineDn := line.new(bar_index, condLo , bar_index - consCnt, condLo , color=color.lime, style=line.style_dashed)
fill(plot(condHi, "", na, 1, plot.style_stepline, editable=false), plot(condLo, "", na, 1, plot.style_stepline, editable=false), paintCons and consCnt > 5 ? color.white : na, "", false)
//buy_col = color.new(#0ac20a,0)
//sell_col = color.new(#fd1605,0)
//text_col = color.new(#FFFFFF,0)
// -------- Bearish trend (blue) color selection --------
// getSellColor(count) =>
// if count == 1
// color.new(#11e7f2,0)
// else
// if count == 2
// color.new(#11d9f2,0)
// else
// if count == 3
// color.new(#11cbf2,0)
// else
// if count == 4
// color.new(#11aff2,0)
// else
// if count == 5
// color.new(#1193f2,0)
// else
// if count == 6
// color.new(#1176f2,0)
// else
// if count == 7
// color.new(#105df4,0)
// else
// if count == 8
// color.new(#1051f5,0)
// else
// if count == 9
// color.new(#0f44f5,0)
// else
// if count == 10
// color.new(#0c3de0,0)
// else
// if count == 11
// color.new(#0935ca,0)
// else
// if count == 12
// color.new(#062eb4,0)
// else
// if count == 13
// color.new(#02269e,0)
// -------- Bullish trend (blue) color selection --------
// getBuyColor(count) =>
// if count == 1
// color.new(#eef211,0)
// else
// if count == 2
// color.new(#efdc11,0)
// else
// if count == 3
// color.new(#f0c511,0)
// else
// if count == 4
// color.new(#f1af11,0)
// else
// if count == 5
// color.new(#f29811,0)
// else
// if count == 6
// color.new(#f28811,0)
// else
// if count == 7
// color.new(#f27811,0)
// else
// if count == 8
// color.new(#f26811,0)
// else
// if count == 9
// color.new(#f25811,0)
// else
// if count == 10
// color.new(#ea420d,0)
// else
// if count == 11
// color.new(#e12c09,0)
// else
// if count == 12
// color.new(#d81605,0)
// else
// if count == 13
// color.new(#cf0000,0)
// -------- Calculate bearish trend sequence --------
buySetup = 0
buySetup := close < close ? buySetup == 13 ? 1 : buySetup + 1 : 0
// -------- Calculate bullish trend sequence --------
sellSetup = 0
sellSetup := close > close ? sellSetup == 13 ? 1 : sellSetup + 1 : 0
// -------- Paint bars --------
//barColour = buySetup >= 1 ? getBuyColor(buySetup) : sellSetup >= 1 ? getSellColor(sellSetup) : na
// Candle Coloring
// Input
FastteyLength = 12
SjlowLeyLength = 26
srrrc = close
signalXLength = 9
// Data reference
= ta.macd(srrrc, FastteyLength, SjlowLeyLength, signalXLength)
// 4 level of green
greenHigh = #7bff00
greenMidHigh = #7bff00
greenMidLow = #7bff00
greenLow = #7bff00
// Yellow
yellowLow = #693d8e
// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #ff0000
// Default color
candleBody = yellowLow
// Ranging trend
if histX > 0
if histX > histX and histX > 0
candleBody := greenLow
if histX < 0
if histX < histX and histX < 0
candleBody := redLow
// Bullish trend
if MacdX > 0 and histX > 0
candleBody := greenMidLow
if histX > histX and MacdX > 0 and histX > 0
candleBody := greenMidHigh
if histX > histX and MacdX > 0 and histX > 0
candleBody := greenHigh
// Bearish trend
if MacdX < 0 and histX < 0
candleBody := redMidLow
if histX < histX and MacdX < 0 and histX < 0
candleBody := redMidHigh
if histX < histX and MacdX < 0 and histX < 0
candleBody := redHigh
barcolor(candleBody)
//barcolor(TrendMap == 'RSI Gradient' ? barColour : na, title='Bar colors (heatmap)',editable=false)
//barcolor(momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false)
//plotcandle(open, high, low, close , color = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , wickcolor = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , bordercolor = momentumCandles and candlesMom() ? color.rgb(187, 187, 187) : TrendMap == 'Signal Based' ? (Presets == "Trend Scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? bullcolor : bearcolor) : TrendMap == 'RSI Gradient' ? barColour : TrendMap == 'Trend Gradient' ? candleBody : na , editable=false , editable = false)
fill(plot(showTrendCloud and periodTrendCloud == "Smooth" ? ema150 : na, "", na, editable=false), plot(showTrendCloud and periodTrendCloud == "Smooth" ? ema250 : na, "", na, editable=false), ema150 > ema250 ? color.new(bullcolor, 70) : ema150 < ema250 ? color.new(bearcolor, 70) : na)
plot(ShowTrailingSL and trigger and nz(ta.barssince(low < trailingStop), bar_index) > countBull ? trailingStop : na, "", green, 1, plot.style_linebr, editable=false)
plot(ShowTrailingSL and not trigger and nz(ta.barssince(high > trailingStop), bar_index) > countBear ? trailingStop : na, "", red , 1, plot.style_linebr, editable=false)
p0 = plot(avgOC, "", na , editable=false)
p1 = plot(ema5 , "", colorEma5 , editable=false)
p2 = plot(ema9 , "", colorEma9 , editable=false)
p3 = plot(ema21, "", colorEma21, editable=false)
plot(LongTrendAverage ? ta.ema(close, 250) : na, 'Trend Tracer', linewidth=2, color=close > ta.ema(close, 250) ? color.new(bullcolor, 45) : color.new(bearcolor, 45))
fill(p0, p1, fillEma5 )
fill(p1, p2, fillEma9 )
fill(p2, p3, fillEma21)
fill(plot(showTrendCloud and periodTrendCloud != "Smooth" and periodTrendCloud != "Scalping+" and trendcloud != 0 and close > trendcloud ? trendcloud : na, "", bullcolor, 1, plot.style_linebr, editable=false), p0, color.new(bullcolor, 90))
fill(plot(showTrendCloud and periodTrendCloud != "Smooth" and periodTrendCloud != "Scalping+" and trendcloud != 0 and close < trendcloud ? trendcloud : na, "", bearcolor , 1, plot.style_linebr, editable=false), p0, color.new(bearcolor , 90))
//fill(plot(hma, "", hma > hma ? green : hma < hma ? red : na, editable=false), plot(hma , "", hma > hma ? green : hma < hma ? red : na, editable=false), hma > hma ? green : hma < hma ? red : na)
////////////////////////////////////////////////////////////////////////////////////////////////
// Get user input
indicatorTF = "Chart"
// Functions
sqz(bbLen, bbMult, kcLen, kcMult, source) =>
upperBB = ta.sma(source, bbLen) + ta.stdev(source, bbLen) * bbMult
lowerBB = ta.sma(source, bbLen) - ta.stdev(source, bbLen) * bbMult
upperKC = ta.sma(source, kcLen) + ta.sma(ta.tr, kcLen) * kcMult
lowerKC = ta.sma(source, kcLen) - ta.sma(ta.tr, kcLen) * kcMult
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
qqe(rsiLen, rsiSmooth, factor, source, bbLen, bbMult) =>
rsiMa = ta.ema(ta.rsi(source, rsiLen), rsiSmooth)
delta = ta.ema(ta.ema(math.abs(ta.mom(rsiMa, 1)), rsiLen * 2 - 1), rsiLen * 2 - 1) * factor
longBand = 0.0, longBand := rsiMa > longBand and rsiMa > longBand ? math.max(longBand , rsiMa - delta) : rsiMa - delta
shortBand = 0.0, shortBand := rsiMa < shortBand and rsiMa < shortBand ? math.min(shortBand , rsiMa + delta) : rsiMa + delta
cross1 = ta.cross(rsiMa, shortBand )
cross2 = ta.cross(rsiMa, longBand )
trend = 0.0, trend := cross1 ? 1 : cross2 ? -1 : nz(trend , 1)
fastDelta = trend == 1 ? longBand : shortBand
_hist = rsiMa - 50
_line = fastDelta - 50
= ta.bb(_line, bbLen, bbMult)
// Get components
cond(_offset) =>
top = ta.highest(high, 10)
bot = ta.lowest(low, 10)
osc = ta.ema(hlc3, 5) - ta.ema(ohlc4, 20)
oscRis = osc > osc
oscFal = osc < osc
oscA0 = osc > 0
oscB0 = osc < 0
oscTop = oscFal and oscRis
oscBot = oscRis and oscFal
bullR = oscB0 and oscBot and ((osc > ta.valuewhen(oscB0 and oscBot, osc, 1) and bot < ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearR = oscA0 and oscTop and ((osc < ta.valuewhen(oscA0 and oscTop, osc, 1) and top > ta.valuewhen(oscA0 and oscTop, top, 1)))
bullH = oscB0 and oscBot and ((osc < ta.valuewhen(oscB0 and oscBot, osc, 1) and bot > ta.valuewhen(oscB0 and oscBot, bot, 1)))
bearH = oscA0 and oscTop and ((osc > ta.valuewhen(oscA0 and oscTop, osc, 1) and top < ta.valuewhen(oscA0 and oscTop, top, 1)))
= sqz(20, 2, 20, 2, close)
= qqe(6, 6, 3, close, 50, 0.001)
= qqe(6, 5, 1.618, close, 50, 1)
= ta.dmi(14, 14)
[osc , oscRis , oscFal , oscA0 , oscB0 , oscTop , oscBot , bullR , bearR , bullH , bearH , sqzOn , sqzOff , _hist1 , upper1 , lower1 , _hist2 , _line2 , tvr ]
tf = indicatorTF == "Chart" ? timeframe.period : indicatorTF == "1 minute" ? "1" : indicatorTF == "3 minutes" ? "3" : indicatorTF == "5 minutes" ? "5" : indicatorTF == "10 minutes" ? "10" : indicatorTF == "15 minutes" ? "15" : indicatorTF == "30 minutes" ? "30" : indicatorTF == "45 minutes" ? "45" : indicatorTF == "1 hour" ? "60" : indicatorTF == "2 hours" ? "120" : indicatorTF == "3 hours" ? "180" : indicatorTF == "4 hours" ? "240" : indicatorTF == "12 hours" ? "720" : indicatorTF == "1 day" ? "1D" : indicatorTF == "1 week" ? "1W" : indicatorTF == "1 month" ? "1M" : na
= request.security(syminfo.tickerid, tf, cond(indicatorTF != "Chart" and barstate.isrealtime ? 1 : 0))
//colorTVR = tvr < 15 ? #F6525F : tvr > 15 and tvr < 25 ? #B2B5BE : #66BB6A
// Plots
//plot(Presets == "Money Moves TrendVR" ? tvr : na, "", colorTVR, editable=false)
TrendText = "Trending"
if tvr < 15 and tvr < 25
TrendText := "No trend"
if tvr > 15 and tvr < 25
TrendText := "Ranging"
//------------------------------------------------------------------------------------------------------- Volatitiry
//Calculates Volatility for Dashboard
atrr = 3 * ta.atr(10)
stdAtr = 2 * ta.stdev(atrr, 20)
smaAtr = ta.sma(atrr, 20)
topAtrDev = smaAtr + stdAtr
bottomAtrDev = smaAtr - stdAtr
calcDev = (atrr - bottomAtrDev) / (topAtrDev - bottomAtrDev)
percentVol = 40 * calcDev + 30
AvrLength = 21
PercentFilter = 144
xAavrVolume = ta.rma(volume, AvrLength)
nResLess = volume * 100 / xAavrVolume < PercentFilter ? 0 : volume
nRes = nResLess
clr = close < open ? #b2b5be : #00dbff
//plot(nRes, color=clr, style=plot.style_columns, title='Volume Filter', transp=20)
VolitiText = "Inactive"
if nRes
VolitiText := "Active"
//////////////////////////////////////////
ema69 = ta.ema(close, 9)
totalSentTxt = ema69 > ema69 ? 'Bullish' : ema69 < ema69 ? 'Bearish' : 'Flat'
// INputs
//Timezones
tz_incr = 0
use_exchange = false
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//Session A
NYSes = true
NYTxt = 'New York'
NYTime = '1300-2200'
//Session B
LDSes = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
//Session C
show_sesc = true
sesc_txt = 'Tokyo'
sesc_ses = '0000-0900'
//Session D
show_sesd = true
sesd_txt = 'Sydney'
sesd_ses = '2100-0600'
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tff = timeframe.period
var tz = use_exchange ? syminfo.timezone :
str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))
is_sesa = math.sign(nz(time(tff, NYTime, tz)))
is_sesb = math.sign(nz(time(tff, sesb_ses, tz)))
is_sesc = math.sign(nz(time(tff, sesc_ses, tz)))
is_sesd = math.sign(nz(time(tff, sesd_ses, tz)))
////////////////////////////////////////////
SessionText = "Default"
if is_sesd
SessionText := sesd_txt
if is_sesc
SessionText := sesc_txt
if is_sesb
SessionText := sesb_txt
if is_sesa
SessionText := NYTxt
if is_sesd and is_sesc
SessionText := "Sydney/Tokyo"
if is_sesb and is_sesc
SessionText := "Tokyo/London"
if is_sesb and is_sesa
SessionText := "London/Newyork"
if is_sesa and is_sesd
SessionText := "Newyork/Sydney"
//-----------------------------------------------------------------------------}
//Overlays color.green : color.red
//
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard = showDashboard ? table.new(dashboard_loc, 3, 7, color.rgb(0, 0, 0, 60), #3d384300, 2, color.rgb(30, 34, 45 , 60), 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column, row, txt, 0, 0, signal ? #000000 : color.white, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
if barstate.islast and showDashboard
// MTF Trend
dashboard_cell(0, 0 , "MTF")
dashboard_cell(0, 2 , "M5") , dashboard_cell_bg(0, 2 , TF5Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 3 , "M15") , dashboard_cell_bg(0, 3 , TF15Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 4 , "M30") , dashboard_cell_bg(0, 4 , TF30Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 5 , "1H") , dashboard_cell_bg(0, 5 , TF60Bull ? color.rgb(70, 153, 67) : #880000)
dashboard_cell(0, 6 , "4H") , dashboard_cell_bg(0, 6 , TF240Bull ? color.rgb(70, 153, 67) : #880000)
// Middel part
dashboard_cell(1, 0 , "PoseidonPips")
dashboard_cell(1, 2 , "Market State")
dashboard_cell(1, 3 , "Volatility")
dashboard_cell(1, 4 , "Institutional Activity")
dashboard_cell(1, 5 , "Current Session (UTC)")
dashboard_cell(1, 6 , "Trend Pressure")
// End part
dashboard_cell(2, 0 , "")
dashboard_cell(2, 2 , TrendText)
dashboard_cell(2, 3 , str.tostring(percentVol, '##.##') + '%')
dashboard_cell(2, 4 , VolitiText)
dashboard_cell(2, 5 , SessionText)
dashboard_cell(2, 6 , totalSentTxt)
// Alerts
// Cross Functions for SL and TP
f_sl_crossed() =>
ret = false
crossBull = low >= ta.lowest(low, 5) and low < ta.lowest(low, 5)
crossBear = high <= ta.highest(high, 5) and high > ta.highest(high, 5)
ret := trigger ? crossBull : crossBear
ret
f_tp_crossed(tp) =>
ret = false
crossBull = high <= tp and high > tp
crossBear = low >= tp and low < tp
ret := trigger ? crossBull : crossBear
ret
// Alert Conditions
alert04 = bull and close <= StrongFilter
alert07 = bull and close > StrongFilter
alert09 = f_sl_crossed()
alert11 = f_tp_crossed(60.0)
alert12 = f_tp_crossed(80.0)
alert13 = f_tp_crossed(100.0)
alert14 = periodTrendCloud == "Smooth" ? ta.crossunder(ema150, ema250) : (close < trendcloud) and (close > trendcloud )
alert15 = periodTrendCloud == "Smooth" ? ta.crossover(ema150, ema250) : (close > trendcloud) and (close < trendcloud )
// Signal Alerts
if alert04 and Normalbuy_alert
alert('Buy Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert07 and Strongbuy_alert
alert('Strong Buy Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if (bear and close >= StrongFilter) and Normalsell_alert
alert('Sell Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if (bear and close < StrongFilter) and Strongsell_alert
alert('Strong Sell Signal Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Risk Management Alerts
if alert09 and slalert
alert('SL Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert11 and tp1alert
alert('Target 1 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert12 and tp2alert
alert('Target 2 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert13 and tp3alert
alert('Target 3 Alert !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Cloud Alerts
if alert15 and bullcrosscloud_alert
alert('Cloud Turned Bullish !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
if alert14 and bearcrosscloud_alert
alert('Cloud Turned Bearish !!!', alert.freq_once_per_bar_close)
alert(syminfo.tickerid)
// Alert Conditions for TradingView
alertcondition(alert04, "Normal Buy Alert", "Normal Buy Signal")
alertcondition(alert07, "Strong Buy Alert", "Strong Buy Signal")
alertcondition((bear and close >= StrongFilter), "Normal Sell Alert", "Normal Sell Signal")
alertcondition((bear and close < StrongFilter), "Strong Sell Alert", "Strong Sell Signal")
alertcondition(alert09, "SL Crossed Alert", "Stop Loss Crossed")
alertcondition(alert11, "TP1 Crossed Alert", "Target 1 Crossed")
alertcondition(alert12, "TP2 Crossed Alert", "Target 2 Crossed")
alertcondition(alert13, "TP3 Crossed Alert", "Target 3 Crossed")
// Input
fastLength = 12
slowLength = 26
srcceed = close
signalLength = 9
// Data reference
= ta.macd(srcceed, fastLength, slowLength, signalLength)
// 4 level of green
greenHighh = #7bff00
greenMidHighh = #7bff00
greenMidLowh = #7bff00
greenLowh = #7bff00
// Yellow
yellowLowh = #693d8e
// 4 level of red
redHighh = #ff0000
redMidHighh = #ff0000
redMidLowh = #ff0000
redLowh = #ff0000
// Default color
candleBodyd = yellowLowh
// Ranging trend
if hist > 0
if hist > hist and hist > 0
candleBodyd := greenLowh
if hist < 0
if hist < hist and hist < 0
candleBodyd := redLowh
// Bullish trend
if macdda > 0 and hist > 0
candleBodyd := greenMidLowh
if hist > hist and macd > 0 and hist > 0
candleBodyd := greenMidHighh
if hist > hist and macd > 0 and hist > 0
candleBodyd := greenHighh
// Bearish trend
if macdda < 0 and hist < 0
candleBodyd := redMidLowh
if hist < hist and macd < 0 and hist < 0
candleBodyd := redMidHighh
if hist < hist and macd < 0 and hist < 0
candleBodyd := redHighh
barcolor(candleBodyd) // Include suggestion by Shaheen204
//
tenkan_len = 365
tenkan_mult = 3
kijun_len = 365
kijun_mult = 7
spanB_len = 365
spanB_mult = 10
offset = 1
//------------------------------------------------------------------------------
avg(src,length,mult)=>
atr = ta.atr(50)*mult
up = hl2 + atr
dn = hl2 - atr
upper = 0.,lower = 0.
upper := src < upper ? math.min(up,upper ) : up
lower := src > lower ? math.max(dn,lower ) : dn
os = 0,max = 0.,min = 0.
os := src > upper ? 1 : src < lower ? 0 : os
spt = os == 1 ? lower : upper
max := ta.cross(src,spt) ? math.max(src,max ) : os == 1 ? math.max(src,max ) : spt
min := ta.cross(src,spt) ? math.min(src,min ) : os == 0 ? math.min(src,min ) : spt
math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Smart Money Concept
settings = "Settings"
zigzag_len = input.int(9, "ZigZag Length", group=settings)
show_zigzag = input.bool(false, "Show Zigzag", group=settings)
fib_factor = input.float(0.33, "Fib Factor for breakout confirmation", 0, 1, 0.01, group=settings)
text_size = input.string(size.tiny, "Text Size", , group=settings)
delete_boxes = input.bool(true, "Delete Old/Broken Boxes", group=settings)
bu_ob_inline_color = "Bu-OB Colors"
be_ob_inline_color = "Be-OB Colors"
bu_bb_inline_color = "Bu-BB Colors"
be_bb_inline_color = "Be-BB Colors"
bu_ob_display_settings = "Bu-OB Display Settings"
bu_ob_color = input.color(color.new(color.green, 70), "Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_border_color = input.color(color.green, "Border Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_text_color = input.color(color.green, "Text Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
be_ob_display_settings = "Be-OB Display Settings"
be_ob_color = input.color(color.new(color.red, 70), "Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_border_color = input.color(color.red, "Border Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_text_color = input.color(color.red, "Text Color", group=be_ob_display_settings, inline=be_ob_inline_color)
bu_bb_display_settings = "Bu-BB & Bu-MB Display Settings"
bu_bb_color = input.color(color.new(color.green, 70), "Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_border_color = input.color(color.green, "Border Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_text_color = input.color(color.green, "Text Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
be_bb_display_settings = "Be-BB & Be-MB Display Settings"
be_bb_color = input.color(color.new(color.red, 70), "Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_border_color = input.color(color.red, "Border Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_text_color = input.color(color.red, "Text Color", group=be_bb_display_settings, inline=be_bb_inline_color)
var float high_points_arr = array.new_float(5)
var int high_index_arr = array.new_int(5)
var float low_points_arr = array.new_float(5)
var int low_index_arr = array.new_int(5)
var box bu_ob_boxes = array.new_box(5)
var box be_ob_boxes = array.new_box(5)
var box bu_bb_boxes = array.new_box(5)
var box be_bb_boxes = array.new_box(5)
to_up = high >= ta.highest(zigzag_len)
to_down = low <= ta.lowest(zigzag_len)
trend = 1
trend := nz(trend , 1)
trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend
last_trend_up_since = ta.barssince(to_up )
low_val = ta.lowest(nz(last_trend_up_since > 0 ? last_trend_up_since : 1, 1))
low_index = bar_index - ta.barssince(low_val == low)
last_trend_down_since = ta.barssince(to_down )
high_val = ta.highest(nz(last_trend_down_since > 0 ? last_trend_down_since : 1, 1))
high_index = bar_index - ta.barssince(high_val == high)
if ta.change(trend) != 0
if trend == 1
array.push(low_points_arr, low_val)
array.push(low_index_arr, low_index)
if trend == -1
array.push(high_points_arr, high_val)
array.push(high_index_arr, high_index)
f_get_high(ind) =>
f_get_low(ind) =>
f_delete_box(box_arr) =>
if delete_boxes
box.delete(array.shift(box_arr))
else
array.shift(box_arr)
0
= f_get_high(0)
= f_get_high(1)
= f_get_low(0)
= f_get_low(1)
if ta.change(trend) != 0 and show_zigzag
if trend == 1
line.new(h0i, h0, l0i, l0)
if trend == -1
line.new(l0i, l0, h0i, h0)
market = 1
market := nz(market , 1)
// market := market == 1 and close < l0 and low < l0 - math.abs(h0 - l0) * fib_factor ? -1 : market == -1 and close > h0 and high > h0 + math.abs(h0 - l0) * fib_factor ? 1 : market
last_l0 = ta.valuewhen(ta.change(market) != 0, l0, 0)
last_h0 = ta.valuewhen(ta.change(market) != 0, h0, 0)
market := last_l0 == l0 or last_h0 == h0 ? market : market == 1 and l0 < l1 and l0 < l1 - math.abs(h0 - l1) * fib_factor ? -1 : market == -1 and h0 > h1 and h0 > h1 + math.abs(h1 - l0) * fib_factor ? 1 : market
bu_ob_index = bar_index
bu_ob_index := nz(bu_ob_index , bar_index)
for i=h1i to l0i
index = bar_index - i
if open > close
bu_ob_index := bar_index
bu_ob_since = bar_index - bu_ob_index
be_ob_index = bar_index
be_ob_index := nz(be_ob_index , bar_index)
for i=l1i to h0i
index = bar_index - i
if open < close
be_ob_index := bar_index
be_ob_since = bar_index - be_ob_index
be_bb_index = bar_index
be_bb_index := nz(be_bb_index , bar_index)
for i=h1i - zigzag_len to l1i
index = bar_index - i
if open > close
be_bb_index := bar_index
be_bb_since = bar_index - be_bb_index
bu_bb_index = bar_index
bu_bb_index := nz(bu_bb_index , bar_index)
for i=l1i - zigzag_len to h1i
index = bar_index - i
if open < close
bu_bb_index := bar_index
bu_bb_since = bar_index - bu_bb_index
if ta.change(market) != 0
if market == 1
line.new(h1i, h1, h0i, h1, color=color.green, width=1)
label.new(int(math.avg(h1i, l0i)), h1, "BoS", color=color.new(color.black, 100), style=label.style_label_down, textcolor=color.green, size=size.small)
bu_ob = box.new(bu_ob_index, high , bar_index + 10, low , bgcolor=bu_ob_color, border_color=bu_ob_border_color, text="Bu-OB", text_color=bu_ob_text_color, text_halign=text.align_right, text_size=text_size)
bu_bb = box.new(bu_bb_index, high , bar_index + 10, low , bgcolor=bu_bb_color, border_color=bu_bb_border_color, text=l0 < l1 ? "Bu-BB" : "Bu-MB", text_color=bu_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(bu_ob_boxes, bu_ob)
array.push(bu_bb_boxes, bu_bb)
if market == -1
line.new(l1i, l1, l0i, l1, color=color.red, width=1)
label.new(int(math.avg(l1i, h0i)), l1, "BoS", color=color.new(color.black, 100), style=label.style_label_up, textcolor=color.red, size=size.small)
be_ob = box.new(be_ob_index, high , bar_index + 10, low , bgcolor=be_ob_color, border_color=be_ob_border_color, text="Be-OB", text_color=be_ob_text_color, text_halign=text.align_right, text_size=text_size)
be_bb = box.new(be_bb_index, high , bar_index + 10, low , bgcolor=be_bb_color, border_color=be_bb_border_color, text=h0 > h1 ? "Be-BB" : "Be-MB", text_color=be_bb_text_color, text_halign=text.align_right, text_size=text_size)
array.push(be_ob_boxes, be_ob)
array.push(be_bb_boxes, be_bb)
for bull_ob in bu_ob_boxes
bottom = box.get_bottom(bull_ob)
top = box.get_top(bull_ob)
if close < bottom
f_delete_box(bu_ob_boxes)
else if close < top
alert("Price in the BU-OB zone")
else
box.set_right(bull_ob, bar_index + 10)
for bear_ob in be_ob_boxes
top = box.get_top(bear_ob)
bottom = box.get_bottom((bear_ob))
if close > top
f_delete_box(be_ob_boxes)
if close > bottom
alert("Price in the BE-OB zone")
else
box.set_right(bear_ob, bar_index + 10)
for bear_bb in be_bb_boxes
top = box.get_top(bear_bb)
bottom = box.get_bottom(bear_bb)
if close > top
f_delete_box(be_bb_boxes)
else if close > bottom
alert("Price in the BE-BB zone")
else
box.set_right(bear_bb, bar_index + 10)
for bull_bb in bu_bb_boxes
bottom = box.get_bottom(bull_bb)
top = box.get_top(bull_bb)
if close < bottom
f_delete_box(bu_bb_boxes)
else if close < top
alert("Price in the BU-BB zone")
else
box.set_right(bull_bb, bar_index + 10)
alertcondition(ta.change(market) != 0, "MSB", "MSB")
enableAutoTrend = input(true, "Enable Auto Trendlines", group="AUTO TRENDLINES SETTINGS")
srcTrendChannel = input(close, "Trend channel source", group="AUTO TRENDLINES SETTINGS")
lenTrendChannel = input.int(50, "Trend channel loopback", 2, group="AUTO TRENDLINES SETTINGS")
a = ta.wma(srcTrendChannel, lenTrendChannel), b = ta.sma(srcTrendChannel, lenTrendChannel)
A = 4 * b - 3 * a, B = 3 * a - 2 * b
m = (A - B) / (lenTrendChannel - 1)
d = 0., for i = 0 to lenTrendChannel - 1 by 1
l = B + m * i
d += math.pow(srcTrendChannel - l, 2)
rmse = math.sqrt(d / (lenTrendChannel - 1)) * 2
l(css, k) =>
line lr = enableAutoTrend ? line.new(bar_index - lenTrendChannel + 1, A + k, bar_index, B + k, extend=extend.right, color=css) : na
line.delete(lr )
l(#808080, rmse), l(#808080, 0), l(#808080,-rmse)
// ==========================================================================================
// === Dashboard with Telegram Link ===
var table myTable = table.new(position.top_center, 1, 1, border_width=1, frame_color=color.black, bgcolor=color.white)
// Add Telegram Message to Dashboard
table.cell(myTable, 0, 0, "Join Telegram @KING OF BTC VIP", bgcolor=color.blue, text_color=color.white, text_size=size.normal)
$INDIBOT STRATEGY ABO SALTAN $//@version=5
indicator(title = '$INDIBOT STRATEGY$', overlay = true, max_labels_count=500, max_lines_count=200, max_boxes_count=200)
//INPUTS
srcParams = 'Pivot Source | Left Length | Right Length'
srcH = input.source(high, title = 'High', inline = 'Pivot High', group = srcParams)
leftLenH = input.int(title = '', defval = 4, minval = 0, inline = 'Pivot High', group = srcParams)
rightLenH = input.int(title = '', defval = 2, minval = 0, inline = 'Pivot High', group = srcParams)
colorH = input.color(title = '', defval = color.new(color.teal, 50), inline = 'Pivot High', group = srcParams)
srcL = input.source(low, title = 'Low', inline = 'Pivot Low', group = srcParams)
leftLenL = input.int(title = '', defval = 4, minval = 0, inline = 'Pivot Low', group = srcParams)
rightLenL = input.int(title = '', defval = 2, minval = 0, inline = 'Pivot Low', group = srcParams)
colorL = input.color(title = '', defval = color.new(color.red, 50), inline = 'Pivot Low', group = srcParams)
markDisplay = 'Pivots Markers'
tip2 = "Higher High Lower High Higher Low Lower Low"
showhh = input.bool(false, 'Show HH LH HL LL', inline = '1', group = markDisplay, tooltip = tip2)
// showlh = input.bool(true, 'Lower High', inline = '1', group = markDisplay)
// showhl = input.bool(true, 'Higher Low', inline = '1', group = markDisplay)
// showll = input.bool(true, 'Lower Low', inline = '1', group = markDisplay)
settings = 'Others'
maxBarsBack = input.int(0, 'Maximum Bars to Display (0 = All)', minval = 0, group = settings)
string GROUP_PLS = 'Labels'
bool showLabelsPriceScaleInput = input.bool(false, 'Show Labels on Price Scale.', tooltip="", group=GROUP_PLS)
// options
labelDisplay = showLabelsPriceScaleInput ? display.all : display.pane // , editable = false, display=labelDisplay)
// Get High and Low Pivot Points
ph = ta.pivothigh(srcH, leftLenH, rightLenH)
pl = ta.pivotlow(srcL, leftLenL, rightLenL)
// Higher Highs, Lower Highs, Higher Lows, Lower Lows
ph_value = srcH
pl_value = srcL
valuewhen_1 = ta.valuewhen(not na(ph), ph_value, 1)
valuewhen_2 = ta.valuewhen(not na(ph), ph_value, 0)
higherhigh = na(ph) ? na : valuewhen_1 < valuewhen_2 ? ph : na
lowerhigh = na(ph) ? na : valuewhen_1 > valuewhen_2 ? ph : na
valuewhen_3 = ta.valuewhen(not na(pl), pl_value, 1)
valuewhen_4 = ta.valuewhen(not na(pl), pl_value, 0)
higherlow = na(pl) ? na : valuewhen_3 < valuewhen_4 ? pl : na
lowerlow = na(pl) ? na : valuewhen_3 > valuewhen_4 ? pl : na
// Add helper function to check if we should display for current bar
isInDisplayRange() => maxBarsBack == 0 or (bar_index > (last_bar_index - maxBarsBack))
plotshape(showhh and isInDisplayRange() ? higherhigh : na, title = 'HH', style = shape.triangledown, location = location.abovebar, color = colorH, text = 'HH', textcolor = colorH, offset = -rightLenH,display=labelDisplay)
plotshape(showhh and isInDisplayRange() ? higherlow : na, title = 'HL', style = shape.triangleup, location = location.belowbar, color = colorL, text = 'HL', textcolor = colorL, offset = -rightLenH,display=labelDisplay)
plotshape(showhh and isInDisplayRange() ? lowerhigh : na, title = 'LH', style = shape.triangledown, location = location.abovebar, color = colorH, text = 'LH', textcolor = colorH, offset = -rightLenL,display=labelDisplay)
plotshape(showhh and isInDisplayRange() ? lowerlow : na, title = 'LL', style = shape.triangleup, location = location.belowbar, color = colorL, text = 'LL', textcolor = colorL, offset = -rightLenL,display=labelDisplay)
//indicator('ICT PO3 ', overlay=true, max_labels_count=200, max_lines_count=200, max_boxes_count=200)
import Llopezf/Time/1
var grp3 = '***************Show Market Open*************** '
sess1Hour = input.int(1, title='open in hour ', minval=0, maxval=23, inline='0', group=grp3)
sess1Minute = input.int(0, title=' and minute', minval=0, maxval=60, inline='0', group=grp3)
// sess1Show_ver = input.bool(true, title='vertical', inline='1', group=grp3)//
// sess1Show_hor = input.bool(true, title='Horizontal', inline='1', group=grp3)//
// sess1Text = input.string("Session Open ", title='', inline='1', group=grp3)
// sess1Col = input.color(color.red, title='', inline="1", group=grp3)
inSession1 = hour == sess1Hour and minute == sess1Minute and second == 0
var grp4 = '*************** Other Settings ***************'
extendHours = input.int(22, title='Extend Horizontal lines( hours)?', minval=1, maxval=22, group=grp4)
//line_set_style_open=input.string(defval=line.style_dotted, options= ,title='line style' , group=grp4)
// linesWidth = input.int(1, 'Box And Lines Width ?', minval=1, maxval=4, group=grp4)
// _labelSize = input.string("Tiny", title='Label Size', options= , group=grp4)
// labelSize = _labelSize == "auto" ? size.auto : _labelSize == "Tiny" ? size.tiny : _labelSize == "Small" ? size.small : _labelSize == "Normal" ? size.normal : size.huge
color_up = input.color(color.green, title='', inline="1", group=grp4)
color_dn = input.color(color.red, title='', inline="1", group=grp4)
var float open_d=na
var float new_h=na
var float new_l=na
var box candle=na
var line sh_up=na
var line sh_dn=na
var color ca_color=na
_extend = extendHours * 3600000
if inSession1 and not inSession1
open_d:=open
new_h:=open
new_l:=open
// if sess1Show_ver
// line.new(time,open_d,time,2*open_d,extend = extend.both,xloc=xloc.bar_time,style = line_set_style_open,color = sess1Col,width = linesWidth)
// if sess1Show_hor
// line.new(time, open, time + _extend, open, xloc=xloc.bar_time, color=sess1Col, width=linesWidth,style = line_set_style_open)
// label.new(time + _extend, open, sess1Text, xloc=xloc.bar_time, style=label.style_none, size=labelSize, textcolor=sess1Col)
if low < new_l
new_l := low
new_l
if high > new_h
new_h := high
new_h
if close !=close
ca_color:=close>open_d? color_up:color_dn
box.delete(candle )
candle:=box.new( bar_index+20,open_d ,bar_index+26,close,bgcolor=ca_color,border_color =na)
if close>open_d // رسم شدو بالا
line.delete(sh_up )
line.delete(sh_dn )
sh_up:= line.new(bar_index+23,close,bar_index+23,new_h,width = 2,color = ca_color)
sh_dn:= line.new(bar_index+23,open_d,bar_index+23,new_l,width = 2,color = ca_color)
else
line.delete(sh_up )
line.delete(sh_dn )
sh_up:= line.new(bar_index+23,open_d,bar_index+23,new_h,width = 2,color = ca_color)
sh_dn:= line.new(bar_index+23,close,bar_index+23,new_l,width = 2,color = ca_color)
//indicator("Vela Dividida en Tercios by Leo", overlay=true)
// Inputs para seleccionar la hora y minuto de la vela a analizar
horaSeleccionada = input(8, "Hora (24h)")
minutoSeleccionado = input(45, "Minuto")
// Input para seleccionar la diferencia horaria con respecto a UTC
diferenciaUTC = input.int(-8, "Diferencia UTC (horas)", minval=-12, maxval=14)
// Inputs para colores de cada tercio
colorTercio1 = input.color(color.rgb(218, 185, 51, 80), "Color Primer Tercio")
colorTercio2 = input.color(color.rgb(33, 149, 243, 80), "Color Segundo Tercio")
colorTercio3 = input.color(color.rgb(255, 82, 82, 80), "Color Tercer Tercio")
// Obtener la hora y minuto de la vela actual ajustados a UTC
horaActual = hour(time) + diferenciaUTC
if horaActual < 0
horaActual := horaActual + 24
if horaActual >= 24
horaActual := horaActual - 24
minutoActual = minute(time)
// Detectar la vela seleccionada
esVelaSeleccionada = (horaActual == horaSeleccionada and minutoActual == minutoSeleccionado)
// Variables para almacenar los valores de la vela seleccionada
var float highVela = na
var float lowVela = na
var float tercio = na
if esVelaSeleccionada
highVela := high
lowVela := low
tercio := (highVela - lowVela) / 3
// Dibujar las áreas de cada tercio solo en la vela seleccionada
if esVelaSeleccionada and not na(tercio)
box.new(left=int(bar_index - 1), right=int(bar_index + 2), top=highVela, bottom=highVela - tercio, border_width=0, bgcolor=colorTercio1)
box.new(left=int(bar_index - 1), right=int(bar_index + 2), top=highVela - tercio, bottom=highVela - 2 * tercio, border_width=0, bgcolor=colorTercio2)
box.new(left=int(bar_index - 1), right=int(bar_index + 2), top=highVela - 2 * tercio, bottom=lowVela, border_width=0, bgcolor=colorTercio3)
//indicator("Trend Levels by Leo", overlay=true)
// Settings
showTrendLevels = input(true, "Show Trend Levels", group='Channel')
mult2 = input.float(15, 'Factor', minval=0, group='Channel')
slope = input.float(50, title='Slope', minval=0, group='Channel') * mult2
// Style
colUp = input.color(#089981, ' ', inline='color', group='Colors')
colMa = input.color(#787b86, ' ', inline='color', group='Colors')
colDn = input.color(#f23645, ' ', inline='color', group='Colors')
color colUp1 = color.new(colUp, 50)
color colUp2 = color.new(colUp, 0)
color avgCss = color.new(colMa, 0)
color colDn1 = color.new(colDn, 0)
color colDn2 = color.new(colDn, 50)
// Calculation
var float pc_avg = close
var int os = 1
var float hold_atr = 0.
atr = nz(ta.atr(200)) * mult2
pc_avg := math.abs(close - pc_avg) > atr ? close : pc_avg + os * hold_atr / slope
hold_atr := pc_avg == close ? atr / 2 : hold_atr
os := pc_avg > pc_avg ? 1 : pc_avg < pc_avg ? -1 : os
pc_R2 = showTrendLevels ? pc_avg + hold_atr : na
pc_R1 = showTrendLevels ? pc_avg + hold_atr / 2 : na
pc_S1 = showTrendLevels ? pc_avg - hold_atr / 2 : na
pc_S2 = showTrendLevels ? pc_avg - hold_atr : na
pc_avg_plot = showTrendLevels ? pc_avg : na
// Plot channels
plot(pc_R2, 'Upper Resistance', color=colDn1,display=labelDisplay)
plot(pc_R1, 'Lower Resistance', color=colDn2,display=labelDisplay)
plot(pc_avg_plot, 'Average', color=avgCss,display=labelDisplay)
plot(pc_S1, 'Upper Support', color=colUp1,display=labelDisplay)
plot(pc_S2, 'Lower Support', color=colUp2,display=labelDisplay)
//indicator('OSTDV by Leo', overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// Time zone input
int time_zone_offset = input.int(-5, 'Time Zone Offset (UTC+/-)', minval = -12, maxval = 14, tooltip = 'Enter the UTC offset for your timezone. For example, UTC-4 would be -4, UTC+5 would be 5')
// Input variables
int session_start_hour = input.int(19, 'Session Start Time', minval = 0, maxval = 23, tooltip = 'Hour in your selected timezone')
int session_start_minute = input.int(0, 'Session Start Minute', minval = 0, maxval = 59)
int session_end_hour = input.int(22, 'Session End Time', minval = 0, maxval = 23, tooltip = 'Hour in your selected timezone')
int session_end_minute = input.int(3, 'Session End Minute', minval = 0, maxval = 59)
int fib_line_width = input.int(1, 'Fibonacci Line Width', minval = 1, maxval = 5)
int line_offset = input.int(10, 'Distance of label from the fib', minval = 1, maxval = 500)
// Background color input
color background_color = input(color.new(#b39ddb, 100))
// Initialize arrays for fib levels, labels, and colors
var array fib_levels = array.new_float()
var array fib_labels_text = array.new_string()
var array fib_colors = array.new_color()
// Function to reset fib levels and labels at the beginning of each session
resetFibLevelsAndLabels() =>
array.clear(fib_levels)
array.clear(fib_labels_text)
array.clear(fib_colors)
// Extreme levels
array.push(fib_levels, 5.0)
array.push(fib_labels_text, 'extreme')
array.push(fib_colors, #E91E63) // Pink
array.push(fib_levels, 4.5)
array.push(fib_labels_text, '')
array.push(fib_colors, #E91E63) // Pink
// SMR level
array.push(fib_levels, 4.0)
array.push(fib_labels_text, 'smr')
array.push(fib_colors, color.black) // Black
// X level
array.push(fib_levels, 3.5)
array.push(fib_labels_text, 'x')
array.push(fib_colors, #FF9800) // Orange
// Micro SMR level
array.push(fib_levels, 3.272)
array.push(fib_labels_text, 'micro smr')
array.push(fib_colors, #FF9800) // Orange
array.push(fib_levels, 3.0)
array.push(fib_labels_text, '')
array.push(fib_colors, #FF9800) // Orange
// CV level
array.push(fib_levels, 2.5)
array.push(fib_labels_text, 'lv')
array.push(fib_colors, color.gray) // Gray
// SB level
array.push(fib_levels, 2.0)
array.push(fib_labels_text, 'sb')
array.push(fib_colors, color.black) // Black
// Retracement level
array.push(fib_levels, 1.5)
array.push(fib_labels_text, 'retracement')
array.push(fib_colors, #00BCD4) // Cyan
array.push(fib_levels, 1.1111)
array.push(fib_labels_text, '')
array.push(fib_colors, #FFCDD2) // Light Pink
array.push(fib_levels, 1.0)
array.push(fib_labels_text, '')
array.push(fib_colors, color.silver) // Light Gray
array.push(fib_levels, 0.62)
array.push(fib_labels_text, '')
array.push(fib_colors, #FF9800) // Orange
array.push(fib_levels, 0.5)
array.push(fib_labels_text, '')
array.push(fib_colors, #00BCD4) // Cyan
array.push(fib_levels, 0.0)
array.push(fib_labels_text, '')
array.push(fib_colors, color.gray) // Gray with pattern
array.push(fib_levels, -0.1111)
array.push(fib_labels_text, '')
array.push(fib_colors, #FFCDD2) // Light Pink
// Retracement level
array.push(fib_levels, -0.5)
array.push(fib_labels_text, 'retracement')
array.push(fib_colors, #00BCD4) // Cyan
// SB level
array.push(fib_levels, -1.0)
array.push(fib_labels_text, 'sb')
array.push(fib_colors, color.black) // Black
// Micro SMR level
array.push(fib_levels, -2.0)
array.push(fib_labels_text, 'micro smr')
array.push(fib_colors, #FF9800) // Orange
array.push(fib_levels, -2.272)
array.push(fib_labels_text, '')
array.push(fib_colors, #FF9800) // Orange
// X level
array.push(fib_levels, -2.5)
array.push(fib_labels_text, 'x')
array.push(fib_colors, #FF9800) // Orange
// SMR level
array.push(fib_levels, -3.0)
array.push(fib_labels_text, 'smr')
array.push(fib_colors, color.black) // Black
// Extreme level
array.push(fib_levels, -3.5)
array.push(fib_labels_text, '')
array.push(fib_colors, #E91E63) // Pink
array.push(fib_levels, -4.0)
array.push(fib_labels_text, 'extreme')
array.push(fib_colors, #E91E63) // Pink
// Function to determine if the current bar is within the session
isSession(int current_hour, int current_minute, int startHour, int startMinute, int endHour, int endMinute) =>
float current_time = current_hour + current_minute / 60.0
float start_time = startHour + startMinute / 60.0
float end_time = endHour + endMinute / 60.0
start_time < end_time ? (current_time >= start_time and current_time < end_time) : (current_time >= start_time or current_time < end_time)
// Convert UTC time to the user-selected time zone
int current_hour_custom_tz = (hour(time) + time_zone_offset) % 24
// Handle negative hours by adding 24
current_hour_custom_tz := current_hour_custom_tz < 0 ? current_hour_custom_tz + 24 : current_hour_custom_tz
int current_minute = minute(time)
bool in_session = isSession(current_hour_custom_tz, current_minute, session_start_hour, session_start_minute, session_end_hour, session_end_minute)
// Background color for session
bgcolor(in_session ? background_color : na)
var float session_high = na
var float session_low = na
var int session_bars = 0
var bool session_processed = false
var int last_session_end_bar = 0
var float last_session_high = na
var float last_session_low = na
var int last_session_bars = 0
// Store the Fibonacci lines and labels in variables to manage them
var array fib_lines = array.new_line()
var array fib_labels = array.new_label()
// Function to create a label at the center of the line
createLabel(price, labelText, labelColor) =>
label.new(bar_index - int(last_session_bars / 2) + line_offset, price, text = labelText, style = label.style_label_center, color = color.new(color.white, 100), size = size.small, textcolor = labelColor)
// Clear all previous lines and labels
clearAllLinesAndLabels() =>
while array.size(fib_lines) > 0
line.delete(array.pop(fib_lines))
while array.size(fib_labels) > 0
label.delete(array.pop(fib_labels))
// Script logic for monitoring sessions and drawing Fibonacci levels
if barstate.isnew
if in_session
// In session: track session high, low, and bar count
session_high := na(session_high) ? high : math.max(high, session_high)
session_low := na(session_low) ? low : math.min(low, session_low)
session_bars := session_bars + 1
session_processed := false
else if not in_session and not session_processed and not na(session_high) and not na(session_low) and session_bars > 0
// Session just ended: save its data for drawing
last_session_high := session_high
last_session_low := session_low
last_session_bars := session_bars
last_session_end_bar := bar_index - 1
// Clear previous drawings and reset for new drawings
clearAllLinesAndLabels()
// Reset fib levels and labels
resetFibLevelsAndLabels()
// Calculate session range and midpoint
float session_range = last_session_high - last_session_low
float session_midpoint = (last_session_high + last_session_low) / 2
// Calculate the start index of the session
int session_start_index = last_session_end_bar - last_session_bars + 1
// Draw Fibonacci lines and create labels for the latest closed session only
for i = 0 to array.size(fib_levels) - 1
float level = array.get(fib_levels, i)
float fibPrice = session_midpoint + (level - 0.5) * session_range
color levelColor = array.get(fib_colors, i)
// Create lines from session start to session end (not extending right)
line fibLine = line.new(session_start_index, fibPrice, last_session_end_bar, fibPrice,
width = fib_line_width, color = levelColor)
// Create labels
label fibLabel = createLabel(fibPrice, array.get(fib_labels_text, i), levelColor)
array.push(fib_lines, fibLine)
array.push(fib_labels, fibLabel)
// Reset session variables for the next session
session_high := na
session_low := na
session_bars := 0
session_processed := true
//indicator("Clustering Clouds v2", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=350 , max_bars_back = 5000 )
// Get user input
// --------------------------------------------------------------------------------------------------------------------
// VISUAL SETTINGS
// --------------------------------------------------------------------------------------------------------------------
var g_visuals = '🎨 Visual Settings'
themeMode = input.string('Light', 'Color Theme', options = ,
tooltip = 'Select color theme for better visibility in different chart modes', group = g_visuals, display = display.none)
// Dark theme colors - Updated to match FibExtender Pro
var color darkLongColor = #2962FF // Strong blue
var color darkShortColor = #FF6D00 // Orange
var color darkTableText = #ffffff
var color darkTableBg = #1e222d // Darker background
var color darkTableHeader = #2a2e39 // Slightly lighter than background
// Light theme colors - Updated to match style
var color lightLongColor = #0064fe // DARK_BLUE from FibExtender
var color lightShortColor = #10cab8 // TURQUOISE from FibExtender
var color lightTableText = #000000
var color lightTableBg = #f0f3fa // Light background
var color lightTableHeader = #e1e5ef // Slightly darker than background
// Custom colors group
var g_custom = '🎨 Custom Colors'
showCustomColors = themeMode == 'Custom'
// Custom colors with updated names and comprehensive tooltips
customLongColor = input.color(darkLongColor, 'Fast SMA & Long Signal',
tooltip='Color Settings for Strategy Elements: ' +
'• Fast SMA & Long Signal: Color for the faster moving average and long position indicators ' +
'• Slow SMA & Exit: Color for the slower moving average and exit signals',
inline = 'custom1', group = g_custom, display = display.none)
customShortColor = input.color(darkShortColor, 'Slow SMA & Exit',
inline = 'custom1', group = g_custom, display = display.none)
customTableText = input.color(darkTableText, 'Table Text',
tooltip='Table Color Settings: ' +
'• Table Text: Color for all text elements in the table ' +
'• Table Background: Main background color for the table cells',
inline = 'custom2', group = g_custom, display = display.none)
customTableBg = input.color(darkTableBg, 'Table Background',
inline = 'custom2', group = g_custom, display = display.none)
customTableHeader = input.color(darkTableHeader, 'Header Background',
tooltip='Color for table header and footer sections',
group = g_custom, display = display.none)
// Function to get theme colors
getThemeColors() =>
color longColor = switch themeMode
'Dark' => darkLongColor
'Light' => lightLongColor
=> customLongColor
color shortColor = switch themeMode
'Dark' => darkShortColor
'Light' => lightShortColor
=> customShortColor
color tableText = switch themeMode
'Dark' => darkTableText
'Light' => lightTableText
=> customTableText
color tableBg = switch themeMode
'Dark' => darkTableBg
'Light' => lightTableBg
=> customTableBg
color tableHeader = switch themeMode
'Dark' => darkTableHeader
'Light' => lightTableHeader
=> customTableHeader
= getThemeColors()
enableDashboard = input(true, "Enable Dashboard", group="DASHBOARD SETTINGS")
locationDashboard = input.string("Bottom right", "Location", , group="DASHBOARD SETTINGS")
sizeDashboard = input.string("Tiny", "Size", , group="DASHBOARD SETTINGS")
colorBackground = input(#ffffff, "Bg color", group="DASHBOARD SETTINGS")
colorFrame = input(#000000, "Frame color", group="DASHBOARD SETTINGS")
colorBorder = input(#ffffff, "Border color", group="DASHBOARD SETTINGS")
showSignals = input(true, "Show signals", group="BUY AND SELL SIGNALS SETTINGS")
strategy = input.string("Normal", "Strategy", , group="BUY AND SELL SIGNALS SETTINGS")
sensitivity = input.float(5, "Sensitivity", 0.1, step=0.1, group="BUY AND SELL SIGNALS SETTINGS")
consSignalsFilter = input(false, "Consolidation signals filter", group="BUY AND SELL SIGNALS SETTINGS")
StrongSignalsOnly = input(false, "Strong signals only", group="BUY AND SELL SIGNALS SETTINGS")
candleColors = input(false, "Candle colors", group="BUY AND SELL SIGNALS SETTINGS")
momentumCandles = input(false, "Momentum candles", group="BUY AND SELL SIGNALS SETTINGS")
highVolSignals = input(false, "High volume signals only", group="BUY AND SELL SIGNALS SETTINGS")
enableTrailingSL = input(false, "Enable trailing stop-loss", group="RISK MANAGEMENT SETTINGS")
usePercSL = input(false, "% Trailing sl", inline="2", group="RISK MANAGEMENT SETTINGS")
percTrailingSL = input.float(1, "", 0, step=0.1, inline="2", group="RISK MANAGEMENT SETTINGS")
enableSwings = input(false, "Enable Swing High's & Swing's Low's", inline="3", group="RISK MANAGEMENT SETTINGS")
periodSwings = input.int(10, "", 2, inline="3", group="RISK MANAGEMENT SETTINGS")
enableTpSlAreas = input(true, "Enable take profit/stop-loss areas", group="RISK MANAGEMENT SETTINGS")
useTP1 = input(true, "", inline="4", group="RISK MANAGEMENT SETTINGS")
multTP1 = input.float(1, "TP 1", 0, inline="4", group="RISK MANAGEMENT SETTINGS")
useTP2 = input(true, "", inline="5", group="RISK MANAGEMENT SETTINGS")
multTP2 = input.float(2, "TP 2", 0, inline="5", group="RISK MANAGEMENT SETTINGS")
useTP3 = input(true, "", inline="6", group="RISK MANAGEMENT SETTINGS")
multTP3 = input.float(3, "TP 3", 0, inline="6", group="RISK MANAGEMENT SETTINGS")
tpLabels = true //input(true, "Take profit labels", group="RISK MANAGEMENT SETTINGS")
tslLabels = input(false, "Enable Trailing Stoploss", group="RISK MANAGEMENT SETTINGS")
showTrendCloud = input(true, "Show Trend cloud", group="TREND CLOUD SETTINGS")
periodTrendCloud = input.string("New", "Trend cloud period", , group="TREND CLOUD SETTINGS")
signalsTrendCloud = input(false, "Trend only signals", group="TREND CLOUD SETTINGS")
fastTrendCloud = input(false, "Fast trend cloud", group="TREND CLOUD SETTINGS")
fastTrendCloudLen = input.int(55, "Fast trend cloud", 2, group="TREND CLOUD SETTINGS")
enableAutoTrend = input(false, "Enable Auto Trendlines", group="AUTO TRENDLINES SETTINGS")
srcTrendChannel = input(close, "Trend channel source", group="AUTO TRENDLINES SETTINGS")
lenTrendChannel = input.int(200, "Trend channel loopback", 2, group="AUTO TRENDLINES SETTINGS")
enableSR = input(false, "Enable support and resistance", group="AUTO SUPPORT AND RESISTANCE SETTINGS")
lineSrStyle = input.string("Dashed", "Line Style", , group="AUTO SUPPORT AND RESISTANCE SETTINGS")
lineSrWidth = input.int(2, "Line Width", 1, 4, group="AUTO SUPPORT AND RESISTANCE SETTINGS")
showCons = input(false, "Consolidation Zones", group="CONSOLIDATION ZONES")
lbPeriod = input.int(10, "Loopback Period", 2, 50, group="CONSOLIDATION ZONES")
lenCons = input.int(5, "Min Consolidation Length", 2, 20, group="CONSOLIDATION ZONES")
paintCons = input(true, "Paint Consolidation Area", group="CONSOLIDATION ZONES")
colorZone = input(color.new(color.blue, 70), "Zone Color", group="CONSOLIDATION ZONES")
box_ob = input.bool(false, "Toggle Order Block", group="ORDER BLOCK")
box_hide_gray = input.bool(false, "Hide gray boxes", group="ORDER BLOCK")
bos_type = input.string("High and Low", "MSB trigger", , group="ORDER BLOCK")
box_sv = input.bool(true, "Plot demand boxes", group="ORDER BLOCK")
box_test_delay = input.int(3, "Delay to count test of demand box", 1, group="ORDER BLOCK")
box_fill_delay = input.int(3, "Delay to count fill of demand box", 1, group="ORDER BLOCK")
box_test_sv = input.bool(true, "Dim tested demand boxes", group="ORDER BLOCK")
box_stop_sv = input.bool(true, "Stop plotting filled demand boxes", group="ORDER BLOCK")
// Functions
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
atr(len) =>
tr = ta.tr
atr = 0.0
atr := nz(atr + (tr - atr ) / len, tr)
supertrend(src, factor, len) =>
atr = ta.atr(len)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or close < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend
if prevSuperTrend == prevUpperBand
direction := close > upperBand ? 1 : -1
else
direction := close < lowerBand ? -1 : 1
superTrend := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
dchannel(len)=>
hh = ta.highest(len)
ll = ta.lowest (len)
trend = 0
trend := close > hh ? 1 : close < ll ? -1 : nz(trend )
trendScalper(show, len1, len2, len3, colorBull, colorBear, colorBarBull, colorBarBear) =>
avgOC = math.avg(open, close)
ha_o = 0.0, ha_o := na(ha_o ) ? avgOC : (ha_o + ohlc4 ) / 2
ema1 = ta.ema(ha_o, len1), ema2 = ta.ema(ha_o, len2), ema3 = ta.ema(ha_o, len3)
ris1 = ema1 > ema1 , ris2 = ema2 > ema2 , ris3 = ema3 > ema3
fal1 = ema1 < ema1 , fal2 = ema2 < ema2 , fal3 = ema3 < ema3
colorEma1 = ris1 ? colorBull : fal1 ? colorBear : na, colorEma2 = ris2 ? colorBull : fal2 ? colorBear : na, colorEma3 = ris3 ? colorBull : fal3 ? colorBear : na
fillEma1 = avgOC > ema1 ? colorBull : avgOC < ema1 ? colorBear : na, fillEma2 = ema1 > ema2 ? colorBull : ema1 < ema2 ? colorBear : na, fillEma3 = ema2 > ema3 ? colorBull : ema2 < ema3 ? colorBear : na
colorBar = close < ema1 and close < ema2 ? colorBarBear : colorBarBull
candlesMom() =>
= ta.macd(close, 12, 26, 9)
(macd > 0 and macd > macd ) or (macd < 0 and macd < macd )
trailingSL(buy, sell, factor, len, usePerc, perc) =>
atr = atr(len)
upperBand = high + (usePerc ? high * (perc / 100) : factor * atr)
lowerBand = low - (usePerc ? low * (perc / 100) : factor * atr)
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or buy ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or sell ? upperBand : prevUpperBand
int direction = na
float stop = na
prevSuperTrend = stop
if prevSuperTrend == prevUpperBand
direction := buy ? 1 : -1
else
direction := sell ? -1 : 1
stop := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
add_to_zz(zz, val, bi) =>
array.unshift(zz, bi)
array.unshift(zz, val)
if array.size(zz) > 12
array.pop(zz)
update_zz(zz, val, bi, dir) =>
if array.size(zz) == 0
add_to_zz(zz, val, bi)
else
if dir == 1 and val > array.get(zz, 0) or dir == -1 and val < array.get(zz, 0)
array.set(zz, 0, val)
array.set(zz, 1, bi)
0
float ph1 = ta.pivothigh(high, 10, 10)
float pl1 = ta.pivotlow (low , 10, 10)
LSRstyle = lineSrStyle == "Dashed" ? line.style_dashed : lineSrStyle == "Solid" ? line.style_solid : line.style_dotted
prdhighest = ta.highest(300)
prdlowest = ta.lowest (300)
cwidth = (prdhighest - prdlowest) * 10 / 100
var pivotvals = array.new_float(0)
if ph1 or pl1
array.unshift(pivotvals, ph1 ? ph1 : pl1)
if array.size(pivotvals) > 20
array.pop(pivotvals)
get_sr_vals(ind) =>
float lo = array.get(pivotvals, ind)
float hi = lo
int numpp = 0
for y = 0 to array.size(pivotvals) - 1 by 1
float cpp = array.get(pivotvals, y)
float wdth = cpp <= lo ? hi - cpp : cpp - lo
if wdth <= cwidth
lo := cpp <= lo ? cpp : lo
hi := cpp > lo ? cpp : hi
numpp += 1
numpp
var sr_up_level = array.new_float(0)
var sr_dn_level = array.new_float(0)
sr_strength = array.new_float(0)
find_loc(strength) =>
ret = array.size(sr_strength)
for i = ret > 0 ? array.size(sr_strength) - 1 : na to 0 by 1
if strength <= array.get(sr_strength, i)
break
ret := i
ret
ret
check_sr(hi, lo, strength) =>
ret = true
for i = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by 1
if array.get(sr_up_level, i) >= lo and array.get(sr_up_level, i) <= hi or array.get(sr_dn_level, i) >= lo and array.get(sr_dn_level, i) <= hi
if strength >= array.get(sr_strength, i)
array.remove(sr_strength, i)
array.remove(sr_up_level, i)
array.remove(sr_dn_level, i)
ret
else
ret := false
ret
break
ret
// Get components
rsi = ta.rsi(close, 14)
vosc = ta.obv - ta.ema(ta.obv, 20)
bs = ta.ema(nz(math.abs((open - close) / (high - low) * 100)), 3)
ema = ta.ema(close, 200)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep(sym, res, src) =>
bool bull = na
bull := equal_tf(res) ? src : bull
bull := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on) : bull
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull := array.pop(bull_array)
array.clear(bull_array)
bull
TF1Bull = securityNoRep(syminfo.tickerid, "1" , emaBull)
TF3Bull = securityNoRep(syminfo.tickerid, "3" , emaBull)
TF5Bull = securityNoRep(syminfo.tickerid, "5" , emaBull)
TF10Bull = securityNoRep(syminfo.tickerid, "10" , emaBull)
TF15Bull = securityNoRep(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep(syminfo.tickerid, "60" , emaBull)
TF120Bull = securityNoRep(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep(syminfo.tickerid, "240" , emaBull)
TF720Bull = securityNoRep(syminfo.tickerid, "720" , emaBull)
TFDBull = securityNoRep(syminfo.tickerid, "1440", emaBull)
ema150 = ta.ema(close, 150)
ema250 = ta.ema(close, 250)
hma55 = ta.hma(close, 55 )
= ta.macd(close, 12, 26, 9)
supertrend = supertrend(ohlc4, sensitivity, 10)
maintrend = dchannel(30)
confBull = (ta.crossover (close, supertrend) or (ta.crossover (close, supertrend) and maintrend < 0)) and macd > 0 and macd > macd and ema150 > ema250 and hma55 > hma55 and maintrend > 0
confBear = (ta.crossunder(close, supertrend) or (ta.crossunder(close, supertrend) and maintrend > 0)) and macd < 0 and macd < macd and ema150 < ema250 and hma55 < hma55 and maintrend < 0
trendcloud = supertrend(ohlc4, periodTrendCloud == "Long term" ? 7 : 4, 10)
hma = fastTrendCloud ? ta.hma(close, fastTrendCloudLen) : na
none = close > 0
= ta.dmi(14, 14)
consFilter = adx > 20
StrongFilter = ta.ema(close, 200)
volFilter = (ta.ema(volume, 25) - ta.ema(volume, 26)) / ta.ema(volume, 26) > 0
trendFilter = trendcloud
bull = (strategy == "Normal" ? ta.crossover (close, supertrend) : confBull and not confBull ) and strategy != "Trend scalper" and (StrongSignalsOnly ? close > StrongFilter : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "New" ? ema150 > ema250 : close > trendFilter) : none)
bear = (strategy == "Normal" ? ta.crossunder(close, supertrend) : confBear and not confBear ) and strategy != "Trend scalper" and (StrongSignalsOnly ? close < StrongFilter : none) and (consSignalsFilter ? consFilter : none) and (highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud == "New" ? ema150 < ema250 : close < trendFilter) : none)
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
= trendScalper(strategy == "Trend scalper" ? true : false, 5, 9, 21, color.green, color.red, #00DD00, #DD0000)
trailingStop = trailingSL(bull, bear, 2.2, 14, usePercSL, percTrailingSL)
float _ph = ta.highestbars(high, periodSwings) == 0 ? high : na
float _pl = ta.lowestbars (low, periodSwings) == 0 ? low : na
var _dir = 0, dir_ = _pl and na(_ph) ? -1 : _dir, _dir := _ph and na(_pl) ? 1 : dir_, dirChg = ta.change(_dir)
var zz = array.new_float(0), zzOld = array.copy(zz)
float zzLive = _ph or _pl ? (dirChg ? add_to_zz(zz, _dir == 1 ? _ph : _pl, bar_index) : update_zz(zz, _dir == 1 ? _ph : _pl, bar_index, _dir)) : na
a = ta.wma(srcTrendChannel, lenTrendChannel), b_ = ta.sma(srcTrendChannel, lenTrendChannel)
A = 4 * b_ - 3 * a, B = 3 * a - 2 * b_
m = (A - B) / (lenTrendChannel - 1)
d = 0., for i = 0 to lenTrendChannel - 1 by 1
l = B + m * i
d += math.pow(srcTrendChannel - l, 2)
rmse = math.sqrt(d / (lenTrendChannel - 1)) * 2
float hb_ = ta.highestbars(lbPeriod) == 0 ? high : na
float lb_ = ta.lowestbars (lbPeriod) == 0 ? low : na
var int dir = 0
float zz_ = na
float pp = na
var int consCnt = 0
var float condHi = na
var float condLo = na
float H_ = ta.highest(lenCons)
float L_ = ta.lowest (lenCons)
var line lineUp = na
var line lineDn = na
bool breakUp = false
bool breakDn = false
var float pvh1_price = array.new_float(1000, na)
var int pvh1_time = array.new_int (1000, na)
var float pvl1_price = array.new_float(1000, na)
var int pvl1_time = array.new_int (1000, na)
var float pvh2_price = array.new_float(1000, na)
var int pvh2_time = array.new_int (1000, na)
var float pvl2_price = array.new_float(1000, na)
var int pvl2_time = array.new_int (1000, na)
var float htcmrll_price = na
var int htcmrll_time = na
var float ltcmrhh_price = na
var int ltcmrhh_time = na
var box long_boxes = array.new_box()
var box short_boxes = array.new_box()
var float temp_pv_0 = na
var float temp_pv_1 = na
var float temp_pv_2 = na
bool pvh = high < high and high > high
bool pvl = low > low and low < low
int pv1_time = bar_index
float pv1_high = high
float pv1_low = low
float trigger_high = bos_type == "High and Low" ? high : math.max(open, close)
float trigger_low = bos_type == "High and Low" ? low : math.min(open, close)
var buyBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(buyBars, i))
var sellBars = array.new_box(365, na)
for i = 0 to 364
box.delete(array.get(sellBars, i))
// Colors
green = #00DD00, green50 = color.new(green, 50), green20 = color.new(green, 80)
red = #DD0000, red50 = color.new(red, 50), red20 = color.new(red, 80)
silver = #B2B5BE, silver50 = color.new(silver, 50), silver20 = color.new(silver, 80)
///
var float _llv = na
var float _hhv = na
var float sell_tsl = na
var float buy_tsl = na
if ( bear and tslLabels )
_llv := low
_hhv := na
else if (low < _llv )
_llv := low
if ( bull and tslLabels )
_hhv := high
_llv := na
else if (high > _hhv )
_hhv := high
// Plots
atrBand = usePercSL ? (trigger ? low : high) * (percTrailingSL / 100) : ta.atr(14) * 2.2
atrStop = trigger ? low - atrBand : high + atrBand
lastTrade(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade(close)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y-lastTrade(atrStop))*multTP1 + entry_y
tp2_y = (entry_y-lastTrade(atrStop))*multTP2 + entry_y
tp3_y = (entry_y-lastTrade(atrStop))*multTP3 + entry_y
sell_tsl := _llv + atrBand // (entry_y-_llv)*multTP1 + entry_y //_llv
buy_tsl := _hhv - atrBand
labelTpSl(cond, y, txt, color) =>
label labelTpSl = enableTpSlAreas and cond ? label.new(bar_index + 1, y, txt, xloc.bar_index, yloc.price, color, label.style_label_left, color.rgb(0, 0, 0), size.normal) : na
label.delete(labelTpSl )
labelTpSl(none, entry_y, "Entry : " + str.tostring(math.round_to_mintick(entry_y)), color.orange)
labelTpSl(none, stop_y , "Stop loss : " + str.tostring(math.round_to_mintick(stop_y)), #ff1100)
labelTpSl(useTP1 and multTP1 != 0, tp1_y, "TP✅ 1 : " + str.tostring(math.round_to_mintick(tp1_y)), #00ffbb)
labelTpSl(useTP2 and multTP2 != 0, tp2_y, "TP✅ 2 : " + str.tostring(math.round_to_mintick(tp2_y)), #00ffbb)
labelTpSl(useTP3 and multTP3 != 0, tp3_y, "TP✅ 3 : " + str.tostring(math.round_to_mintick(tp3_y)), #00ffbb)
labelTpSl(none, sell_tsl , "Trailing Stoploss : " + str.tostring(math.round_to_mintick(sell_tsl)), #ff1100)
labelTpSl(none, buy_tsl , "Trailing Stoploss : " + str.tostring(math.round_to_mintick(buy_tsl)), #ff1100)
lineTpSl(cond, y, color, style) =>
line lineTpSl = enableTpSlAreas and cond ? line.new(bar_index - (trigger ? countBull : countBear), y, bar_index + 1, y, xloc.bar_index, extend.none, color, style) : na
line.delete(lineTpSl )
lineTpSl(none, entry_y, color.orange, line.style_dashed)
lineTpSl(none, stop_y , #ff1100 , line.style_solid )
lineTpSl(useTP1 and multTP1 != 0, tp1_y, #00ffbb, line.style_dotted)
lineTpSl(useTP2 and multTP2 != 0, tp2_y,#00ffbb, line.style_dotted)
lineTpSl(useTP3 and multTP3 != 0, tp3_y, #00ffbb, line.style_dotted)
lineTpSl(none, sell_tsl , #ff1100 , line.style_solid )
lineTpSl(none, buy_tsl , #ff1100 , line.style_solid )
var dashboard_loc = locationDashboard == "Top right" ? position.top_right : locationDashboard == "Top left" ? position.top_left : locationDashboard == "Middle right" ? position.middle_right : locationDashboard == "Middle left" ? position.middle_left : locationDashboard == "Bottom right" ? position.bottom_right : position.bottom_left
var dashboard_size = sizeDashboard == "Tiny" ? size.tiny : sizeDashboard == "Small" ? size.small : size.normal
var dashboard = table.new(dashboard_loc, 3, 20, colorBackground, colorFrame, 3, colorBorder, 3)
dashboard_cell(column, row, txt) => table.cell(dashboard, column, row, txt, 0, 0, color.rgb(0, 0, 0), text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
l(css, k) =>
line lr = enableAutoTrend ? line.new(bar_index - lenTrendChannel + 1, A + k, bar_index, B + k, extend=extend.right, color=css) : na
line.delete(lr )
// l(color.blue, rmse), l(color.blue, 0), l(color.blue, -rmse)
buy = showSignals and bull ? label.new(bar_index, low , close > StrongFilter ? "Strong Buy" : "Buy" , xloc.bar_index, yloc.belowbar, #00ffbb, label.style_label_up , color.rgb(0, 0, 0), size.small) : na
sell = showSignals and bear ? label.new(bar_index, high, close < StrongFilter ? "Strong Sell" : "Sell", xloc.bar_index, yloc.abovebar, #ff1100 , label.style_label_down, color.rgb(0, 0, 0), size.small) : na
tpLabels(tp) =>
tp1Bull = ta.crossover (rsi, 70), tp2Bull = ta.crossover (rsi, 75), tp3Bull = ta.crossover (rsi, 80)
tp1Bear = ta.crossunder(rsi, 30), tp2Bear = ta.crossunder(rsi, 25), tp3Bear = ta.crossunder(rsi, 20)
tp1Bull := tp1Bull and (nz(ta.barssince(tp1Bull) , 9999) > countBull), tp2Bull := tp2Bull and (ta.barssince(tp1Bull) <= countBull), tp2Bull := tp2Bull and (nz(ta.barssince(tp2Bull) , 9999) > countBull), tp3Bull := tp3Bull and (ta.barssince(tp2Bull) <= countBull), tp3Bull := tp3Bull and (nz(ta.barssince(tp3Bull) , 9999) > countBull)
tp1Bear := tp1Bear and (nz(ta.barssince(tp1Bear) , 9999) > countBear), tp2Bear := tp2Bear and (ta.barssince(tp1Bear) <= countBear), tp2Bear := tp2Bear and (nz(ta.barssince(tp2Bear) , 9999) > countBear), tp3Bear := tp3Bear and (ta.barssince(tp2Bear) <= countBear), tp3Bear := tp3Bear and (nz(ta.barssince(tp3Bear) , 9999) > countBear)
if strategy != "Trend scalper" and tpLabels
trigger ? (tp == 1 ? tp1Bull : tp == 2 ? tp2Bull : tp3Bull) : (tp == 1 ? tp1Bear : tp == 2 ? tp2Bear : tp3Bear)
plotshape(tpLabels(1), "", shape.cross, location.abovebar, trigger ? #00ffbb : na , 0, "✔ TP1", trigger ? #00ffbb : na , false,display=labelDisplay)
plotshape(tpLabels(2), "", shape.cross, location.abovebar, trigger ? #00ffbb : na , 0, "✔ TP2", trigger ? #00ffbb : na , false,display=labelDisplay)
plotshape(tpLabels(3), "", shape.cross, location.abovebar, trigger ? #00ffbb : na , 0, "✔ TP3", trigger ? #00ffbb : na , false,display=labelDisplay)
plotshape(tpLabels(1), "", shape.cross, location.belowbar, trigger ? na : #ff1100, 0, "✔ TP1", trigger ? na : #ff1100, false,display=labelDisplay)
plotshape(tpLabels(2), "", shape.cross, location.belowbar, trigger ? na : #ff1100, 0, "✔ TP2", trigger ? na : #ff1100, false,display=labelDisplay)
plotshape(tpLabels(3), "", shape.cross, location.belowbar, trigger ? na : #ff1100, 0, "✔ TP3", trigger ? na : #ff1100, false,display=labelDisplay)
var label zzLabel = na
if array.size(zz) > 12 and enableSwings
if array.get(zz, 0) != array.get(zzOld, 0) or array.get(zz, 1) != array.get(zzOld, 1)
if array.get(zz, 2) == array.get(zzOld, 2) and array.get(zz, 3) == array.get(zzOld, 3)
label.delete(zzLabel)
zzLabel := label.new(math.round(array.get(zz, 1)), array.get(zz, 0), _dir == 1 ? array.get(zz, 0) > array.get(zz, 4) ? ((array.get(zz, 4) < array.get(zz, 8)) ? "High" : "HH") : "LH" : array.get(zz, 0) < array.get(zz, 4) ? ((array.get(zz, 4) > array.get(zz, 8)) ? "Low" : "LL") : "HL", xloc.bar_index, yloc.price, color.new(color.white, 100), _dir == 1 ? label.style_label_down : label.style_label_up, _dir == 1 ? #00ffbb : #ff1100)
var sr_lines = array.new_line(11, na)
for x = 1 to 10 by 1
line.set_color(array.get(sr_lines, x), color=line.get_y1(array.get(sr_lines, x)) >= close ? color.red : color.lime)
if ph1 or pl1
array.clear(sr_up_level)
array.clear(sr_dn_level)
array.clear(sr_strength)
for x = 0 to array.size(pivotvals) - 1 by 1
= get_sr_vals(x)
if check_sr(hi, lo, strength)
loc = find_loc(strength)
if loc < 5 and strength >= 2
array.insert(sr_strength, loc, strength)
array.insert(sr_up_level, loc, hi)
array.insert(sr_dn_level, loc, lo)
if array.size(sr_strength) > (enableSR ? 5 : 0)
array.pop(sr_strength)
array.pop(sr_up_level)
array.pop(sr_dn_level)
for x = 1 to 10 by 1
line.delete(array.get(sr_lines, x))
for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by 1
float mid = math.round_to_mintick((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
rate = 100 * (mid - close) / close
array.set(sr_lines, x + 1, line.new(x1=bar_index, y1=mid, x2=bar_index - 1, y2=mid, extend=extend.both, color=mid >= close ? color.red : color.lime, style=LSRstyle, width=lineSrWidth))
if showCons and barstate.isconfirmed
dir := hb_ and na(lb_) ? 1 : lb_ and na(hb_) ? -1 : dir
if hb_ and lb_
if dir == 1
zz_ := hb_
else
zz_ := lb_
else
zz_ := hb_ ? hb_ : lb_ ? lb_ : na
for x = 0 to 1000
if na(close) or dir != dir
break
if zz_
if na(pp)
pp := zz_
else
if dir == 1 and zz_ > pp
pp := zz_
if dir == -1 and zz_ < pp
pp := zz_
if pp != pp
if consCnt > lenCons
if pp > condHi
breakUp := true
if pp < condLo
breakDn := true
if consCnt > 0 and pp <= condHi and pp >= condLo
consCnt += 1
else
consCnt := 0
else
consCnt += 1
if consCnt >= lenCons
if consCnt == lenCons
condHi := H_
condLo := L_
else
line.delete(lineUp)
line.delete(lineDn)
condHi := math.max(condHi, high)
condLo := math.min(condLo, low )
lineUp := line.new(bar_index, condHi , bar_index - consCnt, condHi , color=color.red , style=line.style_dashed)
lineDn := line.new(bar_index, condLo , bar_index - consCnt, condLo , color=color.lime, style=line.style_dashed)
// fill(plot(condHi, "", na, 1, plot.style_stepline, editable=false), plot(condLo, "", na, 1, plot.style_stepline, editable=false), paintCons and consCnt > lenCons ? colorZone : na, "", false)
if box_ob and barstate.isconfirmed
if pvh
array.pop(pvh1_price)
array.pop(pvh1_time)
array.unshift(pvh1_price, pv1_high)
array.unshift(pvh1_time, pv1_time)
if array.size(pvh1_price) > 2
temp_pv_0 := array.get(pvh1_price, 0)
temp_pv_1 := array.get(pvh1_price, 1)
temp_pv_2 := array.get(pvh1_price, 2)
if temp_pv_0 > temp_pv_1
for i = 0 to array.size(pvl1_time) - 1 by 1
temp_ltcmrhh_time = array.get(pvl1_time, i)
if temp_ltcmrhh_time < array.get(pvh1_time, 0)
ltcmrhh_price := array.get(pvl1_price, i)
ltcmrhh_time := temp_ltcmrhh_time
break
if temp_pv_0 < temp_pv_1 and temp_pv_1 > temp_pv_2
array.pop(pvh2_price)
array.pop(pvh2_time)
array.unshift(pvh2_price, temp_pv_1)
array.unshift(pvh2_time, array.get(pvh1_time, 1))
if pvl
array.pop(pvl1_price)
array.pop(pvl1_time)
array.unshift(pvl1_price, pv1_low)
array.unshift(pvl1_time, pv1_time)
if array.size(pvl1_price) > 2
temp_pv_0 := array.get(pvl1_price, 0)
temp_pv_1 := array.get(pvl1_price, 1)
temp_pv_2 := array.get(pvl1_price, 2)
if temp_pv_0 < temp_pv_1
for i = 0 to array.size(pvh1_time) - 1 by 1
temp_htcmrll_time = array.get(pvh1_time, i)
if temp_htcmrll_time < array.get(pvl1_time, 0)
htcmrll_price := array.get(pvh1_price, i)
htcmrll_time := temp_htcmrll_time
break
if temp_pv_0 > temp_pv_1 and temp_pv_1 < temp_pv_2
array.pop(pvl2_price)
array.pop(pvl2_time)
array.unshift(pvl2_price, temp_pv_1)
array.unshift(pvl2_time, array.get(pvl1_time, 1))
if trigger_high > htcmrll_price
if box_sv
loBox = box.new(left=array.get(pvl1_time, 0), top=math.min(high , high ), right=bar_index, bottom=array.get(pvl1_price, 0), bgcolor=color.rgb(0, 255, 0, 80), border_color=color.rgb(0, 255, 0, 80), extend=extend.right)
if array.size(long_boxes) >= 25
box.delete(array.shift(long_boxes))
array.push(long_boxes, loBox)
htcmrll_price := na
htcmrll_price
if trigger_low < ltcmrhh_price
if box_sv
hiBox = box.new(left=array.get(pvh1_time, 0), top=array.get(pvh1_price, 0), right=bar_index, bottom=math.max(low , low ), bgcolor=color.rgb(255, 0, 0, 80), border_color=color.rgb(255, 0, 0, 80), extend=extend.right)
if array.size(short_boxes) >= 25
box.delete(array.shift(short_boxes))
array.push(short_boxes, hiBox)
ltcmrhh_price := na
ltcmrhh_price
if array.size(short_boxes) > 0
for i = array.size(short_boxes) - 1 to 0 by 1
tbox = array.get(short_boxes, i)
top = box.get_top(tbox)
bottom = box.get_bottom(tbox)
if trigger_high > bottom and box.get_left(tbox) + box_test_delay < bar_index and box_test_sv
if box_hide_gray
box.set_bgcolor(tbox, #00000000)
box.set_border_color(tbox, #00000000)
else
box.set_bgcolor(tbox, color.rgb(192, 192, 192, 80))
box.set_border_color(tbox, color.rgb(192, 192, 192, 80))
if trigger_high > top and box.get_left(tbox) + box_fill_delay < bar_index
if box_stop_sv
box.set_right(tbox, bar_index)
box.set_extend(tbox, extend.none)
array.remove(short_boxes, i)
if array.size(long_boxes) > 0
for i = array.size(long_boxes) - 1 to 0 by 1
lbox = array.get(long_boxes, i)
top = box.get_top(lbox)
bottom = box.get_bottom(lbox)
if trigger_low < top and box.get_left(lbox) + box_test_delay < bar_index and box_test_sv
if box_hide_gray
box.set_bgcolor(lbox, #00000000)
box.set_border_color(lbox, #00000000)
else
box.set_bgcolor(lbox, color.rgb(192, 192, 192, 80))
box.set_border_color(lbox, color.rgb(192, 192, 192, 80))
if trigger_low < bottom and box.get_left(lbox) + box_fill_delay < bar_index
if box_stop_sv
box.set_right(lbox, bar_index)
box.set_extend(lbox, extend.none)
array.remove(long_boxes, i)
// ============== ============== ============== ============== ============== ============== ============== ============== ============== ==============
// NEW LABEL
// ============== ============== ============== ============== ============== ============== ============== ============== ============== ==============
// Calculate indicators
// fastSMA = ta.sma(close, 5)
// slowSMA = ta.sma(close, 100)
// priceRange = high - low
// longRangeThreshold = low + (0.2 * priceRange) // 20% above low for longs
// shortRangeThreshold = high - (0.2 * priceRange) // 20% below high for shorts
// // Calculate ATR for gradient effects
// atr = ta.atr(14)
// // Calculate gradient colors based on price distance
// fastSMAColorWithGradient = color.from_gradient(math.abs(close - fastSMA), 0.0, atr, color.new(themeColorLong, 70), themeColorLong)
// slowSMAColorWithGradient = color.from_gradient(math.abs(close - slowSMA), 0.0, atr, color.new(themeColorShort, 70), themeColorShort)
// // Plot main SMA lines with enhanced 3D style
// // plot(fastSMA, color=fastSMAColorWithGradient, title="Fast SMA", linewidth=3, style=plot.style_line)
// plot(slowSMA, color=slowSMAColorWithGradient, title="Slow SMA", linewidth=3, style=plot.style_line)
// // Plot zones around SMAs for 3D effect
// // fastSMA_upper = plot(fastSMA + atr * 0.5, color=color.new(themeColorLong, 90), title="Fast SMA Upper", style=plot.style_line, linewidth=1)
// // fastSMA_lower = plot(fastSMA - atr * 0.5, color=color.new(themeColorLong, 90), title="Fast SMA Lower", style=plot.style_line, linewidth=1)
// // fill(fastSMA_upper, fastSMA_lower, color=color.new(themeColorLong, 95), title="Fast SMA Zone")
// slowSMA_upper = plot(slowSMA + atr * 0.5, color=color.new(themeColorShort, 90), title="Slow SMA Upper", style=plot.style_line, linewidth=1)
// slowSMA_lower = plot(slowSMA - atr * 0.5, color=color.new(themeColorShort, 90), title="Slow SMA Lower", style=plot.style_line, linewidth=1)
// fill(slowSMA_upper, slowSMA_lower, color=color.new(themeColorShort, 95), title="Slow SMA Zone")
// // Plot range thresholds with enhanced style
// longThresholdColor = color.from_gradient(math.abs(close - longRangeThreshold), 0.0, atr, color.new(themeColorLong, 70), themeColorLong)
// shortThresholdColor = color.from_gradient(math.abs(close - shortRangeThreshold), 0.0, atr, color.new(themeColorShort, 70), themeColorShort)
// //@version=6
// indicator("Smoothed Gaussian Trend Filter ", "AlgoAlpha - Smoothed Gaussian Trend", overlay = true)
periodInput = input.int(15, title="Gaussian Length", tooltip="Period used to calculate the Gaussian alpha.", group = "Gaussian Filter Settings")
polesInput = input.int(3, title="Poles", minval=1, maxval=4, tooltip="Order of the Gaussian filter, affects smoothness.", group = "Gaussian Filter Settings")
linreglen = input.int(22, title="Smoothing Length", tooltip="Length for linear regression smoothing applied on the gaussian line.", group = "Smoothing Settings")
linregoffset = input.int(7, title="Flatten Multiplier", tooltip="Offset for flattening the output, making it less wavey.", group = "Smoothing Settings")
en_table = input.bool(true, title="Enable Table", tooltip="Enables/Disables the table.", group = "Extra Timeframes")
table_size = input.string("Tiny", title="Table Size", options = , tooltip="Size of the table.", group = "Extra Timeframes")
t1 = input.timeframe("5", "Time frame 1", group = "Extra Timeframes")
t2 = input.timeframe("15", "Time frame 2", group = "Extra Timeframes")
t3 = input.timeframe("60", "Time frame 3", group = "Extra Timeframes")
t4 = input.timeframe("240", "Time frame 4", group = "Extra Timeframes")
t5 = input.timeframe("1D", "Time frame 5", group = "Extra Timeframes")
vol_int = input.bool(true, title="", tooltip="Highlight based on volume intensity.", group = "Appearance", inline = "vol")
vol_filt = input.int(70, title="Volume Intensity Highlighting Strength", minval=1, maxval=99, tooltip="Adjusts sensitivity to volume changes.", group = "Appearance", inline = "vol")
mid_trnd_sig = input.bool(false, title=" Mid-Trend Signals", tooltip="Enable additional buy/sell signals during trends.", group = "Appearance")
bands = input.bool(false, title=" Trailing Bands", tooltip="Enables/Disables Trend Bands", group = "Appearance")
//barcol = input.bool(true, title=" Bar Color", tooltip="Enables/Disables Candle Colouring", group = "Appearance")
green1 = input.color(#00ffbb, title="Bullish Color", tooltip="Color for bullish signals and indicators.", group = "Appearance")
red1 = input.color(#ff1100, title="Bearish Color", tooltip="Color for bearish signals and indicators.", group = "Appearance")
calcGaussianAlpha(_length, _order) =>
freq = (2.0 * math.pi) / _length
factorB = (1.0 - math.cos(freq)) / (math.pow(1.414, (2.0 / _order)) - 1.0)
alphaVal = -factorB + math.sqrt(factorB * factorB + 2.0 * factorB)
alphaVal
gaussianSmooth(dataIn, filterLevel, alphaCoeff) =>
var float runningFilterValue = 0.0
oneMinusAlpha = 1.0 - alphaCoeff
alphaSquared = alphaCoeff * alphaCoeff
alphaCubed = alphaCoeff * alphaCoeff * alphaCoeff
alpha4 = alphaCoeff * alphaCoeff * alphaCoeff * alphaCoeff
omaSquared = oneMinusAlpha * oneMinusAlpha
omaCubed = omaSquared * oneMinusAlpha
oma4 = omaCubed * oneMinusAlpha
if filterLevel == 1
runningFilterValue := alphaCoeff * dataIn +
oneMinusAlpha * nz(runningFilterValue )
else
if filterLevel == 2
runningFilterValue := alphaSquared * dataIn
+ 2.0 * oneMinusAlpha * nz(runningFilterValue )
- omaSquared * nz(runningFilterValue )
else
if filterLevel == 3
runningFilterValue := alphaCubed * dataIn
+ 3.0 * oneMinusAlpha * nz(runningFilterValue )
- 3.0 * omaSquared * nz(runningFilterValue )
+ omaCubed * nz(runningFilterValue )
else
if filterLevel == 4
runningFilterValue := alpha4 * dataIn
+ 4.0 * oneMinusAlpha * nz(runningFilterValue )
- 6.0 * omaSquared * nz(runningFilterValue )
+ 4.0 * omaCubed * nz(runningFilterValue )
- oma4 * nz(runningFilterValue )
runningFilterValue
pine_supertrend(src, factor, atrPeriod) =>
atr = ta.atr(atrPeriod)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand )
prevUpperBand = nz(upperBand )
lowerBand := lowerBand > prevLowerBand or src < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or src > prevUpperBand ? upperBand : prevUpperBand
int _direction = na
float superTrend = na
prevSuperTrend = superTrend
if na(atr )
_direction := 1
else if prevSuperTrend == prevUpperBand
_direction := src > upperBand ? -1 : 1
else
_direction := src < lowerBand ? 1 : -1
superTrend := _direction == -1 ? lowerBand : upperBand
tableSize(table_size) =>
switch table_size
"Tiny" => size.tiny
"Small" => size.small
"Medium" => size.normal
"Large" => size.large
alphaValue = calcGaussianAlpha(periodInput, polesInput)
gmaOutput = gaussianSmooth(close, polesInput, alphaValue)
final = ta.linreg(gmaOutput, linreglen, linregoffset)
= pine_supertrend(final, 0.15, 21)
trend = final > final ? 1 : -1
trend1 = final > ST1? 1 : -1
ranging = (trend * trend1 < 0)
z = 33
s_vol = ta.hma((volume - ta.lowest(volume, z)) / (ta.highest(volume, z) - ta.lowest(volume, z)), 4)
transparency_ = math.min(100 - s_vol * 100, vol_filt)
dist = ta.sma(math.abs(close - open), 100)
main = plot(final, color=ranging and mid_trnd_sig ? color.gray : trend1 > 0 ? color.new(green1, vol_int ? transparency_*0.5 : 00) : color.new(red1, vol_int ? transparency_ *0.5: 20), linewidth=3,display=labelDisplay)
bull1 = plot(trend1 > 0 ? final - dist * 2 : na, style=plot.style_linebr, color=color.new(green1, 20), display = bands ? display.all : display.none)
bear1 = plot(trend1 < 0 ? final + dist * 2 : na, style=plot.style_linebr, color=color.new(red1, 40), display = bands ? display.all : display.none)
fill(main, bull1, final, final - dist * 2, color.new(ranging and mid_trnd_sig ? color.gray : green1, vol_int ? transparency_ : 50), color.new(ranging and mid_trnd_sig ? color.gray : green1, 93), display = bands ? display.all : display.none)
fill(main, bear1, final + dist * 2, final, color.new(ranging and mid_trnd_sig ? color.gray : red1, 93), color.new(ranging and mid_trnd_sig ? color.gray : red1, vol_int ? transparency_ : 50), display = bands ? display.all : display.none)
h = math.max(ta.highest(14), ta.highest(final, 14), final + dist * 2)
l = math.min(ta.lowest(14), ta.lowest(final, 14), final - dist * 2)
// plotshape(trend1 > 0 and (mid_trnd_sig ? not ranging and ranging : trend1 < 0) ? l : na, title="Bullish Signal", style=shape.labelup, location=location.absolute, size=size.small, color=green)
// plotshape(trend1 < 0 and (mid_trnd_sig ? not ranging and ranging : trend1 > 0) ? h : na, title="Bearish Signal", style=shape.labeldown, location=location.absolute, size=size.small, color=red)
//barcolor(barcol ? ranging and mid_trnd_sig ? color.gray : trend1 > 0 ? color.new(green1, vol_int ? transparency_*0.5 : 00) : color.new(red1, vol_int ? transparency_ *0.5: 00) : na, title = "Bar Coloring")
// plot(longRangeThreshold, color=longThresholdColor, title="Long Range Threshold", style=plot.style_circles, linewidth=2)
// plot(shortRangeThreshold, color=shortThresholdColor, title="Short Range Threshold", style=plot.style_circles, linewidth=2)
// barcolor(momentumCandles and candlesMom() ? color.purple : candleColors ? (strategy == "Trend scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray : trigger ? green : red) : na, editable=false)
// fill(plot(showTrendCloud and periodTrendCloud == "New" ? ema150 : na, "", na, editable=false), plot(showTrendCloud and periodTrendCloud == "New" ? ema250 : na, "", na, editable=false), ema150 > ema250 ? color.new(themeColorShort, 70) : ema150 < ema250 ? color.new(themeColorShort, 70) : na)
// plot(enableTrailingSL and trigger and nz(ta.barssince(low < trailingStop), bar_index) > countBull ? trailingStop : na, "", green, 1, plot.style_linebr, editable=false)
// plot(enableTrailingSL and not trigger and nz(ta.barssince(high > trailingStop), bar_index) > countBear ? trailingStop : na, "", red , 1, plot.style_linebr, editable=false)
// p0 = plot(avgOC, "", na , editable=false)
// p1 = plot(ema5 , "", colorEma5 , editable=false)
// p2 = plot(ema9 , "", colorEma9 , editable=false)
// p3 = plot(ema21, "", colorEma21, editable=false)
// = getThemeColors()
// fill(p0, p1, fillEma5 )
// fill(p1, p2, fillEma9 )
// fill(p2, p3, fillEma21)
// fill(plot(showTrendCloud and periodTrendCloud != "New" and trendcloud != 0 and close > trendcloud ? trendcloud : na, "", color.green, 1, plot.style_linebr, editable=false), p0, color.new(color.green, 90))
// fill(plot(showTrendCloud and periodTrendCloud != "New" and trendcloud != 0 and close < trendcloud ? trendcloud : na, "", color.red , 1, plot.style_linebr, editable=false), p0, color.new(color.red , 90))
// fill(plot(hma, "", hma > hma ? green : hma < hma ? red : na, editable=false), plot(hma , "", hma > hma ? green : hma < hma ? red : na, editable=false), hma > hma ? green : hma < hma ? red : na)
// Alerts
f_crossed_over() =>
ret = false
for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by 1
float mid = math.round_to_mintick((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
if close <= mid and close > mid
ret := true
ret
ret
f_crossed_under() =>
ret = false
for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by 1
float mid = math.round_to_mintick((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
if close >= mid and close < mid
ret := true
ret
ret
f_sl_crossed() =>
ret = false
stop = enableTrailingSL ? trailingStop : stop_y
crossBull = low >= stop and low < stop and ta.barssince(low >= stop and low < stop ) >= countBull - 1
crossBear = high <= stop and high > stop and ta.barssince(high <= stop and high > stop ) >= countBear - 1
ret := trigger ? crossBull : crossBear
f_tp_crossed(tp) =>
ret = false
profit = tp
crossBull = high <= profit and high > profit and ta.barssince(high <= profit and high > profit ) >= countBull - 1
crossBear = low >= profit and low < profit and ta.barssince(low >= profit and low < profit ) >= countBear - 1
ret := trigger ? crossBull : crossBear
alert01 = (bull and close <= StrongFilter) or (bull and close > StrongFilter)
alert02 = (bear and close >= StrongFilter) or (bear and close < StrongFilter)
alert03 = (bull and close > StrongFilter) or (bear and close < StrongFilter)
alert04 = bull and close <= StrongFilter
alert05 = f_crossed_over()
alert06 = bear and close >= StrongFilter
alert07 = bull and close > StrongFilter
alert08 = bear and close < StrongFilter
alert09 = f_sl_crossed()
alert10 = f_crossed_under()
alert11 = f_tp_crossed(tp1_y)
alert12 = f_tp_crossed(tp2_y)
alert13 = f_tp_crossed(tp3_y)
alert14 = periodTrendCloud == "New" ? ta.crossunder(ema150, ema250) : (close < trendcloud) and (close > trendcloud)
alert15 = periodTrendCloud == "New" ? ta.crossover (ema150, ema250) : (close > trendcloud) and (close < trendcloud)
alerts(sym) =>
if alert01 or alert02 or alert03 or alert04 or alert05 or alert06 or alert07 or alert08 or alert09 or alert10 or alert11 or alert12 or alert13 or alert14 or alert15
alert("NEW ALERT", alert.freq_once_per_bar_close)
alerts(syminfo.tickerid)
//indicator("8 AM Strategy by Leo", overlay = true, max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 1000)
// Mostrar estrategia
showpips = input.bool(true, "Show 8 AM Strategy")
// Input de hora y minuto configurables para la vela especial
input_hour = input.int(15, title="Hour for 8AM NY Candle",options= , tooltip="15 Summer Time NY 14 Standard Time NY")
input_minute = input.int(0, title="Minute for 8AM NY Candle")
// // Minutos considerados hasta la 8 AM (ya no lo usamos para función de reinicio)
// input_minutes = input.int(900, title="Minutes to consider until 8 AM, New York time", options= , tooltip="900 Summer Time NY 840 Standard Time NY")
// Factor de escala
scaleFactor = input.float(100, title="Scaling Factor for Forex", options= , tooltip="100 XAUXXX 10 XAGXXX, EURXXX")
// Ancho y estilo de líneas
gline_width = input.int(2, "Line Width", minval=1)
gline_style = input.string("Dashed", title="Line Style", options= )
gselected_style = gline_style == "Solid" ? line.style_solid : gline_style == "Dashed" ? line.style_dashed : line.style_dotted
// Función para detectar la vela configurada
is_800_candle() =>
hour(time) == input_hour and minute(time) == input_minute
// Detectar si la vela actual es la de las 8 AM
is_800_candle_current = is_800_candle()
// Fondo azul en la vela 8 AM
bgcolor(is_800_candle_current ? color.new(color.blue, 90) : na)
// Variables para capturar valores
var float first_x_high = na
var float first_x_low = na
var float first_x_open = na
var bool open_captured = false
// Reiniciar los valores cuando ocurre la siguiente vela 8 AM
if is_800_candle_current
first_x_high := na
first_x_low := na
first_x_open := open
open_captured := true
// Si no están capturados, seguir actualizando high y low
if not open_captured
fi
Price action-based monitoring indicatorsPrice action-based indicators, EMA20, support, resistance, and candlestick charts.
MB Break & Retest MB Break & Retest + VWAP (ORB) is an Opening Range Breakout indicator built for intraday trading. It captures the first 15 minutes of the session to plot the Opening Range High, Low, and Midpoint. After the Opening Range is set, it looks for a confirmed breakout using two conditions: price must close a user-defined distance beyond the OR High or OR Low, and the breakout candle must meet a minimum 5-minute volume threshold. If both the OR High and OR Low break in the same session, the indicator flags the market as choppy and avoids taking trades.
Trades are not taken on the breakout candle. Instead, the script waits for price to retest the Opening Range midpoint and enter only when that retest shows acceptable confirmation. Optional filters include a close-position filter (requiring the candle to close in the top/bottom portion of its range), a minimum retest volume requirement, and a midpoint “respect” filter that requires price to reject away from the midpoint by a set distance rather than simply touching it.
An optional VWAP filter adds directional bias: longs are allowed only when the midpoint is sufficiently below VWAP (with a configurable buffer), and shorts are allowed only when the midpoint is sufficiently above VWAP. The VWAP line can be displayed, and the script tracks how many potential trades were filtered out by the VWAP rule.
The indicator also includes built-in trade management and visual risk tools. It plots stop-loss and take-profit zones, supports a partial profit target (taking 50% off at a specified move), and can move the stop to break-even once a configurable R:R threshold is reached. Entry, partial, break-even, stop, and target events can be labeled on the chart.
A live status panel shows the current state (watching, breakout detected, trade active, session closed, or choppy), along with OR levels, midpoint, VWAP context, and volume information. A backtest dashboard summarizes performance metrics such as net P/L, win rate, profit factor, average win/loss, long vs short stats, breakeven exits, partial exits, streaks, and VWAP-filtered counts.
SBMS RSI+MAThis is clearly indicating the RSI with colors on panel and gives idea about overbought and oversold easily in visually clear color bands.
We have made the Alerts facility for knowing the trend improving or trend slowing now.
If this is combined with RSI divergence can be best tool to spot revrsals like in case of Double Bottom OR Double Top to confirm for trade initiation.
ALL-IN ZONE X (EMA + BB + Swing + TP Panel)ALL-IN ZONE X is a technical analysis indicator designed to help traders identify high-probability trade zones using a combination of trend, volatility, and price structure.
This indicator integrates:
Exponential Moving Averages (EMA) for trend direction
Bollinger Bands (BB) to visualize volatility and price expansion
Swing structure detection to highlight potential market turning points
A Take Profit (TP) panel to assist with structured trade planning
ALL-IN ZONE X is intended for discretionary trading and educational purposes only.
It does not generate automated buy or sell orders and should be used as a confluence tool alongside proper risk management and market analysis.
Disclaimer:
This indicator does not provide financial advice. Trading involves risk, and past performance does not guarantee future results.
QVAND MASTER Channels QVAND MASTER Channels — Close Only Trend Channels (Multi Window)
QVAND MASTER Channels plots multiple sloping price channels designed to show trend structure using closing prices only. Wicks are intentionally ignored so the channels reflect where price was actually accepted, instead of expanding from brief spikes.
What this indicator plots
• 3 primary channels built from rolling windows of 12 / 6 / 3 months (defaults).
• On 15m and 30m charts only, it automatically adds 2 shorter channels (2 / 1 month) to show nearer-term structure.
• Each channel includes a top/bottom boundary, optional midline, optional fill, and optional right extension.
How it works
For each selected window:
1. The script identifies the start of the window (by calendar months back) and the current bar.
2. It creates a baseline as a straight line connecting:
• the close at the window start, and
• the latest close.
3. It then measures the maximum and minimum deviation of closing prices from that baseline throughout the window.
4. The channel boundaries are built as:
• Top = baseline + max close deviation
• Bottom = baseline + min close deviation
• Midline = midpoint between top and bottom
This produces channels that adapt as new data arrives while staying anchored to close behavior rather than wick noise.
What makes it different
• Close only construction (no wicks): avoids spike-driven channel expansion.
• Baseline + deviation envelope: width comes from real close dispersion around the baseline, not generic bands.
• Multi window view: long/mid/short structure on one chart, with extra local channels on 15m/30m.
Customization
You can adjust: master timeframe, each window length (months), colors, line width, fill opacity, midline on/off, right extension on/off, and whether the 15m/30m extra channels are shown.
Performance note
This is a heavier script due to historical scanning across multiple windows. On some symbols/timeframes it may take ~20–25 seconds to load/paint.
TRIZONACCI_Mean reversal_signalsMarket State Engine
Deterministic Confidence-Scoring System for TradingView
A professional-grade PineScript v5 indicator that scores market conditions from 0-100, helping traders identify high-quality trading opportunities through systematic structure analysis, VWAP positioning, order flow dynamics, and time-based context.
🎯 Overview
The Market State Engine is not a trading bot—it's a noise-reduction and opportunity-ranking system designed to filter market conditions and surface only the highest-quality setups.
Instead of blindly taking every signal, this indicator:
✅ Scores market conditions objectively (0-100 scale)
✅ Filters out low-probability setups automatically
✅ Classifies opportunities into A, A+, and A++ grades
✅ Alerts only on confirmed structure shifts with supporting context
✅ Keeps the human in control - provides intelligence, not automation
Philosophy: Reduce Noise. Enforce Discipline. Surface Quality.
🚀 Key Features
Deterministic Scoring - No black boxes, fully explainable logic
Multi-Factor Analysis - Combines 4 independent market state components
Structure-First Approach - Only alerts on confirmed pivot breaks
VWAP Mean Reversion Logic - Directional filtering based on VWAP zones
Order Flow Proxy - CVD divergence and confirmation detection
Session-Aware Scoring - Prioritizes high-volume New York sessions
Alert De-Duplication - One alert per unique structure shift
Zero Repainting - Uses confirmed pivots only (left=2, right=2)
Fully Configurable - All parameters exposed as inputs
Visual Feedback - VWAP bands, setup labels, and real-time score panel
📊 Scoring System (0-100)
The Market State Engine evaluates four independent components, each contributing up to 25 points for a maximum total score of 100.
🎯 Component Breakdown
Component Max Points Description
VWAP Context 25 Measures price deviation from session VWAP
Structure Shift 25 Confirms pivot breakout (HARD GATE)
CVD Alignment 25 Detects order flow divergence/confirmation
Time-of-Day 25 Identifies high-probability trading sessions
1️⃣ VWAP Context (Max 25 Points)
Purpose: Identifies extreme price deviations from fair value for mean-reversion opportunities.
VWAP (Volume-Weighted Average Price) is calculated session-anchored to New York market time, with standard deviation bands creating zones of opportunity.
Band Structure:
1st Band: ±1σ from VWAP (fair value zone)
2nd Band: ±2σ from VWAP (moderate deviation)
3rd Band: ±3σ from VWAP (extreme deviation)
Scoring Logic (Exclusive):
Price in 3rd VWAP Band (>2σ and ≤3σ) → +25 points
Price in 2nd VWAP Band (>1σ and ≤2σ) → +15 points
Otherwise (inside 1σ or beyond 3σ) → 0 points
Key Insight: The further price stretches from VWAP, the higher the probability of mean reversion.
2️⃣ Structure Shift (Max 25 Points) — HARD GATE
Purpose: Confirms momentum shift through confirmed pivot breakouts.
⚠️ CRITICAL: Structure shift is mandatory. If no valid structure shift occurs, the total score becomes 0 regardless of other factors.
Detection Method:
Uses TradingView's ta.pivothigh() and ta.pivotlow() functions with locked parameters:
Left bars: 2
Right bars: 2
Source: Configurable (Wick or Body)
Break confirmation: Candle close only
Bullish Structure Shift:
✅ Prior swing high exists (confirmed pivot)
✅ Current candle closes above swing high + tick buffer
✅ Must occur in VWAP 2nd or 3rd band
✅ VWAP Filter: Price must be at or below VWAP (lower bands)
Bearish Structure Shift:
✅ Prior swing low exists (confirmed pivot)
✅ Current candle closes below swing low - tick buffer
✅ Must occur in VWAP 2nd or 3rd band
✅ VWAP Filter: Price must be at or above VWAP (upper bands)
Scoring:
Valid structure shift → +25 points
No structure shift → Total score = 0
Tick Buffer: Default 5 ticks (configurable) - prevents false breaks from minor price noise.
3️⃣ CVD Alignment (Max 25 Points)
Purpose: Detects institutional order flow through volume delta analysis.
CVD (Cumulative Volume Delta) is a proxy for order flow:
Close > Open → +Volume (buying pressure)
Close < Open → -Volume (selling pressure)
Scoring Logic:
Condition Points Description
Divergence +25 Price makes higher high + CVD makes lower high (bearish)
Price makes lower low + CVD makes higher low (bullish)
Confirmation +20 Price and CVD both make higher highs or lower lows
Neutral 0 No clear divergence or confirmation
Lookback Window: Last 20 bars (configurable) - prevents stale divergences.
Key Insight: Divergences suggest weakening momentum, while confirmations validate the trend.
4️⃣ Time-of-Day Context (Max 25 Points)
Purpose: Prioritizes high-volume, high-volatility New York sessions.
Scored Sessions (America/New_York timezone):
Session Time Range (NY) Points Description
Pre-Market 03:00 - 04:00 +25 Early liquidity injection
Market Open 09:30 - 11:30 +25 Highest volume period
Off-Hours All other times 0 Lower probability setups
Key Insight: Structure shifts during active sessions have higher follow-through probability.
🏆 Setup Classification
Setups are graded based on total score thresholds (configurable):
Grade Score Range Typical Components Quality Level
A++ Setup ≥90 All 4 factors aligned
(VWAP 3rd band + Structure + CVD + Session) Premium - Rare
A+ Setup ≥75 Structure + VWAP + CVD or Session
(3 of 4 factors) High - Select
A Setup ≥60 Structure + VWAP + Session
(Minimum viable setup) Good - Regular
No Grade <60 Insufficient confluence Filtered out
Default Thresholds:
A Setup: 60 points
A+ Setup: 75 points
A++ Setup: 90 points
📥 Installation
Step 1: Download the Indicator
Download the market_state_engine.pine file from this repository.
Step 2: Add to TradingView
Open TradingView
Open the Pine Editor (bottom panel)
Click "New" → "Blank indicator"
Delete all default code
Paste the contents of market_state_engine.pine
Click "Add to Chart"
Step 3: Configure for Your Symbol
Click the gear icon next to the indicator name
Adjust Tick Size for your instrument:
ES futures: 0.25
NQ futures: 0.25
Stocks: 0.01
Save settings
⚙️ Configuration
Symbol Settings
Parameter Default Description
Tick Size 0.25 Minimum price movement for your symbol
Tick Buffer Count 5 Ticks beyond swing for valid break
VWAP Settings
Parameter Default Description
VWAP Band 1 (σ) 1.0 1st standard deviation multiplier
VWAP Band 2 (σ) 2.0 2nd standard deviation multiplier
VWAP Band 3 (σ) 3.0 3rd standard deviation multiplier
Session Settings
Parameter Default Description
Session 1 0300-0400 Pre-market window (NY time)
Session 2 0930-1130 Market open window (NY time)
Score Thresholds
Parameter Default Description
A Setup Threshold 60 Minimum score for A grade
A+ Setup Threshold 75 Minimum score for A+ grade
A++ Setup Threshold 90 Minimum score for A++ grade
CVD Settings
Parameter Default Description
CVD Divergence Lookback 20 Maximum bars for divergence detection
Swing Settings
Parameter Default Options Description
Swing Detection Method Wick Wick / Body Use high/low or open/close for pivots
Visual Settings
Parameter Default Description
Show VWAP Bands ✅ Display VWAP and standard deviation bands
Show Setup Labels ✅ Display setup markers on chart
Show Score Panel ✅ Display real-time score breakdown
📖 How to Use
Step 1: Apply to 1-Minute Chart
⚠️ The indicator is locked to 1-minute timeframe - do not use on other timeframes.
Step 2: Understand the Visual Signals
Setup Labels
Green Triangle (▲) - Bullish (Long) setup detected
Red Triangle (▼) - Bearish (Short) setup detected
Label shows Grade (A/A+/A++) and Total Score
VWAP Bands
Yellow Line - Session VWAP (fair value)
Blue Bands - ±1σ (fair value zone)
Purple Bands - ±2σ (moderate deviation)
Red Bands - ±3σ (extreme deviation)
Score Panel (Top Right)
Real-time breakdown of all four components:
Component Score
VWAP Zone 15/25
Structure 25/25
CVD 20/25
Session 25/25
TOTAL 85/100 (A+)
Step 3: Interpret Signals
Valid Long Setup:
✅ Green triangle below candle
✅ Price in lower VWAP bands (below VWAP)
✅ Structure shift breaks swing high
✅ Score ≥60
Valid Short Setup:
✅ Red triangle above candle
✅ Price in upper VWAP bands (above VWAP)
✅ Structure shift breaks swing low
✅ Score ≥60
Step 4: Set Up Alerts (See Alert Conditions section)
🚦 Signal Filters (VWAP Zone Logic)
The indicator uses directional VWAP filtering to prevent counter-trend signals:
Long Signals (Green)
Only allowed when price is AT or BELOW VWAP
✅ Lower 2nd band (-2σ to -1σ)
✅ Lower 3rd band (-3σ to -2σ)
✅ At VWAP exactly
❌ BLOCKED in upper bands (above VWAP)
Logic: Longs when price is stretched below fair value (mean reversion)
Short Signals (Red)
Only allowed when price is AT or ABOVE VWAP
✅ Upper 2nd band (+1σ to +2σ)
✅ Upper 3rd band (+2σ to +3σ)
✅ At VWAP exactly
❌ BLOCKED in lower bands (below VWAP)
Logic: Shorts when price is stretched above fair value (mean reversion)
🎨 Visual Elements
Chart Overlays
Element Color Description
VWAP Line Yellow Session-anchored fair value
±1σ Bands Blue Fair value zone (no score)
±2σ Bands Purple Moderate deviation (15 pts)
±3σ Bands Red Extreme deviation (25 pts)
Swing Highs Red ▼ Confirmed pivot highs
Swing Lows Green ▲ Confirmed pivot lows
Session Background Light Green Active high-value session
Setup Labels
Bullish Setup:
A+
▲ 75
Green label below candle, shows grade and score
Bearish Setup:
A++
▼ 90
Red label above candle, shows grade and score
Score Panel
Real-time table in top-right corner:
Individual component scores (0-25 each)
Total score (0-100)
Current setup grade (A/A+/A++)
Updates in real-time as market conditions change
🔔 Alert Conditions
Setting Up Alerts
Method 1: Built-in Alert Conditions
Click "Create Alert" in TradingView
Select Market State Engine as condition
Choose alert type:
Bullish Setup - Long signals only
Bearish Setup - Short signals only
Any Setup - All signals
Set to "Once Per Bar Close"
Configure notification method (app, email, webhook)
Method 2: Custom Alert Message
Alert messages include full breakdown:
A+ Setup Detected (Score: 85)
Components: VWAP(25) + Structure(25) + CVD(20) + Time(15)
CVD State: Confirmation
Direction: Long
Timeframe: 1m
Alert Behavior
✅ One alert per unique pivot break - no spam
✅ Fires on candle close only - no repainting
✅ Minimum score filter - only A grade or higher (≥60)
✅ Direction-specific - separate bullish/bearish conditions
⚠️ No cooldown between different pivots - multiple alerts per session allowed if different swing levels break
🔧 Technical Details
Timeframe Lock
Required: 1-minute chart only
Reason: Scoring model calibrated for 1m micro-structure
Future: Multi-timeframe support planned for v2
Timezone Configuration
Hard-coded: America/New_York
Session Detection: Uses TradingView's native session functions
Consistency: All time-based logic uses NY timezone
Swing Detection Parameters
Locked to specification:
ta.pivothigh(source, left=2, right=2)
ta.pivotlow(source, left=2, right=2)
Implications:
Pivots confirmed 2 bars after formation
No repainting - historical pivots don't move
4-bar minimum swing structure (2 left + pivot + 2 right)
VWAP Calculation
Type: Session-anchored (resets daily)
Source: Typical price (high + low + close) / 3
Weighting: Volume-weighted
Standard Deviation: True population standard deviation
CVD Proxy Formula
barDelta = close > open ? volume : close < open ? -volume : 0
CVD = cumulative sum of barDelta (session-reset)
Performance Limits
Max Labels: 500 (TradingView limit)
Max Bars Back: 500
Memory: Lightweight - uses only essential variables
💡 Best Practices
1. Use as a Filter, Not a Strategy
❌ Don't: Blindly take every signal
✅ Do: Use score as confluence for your existing analysis
2. Higher Grades = Better Probability
A Setups (60-74): Regular opportunities, still require discretion
A+ Setups (75-89): High-quality, multiple factors aligned
A++ Setups (90-100): Rare premium opportunities, strongest edge
3. Respect the VWAP Zone Filter
The indicator automatically blocks:
Longs in upper VWAP bands (counter-trend)
Shorts in lower VWAP bands (counter-trend)
Trust this logic - it enforces mean reversion discipline.
4. Monitor the Score Panel
Watch which components are scoring to understand why a setup formed:
Missing CVD score? → No order flow confirmation
Missing Time score? → Outside high-volume sessions
Low VWAP score? → Weak deviation from fair value
5. Combine with Risk Management
The indicator provides opportunity scoring, not position sizing:
Use stop losses based on swing structure
Scale position size with setup grade (larger on A++, smaller on A)
Set profit targets at VWAP or opposing band
6. Session Awareness
Prioritize signals during active sessions:
03:00-04:00 NY: Pre-market momentum
09:30-11:30 NY: Highest volume, tightest spreads
Off-hours signals (0 time score) are lower probability but still valid if other factors strong.
7. Understand the Hard Gate
If no structure shift occurs:
Total score = 0
No alerts fire
Other components irrelevant
Why? Structure shift confirms momentum change - without it, there's no tradable opportunity.
8. Avoid Over-Optimization
Default settings are well-calibrated:
Don't chase "perfect" parameters
Test changes on historical data before live use
Document any modifications
9. Leverage Alert De-Duplication
The indicator prevents spam automatically:
One alert per unique swing break
New swing levels = new alerts
No need to manually filter notifications
10. Supplement with Price Action
Use the indicator alongside:
Support/resistance levels
Order flow footprint charts
Volume profile
Market internals (breadth, TICK, etc.)
📚 Example Scenarios
Example 1: A++ Premium Setup (Score: 95)
Price: In lower 3rd VWAP band (-2.8σ) → VWAP: 25 pts
Structure: Close breaks swing high → Structure: 25 pts
CVD: Price LL + CVD HL (bullish div) → CVD: 25 pts
Time: 10:15 AM NY (market open) → Time: 25 pts
Direction: LONG (price below VWAP) → Valid
Grade: A++ (95/100)
Interpretation: All factors aligned - premium mean-reversion long opportunity.
Example 2: A+ Strong Setup (Score: 80)
Price: In upper 2nd VWAP band (+1.5σ) → VWAP: 15 pts
Structure: Close breaks swing low → Structure: 25 pts
CVD: Price HH + CVD LH (bearish div) → CVD: 25 pts
Time: 2:00 PM NY (off-hours) → Time: 0 pts
Direction: SHORT (price above VWAP) → Valid
Grade: A+ (65/100)
Interpretation: Strong setup despite off-hours, bearish divergence adds confidence.
Example 3: Filtered Setup (Score: 0)
Price: In upper 3rd VWAP band (+2.5σ) → VWAP: 25 pts (if allowed)
Structure: Close breaks swing high → Structure: BLOCKED
CVD: Price HH + CVD HH (confirmation) → CVD: 20 pts (if allowed)
Time: 10:00 AM NY → Time: 25 pts (if allowed)
Direction: LONG (price ABOVE VWAP) → ❌ INVALID ZONE
Grade: None (0/100) - NO ALERT
Interpretation: VWAP filter blocked long signal in upper band - prevents counter-trend trade.
🛠️ Troubleshooting
No Signals Appearing
✅ Verify you're on 1-minute chart
✅ Check Tick Size matches your symbol
✅ Ensure VWAP Bands are visible
✅ Wait for confirmed pivots (requires at least 5 bars of history)
Alerts Not Firing
✅ Confirm alert is set to "Once Per Bar Close"
✅ Check score threshold (must be ≥60 by default)
✅ Verify VWAP zone filter isn't blocking signals
✅ Check that structure shift is actually occurring
Score Always Zero
✅ No structure shift detected (hard gate active)
✅ Price may not be in valid VWAP zone (2nd or 3rd band)
✅ Insufficient swing history (wait for pivots to form)
Too Many/Too Few Signals
Too many signals:
Increase A Setup Threshold (e.g., 70 instead of 60)
Increase Tick Buffer Count (reduces false breaks)
Too few signals:
Decrease A Setup Threshold (e.g., 50 instead of 60)
Decrease Tick Buffer Count (more sensitive to breaks)
📜 License
This indicator is provided under the Mozilla Public License 2.0.
🤝 Credits
Developed as a professional trading tool for systematic opportunity identification.
Philosophy: Reduce noise. Enforce discipline. Keep the human in control.
📞 Support
For questions, issues, or feature requests, please consult:
This README documentation
The specification document (pinescript_market_state_engine_spec.docx)
Inline code comments in market_state_engine.pine
🔄 Version History
v1.0 (Current)
Initial release
4-component scoring model (VWAP + Structure + CVD + Time)
VWAP zone directional filtering
Alert de-duplication
Configurable inputs
Real-time score panel
Session-aware logic
🎓 Understanding the Numbers
Quick Reference Card
Score Range Grade Quality Typical Use
90-100 A++ Premium Highest conviction trades
75-89 A+ High Strong probability setups
60-74 A Good Acceptable with discretion
0-59 None Filtered Skip or wait for confluence
Component Contribution Examples
Minimum A Setup (60 points):
Structure (25) + VWAP 3rd band (25) + Time (25) = 75 ✅
Typical A+ Setup (75 points):
Structure (25) + VWAP 2nd band (15) + CVD confirm (20) + Time (25) = 85 ✅
Maximum A++ Setup (100 points):
Structure (25) + VWAP 3rd band (25) + CVD divergence (25) + Time (25) = 100 ✅
🎯 Final Reminder
This is NOT a trading bot.
This is NOT financial advice.
This is a decision-support tool.
Always:
✅ Use proper risk management
✅ Understand the logic before trading
✅ Backtest on your symbols
✅ Keep the human in control
Happy Trading! 📈
ALL-IN ZONE X (EMA + BB + Swing + TP Panel)ALL-IN ZONE X is a technical analysis indicator designed to help traders identify high-probability trade zones using a combination of trend, volatility, and price structure.
This indicator integrates:
Exponential Moving Averages (EMA) for trend direction
Bollinger Bands (BB) to visualize volatility and price expansion
Swing structure detection to highlight potential market turning points
A Take Profit (TP) panel to assist with structured trade planning
ALL-IN ZONE X is intended for discretionary trading and educational purposes only.
It does not generate automated buy or sell orders and should be used as a confluence tool alongside proper risk management and market analysis.
Disclaimer:
This indicator does not provide financial advice. Trading involves risk, and past performance does not guarantee future results.
Trading Range Detector - [GonzaCam]Strict Market Structure
This indicator provides a highly disciplined approach to identifying Market Structure, Swing Points, and Trading Ranges. Unlike standard fractal indicators that simply look for high/low wicks, this script enforces a "Strict" set of rules combining Fractal Geometry, Candle Color, and Close Prices to filter out noise and identify high-probability structure levels.
It is designed for traders who need precise structural mapping (BOS) and want to avoid the "fake-outs" common with standard swing indicators.
Key Features
Strict Swing Detection : A 3-candle pattern is only valid if it meets three specific criteria:
Wick Fractal: The middle candle has the highest high (for Swing Highs) or lowest low (for Swing Lows).
Close Price Fractal: The Body (Close) of the middle candle must also be the highest/lowest of the pattern, preventing weak "wick-only" pivots.
Color Logic: Enforces specific color flows (e.g., Green → Red for tops) to ensure momentum has actually shifted.
Smart Range Tracking:
Active Range: Shows the current trading range (Top and Bottom) with thick, solid lines.
Historical Structure: Automatically archives broken levels as thin, dashed lines, creating a clean history of market structure.
"True Peak" Logic: When a Break of Structure (BOS) occurs, the script enters a "Seeking" phase. It intelligently tracks the Highest High (in a bearish break) or Lowest Low (in a bullish break) to ensure the new range is drawn from the true pivot, not just the first confirmed swing.
How It Works
1. Swing High Definition
A valid Swing High is confirmed when a 3-candle cluster appears with:
Middle Candle: Green Body.
Right Candle: Red Body.
Geometry: Middle Wick High > Left & Right Wicks AND Middle Close > Left & Right Closes.
Confirmation: Price must subsequently close below the low of the middle candle.
2. Swing Low Definition
A valid Swing Low is confirmed when a 3-candle cluster appears with:
Middle Candle: Red Body.
Right Candle: Green Body.
Geometry: Middle Wick Low < Left & Right Wicks AND Middle Close < Left & Right Closes.
Confirmation: Price must subsequently close above the high of the middle candle.
3. Range & BOS Logic
Break of Structure (BOS): Triggered when a candle closes outside the current Range Top or Bottom.
Seeking Phase: After a BOS, the script waits for a new opposing swing to form.
Example: If the market breaks UP (Bullish BOS), the script searches for the next confirmed Swing High.
Optimization: While seeking, it continuously updates to the Highest High reached, ensuring the Range Top is set at the absolute peak of the move.
Settings & Customization
Current Range Style: Customize the Color, Width, and Style (Solid/Dotted) of the active range lines.
Historical Swings Style: Customize the appearance of past structure levels to distinguish them from active price action.
Disclaimer.
This tool is for informational purposes only and does not constitute financial advice. Trading involves risk. Always use proper risk management
Supply & Demand Zones [PLUS]## 🟧 OVERVIEW
Supply & Demand Zones is a professional-grade technical analysis indicator designed to automatically detect and visualize key supply and demand zones on your chart. Built on Order Block and Price Action methodology, this indicator identifies areas where institutional buyers and sellers have placed significant orders, helping traders spot high-probability reversal and continuation zones.
Whether you are a day trader, swing trader, or position trader, this indicator provides clear, actionable zones that adapt to any market and timeframe.
---
## 🟧 HOW IT WORKS
The indicator uses a sophisticated detection algorithm based on two core principles:
**Consolidation Detection**
The algorithm first identifies consolidation (base) candles where price action shows minimal directional commitment. These are candles with small body-to-range ratios, indicating accumulation or distribution phases.
**Impulse Move Validation**
After consolidation, the algorithm waits for a strong impulse move (breakout). When price makes a decisive move away from the consolidation area with sufficient momentum, a zone is created:
- Strong bullish impulse after consolidation = DEMAND zone (support)
- Strong bearish impulse after consolidation = SUPPLY zone (resistance)
**Zone Lifecycle**
Each zone follows a clear lifecycle:
- FRESH: Newly created zone, untested by price
- RETEST: Price has returned to test the zone
- BREAK: Price has closed beyond the zone boundary, invalidating it
---
## 🟧 ICT SMART MONEY CONCEPTS
This indicator aligns with ICT (Inner Circle Trader) Smart Money Concepts, making it an essential tool for traders following institutional trading methodologies:
**Order Blocks**
Supply and demand zones detected by this indicator represent Order Blocks — areas where institutional traders have placed large orders. These zones mark the origin of strong price movements and often act as future support or resistance.
**Liquidity Pools**
Fresh zones indicate areas where retail stop losses and pending orders accumulate. Smart money often targets these zones to fill large positions before reversing price direction.
**Market Structure**
By tracking zone creation, retests, and breaks, traders can identify:
- Break of Structure (BOS): When zones are broken, indicating trend continuation
- Change of Character (CHoCH): When opposing zones form, suggesting potential reversal
- Fair Value Gaps: Impulse moves away from zones often create imbalances
**Mitigation and Rejection**
The retest tracking feature helps identify mitigation blocks — zones that price returns to before continuing in the original direction. High-quality retests with strong rejection (visible in zone status) indicate institutional order flow.
**Kill Zones Integration**
Combine this indicator with session-based analysis to identify zones created during high-volume periods (London Open, New York Open, Asian Session) for higher probability setups.
---
## 🟧 KEY FEATURES
**Automatic Zone Detection**
No manual drawing required. The indicator automatically identifies and plots supply and demand zones based on proven price action patterns.
**Smart Zone Filtering**
Built-in filters prevent chart clutter by removing weak zones, merging overlapping zones, and limiting the maximum number of displayed zones.
**ATR-Based Zone Sizing**
Zone thickness is dynamically adjusted using Average True Range (ATR) to ensure zones are proportional to current market volatility.
**Fresh, Retest, and Break Tracking**
Each zone displays its current status, allowing traders to quickly identify untested zones (highest probability) versus zones that have been retested or broken.
**Customizable Visuals**
Full control over zone colors, transparency, border styles, and text sizes for both demand and supply zones.
**Real-Time Updates**
Zones extend automatically as new candles form, and status updates in real-time as price interacts with each zone.
---
## 🟧 MULTI-MARKET COMPATIBILITY
This indicator works seamlessly across all markets available on TradingView:
**Cryptocurrency**
- Bitcoin (BTC), Ethereum (ETH), and all major altcoins
- Works on spot, futures, and perpetual contracts
- Effective on 24/7 markets with continuous price action
- Adapts to high volatility environments typical of crypto markets
**Forex**
- All major pairs (EUR/USD, GBP/USD, USD/JPY, etc.)
- Cross pairs and exotic currencies
- Perfect for session-based trading (London, New York, Tokyo)
- Timezone feature helps correlate zones with market sessions
**Stocks and Indices**
- Individual stocks on NYSE, NASDAQ, and global exchanges
- Index futures (ES, NQ, YM, etc.)
- ETFs and sector-specific instruments
- Works with pre-market and after-hours data
**Commodities**
- Gold, Silver, and precious metals
- Oil, Natural Gas, and energy markets
- Agricultural commodities
The ATR-based zone sizing automatically adapts to each market's volatility characteristics, ensuring optimal zone detection regardless of the instrument you trade.
---
## 🟧 TIMEFRAME COMPATIBILITY
This indicator is fully adaptive and works on all timeframes available on TradingView:
| Timeframe Category | Examples | Best For |
|-------------------|----------|----------|
| Scalping | 1m, 3m, 5m | Quick entries, tight stops |
| Intraday | 15m, 30m, 1H | Day trading, session-based trading |
| Swing | 4H, Daily | Multi-day holds, trend following |
| Position | Weekly, Monthly | Long-term investing, major levels |
The indicator automatically adjusts its detection parameters based on the selected timeframe to provide optimal zone detection across all trading styles.
---
## 🟧 TIMEZONE SUPPORT
The indicator includes comprehensive timezone support with 70+ major world timezones. Zone creation timestamps are displayed in your selected local time, making it easy to correlate zones with specific trading sessions:
- Americas: New York, Chicago, Los Angeles, Toronto, Sao Paulo
- Europe: London, Paris, Frankfurt, Zurich, Moscow
- Asia-Pacific: Tokyo, Hong Kong, Singapore, Sydney, Dubai
- And many more...
Select your local timezone in the settings to see zone creation times in your preferred format.
---
## 🟧 DETECTION MODES
Three detection modes are available to match your trading style:
**Confirmed Only (Default)**
Zones are only created after the candle closes. This provides the most reliable signals with zero repaint risk. Recommended for most traders.
**Realtime Preview**
Zones can be created on the current candle before it closes. Provides faster signals but with minor noise potential.
**Realtime Aggressive**
Updates on every price tick. Fastest response but highest noise. Only recommended for experienced traders who understand the tradeoffs.
---
## 🟧 WHO SHOULD USE THIS INDICATOR
This indicator is designed for:
- **Price Action Traders** who base their decisions on support and resistance levels
- **Supply and Demand Traders** looking for automated zone identification
- **Order Block Traders** who want to identify institutional order flow areas
- **ICT/Smart Money Traders** applying institutional trading concepts
- **Swing Traders** seeking key levels for entries and exits
- **Day Traders** who need quick identification of intraday levels
- **Crypto Traders** navigating volatile digital asset markets
- **Forex Traders** trading major and exotic currency pairs
- **Stock Traders** analyzing equities and indices
- **Risk Managers** who want clear zones for stop loss and take profit placement
---
## 🟧 ALERT SYSTEM
Built-in alert system notifies you of important zone events:
- **Fresh Zone Alert**: Triggered when a new zone is created
- **Retest Alert**: Triggered when price returns to test an existing zone
- **Break Alert**: Triggered when a zone is invalidated by price
Alerts can be configured to send notifications via TradingView app, email, webhook, or other supported methods.
---
## 🟧 SETTINGS OVERVIEW
**Consolidation Settings**
- Consolidation Threshold: Defines what constitutes a base candle (default 73%)
**Move Strength Settings**
- Min Move Strength: Minimum impulse required to create a zone (default 60%)
- Min Move Size (ATR): Minimum move size relative to ATR (default 0.5)
**Zone Filter Settings**
- Enable Zone Filter: Toggle all filtering on/off
- Min Zone Size (ATR): Minimum zone height filter
- Min/Max Zone Thickness: Zone size limits
- Min Base Candles: Required consolidation length
- Overlap Threshold: Controls zone merging behavior
- Max Zones Limit: Maximum zones
**Visual Settings**
- Separate color controls for Fresh and Retest zones
- Border width and style options
- Text size and color customization
- Break zone display options
---
## 🔶 UPGRADE TO PRO 🔶
Looking for more advanced features? **Supply & Demand Zones AI ** includes:
🔸 AI/ML-Based Zone Strength Scoring (0-100%)
🔸 Touch Quality and Bounce Strength Analysis
🔸 Advanced Volume Analysis and Validation
🔸 Multiple Retest Color Levels (1, 2, 3+)
🔸 Professional Break Alerts with Stop Loss Warnings
🔸 Enhanced Visual Indicators and Symbols
🔸 Base Candle Counter for Consolidation Analysis
---
## 🟧 USAGE TIPS
1. **Fresh Zones First**: Prioritize trading from fresh zones as they have the highest probability of holding.
2. **Confluence**: Combine zones with other analysis methods (trendlines, moving averages, Fibonacci) for higher probability setups.
3. **Multi-Timeframe**: Check higher timeframe zones for major levels, then use lower timeframe zones for precise entries.
4. **Risk Management**: Always place your stop loss beyond the zone boundary to account for zone breaks.
5. **Session Awareness**: Use timezone settings to understand when zones were created relative to major trading sessions.
---
## 🟧 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and use proper risk management when trading.






















