Search code examples
pine-scriptinverse

Inverse pair in Pine script


I am aware of the alt+I inverse scale function in Tradingview. How do I apply an inverse function within a Pine script, instead of loading e.g. an inverse pair as done in the MWE below?

//@version=4
study(title="", overlay=false)

timeperiod = "1"

v1 = security("FX_IDC:CADAUD", timeframe.period, close)

lengthFast = input(3,  minval = 0, title = "Fast MA on RSI")
rFast = rsi(v1, lengthFast)
fastMA1  = sma(rFast, lengthFast) 

plot(fastMA, "Fast MA", color=color.red, linewidth=1)

Solution

  • If you actually need to call the symbol itself it can be done like this, however there isn't a way to validate if the symbol is an actual valid symbol or not.

    //@version=4
    study("Inverse Ticker", overlay = true)
    
    var string ticker = syminfo.prefix + ":" + syminfo.currency + syminfo.basecurrency
    
    inv_close = security(ticker, timeframe.period, close)
    
    plot(inv_close)
    

    Otherwise you can just use 1 / close

    eg for AUDCAD where y equals the current close price

    1 x AUD = y x CAD

    (1 x AUD) / y = (y x CAD) / y

    (1 x AUD) / y = 1 x CAD

    = 1 / y

    For inverted candles :

    //@version=4
    study("Inverse", overlay = false)
    
    o = 1 / open
    h = 1 / high
    l = 1 / low
    c = 1 / close
    
    plotcandle(open = o, high = h, low = l, close = c, title = "Inverse pair", color = c >= o ? color.green : color.red, wickcolor = color.gray)