Benster
Benster

Reputation: 91

pine-script how to know if last trade was a stop loss, wait n bars to open a new trade, how to reference id of last trade

I have a trailing stop in Pine Script code. I would like to the strategy to wait for n bars before being able to open a new trade if the last trade was a stop loss. n could be an input. The best way would be to check what the id of last trade. If the id matches that of trade which would have been a stop, I can start counting bars. How do I reference the id of the last trade? Thanks

Upvotes: 1

Views: 4716

Answers (2)

Savva
Savva

Reputation: 66

I believe the following might work for you. With each script iteration you can check if current bar's losstrades series variable has increased since the previous bar, hence letting you know that the last trade was a loss, and vice versa.

As far as getting an id of the last trade, you can track them and store them in var when you place a trade, to access at a later iteration.

//@version=4
strategy("Bars after loss", overlay=true)

var lastTradeId = "somerandomid"
var lastTradeWasLoss = false
barsWait = 5 // our N

if (strategy.losstrades[0] > strategy.losstrades[1])
    // last trade was a loss
    lastTradeWasLoss := true
    
if (strategy.wintrades[0] > strategy.wintrades[1])
    // successful trade, reset
    lastTradeWasLoss := false

// Check if strategy has no open position
isFlat = (strategy.position_size == 0)

// Check if strategy had no open position for more than N bars
if (isFlat and lastTradeWasLoss and barssince(ifFlat) > barsWait)
    // it's been more than N bars since last position was flat
    
    // store last trade id for later use
    lastTradeId := "somethingotherrandom"
    
    // execute trade
    strategy.entry(id=lastTradeId, ...)

Upvotes: 0

PineCoders-LucF
PineCoders-LucF

Reputation: 8799

There's no mechanism to reference past trades by id. You can use something like this to calculate bars since the last loss, and test on that:

lastTradeResult = change(strategy.netprofit)
barsSinceLastLoss = barssince(lastTradeResult < 0)

Upvotes: 3

Related Questions