How can i add a fuction to stop my pine code strategy after "x" losses in a row (martingale sistem)

Viewed 36

I am triyng to build a strategy on tradingview which i want to automate after but i am stuck to 2 functions...

Inside the strategy is a simple buy after a red candle close(for close to 50% win rate) 1:1 risk ration reward, the thing is that the backtesting show a loss for a long period of time because it can catch 7 or 8 lossing trades in a row and blow up my account...

So i want to stop the strategy after EX: 7 losses in a row and start again after with multiplier 1 and double after as usual, but to stop after it lost the "x" loss in a row.

The 2nd thing it would be to enter a trade after 2 losses in a row, so in this way i could start after some losses and same here after "x" losses in a row Stop strategy and restart it.

I hope i explained as clear as possible...

I couldn't find anything about this 2 functions, i have to mention that i am new to pine code but still i manage to build this strategy after watching multiple startegys code...some code is barrowed.

Here is my full code :

//@version=5

strategy(title='Test martingale', overlay=true, slippage=15, initial_capital=1000, currency=currency.USD)

maxWinStreak = input.int(title="Max Winning Streak Length",
     defval=7, minval=1)

newWin = (strategy.wintrades > strategy.wintrades[1]) and
     (strategy.losstrades == strategy.losstrades[1]) and
     (strategy.eventrades == strategy.eventrades[1])

// loss steak

maxLossStreak = input.int(title="Max Losing Streak Length",
     defval=7, minval=1)

newLoss = (strategy.losstrades > strategy.losstrades[1]) and
     (strategy.wintrades == strategy.wintrades[1]) and
     (strategy.eventrades == strategy.eventrades[1])



// Figure out current winning streak length
streakLen = 0

streakLen := if (newWin)
    nz(streakLen[1]) + 1
else
    if (strategy.losstrades > strategy.losstrades[1]) or
         (strategy.eventrades > strategy.eventrades[1])
        0
    else
        nz(streakLen[1])


// Figure out current lossing streak length
streakLen2 = 0

streakLen2 := if (newLoss)
    nz(streakLen2[1]) + 1
else
    if (strategy.wintrades > strategy.wintrades[1]) or
         (strategy.eventrades > strategy.eventrades[1])
        0
    else
        nz(streakLen2[1])
//Max lossing streak        
okToTrade1 = streakLen2 < maxLossStreak
//Max winning streak
okToTrade = streakLen < maxWinStreak 
src = close
long = close  < open  
win_mult = input.float(defval=1.00, step=0.05, title='Multiplier for Winning Streak')
loss_mult = input.float(defval=2, step=0.05, title='Multiplier for Losing Streak')
//Just hedge the last trade 
dir = 0.0

//Count the current streak of winning/losing trades
calcWinMult(mult) =>
    result = 0.0
    change_1 = ta.change(strategy.losstrades)
    change_2 = ta.change(strategy.wintrades)
    change_3 = ta.change(strategy.eventrades)
    result := na(result[1]) ? 1 : change_1 > 0 ? 1 : change_2 > 0 or change_3 > 0 ? nz(result[1]) * mult : nz(result[1])
    result
calcLossMult(mult) =>
    result = 0.0
    change_1 = ta.change(strategy.wintrades)
    change_2 = ta.change(strategy.losstrades)
    change_3 = ta.change(strategy.eventrades)
    result := na(result[1]) ? 1 : change_1 > 0 ? 1 : change_2 > 0 or change_3 > 0 ? nz(result[1]) * mult : nz(result[1])
    result

//Gett the type of trade we need
type = 0.0
change_1 = ta.change(strategy.losstrades)
type := ta.change(strategy.wintrades) > 0 ? 1 : change_1 > 0 ? -1 : nz(type[1], 1)

//Get the martingale multiplier for the nex trade
calcWinMult__1 = calcWinMult(win_mult)
calcLossMult__1 = calcLossMult(loss_mult)
qtyMult = type > 0 ? calcWinMult__1 : calcLossMult__1

//Basic buy/sell signals
buy = long
//Plot
red = color.red
green = color.lime
white = color.white
plotshape(long, text='buy', style=shape.labelup, location=location.belowbar, 
color=color.new(green, 0), textcolor=color.new(white, 0))

lots = input(defval=1)
adjustedLots = 1 * qtyMult


if  strategy.equity > strategy.initial_capital * 0.2 and strategy.closedtrades +  strategy.opentrades < 5000 and okToTrade and okToTrade1
      strategy.entry('LONG', strategy.long, qty=adjustedLots, when=buy)
   
      strategy.exit('L.exit', from_entry='LONG', profit= 200, loss=200)  

Thank you in advance for your help.

1 Answers

Here is the helper function calculates number of losses in a row. You can use it in your script for detect is the strategy can trade or not.

//@version=5
strategy("My strategy", overlay=true, margin_long=100, margin_short=100)

numberOfLossesInRow()=>
    result = 0
    if 0 != strategy.closedtrades        
        for i = strategy.closedtrades - 1 to 0
            if strategy.closedtrades.profit(i) < 0
                result += 1
            else
                break
    result

lossesInRow = numberOfLossesInRow()
plot(lossesInRow)

canTrade = lossesInRow < 5
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition and canTrade)
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition and canTrade)
    strategy.entry("My Short Entry Id", strategy.short)
Related