Index Toolbox

mail@pastecode.io avatar
unknown
plain_text
a year ago
29 kB
16
Indexable
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EB

//@version=5
indicator("Index Toolbox", overlay=true, max_bars_back=500, max_labels_count=500, max_lines_count=500, max_boxes_count=500)

//INPUTS
i_tz = input.string('America/New_York', title='Timezone: ', tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group='Session')
sessionFiveRange = input.session(title='H/L/O Range: ', defval='0000-0830', inline='e', group='Session')

sessionOneRange = input.session(title='Open of Day: ', defval='0830-0831', inline='a', group='Session')
sessionTwoRange = input.session(title='NY Lunch: ', defval='1200-1300', inline='b', group='Session')
sessionThreeRange = input.session(title='Algorithm: ', defval='1330-1331', inline='c', group='Session')
sessionFourRange = input.session(title='End of Day: ', defval='1630-1631', inline='d', group='Session')

colorOne = input.color(color.new(color.black,65),title="Open of Day:",inline="s_1",group="Style")
lineStyleOne = input.string(title="-", defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid],inline="s_1",group="Style")

colorTwo = input.color(color.new(color.black,65),title="Ny Lunch:",inline="s_2",group="Style")
colorTwoFill = input.color(color.new(color.orange,90),title="-",inline="s_2",group="Style")
lineStyleTwo = input.string(title="-", defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid],inline="s_2",group="Style")

colorThree = input.color(color.new(color.purple,65),title="Algorithm:",inline="s_3",group="Style")
lineStyleThree = input.string(title="-", defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid],inline="s_3",group="Style")

colorFour = input.color(color.new(color.black,65),title="End of Day:",inline="s_4",group="Style")
lineStyleFour = input.string(title="-", defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid],inline="s_4",group="Style")

colorFiveHL = input.color(color.new(color.black,65),title="H/L:",inline="s_5",group="Style")
colorFiveOpen = input.color(color.new(color.orange,0),title="Open:",inline="s_5",group="Style")
activeFive = input.color(color.new(color.yellow,95),title="-",inline="s_5",group="Style")
passiveFive = input.color(color.new(color.gray,95),title="/",inline="s_5",group="Style")
lineStyleFive = input.string(title="-", defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid],inline="s_5",group="Style")

//Sessions
in_session_one = time(timeframe.period, sessionOneRange,i_tz)
sessionOneActive = in_session_one and timeframe.multiplier <= 30

in_session_two = time(timeframe.period, sessionTwoRange,i_tz)
sessionTwoActive = in_session_two and timeframe.multiplier <= 30

in_session_three = time(timeframe.period, sessionThreeRange,i_tz)
sessionThreeActive = in_session_three and timeframe.multiplier <= 30

in_session_four = time(timeframe.period, sessionFourRange,i_tz)
sessionFourActive = in_session_four and timeframe.multiplier <= 30

in_session_five = time(timeframe.period, sessionFiveRange,i_tz)
sessionFiveActive = in_session_five and timeframe.multiplier <= 30

f_resInMinutes() =>
    _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)

barHour = hour(time,i_tz)
barMin = minute(time,i_tz)

checkLastBar(sessionRange)=>
    splitSessionOne = str.split(sessionRange,'')
    
    hour1 = array.get(splitSessionOne,5)
    hour2 = array.get(splitSessionOne,6)
    hourSessionOne = str.tonumber(hour1+hour2)
    
    min1 = array.get(splitSessionOne,7)
    min2 = array.get(splitSessionOne,8)
    minSessionOne = str.tonumber(min1+min2)
    
    if hourSessionOne == 0
        hourSessionOne := 24
    
    if minSessionOne == 0
        minSessionOne := 60
        hourSessionOne := hourSessionOne -1
    
    _islastBarSession = (barHour == hourSessionOne) and (barMin >= minSessionOne - f_resInMinutes())
    islastBarSession = _islastBarSession and _islastBarSession[1] == false
    
islastBarSessionFive = checkLastBar(sessionFiveRange)

var float highVal = na, var float lowVal = na, var float openVal = na
var line hLine = na, var line lLine = na, var line oLine = na
var line tempHLine = na, var line tempLLine = na
var linefill fill1 = na

