After self.buy(), the order is not executed straight away: it goes through several statuses. Submitted (sent to the broker), Accepted (accepted), then Completed (executed), or else Canceled, Expired, Margin (not enough cash) and Rejected.
notify_order(self, order) is called at every change. You first skip the intermediate steps: if order.status in [order.Submitted, order.Accepted]: return. Then you handle the execution and the failures.
When the order is Completed, order.executed.price gives the actual price of execution, order.executed.size the quantity and order.executed.comm the commission. order.isbuy() tells whether it was a buy.
A common pattern: keep the pending order in self.order and send nothing while it is not None. You reset it to None in notify_order once the order is finished, which avoids duplicates.
Examples
KAPPA-X (fictional market) : The vertical line is the bar where the strategy decides to buy. The order only executes at the next open: if the price has jumped in between, notify_order reveals it through order.executed.price.
15 January 2015: the Swiss franc soars : That day the Swiss National Bank dropped its floor of 1.20 francs per euro. EUR/CHF fell from about 1.20 to below 1.00 within minutes, and many stop orders were filled very far from their planned price. Only the price actually executed counts, the one notify_order passes on.
Key terms
notify_order
Method called at each change of an order’s status
Completed
Status of a fully executed order
Margin
Status of an order refused for lack of cash or margin