I happen to be working with that right now in case any of this makes any sense for ya.
c = context
pflo = c.portfolio
if some condition calling for liquidation and not c.liquidating:
c.liquidating = 1 # Initialize liquidation
for sec in pflo.positions: # Try to liquidate
if pflo.positions[sec].amount <= 0: continue
if get_open_orders(sec): continue # Avoid shorting
order_target(sec, 0) # Sell all
return
and then on succeeding bars, have to make sure. This is mostly a repeat of above with a logging line added:
if c.liquidating: # Clean/finish up missed liquidations, partial sells etc.
for sec in pflo.positions: # Try to complete liquidation
if pflo.positions[sec].amount <= 0: continue
if get_open_orders(sec): continue # Avoid shorting
log.info('liquidating yet {} shrs {} of {} remaining'.format(
sec.symbol, pflo.positions[sec].amount, sec.symbol))
order_target(sec, 0) # Sell all
return
Once done, clear the trigger:
if not pflo.positions_value:
c.liquidating = 0
return