if sessionFiveActive
    if sessionFiveActive[1] == false
        openVal := open
    if high >= nz(highVal, 0)
        highVal := high
    else
        highVal := highVal

    if low <= nz(lowVal, high)
        lowVal := low
    else
        lowVal := lowVal
else
    highVal := na
    lowVal := na
    openVal := na

startIndexH = ta.valuewhen(na(highVal[1]) and highVal, bar_index, 0)
startIndexL = ta.valuewhen(na(lowVal[1]) and lowVal, bar_index, 0)

//Plot H/L lines
if sessionFiveActive
    oLine := line.new(startIndexH, openVal, bar_index, openVal, color=colorFiveOpen, width=1, style=lineStyleFive)
    tempHLine := line.new(startIndexH, highVal, bar_index, highVal, color=colorFiveHL, width=1, style=lineStyleFive)
    tempLLine := line.new(startIndexL, lowVal, bar_index, lowVal, color=colorFiveHL, width=1, style=lineStyleFive)
    fill1 := linefill.new(tempHLine, tempLLine, activeFive)
    linefill.delete(fill1[1]) 
    line.delete(tempHLine[1]), line.delete(tempLLine[1])

if islastBarSessionFive
    hLine := line.new(startIndexH, highVal, bar_index, highVal, color=colorFiveHL, width=1, style=lineStyleFive)
    lLine := line.new(startIndexL, lowVal, bar_index, lowVal, color=colorFiveHL, width=1, style=lineStyleFive)
    linefill.new(hLine, lLine, passiveFive)

var line openLine = na
if sessionOneActive and sessionOneActive[1] == false
    openLine := line.new(bar_index,high,bar_index,low,extend=extend.both,color=colorOne, style=lineStyleOne)
    
var line lunchOpen = na, var line lunchClose = na
if sessionTwoActive and sessionTwoActive[1] == false
    lunchOpen := line.new(bar_index,high,bar_index,low,extend=extend.both,color=colorTwo , style=lineStyleTwo)

if sessionTwoActive==false and sessionTwoActive[1]
    lunchClose := line.new(bar_index,high,bar_index,low,extend=extend.both,color=colorTwo, style=lineStyleTwo)
    linefill.new(lunchOpen, lunchClose, colorTwoFill)

var line algoLine = na
if sessionThreeActive and sessionThreeActive[1] == false
    algoLine := line.new(bar_index,high,bar_index,low,extend=extend.both,color=colorThree, style=lineStyleThree)    
    
var line endLine = na
if sessionFourActive and sessionFourActive[1] == false
    endLine := line.new(bar_index,high,bar_index,low,extend=extend.both,color=colorFour, style=lineStyleFour) 

//------------------------------------------------------------------------------------
// Trading Checklist
//------------------------------------------------------------------------------------
_titleGrp = "Title"
_TitleTxt = input.string("Trading Checklist", "Title", inline="1", group=_titleGrp)
title_text_color = input.color(#14a9e4b0, "", inline="1", group=_titleGrp)
_titleTextSize = input.string('Large', 'Text Size', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group=_titleGrp)
titleTextSize = _titleTextSize == 'Auto' ? size.auto : _titleTextSize == 'Tiny' ? size.tiny : _titleTextSize == 'Small' ? size.small : _titleTextSize == 'Normal' ? size.normal : _titleTextSize == 'Large' ? size.large : size.huge
_title_alignment = input.string('Center', 'Text Alignment ', group=_titleGrp, options=['Left', 'Center', 'Right'])
title_alignment = _title_alignment == "Left" ? text.align_left : _title_alignment == "Center" ? text.align_center : text.align_right

_bodyGrp = "Body"
_midTxt = input.text_area("TRADING PLAN\n✅ Trend Direction\n✅ Check London Fix\n\n✅9:30 to 10am reversal\n✅ Risk 1%\n\nPSYCHOLOGY\n✅ Don't Chase!", "Body", group=_bodyGrp)
body_text_color = input.color(#d6d6d6b0, "Text Color", group=_bodyGrp)
bg_color = input.color(#00000000, "Background Color", group=_bodyGrp)
_bodyTextSize = input.string('Normal', 'Text Size', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group=_bodyGrp)
bodyTextSize = _bodyTextSize == 'Auto' ? size.auto : _bodyTextSize == 'Tiny' ? size.tiny : _bodyTextSize == 'Small' ? size.small : _bodyTextSize == 'Normal' ? size.normal : _bodyTextSize == 'Large' ? size.large : size.huge
_txt_alignment = input.string('Left', 'Text Alignment ', group=_bodyGrp, options=['Left', 'Center', 'Right'])
txt_alignment = _txt_alignment == "Left" ? text.align_left : _txt_alignment == "Center" ? text.align_center : text.align_right

_tableGrp = "Position"
_tableYpos = input.string('Top', '↕ ', inline='01', group=_tableGrp, options=['Top', 'Middle', 'Bottom'])
tableYpos = _tableYpos == "Top" ? "top" : _tableYpos == "Bottom" ? "bottom" : "middle"
_tableXpos = input.string('Right', '   ↔', inline='01', group=_tableGrp, options=['Left', 'Center', 'Right'], tooltip='Position on the chart.')
tableXpos = _tableXpos == "Right" ? "right" : _tableXpos == "Center" ? "center" : "left"

// Draw Table
var tradingPanel = table.new(position= tableYpos + '_' + tableXpos , columns=1, rows=3, bgcolor=bg_color, border_width = 0)
if barstate.islast
    // Title
    table.cell(table_id=tradingPanel, column=0, row=0, text=_TitleTxt, text_size=titleTextSize, text_color=title_text_color, text_halign = title_alignment)
    // Body
    table.cell(table_id=tradingPanel, column=0, row=1, text=_midTxt, text_size=bodyTextSize, text_color=body_text_color, text_halign = txt_alignment)

var GRP1 = "Settings"
showLines = input(title='Show Lines ?', defval=true, group=GRP1)
showBackground = input(title='Show Background ?', defval=true, group=GRP1)
showMiddleLine = input(title='Show Middle Line ?', defval=true, group=GRP1)
extendLines = input(title='Extend Lines ?', defval=true, group=GRP1)
rangeTime = input.session(title='Session Time', defval='0530-0900', group=GRP1)
extendTime = input.session(title='Extended Lines Time', defval='0900-1659', group=GRP1)

var GRP2 = "Styles"
linesWidth = input.int(2, 'Box And Lines Width ?', minval=1, maxval=4, group=GRP2)
boxLineColor = input(color.blue, 'Box and H/L Line Color', group=GRP2)
middleLineColor = input(color.red, 'Middle Line Color', group=GRP2)
backgroundColor = input(color.new(color.aqua, 90), 'Box Background Color', group=GRP2)

inSession = not na(time(timeframe.period, rangeTime))
inExtend = not na(time(timeframe.period, extendTime))

startTime = 0
startTime := inSession and not inSession[1] ? time : startTime[1]

//Box lines
var line lowHLine = na
var line topHLine = na
var line leftVLine = na
var line rightVLine = na
var line middleHLine = na
var box bgBox = na

var low_val = 0.0
var high_val = 0.0
if inSession and not inSession[1]
    low_val := low
    high_val := high
    high_val

// Plot lines
if inSession and timeframe.isintraday
    if inSession[1]
        line.delete(lowHLine)
        line.delete(topHLine)
        line.delete(leftVLine)
        line.delete(rightVLine)
        line.delete(middleHLine)
        box.delete(bgBox)

    if low < low_val
        low_val := low
        low_val
    if high > high_val
        high_val := high
        high_val

    //Create Box
    //x1, y1, x2, y2
    if showBackground
        bgBox := box.new(startTime, high_val, time, low_val, xloc=xloc.bar_time, bgcolor=backgroundColor, border_width=0)

    if showLines
        lowHLine := line.new(startTime, low_val, time, low_val, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)
        topHLine := line.new(startTime, high_val, time, high_val, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)
        leftVLine := line.new(startTime, high_val, startTime, low_val, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)
        rightVLine := line.new(time, high_val, time, low_val, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)

    //Create Middle line
    if showMiddleLine
        middleHLine := line.new(startTime, (high_val + low_val) / 2, time, (high_val + low_val) / 2, xloc=xloc.bar_time, color=middleLineColor, style=line.style_dotted, width=linesWidth)

else
    if inExtend and extendLines and not inSession and timeframe.isintraday
        time1 = line.get_x1(lowHLine)
        time2 = line.get_x2(lowHLine)
        price = line.get_y1(lowHLine)
        line.delete(lowHLine)
        lowHLine := line.new(time1, price, time, price, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)
        
        time1 := line.get_x1(topHLine)
        time2 := line.get_x2(topHLine)
        price := line.get_y1(topHLine)
        line.delete(topHLine)
        topHLine := line.new(time1, price, time, price, xloc=xloc.bar_time, color=boxLineColor, style=line.style_solid, width=linesWidth)

        time1 := line.get_x1(middleHLine)
        time2 := line.get_x2(middleHLine)
        price := line.get_y1(middleHLine)
        line.delete(middleHLine)
        middleHLine := line.new(time1, price, time, price, xloc=xloc.bar_time, color=middleLineColor, style=line.style_dotted, width=linesWidth)
        middleHLine


//////////////////////SMT///////////////////////////////////
length = input.int(3, 'Pivot Lookback', minval = 2)

//Symbol A
useSym1 = input(true, 'Comparison Symbol', inline = 'symA')
sym1    = input.symbol('CME_MINI_DL:ES1!', '', inline = 'symA')

//Symbol B
useSym2 = input(true, 'Comparison Symbol', inline = 'symB')
sym2   = input.symbol('CBOT_MINI_DL:YM1!', '', inline = 'symB')

//Style
bullDivCss = input.color(#ff1100, 'Swing High', group = 'Style')
bearDivCss = input.color(#2157f3, 'Swing Low', group = 'Style')

//Dashboard
showDash = input(false, 'Show Dashboard'                                                               , group = 'Dashboard')
dashLoc  = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size'        , options = ['Tiny', 'Small', 'Normal']                 , group = 'Dashboard')

//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
n = bar_index

get_hl() => [high, low, close]

//Swing highs divergences
get_divergence(ph, y2, sym_y2, css)=>
    var float y1 = na
    var float sym_y1 = na
    var int x1 = na
    var smt = 0

    if y2 != y2[1] and sym_y2 != sym_y2[1] 
        //Test for SMT
        if (y2 - y1) * (sym_y2 - sym_y1) < 0
            line.new(n[length], y2, x1, y1, color = css)

            smt += 1
        
        sym_y1 := sym_y2
        y1 := y2
        x1 := n[length]
    else if (ph and y2 > y2[1]) or (not ph and y2 < y2[1]) 
        sym_y1 := na
        y1 := y2
        x1 := n[length]
    
    smt

//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
var phN = 0, var plN = 0
var ph_smt1 = 0.
var pl_smt1 = 0.
var ph_smt2 = 0.
var pl_smt2 = 0.

ticker1 = syminfo.ticker(sym1)
ticker2 = syminfo.ticker(sym2)

//-----------------------------------------------------------------------------}
//Detect swing highs/lows and divergences
//-----------------------------------------------------------------------------{
ph = fixnan(ta.pivothigh(length, length))
pl = fixnan(ta.pivotlow(length, length))
phN += ph != ph[1] ? 1 : 0
plN += pl != pl[1] ? 1 : 0

//Comparison symbol pivots
[h1, l1, c1] = request.security(sym1, timeframe.period, get_hl())
[h2, l2, c2] = request.security(sym2, timeframe.period, get_hl())

//Detect swing high divergences
if useSym1
    sym_ph1 = fixnan(ta.pivothigh(h1, length, length))
    sym_pl1 = fixnan(ta.pivotlow(l1, length, length))

    ph_smt1 := get_divergence(true, ph, sym_ph1, bullDivCss)
    pl_smt1 := get_divergence(false, pl, sym_pl1, bearDivCss)

if useSym2
    sym_ph2 = fixnan(ta.pivothigh(h2, length, length))
    sym_pl2 = fixnan(ta.pivotlow(l2, length, length))
    
    ph_smt2 := get_divergence(true, ph, sym_ph2, bullDivCss)
    pl_smt2 := get_divergence(false, pl, sym_pl2, bearDivCss)

txt = ''
if ph != ph[1]
    if ph_smt1 > ph_smt1[1]
        txt += ticker1
    if ph_smt2 > ph_smt2[1]
        txt += txt != '' ? ' | ' : ''
        txt += ticker2

    if txt != ''
        label.new(n[length], ph, txt
          , color = bullDivCss
          , style = label.style_label_down
          , textcolor = color.white
          , size = size.tiny)
else
    if pl_smt1 > pl_smt1[1]
        txt += ticker1
    if pl_smt2 > pl_smt2[1]
        txt += txt != '' ? ' | ' : ''
        txt += ticker2

    if txt != ''
        label.new(n[length], pl, txt
          , color = bearDivCss
          , style = label.style_label_up
          , textcolor = color.white
          , size = size.tiny)
    
//-----------------------------------------------------------------------------}
//Tables
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left 
  : dashLoc == 'Top Right' ? position.top_right 
  : position.bottom_right

var table_size = textSize == 'Tiny' ? size.tiny 
  : textSize == 'Small' ? size.small 
  : size.normal

var tb = table.new(table_position, 3, 3
  , bgcolor = #1e222d
  , border_color = #373a46
  , border_width = 1
  , frame_color = #373a46
  , frame_width = 1)

if barstate.isfirst and showDash
    tb.cell(1, 0, 'Swing High', text_color = color.white)
    tb.cell(2, 0, 'Swing Low', text_color = color.white)
    
    tb.cell(0, 1, ticker1, text_color = color.white)
    tb.cell(0, 2, ticker2, text_color = color.white)

if barstate.islast and showDash
    //Symbol 1
    tb.cell(1, 1, str.format('{0} ({1, number, percent})', ph_smt1, ph_smt1 / phN)
      , text_color = bullDivCss)
    tb.cell(2, 1, str.format('{0} ({1, number, percent})', pl_smt1, pl_smt1 / plN)
      , text_color = bearDivCss)
    
    //Symbol 2
    tb.cell(1, 2, str.format('{0} ({1, number, percent})', ph_smt2, ph_smt2 / phN)
      , text_color = bullDivCss)
    tb.cell(2, 2, str.format('{0} ({1, number, percent})', pl_smt2, pl_smt2 / plN)
      , text_color = bearDivCss)

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

//****************************************************************************//
// Define User Input Variables

nATRPeriod = input(50, 'ATR Period')
nATRMultip = input.float(3.5, 'Multiplier', minval=0.5, maxval=1000, step=0.25)
len2 = 20  //input(20, minval=1, title="Smooth")
src = close
out = ta.vwma(src, len2)

xsrc = close
xprd1 = 12
xsrc2 = close
xprd2 = 26
xsmooth = 1
fillSW = input(title='Mumları Renkli Kullan', defval=true)
fillSW1 = input(title='Mumları Yeşil Kullan - Red', defval=false)
fastSW = input(title='Fast Moving Avarage Göster', defval=true)
slowSW = input(title='Slow Moving Avarage Göster', defval=true)
labelSwitch = input(title='Trend Asistan', defval=true)
plotSigsw = input(title='Al/Sat Sinyaller? ', defval=true)
plotRibsw = input(title='Al/Sat Ribbon', defval=true)
plotRibbonPos = input.string(title='Ribbon', options=['Top', 'Bottom'], defval='Top')

xfixtf = input(title='** Sabit Zaman Dilimi) **', defval=false)
xtf = input.timeframe(title='** Hangi zaman dilimine sabitlensin ? **)', defval='D')

plotSig2sw = input(title='Momentum Al/Sat Sinyalleri? ', defval=true)
plotSig2lv = input.int(title='Sinyal Aralığı (yüksek = daha detaylı)', defval=1, minval=0, maxval=1)

//****************************************************************************//
//Calculate Indicators

stop = ta.ema(xsrc, xprd1)
wavy_h = ta.ema(high, 14)
wavy_c = ta.ema(close, 14)
wavy_l = ta.ema(low, 14)
tunnel1 = ta.ema(close, 144)
tunnel2 = ta.ema(close, 169)

plot(stop, title='TP EMA', color=color.new(color.red, 0), linewidth=2)
plot(wavy_h, title='EB 14 High', color=color.new(color.aqua, 0), linewidth=1, style=plot.style_cross)
plot(wavy_c, title='EB 14 Mid', color=color.new(color.silver, 0), linewidth=1, style=plot.style_cross)
plot(wavy_l, title='EB 14 Low', color=color.new(color.aqua, 0), linewidth=1, style=plot.style_cross)

plot(tunnel1, title='Tunnel 144', color=color.new(color.purple, 0), linewidth=1, style=plot.style_line)
plot(tunnel2, title='Tunnel 169', color=color.new(color.purple, 0), linewidth=2, style=plot.style_line)

xPrice = ta.ema(xsrc, xsmooth)
FastMA = xfixtf ? ta.ema(request.security(syminfo.tickerid, xtf, ta.ema(xsrc, xprd1)), xsmooth) : ta.ema(xPrice, xprd1)


xPrice2 = ta.ema(xsrc2, xsmooth)
SlowMA = xfixtf ? ta.ema(request.security(syminfo.tickerid, xtf, ta.ema(xsrc2, xprd2)), xsmooth) : ta.ema(xPrice2, xprd2)

Bull = FastMA > SlowMA
Bear = FastMA < SlowMA

//****************************************************************************//
// Define Color Zones

Green = Bull and xPrice > FastMA  // Buy
Blue = Bear and xPrice > FastMA and xPrice > SlowMA  //Pre Buy 2 (Strong dip) Consider adding long position
LBlue = Bear and xPrice > FastMA and xPrice < SlowMA  //Pre Buy 1 (Weak Dip)

Red = Bear and xPrice < FastMA  // Sell
Orange = Bull and xPrice < FastMA and xPrice < SlowMA  // Pre Sell 2 (Strong Rally) Consider adding short position
Yellow = Bull and xPrice < FastMA and xPrice > SlowMA  // Pre Sell 1 (Weak Rally)

//****************************************************************************//
// Display color on chart

//****************************************************************************//
// Display MA lines

FastL = plot(fastSW ? FastMA : na, 'Fast EMA', color=color.new(color.red, 100))
SlowL = plot(slowSW ? SlowMA : na, 'Slow EMA', color=color.new(color.blue, 100))
fillcolor = Bull ? color.green : Bear ? color.red : color.black
fill(FastL, SlowL, fillcolor, transp=70)

//****************************************************************************//
// Define Buy and Sell condition
// This is only for thebasic usage of CDC Actionzone (EMA Crossover) 
// ie. Buy on first green bar and sell on first red bar

buycond = Green and Green[1] == 0
sellcond = Red and Red[1] == 0

bullish = ta.barssince(buycond) < ta.barssince(sellcond)
bearish = ta.barssince(sellcond) < ta.barssince(buycond)

buy = bearish[1] and buycond
sell = bullish[1] and sellcond

bColor_BullBear = bullish ? color.green : bearish ? color.red : na

//****************************************************************************//
// Plot Buy and Sell point on chart

plotshape(plotSigsw ? buy : na, style=shape.circle, title='Buy Signal', location=location.belowbar, size=size.tiny, color=color.new(color.green, 0))
plotshape(plotSigsw ? sell : na, style=shape.circle, title='Sell Signal', location=location.abovebar, size=size.tiny, color=color.new(color.red, 0))


// Display Buy/Sell Ribbon


plotshape(plotRibsw ? plotRibbonPos == 'Top' ? close : na : na, style=shape.square, title='Buy/Sell Ribbon', location=location.top, color=bColor_BullBear)

plotshape(plotRibsw ? plotRibbonPos == 'Bottom' ? close : na : na, style=shape.square, title='Buy/Sell Ribbon', location=location.bottom, color=bColor_BullBear)


//****************************************************************************//
// Label

labelstyle = close > SlowMA ? label.style_label_down : label.style_label_up
labelyloc = close > SlowMA ? yloc.abovebar : yloc.belowbar
labeltcolor = buy ? color.black : sell ? color.white : close > close[1] ? color.green : color.red
labelbgcolor = buy ? color.green : sell ? color.red : color.silver
labeltext = buy ? 'BUY next bar\n' : sell ? 'SELL next bar\n' : ' '
trendText = bullish ? 'bullish' : bearish ? 'bearish' : 'sideways'




// Momentum Signal using StochRSI

// Adds a momentum based signal following trends to the script
// Default is hidden, only use with caution
// Parameters for STOCH RSI is hard-coded to avoid cluttering the input screen further
// If you need to change anything, make a copy of the code and change it.
// Inputs are commented out, to enable them comment out the hard coded variables first!

// fixed inputs //

smoothK = 3
smoothD = 3
RSIlen = 14
STOlen = 14
SRsrc = close
OSlevel = 30
OBlevel = 70

// User inputs // // COMMENT ABOVE VARIABLES FIRST!! 

// smoothK = input(3,"StochRSI smooth K",type=input.integer,minval=1)
// smoothD = input(3,"StochRSI smooth D",type=input.integer,minval=1)
// RSIlen = input(14,"RSI length",type=input.integer,minval=1)
// STOlen = input(14,"Stochastic length",type=input.integer,minval=1)
// SRsrc = input(close,"Source for StochasticRSI",type=input.source)
// OSlevel = input(30,"Oversold Threshold",type=input.float,minval=0.00)
// OBlevel = input(70,"Oversold Threshold",type=input.float,minval=0.00)

// calculations //
rsi1 = ta.rsi(SRsrc, RSIlen)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, STOlen), smoothK)
d = ta.sma(k, smoothD)

// storsiBuySig =  if bullish
//     if (d < OSlevel and crossover(k,d))
//         3
//     else if crossover(k,OSlevel)
//         2
//     else if d > OSlevel and crossover(k,d)
//         1
//     else
//         0
// else
//     0

crossover_1 = ta.crossover(k, d)
crossover_2 = ta.crossover(k, d)
iff_1 = d > OSlevel and crossover_2 ? 1 : 0
iff_2 = d < OSlevel and crossover_1 ? 2 : iff_1
storsiBuySig = bullish ? iff_2 : 0

crossunder_1 = ta.crossunder(k, d)
crossunder_2 = ta.crossunder(k, d)
iff_3 = d < OBlevel and crossunder_2 ? 1 : 0
iff_4 = d > OBlevel and crossunder_1 ? 2 : iff_3
storsiSellSig = bearish ? iff_4 : 0

buymore = plotSig2sw ? storsiBuySig > plotSig2lv ? storsiBuySig : na : na
sellmore = plotSig2sw ? storsiSellSig > plotSig2lv ? storsiSellSig : na : na

plotshape(buymore, 'Buy more signals', style=shape.triangleup, location=location.belowbar, color=color.new(color.teal, 0), size=size.small)
plotshape(sellmore, 'Sell more signals', style=shape.triangledown, location=location.abovebar, color=color.new(color.orange, 0), size=size.small)


//****************************************************************************//
// Alert conditions

alertcondition(buy, title='*Bullish Alarm*', message='Long {{exchange}}:{{ticker}}')

alertcondition(sell, title='*Bearish Alarm*', message='Short {{exchange}}:{{ticker}}')

alertcondition(bullish, title='is Bullish')

alertcondition(bearish, title='is Bearish')

alertcondition(Green, title='is Green')

alertcondition(Blue, title='is Blue (Strong Rally)')

alertcondition(LBlue, title='is Light Blue (Rally)')

alertcondition(Red, title='is Red')

alertcondition(Orange, title='is Orange (Strong Dip)')

alertcondition(Yellow, title='is Yellow (Dip)')


//****************************************************************************//


[supertrend, direction] = ta.supertrend(nATRMultip, nATRPeriod)

LONG  = ta.change(direction) < 0
SHORT = ta.change(direction) > 0
//Bar Color Gradient Version

bColor = Green ? color.green : Blue ? color.blue : LBlue ? color.aqua : Red ? color.red : Orange ? color.orange : Yellow ? color.yellow : na
barcolor(color=fillSW ? bColor : na)

// Show Break Alerts
plotshape(SHORT, title='ATR Sell', style=shape.labeldown, location=location.abovebar, size=size.normal, text='Sell', textcolor=color.new(color.white, 0), color=color.new(color.red, 0))
plotshape(LONG, title='ATR Buy', style=shape.labelup, location=location.belowbar, size=size.normal, text='Buy', textcolor=color.new(color.white, 0), color=color.new(color.green, 0))


// === /PLOTTING ===
// Send alert to TV alarm sub-system
alertcondition(LONG, title='Buy', message='Buy')
alertcondition(SHORT, title='Sell', message='Sell')

alertcondition(buymore, title='Buy more signals', message='Buy more')
alertcondition(sellmore, title='Sell more signals', message='Sell more')


////////////////////////////////////////////////////////////////////////////////VWMA