Search code examples
pine-scripttrading

Complete trade and ignoring any new signals MTF


I've been trying for the build backtest strategy. How can i complete this trade and ignoring any new signals?

This my code based on MTF

long = pos(cond1) == 1 and pos(cond2) == 1
short = pos(cond1) == 0 and pos(cond2) == 0

//////////////////////////////////////////////////////////////////////////////////////////////////

var S_sell = false
var S_buy = false

// Defines Trade Signals
buy = long and not S_sell
sell = short and not S_buy

// turning switches off/on after signal is generated 
if buy
    S_sell := true
    S_buy := false

if sell
    S_sell := false
    S_buy := true


if buy
    strategy.entry('Long Entry', strategy.long)

if sell
    strategy.entry('Short Entry', strategy.short)

///////////////////////////////////////////////////////////////

Long_Entry := buy ? close : Long_Entry[1]
Long_StopLoss := buy ? close - Long_Stop_atr : Long_StopLoss[1]
Long_TakeProfit := buy ? close + Long_Profit_atr : Long_TakeProfit[1]

Short_Entry := sell ? close : Short_Entry[1]
Short_StopLoss := sell ? close + Short_Stop_atr : Short_StopLoss[1]
Short_TakeProfit := sell ? close - Short_Profit_atr : Short_TakeProfit[1]

strategy.exit('Close', 'Long Entry', stop=Long_StopLoss, limit=Long_TakeProfit)
strategy.exit('Close', 'Short Entry', stop=Short_StopLoss, limit=Short_TakeProfit)

longEntry = strategy.position_size <= 0
shortEntry = strategy.position_size >= 0

My bakctest strategy looks like this: enter image description here


Solution

  • You can check your position size when a new signal is given and make sure you are not in a trade if you wish for a trade to finish before taking a new one.

    if buy and strategy.position_size == 0 
        strategy.entry('Long Entry', strategy.long)
    
    if sell and strategy.position_size == 0 
        strategy.entry('Short Entry', strategy.short)