(self)
| 869 | raise _OutOfMoneyError |
| 870 | |
| 871 | def _process_orders(self): |
| 872 | data = self._data |
| 873 | open, high, low = data.Open[-1], data.High[-1], data.Low[-1] |
| 874 | reprocess_orders = False |
| 875 | |
| 876 | # Process orders |
| 877 | for order in list(self.orders): # type: Order |
| 878 | |
| 879 | # Related SL/TP order was already removed |
| 880 | if order not in self.orders: |
| 881 | continue |
| 882 | |
| 883 | # Check if stop condition was hit |
| 884 | stop_price = order.stop |
| 885 | if stop_price: |
| 886 | is_stop_hit = ((high >= stop_price) if order.is_long else (low <= stop_price)) |
| 887 | if not is_stop_hit: |
| 888 | continue |
| 889 | |
| 890 | # > When the stop price is reached, a stop order becomes a market/limit order. |
| 891 | # https://www.sec.gov/fast-answers/answersstopordhtm.html |
| 892 | order._replace(stop_price=None) |
| 893 | |
| 894 | # Determine purchase price. |
| 895 | # Check if limit order can be filled. |
| 896 | if order.limit: |
| 897 | is_limit_hit = low <= order.limit if order.is_long else high >= order.limit |
| 898 | # When stop and limit are hit within the same bar, we pessimistically |
| 899 | # assume limit was hit before the stop (i.e. "before it counts") |
| 900 | is_limit_hit_before_stop = (is_limit_hit and |
| 901 | (order.limit <= (stop_price or -np.inf) |
| 902 | if order.is_long |
| 903 | else order.limit >= (stop_price or np.inf))) |
| 904 | if not is_limit_hit or is_limit_hit_before_stop: |
| 905 | continue |
| 906 | |
| 907 | # stop_price, if set, was hit within this bar |
| 908 | price = (min(stop_price or open, order.limit) |
| 909 | if order.is_long else |
| 910 | max(stop_price or open, order.limit)) |
| 911 | else: |
| 912 | # Market-if-touched / market order |
| 913 | # Contingent orders always on next open |
| 914 | prev_close = data.Close[-2] |
| 915 | price = prev_close if self._trade_on_close and not order.is_contingent else open |
| 916 | if stop_price: |
| 917 | price = max(price, stop_price) if order.is_long else min(price, stop_price) |
| 918 | |
| 919 | # Determine entry/exit bar index |
| 920 | is_market_order = not order.limit and not stop_price |
| 921 | time_index = ( |
| 922 | (self._i - 1) |
| 923 | if is_market_order and self._trade_on_close and not order.is_contingent else |
| 924 | self._i) |
| 925 | |
| 926 | # If order is a SL/TP order, it should close an existing trade it was contingent upon |
| 927 | if order.parent_trade: |
| 928 | trade = order.parent_trade |
no test coverage detected