Search code examples
pine-scriptpine-script-v5

Get indicator with trade entry value - Pine Script


I want to set stop loss of 2ATR at moment of trade entry. With Pine Script I set stop loss of 2ATR, however not at moment of trade entry, but Pine Script updates ATR value to last closed candle.Preferred verion is v4 are v5 of PS.

Thanks

atr = atr(14)

if EntryShortCondiction1 and EntryShortCondiction2
    strategy.entry("Short", false, 100)
    
ShortStop = (strategy.position_avg_price + atr*2)
ShortProfit = (strategy.position_avg_price - atr*2)

if strategy.position_size<0
    strategy.exit(id = "Short", stop=ShortStop, limit=ShortProfit)

Solution

  • You can use the strategy.opentrades.entry_price variable to get the entry price.

    Here is an example:

    //@version=5
    strategy("My strategy", overlay=true, margin_long=100, margin_short=100)
    
    _atr = ta.atr(14)
    
    longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
    
    if (longCondition)
        strategy.entry("Long", strategy.long)
    
    lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
    
    var float tp = na
    var float sl = na
    
    if (strategy.position_size[1] != strategy.position_size)
        tp := lastEntryPrice + (_atr * 2)
        sl := lastEntryPrice - (_atr * 2)
    
    inTrade = strategy.position_size > 0
    
    plot(inTrade ? tp : na, color=color.green, style=plot.style_circles)
    plot(inTrade ? sl : na, color=color.red, style=plot.style_circles)
    plot(lastEntryPrice)
    
    strategy.exit("Short", "Long", stop=sl, limit=tp)
    

    enter image description here

    So, entry price is 55334,19, atr at that moment is 2725,88. Take profit = 55334,19 + (2 * 2725,88) = 60785,95 which seems to be correct.