My stop-loss order is getting executed when it shouldn't
-
Hi. This is a big program, I have been using it for a long time, but yesterday I discovered a problem and it's driving me crazy.
I am back-testing using Forex 5M data.
I open a BUY market order on 7/24 at 14:00.
The order Completes (opening the order) in the next bar at 14:05 at price 1.11351.
I open a stop-loss order below my executed BUY price:self.sell( exectype=bt.Order.Stop, price=1.11194, size=self.order_size )
and a take-profit order above my executed price:
self.sell( exectype=bt.Order.Limit, price=1.11520, size=self.order_size )
Many bars go by that don't have lows below my SL or highs above my TP.
Then the next morning at 7:40 I get this bar:
Date Time Open High Low Close Volume 25.04.2019 07:40:00.000 GMT-0400,1.11243,1.11260,1.11235,1.11259,1505.38
the low is still above my SL and the high is still below my TP, but both my SL and TP orders complete!
My next() method is printing each bar so I know that's the one.
Here's a dump of my SL order -- print(order) in the notify_order for status Completed:
2019-07-25T07:40:00-04:00, 1.11416 1.11433 1.11394 1.11396 33.958517326947884 1.0 2 Ref: 41 OrdType: 1 OrdType: Sell Status: 4 Status: Completed Size: -100 Price: 1.1119400000000002 Price Limit: None TrailAmount: None TrailPercent: None ExecType: 3 ExecType: Stop CommInfo: <backtrader.comminfo.CommInfoBase object at 0x7fde4c3ad780> End of Session: 737264.9999999999 Info: AutoOrderedDict([('type', 'sl'), ('parent', 40)]) Broker: None Alive: False 2019-07-25T07:40:00-04:00, order #41 SELL completed, info AutoOrderedDict([('type', 'sl'), ('parent', 40)]) price 1.11194 size 100.00 pnl -0.16 pprice 0.00000 balance 999
Why did that SL order fire?
I'm running Backtrader 1.9.74.123
Any ideas would be hugely appreciated.
-
@leecallen Never mind -- I figured it out.
The next bar at 7:45 hits both the SL and the TP. And then I remembered: in Backtrader the order events get processed before the next() logic. And some bug in my code (I know where it is) is posting the prev-bar datetime in my logging.
And I guess I need to set up OCO or bracket orders or something so my SL and TP can't both fire.
-
"And some bug in my code (I know where it is) is posting the prev-bar datetime in my logging."
In some ways these types of bugs are the worst and the best. They're good because it means you were probably right about the logic. They're horrible because you spend hours trying to find them.
Good luck!
-
May be you can help how check type of order that accepted? Because I am updating take profit Limit order by moving average price and every updating of price I receiving new Limit order - previous not replaced.