Search code examples
pine-scriptpine-script-v5pine-script-v4

Pine-script How to calculate on close when calc_on_every_tick=true


var line _lpLine = line.new(0, 0, 0, 0, extend=extend.left, style=line.style_dashed, color=color.yellow)

_lastTradedPrice = close
line.set_xy1(_lpLine, bar_index-1, _lastTradedPrice)
line.set_xy2(_lpLine, bar_index, _lastTradedPrice)

The code above plots the Last Price Line/ creates a line for the last traded price. It works perfectly in an indicator script but doesn't in a strategy script because by default calc_on_every_tick is set to false.

If I set calc_on_every_tick to true, the Last Price Line will now work perfectly in the strategy but now I'm faced with another problem. The script will now enter trades while the bar is still forming and not when only after it has closed. How do I solve this predicament?


Solution

  • You can delay your order signal by 1 candle, so it will match the calc_on_every_tick = false behavior, as is shown below with the default strategy:

    //@version=4
    strategy("My Strategy", overlay=true, margin_long=100, margin_short=100, calc_on_every_tick = true)
    
    longCondition = crossover(sma(close, 14), sma(close, 28))
    if nz(longCondition[1]) // signal 1 candle delayed 
        strategy.entry("My Long Entry Id", strategy.long)
    
    shortCondition = crossunder(sma(close, 14), sma(close, 28))
    if nz(shortCondition[1]) // signal 1 candle delayed 
        strategy.entry("My Short Entry Id", strategy.short)