def _resend_order(self): remain_volume = self.target_order.volume - self.target_order.executed_volume if not self.check_notional(self.symbol, remain_volume): self.on_stop() return if self._n_retried < self.n_retry: self._n_retried += 1 logger.info(f'{self} retry No.{self._n_retried}') price = self._get_price() order = self.create_order(self.target_order.symbol, price, remain_volume, self.target_order.direction, EnumOrderType.LIMIT) self._client_order_id = order.client_order_id else: if self.due_action == EnumOrderStatus.CANCELLING: self.on_stop() return else: self.price_level = -2 price = self._get_price() order = self.create_order(self.target_order.symbol, price, remain_volume, self.target_order.direction, EnumOrderType.LIMIT) self._client_order_id = order.client_order_id
def wrapper(*args, **kwargs): n_retry = 0 sleep_seconds = self._sleep_seconds while True: try: result = job_func(*args, **kwargs) n_retry = 0 return result except self._exception as e: logger.debug("error happened: %s", e) if n_retry < self._max_retry: n_retry += 1 logger.debug( "retry no.%d for %s", n_retry, format_function(job_func, *args, **kwargs)) if sleep_seconds > 0: logger.debug("sleep %d seconds", sleep_seconds) time.sleep(sleep_seconds) sleep_seconds *= self._sleep_multiplier continue else: logger.exception(e) logger.info("failed to execute %s", format_function(job_func, *args, **kwargs)) break return copy(self._default_result)
def on_trade(self, trade: TradeData): key = (trade.client_order_id, trade.trade_id) if key in self._trade_dict: return False else: self._trade_dict[key] = trade self._portfolio.on_trade(trade) logger.info("%s receive %s", self, trade.pretty_string()) return True
def execute(self, actor: _Actor): strategy = actor.strategy_dict[self.strategy_id] if not self.config_file: strategy.reconfigure() else: strategy_config = parse_file(self.config_file) actor.modify_strategy(strategy_config) logger.info('Modify with %s', strategy_config) strategy.on_init()
def check_risk(self, strategy: StrategyTemplate): strategy.update_portfolio() for position in strategy.portfolio: symbol = position.symbol pnl_ratio = position.unrealized_pnl_rate() contract = ContractData.get_contract(symbol) if (abs(position.amount) > contract.min_quantity) and ( pnl_ratio < -abs(self.stop_loss)): logger.info( f'Stop loss triggered by {self} with pnl rate {pnl_ratio}\n{position.pretty_string()}' ) strategy.close_position(position.symbol)
def check_order(self, order: OrderData): symbol = order.symbol present_asset_value = self.portfolio[symbol].asset_value if order.direction == EnumOrderDirection.BUY: volume = order.volume else: volume = -order.volume new_value = volume * order.price if abs(present_asset_value + new_value) > self.max_notional: logger.info("Present notional is %f and new notional is %f while the maximum limit is %f\n" "%s", present_asset_value, new_value, self.max_notional, order) return False return True
def execute(self, actor: _Actor): if self.strategy_id.upper() == ALL_STRATEGY: strategy_list = actor.strategy_dict.values() elif self.strategy_id in self.strategy_id: strategy_list = [ actor.strategy_dict[self.strategy_id], ] else: logger.info('strategy_id %s does not exist', self.strategy_id) return for strategy in strategy_list: try: self.single_command_impl(strategy) except Exception as e: logger.exception(e) logger.info("Failing to execute commands %s for %s", self, strategy)
def on_order_status(self, order: OrderData): client_order_id = order.client_order_id # the order should be sent by OMS before if client_order_id in self._order_dict: local_order = self._order_dict[client_order_id] # order was in active mode if not local_order.is_closed(): self._order_dict[client_order_id].on_order(order) self._portfolio.on_order_status(order) # order was already closed before else: order = local_order else: self._order_dict[order.client_order_id] = order logger.info("%s receive %s", self, order.pretty_string()) return
def on_packet(self, data: dict): if 'table' in data: name = data['table'] if name in self._callback_dict: callback = self._callback_dict[name] if isinstance(data['data'], list): for data in data['data']: callback(data) else: callback(data['data']) else: logger.debug("BitMex received other data: %s", data) elif 'request' in data: req = data['request'] if 'success' in data: success = data['success'] flag = 'succeeded' if success else 'failed' logger.debug("request for operation %s %s", req, flag) else: logger.info("request failed %s with error %s", req, data['error']) else: logger.debug("BitMex received other data: %s", data)
def on_funding(self, funding: FundingData): if funding.funding_id not in self._funding_dict: self._funding_dict[funding.funding_id] = funding self._portfolio.on_funding(funding) logger.info("%s receive %s", self, funding.pretty_string())
def execute(self, actor: _Actor): strategy_config = parse_file(self.config_file) strategy = actor.create_strategy(strategy_config) actor.add_strategy(strategy) logger.info('Add %s with %s', strategy, strategy_config)
def execute(self, actor: _Actor): logger.info("Execute algorithm for: \n%s", self.order.pretty_string()) actor.send_order(self.order)
def single_command_impl(self, strategy: StrategyTemplate): strategy.load_portfolio(self.file_name) logger.info('Load portfolio\n' + strategy.portfolio.describe())