[Add] init cta strategy in thread to avoid ui block

This commit is contained in:
vn.py 2019-02-17 15:00:02 +08:00
parent 9df1cf9a74
commit ae78a7f0c0
2 changed files with 48 additions and 21 deletions

View File

@ -8,6 +8,8 @@ from collections import defaultdict
from pathlib import Path from pathlib import Path
from typing import Any, Callable from typing import Any, Callable
from datetime import datetime, timedelta from datetime import datetime, timedelta
from threading import Thread
from queue import Queue, Empty
from vnpy.event import Event, EventEngine from vnpy.event import Event, EventEngine
from vnpy.trader.engine import BaseEngine, MainEngine from vnpy.trader.engine import BaseEngine, MainEngine
@ -64,6 +66,9 @@ class CtaEngine(BaseEngine):
self.stop_order_count = 0 # for generating stop_orderid self.stop_order_count = 0 # for generating stop_orderid
self.stop_orders = {} # stop_orderid: stop_order self.stop_orders = {} # stop_orderid: stop_order
self.init_thread = None
self.init_queue = Queue()
def init_engine(self): def init_engine(self):
""" """
""" """
@ -406,8 +411,26 @@ class CtaEngine(BaseEngine):
""" """
Init a strategy. Init a strategy.
""" """
self.init_queue.put(strategy_name)
if not self.init_thread:
self.init_thread = Thread(target=self._init_strategy)
self.init_thread.start()
def _init_strategy(self):
"""
Init strategies in queue.
"""
while not self.init_queue.empty():
strategy_name = self.init_queue.get()
strategy = self.strategies[strategy_name] strategy = self.strategies[strategy_name]
if strategy.inited:
self.write_log(f"{strategy_name}已经完成初始化,禁止重复操作")
continue
self.write_log(f"{strategy_name}开始执行初始化")
# Call on_init function of strategy # Call on_init function of strategy
self.call_strategy_func(strategy, strategy.on_init) self.call_strategy_func(strategy, strategy.on_init)
@ -428,8 +451,12 @@ class CtaEngine(BaseEngine):
else: else:
self.write_log(f"行情订阅失败,找不到合约{strategy.vt_symbol}", strategy) self.write_log(f"行情订阅失败,找不到合约{strategy.vt_symbol}", strategy)
# Put event to update init completed status.
strategy.inited = True strategy.inited = True
self.put_strategy_event(strategy) self.put_strategy_event(strategy)
self.write_log(f"{strategy_name}初始化完成")
self.init_thread = None
def start_strategy(self, strategy_name: str): def start_strategy(self, strategy_name: str):
""" """

View File

@ -173,7 +173,7 @@ class StrategyManager(QtWidgets.QFrame):
def init_ui(self): def init_ui(self):
"""""" """"""
self.setMaximumHeight(200) self.setMaximumHeight(300)
self.setFrameShape(self.Box) self.setFrameShape(self.Box)
self.setLineWidth(1) self.setLineWidth(1)