Indicator · Pine Script v5 · On the chart

River Strategy with SuperScalper by Leo

by IAMATOMIC001· code credited to leandrolopezf1920

The River Strategy with SuperScalper plots custom Bollinger Bands to form a price channel on the main chart overlay.

View on GitHub

Repaints

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code1,712
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update12 months ago31 Oct 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

1,712 lines of Pine Script v5 from Indicators/RIVER_STRAT_WITH-SUPERSCALPER_BY_LEO.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

RIVER_STRAT_WITH-SUPERSCALPER_BY_LEO.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © leandrolopezf1920

//Immagine you that the cyan lines are a River, any time the price can cross up or down this river, you must buy or sell only when the bar are dry..
//BUY at highest price of the first bar that is completely dry over the river
//SELL at the lowest price of the first bar that is completely dry under the river
//Stoploss is placed at the river bands, take profit is placed at 1:1 and 1:2 ratio, a risk money management must be applied.
//This strategy can be used with multiple time frame

//@version=5
indicator("River Strategy with SuperScalper by Leo", shorttitle="River Strategy by Leo", overlay=true, max_labels_count=500,max_lines_count=500, max_bars_back=5000)
bblenght = input.int(55, minval=1, title="Bollinger Bars Length")
bbstdev = input.float(0.2, minval=0.2, title="Bollinger Bars Standard Deviation")

// Calculate BB 55 0.2
source1 = close
basis1 = ta.sma(source1, bblenght)
dev = bbstdev * ta.stdev(source1, bblenght)
upperBB = basis1 + dev
lowerBB = basis1 - dev

// is over the top?
isOverBBTop = ta.lowest(low, 1) > upperBB
isUnderBBBottom = ta.highest(high, 1) < lowerBB
newisOverBBTop = ta.change(isOverBBTop)
newisUnderBBBottom = ta.change(isUnderBBBottom)

// receive high and low range
high_range = ta.valuewhen(newisOverBBTop, high, 0)
low_range = ta.valuewhen(newisUnderBBBottom, low, 0)

bblow = ta.valuewhen(newisOverBBTop, (lowerBB / 0.00005) * 0.00005, 0)
bbhigh = ta.valuewhen(newisUnderBBBottom, (((upperBB * 1000) / 5) + 5) * 5 / 1000, 0)

// take it only if over the BB limit
buy_limit_entry = isOverBBTop ? (high_range == high_range[1] ? high_range + 0.001 : na) : na
sell_limit_entry = isUnderBBBottom ? (low_range == low_range[1] ? low_range - 0.001 : na) : na

take_profit_buy = isOverBBTop ? (high_range == high_range[1] ? buy_limit_entry + buy_limit_entry - bblow : na) : na
take_profit_sell = isUnderBBBottom ? (low_range == low_range[1] ? sell_limit_entry - (bbhigh - sell_limit_entry) : na) : na

take_profit2_buy = isOverBBTop ? (high_range == high_range[1] ? buy_limit_entry + 2 * (buy_limit_entry - bblow) : na) : na
take_profit2_sell = isUnderBBBottom ? (low_range == low_range[1] ? sell_limit_entry - 2 * (bbhigh - sell_limit_entry) : na) : na

stop_loss_buy = isOverBBTop ? (high_range == high_range[1] ? bblow : na) : na
stop_loss_sell = isUnderBBBottom ? (low_range == low_range[1] ? bbhigh : na) : na

highlightHigh = isOverBBTop ? color.lime : color.aqua
highlightLow = isUnderBBBottom ? color.lime : color.aqua

colorLineUp = buy_limit_entry ? color.blue : color.blue
colorLineDown = sell_limit_entry ? color.red : color.red

colorBuyTP = close >= take_profit_buy ? color.lime : color.fuchsia
colorSellTP = close <= take_profit_sell ? color.lime : color.fuchsia
colorBuyTP2 = close >= take_profit2_buy ? color.lime : color.fuchsia
colorSellTP2 = close <= take_profit2_sell ? color.lime : color.fuchsia

// Plot Statements
var int daysToShow = 5
var int msInDay = 86400000
var int now = timenow

plotCondition = (now - time < daysToShow * msInDay)

bbup = plot(plotCondition ? upperBB : na, title="BB Upper Band", style=plot.style_linebr, linewidth=2, color=highlightHigh)
bbdo = plot(plotCondition ? lowerBB : na, title="BB Bottom Band", style=plot.style_linebr, linewidth=2, color=highlightLow)
plot(plotCondition ? buy_limit_entry : na, title="Buy Entry", style=plot.style_linebr, linewidth=2, color=colorLineUp, transp=50)
plot(plotCondition ? sell_limit_entry : na, title="Short Entry", style=plot.style_linebr, linewidth=2, color=colorLineDown, transp=50)
plot(plotCondition ? stop_loss_buy : na, title="Buy Stop Loss", style=plot.style_circles, linewidth=2, color=color.rgb(136, 14, 79, 30))
plot(plotCondition ? stop_loss_sell : na, title="Short Stop Loss", style=plot.style_circles, linewidth=2, color=color.rgb(136, 14, 79, 30))
plot(plotCondition ? take_profit_buy : na, title="Buy TP 1:1", style=plot.style_circles, linewidth=2, color=colorBuyTP, transp=30)
plot(plotCondition ? take_profit_sell : na, title="Short TP 1:1", style=plot.style_circles, linewidth=2, color=colorSellTP, transp=30)
plot(plotCondition ? take_profit2_buy : na, title="Buy TP2 1:2", style=plot.style_circles, linewidth=2, color=colorBuyTP2, transp=30)
plot(plotCondition ? take_profit2_sell : na, title="Short TP2 1:2", style=plot.style_circles, linewidth=2, color=colorSellTP2, transp=30)
fill(bbup, bbdo, color=color.rgb(0, 187, 212, 80))

