PROFIT INDICATOR
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Ã‚Â© MANNU
//@version=4

study(title="MANNU MATRIX", shorttitle="MANNU MATRIX", overlay=true) 
showpivot       = input(defval = false, title="Show CPR")
showVWAP        = input(title="Show VWAP", type=input.bool, defval=false)
showEMA20       = input(title="Show EMA-20", type=input.bool, defval=false)
showEMA50       = input(title="Show EMA-50", type=input.bool, defval=false)
showEMA200      = input(title="Show EMA-200", type=input.bool, defval=false)
showSMA50       = input(title="Show SMA-50", type=input.bool, defval=false)
showSMA200      = input(title="Show SMA-200", type=input.bool, defval=false)
showBB          = input(title="Show BB", type=input.bool, defval=false)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// EMA - 5/20/50/100/200 ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

EMA20_Len       = input(20, minval=1, title="EMA20_Length")
//EMA20_src     = input(close, title="EMA20_Source")
//EMA20_offset  = input(title="EMA20_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA20_out       = ema(close, EMA20_Len)
plot(showEMA20 ? EMA20_out:na, title="EMA20", color=color.red, offset=0,linewidth=2)

EMA50_Len       = input(50, minval=1, title="EMA50_Length")
//EMA50_src     = input(close, title="EMA50_Source")
//EMA50_offset  = input(title="EMA50_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA50_out       = ema(close, EMA50_Len)
plot(showEMA50 ? EMA50_out:na, title="EMA50", color=color.blue, offset=0,linewidth=2)

EMA200_Len       = input(200, minval=1, title="EMA200_Length")
//EMA200_src     = input(close, title="EMA200_Source")
//EMA200_offset  = input(title="EMA200_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
EMA200_out       = ema(close, EMA200_Len)
plot(showEMA200 ? EMA200_out:na, title="EMA200", color=color.yellow, offset=0,linewidth=2)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// SMA - 9/20/50/100/200 ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

SMA50_Len       = input(50, minval=1, title="SMA50_Length")
//SMA50_src     = input(close, title="SMA50_Source")
//SMA50_offset  = input(title="SMA50_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
SMA50_out       = sma(close, SMA50_Len)
plot(showSMA50 ? SMA50_out:na, title="SMA50", color=color.maroon, offset=0,linewidth=2)

SMA200_Len       = input(200, minval=1, title="SMA200_Length")
//SMA200_src     = input(close, title="SMA200_Source")
//SMA200_offset  = input(title="SMA200_Offset", type=input.integer, defval=0, minval=-500, maxval=500)
SMA200_out       = sma(close, SMA200_Len)
plot(showSMA200 ? SMA200_out:na, title="SMA200", color=color.aqua, offset=0,linewidth=2)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// VWAP /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//vwaplength    = input(title="VWAP Length", type=input.integer, defval=1)
//cvwap         = ema(vwap,vwaplength)
cvwap1          = vwap(hlc3)
plotvwap        = plot(showVWAP ? cvwap1 : na,title="VWAP",color=color.black, transp=0, linewidth=2)


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// CENTRAL PIVOT RANGE (CPR) //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
res             = input(title="Resolution", type=input.resolution, defval="D")
res1            = input(title="Resolution", type=input.resolution, defval="W")
res2            = input(title="Resolution", type=input.resolution, defval="M")
H               = security(syminfo.tickerid, res, high[1],   barmerge.gaps_off, barmerge.lookahead_on)
L               = security(syminfo.tickerid, res, low[1],    barmerge.gaps_off, barmerge.lookahead_on)
C               = security(syminfo.tickerid, res, close[1],  barmerge.gaps_off, barmerge.lookahead_on)
WH              = security(syminfo.tickerid, res1, high[1],  barmerge.gaps_off, barmerge.lookahead_on)
WL              = security(syminfo.tickerid, res1, low[1],   barmerge.gaps_off, barmerge.lookahead_on)
WC              = security(syminfo.tickerid, res1, close[1], barmerge.gaps_off, barmerge.lookahead_on)
MH              = security(syminfo.tickerid, res2, high[1],  barmerge.gaps_off, barmerge.lookahead_on)
ML              = security(syminfo.tickerid, res2, low[1],   barmerge.gaps_off, barmerge.lookahead_on)
MC              = security(syminfo.tickerid, res2, close[1], barmerge.gaps_off, barmerge.lookahead_on)
TTH              = security(syminfo.tickerid, res, high,  barmerge.gaps_off, barmerge.lookahead_on)
TTL              = security(syminfo.tickerid, res, low,   barmerge.gaps_off, barmerge.lookahead_on)
TTC              = security(syminfo.tickerid, res, close, barmerge.gaps_off, barmerge.lookahead_on)

