'Test that any open orders for an equity that gets delisted are
canceled.  Unless an equity is auto closed, any open orders for that
equity will persist indefinitely.'

def test_cancel_open_orders(self):

    auto_close_delta = self.trading_calendar.day
    resources = self.make_data(auto_close_delta, 'daily')
    env = resources.env
    assets = resources.assets
    first_asset_end_date = assets[0].end_date
    first_asset_auto_close_date = assets[0].auto_close_date
    def initialize(context):
        pass
    def handle_data(context, data):
        assert (context.portfolio.cash == context.portfolio.starting_cash)
        today_session = self.trading_calendar.minute_to_session_label(context.get_datetime())
        day_after_auto_close = self.trading_calendar.next_session_label(first_asset_auto_close_date)
        if (today_session == first_asset_end_date):
            assert (len(context.get_open_orders()) == 0)
            context.order(context.sid(0), 10)
            assert (len(context.get_open_orders()) == 1)
        elif (today_session == first_asset_auto_close_date):
            assert (len(context.get_open_orders()) == 1)
        elif (today_session == day_after_auto_close):
            assert (len(context.get_open_orders()) == 0)
    algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data, env=env, sim_params=resources.sim_params)
    results = algo.run(resources.data_portal)
    orders = results['orders']
    def orders_for_date(date):
        return orders.iloc[self.test_days.get_loc(date)]
    original_open_orders = orders_for_date(first_asset_end_date)
    assert (len(original_open_orders) == 1)
    last_close_for_asset = algo.trading_calendar.session_close(first_asset_end_date)
    self.assertDictContainsSubset({'amount': 10, 'commission': 0, 'created': last_close_for_asset, 'dt': last_close_for_asset, 'sid': assets[0], 'status': ORDER_STATUS.OPEN, 'filled': 0}, original_open_orders[0])
    orders_after_auto_close = orders_for_date(first_asset_auto_close_date)
    assert (len(orders_after_auto_close) == 1)
    self.assertDictContainsSubset({'amount': 10, 'commission': 0, 'created': last_close_for_asset, 'dt': algo.trading_calendar.session_close(first_asset_auto_close_date), 'sid': assets[0], 'status': ORDER_STATUS.CANCELLED, 'filled': 0}, orders_after_auto_close[0])
