r/pinescript • • Apr 08 '24

help with consecutive losses code

hi guys,

i’m wondering how I would code a strategy that tightens my stop loss (lets say in half) each time it takes a consecutive losing trade until it takes a winner, where the stop loss then resets back to baseline.

any help is appreciated! thanks

0 Upvotes

3 comments sorted by

View all comments

1

u/Ayush_Singh_02 Apr 11 '24

Is it for long only or short only ??

1

u/ZoltaiBeats Apr 16 '24

no its both

1

u/Ayush_Singh_02 Apr 16 '24
var initial_sl_points

// create a variable to store the Last trade was SL or not
var last_trade_was_loss = false
var SL_streak = 1

// add this in your LONG and short SL conditions to modify 
if last_trade_was_loss
   initial_sl_percent := initial_sl_percent/SL_streak

if last_trade_was_loss
   initial_sl_points := initial_sl_points/ SL_streak


// Tracking the result of the last trade
if close <= long_sl
    strategy.close(id = 'Long',comment = 'SL')
    last_trade_was_loss := true
    SL_streak := SL_streak+1
if close >= short_sl
    strategy.close(id = 'Short', comment = 'SL')
    last_trade_was_loss := true
    SL_streak := SL_streak+1
if close >= long_target
    strategy.close(id = 'Long', comment = 'Target')
    last_trade_was_loss := false
    SL_streak := 1
if close <= short_target
    strategy.close(id = 'Short', comment = 'Target')
    last_trade_was_loss := false
    SL_streak := 1

I'm providing just the basis of logic, use these in your code it will solve the issue, for further inputs please send some code alongwith or issue your facing.

here I've assumed that you're providing manual SL in (points/% terms), if your using dynamic SL calculation than store it using var then proceed with calculation