PP              = (H + L + C) / 3
TC              = (H + L)/2
BC              = (PP - TC) + PP
R1              = (PP * 2) - L
R2              = PP + (H - L)
R3              = H + 2*(PP - L)
R4              = PP * 3 + (H - 3 * L)
S1              = (PP * 2) - H
S2              = PP - (H - L)
S3              = L - 2*(H - PP)
S4              = PP*3 - (3*H - L)
WPP             = (WH + WL + WC)/3
WTC             = (WH + WL)/2
WBC             = (WPP - WTC) + WPP
MPP             = (MH + ML + MC)/3
MTC             = (MH + ML)/2
MBC             = (MPP - MTC) + MPP
TOPP             = (TTH + TTL + TTC)/3
TOTC             = (TTH + TTL)/2
TOBC             = (TOPP - TOTC) + TOPP
TR1              = (TOPP * 2) - TTL
TR2              = TOPP + (TTH - TTL)
TS1              = (TOPP * 2) - TTH
TS2              = TOPP - (TTH - TTL)
plot(showpivot ? PP : na, title="PP", style=plot.style_stepline, color=color.blue, linewidth=2)
plot(showpivot ? TC : na, title="TC", style=plot.style_circles, color=color.blue,   linewidth=1)
plot(showpivot ? BC : na, title="BC", style=plot.style_circles, color=color.blue,   linewidth=1)

plot(showpivot ? WPP : na, title="WPP", style=plot.style_stepline, color=color.black, linewidth=2)
plot(showpivot ? WTC : na, title="WTC", style=plot.style_stepline, color=color.black,   linewidth=2)
plot(showpivot ? WBC : na, title="WBC", style=plot.style_stepline, color=color.black,   linewidth=2)

plot(showpivot ? MPP : na, title="MPP", style=plot.style_stepline, color=color.black, linewidth=2)
plot(showpivot ? MTC : na, title="MTC", style=plot.style_stepline, color=color.black,   linewidth=2)
plot(showpivot ? MBC : na, title="MBC", style=plot.style_stepline, color=color.black,   linewidth=2)

plot(showpivot ? S1 : na, title="S1", style=plot.style_stepline, color=color.green,  linewidth=1)
plot(showpivot ? S2 : na, title="S2", style=plot.style_stepline, color=color.green,  linewidth=1)
plot(showpivot ? S3 : na, title="S3", style=plot.style_stepline, color=color.green,  linewidth=1)
plot(showpivot ? S4 : na, title="S4", style=plot.style_stepline, color=color.green,  linewidth=1)

plot(showpivot ? R1 : na, title="R1", style=plot.style_stepline, color=color.red,  linewidth=1)
plot(showpivot ? R2 : na, title="R2", style=plot.style_stepline, color=color.red,  linewidth=1)
plot(showpivot ? R3 : na, title="R3", style=plot.style_stepline, color=color.red,  linewidth=1)
plot(showpivot ? R4 : na, title="R4", style=plot.style_stepline, color=color.red,  linewidth=1)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// PREVIOUS DAY /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
prevDayHigh     = security(syminfo.tickerid, 'D', high[1], lookahead=true)
prevDayLow      = security(syminfo.tickerid, 'D', low[1], lookahead=true)
plot( showpivot and prevDayHigh ? prevDayHigh : na, title="Prev Day High", style=plot.style_circles, linewidth=2, color=color.red, transp=0)
plot( showpivot and prevDayLow ? prevDayLow  :  na, title="Prev Day Low", style=plot.style_circles, linewidth=2, color=color.green, transp=0)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// PREVIOUS WEEKLY  ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
prevWeekHigh     = security(syminfo.tickerid, 'W', high[1], lookahead=true)
prevWeekLow      = security(syminfo.tickerid, 'W', low[1], lookahead=true)
plot( showpivot and prevWeekHigh ? prevWeekHigh : na, title="Prev Week High", style=plot.style_stepline, linewidth=2, color=color.red, transp=0)
plot( showpivot and prevWeekLow ? prevWeekLow  :  na, title="Prev Week Low", style=plot.style_stepline, linewidth=2, color=color.green, transp=0)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// PREVIOUS MONTH /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
prevMonthHigh    = security(syminfo.tickerid, 'M', high[1], lookahead=true)
prevMonthLow     = security(syminfo.tickerid, 'M', low[1], lookahead=true)
plot( showpivot and prevMonthHigh ? prevMonthHigh : na, title="Prev Month High", style=plot.style_stepline, linewidth=2, color=color.red, transp=0)
plot( showpivot and prevMonthLow ? prevMonthLow  :  na, title="Prev Month Low", style=plot.style_stepline, linewidth=2, color=color.green, transp=0)



//HAlftrend

amplitude = input(title="Amplitude", defval=3)
channelDeviation = input(title="Channel Deviation", defval=2)
showArrows = input(title="Show Arrows", defval=true)
showChannels = input(title="Show Channels", defval=false)

var int trend1 = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)

var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na

atr2 = atr(100) / 2
dev1 = channelDeviation * atr2

highPrice = high[abs(highestbars(amplitude))]
lowPrice = low[abs(lowestbars(amplitude))]
highma = sma(high, amplitude)
lowma = sma(low, amplitude)

if nextTrend == 1
	maxLowPrice := max(lowPrice, maxLowPrice)

	if highma < maxLowPrice and close < nz(low[1], low)
		trend1 := 1
		nextTrend := 0
		minHighPrice := highPrice
else
	minHighPrice := min(highPrice, minHighPrice)

	if lowma > minHighPrice and close > nz(high[1], high)
		trend1 := 0
		nextTrend := 1
		maxLowPrice := lowPrice

if trend1 == 0
	if not na(trend1[1]) and trend1[1] != 0
		up := na(down[1]) ? down : down[1]
		arrowUp := up - atr2
	else
		up := na(up[1]) ? maxLowPrice : max(maxLowPrice, up[1])
	atrHigh := up + dev1
	atrLow := up - dev1
else
	if not na(trend1[1]) and trend1[1] != 1 
		down := na(up[1]) ? up : up[1]
		arrowDown := down + atr2
	else
		down := na(down[1]) ? minHighPrice : min(minHighPrice, down[1])
	atrHigh := down + dev1
	atrLow := down - dev1

ht = trend1 == 0 ? up : down

var color buyColor = color.green
var color sellColor = color.red

htColor = trend1 == 0 ? buyColor : sellColor
htPlot = plot(ht, title="HalfTrend", linewidth=2, color=htColor)

//atrHighPlot = plot(showChannels ? atrHigh : na, title="ATR High", style=plot.style_circles, color=sellColor)
//atrLowPlot = plot(showChannels ? atrLow : na, title="ATR Low", style=plot.style_circles, color=buyColor)

//fill(htPlot, atrHighPlot, title="ATR High Ribbon", color=sellColor)
//fill(htPlot, atrLowPlot, title="ATR Low Ribbon", color=buyColor)

buySignal = not na(arrowUp) and (trend1 == 0 and trend1[1] == 1)
sellSignal = not na(arrowDown) and (trend1 == 1 and trend1[1] == 0)

plotshape(showArrows and buySignal ? atrLow : na, title="Arrow Up" ,text="Buy" , style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, location=location.absolute, size=size.small,color=buyColor)
//plotshape(showArrows and sellSignal ? atrHigh : na, title="Arrow Down", style=shape.triangledown, location=location.absolute, size=size.tiny, color=sellColor)

plotshape(showArrows and sellSignal ? atrHigh : na, title="Arrow Down",text="Sell",  size=size.tiny, color=color.red, textcolor=color.white,style=shape.labeldown , location=location.absolute, size=size.small, color=sellColor)
alertcondition(buySignal, title="Alert: Buy", message="Buy")
alertcondition(sellSignal, title="Alert: Sell", message="Sell")

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// BOLLINGER BANDS/////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

