def cancel_orders_eod(context, data): """ Cancel all open orders at the end of the day. We do it manually, to store the canceled orders and resubmit them a day later at market open. See also zipline.finance.blotter.simulation_blotter.SimulationBlotter.execute_cancel_policy To apply, use: schedule_function(cancel_orders_eod, date_rules.every_day(), time_rules.market_close()) """ # Delete the previous stored orders # Store all orders that have been canceled to resubmit them later if not hasattr(context, 'canceled_orders'): context.canceled_orders = {} else: context.canceled_orders.clear() for security, open_orders in list(get_open_orders().items()): for order in open_orders: if order.sid in context.canceled_orders: context.canceled_orders[order.sid] += order.amount - order.filled else: context.canceled_orders[order.sid] = order.amount - order.filled cancel_order(order)
def do_cancel_order(context, sym, do_delete, order): logging.info("X CANCELED {0:s} with {1:,d} / {2:,d} filled" \ .format(sym, order.filled, order.amount)) cancel_order(order) if do_delete: del context.duration[order.id]
def cancel(context, data): open_orders = get_all_open_orders() for order in open_orders: #print("X CANCELED {0:s} with {1:,d} / {2:,d} filled" #.format(order.sid.symbol, #order.filled, #order.amount)) cancel_order(order) context.reorder_dict[order.sid] = order.amount - order.filled
def cancel_all_open_orders(context, data, asset=None): ''' Cancel all open orders on a particular assets, or all if asset is None. ''' if asset: open_orders = get_open_orders(asset) else: open_orders = get_open_orders() try: iter(open_orders) except: open_orders = [open_orders] if open_orders: for asset in open_orders: if context.params['verbose']: print('cancelling order on {}'.format(asset.symbol)) cancel_order(asset)
def handle_data(context, data): # Skip first 200 periods to get full windows context.i += 1 if context.i < 200: return # Calculate moving averages short_mavg = data.history(context.fut, 'price', 50, '1m').mean() long_mavg = data.history(context.fut, 'price', 200, '1m').mean() # Enter the long position if short_mavg > long_mavg and not context.invested: fut_contract = data.current(context.fut, 'contract') # cancel open orders for contract, if any for order in get_open_orders(fut_contract): cancel_order(order) order_target_percent(fut_contract, 1) context.invested = True # Exit the long position elif short_mavg < long_mavg and context.invested: # cancel any open orders for order in get_open_orders(): cancel_order(order) positions = context.portfolio.positions for asset in positions: order_target_percent(asset, 0) context.invested = False # Save values for later inspection record(current_price=data.current(context.fut, "price"), short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data): global sell_status, buy_status can_trade = data.can_trade(context.smb) current = data.current(symbol('002450'), 'price') print(current) # hist = data.history(symbol('600496'), bar_count=20, frequency='1m', fields='open') # print(hist) print(datetime.datetime.now()) print(context.portfolio) print(context.portfolio.positions) orders = context.get_open_orders() if orders and len(orders) > 0: real_order = six.next(six.itervalues(orders))[0] cancel_order(real_order) if not sell_status: order(symbol('002450'), -200, limit_price=current - 0.01) sell_status = True if not buy_status: buy_price = current - 0.1 if buy_price * 100 <= context.portfolio.cash: order(symbol('002450'), 300, limit_price=buy_price) buy_status = True
def rebalance2(context, data): open_orders = get_open_orders() if open_orders: for security, orders in open_orders.items(): for oo in orders: cancel_order(oo) pipeline_data = context.pipeline_data all_assets = pipeline_data.index positions = context.portfolio.positions for asset in all_assets: order_target_percent(asset, 1 / len(all_assets)) # Remove any assets that should no longer be in our portfolio. positions = context.portfolio.positions for asset in viewkeys(positions) - set(all_assets): # This will fail if the asset was removed from our portfolio because it # was delisted. if data.can_trade(asset): order(asset, -positions[asset].amount)
def rebalance(context, data): pipeline_data = context.pipeline_data # Sort by P/B ratio assets_by_pb_ratio = pipeline_data.sort_values('pb_ratio', ascending=True) # Remove nulls assets_by_pb_ratio = assets_by_pb_ratio.loc[ assets_by_pb_ratio.pb_ratio.notnull()] # If we don't have enough data for a complete portfolio, do nothing if len(assets_by_pb_ratio) < 6: return longs = assets_by_pb_ratio.index[:3] shorts = assets_by_pb_ratio.index[-3:] # Build a 1x-leveraged, equal-weight, long-short portfolio. allocation_per_asset = 1.0 / 6.0 for asset in longs: for order in get_open_orders(asset): cancel_order(order) order_target_percent(asset, allocation_per_asset) for asset in shorts: for order in get_open_orders(asset): cancel_order(order) order_target_percent(asset, -allocation_per_asset) # Remove any assets that should no longer be in our portfolio. portfolio_assets = longs | shorts positions = context.portfolio.positions exit_positions = set(positions) - set(portfolio_assets) record(num_positions=len(positions)) for asset in exit_positions: for order in get_open_orders(asset): cancel_order(order) order_target_percent(asset, 0)
def rebalance(context, data): # Pipeline data will be a dataframe with integer columns named 'deciles' pipeline_data = context.pipeline_data all_assets = pipeline_data.index longs = all_assets[pipeline_data.deciles >= 10 - TOP_N_DECILES] shorts = all_assets[pipeline_data.deciles < TOP_N_DECILES] universe_size = len(all_assets) positions_per_side = universe_size * TOP_N_DECILES / 10 position_size = 0.5 / positions_per_side record(universe_size=universe_size, positions_per_side=positions_per_side, position_size=position_size) # Build a 1x-leveraged, equal-weight, long-short portfolio. for asset in longs: for order in get_open_orders(asset): cancel_order(order) order_target_percent(asset, position_size) for asset in shorts: for order in get_open_orders(asset): cancel_order(order) order_target_percent(asset, -position_size) # Remove any assets that should no longer be in our portfolio. portfolio_assets = longs | shorts positions = context.portfolio.positions for asset in set(positions) - set(portfolio_assets): for order in get_open_orders(asset): cancel_order(order) if data.can_trade(asset): order_target_percent(asset, 0)
def cancel_open(context, data): oo = get_open_orders() for sec in oo: for order in oo[sec]: cancel_order(order.id)
def cancel_all_open_orders(context): """ cancel all open orders. """ open_orders = get_open_orders() for oo in open_orders: cancel_order(oo)
def cancle_open_orders(context, data): for key, val in context.get_open_orders().items(): for order in val: print("cancel order {} for {}, amount {}, filled {}".format( order.id, order.sid, order.amount, order.filled)) cancel_order(order.id)
def cancel_open_orders(self, data): for security in get_open_orders(): for order in get_open_orders(security): cancel_order(order) log.warn('CANCEL: {} had open orders {}: now cancelled'.format(str(security),order))
def cancle_open_orders(context, data): for key, val in context.get_open_orders().items(): for order in val: print( "cancel order {} for {}, amount {}, filled {}".format(order.id, order.sid, order.amount, order.filled)) cancel_order(order.id)