ATRStopLossFinder
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt

//@version=5
//@description Average True Range Stop Loss Finder
// credits to https://www.tradingview.com/u/shayankm/ for the initial version
library (title="ATRStopLossFinder", overlay=true)


ma_function(source, length, smoothing) =>
	if smoothing == "RMA"
		ta.rma(source, length)
	else
		if smoothing == "SMA"
			ta.sma(source, length)
		else
			if smoothing == "EMA"
				ta.ema(source, length)
			else
				ta.wma(source, length)



// ATR
//@function
//Returns the ATR
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export atr(simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) => 

    tr = math.max(refHigh - refLow, math.abs(refHigh - refClose[1]), math.abs(refLow - refClose[1]))
    atr =  ma_function(tr, length, smoothing) * multiplier
    atr // return

// ATR (Ticks)
//@function
//Returns the ATR
//@param tickValue simple float tick value (use getTickValueSymbol)
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export atrTicks(series float tickValue, simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) => 

    atrTicks = atr(length, smoothing, multiplier, refHigh, refLow, refClose) / tickValue
    atrTicks // return
    

// Stop Loss Finder
//@function
//Returns the stop losses for an entry on this candle, depending on the ATR
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossLong, series float stopLossShort, series float atr
export stopLossFinder(simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) => 

    atr =  atr(length, smoothing, multiplier, refHigh, refLow, refClose)
    stopLossShort = atr + refHigh
    stopLossLong = refLow - atr
    
    [stopLossLong, stopLossShort, atr]
    

// Stop Loss Finder (Ticks)
//@function
//Returns the stop losses for an entry on this candle in ticks, depending on the ATR
//@param tickValue simple float tick value (use getTickValueSymbol)
//@param length simple int optional to select the lookback amount of candles
//@param smoothing string optional to select the averaging method, options=["RMA", "SMA", "EMA", "WMA"]
//@param multiplier simple float optional if you want to tweak the speed the trend changes.
//@param refHigh series float optional if you want to use another timeframe or symbol, pass it's 'high' series here
//@param refLow series float optional if you want to use another timeframe or symbol, pass it's 'low' series here
//@param refClose series float optional if you want to use another timeframe or symbol, pass it's 'close' series here
//@returns series float stopLossTicks
export stopLossTicks(series float tickValue, simple int length = 14, string smoothing = "RMA", simple float multiplier = 1.5, series float refHigh = high, series float refLow = low, series float refClose = close) => 
    
    atrTicks = atrTicks(tickValue , length, smoothing, multiplier, refHigh, refLow, refClose) 
    stopLossTicksShort = (refHigh - refClose) / tickValue + atrTicks // assuming opening positions from last close value, so we need to add the difference to high
    stopLossTicksLong =  (refClose - refLow) / tickValue + atrTicks // assuming opening positions from last close value, so we need to add the difference to low
    
    [stopLossTicksLong, stopLossTicksShort, atrTicks]
    


length = input.int(title="Length", defval=14, minval=1)
smoothing = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
m = input.float(1.5, "Multiplier")
src1 = input.source(high,"Source high")
src2 = input.source(low,"Source low")
src3 = input.source(close,"Source close")
pline = input.bool(true, "Show Price Lines")
col1 = input.color(color.blue, "ATR Text Color")
col2 = input.color(color.teal, "Low Text Color",inline ="1")
col3 = input.color(color.red, "High Text Color",inline ="2")

collong = input.color(color.teal, "Low Line Color",inline ="1")
colshort = input.color(color.red, "High Line Color",inline ="2")

// GetTickValueSymbol() returns the tick value (currency value of
// smallest possible price change) for the specified instrument,
// loaded with 'security' in a non-repainting manner.
getTickValueSymbol(simple string symbol) =>
    request.security(symbol, "D", (syminfo.mintick * syminfo.pointvalue)[1],lookahead=barmerge.lookahead_on)


// data
[stopLossLong, stopLossShort, atr] = stopLossFinder(length, smoothing, m, src1, src2, src3)
tickValue = getTickValueSymbol(syminfo.tickerid)
[stopLossTicksLong, stopLossTicksShort, atrTicks] = stopLossTicks(tickValue, length, smoothing, m, src1, src2, src3)