length1          = 20                //input(20, minval=1)
src1             = close             //input(close, title="BB_Source")
mult            = 2                 //input(2.0, minval=0.001, maxval=50, title="BB_StdDev")
basis           = sma(src1, length1)
dev             = mult * stdev(src1, length1)
upper           = basis + dev
lower           = basis - dev
p1              = plot(showBB ? upper : na, "Upper", color=color.red, editable=true)
p2              = plot(showBB ? lower: na, "Lower", color=color.green, editable=true)
plot(showBB ? basis : na, "Basis", color=#872323, editable=true)
fill(p1, p2, title = "Background", color=#198787, transp=95)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// FIB LEVELS /////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Fib levels


//------------------------------------------------------------------------------
extendType          =input(true, title="Extend lines?") ? extend.right : extend.none
show_price          =input(true, title="show price?") 
Reverse             =input(false, title="Reverse Direction?")
//------------------------------------------------------------------------------

FPeriod      = input(100, title="lookback length")
Fhigh        = highest(FPeriod)
Flow         = lowest(FPeriod)
SwingHigh    = highestbars(high, FPeriod)
SwingLow     = lowestbars(low, FPeriod)
downfib      = Reverse ? SwingHigh > SwingLow : SwingHigh < SwingLow

X1_offset    = downfib ? SwingHigh : SwingLow
X2_offset    =15

bar_index_duration  = time - time[1]                                        // time between bars

X1           = X1_offset * bar_index_duration                               // starting level x position
X2           = X2_offset * bar_index_duration                               // ending level x position
lbl_X2       = ((show_price ? 15 : 6) + X2_offset) * bar_index_duration     // label x position

F000        =downfib ? Flow : Fhigh
F236        =downfib ? (Fhigh-Flow) * 0.236 + Flow : Fhigh - (Fhigh-Flow) * 0.236
F382        =downfib ? (Fhigh-Flow) * 0.382 + Flow : Fhigh - (Fhigh-Flow) * 0.382
F500        =downfib ? (Fhigh-Flow) * 0.500 + Flow : Fhigh - (Fhigh-Flow) * 0.500
F618        =downfib ? (Fhigh-Flow) * 0.618 + Flow : Fhigh - (Fhigh-Flow) * 0.618
F786        =downfib ? (Fhigh-Flow) * 0.786 + Flow : Fhigh - (Fhigh-Flow) * 0.786
F100        =downfib ? Fhigh : Flow  

F000_color  =color.new(color.orange,0)
F236_color  =color.new(color.orange,0)
F382_color  =color.new(color.orange,0)
F500_color  =color.new(color.orange,0)
F618_color  =color.new(color.orange,0)
F786_color  =color.new(color.orange,0)
F100_color  =color.new(color.orange,0)

F000_lbl    =show_price ? "0% [" + tostring(F000) + " ]" : "0%"
F236_lbl    =show_price ? "23.6% [" + tostring(F236) + " ]" : "23.6%"
F382_lbl    =show_price ? "38.2% [" + tostring(F382) + " ]" : "38.2%"
F500_lbl    =show_price ? "50% [" + tostring(F500) + " ]" : "50%"
F618_lbl    =show_price ? "61.8% [" + tostring(F618) + " ]" : "61.8%"
F786_lbl    =show_price ? "78.6% [" + tostring(F786) + " ]" : "78.6%"
F100_lbl    =show_price ? "100% [" + tostring(F100) + " ]" : "100%"

//------------------------------------------------------------------------------
//Setup line & Label Appearance

line_style      =line.style_solid
label_style     =label.style_none
label_size      =size.normal 

//------------------------------------------------------------------------------
// 0 line
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F000,
     x2         = time + X2,
     y2         = F000,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F000_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F000,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F000_lbl,
     color      =F000_color,
     textcolor  =F000_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1])

//------------------------------------------------------------------------------
//236 line
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F236,
     x2         = time + X2,
     y2         = F236,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F236_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F236,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F236_lbl,
     color      =F236_color,
     textcolor  =F236_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1]) 
 
//------------------------------------------------------------------------------
// 382 line
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F382,
     x2         = time + X2,
     y2         = F382,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F382_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F382,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F382_lbl,
     color      =F382_color,
     textcolor  =F382_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1])
//------------------------------------------------------------------------------
//500 line 
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F500,
     x2         = time + X2,
     y2         = F500,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F500_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F500,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F500_lbl,
     color      =F500_color,
     textcolor  =F500_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1]) 
//------------------------------------------------------------------------------
//618 line 
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F618,
     x2         = time + X2,
     y2         = F618,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F618_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F618,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F618_lbl,
     color      =F618_color,
     textcolor  =F618_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1])
//------------------------------------------------------------------------------ 

//786 line
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F786,
     x2         = time + X2,
     y2         = F786,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F786_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F786,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F786_lbl,
     color      =F786_color,
     textcolor  =F786_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1]) 
//------------------------------------------------------------------------------
//100 line
if true
    ln = line.new(
     x1         = time + X1,        
     y1         = F100,
     x2         = time + X2,
     y2         = F100,
     xloc       =xloc.bar_time,
     extend     =extendType,
     color      =F100_color,
     style      =line_style,
     width      =1
     )
    line.delete(ln[1])