// Add labels
var label tp1Label = na
if (not na(take_profit_buy) and na(tp1Label) and plotCondition)
    tp1Label := label.new(x=bar_index, y=take_profit_buy, text="TP1", color=#ffffff00, textcolor=color.green, style=label.style_label_left)
if (not na(tp1Label))
    label.set_text(tp1Label, "TP1 Buy: " + str.tostring(math.round_to_mintick(take_profit_buy)))
    label.set_x(tp1Label, bar_index)
    label.set_y(tp1Label, take_profit_buy)

var label tp1SellLabel = na
if (not na(take_profit_sell) and na(tp1SellLabel) and plotCondition)
    tp1SellLabel := label.new(x=bar_index, y=take_profit_sell, text="TP1 Sell", color=#ffffff00, textcolor=color.red, style=label.style_label_left)
if (not na(tp1SellLabel))
    label.set_text(tp1SellLabel, "TP1 Sell: " + str.tostring(math.round_to_mintick(take_profit_sell)))
    label.set_x(tp1SellLabel, bar_index)
    label.set_y(tp1SellLabel, take_profit_sell)

var label tp2BuyLabel = na
if (not na(take_profit2_buy) and na(tp2BuyLabel) and plotCondition)
    tp2BuyLabel := label.new(x=bar_index, y=take_profit2_buy, text="TP2", color=#ffffff00, textcolor=color.green, style=label.style_label_left)
if (not na(tp2BuyLabel))
    label.set_text(tp2BuyLabel, "TP2 Buy: " + str.tostring(math.round_to_mintick(take_profit2_buy)))
    label.set_x(tp2BuyLabel, bar_index)
    label.set_y(tp2BuyLabel, take_profit2_buy)

var label tp2SellLabel = na
if (not na(take_profit2_sell) and na(tp2SellLabel) and plotCondition)
    tp2SellLabel := label.new(x=bar_index, y=take_profit2_sell, text="TP2 Sell", color=#ffffff00, textcolor=color.red, style=label.style_label_left)
if (not na(tp2SellLabel))
    label.set_text(tp2SellLabel, "TP2 Sell: " + str.tostring(math.round_to_mintick(take_profit2_sell)))
    label.set_x(tp2SellLabel, bar_index)
    label.set_y(tp2SellLabel, take_profit2_sell)

var label buyLimitLabel = na
if (not na(buy_limit_entry) and na(buyLimitLabel) and plotCondition)
    buyLimitLabel := label.new(x=bar_index, y=buy_limit_entry, text="Buy Entry", color=#ffffff00, textcolor=color.blue, style=label.style_label_center)
if (not na(buyLimitLabel))
    label.set_x(buyLimitLabel, bar_index)
    label.set_y(buyLimitLabel, buy_limit_entry)

var label sellLimitLabel = na
if (not na(sell_limit_entry) and na(sellLimitLabel) and plotCondition)
    sellLimitLabel := label.new(x=bar_index, y=sell_limit_entry, text="Sell Entry", color=#ffffff00, textcolor=color.blue, style=label.style_label_center)
if (not na(sellLimitLabel))
    label.set_x(sellLimitLabel, bar_index)
    label.set_y(sellLimitLabel, sell_limit_entry)

var label stopLossBuyLabel = na
if (not na(stop_loss_buy) and na(stopLossBuyLabel) and plotCondition)
    stopLossBuyLabel := label.new(x=bar_index, y=stop_loss_buy, text="SL Buy", color=#ffffff00, textcolor=color.maroon,style=label.style_label_center)
if (not na(stopLossBuyLabel))
    label.set_x(stopLossBuyLabel, bar_index)
    label.set_y(stopLossBuyLabel, stop_loss_buy)

var label stopLossSellLabel = na
if (not na(stop_loss_sell) and na(stopLossSellLabel) and plotCondition)
    stopLossSellLabel := label.new(x=bar_index, y=stop_loss_sell, text="SL Sell", color=#ffffff00, textcolor=color.maroon,style=label.style_label_center)
if (not na(stopLossSellLabel))
    label.set_x(stopLossSellLabel, bar_index)
    label.set_y(stopLossSellLabel, stop_loss_sell)

////////////////////////////////////////////////////////////////////////////////
// Slaya-Wolf-SuperScalper BY LEO
////////////////////////////////////////////////////////////////////////////////

// SIGNAL MEANINGS//
//"Buy Label" = Strong Buy//
//"Sell Label" = Strong Sell//
//"Don't Long" = Green Cross//
//"Don't Short" = Red Cross//
//"Weak Buy " = Green Circle//
//"Weak Sell" = Red Circle//
//"Reversal Buy" = Green Diamond//
//"Reversal Sell" = Red Diamond//

// Get user settings
res               = input.timeframe(title='TIMEFRAME', defval='1h', group ="NON REPAINT HA")
showBuySell       = input(true, "BUY/SELL SIGNALS ON/OFF", group="BUY & SELL SIGNALS")
sensitivity       = input.float(2.7, "SENSITIVITY (1-6)", 0.1, 10, group="BUY & SELL SIGNALS")
percentStop       = input.float(1.0, "STOP LOSS %", 0, group="BUY & SELL SIGNALS")
percentTake       = input.float(0.2, "TAKE PROFIT %", 0, group="BUY & SELL SIGNALS")
percentTake2      = input.float(0.4, "TAKE PROFIT2 %", 0, group="BUY & SELL SIGNALS")
percentTake3      = input.float(0.6, "TAKE PROFIT3 %", 0, group="BUY & SELL SIGNALS")
percentTake4      = input.float(0.8, "TAKE PROFIT4 %", 0, group="BUY & SELL SIGNALS")
percentTake5      = input.float(1, "TAKE PROFIT5 %", 0, group="BUY & SELL SIGNALS")
//Strong Buy/Sell
showStrongBuySell  = input(true, "STRONG BUY/SELL SIGNALS ON/OFF", group="STRONG BUY & SELL SIGNALS")
sensitivity2       = input.float(13, "SENSITIVITY", 0.1, 20, group="STRONG BUY & SELL SIGNALS")
percentStrongStop       = input.float(1.0, "STOP LOSS %", 0)
percentStrongTake       = input.float(0.2, "TAKE PROFIT %", 0)
percentStrongTake2      = input.float(0.4, "TAKE PROFIT2 %", 0)
percentStrongTake3      = input.float(0.6, "TAKE PROFIT3 %", 0)
percentStrongTake4      = input.float(0.8, "TAKE PROFIT4 %", 0)
percentStrongTake5      = input.float(1, "TAKE PROFIT5 %", 0)

offsetSignal      = input.float(1, "SIGNAL OFFSET", 0, group="BUY & SELL SIGNALS")
showReversal      = input(true, "REVERSAL SIGNALS ON/OFF", group="BUY & SELL SIGNALS")
// Entry & Exit
enableE           = input(true, "EXIT & ENTRY ON/OFF", group="EXIT & ENTRY")
//Stop              = input.color(color.new(#83868f, 5), "STOP LOSS", group="EXIT & ENTRY")
Entry             = input.color(#be00104c, "ENTRY", group="EXIT & ENTRY")
Tp1               = input.color(#00be064d, "TAKE PROFIT", group="EXIT & ENTRY")
// Supply & Demand
enableSD          = input(true, "SUPPLY & DEMAND ON/OFF", group="SUPPLY & DEMAND")
mitigation        = input.string('Wick', 'MITIGATION', options = ['Wick', 'Close'], group ="SUPPLY & DEMAND")
length            = input.int(20, 'VOLUME PIVOT', minval = 1, group ="SUPPLY & DEMAND")
bull_ext_last     = input.int(1, 'DEMAND', minval = 1, inline = 'bull', group ="SUPPLY & DEMAND")
bull_avg_css      = input.color(color.rgb(0, 221, 255, 50), '', inline = 'bull', group ="SUPPLY & DEMAND")
bull_css          = input.color(color.new(#00000000, 100), '', inline = 'bull', group ="SUPPLY & DEMAND")
bg_bull_css       = input.color(color.new(#00ff0a, 90), '', inline = 'bull', group ="SUPPLY & DEMAND")
bear_ext_last     = input.int(1, 'SUPPLY', minval = 1 , inline = 'bear', group ="SUPPLY & DEMAND")
bear_avg_css      = input.color(color.rgb(233, 30, 98, 50), '', inline = 'bear', group ="SUPPLY & DEMAND")
bear_css          = input.color(color.new(#00000000, 100), '', inline = 'bear', group ="SUPPLY & DEMAND")
bg_bear_css       = input.color(color.new(#ff0015, 90), '', inline = 'bear', group ="SUPPLY & DEMAND")
line_style        = input.string("Solid", "LINE STYLE", ["Solid", "Dotted", "Dashed"], group ="SUPPLY & DEMAND")
line_width        = input.int(2, 'LINE WIDTH', minval = 1, group ="SUPPLY & DEMAND")
// Support & Resistance
enableSR          = input(true, "SUPPORT & RESISTANCE ON/Off", group="SUPPORT & RESISTANCE")
colorSup          = input(#00ddff81, "SUPPORT", group="SUPPORT & RESISTANCE")
colorRes          = input(color.rgb(233, 30, 98, 50), "RESISTANCE", group="SUPPORT & RESISTANCE")
strengthSR        = input.int(6, "S/R STRENGTH", 1, group="SUPPORT & RESISTANCE")
lineStyle1        = input.string("Dashed", "LINE STYLE", ["Solid", "Dotted", "Dashed"], group="SUPPORT & RESISTANCE")
lineWidth1        = input.int(2, "LINE WIDTH", 1, group="SUPPORT & RESISTANCE")
expandSR          = input(true, "EXTEND LINES", group = "SUPPORT & RESISTANCE")
useZones          = input(true, "ZONE ON/OFF", group="SUPPORT & RESISTANCE")
useHLZones        = input(true, "HIGH LOW ZONES ON/OFF", group="SUPPORT & RESISTANCE")
zoneWidth         = input.int(4, "ZONE WIDTH %", 0, tooltip="it's calculated using % of the distance between highest/lowest in last 300 bars", group="SUPPORT & RESISTANCE")


// Create non-repainting security function
rp_security(_symbol, _res, _src) =>
    request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])

htfHigh = rp_security(syminfo.tickerid, res, high)
htfLow = rp_security(syminfo.tickerid, res, low)

// Main Indicator
// Functions
smoothrng(x, t, m) =>
    wper = t * 2 - 1
    avrng = ta.ema(math.abs(x - x[1]), t)
    smoothrng = ta.ema(avrng, wper) * m
rngfilt(x, r) =>
    rngfilt = x
    rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
securityNoRep(sym, res, src) => request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on)
swingPoints(prd1) =>
    pivHi = ta.pivothigh(prd1, prd1)
    pivLo = ta.pivotlow (prd1, prd1)
    last_pivHi = ta.valuewhen(pivHi, pivHi, 1)
    last_pivLo = ta.valuewhen(pivLo, pivLo, 1)
    hh = pivHi and pivHi > last_pivHi ? pivHi : na
    lh = pivHi and pivHi < last_pivHi ? pivHi : na
    hl = pivLo and pivLo > last_pivLo ? pivLo : na
    ll = pivLo and pivLo < last_pivLo ? pivLo : na
    [hh, lh, hl, ll]
f_chartTfInMinutes() =>
    float _resInMinutes = timeframe.multiplier * (
      timeframe.isseconds ? 1                   :
      timeframe.isminutes ? 1.                  :
      timeframe.isdaily   ? 60. * 24            :
      timeframe.isweekly  ? 60. * 24 * 7        :
      timeframe.ismonthly ? 60. * 24 * 30.4375  : na)
f_kc(src, len, sensitivity) =>
    basis1 = ta.sma(src, len)
    span  = ta.atr(len)
    [basis1 + span * sensitivity, basis1 - span * sensitivity]
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)
    [wt1, wt2]
f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0]
f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0]
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[2] >= topLimit ? src[2] : na
    fractalBot = f_fractalize(src) < 0 and src[2] <= botLimit ? src[2] : na
    highPrev = ta.valuewhen(fractalTop, src[2], 0)[2]
    highPrice = ta.valuewhen(fractalTop, high[2], 0)[2]
    lowPrev = ta.valuewhen(fractalBot, src[2], 0)[2]
    lowPrice = ta.valuewhen(fractalBot, low[2], 0)[2]
    bearSignal = fractalTop and high[1] > highPrice and src[1] < highPrev
    bullSignal = fractalBot and low[1] < lowPrice and src[1] > lowPrev
    [bearSignal, bullSignal]

// Get components
source    = input(close, title = "Smoothring Source", group = "Smoothing")
smrng1_input= input.int(200, "Smring1", 1, 200 , 1 , group = "Smoothing")
smrng1_sens = input.float(defval = 13.0,title = "sens",minval = 0.1, maxval = 50 , step = 0.01 , group = "Smoothing")
smrng2_input= input.int(32, "Smring2", 1, 500 , 1 , group = "Smoothing")
smrng1    = smoothrng(source, smrng1_input, smrng1_sens)
smrng2    = smoothrng(source, smrng2_input, sensitivity)
smrng     = (smrng1 + smrng2) / 2
filt      = rngfilt(source, smrng)
up        = 0.0, up := filt > filt[1] ? nz(up[1]) + 1 : filt < filt[1] ? 0 : nz(up[1])
dn        = 0.0, dn := filt < filt[1] ? nz(dn[1]) + 1 : filt > filt[1] ? 0 : nz(dn[1])
bullCond  = bool(na), bullCond := source > filt and source > source[1] and up > 0 or source > filt and source < source[1] and up > 0
bearCond  = bool(na), bearCond := source < filt and source < source[1] and dn > 0 or source < filt and source > source[1] and dn > 0
lastCond  = 0, lastCond := bullCond ? 1 : bearCond ? -1 : lastCond[1]
bull      = bullCond and lastCond[1] == -1
bear      = bearCond and lastCond[1] == 1
smrng3    = smoothrng(source, smrng2_input, sensitivity2)
smrngstrong     = (smrng1 + smrng3) / 2
filt2      = rngfilt(source, smrngstrong)
up2        = 0.0, up2 := filt2 > filt2[1] ? nz(up2[1]) + 1 : filt2 < filt2[1] ? 0 : nz(up2[1])
dn2        = 0.0, dn2 := filt2 < filt2[1] ? nz(dn2[1]) + 1 : filt2 > filt2[1] ? 0 : nz(dn2[1])
strongbullCond  = bool(na), strongbullCond := source > filt2 and source > source[1] and up2 > 0 or source > filt2 and source < source[1] and up2 > 0
strongbearCond  = bool(na), strongbearCond := source < filt2 and source < source[1] and dn2 > 0 or source < filt2 and source > source[1] and dn2 > 0
lastCond2  = 0, lastCond2 := strongbullCond ? 1 : strongbearCond ? -1 : lastCond2[1]
strongbull      = strongbullCond and lastCond2[1] == -1
strongbear      = strongbearCond and lastCond2[1] == 1
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
countStrongBull = ta.barssince(strongbull)
countStrongBear = ta.barssince(strongbear)
trigger   = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
rsi       = ta.rsi(close, 28)
rsiOb     = rsi > 68 and rsi > ta.ema(rsi, 10)
rsiOs     = rsi < 28 and rsi < ta.ema(rsi, 10)
dHigh     = securityNoRep(syminfo.tickerid, "D", high [1])
dLow      = securityNoRep(syminfo.tickerid, "D", low  [1])
dClose    = securityNoRep(syminfo.tickerid, "D", close[1])
ema = ta.ema(close, 144)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep1(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()) + (timeframe.isseconds ? "S" : "") : 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   = securityNoRep1(syminfo.tickerid, "1"   , emaBull)
TF3Bull   = securityNoRep1(syminfo.tickerid, "3"   , emaBull)
TF5Bull   = securityNoRep1(syminfo.tickerid, "5"   , emaBull)
TF15Bull  = securityNoRep1(syminfo.tickerid, "15"  , emaBull)
TF30Bull  = securityNoRep1(syminfo.tickerid, "30"  , emaBull)
TF60Bull  = securityNoRep1(syminfo.tickerid, "60"  , emaBull)
TF120Bull = securityNoRep1(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep1(syminfo.tickerid, "240" , emaBull)
TF480Bull = securityNoRep1(syminfo.tickerid, "480" , emaBull)
TFDBull   = securityNoRep1(syminfo.tickerid, "1440", emaBull)
[wt1, wt2] = wavetrend(close, 5, 10)
[wtDivBear1, wtDivBull1] = f_findDivs(wt2, 15, -40)
[wtDivBear2, wtDivBull2] = f_findDivs(wt2, 45, -65)
wtDivBull = wtDivBull1 or wtDivBull2
wtDivBear = wtDivBear1 or wtDivBear2


// Colors
white = #00e4fd, white30 = color.new(white, 100)
blue = #fd00a4, blue30 = color.new(blue, 100)
whiteish  = #ffffff, whiteish30  = color.new(whiteish , 100)
Stop = color.rgb(253, 0, 164, 50)

// Plot
off = percWidth(300, offsetSignal)
//barcolor(up > dn ? white : blue)
plotshape(showBuySell and bull ? low  - off : na, "Buy Label" , shape.labelup  , location.absolute, color(#028a14), 0, "Buy" , color.white, size=size.tiny)
plotshape(showBuySell and bear ? high + off : na, "Sell Label", shape.labeldown, location.absolute, color(#8b010d), 0, "Sell", color.white, size=size.tiny)
plotshape(showStrongBuySell and strongbull ? low  - off : na, "Strong Buy Label" , shape.labelup  , location.absolute, color(#028a14), 0, "Strong-Buy" , color.white, size=size.tiny)
plotshape(showStrongBuySell and strongbear ? high + off : na, "Strong Sell Label", shape.labeldown, location.absolute, color(#8b010d), 0, "Strong-Sell", color.white, size=size.tiny)
//plotshape(ta.crossover(wt1, wt2) and wt2 <= -53, "Don't Sell/Bottom" , shape.xcross, location.belowbar, color(#fd0015), size=size.tiny)
//plotshape(ta.crossunder(wt1, wt2) and wt2 >= 53, "Don't Buy/Top", shape.xcross, location.abovebar, color(#00ff22), size=size.tiny)
//plotshape(wtDivBull, "Weak Buy ", shape.circle  , location.belowbar, color(#00ff22), size=size.auto)
//plotshape(wtDivBear, "Weak Sell", shape.circle, location.abovebar, color(#fd0015), size=size.auto)
//plotshape(showReversal and rsiOs, "Reversal Buy" , shape.diamond, location.belowbar, color(#00ff22), size=size.tiny)
//plotshape(showReversal and rsiOb, "Reversal Sell", shape.diamond, location.abovebar, color(#fd0015), size=size.tiny)

srcStop = close
atrBand = srcStop * (percentStop / 700)
atrBand2 = srcStop * (percentTake / 100)
atrBand3 = srcStop * (percentTake2 / 100)
atrBand4 = srcStop * (percentTake3 / 100)
atrBand5 = srcStop * (percentTake4 / 100)
atrBand6 = srcStop * (percentTake5 / 100)
atrStop = trigger ? srcStop - atrBand : srcStop + atrBand
atrTake = trigger ? srcStop - atrBand2 : srcStop + atrBand2
atrTake2 = trigger ? srcStop - atrBand3 : srcStop + atrBand3
atrTake3 = trigger ? srcStop - atrBand4 : srcStop + atrBand4
atrTake4 = trigger ? srcStop - atrBand5 : srcStop + atrBand5
atrTake5 = trigger ? srcStop - atrBand6 : srcStop + atrBand6
lastTrade(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade(srcStop)
stop_y = lastTrade(atrStop)
tp1_y = (entry_y - lastTrade(atrTake)) + entry_y
tp2_y = (entry_y - lastTrade(atrTake2)) + entry_y
tp3_y = (entry_y - lastTrade(atrTake3)) + entry_y
tp4_y = (entry_y - lastTrade(atrTake4)) + entry_y
tp5_y = (entry_y - lastTrade(atrTake5)) + entry_y

// Labels
labelTpSl(y, txt, color) =>
    label labelTpSl = percentStop and enableE != 0 ? 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[1])
labelTpSl(entry_y, "Entry: " + str.tostring(math.round_to_mintick(entry_y)), color = Entry)
labelTpSl(stop_y , "StopLoss: " + str.tostring(math.round_to_mintick(stop_y)), color = Stop)
labelTpSl(tp1_y, "Take Profit 1: " + str.tostring(math.round_to_mintick(tp1_y)), color = Tp1)
labelTpSl(tp2_y, "Take Profit 2: " + str.tostring(math.round_to_mintick(tp2_y)), color = Tp1)
labelTpSl(tp3_y, "Take Profit 3: " + str.tostring(math.round_to_mintick(tp3_y)), color = Tp1)
labelTpSl(tp4_y, "Take Profit 4: " + str.tostring(math.round_to_mintick(tp4_y)), color = Tp1)
labelTpSl(tp5_y, "Take Profit 5: " + str.tostring(math.round_to_mintick(tp5_y)), color = Tp1)
lineTpSl(y, color) =>
    line lineTpSl = percentStop and enableE != 0 ? line.new(bar_index - (trigger ? countBull : countBear) + 4, y, bar_index + 1, y, xloc.bar_index, extend.none, color, line.style_solid) : na
    line.delete(lineTpSl[1])
lineTpSl(entry_y, color = Entry)
lineTpSl(stop_y, color = Stop)
lineTpSl(tp1_y, color = Tp1)
lineTpSl(tp2_y, color = Tp1)
lineTpSl(tp3_y, color = Tp1)
lineTpSl(tp4_y, color = Tp1)
lineTpSl(tp5_y, color = Tp1)

// SUPPLY & DEMAND
//Functions 

//Line Style function
get_line_style(style) =>
    out = switch style
        'Solid'  => line.style_solid
        'Dashed' => line.style_dashed
        'Dotted' => line.style_dotted

//Function to get order block coordinates
get_coordinates(condition, top, btm, ob_val)=>
    var ob_top  = array.new_float(0)
    var ob_btm  = array.new_float(0)
    var ob_avg  = array.new_float(0)
    var ob_left = array.new_int(0)

    float ob = na

    //Append coordinates to arrays
    if condition and enableSD
        avg = math.avg(top, btm)
        
        array.unshift(ob_top, top)
        array.unshift(ob_btm, btm)
        array.unshift(ob_avg, avg)
        array.unshift(ob_left, time[length])
        
        ob := ob_val
    
    [ob_top, ob_btm, ob_avg, ob_left, ob]

//Function to remove mitigated order blocks from coordinate arrays
remove_mitigated(ob_top, ob_btm, ob_left, ob_avg, target, bull)=>
    mitigated = false
    target_array = bull ? ob_btm : ob_top

    for element in target_array
        idx = array.indexof(target_array, element)

        if (bull ? target < element : target > element)
            mitigated := true

            array.remove(ob_top, idx)
            array.remove(ob_btm, idx)
            array.remove(ob_avg, idx)
            array.remove(ob_left, idx)
    
    mitigated

//Function to set order blocks
set_order_blocks(ob_top, ob_btm, ob_left, ob_avg, ext_last, bg_css, border_css, lvl_css)=>
    var ob_box = array.new_box(0)
    var ob_lvl = array.new_line(0)

    //Fill arrays with boxes/lines
    if barstate.isfirst
        for i = 0 to ext_last-1
            array.unshift(ob_box, box.new(na,na,na,na
              , xloc = xloc.bar_time
              , extend= extend.right
              , bgcolor = bg_css
              , border_color = color.new(border_css, 70)))

            array.unshift(ob_lvl, line.new(na,na,na,na
              , xloc = xloc.bar_time
              , extend = extend.right
              , color = lvl_css
              , style = get_line_style(line_style)
              , width = line_width))

    //Set order blocks
    if barstate.islast
        if array.size(ob_top) > 0
            for i = 0 to math.min(ext_last-1, array.size(ob_top)-1)
                get_box = array.get(ob_box, i)
                get_lvl = array.get(ob_lvl, i)

                box.set_lefttop(get_box, array.get(ob_left, i), array.get(ob_top, i))
                box.set_rightbottom(get_box, array.get(ob_left, i), array.get(ob_btm, i))

                line.set_xy1(get_lvl, array.get(ob_left, i), array.get(ob_avg, i))
                line.set_xy2(get_lvl, array.get(ob_left, i)+1, array.get(ob_avg, i))

//Global elements 
var os = 0
var target_bull = 0.
var target_bear = 0.

n = bar_index
upper = ta.highest(length)
lower = ta.lowest(length)

if mitigation == 'Close'
    target_bull := ta.lowest(close, length)
    target_bear := ta.highest(close, length)
else
    target_bull := lower
    target_bear := upper

os := high[length] > upper ? 0 : low[length] < lower ? 1 : os[1]

phv = ta.pivothigh(volume, length, length)


//Get bullish/bearish order blocks coordinates 
[bull_top
  , bull_btm
  , bull_avg
  , bull_left
  , bull_ob] = get_coordinates(phv and os == 1, hl2[length], low[length], low[length])

[bear_top
  , bear_btm
  , bear_avg
  , bear_left
  , bear_ob] = get_coordinates(phv and os == 0, high[length], hl2[length], high[length])

//Remove mitigated order blocks
mitigated_bull = remove_mitigated(bull_top
  , bull_btm
  , bull_left
  , bull_avg
  , target_bull
  , true)

mitigated_bear = remove_mitigated(bear_top
  , bear_btm
  , bear_left
  , bear_avg
  , target_bear
  , false)

//Set bullish order blocks
set_order_blocks(bull_top
  , bull_btm
  , bull_left
  , bull_avg
  , bull_ext_last
  , bg_bull_css
  , bull_css
  , bull_avg_css)

//Set bearish order blocks
set_order_blocks(bear_top
  , bear_btm
  , bear_left
  , bear_avg
  , bear_ext_last
  , bg_bear_css
  , bear_css
  , bear_avg_css)

// SUPPORT & RESISTANCE

percWidth1(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100

// Get components
rb            = 10
prd1           = 284
ChannelW      = 10
label_loc     = 55
style1        = lineStyle1 == "Solid" ? line.style_solid : lineStyle1 == "Dotted" ? line.style_dotted :  line.style_dashed
ph            = ta.pivothigh(rb, rb)
pl            = ta.pivotlow (rb, rb)
sr_levels     = array.new_float(21, na)
prdhighest    = ta.highest(prd1)
prdlowest     = ta.lowest(prd1)
cwidth        = percWidth(prd1, ChannelW)
zonePerc      = percWidth(300, zoneWidth)
aas           = array.new_bool(41, true)
u1            = 0.0, u1 := nz(u1[1])
d1            = 0.0, d1 := nz(d1[1])
highestph     = 0.0, highestph := highestph[1]
lowestpl      = 0.0, lowestpl := lowestpl[1]
var sr_levs   = array.new_float(21, na)
label hlabel  = na, label.delete(hlabel[1])
label llabel  = na, label.delete(llabel[1])
var sr_lines  = array.new_line(21, na)
var sr_linesH = array.new_line(21, na)
var sr_linesL = array.new_line(21, na)
var sr_linesF = array.new_linefill(21, na)
var sr_labels = array.new_label(21, na)
if ph or pl
    for x = 0 to array.size(sr_levels) - 1
        array.set(sr_levels, x, na)
    highestph := prdlowest
    lowestpl := prdhighest
    countpp = 0
    for x = 0 to prd1
        if na(close[x])
            break
        if not na(ph[x]) or not na(pl[x])
            highestph := math.max(highestph, nz(ph[x], prdlowest), nz(pl[x], prdlowest))
            lowestpl := math.min(lowestpl, nz(ph[x], prdhighest), nz(pl[x], prdhighest))
            countpp += 1
            if countpp > 40
                break
            if array.get(aas, countpp)
                upl = (ph[x] ? high[x + rb] : low[x + rb]) + cwidth
                dnl = (ph[x] ? high[x + rb] : low[x + rb]) - cwidth
                u1 := countpp == 1 ? upl : u1
                d1 := countpp == 1 ? dnl : d1
                tmp = array.new_bool(41, true)
                cnt = 0
                tpoint = 0
                for xx = 0 to prd1
                    if na(close[xx])
                        break
                    if not na(ph[xx]) or not na(pl[xx])
                        chg = false
                        cnt += 1
                        if cnt > 40
                            break
                        if array.get(aas, cnt)
                            if not na(ph[xx])
                                if high[xx + rb] <= upl and high[xx + rb] >= dnl
                                    tpoint += 1
                                    chg := true
                            if not na(pl[xx])
                                if low[xx + rb] <= upl and low[xx + rb] >= dnl
                                    tpoint += 1
                                    chg := true
                        if chg and cnt < 41
                            array.set(tmp, cnt, false)
                if tpoint >= strengthSR
                    for g = 0 to 40 by 1
                        if not array.get(tmp, g)
                            array.set(aas, g, false)
                    if ph[x] and countpp < 21
                        array.set(sr_levels, countpp, high[x + rb])
                    if pl[x] and countpp < 21
                        array.set(sr_levels, countpp, low[x + rb])

// Plot
var line highest_ = na, line.delete(highest_)
var line lowest_  = na, line.delete(lowest_)
var line highest_fill1 = na, line.delete(highest_fill1)
var line highest_fill2 = na, line.delete(highest_fill2)
var line lowest_fill1  = na, line.delete(lowest_fill1)
var line lowest_fill2  = na, line.delete(lowest_fill2)
hi_col = close >= highestph ? colorSup : colorRes
lo_col = close >= lowestpl  ? colorSup : colorRes
if enableSR
    highest_ := line.new(bar_index - 311, highestph, bar_index, highestph, xloc.bar_index, expandSR ? extend.both : extend.right, hi_col, style1, lineWidth1)
    lowest_  := line.new(bar_index - 311, lowestpl , bar_index, lowestpl , xloc.bar_index, expandSR ? extend.both : extend.right, lo_col, style1, lineWidth1)
    if useHLZones
        highest_fill1 := line.new(bar_index - 311, highestph + zonePerc, bar_index, highestph + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
        highest_fill2 := line.new(bar_index - 311, highestph - zonePerc, bar_index, highestph - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
        lowest_fill1  := line.new(bar_index - 311, lowestpl + zonePerc , bar_index, lowestpl + zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
        lowest_fill2  := line.new(bar_index - 311, lowestpl - zonePerc , bar_index, lowestpl - zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
        linefill.new(highest_fill1, highest_fill2, color.new(hi_col, 90))
        linefill.new(lowest_fill1 , lowest_fill2 , color.new(lo_col, 90))
if ph or pl
    for x = 0 to array.size(sr_lines) - 1
        array.set(sr_levs, x, array.get(sr_levels, x))
for x = 0 to array.size(sr_lines) - 1
    line.delete(array.get(sr_lines, x))
    line.delete(array.get(sr_linesH, x))
    line.delete(array.get(sr_linesL, x))
    linefill.delete(array.get(sr_linesF, x))
    if array.get(sr_levs, x) and enableSR
        line_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
        array.set(sr_lines, x, line.new(bar_index - 355, array.get(sr_levs, x), bar_index, array.get(sr_levs, x), xloc.bar_index, expandSR ? extend.both : extend.right, line_col, style1, lineWidth1))
        if useZones
            array.set(sr_linesH, x, line.new(bar_index - 355, array.get(sr_levs, x) + zonePerc, bar_index, array.get(sr_levs, x) + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
            array.set(sr_linesL, x, line.new(bar_index - 355, array.get(sr_levs, x) - zonePerc, bar_index, array.get(sr_levs, x) - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
            array.set(sr_linesF, x, linefill.new(array.get(sr_linesH, x), array.get(sr_linesL, x), color.new(line_col, 90)))
for x = 0 to array.size(sr_labels) - 1
    label.delete(array.get(sr_labels, x))
    if array.get(sr_levs, x) and enableSR
        lab_loc = close >= array.get(sr_levs, x) ? label.style_label_up : label.style_label_down
        lab_col = close >= array.get(sr_levs, x) ? colorSup             : colorRes

// Labels for Take Profits
labelTpSl(tp1_y, "Take Profit 1: " + str.tostring(math.round_to_mintick(tp1_y)), color = Tp1)
labelTpSl(tp2_y, "Take Profit 2: " + str.tostring(math.round_to_mintick(tp2_y)), color = Tp1)
labelTpSl(tp3_y, "Take Profit 3: " + str.tostring(math.round_to_mintick(tp3_y)), color = Tp1)
labelTpSl(tp4_y, "Take Profit 4: " + str.tostring(math.round_to_mintick(tp4_y)), color = Tp1)
labelTpSl(tp5_y, "Take Profit 5: " + str.tostring(math.round_to_mintick(tp5_y)), color = Tp1)

lineTpSl(tp1_y, color = Tp1)
lineTpSl(tp2_y, color = Tp1)
lineTpSl(tp3_y, color = Tp1)
lineTpSl(tp4_y, color = Tp1)
lineTpSl(tp5_y, color = Tp1)

////////////////////////////////
//SMMA 33/144 H/L with Pivot Points
////////////////////////////////

AUTO = 'Auto'
HOURLY = 'Hourly'
DAILY = 'Daily'
WEEKLY = 'Weekly'
MONTHLY = 'Monthly'
QUARTERLY = 'Quarterly'
YEARLY = 'Yearly'
BIYEARLY = 'Biyearly'
TRIYEARLY = 'Triyearly'
QUINQUENNIAL = 'Quinquennial'


FIBONACCI = 'Fibonacci'
CAMARILLA = 'Camarilla'
DEMARK = 'OFF'


kind = input.string(title='Type', defval='Camarilla', options=[DEMARK, FIBONACCI, CAMARILLA], inline='Pi', group='Pivots')
pivot_time_frame = input.string(title='', defval=DAILY, options=[AUTO, HOURLY, DAILY, WEEKLY, MONTHLY, QUARTERLY, YEARLY, BIYEARLY, TRIYEARLY, QUINQUENNIAL], inline='Pi', group='Pivots')
look_back = input.int(title='', defval=1, minval=1, maxval=5000, inline='Pi', group='Pivots', tooltip='No Of previous Levels')
is_daily_based = input.bool(title='Use Daily-based Values', defval=true, tooltip='When this option is unchecked, Pivot Points will use intraday data while calculating on intraday charts. If Extended Hours are displayed on the chart, they will be taken into account during the pivot level calculation. If intraday OHLC values are different from daily-based values (normal for stocks), the pivot levels will also differ.')

show_labels = false  //input.bool(title="Show Labels", type=input.bool, defval=false, inline = "labels")
position_labels = input.string('Left', '', options=['Left', 'Right'], inline='labels')

swing = input.bool(defval=false, title='Swing    ', inline='Swing', group='Settings', tooltip='Turn On Swing Hi/Lo')  //
prd = input.int(defval=10, title='   ', inline='Swing', group='Settings')
ColorSelector(c_) =>
    c_ == 'aqua' ? color.aqua : c_ == 'black' ? color.black : c_ == 'blue' ? color.blue : c_ == 'fuchsia' ? color.fuchsia : c_ == 'gray' ? color.gray : c_ == 'green' ? color.green : c_ == 'lime' ? color.lime : c_ == 'maroon' ? color.maroon : c_ == 'navy' ? color.navy : c_ == 'olive' ? color.olive : c_ == 'orange' ? color.orange : c_ == 'purple' ? color.purple : c_ == 'red' ? color.red : c_ == 'silver' ? color.silver : c_ == 'teal' ? color.teal : c_ == 'white' ? color.white : c_ == 'yellow' ? color.yellow : color.black

Hi_color = input.string(title='HH', defval='orange', options=['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 'silver', 'teal', 'white', 'yellow'],inline='Swing',group='Settings')
Lo_color = input.string(title='LL', defval='black', options=['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 'silver', 'teal', 'white', 'yellow'],inline='Swing',group='Settings')
showlast = input.bool(title='Show Only Last Period', defval=true, group='Settings', tooltip='Shows only Today levels bar by bar')
showlabels = input.bool(title='Show Labels', defval=true, group='Settings', tooltip='Shows labels on plotted pivots')
ltcol    = input.color(color.black,"Target Color",inline='labels')
lbcol    = input.color(color.rgb(255, 136, 0),"Breakout/down Color",inline='labels')
lstyle2 = input.string(title='CPR Style', options=['Solid', 'Circles', 'Cross'], defval='Solid', group='Style', tooltip='Change Line Style for CPR')
cmidon = input.bool(defval=false, title='Cam Mid   ', group='Settings', tooltip='Turn Camarilla Mid')
cprturnon = input.bool(title='Turn On CPR', defval=false, group='Settings', tooltip='Turn CPR on')
JP = input.bool(title='Just Pivot', defval=false, group='Settings', tooltip='Show Only Pivot of the day')
PDHL = input.bool(false, 'Prev HiLo   ', inline='Settings', group='Settings')
PColor = input.color(color.orange, '', inline='Settings', group='Settings')
Pres = input.timeframe(defval='D', inline='Settings', group='Settings')
lvl = input.int(1, title='', inline='Settings', group='Settings')
vwaplot = input.bool(false, title='VWAP', inline='vwap', group='Settings', tooltip='Turn on Vwap')
emaplot = input.bool(false, title='EMA on   ', inline='Settings', group='Settings', tooltip='Turns On 3 Ema\'s On Chart, Levels can be Edited')
choice = input.string(title='', defval='EMA', options=['EMA', 'SMA'], inline='Settings', group='Settings', tooltip='Select Either EMA or SMA from dropdown menu')
MAa = input.int(9, title='EMA', inline='EMA', minval=1, maxval=500, group='Settings')
MAb = input.int(27, title=' ', inline='EMA', minval=1, maxval=500, group='Settings')
MAc = input.int(111, title=' ', inline='EMA', minval=1, maxval=500, group='Settings')
lw = input.int(1, title='Width', minval=1, maxval=3, inline='EMA', group='Settings')
HammerInput = input.bool(true, 'Hammer', inline='ham', group='Price Action')
HangingManInput = input.bool(true, 'Hanging Man', group='Price Action')
InvertedHammerInput = input.bool(true, 'Inverted Hammer', inline='ham', group='Price Action')

vsr = input.bool(false, title='Show Volume Based S&R', group='Settings', tooltip='Shows Volume Based Support and Resistance on Stocks and Futures')
ATRTsl = input.bool(false, 'Trailing SL', inline='atr', group='Settings', tooltip='Trailing SL')

//Pivot Settings 
var DEF_COLOR = #FB8C00
var S3_COLOR = #000000
var S4_COLOR = #ff9800
var S5_COLOR = #ff0000
var arr_time = array.new_int()
var p = array.new_float()
p_show = input.bool(false, 'P‏  ‏  ‏  ‏  ‏  ‏  ‏  ‏', inline='P')
p_color = input.color(DEF_COLOR, '', inline='P')

var r1 = array.new_float()
var s1 = array.new_float()
s1r1_show = input.bool(false, 'S1/R1', inline='S1/R1')
s1r1_color = input.color(DEF_COLOR, '', inline='S1/R1')

var r2 = array.new_float()
var s2 = array.new_float()
s2r2_show = input.bool(true, 'S2/R2', inline='S2/R2')
s2r2_color = input.color(S3_COLOR, '', inline='S2/R2')

var r3 = array.new_float()
var s3 = array.new_float()
s3r3_show = input.bool(true, 'S3/R3', inline='S3/R3')
s3r3_color = input.color(S4_COLOR, '', inline='S3/R3')

var r4 = array.new_float()
var s4 = array.new_float()
s4r4_show = input.bool(true, 'S4/R4', inline='S4/R4')
s4r4_color = input.color(S5_COLOR, '', inline='S4/R4')

var r5 = array.new_float()
var s5 = array.new_float()
s5r5_show = input.bool(true, 'S5/R5', inline='S5/R5')
s5r5_color = input.color(S5_COLOR, '', inline='S5/R5')

pivotX_open = float(na)
pivotX_open := nz(pivotX_open[1], open)
pivotX_high = float(na)
pivotX_high := nz(pivotX_high[1], high)
pivotX_low = float(na)
pivotX_low := nz(pivotX_low[1], low)
pivotX_prev_open = float(na)
pivotX_prev_open := nz(pivotX_prev_open[1])
pivotX_prev_high = float(na)
pivotX_prev_high := nz(pivotX_prev_high[1])
pivotX_prev_low = float(na)
pivotX_prev_low := nz(pivotX_prev_low[1])
pivotX_prev_close = float(na)
pivotX_prev_close := nz(pivotX_prev_close[1])

get_pivot_resolution() =>
    resolution = 'M'
    if pivot_time_frame == AUTO
        if timeframe.isintraday
            resolution := timeframe.multiplier <= 15 ? 'D' : 'W'
            resolution
        else if timeframe.isweekly or timeframe.ismonthly
            resolution := '12M'
            resolution
    else if pivot_time_frame == HOURLY
        resolution := '240'
        resolution
    else if pivot_time_frame == DAILY
        resolution := 'D'
        resolution
    else if pivot_time_frame == WEEKLY
        resolution := 'W'
        resolution
    else if pivot_time_frame == MONTHLY
        resolution := 'M'
        resolution
    else if pivot_time_frame == QUARTERLY
        resolution := '3M'
        resolution
    else if pivot_time_frame == YEARLY or pivot_time_frame == BIYEARLY or pivot_time_frame == TRIYEARLY or pivot_time_frame == QUINQUENNIAL
        resolution := '12M'
        resolution
    resolution

var lines = array.new_line()
var labels = array.new_label()

draw_line(i, pivot, col) =>
    if array.size(arr_time) > 1
        array.push(lines, line.new(array.get(arr_time, i), array.get(pivot, i), array.get(arr_time, i + 1), array.get(pivot, i), color=col, xloc=xloc.bar_time))

draw_label(i, y, txt, txt_color) =>
    if show_labels
        offset = '‏  ‏  ‏  ‏  ‏'
        labels_align_str_left = position_labels == 'Left' ? txt + offset : offset + txt
        x = position_labels == 'Left' ? array.get(arr_time, i) : array.get(arr_time, i + 1)
        array.push(labels, label.new(x=x, y=y, text=labels_align_str_left, textcolor=txt_color, style=label.style_label_center, color=#00000000, xloc=xloc.bar_time))


fibonacci() =>
    pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3
    pivot_range = pivotX_prev_high - pivotX_prev_low
    array.push(p, pivotX_Median)
    array.push(r1, pivotX_Median + 0.382 * pivot_range)
    array.push(s1, pivotX_Median - 0.382 * pivot_range)
    array.push(r2, pivotX_Median + 0.618 * pivot_range)
    array.push(s2, pivotX_Median - 0.618 * pivot_range)
    array.push(r3, pivotX_Median + 1 * pivot_range)
    array.push(s3, pivotX_Median - 1 * pivot_range)
    array.push(r4, pivotX_Median + 1.272 * pivot_range)
    array.push(s4, pivotX_Median - 1.272 * pivot_range)
    array.push(r5, pivotX_Median + 1.618 * pivot_range)
    array.push(s5, pivotX_Median - 1.618 * pivot_range)


camarilla() =>
    pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3
    pivot_range = pivotX_prev_high - pivotX_prev_low
    H4 = pivotX_prev_close + pivot_range * 1.1 / 2
    H3 = pivotX_prev_close + pivot_range * 1.1 / 4
    H2 = pivotX_prev_close + pivot_range * 1.1 / 6
    H1 = pivotX_prev_close + pivot_range * 1.1 / 12
    L1 = pivotX_prev_close - pivot_range * 1.1 / 12
    L2 = pivotX_prev_close - pivot_range * 1.1 / 6
    L3 = pivotX_prev_close - pivot_range * 1.1 / 4
    L4 = pivotX_prev_close - pivot_range * 1.1 / 2
    L5 = L4 - 1.168 * (L3 - L4)
    H5 = H4 + 1.168 * (H4 - H3)
    H6 = pivotX_prev_high / pivotX_prev_low * pivotX_prev_close
    L6 = pivotX_prev_close - (H6 - pivotX_prev_close)
    array.push(p, pivotX_Median)
    array.push(r1, H2)
    array.push(s1, L2)
    array.push(r2, H3)
    array.push(s2, L3)
    array.push(r3, H4)
    array.push(s3, L4)
    array.push(r4, H5)
    array.push(s4, L5)
    array.push(r5, H6)
    array.push(s5, L6)

resolution = get_pivot_resolution()

[sec_open, sec_high, sec_low, sec_close] = request.security(syminfo.tickerid, resolution, [open, high, low, close], lookahead=barmerge.lookahead_on)
sec_open_gaps_on = request.security(syminfo.tickerid, resolution, open, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on)

var number_of_years = 0
is_change_years = false
var custom_years_resolution = pivot_time_frame == BIYEARLY or pivot_time_frame == TRIYEARLY or pivot_time_frame == QUINQUENNIAL
if custom_years_resolution and ta.change(time(resolution))
    number_of_years += 1
    if pivot_time_frame == BIYEARLY and number_of_years % 2 == 0
        is_change_years := true
        number_of_years := 0
        number_of_years
    else if pivot_time_frame == TRIYEARLY and number_of_years % 3 == 0
        is_change_years := true
        number_of_years := 0
        number_of_years
    else if pivot_time_frame == QUINQUENNIAL and number_of_years % 5 == 0
        is_change_years := true
        number_of_years := 0
        number_of_years

var is_change = false
var uses_current_bar = timeframe.isintraday
var change_time = int(na)
is_time_change = ta.change(time(resolution)) and not custom_years_resolution or is_change_years
if is_time_change
    change_time := time
    change_time


if not uses_current_bar and is_time_change or uses_current_bar and not na(sec_open_gaps_on)
    if is_daily_based
        pivotX_prev_open := sec_open[1]
        pivotX_prev_high := sec_high[1]
        pivotX_prev_low := sec_low[1]
        pivotX_prev_close := sec_close[1]
        pivotX_open := sec_open
        pivotX_high := sec_high
        pivotX_low := sec_low
        pivotX_low
    else
        pivotX_prev_high := pivotX_high
        pivotX_prev_low := pivotX_low
        pivotX_prev_open := pivotX_open
        pivotX_open := open
        pivotX_high := high
        pivotX_low := low
        pivotX_prev_close := close[1]
        pivotX_prev_close

    if barstate.islast and not is_change and array.size(arr_time) > 0
        array.set(arr_time, array.size(arr_time) - 1, change_time)
    else
        array.push(arr_time, change_time)

    if kind == FIBONACCI
        fibonacci()
    else if kind == CAMARILLA
        camarilla()

    if array.size(arr_time) > look_back
        if array.size(arr_time) > 0
            array.shift(arr_time)
        if array.size(p) > 0 and p_show
            array.shift(p)
        if array.size(r1) > 0 and s1r1_show
            array.shift(r1)
        if array.size(s1) > 0 and s1r1_show
            array.shift(s1)
        if array.size(r2) > 0 and s2r2_show
            array.shift(r2)
        if array.size(s2) > 0 and s2r2_show
            array.shift(s2)
        if array.size(r3) > 0 and s3r3_show
            array.shift(r3)
        if array.size(s3) > 0 and s3r3_show
            array.shift(s3)
        if array.size(r4) > 0 and s4r4_show
            array.shift(r4)
        if array.size(s4) > 0 and s4r4_show
            array.shift(s4)
        if array.size(r5) > 0 and s5r5_show
            array.shift(r5)
        if array.size(s5) > 0 and s5r5_show
            array.shift(s5)
    is_change := true
    is_change
else
    if is_daily_based
        pivotX_high := math.max(pivotX_high, sec_high)
        pivotX_low := math.min(pivotX_low, sec_low)
        pivotX_low
    else
        pivotX_high := math.max(pivotX_high, high)
        pivotX_low := math.min(pivotX_low, low)
        pivotX_low

if barstate.islast and array.size(arr_time) > 0 and is_change
    is_change := false
    if array.size(arr_time) > 2 and custom_years_resolution
        last_pivot_time = array.get(arr_time, array.size(arr_time) - 1)
        prev_pivot_time = array.get(arr_time, array.size(arr_time) - 2)
        estimate_pivot_time = last_pivot_time - prev_pivot_time
        array.push(arr_time, last_pivot_time + estimate_pivot_time)
    else
        array.push(arr_time, time_close(resolution))

    for i = 0 to array.size(lines) - 1 by 1
        if array.size(lines) > 0
            line.delete(array.shift(lines))
        if array.size(lines) > 0
            label.delete(array.shift(labels))

    for i = 0 to array.size(arr_time) - 2 by 1
        if array.size(p) > 0 and p_show
            draw_line(i, p, p_color)
            draw_label(i, array.get(p, i), 'P', p_color)
        if array.size(r1) > 0 and s1r1_show
            draw_line(i, r1, s1r1_color)
            draw_label(i, array.get(r1, i), 'R1', s1r1_color)
        if array.size(s1) > 0 and s1r1_show
            draw_line(i, s1, s1r1_color)
            draw_label(i, array.get(s1, i), 'S1', s1r1_color)
        if array.size(r2) > 0 and s2r2_show
            draw_line(i, r2, s2r2_color)
            draw_label(i, array.get(r2, i), 'R2', s2r2_color)
        if array.size(s2) > 0 and s2r2_show
            draw_line(i, s2, s2r2_color)
            draw_label(i, array.get(s2, i), 'S2', s2r2_color)
        if array.size(r3) > 0 and s3r3_show
            draw_line(i, r3, s3r3_color)
            draw_label(i, array.get(r3, i), 'R3', s3r3_color)
        if array.size(s3) > 0 and s3r3_show
            draw_line(i, s3, s3r3_color)
            draw_label(i, array.get(s3, i), 'S3', s3r3_color)
        if array.size(r4) > 0 and s4r4_show
            draw_line(i, r4, s4r4_color)
            draw_label(i, array.get(r4, i), 'R4', s4r4_color)
        if array.size(s4) > 0 and s4r4_show
            draw_line(i, s4, s4r4_color)
            draw_label(i, array.get(s4, i), 'S4', s4r4_color)
        if array.size(r5) > 0 and s5r5_show
            draw_line(i, r5, s5r5_color)
            draw_label(i, array.get(r5, i), 'R5', s5r5_color)
        if array.size(s5) > 0 and s5r5_show
            draw_line(i, s5, s5r5_color)
            draw_label(i, array.get(s5, i), 'S5', s5r5_color)



////////////////////////////////
//float ph = na, float pl = na
//ph := pivothigh(prd, prd)
//pl := pivotlow(prd, prd)

//plotshape(ph and swing, text="H",  style=shape.labeldown, color=na, textcolor=color.red, location=location.abovebar , offset = -prd)
//plotshape(pl and swing, text="L",  style=shape.labeldown, color=na, textcolor=color.green, location=location.belowbar , offset = -prd)

//lft = input.int(30, 'Swing Hi', group='Settings'')
//rght = input.int(30, 'Swing Lo', group='Settings'')

hih = ta.pivothigh(high, prd, prd)
lol = ta.pivotlow(low, prd, prd)

top = ta.valuewhen(hih, high[prd], 0)
bot = ta.valuewhen(lol, low[prd], 0)

plot(swing ? top : na, color=top != top[1] ? na : ColorSelector(Hi_color), offset=-prd, editable=false)
plot(swing ? bot : na, color=bot != bot[1] ? na : ColorSelector(Lo_color), offset=-prd, editable=false)
////////ORB {
sess = input.session('0915-0945', title='ORB Period', inline='orb', group='Settings')

t = time(timeframe.period, sess + ':1234567')
hide = timeframe.isintraday and timeframe.multiplier <= 10


is_newbar(res) =>
    ta.change(time(res)) != 0
in_session = not na(t)
is_first = in_session and not in_session[1]

orb_high = float(na)
orb_low = float(na)

if is_first
    orb_high := high
    orb_low := low
    orb_low
else
    orb_high := orb_high[1]
    orb_low := orb_low[1]
    orb_low
if high > orb_high and in_session
    orb_high := high
    orb_high
if low < orb_low and in_session
    orb_low := low
    orb_low

show15highlow = input.bool(title='ORB ', defval=false, inline='orb', group='Settings')

plot(show15highlow ? orb_high : na, style=plot.style_circles, color=orb_high[1] != orb_high ? na : color.purple, title='IB High', linewidth=1, show_last=75)
plot(show15highlow ? orb_low : na, style=plot.style_circles, color=orb_low[1] != orb_low ? na : color.purple, title='IB Low', linewidth=1, show_last=75)

//}


hhtf = request.security(syminfo.tickerid, resolution, high[1], lookahead=barmerge.lookahead_on)
lhtf = request.security(syminfo.tickerid, resolution, low[1], lookahead=barmerge.lookahead_on)
chtf = request.security(syminfo.tickerid, resolution, close[1], lookahead=barmerge.lookahead_on)

rng = hhtf - lhtf

// is this last bar for HTF?
islast = showlast ? request.security(syminfo.tickerid, resolution, barstate.islast, lookahead=barmerge.lookahead_on) : true

// Line Style

linestyleL = plot.style_circles
///////Calculation Camarilla
H4 = chtf + rng * 1.1 / 2
H3 = chtf + rng * 1.1 / 4
H2 = chtf + rng * 1.1 / 6
H1 = chtf + rng * 1.1 / 12
L1 = chtf - rng * 1.1 / 12
L2 = chtf - rng * 1.1 / 6
L3 = chtf - rng * 1.1 / 4
L4 = chtf - rng * 1.1 / 2
L5 = L4 - 1.168 * (L3 - L4)  //L5 = chtf - (H5 - chtf)
H5 = H4 + 1.168 * (H4 - H3)  //H5 = (hhtf / lhtf) * chtf
H6 = hhtf / lhtf * chtf  //H6 = H5 + 1.168 * (H5 - H4) 
L6 = chtf - (H6 - chtf)  //L6 = chtf - (H6 - chtf)
SLbull = (H4 + H3) / 2
SLbear = (L4 + L3) / 2
mid = (H3 + L3) / 2
////////Color Settings

//plot(islast and kind == CAMARILLA and cmidon ? mid : na, 'Mid-H3-L3', color=color.new(#000000, 60), linewidth=1, style=linestyleL, editable=false)
//plot(islast and kind == CAMARILLA and cmidon ? SLbull : na, 'SLBull H3-H4', color=color.new(#ff0000, 60), linewidth=1, style=linestyleL, editable=false)
//plot(islast and kind == CAMARILLA and cmidon ? SLbear : na, 'SLBear L3-L4', color=color.new(#388e3c, 60), linewidth=1, style=linestyleL, editable=false)

// Label for S/R
mndr = time - time[1]
mndr := ta.change(mndr) > 0 ? mndr[1] : mndr

Round_it(valu) =>
    a = 0
    num = syminfo.mintick
    s = valu
    if na(s)
        s := syminfo.mintick
        s
    if num < 1
        for i = 1 to 20 by 1
            num *= 10
            if num > 1
                break
            a += 1
            a

    for x = 1 to a by 1
        s *= 10
        s
    s := math.round(s)
    for x = 1 to a by 1
        s /= 10
        s
    s := s < syminfo.mintick ? syminfo.mintick : s
    s

// Labels
if showlabels and kind == CAMARILLA
    var label s3label = na
    var label s4label = na
    var label s5label = na
    var label s6label = na
    var label r3label = na
    var label r4label = na
    var label r5label = na
    var label r6label = na

    label.delete(s3label)
    label.delete(s4label)
    label.delete(s5label)
    label.delete(s6label)
    label.delete(r3label)
    label.delete(r4label)
    label.delete(r5label)
    label.delete(r6label)
    //s3label := label.new(x=time + mndr * 20, y=L3, text='Sell Entry •' + str.tostring(Round_it(L3)), color=color.new(#000000, 100), textcolor=color.green, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(L3) and na(s3label) and plotCondition)
        s3label:= label.new(x=bar_index, y=H3, text="Sell Entry • ", color=#ffffff00, textcolor=color.red, style=label.style_label_left)
    if (not na(s3label))
        label.set_text(s3label, "Sell Entry • " + str.tostring(math.round_to_mintick(L3)))
        label.set_x(s3label, bar_index)
        label.set_y(s3label, L3)    
    //s4label := label.new(x=time + mndr * 20, y=L4, text='Sell Confirmation •' + str.tostring(Round_it(L4)), color=color.new(#000000, 100), textcolor=lbcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(L4) and na(s4label) and plotCondition)
        s4label:= label.new(x=bar_index, y=L4, text="Sell Confirmation • ", color=#ffffff00, textcolor=color.orange, style=label.style_label_left)
    if (not na(s4label))
        label.set_text(s4label, "Sell Confirmation • " + str.tostring(math.round_to_mintick(L4)))
        label.set_x(s4label, bar_index)
        label.set_y(s4label, L4)
    //s5label := label.new(x=time + mndr * 20, y=L5, text='Target •' + str.tostring(Round_it(L5)), color=color.new(#000000, 100), textcolor=ltcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(L5) and na(s5label) and plotCondition)
        s5label:= label.new(x=bar_index, y=L5, text="Target • ", color=#ffffff00, textcolor=color.black, style=label.style_label_left)
    if (not na(s5label))
        label.set_text(s5label, "Target • " + str.tostring(math.round_to_mintick(L5)))
        label.set_x(s5label, bar_index)
        label.set_y(s5label, L5)
    //s6label := label.new(x=time + mndr * 20, y=L6, text='Target •' + str.tostring(Round_it(L6)), color=color.new(#000000, 100), textcolor=ltcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(L6) and na(s6label) and plotCondition)
        s6label:= label.new(x=bar_index, y=L6, text="Target • ", color=#ffffff00, textcolor=color.black, style=label.style_label_left)
    if (not na(s6label))
        label.set_text(s6label, "Target • " + str.tostring(math.round_to_mintick(L6)))
        label.set_x(s6label, bar_index)
        label.set_y(s6label, L6)
    //r3label := label.new(x=time + mndr * 20, y=H3, text='Buy Entry •' + str.tostring(Round_it(H3)), color=color.new(#000000, 100), textcolor=color.red, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(H3) and na(r3label) and plotCondition)
        r3label:= label.new(x=bar_index, y=H3, text="Buy Entry • ", color=#ffffff00, textcolor=color.red, style=label.style_label_left)
    if (not na(r3label))
        label.set_text(r3label, "Buy Entry • " + str.tostring(math.round_to_mintick(H3)))
        label.set_x(r3label, bar_index)
        label.set_y(r3label, H3)    
    //r4label := label.new(x=time + mndr * 20, y=H4, text='Buy Confirmation •' + str.tostring(Round_it(H4)), color=color.new(#000000, 100), textcolor=lbcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(H4) and na(r4label) and plotCondition)
        r4label:= label.new(x=bar_index, y=H4, text="Buy Confirmation • ", color=#ffffff00, textcolor=color.orange, style=label.style_label_left)
    if (not na(r4label))
        label.set_text(r4label, "Buy Confirmation • " + str.tostring(math.round_to_mintick(H4)))
        label.set_x(r4label, bar_index)
        label.set_y(r4label, H4)
    //r5label := label.new(x=time + mndr * 20, y=H5, text='Target •' + str.tostring(Round_it(H5)), color=color.new(#000000, 100), textcolor=ltcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(H5) and na(r5label) and plotCondition)
        r5label:= label.new(x=bar_index, y=H5, text="Target • ", color=#ffffff00, textcolor=color.black, style=label.style_label_left)
    if (not na(r5label))
        label.set_text(r5label, "Target • " + str.tostring(math.round_to_mintick(H5)))
        label.set_x(r5label, bar_index)
        label.set_y(r5label, H5)    
    //r6label := label.new(x=time + mndr * 20, y=H6, text='Target •' + str.tostring(Round_it(H6)), color=color.new(#000000, 100), textcolor=ltcol, style=label.style_label_right, xloc=xloc.bar_time, yloc=yloc.price)
    if (not na(H6) and na(r6label) and plotCondition)
        r6label:= label.new(x=bar_index, y=H6, text="Target • ", color=#ffffff00, textcolor=color.black, style=label.style_label_left)
    if (not na(r6label))
        label.set_text(r6label, "Target • " + str.tostring(math.round_to_mintick(H6)))
        label.set_x(r6label, bar_index)
        label.set_y(r6label, H6) 
    //r6label

//////Central Pivot
Pivot = (hhtf + lhtf + chtf) / 3
BC = (hhtf + lhtf) / 2
TC = Pivot - BC + Pivot
//LineStyle CPR
linestylee = lstyle2 == 'Solid' ? plot.style_line : lstyle2 == 'Circles' ? plot.style_circles : lstyle2 == 'Cross' ? plot.style_cross : na


//plot(islast and cprturnon ? TC : na, title='TC', color=color.new(color.blue, 0), linewidth=1, style=linestylee)
//plot(islast and cprturnon ? Pivot : na, title='Pivot', color=color.new(color.red, 0), linewidth=1, style=linestylee)
//plot(islast and cprturnon ? BC : na, title='BC', color=color.new(color.blue, 0), linewidth=1, style=linestylee)
//plot(islast and JP ? Pivot : na, title='JPivot', color=color.new(color.red, 0), linewidth=2, style=linestylee)
if showlabels and JP
    var label jplabel = na

    label.delete(jplabel)
    jplabel := label.new(x=time + mndr * 20, y=Pivot, text='Pivot  •' + str.tostring(Round_it(Pivot)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    chtf
///////Day High Low//////
phhtf = request.security(syminfo.tickerid, Pres, high[lvl], lookahead=barmerge.lookahead_on)
plhtf = request.security(syminfo.tickerid, Pres, low[lvl], lookahead=barmerge.lookahead_on)
pchtf = request.security(syminfo.tickerid, Pres, close[lvl], lookahead=barmerge.lookahead_on)
islast2 = showlast ? request.security(syminfo.tickerid, Pres, barstate.islast, lookahead=barmerge.lookahead_on) : true
//plot(islast2 and PDHL ? phhtf : na, title='Day High', color=PColor, linewidth=2, style=linestylee)
//plot(islast2 and PDHL ? plhtf : na, title='Day Low', color=PColor, linewidth=2, style=linestylee)
//plot(islast2 and PDHL ? pchtf : na, title='Day Close', color=PColor, linewidth=2, style=linestylee)
if showlabels and PDHL
    var label pdhlabel = na
    var label pdllabel = na
    var label pdclabel = na

    label.delete(pdhlabel)
    label.delete(pdllabel)
    label.delete(pdclabel)
    pdhlabel := label.new(x=time + mndr * 20, y=phhtf, text='PDH  •' + str.tostring(Round_it(phhtf)), color=color.new(#000000, 100), textcolor=PColor, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    pdllabel := label.new(x=time + mndr * 20, y=plhtf, text='PDL  •' + str.tostring(Round_it(plhtf)), color=color.new(#000000, 100), textcolor=PColor, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    pdclabel := label.new(x=time + mndr * 20, y=pchtf, text='PDC  •' + str.tostring(Round_it(pchtf)), color=color.new(#000000, 100), textcolor=PColor, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    pdclabel
//////Fibo Pivot

pivot = (hhtf + lhtf + chtf) / 3.0
R1 = pivot + 0.382 * rng
S1 = pivot - 0.382 * rng
R2 = pivot + 0.618 * rng
S2 = pivot - 0.618 * rng
R3 = pivot + rng
S3 = pivot - rng
R4 = pivot + 1.272 * rng
S4 = pivot - 1.272 * rng
R5 = pivot + 1.618 * rng
S5 = pivot - 1.618 * rng
R6 = pivot + 2.058 * rng
S6 = pivot - 2.058 * rng
R7 = pivot + 2.618 * rng
S7 = pivot - 2.618 * rng

if showlabels and kind == FIBONACCI
    var label fs1label = na
    var label fs2label = na
    var label fs3label = na
    var label fs4label = na
    var label plabel = na
    var label fr1label = na
    var label fr2label = na
    var label fr3label = na
    var label fr4label = na

    label.delete(fs1label)
    label.delete(fs2label)
    label.delete(fs3label)
    label.delete(fs4label)
    label.delete(plabel)
    label.delete(fr1label)
    label.delete(fr2label)
    label.delete(fr3label)
    label.delete(fr4label)
    fs1label := label.new(x=time + mndr * 20, y=S1, text='0.382  ' + str.tostring(Round_it(S1)), color=color.new(#000000, 100), textcolor=color.green, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fs2label := label.new(x=time + mndr * 20, y=S2, text='0.618 ' + str.tostring(Round_it(S2)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fs3label := label.new(x=time + mndr * 20, y=S3, text='100 ' + str.tostring(Round_it(S3)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fs4label := label.new(x=time + mndr * 20, y=S4, text='1.272 ' + str.tostring(Round_it(S4)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    plabel := label.new(x=time + mndr * 20, y=pivot, text='Pivot ' + str.tostring(Round_it(pivot)), color=color.new(#000000, 100), textcolor=color.silver, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fr1label := label.new(x=time + mndr * 20, y=R1, text='0.382 ' + str.tostring(Round_it(R1)), color=color.new(#000000, 100), textcolor=color.red, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fr2label := label.new(x=time + mndr * 20, y=R2, text='0.618 ' + str.tostring(Round_it(R2)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fr3label := label.new(x=time + mndr * 20, y=R3, text='100 ' + str.tostring(Round_it(R3)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fr4label := label.new(x=time + mndr * 20, y=R4, text='1.272 ' + str.tostring(Round_it(R4)), color=color.new(#000000, 100), textcolor=color.black, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
    fr4label

PAB = input.bool(true, 'Price Action Bars', group='Settings')
//Dark Cloud
DRKC = open[1] < close[1] ? open > high[1] ? close < close[1] - (close[1] - open[1]) / 2 ? close > open[1] ? #dbff01 : na : na : na : na
barcolor(PAB ? DRKC : na, title='Dark Cloud')

//Bearish Engulfing
BrEng = close < open[1] ? low < low[1] ? high > high[1] ? open >= open[1] ? #ff0000 : na : na : na : na
barcolor(PAB ? BrEng : na, title='Bearish Engulf')


//Bullish Engulfing
BuEng = low < low[1] ? high > high[1] ? open <= open[1] ? close > open[1] ? #00ff0a : na : na : na : na
barcolor(PAB ? BuEng : na, title='Bullish Engulf')

BearishENG = open[1] < close[1] ? close < open[1] ? open > close[1] ? #ff0000 : na : na : na
barcolor(PAB ? BearishENG : na, title='Bearish 2 Engulf')
BullishENG = open[1] > close[1] ? close > open[1] ? open < close[1] ? #00ff0a : na : na : na
barcolor(PAB ? BullishENG : na, title='Bullish 2 Engulf')

//Three White Soldiers
//TWS = close > open ? close[1] > open[1] ? close[2] > open[2] ? close > high[1] ? close[1] > high[2] ? open < close[1] ? open[1] < close[2] ? (high - close ) * 3 < close - open ? (high[1] - close[1]) * 3 < close[1] - open[1] ? (high[2] - close[2]) * 3 < close[2] - open[2] ? #66ff00 : na : na : na : na : na : na:na : na : na : na
//barcolor(PAB ? TWS : na, title="Three white soliders")
//TBC = close < open ? close[1] < open[1] ? close[2] < open[2] ? close < low[1] ? close[1] < low[2] ? open > close[1] ? open[1] > close[2] ? (close - low) * 3 < open - close ? (close[1] - low[1]) * 3 < open[1] - close[1] ? (close[2] - low[2]) * 3 < open[2] - close[2] ? #ff6600 : na : na : na : na : na : na:na : na : na : na
//barcolor (PAB ? TBC : na, title = "Three Black Crows")
/////VWAP////MVWAP
Length = input.int(50, title='MVWAP', inline='vwap', group='Settings')
mvwap = ta.ema(ta.vwap, Length)
//plot(vwaplot ? mvwap : na, linewidth=2, title='MVWAP', style=plot.style_line, color=color.new(color.purple, 0))

//plot(ta.vwap and vwaplot ? ta.vwap : na, linewidth=lw, title='VWAP', color=color.new(#FF7000, 0))

//////EMA
//plot(emaplot and choice == 'EMA' ? ta.ema(close, MAa) : emaplot and choice == 'SMA' ? ta.sma(close, MAa) : na, title='Fast MA', color=color.new(color.green, 0), linewidth=lw)
//plot(emaplot and choice == 'EMA' ? ta.ema(close, MAb) : emaplot and choice == 'SMA' ? ta.sma(close, MAb) : na, title='Mid MA', color=color.new(color.black, 0), linewidth=lw)
//plot(emaplot and choice == 'EMA' ? ta.ema(close, MAc) : emaplot and choice == 'SMA' ? ta.sma(close, MAc) : na, title='Slow MA', color=color.new(color.red, 0), linewidth=lw)


////////////Volume Based Support Resistance
Vlength = input.int(20, minval=1, group='Volume S/R Settings')
Vchange = volume / volume[1] - 1
stdev = ta.stdev(Vchange, Vlength)
difference = Vchange / stdev[1]
Treshold = input(5)
zero = 0
signal = math.abs(difference)
vstylee = plot.style_circles

leveluphi = ta.valuewhen(signal > Treshold, high[1], 0)
leveluplo = ta.valuewhen(signal > Treshold, low[1], 0)

//plot(UpperTreshold, color=black)
pv1 = plot(vsr and leveluphi ? leveluphi : na, title='LevelHi', style=vstylee, color=color.new(color.blue, 0))
pv2 = plot(vsr and leveluplo ? leveluplo : na, title='Levello', style=vstylee, color=color.new(color.blue, 0))
fill(pv1, pv2, color=color.new(color.black, 50), title='Fill')
////////////////////////
Ecandle = input.bool(false, 'Indecisive-Candle', group='Settings', tooltip='Shows 50% Candles')

cand = high - low
bodyr = open - close

candle = bodyr * 100 / cand

barcolor(Ecandle and candle > -50 and candle < 50 ? #0b00ff : na)
///// 

///////// Day Range
On = input.bool(false, 'Day Range', group='Settings')

fill(plot1=plot(On and islast ? H4 : na, color=color.new(#ff7700, 80), editable=false), plot2=plot(On and islast ? R2 : na, color=color.new(#ff7700, 100), editable=false), color=color.new(#ff7700, 75))
fill(plot1=plot(On and islast ? L4 : na, color=color.new(#000000, 80), editable=false), plot2=plot(On and islast ? S2 : na, color=color.new(#000000, 100), editable=false), color=color.new(#000000, 75))

//Price Action {
TR1 = input.int(27, title='SMA to determine Trend', minval=1, maxval=500)
TR2 = input.int(111, title='SMA to determine Trend', minval=1, maxval=500)
CS = input.int(14, title='Candle Strength', minval=14, maxval=50)
confirm = barstate.isconfirmed
C_DownTrend = true
C_UpTrend = true
var trendRule1 = 'EMA50'
var trendRule2 = 'EMA50, EMA200'
var trendRule = input.string(trendRule1, '', options=[trendRule1, trendRule2, 'No detection'], inline='RT', group='Price Action')

if trendRule == trendRule1
    priceAvg = ta.ema(close, TR1)
    C_DownTrend := close < priceAvg
    C_UpTrend := close > priceAvg
    C_UpTrend

if trendRule == trendRule2
    sma200 = ta.ema(close, TR2)
    sma50 = ta.ema(close, TR1)
    C_DownTrend := close < sma50 and sma50 < sma200
    C_UpTrend := close > sma50 and sma50 > sma200
    C_UpTrend
C_Len = CS  // ema depth for bodyAvg
C_ShadowPercent = 5.0  // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0  // shows the number of times the shadow dominates the candlestick body

C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high - low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100 < C_ShadowEqualsPercent and math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100 < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals

patternLabelPosLow = low - ta.atr(30) * 0.99
patternLabelPosHigh = high + ta.atr(30) * 0.99


text_color_bullish = input(color.green, 'Text Color Bull')
text_color_bearish = input(color.red, 'Text color Bear')
CandleType = input.string(title='Pattern Type', defval='Both', options=['Bullish', 'Bearish', 'Both'])


C_HammerBullishNumberOfCandles = 1
C_HammerBullish = false
if C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow and confirm
    if C_DownTrend
        C_HammerBullish := true
        C_HammerBullish
alertcondition(C_HammerBullish, title='Hammer – Bullish', message='New Hammer – Bullish pattern detected')
if C_HammerBullish and HammerInput and ('Bullish' == CandleType or CandleType == 'Both')

    var ttBullishHammer = 'Hammer\nHammer candlesticks form when a security moves lower after the open, but continues to rally into close above the intraday low. The candlestick that you are left with will look like a square attached to a long stick-like figure. This candlestick is called a Hammer if it happens to form during a decline.'
    label.new(bar_index, patternLabelPosLow, text='H', style=label.style_none, textcolor=text_color_bullish, tooltip=ttBullishHammer)


C_HangingManBearishNumberOfCandles = 1
C_HangingManBearish = false
if C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow and confirm
    if C_UpTrend
        C_HangingManBearish := true
        C_HangingManBearish
alertcondition(C_HangingManBearish, title='Hanging Man – Bearish', message='New Hanging Man – Bearish pattern detected')
if C_HangingManBearish and HangingManInput and ('Bearish' == CandleType or CandleType == 'Both')

    var ttBearishHangingMan = 'Hanging Man\nWhen a specified security notably moves lower after the open, but continues to rally to close above the intraday low, a Hanging Man candlestick will form. The candlestick will resemble a square, attached to a long stick-like figure. It is referred to as a Hanging Man if the candlestick forms during an advance.'
    label.new(bar_index, patternLabelPosHigh, text='HM', style=label.style_none, textcolor=text_color_bearish, tooltip=ttBearishHangingMan)


C_InvertedHammerBullishNumberOfCandles = 1
C_InvertedHammerBullish = false
if C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow and confirm
    if C_DownTrend
        C_InvertedHammerBullish := true
        C_InvertedHammerBullish
alertcondition(C_InvertedHammerBullish, title='Inverted Hammer – Bullish', message='New Inverted Hammer – Bullish pattern detected')
if C_InvertedHammerBullish and InvertedHammerInput and ('Bullish' == CandleType or CandleType == 'Both')

    var ttBullishInvertedHammer = 'Inverted Hammer\nIf in a downtrend, then the open is lower. When it eventually trades higher, but closes near its open, it will look like an inverted version of the Hammer Candlestick. This is a one-day bullish reversal pattern.'
    label.new(bar_index, patternLabelPosLow, text='IH', style=label.style_none, textcolor=text_color_bullish, tooltip=ttBullishInvertedHammer)



// ATR Trailing SL {
nATRPeriod = input.int(5, 'Period', inline='atr', group='Settings')
nATRMultip = input.float(3.5, 'Multi', inline='atr', group='Settings')
xATR = ta.atr(nATRPeriod)
nLoss = nATRMultip * xATR
xATRTrailingStop = 0.0
iff_1 = close > nz(xATRTrailingStop[1], 0) ? close - nLoss : close + nLoss
iff_2 = close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), close + nLoss) : iff_1
xATRTrailingStop := close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), close - nLoss) : iff_2
col = close < xATRTrailingStop[1] ? color.silver : color.black
plot(ATRTsl ? xATRTrailingStop[1] : na, color=col, title='ATR Trailing Stop')  //}

//Table {
//var table info = table.new(position.top_center, 1, 1)
//var table logo = table.new(position.bottom_right, 1, 1)
//if barstate.islast
    //table.cell(logo, 0, 0, '@llopezf', text_size=size.normal, text_color=color.orange)
    //table.cell(info, 0, 0, 't.me/signals_leo', text_size=size.small, text_color=color.black)
//}
//{RSI col
rsicol = input.bool(false, title='Show RSI colors?', group='Settings', tooltip='Show RSI Levels On Bars')

srcRSI = close
lenRSI = input.int(14, minval=1, title='RSI Length', group='RSI Settings')
up11 = ta.rma(math.max(ta.change(srcRSI), 0), lenRSI)
down = ta.rma(-math.min(ta.change(srcRSI), 0), lenRSI)
rsi1 = down == 0 ? 100 : up11 == 0 ? 0 : 100 - 100 / (1 + up11 / down)
//coloring method below
srcRSI1 = close
lenRSI1 = input.int(60, minval=1, title='Over Bought', group='RSI Settings')
srcRSI2 = close
lenRSI2 = input.int(40, minval=1, title='Over Sold', group='RSI Settings')
isup() =>
    rsi1 > lenRSI1
isdown() =>
    rsi1 < lenRSI2
barcolor(rsicol and isup() ? color.green : rsicol and isdown() ? color.red : na)  // }
//Mid Point {
Mid = input.bool(true, 'Mid Point', group='Settings')
plotchar(Mid ? hl2 : na, char='•', color=color.new(color.red, 0), location=location.absolute, size=size.tiny, offset=1, show_last=5)  //} 
//BollingerBands {
bbon = input.bool(false, title='BollingerBands', inline='BB', group='Settings')
bblength = input.int(27, '', minval=1, inline='BB', group='Settings')
bbsrc = input.source(close, title='', inline='BB', group='Settings')
mult = input.float(2.0, minval=0.001, maxval=50, title='', inline='BB', group='Settings')
basis = ta.sma(bbsrc, bblength)
dev1 = mult * ta.stdev(bbsrc, bblength)
upper1 = basis + dev1
lower1 = basis - dev1
offset = input.int(0, 'BB Offset', minval=-500, maxval=500)
plot(bbon ? basis : na, 'Basis', color=color.new(#872323, 0), offset=offset)
b1 = plot(bbon ? upper1 : na, 'Upper', color=color.new(color.teal, 0), offset=offset)
b2 = plot(bbon ? lower1 : na, 'Lower', color=color.new(color.teal, 0), offset=offset)
fill(b1, b2, title='Background', color=color.new(#198787, 95))  //}

////////////Trendlines Taken from Lonesomeblue
startyear = input(defval=2020, title='Start Year',group='Trendline')
startmonth = input(defval=1, title='Start Month',group='Trendline')
startday = input(defval=1, title='Start day',group='Trendline')
prdl = input.int(defval=10, title='Pivot Period', minval=10, maxval=50,group='Trendline')
PPnum = input.int(defval=3, title='Number of Pivot Points to check', minval=2, maxval=8,group='Trendline')
utcol = input.color(defval=color.lime, title='Colors', inline='tcol',group='Trendline')
dtcol = input.color(defval=color.red, title='', inline='tcol',group='Trendline')

float ph1 = ta.pivothigh(prdl, prdl)
float pl1 = ta.pivotlow(prdl, prdl)

var tval = array.new_float(PPnum)
var tpos = array.new_int(PPnum)
var bval = array.new_float(PPnum)
var bpos = array.new_int(PPnum)

add_to_array(apointer1, apointer2, val) =>
    array.unshift(apointer1, val)
    array.unshift(apointer2, bar_index)
    array.pop(apointer1)
    array.pop(apointer2)

if ph1
    add_to_array(tval, tpos, ph1)

if pl1
    add_to_array(bval, bpos, pl1)

// line definitions
maxline = 3
var bln = array.new_line(maxline, na)
var tln = array.new_line(maxline, na)

// loop for pivot points to check if there is possible trend line
countlinelo = 0
countlinehi = 0

starttime = timestamp(startyear, startmonth, startday, 0, 0, 0)

if time >= starttime
    for x = 0 to maxline - 1 by 1
        line.delete(array.get(bln, x))
        line.delete(array.get(tln, x))
    for p1 = 0 to PPnum - 2 by 1
        uv1 = 0.0
        uv2 = 0.0
        up1 = 0
        up2 = 0
        if countlinelo <= maxline
            for p2 = PPnum - 1 to p1 + 1 by 1
                val1 = array.get(bval, p1)
                val2 = array.get(bval, p2)
                pos1 = array.get(bpos, p1)
                pos2 = array.get(bpos, p2)
                if val1 > val2
                    diff = (val1 - val2) / (pos1 - pos2)
                    hline = val2 + diff
                    lloc = bar_index
                    lval = low
                    valid = true
                    for x = pos2 + 1 - prd to bar_index by 1
                        if close[bar_index - x] < hline
                            valid := false
                            break
                        lloc := x
                        lval := hline
                        hline += diff
                        hline


                    if valid
                        uv1 := hline - diff
                        uv2 := val2
                        up1 := lloc
                        up2 := pos2
                        break

        dv1 = 0.0
        dv2 = 0.0
        dp1 = 0
        dp2 = 0
        if countlinehi <= maxline
            for p2 = PPnum - 1 to p1 + 1 by 1
                val1 = array.get(tval, p1)
                val2 = array.get(tval, p2)
                pos1 = array.get(tpos, p1)
                pos2 = array.get(tpos, p2)
                if val1 < val2
                    diff = (val2 - val1) / float(pos1 - pos2)
                    hline = val2 - diff
                    lloc = bar_index
                    lval = high
                    valid = true
                    for x = pos2 + 1 - prd to bar_index by 1
                        if close[bar_index - x] > hline
                            valid := false
                            break
                        lloc := x
                        lval := hline
                        hline -= diff
                        hline

                    if valid
                        dv1 := hline + diff
                        dv2 := val2
                        dp1 := lloc
                        dp2 := pos2
                        break

        // if there is continues uptrend line then draw it
        if up1 != 0 and up2 != 0 and countlinelo < maxline
            countlinelo += 1
            array.set(bln, countlinelo - 1, line.new(up2 - prd, uv2, up1, uv1, color=utcol))

        // if there is continues downtrend line then draw it
        if dp1 != 0 and dp2 != 0 and countlinehi < maxline
            countlinehi += 1
            array.set(tln, countlinehi - 1, line.new(dp2 - prd, dv2, dp1, dv1, color=dtcol))
//------------------------------------------------------------------------------
//  === SMMA 33/144 H/L BY LEO ===
//------------------------------------------------------------------------------

// SMMA 33 HIGH
len1 = input.int(33, minval=1, title='Length')
src1 = input(high, title='Source')
var float smma1 = na
sma_1 = ta.sma(src1, len1)
smma1 := na(smma1[1]) ? sma_1 : (smma1[1] * (len1 - 1) + src1) / len1
plot(smma1, title='33 High', color=#03b3b099, linewidth=1)

// SMMA 33 LOW
len2 = input.int(33, minval=1, title='Length')
src2 = input(low, title='Source')
var float smma2 = na
sma_2 = ta.sma(src2, len2)
smma2 := na(smma2[1]) ? sma_2 : (smma2[1] * (len2 - 1) + src2) / len2
plot(smma2, title='33 Low', color=#03b3b099, linewidth=1)

// SMMA 144 HIGH
len3 = input.int(144, minval=1, title='Length')
src3 = input(high, title='Source')
var float smma3 = na
sma_3 = ta.sma(src3, len3)
smma3 := na(smma3[1]) ? sma_3 : (smma3[1] * (len3 - 1) + src3) / len3
plot(smma3, title='144 High', color=#ff52529a, linewidth=1)

// SMMA 144 LOW
len4 = input.int(144, minval=1, title='Length')
src4 = input(low, title='Source')
var float smma4 = na
sma_4 = ta.sma(src4, len4)
smma4 := na(smma4[1]) ? sma_4 : (smma4[1] * (len4 - 1) + src4) / len4
plot(smma4, title='144 Low', color=#ff52529a, linewidth=1)

// Selección de visualización
showMayor = input.bool(true, title="Major Cross")
showMenor = input.bool(false, title="Minor Cross")

// Plot cruces entre SMMA 33 y SMMA 144 basado en la selección
plot(showMayor and ta.crossover(smma1, smma3) ? smma1 : na, style=plot.style_cross, linewidth=5, color=#00897bf8, title='Major 33H ⇑ 144H')
plot(showMayor and ta.crossover(smma2, smma3) ? smma2 : na, style=plot.style_cross, linewidth=5, color=#00897bf8, title='Major 33L ⇑ 144H')
plot(showMayor and ta.crossunder(smma1, smma4) ? smma1 : na, style=plot.style_cross, linewidth=5, color=#880e28, title='Major 33H ⇓ 144L')
plot(showMayor and ta.crossunder(smma2, smma4) ? smma2 : na, style=plot.style_cross, linewidth=5, color=#880e28, title='Major 33L ⇓ 144L')

plot(showMenor and ta.crossover(smma1, smma4) ? smma1 : na, style=plot.style_cross, linewidth=5, color=#3cea3f, title='Minor 33H ⇑ 144L')
plot(showMenor and ta.crossover(smma2, smma4) ? smma2 : na, style=plot.style_cross, linewidth=5, color=#3cea3f, title='Minor 33L ⇑ 144L')
plot(showMenor and ta.crossunder(smma2, smma3) ? smma2 : na, style=plot.style_cross, linewidth=5, color=#ff5252, title='Minor 33L ⇓ 144H')
plot(showMenor and ta.crossunder(smma1, smma3) ? smma1 : na, style=plot.style_cross, linewidth=5, color=#ff5252, title='Minor 33H ⇓ 144H')

Overview

River Strategy with SuperScalper by Leo identifies breakout conditions when price bars clear the channel boundaries to generate entry, stop loss, and multi-tier take profit levels. The script offers configurable sensitivity settings, optional strong signal alerts, supply and demand zone mapping, and multi-timeframe inputs for trade management.

Details

Published by

IAMATOMIC001 on GitHub

Code credit

leandrolopezf1920, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Support & resistance, Scalping, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Reads higher-timeframe data with lookahead on, so the history can show signals that were not there in real time

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Bollinger Bars Lengthint55bblenght
Bollinger Bars Standard Deviationfloat0.2bbstdev
TIMEFRAMEtimeframe1hres
BUY/SELL SIGNALS ON/OFFbooltrueshowBuySell
SENSITIVITY (1-6)float2.7sensitivity
STOP LOSS %float1.0percentStop
TAKE PROFIT %float0.2percentTake
TAKE PROFIT2 %float0.4percentTake2
TAKE PROFIT3 %float0.6percentTake3
TAKE PROFIT4 %float0.8percentTake4
TAKE PROFIT5 %float1percentTake5
STRONG BUY/SELL SIGNALS ON/OFFbooltrueshowStrongBuySell
Show all 40 settings
SettingTypeDefaultVariable
SENSITIVITYfloat13sensitivity2
STOP LOSS %float1.0percentStrongStop
TAKE PROFIT %float0.2percentStrongTake
TAKE PROFIT2 %float0.4percentStrongTake2
TAKE PROFIT3 %float0.6percentStrongTake3
TAKE PROFIT4 %float0.8percentStrongTake4
TAKE PROFIT5 %float1percentStrongTake5
SIGNAL OFFSETfloat1offsetSignal
REVERSAL SIGNALS ON/OFFbooltrueshowReversal
EXIT & ENTRY ON/OFFbooltrueenableE
ENTRYcolor#be00104cEntry
TAKE PROFITcolor#00be064dTp1
SUPPLY & DEMAND ON/OFFbooltrueenableSD
MITIGATIONstringWickmitigation
VOLUME PIVOTint20length
DEMANDint1bull_ext_last
bull_avg_csscolorcolor.rgb(0, 221, 255, 50)bull_avg_css
bull_csscolorcolor.new(#00000000, 100)bull_css
bg_bull_csscolorcolor.new(#00ff0a, 90)bg_bull_css
SUPPLYint1bear_ext_last
bear_avg_csscolorcolor.rgb(233, 30, 98, 50)bear_avg_css
bear_csscolorcolor.new(#00000000, 100)bear_css
bg_bear_csscolorcolor.new(#ff0015, 90)bg_bear_css
LINE STYLEstringSolidline_style
LINE WIDTHint2line_width
SUPPORT & RESISTANCE ON/OffbooltrueenableSR
SUPPORTcolor#00ddff81colorSup
RESISTANCEcolorcolor.rgb(233, 30, 98, 50)colorRes
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

ATR Trailing Stop

by mihakralj
99 stars

Calculates an ATR-based trailing stop overlaid on the price chart to assist with trend identification and stop placement. Using a specified ATR period and multiplier, it projects upper and lower bounds around the closing price. The stop line ratchets up during

Indicator v5 TrendVolatility & bands
Updated 4 weeks ago · Apache-2.0 GitHub repository of ATR Trailing Stop

Moon Dev Lunar Sniper

by moondevonyt
92 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev Lunar Sniper

SuperTrend & Pivots

by dcaoyuan
55 stars

This overlay indicator plots a SuperTrend line on the price chart using a fixed ATR length of 10 and a factor of 3. When the trend direction is up it draws a green line and a light green fill toward the candle midpoint; when down it draws a red line and a ligh

Indicator v6 TrendVolatility & bands
Updated 6 months ago · Apache-2.0 GitHub repository of SuperTrend & Pivots

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers