Open, Open +/- EMA ATR Lines with Labels
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AOSSA_Traders

//@version=5
indicator("Open, Open +/- EMA ATR Lines with Labels", shorttitle="O, O+/-EMA ATR Lines", overlay=true)

timeframeInput = input.string(defval="D", title="Timeframe", options=["1", "5", "15", "30", "60", "240", "D", "W", "M"])
atrLength = input.int(14, title="ATR Length")

openFromTF = request.security(syminfo.tickerid, timeframeInput, open)
highFromTF = request.security(syminfo.tickerid, timeframeInput, high)
lowFromTF = request.security(syminfo.tickerid, timeframeInput, low)
closeFromTF = request.security(syminfo.tickerid, timeframeInput, close)

isNotFirstBar = not na(closeFromTF[1])
trueRange = isNotFirstBar ? math.max(highFromTF - lowFromTF, math.abs(highFromTF - closeFromTF[1]), math.abs(lowFromTF - closeFromTF[1])) : highFromTF - lowFromTF
emaATR = ta.ema(trueRange, atrLength)

upper = openFromTF + emaATR
lower = openFromTF - emaATR

calculatePips(value) =>
    pips = math.round((value - openFromTF) * 10000)
    pips

formatNumber(value) =>
    str.tostring(math.floor(value * 100000) / 100000)

var line upperLine = line.new(x1=bar_index - 100, y1=upper, x2=bar_index, y2=upper, color=color.blue, width=2)
var line lowerLine = line.new(x1=bar_index - 100, y1=lower, x2=bar_index, y2=lower, color=color.blue, width=2)
var line openLine = line.new(x1=bar_index - 100, y1=openFromTF, x2=bar_index, y2=openFromTF, color=color.green, width=1)

var label upperLabel = label.new(x=bar_index, y=upper, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)
var label lowerLabel = label.new(x=bar_index, y=lower, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)
var label openLabel = label.new(x=bar_index, y=openFromTF, text="", color=color.black, xloc=xloc.bar_index, yloc=yloc.price, size=size.normal, textcolor = color.white)

line.set_xy1(upperLine, bar_index - 100, upper)
line.set_xy2(upperLine, bar_index +10, upper)
label.set_xy(upperLabel, bar_index +10, upper)
label.set_text(upperLabel, formatNumber(upper) + " (" + str.tostring(calculatePips(upper)) + " pips)")

line.set_xy1(lowerLine, bar_index - 100, lower)
line.set_xy2(lowerLine, bar_index +10, lower)
label.set_xy(lowerLabel, bar_index +10, lower)
label.set_text(lowerLabel, formatNumber(lower) + " (" + str.tostring(calculatePips(lower)) + " pips)")

line.set_xy1(openLine, bar_index - 100, openFromTF)
line.set_xy2(openLine, bar_index +10, openFromTF)
label.set_xy(openLabel, bar_index +10, openFromTF)
label.set_text(openLabel, formatNumber(openFromTF))