if true
    lbl = label.new(
     x          =time + lbl_X2,
     y          =F100,
     xloc       =xloc.bar_time,
     yloc       =yloc.price,
     text       =F100_lbl,
     color      =F100_color,
     textcolor  =F100_color,
     style      =label_style,
     size       =label_size
     )
    label.delete(lbl[1])

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// Multiple HMA////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//inputs
src=close
useCurrentRes = input(true, title="Use Current Chart Resolution?")
resCustom = input(title="Use Different Timeframe? Uncheck Box Above", type=input.resolution, defval="D")
len = input(33, title="Moving Average Length - LookBack Period")
//periodT3 = input(defval=7, title="Tilson T3 Period", minval=1) 
factorT3 = input(defval=7, title="Tilson T3 Factor - *.10 - so 7 = .7 etc.", minval=0) 
atype = input(4,minval=1,maxval=8,title="1=SMA, 2=EMA, 3=WMA, 4=HullMA, 5=VWMA, 6=RMA, 7=TEMA, 8=Tilson T3")
spc=input(false, title="Show Price Crossing 1st Mov Avg - Highlight Bar?")
cc = input(true,title="Change Color Based On Direction?")
smoothe = input(2, minval=1, maxval=10, title="Color Smoothing - Setting 1 = No Smoothing")
doma2 = input(false, title="Optional 2nd Moving Average")
spc2=input(false, title="Show Price Crossing 2nd Mov Avg?")
len2 = input(50, title="Moving Average Length - Optional 2nd MA")
sfactorT3 = input(defval=7, title="Tilson T3 Factor - *.10 - so 7 = .7 etc.", minval=0)
atype2 = input(1,minval=1,maxval=8,title="1=SMA, 2=EMA, 3=WMA, 4=HullMA, 5=VWMA, 6=RMA, 7=TEMA, 8=Tilson T3")
cc2 = input(true,title="Change Color Based On Direction 2nd MA?")
warn = input(false, title="***You Can Turn On The Show Dots Parameter Below Without Plotting 2nd MA to See Crosses***")
warn2 = input(false, title="***If Using Cross Feature W/O Plotting 2ndMA - Make Sure 2ndMA Parameters are Set Correctly***")
sd = input(false, title="Show Dots on Cross of Both MA's")

res_MHMA = useCurrentRes ? timeframe.period : resCustom
//hull ma definition
hullma = wma(2*wma(src, len/2)-wma(src, len), round(sqrt(len)))
//TEMA definition
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
tema = 3 * (ema1 - ema2) + ema3

//Tilson T3
factor = factorT3 *.10
gd(src, len, factor) => ema(src, len) * (1 + factor) - ema(ema(src, len), len) * factor 
t3(src, len, factor) => gd(gd(gd(src, len, factor), len, factor), len, factor) 
tilT3 = t3(src, len, factor) 
 

avg = atype == 1 ? sma(src,len) : atype == 2 ? ema(src,len) : atype == 3 ? wma(src,len) : atype == 4 ? hullma : atype == 5 ? vwma(src, len) : atype == 6 ? rma(src,len) : atype == 7 ? 3 * (ema1 - ema2) + ema3 : tilT3
//2nd Ma - hull ma definition
hullma2 = wma(2*wma(src, len2/2)-wma(src, len2), round(sqrt(len2)))
//2nd MA TEMA definition
sema1 = ema(src, len2)
sema2 = ema(sema1, len2)
sema3 = ema(sema2, len2)
stema = 3 * (sema1 - sema2) + sema3

//2nd MA Tilson T3
sfactor = sfactorT3 *.10
sgd(src, len2, sfactor) => ema(src, len2) * (1 + sfactor) - ema(ema(src, len2), len2) * sfactor 
st3(src, len2, sfactor) => sgd(sgd(gd(src, len2, sfactor), len2, sfactor), len2, sfactor) 
stilT3 = st3(src, len2, sfactor) 

avg2 = atype2 == 1 ? sma(src,len2) : atype2 == 2 ? ema(src,len2) : atype2 == 3 ? wma(src,len2) : atype2 == 4 ? hullma2 : atype2 == 5 ? vwma(src, len2) : atype2 == 6 ? rma(src,len2) : atype2 == 7 ? 3 * (ema1 - ema2) + ema3 : stilT3

out = avg 
out_two = avg2

out1 = security(syminfo.tickerid, res_MHMA, out)
out2 = security(syminfo.tickerid, res_MHMA, out_two)

//Formula for Price Crossing Moving Average #1
cr_up = open < out1 and close > out1
cr_Down = open > out1 and close < out1
//Formula for Price Crossing Moving Average #2
cr_up2 = open < out2 and close > out2
cr_Down2 = open > out2 and close < out2

ma_up = out1 >= out1[smoothe]
ma_down = out1 < out1[smoothe]

