Last active
October 2, 2016 06:31
-
-
Save illoyd/a6088b5ad1a070b0584cd6783cced1d4 to your computer and use it in GitHub Desktop.
AnyOneOrder for Quantopian
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is an example of a one-or-the-other order, generalised as an any-one order. Useful when setting orders around a price point, such that if one order is triggered (begins to fill) the other orders are cancelled. | |
""" | |
class AnyOneOrder(object): | |
""" A group of orders where when one order is triggered, all other open orders are cancelled. """ | |
def __init__(self, *orders_or_ids): | |
self.order_ids = set( | |
map(self._get_id, orders_or_ids) | |
) | |
def update(self, context, data): | |
""" If any orders are filling, cancel all other orders. """ | |
# Get all filling or filled orders | |
ex_orders = self.executing_orders() | |
# All unfilled orders should be cancelled | |
if ex_orders: self.cancel_pending() | |
# To be helpful, return the list of executing orders | |
return ex_orders | |
def executing_orders(self): | |
return set( filter( self._is_executing_order, self.orders() ) ) | |
def pending_orders(self): | |
return set( filter( self._is_pending_order, self.orders() ) ) | |
def add(self, order_or_id): | |
order_or_id = self._get_id(order_or_id) | |
return self.order_ids.add(order_or_id) | |
def remove(self, order_or_id): | |
order_or_id = self._get_id(order_or_id) | |
return self.order_ids.remove(order_or_id) | |
def orders(self): | |
""" Return all orders, as Orders, for this AnyOne order. """ | |
return set( map(get_order, self.order_ids) ) | |
def cancel(self): | |
""" Cancel this AnyOne order, which cancels all child orders. """ | |
for order in self.orders(): | |
cancel_order(order) | |
pass | |
def cancel_pending(self): | |
""" Cancel any pending (e.g. not filled or filling) orders. """ | |
for order in self.pending_orders(): | |
cancel_order(order) | |
pass | |
@staticmethod | |
def _get_id(obj_or_id): | |
""" Helper to return the order ID, whether given as an Order or as an ID. """ | |
try: | |
return obj_or_id.id | |
except AttributeError: | |
return obj_or_id | |
@classmethod | |
def _is_open_order(klass, order): | |
""" Helper to find all orders that considered open. """ | |
return order.status == 0 | |
@classmethod | |
def _is_executing_order(klass, order): | |
""" Helper to find all orders that are filling or filled. """ | |
return order.filled != 0 and klass._is_open_order(order) | |
@classmethod | |
def _is_pending_order(klass, order): | |
""" Helper to find all orders that are filling or filled. """ | |
return order.filled == 0 and klass._is_open_order(order) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment