-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdaemon.py
More file actions
180 lines (154 loc) · 6.46 KB
/
Copy pathdaemon.py
File metadata and controls
180 lines (154 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
Polymarket Bot Daemon
Sleeps until the next relevant event, then fires the appropriate command.
Events (all times UTC):
- 05:30 ECMWF 00Z processed → --scan (new forecasts, enter positions)
- 10:00 GFS 06Z processed → --scan (secondary update)
- 17:30 ECMWF 12Z processed → --scan (afternoon forecast update)
- Every 30m opportunistic scan → --scan
- Every 30m risk check → --exit-scan
- Per-city nowcast windows (2pm and 3:30pm local → UTC) → --nowcast
- 01:00 Daily resolve → --resolve
Run once:
source venv/bin/activate && python daemon.py
"""
import logging
import time
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[
logging.StreamHandler(sys.stdout),
],
)
log = logging.getLogger("daemon")
# ── Event schedule ────────────────────────────────────────────────────────────
# Fixed UTC times for model runs: (hour, minute, command, label)
MODEL_RUN_EVENTS = [
(7, 13, "--scan", "ECMWF 00Z + GFS 00Z scan"),
(9, 45, "--scan", "GFS 06Z + ICON 06Z scan"),
(13, 30, "--scan", "Europe nowcast window scan"),
(19, 17, "--scan", "GFS 12Z + US nowcast scan"),
(7, 47, "--resolve", "Morning resolve"),
(19, 55, "--resolve", "Afternoon resolve"),
]
# Per-city nowcast windows: fire at 2:00pm and 3:30pm local time
CITY_TIMEZONES = {
"New York City": "America/New_York",
"Chicago": "America/Chicago",
"Atlanta": "America/New_York",
"Miami": "America/New_York",
"Dallas": "America/Chicago",
"Seattle": "America/Los_Angeles",
"London": "Europe/London",
"Paris": "Europe/Paris",
"Madrid": "Europe/Madrid",
"Munich": "Europe/Berlin",
"Milan": "Europe/Rome",
"Hong Kong": "Asia/Hong_Kong",
"Toronto": "America/Toronto",
"Buenos Aires": "America/Argentina/Buenos_Aires",
"Sao Paulo": "America/Sao_Paulo",
"Tel Aviv": "Asia/Jerusalem",
}
NOWCAST_LOCAL_HOURS = [14, 0] # 2:00pm local
NOWCAST_LOCAL_HOURS2 = [15, 30] # 3:30pm local
def _nowcast_utc_times(date_utc: datetime.date) -> list[tuple[datetime, str]]:
"""Return all nowcast fire times in UTC for a given date."""
events = []
seen_utc = set()
for city, tz_str in CITY_TIMEZONES.items():
tz = ZoneInfo(tz_str)
for h, m in [NOWCAST_LOCAL_HOURS, NOWCAST_LOCAL_HOURS2]:
# Build naive local datetime then localise
local_naive = datetime(date_utc.year, date_utc.month, date_utc.day, h, m)
local_dt = local_naive.replace(tzinfo=tz)
utc_dt = local_dt.astimezone(timezone.utc)
key = utc_dt.replace(second=0, microsecond=0)
if key not in seen_utc:
seen_utc.add(key)
events.append((key, f"Nowcast {city} {h:02d}:{m:02d} local"))
return events
def _build_schedule(now: datetime) -> list[tuple[datetime, str, str]]:
"""
Build a sorted list of (fire_time_utc, command_flag, label) for today + tomorrow.
Skips any events already in the past.
"""
events = []
for day_offset in [0, 1]:
d = (now + timedelta(days=day_offset)).date()
# Fixed model run events
for h, m, flag, label in MODEL_RUN_EVENTS:
fire = datetime(d.year, d.month, d.day, h, m, tzinfo=timezone.utc)
if fire > now:
events.append((fire, flag, label))
# Nowcast events
for fire, label in _nowcast_utc_times(d):
if fire > now:
events.append((fire, "--nowcast", label))
# Exit scan every 30 minutes (faster risk management / capital recycling)
for hour in range(24):
for minute in (0, 30):
fire = datetime(d.year, d.month, d.day, hour, minute, tzinfo=timezone.utc)
if fire > now:
events.append((fire, "--exit-scan",
f"30m exit scan {hour:02d}:{minute:02d} UTC"))
# Opportunistic scan every 30 minutes so fresh bankroll gets redeployed quickly
# between major model-run scans.
for hour in range(24):
for minute in (0, 30):
fire = datetime(d.year, d.month, d.day, hour, minute, tzinfo=timezone.utc)
if fire > now:
events.append((fire, "--scan",
f"30m opportunistic scan {hour:02d}:{minute:02d} UTC"))
events.sort(key=lambda x: x[0])
return events
def _run(flag: str, label: str, mode: str = "paper"):
log.info("▶ %s (%s)", label, flag)
extra_args = []
if flag == "--scan" and label.startswith("30m opportunistic scan"):
extra_args = ["--opportunistic"]
result = subprocess.run(
[sys.executable, "main.py", "--mode", mode, flag, *extra_args],
capture_output=False,
)
if result.returncode != 0:
log.warning("⚠ %s exited with code %d", flag, result.returncode)
else:
log.info("✓ %s done", label)
def run(mode: str = "paper"):
log.info("Daemon starting in %s mode.", mode)
import os
os.makedirs("logs", exist_ok=True)
while True:
now = datetime.now(timezone.utc)
schedule = _build_schedule(now)
if not schedule:
log.warning("Empty schedule — sleeping 1h")
time.sleep(3600)
continue
next_fire, next_flag, next_label = schedule[0]
wait_secs = (next_fire - now).total_seconds()
log.info("Next: %s at %s UTC (in %.0fm)",
next_label,
next_fire.strftime("%H:%M"),
wait_secs / 60)
if wait_secs > 0:
time.sleep(wait_secs)
# Re-check time after sleep (handles system clock drift / DST)
now2 = datetime.now(timezone.utc)
if abs((now2 - next_fire).total_seconds()) < 120:
_run(next_flag, next_label, mode=mode)
else:
log.warning("Clock drift detected, re-evaluating schedule")
if __name__ == "__main__":
import argparse
p = argparse.ArgumentParser()
p.add_argument("--mode", choices=["paper", "live"], default="paper")
args = p.parse_args()
run(mode=args.mode)