거래 빠르게 안티에서 병신만든거 커서로
feat: Implement backtest source management and enhance candle data handling Changes: - Introduced a new function `_apply_backtest_source_env_from_request` to manage the environment variables for candle, tick, and order book sources based on incoming requests. - Added a teardown function `_teardown_backtest_source_env` to ensure that environment variables do not persist between requests, enhancing the stability of the backtesting environment. - Refactored existing code to utilize the new source management functions, improving code readability and maintainability. - Added new utility functions in `bt_candle_source.py` for fetching and managing candle data, ensuring consistency with live trading data sources. Impact: - These changes improve the flexibility and reliability of the backtesting framework, allowing for better management of data sources and reducing the risk of cross-request contamination.
This commit is contained in:
@@ -19,6 +19,9 @@ _db_instance = None
|
||||
# get_merged_env_snapshot() — TTL 내 재사용 (실매: 웹에서 MAX_DAILY 등 변경 즉시 반영)
|
||||
_merged_env_cache: Optional[Dict[str, str]] = None
|
||||
_merged_env_cache_ts: float = 0.0
|
||||
# get_strategy_env_dict — 전략 config_* 스냅샷 RAM (매 루프 DB 금지)
|
||||
# 유니버스/봉 정합과 무관. 임계값·한도만. 기본 1초 · 분단위 동결 금지.
|
||||
_strategy_env_cache: Dict[str, Any] = {}
|
||||
# env 캐시 세대 카운터 — invalidate 시 +1. 파생 캐시(예: whipsaw 파라미터)가
|
||||
# 이 값으로 무효화를 감지해 안전하게 재계산한다(값은 그대로, 재계산 시점만 동일).
|
||||
_env_generation: int = 0
|
||||
@@ -45,9 +48,10 @@ def set_db(db_obj) -> None:
|
||||
|
||||
def invalidate_merged_env_cache() -> None:
|
||||
"""env/config 저장 후 스냅샷 캐시 무효화 (insert_env_snapshot 등)."""
|
||||
global _merged_env_cache, _merged_env_cache_ts, _env_generation
|
||||
global _merged_env_cache, _merged_env_cache_ts, _env_generation, _strategy_env_cache
|
||||
_merged_env_cache = None
|
||||
_merged_env_cache_ts = 0.0
|
||||
_strategy_env_cache = {}
|
||||
_env_generation += 1
|
||||
|
||||
|
||||
@@ -59,6 +63,17 @@ def _merged_env_cache_ttl_sec() -> float:
|
||||
return 60.0
|
||||
|
||||
|
||||
def _strategy_env_cache_ttl_sec() -> float:
|
||||
"""전략 config_* RAM TTL(초). 기본 1 — 유니버스 분슬롯과 무관.
|
||||
|
||||
웹 저장 시 invalidate_merged_env_cache 로 즉시 무효화.
|
||||
"""
|
||||
try:
|
||||
return max(0.0, float(os.environ.get("STRATEGY_ENV_CACHE_TTL_SEC", "1")))
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
|
||||
def env_cache_generation() -> int:
|
||||
"""현재 env 캐시 세대. invalidate 될 때마다 증가.
|
||||
|
||||
@@ -105,21 +120,38 @@ def get_strategy_env_dict(strategy_id: str) -> dict:
|
||||
|
||||
SCALP → config_scalp, MOMENTUM → config_momentum, SHORT → config_short …
|
||||
실매(get_env_from_db) · 웹 · 파라서치가 동일 소스를 쓰도록 한다.
|
||||
|
||||
RAM TTL(``STRATEGY_ENV_CACHE_TTL_SEC`` 기본 1초): 매 루프 config_* SELECT 금지.
|
||||
유니버스 event_time/분슬롯과 무관 — 손절·한도 등 **설정값**만.
|
||||
웹 저장 → ``invalidate_merged_env_cache`` 즉시 반영.
|
||||
"""
|
||||
global _strategy_env_cache
|
||||
sid = str(strategy_id or "").strip().upper() or "_"
|
||||
ttl = _strategy_env_cache_ttl_sec()
|
||||
now = time.time()
|
||||
gen = _env_generation
|
||||
hit = _strategy_env_cache.get(sid)
|
||||
if (
|
||||
isinstance(hit, dict)
|
||||
and hit.get("gen") == gen
|
||||
and (ttl <= 0 or (now - float(hit.get("ts") or 0)) < ttl)
|
||||
and isinstance(hit.get("data"), dict)
|
||||
):
|
||||
return hit["data"]
|
||||
|
||||
merged = get_merged_env_dict()
|
||||
db = _get_db()
|
||||
if db is None:
|
||||
return merged
|
||||
try:
|
||||
if hasattr(db, "get_strategy_config_snapshot"):
|
||||
strat = db.get_strategy_config_snapshot(strategy_id)
|
||||
if strat:
|
||||
out = dict(merged)
|
||||
out.update(strat)
|
||||
return out
|
||||
except Exception as e:
|
||||
logger.debug("strategy env 조회 실패 (%s): %s", strategy_id, e)
|
||||
return merged
|
||||
out = dict(merged)
|
||||
if db is not None:
|
||||
try:
|
||||
if hasattr(db, "get_strategy_config_snapshot"):
|
||||
strat = db.get_strategy_config_snapshot(strategy_id)
|
||||
if strat:
|
||||
out.update(strat)
|
||||
except Exception as e:
|
||||
logger.debug("strategy env 조회 실패 (%s): %s", strategy_id, e)
|
||||
_strategy_env_cache[sid] = {"data": out, "ts": now, "gen": gen}
|
||||
return out
|
||||
|
||||
|
||||
def get_env_from_db(key: str, default: str = "") -> str:
|
||||
|
||||
Reference in New Issue
Block a user