def process_timer_event(self, event: Event) -> None: """""" self.timer_count += 1 if self.timer_count < self.timer_interval: return self.timer_count = 0 for portfolio_result in self.portfolio_results.values(): portfolio_result.clear_pnl() for contract_result in self.contract_results.values(): contract_result.calculate_pnl() portfolio_result = self.get_portfolio_result( contract_result.reference) portfolio_result.trading_pnl += contract_result.trading_pnl portfolio_result.holding_pnl += contract_result.holding_pnl portfolio_result.total_pnl += contract_result.total_pnl event = Event(EVENT_PM_CONTRACT, contract_result) self.event_engine.put(event) for portfolio_result in self.portfolio_results.values(): event = Event(EVENT_PM_PORTFOLIO, portfolio_result) self.event_engine.put(event)
def process_trade_event(self, event: Event) -> None: """""" trade: TradeData = event.data reference = self.order_reference_map.get(trade.vt_orderid, "") if not reference: return vt_symbol = trade.vt_symbol key = (reference, vt_symbol) contract_result = self.contract_results.get(key, None) if not contract_result: contract_result = ContractResult(self, reference, vt_symbol) self.contract_results[key] = contract_result contract_result.update_trade(trade) # Push trade data with reference trade.reference = reference self.event_engine.put(Event(EVENT_PM_TRADE, trade)) # Auto-subscribe tick data if trade.vt_symbol in self.subscribed: return contract = self.main_engine.get_contract(trade.vt_symbol) if not contract: return req = SubscribeRequest(contract.symbol, contract.exchange) self.main_engine.subscribe(req, contract.gateway_name)
def write_log(self, msg: str): """""" event = Event( EVENT_RECORDER_LOG, msg ) self.event_engine.put(event)
def put_strategy_event(self, strategy: StrategyTemplate): """ Put an event to update strategy status. """ data = strategy.get_data() event = Event(EVENT_PORTFOLIO_STRATEGY, data) self.event_engine.put(event)
def write_log(self, msg: str, source: str = "") -> None: """ Put log event with specific message. """ log = LogData(msg=msg, gateway_name=source) event = Event(EVENT_LOG, log) self.event_engine.put(event)
def write_log(self, msg: str): """""" log = LogData( msg=msg, gateway_name=APP_NAME ) event = Event(EVENT_SPREAD_LOG, log) self.event_engine.put(event)
def write_log(self, msg: str, algo: AlgoTemplate = None): """""" if algo: msg = f"{algo.algo_name}:{msg}" log = LogData(msg=msg, gateway_name=APP_NAME) event = Event(EVENT_ALGO_LOG, data=log) self.event_engine.put(event)
def write_log(self, msg: str, strategy: StrategyTemplate = None): """ Create portfolio engine log event. """ if strategy: msg = f"{strategy.strategy_name}: {msg}" log = LogData(msg=msg, gateway_name=APP_NAME) event = Event(type=EVENT_PORTFOLIO_LOG, data=log) self.event_engine.put(event)
def remove_algo_setting(self, setting_name: str): """""" if setting_name not in self.algo_settings: return self.algo_settings.pop(setting_name) event = Event(EVENT_ALGO_SETTING) event.data = {"setting_name": setting_name, "setting": None} self.event_engine.put(event) self.save_algo_setting()
def run_backtesting(self, class_name: str, vt_symbol: str, interval: str, start: datetime, end: datetime, rate: float, slippage: float, size: int, pricetick: float, capital: int, inverse: bool, setting: dict): """""" self.result_df = None self.result_statistics = None engine = self.backtesting_engine engine.clear_data() if interval == Interval.TICK.value: mode = BacktestingMode.TICK else: mode = BacktestingMode.BAR engine.set_parameters(vt_symbol=vt_symbol, interval=interval, start=start, end=end, rate=rate, slippage=slippage, size=size, pricetick=pricetick, capital=capital, inverse=inverse, mode=mode) strategy_class = self.classes[class_name] engine.add_strategy(strategy_class, setting) engine.load_data() try: engine.run_backtesting() except Exception: msg = f"策略回测失败,触发异常:\n{traceback.format_exc()}" self.write_log(msg) self.thread = None return self.result_df = engine.calculate_result() self.result_statistics = engine.calculate_statistics(output=False) # Clear thread object handler. self.thread = None # Put backtesting done event event = Event(EVENT_BACKTESTER_BACKTESTING_FINISHED) self.event_engine.put(event)
def run_optimization(self, class_name: str, vt_symbol: str, interval: str, start: datetime, end: datetime, rate: float, slippage: float, size: int, pricetick: float, capital: int, inverse: bool, optimization_setting: OptimizationSetting, use_ga: bool): """""" if use_ga: self.write_log("开始遗传算法参数优化") else: self.write_log("开始多进程参数优化") self.result_values = None engine = self.backtesting_engine engine.clear_data() if interval == Interval.TICK: mode = BacktestingMode.TICK else: mode = BacktestingMode.BAR engine.set_parameters(vt_symbol=vt_symbol, interval=interval, start=start, end=end, rate=rate, slippage=slippage, size=size, pricetick=pricetick, capital=capital, inverse=inverse, mode=mode) strategy_class = self.classes[class_name] engine.add_strategy(strategy_class, {}) if use_ga: self.result_values = engine.run_ga_optimization( optimization_setting, output=False) else: self.result_values = engine.run_optimization(optimization_setting, output=False) # Clear thread object handler. self.thread = None self.write_log("多进程参数优化完成") # Put optimization done event event = Event(EVENT_BACKTESTER_OPTIMIZATION_FINISHED) self.event_engine.put(event)
def _query_history(self, vt_symbol: str, interval: Interval, start: datetime, end: datetime) -> None: """""" contract: ContractData = self.main_engine.get_contract(vt_symbol) req = HistoryRequest(symbol=contract.symbol, exchange=contract.exchange, interval=interval, start=start, end=end) if contract.history_data: data = self.main_engine.query_history(req, contract.gateway_name) event = Event(EVENT_CHART_HISTORY, data) self.event_engine.put(event)
def put_event(self): """""" tick_symbols = list(self.tick_recordings.keys()) tick_symbols.sort() bar_symbols = list(self.bar_recordings.keys()) bar_symbols.sort() data = { "tick": tick_symbols, "bar": bar_symbols } event = Event( EVENT_RECORDER_UPDATE, data ) self.event_engine.put(event)
def run(self): """""" while self.active: try: task = self.queue.get(timeout=1) task_type, data = task if task_type == "tick": database_manager.save_tick_data([data]) elif task_type == "bar": database_manager.save_bar_data([data]) except Empty: continue except Exception: self.active = False info = sys.exc_info() event = Event(EVENT_RECORDER_EXCEPTION, info) self.event_engine.put(event)
def put_data_event(self, spread: SpreadData) -> None: """""" event = Event(EVENT_SPREAD_DATA, spread) self.event_engine.put(event)
def put_parameters_event(self, algo: AlgoTemplate, parameters: dict): """""" event = Event(EVENT_ALGO_PARAMETERS) event.data = {"algo_name": algo.algo_name, "parameters": parameters} self.event_engine.put(event)
def put_pos_event(self, spread: SpreadData) -> None: """""" event = Event(EVENT_SPREAD_POS, spread) self.event_engine.put(event)
def put_setting_event(self, setting_name: str, setting: dict): """""" event = Event(EVENT_ALGO_SETTING) event.data = {"setting_name": setting_name, "setting": setting} self.event_engine.put(event)
def put_algo_event(self, algo: SpreadAlgoTemplate) -> None: """""" event = Event(EVENT_SPREAD_ALGO, algo) self.event_engine.put(event)
def write_log(self, msg: str): """""" event = Event(EVENT_BACKTESTER_LOG) event.data = msg self.event_engine.put(event)
def put_event(self, event_type: str, data: Any) -> None: """""" event = Event(event_type, data) self.event_engine.put(event)
def put_stop_order_event(self, stop_order: StopOrder): """ Put an event to update stop order status. """ event = Event(EVENT_CTA_STOPORDER, stop_order) self.event_engine.put(event)
def put_variables_event(self, algo: AlgoTemplate, variables: dict): """""" event = Event(EVENT_ALGO_VARIABLES) event.data = {"algo_name": algo.algo_name, "variables": variables} self.event_engine.put(event)
def put_strategy_event(self, strategy: SpreadStrategyTemplate): """""" data = strategy.get_data() event = Event(EVENT_SPREAD_STRATEGY, data) self.event_engine.put(event)
def write_log(self, msg: str) -> None: log = LogData(msg=msg, gateway_name="EMAIL") event = Event(EVENT_LOG, log) self.event_engine.put(event)
def on_event(self, type: str, data: Any = None) -> None: """ General event push. """ event = Event(type, data) self.event_engine.put(event)
def write_log(self, msg: str): """""" log = LogData(msg=msg, gateway_name="RiskManager") event = Event(type=EVENT_LOG, data=log) self.event_engine.put(event)