col = cc ? ma_up ? color.lime : ma_down ? color.red : color.aqua : color.aqua
col2 = cc2 ? ma_up ? color.lime : ma_down ? color.red : color.aqua : color.white

circleYPosition = out2

plot(out1, title="Multi-Timeframe Moving Avg", style=plot.style_line, linewidth=2, color = col)
plot(doma2 and out2 ? out2 : na, title="2nd Multi-TimeFrame Moving Average", style=plot.style_circles, linewidth=2, color=col2)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// YGS Scalper/////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ShowPAC          = input(true, title="Show wave")
ShowTrendIndi    = input(true, title="Show Trend Indicator")
PACLen           = input(50,minval=2,title="EMA ")
src_YGS          = input(close,title="Source for Wave centre EMA")

// --- CONSTANTS ---
DodgerBlue  = #1E90FF

// === /INPUTS ===
// Constants colours that include fully non-transparent option.
lime100  = #00FF00FF
blue100  = #0000FFFF
aqua100  = #00FFFFFF
darkred100 = #8B0000FF

// === SERIES SETUP ===

// Price action channel (Wave)

pacLo        = ema(low, PACLen)
pacHi        = ema(high, PACLen)


// === /SERIES ===

// === PLOTTING ===
// 
// If selected, Plot the Wave Channel based on EMA high,low and close
L1=plot(ShowPAC ?pacLo:na, color=color.black, linewidth=1, title="up",transp=20)
H1=plot(ShowPAC ?pacHi:na, color=color.black, linewidth=1, title="down",transp=20)

fill(L1,H1, color=color.gray,transp=92,title="Fill Channel")

// Show trend direction indication on the bottom
wcolor = high>pacHi and low>pacHi? color.lime : low<pacLo and high<pacLo ? color.red : color.gray
plotshape(ShowTrendIndi?src_YGS:na, color=wcolor,location=location.bottom,style=shape.square,size=size.normal,transp=20,title="Trend Direction")

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////Trend Strength//////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Trend Strength

t = input(13   , "Length")
p = input(233  , "Plotting Length")
d = input(false, "On Balance Volume Momentum Acceleration (on daily)")

f_speedy(_d, _t) => 
    v = sma(change(_d, _t) / _t, 3) 
    a = change(v, _t) / _t
    v - a

source  = close
pvr     = d and nz(volume) and timeframe.isdaily ? sma(source, t) / sma(volume, t) : na
psgval  = f_speedy(source, t)

plotarrow(psgval, title="Momentum Acceleration Of Price", colorup=color.aqua, colordown=color.orange, transp=80, show_last = p)

plot(nz(volume) * pvr * .041, color=open > close ? color.red : color.green, style=plot.style_columns, title="Volume Histogram", transp=35, show_last = p)
plot(f_speedy(obv,t) * pvr * .34, color=color.aqua, title="Momentum Acceleration of OBV", show_last = p)

// -Alerts ══════════════════════════════════════════════════════════════════════════════════════ //
bothAlertCondition = cross(psgval, 0)  
alertcondition(bothAlertCondition    , "Early Warning"              , "SpeedyGonzales : Probable Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")
alertcondition(bothAlertCondition[1] , "Trading Opportunity"        , "SpeedyGonzales : Probable Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")

longAlertCondition  = crossover(psgval, 0)
alertcondition(longAlertCondition    , "Long : Early Warning"       , "SpeedyGonzales - Not Confirmed Probable Long Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")
alertcondition(longAlertCondition[1] , "Long : Trading Opportunity" , "SpeedyGonzales - Probable Long Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")

shortAlertCondition = crossunder(psgval, 0)
alertcondition(shortAlertCondition   , "Short : Early Warning"      , "SpeedyGonzales - Not Confirmed Probable Short Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")
alertcondition(shortAlertCondition[1], "Short : Trading Opportunity", "SpeedyGonzales - Probable Short Trade Opportunity\n{{exchange}}:{{ticker}}->\nPrice = {{close}},\nTime = {{time}}")

// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
//# *
//# * Purpose     : Ability to optimize a study and observe trade simulation statistics accordingly  
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

// -Inputs ══════════════════════════════════════════════════════════════════════════════════════════ //