refSymbol = input.symbol("BINANCEUS:BTCUSD", "symbol", group="Reference")
refPeriod = input.timeframe('60', "timeframe", group = "Reference", options=['1','5','15','60','240','1440']) // timeframe.period //15'
[refHigh, refLow, refClose] = request.security(refSymbol, refPeriod, [high, low, close])
[stopLossLongRef, stopLossShortRef, atrRef] = stopLossFinder(length, smoothing, m, refHigh, refLow, refClose)
tickValueRef = getTickValueSymbol(refSymbol)
[stopLossTicksRefLong, stopLossTicksRefShort, atrTicksRef] = stopLossTicks(tickValueRef, length, smoothing, m, refHigh, refLow, refClose)

// plotting
p1 = plot(stopLossShort, title = "ATR Short Stop Loss", color= color.new(colshort, transp = 20), trackprice = pline ? true : false)
p2 = plot(stopLossLong, title = "ATR Long Stop Loss", color= color.new(collong, transp = 20), trackprice = pline ? true : false)
pTicks = plot(atrTicks * tickValue, title = "stop loss ticks", color = color.teal, style = plot.style_cross)
p1Ticks = plot(close - stopLossTicksLong * tickValue, title = "stop loss long ticks", color = color.olive, style = plot.style_cross)
p2Ticks = plot(close + stopLossTicksShort * tickValue, title = "stop loss short ticks", color = color.fuchsia, style = plot.style_cross)

p1Ref = plot(stopLossShortRef, title = "ref ATR Short Stop Loss", color= color.new(colshort, transp = 50), trackprice = pline ? true : false)
p2Ref = plot(stopLossLongRef, title = "ref ATR Long Stop Loss", color= color.new(collong, transp = 50), trackprice = pline ? true : false)



// table of values
var table Table = table.new(position.bottom_center, 7, 2, border_width = 3)    

f_fillCell(_table, _column, _row, _value, _timeframe) =>
	_cellText = _timeframe+ str.tostring(_value, "#.##")
    table.cell(_table, _column, _row, _cellText, text_color = col1)
    
if barstate.islast
    // original
    table.cell(Table, 0, 0, "symbol: " + syminfo.tickerid  + " - " + timeframe.period + "min")
    f_fillCell(Table, 1, 0, atr, "ATR: " )
    f_fillCell(Table, 2, 0, stopLossShort, "H: " )
    f_fillCell(Table, 3, 0, stopLossTicksShort, "sl short ticks: " )   
    f_fillCell(Table, 4, 0, stopLossLong, "L: " )   
    f_fillCell(Table, 5, 0, stopLossTicksLong, "sl long ticks: " )   
    f_fillCell(Table, 6, 0, tickValue, "tick value: " )   
    // ref
    table.cell(Table, 0, 1, "ref : " + refSymbol + " - " + refPeriod + "min")
    f_fillCell(Table, 1, 1, atrRef, "ATR: " )
    f_fillCell(Table, 2, 1, stopLossShortRef, "H: " )
    f_fillCell(Table, 3, 1, stopLossTicksRefShort, "sl short ticks: " )   
    f_fillCell(Table, 4, 1, stopLossLongRef, "L: " )   
    f_fillCell(Table, 5, 1, stopLossTicksRefLong, "sl long ticks: " )    
    f_fillCell(Table, 6, 1, tickValueRef, "tick value: " )   
    
    table.cell_set_text_color(Table, 2, 0, color.new(col3, transp = 0))
    table.cell_set_text_color(Table, 3, 0, color.new(col3, transp = 0))
    table.cell_set_text_color(Table, 4, 0, color.new(col2, transp = 0))
    table.cell_set_text_color(Table, 5, 0, color.new(col2, transp = 0))
    table.cell_set_text_color(Table, 2, 1, color.new(col3, transp = 0))
    table.cell_set_text_color(Table, 3, 1, color.new(col3, transp = 0))
    table.cell_set_text_color(Table, 4, 1, color.new(col2, transp = 0))
    table.cell_set_text_color(Table, 5, 1, color.new(col2, transp = 0))
    