from brain_db import get_db_connection from datetime import datetime class DynamicParams: _cache = {} _last_fetch = 0 _CACHE_TTL = 300 # 5 minutes @classmethod def get(cls, key: str, default=None): """Fetch a parameter by key with caching.""" params = cls.get_all() return params.get(key, default) @classmethod def get_all(cls) -> dict: """Fetch all parameters from the database.""" conn = get_db_connection() try: cursor = conn.cursor() cursor.execute("SELECT key, value FROM system_parameters") rows = cursor.fetchall() params = {row["key"]: cls._parse_value(row["value"]) for row in rows} return params finally: conn.close() @classmethod def update(cls, key: str, value): """Update a parameter in the database.""" conn = get_db_connection() try: cursor = conn.cursor() cursor.execute(""" UPDATE system_parameters SET value = ?, last_updated = ? WHERE key = ? """, (str(value), datetime.now().isoformat(), key)) conn.commit() print(f"[Brain] Updated {key} to {value}") finally: conn.close() @staticmethod def _parse_value(val: str): try: if "." in val: return float(val) return int(val) except ValueError: return val # Standardized keys for easy access KEYS = { "WEIGHT_LSTM": "WEIGHT_LSTM", "WEIGHT_XGB": "WEIGHT_XGB", "WEIGHT_SENTIMENT": "WEIGHT_SENTIMENT", "BUY_THRESHOLD": "BUY_THRESHOLD", "NORMAL_BUY_THRESHOLD": "NORMAL_BUY_THRESHOLD", "ATR_MULTIPLIER_SL": "ATR_MULTIPLIER_SL", "ATR_MULTIPLIER_TP1": "ATR_MULTIPLIER_TP1", "MIN_CONFIDENCE": "MIN_CONFIDENCE" }