def order(self, sid, amount, initial_margin, limit_price=None, stop_price=None): # TODO: get rid of the initial_margin parameter when we can figure that out from inside this method # Check if there's enough in the margin account to cover initial margin if self.margin_account_value > self.total_maintenance_margin + initial_margin * amount: TradingAlgorithm.order(self, sid, amount, limit_price, stop_price) else: # there shouldn't be an exception here, right? # TODO: log once you figure out how zipline's logging works pass
def _liquidate_random_positions(self): """Liquidate an entire position (the position in particular is chosen at random) until we are back above maintenance margin.""" while self.margin_account_value < self.total_maintenance_margin: positions_as_list = self.perf_tracker.cumulative_performance.positions.items()[:] chosen_symbol, chosen_position = positions_as_list[random.randint(0, len(positions_as_list) - 1)] TradingAlgorithm.order(self, chosen_symbol, chosen_position.amount) positions_as_list.remove((chosen_symbol, chosen_position)) self.total_maintenance_margin = sum( [position.last_sale_price * 0.32 * position.amount for symbol, position in positions_as_list])