isBackTest = input(false,       "Backtest On/Off"                                                  , group = "Backtest Framework")
dasCapital = input(1000.,       "Initial Capital"                                 , inline = "BT1" , group = "Backtest Framework")
lenBckTst  = input(1,           "Period (Year)", minval=0, step = .1              , inline = "BT1" , group = "Backtest Framework")
isStopLoss = input(false,       "Apply Stop Loss, with Stop Loss Set To %"        , inline = "BT2" , group = "Backtest Framework")
stopLoss   = input(1.,          "", step=.1, minval = 0                           , inline = "BT2" , group = "Backtest Framework") / 100
isBull     = input(false,       "Long : Candle Direction as Confirmation : Short" , inline = "BT3" , group = "Backtest Framework")
isBear     = input(false,       ""                                                , inline = "BT3" , group = "Backtest Framework")
isSudden   = input(true,        "Avoid Sudden Price Changes"                                       , group = "Backtest Framework")
isTest     = input(false,       "❗❗❗ Simulate Trade on Next Bar : Only For Test Purpose (REPAINTS)", group = "Backtest Framework")
lblInOutSL = input(true,        "Trade Entry/Exit Labels  Trade Statistics Label" , inline = "BT4" , group = "Backtest Framework")
lblTrdStat = input(true,        ""                                                , inline = "BT4" , group = "Backtest Framework")

// -Calculations ════════════════════════════════════════════════════════════════════════════════════ //

startBckTst  = time > timenow - lenBckTst * 31556952000 

var inTrade    = false
var entryPrice = 0. 
var exitPrice  = 0. 

