SPX ES Spread
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mrmccraig

//@version=5
indicator("SPX ES Spread", overlay=true)

ESticker = input.string("ES1!", "ES Symbol")
SPXticker = input.string("SPX", "SPX Symbol")
theSource = input.source(close, "Source")
calcMethod = input.string("Source", "Calculation Method", options=["Source", "MA"], tooltip="If 'source' is selected, the difference in the two indices is simply the difference of the two. If 'MA' is selected, a moving average is used.")
maType = input.string("SMA", "MA Type", options=["SMA", "EMA"])
maLen = input.int(21, "MA Length", minval=1)
precision = input.int(1, "Precision", tooltip="How many decimal places the spread will be rounded to.")
tableBGColor = input.color(color.gray, "Table Background")
tableText = input.color(color.white, "Table text, frame")
tablePosition = input.string("Top Right", "Table Position", options=["Top Right", "Top Center", "Top Left"])

// check if we're on either ES chart or SPX chart

symbolCheck = syminfo.ticker == SPXticker ? "SPX" : syminfo.ticker == ESticker ? "ES" : na

otherSymbolValue = 0.00
spreadValue = 0.00

otherSymbolValue := request.security(symbolCheck == "SPX" ? ESticker : SPXticker, timeframe.period, theSource)

if symbolCheck == "SPX" or symbolCheck == "ES"
    spreadValue := calcMethod == "Source" ? otherSymbolValue - theSource : maType == "SMA" ? ta.sma(otherSymbolValue - theSource, maLen) : ta.ema(otherSymbolValue - theSource, maLen)
    spreadValue := math.round(spreadValue, precision)

showTable = not na(symbolCheck)

tablePos = switch (tablePosition)
    "Top Right" => position.top_right
    "Top Center" => position.top_center
    "Top Right" => position.top_left

spreadTable = showTable ? table.new(tablePos, 2, 2, bgcolor=tableBGColor, frame_color=tableText, frame_width=1, border_color=tableText, border_width=1) : na

if barstate.islast and not na(symbolCheck)
    table.cell(spreadTable, 0, 0, text=symbolCheck == "SPX" ? ESticker : symbolCheck == "ES" ? SPXticker : "", text_color=tableText)
    table.cell(spreadTable, 1, 0, text=str.tostring(otherSymbolValue), text_color=tableText)
    table.cell(spreadTable, 0, 1, text="Spread", text_color=tableText)
    table.cell(spreadTable, 1, 1, text=str.tostring(spreadValue), text_color=tableText)
