Files
ai-exchange/scripts/run_trading_journal.py
2026-05-06 17:16:31 +08:00

91 lines
2.9 KiB
Python

from datetime import date, datetime
from pathlib import Path
import json
import os
import sys
from sqlalchemy.exc import SQLAlchemyError
ROOT = Path(__file__).resolve().parents[1]
os.environ.setdefault("DATABASE_URL", "postgresql+psycopg://user:pass@localhost:5432/ai_ict_test")
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from src.services.journal import TradingJournalService, WeeklyReviewService
def main(env=None) -> int:
env = os.environ if env is None else env
output_json = _get_bool(env, "TRADING_JOURNAL_OUTPUT_JSON", False)
journal_service = TradingJournalService()
weekly_review_service = WeeklyReviewService()
instrument_id = _get_optional_int(env, "TRADING_JOURNAL_INSTRUMENT_ID")
execution_id = _get_optional_int(env, "TRADING_JOURNAL_EXECUTION_ID")
week_start = _get_date(env.get("TRADING_JOURNAL_WEEK_START"))
week_end = _get_date(env.get("TRADING_JOURNAL_WEEK_END"))
try:
if execution_id is not None:
journal_id = journal_service.upsert_entry_for_execution(execution_id)
backfill = {"execution_ids": [execution_id], "created": 1 if journal_id else 0}
else:
backfill = journal_service.backfill_missing_entries(limit=_get_int(env, "TRADING_JOURNAL_BACKFILL_LIMIT", 100))
weekly_summary = weekly_review_service.build_summary(
week_start=week_start,
week_end=week_end,
instrument_id=instrument_id,
)
except SQLAlchemyError as exc:
payload = {
"passed": False,
"error_type": exc.__class__.__name__,
"error": str(exc),
}
if output_json:
print(json.dumps(payload, default=str, ensure_ascii=False, sort_keys=True))
else:
print(f"Database unavailable for trading journal sample: {exc.__class__.__name__}")
return 2
payload = {
"passed": True,
"backfill": backfill,
"weekly_summary": weekly_summary,
}
if output_json:
print(json.dumps(payload, default=str, ensure_ascii=False, sort_keys=True))
else:
print(f"Journal backfill created: {backfill['created']}")
print(f"Weekly entries: {weekly_summary['entry_count']}")
print(f"Next week actions: {weekly_summary['next_week_actions']}")
return 0
def _get_optional_int(env, key: str):
value = env.get(key)
if value is None or value == "":
return None
return int(value)
def _get_int(env, key: str, default: int) -> int:
value = env.get(key)
if value is None or value == "":
return default
return int(value)
def _get_bool(env, key: str, default: bool) -> bool:
value = env.get(key)
if value is None or value == "":
return default
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _get_date(value):
if not value:
return None
return date.fromisoformat(str(value))
if __name__ == "__main__":
raise SystemExit(main())