krau
krau

Reputation: 11

How can I have an entry order expire after a set # of bars? (Pine script)

I'm working on creating and backtesting a TradingView strat with ver. 3 pine. I'm new and not great at coding so bear with me. I'd like to have my strategy.entry() limit order expire after 1 bar if it doesn't fill, and I'm having a hard time understanding how to do so with the built-in var "time".

I've figured out how to confirm if there's an existing order that isn't filled yet using two facts:

I can't seem to figure out the time passed part. Ideally, if the first 2 are true and time passed since my entry is greater than bar time length (let's say a 5m bar), then I'd have an accessible true/false to use for cancelling pending entries if 5 minutes have passed since entry.

Upvotes: 1

Views: 2300

Answers (2)

sammy22
sammy22

Reputation: 40

you can use the "ta.barssince" with the order placed conditions

abort_trade = ta.barssince(entry_condition)>5 and strategy.position_size ==0
strategy.cancel_all(abort_trade)

the first line is to make sure that more than 5 bars" for example" have passed since the entry condition .. and at the same time we are not in a position yet .. and in the second line we tell the script to cancel if that happens. also you can use

strategy.cancel("id", when = abort_trade)

this is for @v5 btw .. hope it helped and good luck

Upvotes: 1

Avram Tudor
Avram Tudor

Reputation: 1526

This is in v4 so I'm not sure how well it translates to v3

shouldPlaceOrder = // your enter condition
barsSincePlacingOrder = barssince(shouldPlaceOrder)
shouldCancelOrder = barsSincePlacingOrder == 1 and strategy.position_size == 0

strategy.entry(id, strategy.long, quantity = 1, when = shouldPlaceOrder)
strategy.exit(id, loss = 10, profit = 20)
strategy.cancel(id, when = shouldCancelOrder)

Upvotes: 0

Related Questions