From 49950d4028a45617250042cbbdf3809a76a26111 Mon Sep 17 00:00:00 2001 From: Thigazhezhilan J Date: Mon, 6 Apr 2026 21:20:33 +0530 Subject: [PATCH] Fix MTM timestamp comparison in engine loop --- indian_paper_trading_strategy/engine/mtm.py | 61 +++++++++++++-------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/indian_paper_trading_strategy/engine/mtm.py b/indian_paper_trading_strategy/engine/mtm.py index 520413b..f697508 100644 --- a/indian_paper_trading_strategy/engine/mtm.py +++ b/indian_paper_trading_strategy/engine/mtm.py @@ -125,30 +125,43 @@ def log_mtm( return run_with_retry(_op) -def _get_last_mtm_ts(user_id: str | None = None, run_id: str | None = None): - scope_user, scope_run = get_context(user_id, run_id) - with db_connection() as conn: - with conn.cursor() as cur: - cur.execute( +def _get_last_mtm_ts(user_id: str | None = None, run_id: str | None = None): + scope_user, scope_run = get_context(user_id, run_id) + with db_connection() as conn: + with conn.cursor() as cur: + cur.execute( "SELECT MAX(timestamp) FROM mtm_ledger WHERE user_id = %s AND run_id = %s", (scope_user, scope_run), - ) - row = cur.fetchone() - if not row or row[0] is None: - return None - return row[0].astimezone().replace(tzinfo=None) - -def should_log_mtm(df, now, user_id: str | None = None, run_id: str | None = None): - if df is None: - last_ts = _get_last_mtm_ts(user_id=user_id, run_id=run_id) - if last_ts is None: - return True - return (now - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS - if getattr(df, "empty", False): - return True - try: - last_ts = datetime.fromisoformat(str(df.iloc[-1]["timestamp"])) - except Exception: - return True - return (now - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS + ) + row = cur.fetchone() + if not row or row[0] is None: + return None + value = row[0] + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) + + +def _normalize_dt(value): + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) + +def should_log_mtm(df, now, user_id: str | None = None, run_id: str | None = None): + now_dt = _normalize_dt(now) + if df is None: + last_ts = _get_last_mtm_ts(user_id=user_id, run_id=run_id) + if last_ts is None: + return True + return (now_dt - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS + if getattr(df, "empty", False): + return True + try: + last_ts = datetime.fromisoformat(str(df.iloc[-1]["timestamp"])) + except Exception: + return True + last_ts = _normalize_dt(last_ts) + return (now_dt - last_ts).total_seconds() >= MTM_INTERVAL_SECONDS