69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
"""
|
|
Orchestrator for task coordination and execution
|
|
Manages backtesting tasks with lazy imports
|
|
"""
|
|
from .pool import TaskPool
|
|
from .task import TaskState
|
|
|
|
|
|
class Orchestrator:
|
|
"""Task coordinator for backtesting operations"""
|
|
|
|
def __init__(self, db_path: str, file_dir=None, max_workers: int = 2):
|
|
"""Initialize orchestrator with database path and worker limits"""
|
|
self.db_path = db_path
|
|
self.file_dir = file_dir
|
|
self.pool = TaskPool(max_workers=max_workers)
|
|
self._pending = {}
|
|
|
|
def submit_cta(self, strategy_class, symbol: str, params: dict,
|
|
start: str, end: str, cfg) -> str:
|
|
"""Submit a CTA backtesting task"""
|
|
task_id = f"cta_{symbol}_{id(params)}"
|
|
self.pool.submit(task_id, "cta")
|
|
self._pending = dict(
|
|
strategy_class=strategy_class,
|
|
symbol=symbol,
|
|
params=params,
|
|
start=start,
|
|
end=end,
|
|
cfg=cfg
|
|
)
|
|
return task_id
|
|
|
|
def _run_sync(self, task_id: str):
|
|
"""Execute a task synchronously (lazy import)"""
|
|
# Lazy import to avoid vnpy dependency issues
|
|
from sanguo_backtest.cta_engine import run_cta_backtest
|
|
|
|
task = self.pool.get_task(task_id)
|
|
task.start()
|
|
|
|
try:
|
|
result = run_cta_backtest(
|
|
self._pending["strategy_class"],
|
|
self._pending["symbol"],
|
|
self._pending["params"],
|
|
self._pending["start"],
|
|
self._pending["end"],
|
|
self._pending["cfg"],
|
|
self.db_path
|
|
)
|
|
task.complete(result_id=id(result))
|
|
except Exception as e:
|
|
task.fail(f"{type(e).__name__}: {e}")
|
|
|
|
return task
|
|
|
|
def get_status(self, task_id: str) -> TaskState | None:
|
|
"""Get task status by ID"""
|
|
return self.pool.get_status(task_id)
|
|
|
|
def get_result(self, task_id: str):
|
|
"""Get task result by ID (lazy import)"""
|
|
task = self.pool.get_task(task_id)
|
|
if task and task.status == TaskState.DONE and task.result_id:
|
|
# Lazy import to avoid vnpy dependency issues
|
|
from sanguo_backtest.result_store import load_result
|
|
return load_result(task.result_id, self.db_path)
|
|
return None |