"Pine Script OCA groups: one-cancels-all orders in strategies"
How oca_name and oca_type work in Pine Script strategies, with a working breakout example where one fill cancels the other order, and the difference between cancel and reduce.
An OCA group ("one cancels all") links pending orders so that when one fills, the others in the group are cancelled or reduced. In Pine Script you set it with oca_name and oca_type on strategy.entry() and strategy.order(). SuperCharting's strategy tester runs OCA groups as tradingview.com does.
The three OCA types
oca_type | When one order of the group fills |
|---|---|
strategy.oca.cancel | Every other order of the group is cancelled. |
strategy.oca.reduce | The other orders are reduced by the filled quantity, and cancelled when nothing is left. |
strategy.oca.none | Nothing happens to the others (the default). |
A working example: a breakout in either direction
//@version=6
strategy("Range breakout OCA", overlay = true)
hi = ta.highest(high, 20)[1]
lo = ta.lowest(low, 20)[1]
if strategy.position_size == 0
strategy.entry("Long", strategy.long, stop = hi, oca_name = "breakout", oca_type = strategy.oca.cancel)
strategy.entry("Short", strategy.short, stop = lo, oca_name = "breakout", oca_type = strategy.oca.cancel)
strategy.exit("Long exit", "Long", profit = 400, loss = 200)
strategy.exit("Short exit", "Short", profit = 400, loss = 200)
Two stop orders wait above and below the 20-bar range. When the price breaks one side, that order fills and the other is cancelled, so the strategy never ends up long and short from the same range.
How it behaves
- The group is by name. Orders with the same
oca_nameform one group, whatever their direction. - Fills inside one bar follow the bar's path. If both levels are inside the same bar, the one the price reaches first along the bar fills, as on tradingview.com.
strategy.exit()legs are an OCA group of their own. The profit and loss legs of one exit cancel each other without anyoca_name.- Exit comments:
strategy.exit()takescomment_profit,comment_lossandcomment_trailing. The List of Trades shows the comment of the leg that filled.
How to try it
- Open a chart, for example
NSE:NIFTYon the 15m interval. - Open the Pine Editor, paste the example and click Add to chart.
- Open the Strategy Tester to see the trades. No trade opens on both sides of the same range.
For limits on drawdown, losses and position size, see the strategy risk guide.
Frequently asked questions
What is the difference between oca.cancel and oca.reduce?
cancel removes the other orders when one fills. reduce lowers their quantity by the filled amount, which suits scaling out of a position with several targets.
Does OCA work with strategy.close?
No. strategy.close() is a market order and takes no OCA group. Use OCA on strategy.entry() and strategy.order().