if isBackTest

    var capital       = dasCapital
    var trades        = 0
    var win           = 0
    var loss          = 0
    
    bullCandle        = close > open
    bearCandle        = close < open
    stopLossTrigger   = crossunder(close, entryPrice * (1 - stopLoss))
    
    longCondition     = isTest ?
                          isBull ? 
                             isSudden ? 
                               longAlertCondition [1] and not shortAlertCondition    and bullCandle    : 
                               longAlertCondition [1] and bullCandle                                   : 
                             isSudden ? 
                               longAlertCondition [1] and not shortAlertCondition                      : 
                               longAlertCondition [1]                                                  :
                          isBull ? 
                             isSudden ? 
                               longAlertCondition [2] and not shortAlertCondition[1] and bullCandle[1] : 
                               longAlertCondition [2] and bullCandle[1]                                : 
                             isSudden ? 
                               longAlertCondition [2] and not shortAlertCondition[1]                   : 
                               longAlertCondition [1]

    shortCondition    = isTest ?
                          isBear ? 
                             isSudden ? 
                               shortAlertCondition[1] and not longAlertCondition     and bearCandle    : 
                               shortAlertCondition[1] and bearCandle                                   : 
                             isSudden ? 
                               shortAlertCondition[1] and not longAlertCondition                       : 
                               shortAlertCondition[1]                                                  :
                          isBear ? 
                             isSudden ? 
                               shortAlertCondition[2] and not longAlertCondition [1] and bearCandle[1] : 
                               shortAlertCondition[2] and bearCandle[1]                                : 
                             isSudden ? 
                               shortAlertCondition[2] and not longAlertCondition [1]                   : 
                               shortAlertCondition[1]

    stopLossCondition = isStopLoss ? inTrade and not shortCondition ? stopLossTrigger : 0 : 0

    if startBckTst and longCondition and not inTrade
        entryPrice   := open
        inTrade      := true
        trades       := trades + 1
    
        if lblInOutSL
            label longLabel = label.new(bar_index, low, text="L"
             ,tooltip="entry price  : " + tostring(entryPrice) + "\nentry value : " + tostring(capital, "#.##")
             ,color=color.green, style=label.style_label_up, textcolor=color.white, textalign=text.align_center, size=size.tiny)
    
        alert("long : probable trading opportunity, price " + tostring(close), alert.freq_once_per_bar)


    if (shortCondition or stopLossCondition) and inTrade
        exitPrice    := stopLossCondition ? close : open
        inTrade      := false
        capital      := capital * (exitPrice / entryPrice)

        if exitPrice > entryPrice
            win      := win  + 1
        else
            loss     := loss + 1
    
        if lblInOutSL
            text = stopLossCondition ? "SL" : "TP"
            label shortLabel = label.new(bar_index, high, text = text
                 ,tooltip="change .......... : " + tostring((exitPrice / entryPrice - 1) * 100, "#.##") + "%\nentry/exit price : " + tostring(entryPrice) + " / " + tostring(exitPrice) + "\nnew capital ..... : " + tostring(capital, "#.##")
                 ,color=color.red, style=label.style_label_down, textcolor=color.white, textalign=text.align_center, size=size.tiny)

        alert("short : probable trading opportunity, price " + tostring(close), alert.freq_once_per_bar)

    
    var label wLabel = na
    
    if not inTrade and longAlertCondition[1] and not shortAlertCondition
        wLabel := label.new(bar_index, low, text="⚠️"
         ,tooltip="probable long trading opportunity \nawaiting confirmation (next candle)\nif confirmed, backtest tool will execute trade with open price of the canlde"
         ,color=color.green, style=label.style_none, textcolor=color.white, textalign=text.align_center, size=size.huge)
        label.delete(wLabel[1])
        
        alert("long : early warning : probable trading opportunity, awaiting confirmation (next candle), price " + tostring(close), alert.freq_once_per_bar)

    if inTrade and shortAlertCondition[1] and not longAlertCondition
        wLabel := label.new(bar_index, high, text="⚠️"
         ,tooltip="probable short/take profit trading opportunity \nawaiting confirmation (next candle)\nif confirmed, backtest tool will execute trade with open price of the canlde"
         ,color=color.green, style=label.style_none, textcolor=color.white, textalign=text.align_center, size=size.huge)
        label.delete(wLabel[1])
        
        alert("short : early warning : probable trading opportunity, awaiting confirmation (next candle), price " + tostring(close), alert.freq_once_per_bar)

    if change(time)
        label.delete(wLabel[1])
        
    if stopLossCondition
        alert("stop loss condition, price " + tostring(close), alert.freq_once_per_bar)
    
    
    if lblTrdStat
        var years         = (timenow - time) / 31556952000

        var yearsTxt      = ""
        var remarks       = ""

        if years < lenBckTst
            lenBckTst    := years
            yearsTxt     := tostring(lenBckTst, "#.##") + " Years***"
            remarks      := "\n\n*longs only\n**final value, if trade active displays estimated final value\n***max available data for selected timeframe : # of bars - " + tostring(bar_index)
        else
            yearsTxt     := tostring(lenBckTst, "#.##") + " Year(s)"
            remarks      := "\n\n*longs only\n**final value - if in trade, displays estimated final value"

        inTradeTxt        = inTrade ? "inTrade" : "not inTrade"
        estimated         = inTrade ? capital * (close / entryPrice) : capital
        entryTxt          = inTrade ? tostring(entryPrice) : "not inTrade"
        lastTrdTxt        = inTrade ? ", Gain/Loss " + tostring((estimated/capital - 1) * 100, "#.##") + "%, Stop Loss " + tostring(isStopLoss ? entryPrice * (1 - stopLoss) : na) : ""
        stopLossTxt       = isStopLoss ? "if last value falls by " + tostring(stopLoss * 100) + "% of entry price" : "not applied"
    
        tooltipTxt        = "entires/exit caclulations\n" + 
                             "-long entry , on next bar when arrows below bar pointing up\n" +
                             "-take profit, on next bar when arrows above bar pointing down\n" +
                             "-stop loss " + stopLossTxt + remarks

        label indiLabel   = label.new(time, close 
             ,text="☼☾ Trade Statistics*, Trade Period - " + yearsTxt +
              "\n═════════════════════════════════════" +
              "\nSuccess Ratio ...... : " + tostring((win/trades)*100, "#") + "%" + ", # of Trades - " + tostring(trades) + ", Win/Loss - " + tostring(win) + "/" + tostring(loss) +
              "\nGain/Loss % ........ : " + tostring((estimated/dasCapital - 1) * 100, "#") + "%" + ", Initial/Final Value** - " + tostring(dasCapital) + " / " + tostring(estimated, "#") +
              "\n\nCurrent TradeStatus - " + inTradeTxt + lastTrdTxt +
              "\n═════════════════════════════════════" +
              "\nEntry Price/Value . : " + entryTxt + " / " + tostring(capital, "#.##") + " " + inTradeTxt +
              "\nLast Price/Value ... : " + tostring(close) + " / " + tostring(estimated , "#.##") + " " + inTradeTxt
             ,tooltip=tooltipTxt
             ,color=inTrade ? estimated/dasCapital > 1 ? color.teal : color.maroon : color.gray, xloc=xloc.bar_time, style=label.style_label_left, textcolor=color.white, textalign=text.align_left)

        label.set_x(indiLabel, label.get_x(indiLabel) + round(change(time) * 5))
        label.delete(indiLabel[1])

// -Plotting ════════════════════════════════════════════════════════════════════════════════════ //

bgcolor(isBackTest and startBckTst and startBckTst != startBckTst[1] ? color.blue : na)
plot(inTrade ? entryPrice : exitPrice > 0 ? exitPrice : na, title="Entry/Exit Price Line", color=inTrade ? color.green : color.red, style = plot.style_circles)