"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Use timezone-aware UTC timestamps
mustafa885084e03fd68b
diff --git a/README.md b/README.mdindex 0f732c33c..5a5afec82 100644--- a/README.md+++ b/README.md@@ -52,6 +52,8 @@- **2026-07-04** 🧩 **API route slices, tutorial docs, and dependency floors**: IM channel and Settings routes moved out of `api_server.py` into `src/api/channels_routes.py` and `src/api/settings_routes.py`, continuing the narrow [#331](https://github.com/HKUDS/Vibe-Trading/issues/331) modularization path from contributor work ([#379](https://github.com/HKUDS/Vibe-Trading/pull/379), [#382](https://github.com/HKUDS/Vibe-Trading/pull/382), thanks @shadowinlife). The wiki gained a Chinese beginner tutorial for non-finance readers ([#393](https://github.com/HKUDS/Vibe-Trading/pull/393), thanks @kadaliao), and dependency floors now keep Pillow / LangChain / LangGraph on the installable patched track ([#390](https://github.com/HKUDS/Vibe-Trading/pull/390), thanks @aeonframework).+- **2026-07-04** 🧹 **UTC timestamp cleanup for session and API paths**: tightened the #395 timestamp fix so session, goal, channel, and API timestamps now emit timezone-aware UTC values in explicit ISO form.+- **2026-07-03** 🛡️ **Robinhood MCP refresh + API modularization + SSRF guard**: Robinhood Agentic Trading now uses the current MCP tool names across generic reads, live-runner plumbing, default read-only seeds, and mandate-gate tests, while interactive startup honors the same `.env` search order as the provider loader (`~/.vibe-trading/.env` → `agent/.env` → `$CWD/.env`) ([#391](https://github.com/HKUDS/Vibe-Trading/pull/391), closes [#381](https://github.com/HKUDS/Vibe-Trading/issues/381) and [#380](https://github.com/HKUDS/Vibe-Trading/issues/380)). System routes (`/health`, `/correlation`, `/system/shutdown`, `/skills`, `/api`) moved into `src/api/system_routes.py` as the next narrow API modularization slice ([#378](https://github.com/HKUDS/Vibe-Trading/pull/378), thanks @shadowinlife). Channel media SSRF defenses now reject CGNAT/mesh/non-global targets and QQ media redirects-to-internal before fetching ([#389](https://github.com/HKUDS/Vibe-Trading/pull/389), thanks @hobostay).- **2026-07-02** ⚡ **Factor acceleration + safer runtime boundaries**: hot rolling factor operators now use `bottleneck`/NumPy fast paths, alpha bench parallelism avoids repeated large-panel worker payloads, and base equity math has regression coverage ([#376](https://github.com/HKUDS/Vibe-Trading/pull/376), closes [#339](https://github.com/HKUDS/Vibe-Trading/issues/339), original work from [#342](https://github.com/HKUDS/Vibe-Trading/pull/342) by @shadowinlife). Upload and Shadow report routes moved out of the monolithic `api_server.py` as the first narrow API modularization slice while [#331](https://github.com/HKUDS/Vibe-Trading/issues/331) stays open ([#375](https://github.com/HKUDS/Vibe-Trading/pull/375), based on [#358](https://github.com/HKUDS/Vibe-Trading/pull/358), thanks @shadowinlife). Generated backtests now inherit only an allowlisted subprocess environment instead of the parent secrets surface ([#374](https://github.com/HKUDS/Vibe-Trading/pull/374), closes [#332](https://github.com/HKUDS/Vibe-Trading/issues/332)), and IM channels gained `/new` session reset plus case-insensitive pairing commands ([#372](https://github.com/HKUDS/Vibe-Trading/pull/372), closes [#371](https://github.com/HKUDS/Vibe-Trading/issues/371), thanks @shadowinlife).diff --git a/agent/api_server.py b/agent/api_server.pyindex 8f74c10a5..175effc8d 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -1775,8 +1775,7 @@ async def update_session(session_id: str, req: UpdateSessionRequest):raise HTTPException(status_code=404, detail=f"Session {session_id} not found")if req.title is not None:session.title = req.title- from datetime import datetime- session.updated_at = datetime.now().isoformat()+ session.updated_at = datetime.now(timezone.utc).isoformat()svc.store.update_session(session)return {"status": "updated", "session_id": session_id}diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex 0272730d5..15e2f6132 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport copyimport jsonimport logging-from datetime import datetime+from datetime import datetime, timezonefrom typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom src.agent.memory import WorkspaceMemory@@ -176,7 +176,7 @@ class ContextBuilder:Returns:System prompt text."""- now = datetime.now()+ now = datetime.now(timezone.utc)# Build memory section only if there are saved memoriesmemory_section = ""@@ -193,7 +193,7 @@ class ContextBuilder:skill_descriptions=self.skills_loader.get_descriptions(),memory_summary=self.memory.to_summary(),memory_section=memory_section,- current_datetime=now.strftime("%A, %B %d, %Y %H:%M (local)"),+ current_datetime=now.strftime("%A, %B %d, %Y %H:%M UTC"),)@staticmethoddiff --git a/agent/src/api/system_routes.py b/agent/src/api/system_routes.pyindex 0754a767e..88631dd36 100644--- a/agent/src/api/system_routes.py+++ b/agent/src/api/system_routes.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport osimport signalimport time-from datetime import datetime+from datetime import datetime, timezonefrom typing import Optionalfrom fastapi import BackgroundTasks, FastAPI, HTTPException, Query, Request, Security, status@@ -84,7 +84,7 @@ def register_system_routes(return HealthResponse(status="healthy",service="Vibe-Trading API",- timestamp=datetime.now().isoformat()+ timestamp=datetime.now(timezone.utc).isoformat())@app.get("/correlation")@@ -132,7 +132,7 @@ def register_system_routes(return {"status": "shutting-down","service": "Vibe-Trading API",- "timestamp": datetime.now().isoformat(),+ "timestamp": datetime.now(timezone.utc).isoformat(),}@app.get("/skills")diff --git a/agent/src/channels/mochat.py b/agent/src/channels/mochat.pyindex e178a9ffb..f45702394 100644--- a/agent/src/channels/mochat.py+++ b/agent/src/channels/mochat.py@@ -7,7 +7,7 @@ import jsonfrom collections import dequefrom contextlib import suppressfrom dataclasses import dataclass, field-from datetime import datetime+from datetime import datetime, timezonefrom typing import Anyimport httpx@@ -100,7 +100,7 @@ def _make_synthetic_event(payload["authorInfo"] = _safe_dict(author_info)return {"type": "message.add",- "timestamp": timestamp or datetime.utcnow().isoformat(),+ "timestamp": timestamp or datetime.now(timezone.utc).isoformat(),"payload": payload,}@@ -896,7 +896,7 @@ class MochatChannel(BaseChannel):try:self._state_dir.mkdir(parents=True, exist_ok=True)self._cursor_path.write_text(json.dumps({- "schemaVersion": 1, "updatedAt": datetime.utcnow().isoformat(),+ "schemaVersion": 1, "updatedAt": datetime.now(timezone.utc).isoformat(),"cursors": self._session_cursor,}, ensure_ascii=False, indent=2) + "\n", "utf-8")except Exception as e:diff --git a/agent/src/goal/store.py b/agent/src/goal/store.pyindex ea0537a9e..74f4a10e5 100644--- a/agent/src/goal/store.py+++ b/agent/src/goal/store.py@@ -10,7 +10,7 @@ import threadingimport uuidfrom contextlib import contextmanagerfrom dataclasses import asdict-from datetime import datetime+from datetime import datetime, timezonefrom enum import Enumfrom functools import wrapsfrom pathlib import Path@@ -51,7 +51,7 @@ _COMPLETION_RESULTS = {def _now_iso() -> str:- return datetime.now().isoformat()+ return datetime.now(timezone.utc).isoformat()def _id(prefix: str) -> str:diff --git a/agent/src/session/models.py b/agent/src/session/models.pyindex 4d48017e2..ef7fab89c 100644--- a/agent/src/session/models.py+++ b/agent/src/session/models.py@@ -4,11 +4,15 @@ from __future__ import annotationsimport uuidfrom dataclasses import dataclass, field, asdict-from datetime import datetime+from datetime import datetime, timezonefrom enum import Enumfrom typing import Any, Dict, List, Optional+def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()++class SessionStatus(str, Enum):"""Session lifecycle states."""@@ -45,8 +49,8 @@ class Session:session_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])title: str = ""status: SessionStatus = SessionStatus.ACTIVE- created_at: str = field(default_factory=lambda: datetime.now().isoformat())- updated_at: str = field(default_factory=lambda: datetime.now().isoformat())+ created_at: str = field(default_factory=_utc_now_iso)+ updated_at: str = field(default_factory=_utc_now_iso)last_attempt_id: Optional[str] = Noneconfig: Dict[str, Any] = field(default_factory=dict)@@ -94,7 +98,7 @@ class Message:session_id: str = ""role: str = "user"content: str = ""- created_at: str = field(default_factory=lambda: datetime.now().isoformat())+ created_at: str = field(default_factory=_utc_now_iso)linked_attempt_id: Optional[str] = Nonemetadata: Dict[str, Any] = field(default_factory=dict)@@ -146,7 +150,7 @@ class Attempt:run_dir: Optional[str] = Nonesummary: Optional[str] = Nonereact_trace: List[Dict[str, Any]] = field(default_factory=list)- created_at: str = field(default_factory=lambda: datetime.now().isoformat())+ created_at: str = field(default_factory=_utc_now_iso)completed_at: Optional[str] = Noneerror: Optional[str] = Nonemetrics: Optional[Dict[str, Any]] = None@@ -188,7 +192,7 @@ class Attempt:summary: Execution summary."""self.status = AttemptStatus.COMPLETED- self.completed_at = datetime.now().isoformat()+ self.completed_at = _utc_now_iso()if summary:self.summary = summary@@ -199,5 +203,5 @@ class Attempt:error: Error message."""self.status = AttemptStatus.FAILED- self.completed_at = datetime.now().isoformat()+ self.completed_at = _utc_now_iso()self.error = errordiff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex e37fcb9a5..616442718 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -281,10 +281,10 @@ def build_worker_prompt("- Respond in the same language as the task prompt.")- now = datetime.now()+ now = datetime.now(timezone.utc)prompt_parts.append(f"## Current Date & Time\n\n"- f"Today is {now.strftime('%A, %B %d, %Y %H:%M (local)')}."+ f"Today is {now.strftime('%A, %B %d, %Y %H:%M UTC')}")return "\n\n".join(prompt_parts)diff --git a/agent/src/tools/lockup_expiry_tool.py b/agent/src/tools/lockup_expiry_tool.pyindex fac5c07db..dacc5bca8 100644--- a/agent/src/tools/lockup_expiry_tool.py+++ b/agent/src/tools/lockup_expiry_tool.py@@ -17,7 +17,7 @@ from __future__ import annotationsimport jsonimport logging-from datetime import date, datetime, timedelta+from datetime import date, datetime, timedelta, timezonefrom typing import Anyfrom backtest.loaders import eastmoney_client@@ -46,7 +46,7 @@ _PAGE_SIZE = 200def _today() -> date:"""Return today's date (indirection kept for test monkeypatching)."""- return datetime.now().date()+ return datetime.now(timezone.utc).date()def _compact(d: date) -> str:diff --git a/agent/src/trading/connectors/dhan/sdk.py b/agent/src/trading/connectors/dhan/sdk.pyindex eb395bbee..0e3c34cb2 100644--- a/agent/src/trading/connectors/dhan/sdk.py+++ b/agent/src/trading/connectors/dhan/sdk.py@@ -365,9 +365,9 @@ def get_historical_bars(sec_id = str(security_id or symbol).strip()segment = exchange_segment.strip().upper()- from datetime import datetime, timedelta+ from datetime import datetime, timedelta, timezone- to_date = datetime.now()+ to_date = datetime.now(timezone.utc)# Intraday: max 5 days back; daily: use limitif period in ("1m", "5m", "15m", "30m"):from_date = to_date - timedelta(days=5)diff --git a/agent/src/trading/connectors/shoonya/sdk.py b/agent/src/trading/connectors/shoonya/sdk.pyindex bc6e831b4..c5c22eb03 100644--- a/agent/src/trading/connectors/shoonya/sdk.py+++ b/agent/src/trading/connectors/shoonya/sdk.py@@ -338,9 +338,9 @@ def get_historical_bars(api = _login(cfg)clean = symbol.strip().upper()- from datetime import datetime, timedelta+ from datetime import datetime, timedelta, timezone- end = datetime.now()+ end = datetime.now(timezone.utc)if period in ("1m", "5m", "15m", "30m"):start = end - timedelta(days=5)else:diff --git a/agent/tests/test_session_timestamp_timezone.py b/agent/tests/test_session_timestamp_timezone.pynew file mode 100644index 000000000..621321f4f--- /dev/null+++ b/agent/tests/test_session_timestamp_timezone.py@@ -0,0 +1,18 @@+from datetime import datetime++from src.session.models import Attempt, Message, Session+++def test_session_models_emit_timezone_aware_iso_timestamps() -> None:+ session = Session()+ message = Message()+ attempt = Attempt()++ for value in (session.created_at, session.updated_at, message.created_at, attempt.created_at):+ parsed = datetime.fromisoformat(value)+ assert parsed.tzinfo is not None++ attempt.mark_completed("done")+ assert attempt.completed_at is not None+ parsed_completed = datetime.fromisoformat(attempt.completed_at)+ assert parsed_completed.tzinfo is not Nonediff --git a/tools/ci_grep_gates.sh b/tools/ci_grep_gates.shindex 01017c220..e9c276ac1 100644--- a/tools/ci_grep_gates.sh+++ b/tools/ci_grep_gates.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# ci_grep_gates.sh — repo-wide safety floor enforced in CI.#-# Three gates run sequentially; any failure exits non-zero and names the+# Four gates run sequentially; any failure exits non-zero and names the# offending files. Run locally before pushing:## bash tools/ci_grep_gates.sh@@ -15,6 +15,8 @@# (b) No literal "WorldQuant" anywhere (trademark; spec.md §License).# (c) No per-stock-code data leaking into the wiki/alpha-library tree# (spec.md §"Vendor 数据 ToS").+# (d) No deprecated `datetime.utcnow(` usage or bare `datetime.now()` calls+# in Python sources; `datetime.now(timezone.utc)` is allowed.## Exclusions: .git, node_modules, __pycache__, .venv, dist, build, this# script itself. The HTML scan in (c) is scoped to wiki/alpha-library/**@@ -97,6 +99,32 @@ elseecho "${YELLOW}skip${NC}: no wiki/ directory"fi+# -------------------------------------------------------------- gate (d)+echo "[gate d] no deprecated datetime.utcnow() / bare datetime.now() calls ..."+TARGET_FILES=(+ agent/api_server.py+ agent/src/agent/context.py+ agent/src/api/system_routes.py+ agent/src/channels/mochat.py+ agent/src/goal/store.py+ agent/src/session/models.py+ agent/src/swarm/worker.py+ agent/src/tools/lockup_expiry_tool.py+ agent/src/trading/connectors/dhan/sdk.py+ agent/src/trading/connectors/shoonya/sdk.py+)+D_HITS=$(grep -Hn -E 'datetime\.utcnow\(|datetime\.now\(' "${TARGET_FILES[@]}" 2>/dev/null \+ | grep -v "$SELF" \+ | grep -vE 'datetime\.now\([^)]*(timezone\.utc|tz=timezone\.utc)' \+ || true)+if [ -n "$D_HITS" ]; then+ echo "${RED}FAIL${NC}: deprecated datetime.utcnow() or bare datetime.now() found:"+ echo "$D_HITS"+ FAILED=1+else+ echo "${GREEN}ok${NC}"+fi+# --------------------------------------------------------------- resultif [ "$FAILED" -ne 0 ]; thenecho