stratforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. stratforge/__init__.py +17 -0
  2. stratforge/ccxt_bridge.py +478 -0
  3. stratforge/cfm/__init__.py +3 -0
  4. stratforge/cfm/bars.py +115 -0
  5. stratforge/cfm/download_cde.py +159 -0
  6. stratforge/cfm/isolation.py +14 -0
  7. stratforge/cfm/ledger.py +332 -0
  8. stratforge/cfm/replay.py +224 -0
  9. stratforge/cfm/run_cde_dozen.py +111 -0
  10. stratforge/cfm/run_cde_replay.py +107 -0
  11. stratforge/cfm/run_cde_universe.py +112 -0
  12. stratforge/cfm/run_research.py +110 -0
  13. stratforge/cfm/run_round2.py +78 -0
  14. stratforge/cfm/run_validate.py +196 -0
  15. stratforge/cfm/strats.py +427 -0
  16. stratforge/cfm/strats_cde.py +681 -0
  17. stratforge/cfm/test_isolation.py +43 -0
  18. stratforge/cfm/test_ledger.py +76 -0
  19. stratforge/cfm/test_venue.py +36 -0
  20. stratforge/cfm/venue.py +36 -0
  21. stratforge/live.py +15 -0
  22. stratforge/paper_family.py +15 -0
  23. stratforge/risk_limits.py +337 -0
  24. stratforge/short/__init__.py +5 -0
  25. stratforge/short/backfill_spot_gap.py +90 -0
  26. stratforge/short/engine.py +227 -0
  27. stratforge/short/indicators.py +58 -0
  28. stratforge/short/ledger.py +273 -0
  29. stratforge/short/regime_occupancy.py +156 -0
  30. stratforge/short/regime_stretches.py +50 -0
  31. stratforge/short/replay.py +390 -0
  32. stratforge/short/run_backtest.py +153 -0
  33. stratforge/short/run_regime_gates.py +105 -0
  34. stratforge/short/run_tsmom12.py +263 -0
  35. stratforge/short/test_short.py +269 -0
  36. stratforge/short/test_tsmom.py +139 -0
  37. stratforge/short/tsmom.py +160 -0
  38. stratforge/state.py +20 -0
  39. stratforge/strategies/bar_apply.py +36 -0
  40. stratforge/strategies/bar_freshness.py +53 -0
  41. stratforge/strategies/buy_protect.py +78 -0
  42. stratforge/strategies/config_load.py +82 -0
  43. stratforge/strategies/daily_data_feed.py +341 -0
  44. stratforge/strategies/day_risk.py +51 -0
  45. stratforge/strategies/display_time.py +72 -0
  46. stratforge/strategies/live_data_feed.py +353 -0
  47. stratforge/strategies/live_executor.py +1346 -0
  48. stratforge/strategies/live_node.py +430 -0
  49. stratforge/strategies/live_reconcile.py +358 -0
  50. stratforge/strategies/node_lock.py +48 -0
  51. stratforge/strategies/paper_executor.py +492 -0
  52. stratforge/strategies/paper_family_node.py +304 -0
  53. stratforge/strategies/qty_precision.py +44 -0
  54. stratforge/strategies/research_families.py +335 -0
  55. stratforge/strategies/research_replay.py +681 -0
  56. stratforge/strategies/signal_engine.py +606 -0
  57. stratforge/strategies/universe.py +60 -0
  58. stratforge/viz/__init__.py +1 -0
  59. stratforge/viz/projector.py +402 -0
  60. stratforge-0.1.0.dist-info/METADATA +51 -0
  61. stratforge-0.1.0.dist-info/RECORD +64 -0
  62. stratforge-0.1.0.dist-info/WHEEL +5 -0
  63. stratforge-0.1.0.dist-info/licenses/LICENSE +21 -0
  64. stratforge-0.1.0.dist-info/top_level.txt +1 -0
stratforge/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """stratforge public package.
2
+
3
+ Importing this module puts the package directory first on sys.path so the
4
+ existing ``strategies`` and ``ccxt_bridge`` imports resolve inside the
5
+ package, not a vendored tree on the process cwd.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ _PKG = str(Path(__file__).resolve().parent)
13
+ if _PKG in sys.path:
14
+ sys.path.remove(_PKG)
15
+ sys.path.insert(0, _PKG)
16
+
17
+ __version__ = "0.1.0"
@@ -0,0 +1,478 @@
1
+ """
2
+ ccxt execution bridge for Coinbase Advanced Trade (US).
3
+
4
+ DRY-RUN by default. Live requires ALL of:
5
+ LIVE_TRADING=true
6
+ SIMULATION_MODE=false
7
+ approval file (default data/LIVE_APPROVED) — no env bypass
8
+ COINBASE_API_KEY + COINBASE_API_SECRET
9
+ COINBASE_PORTFOLIO_ID (funded sleeve; no silent default on LIVE)
10
+
11
+ v1 production path: spot long-only (buy to open, sell to close). Shorts/CFM
12
+ remain available as lower-level helpers but LiveExecutor will not call them.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import math
19
+ import os
20
+ import time
21
+ import uuid
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from stratforge.state import state_root
27
+
28
+ logger = logging.getLogger("ccxt_bridge")
29
+
30
+ ROOT = state_root()
31
+ DEFAULT_JOURNAL = ROOT / "data" / "execution_log_bridge.jsonl"
32
+ DEFAULT_APPROVAL = ROOT / "data" / "LIVE_APPROVED"
33
+
34
+
35
+ def normalize_pem_secret(raw: str | None) -> str:
36
+ """Coinbase Advanced Trade secrets are PEMs. .env / systemd EnvironmentFile
37
+ often store real newlines as the two-char sequence \\n. Reconcile already
38
+ unescaped; the order path did not (2026-08-22: Invalid symbol 92 / native
39
+ account-register timeout). Safe no-op if newlines are already real."""
40
+ if not raw:
41
+ return ""
42
+ return str(raw).strip().strip('"').strip("'").replace("\\n", "\n")
43
+
44
+
45
+ def load_live_secrets() -> None:
46
+ """Opt-in: load .env.live then .env. Paper/shadow must never call this."""
47
+ for name in (".env.live", ".env"):
48
+ env_path = ROOT / name
49
+ if not env_path.is_file():
50
+ continue
51
+ try:
52
+ for line in env_path.read_text().splitlines():
53
+ line = line.strip()
54
+ if not line or line.startswith("#") or "=" not in line:
55
+ continue
56
+ k, v = line.split("=", 1)
57
+ k, v = k.strip(), v.strip().strip('"').strip("'")
58
+ if k.upper() in ("COINBASE_API_SECRET", "API_SECRET"):
59
+ v = normalize_pem_secret(v)
60
+ if k and k not in os.environ:
61
+ os.environ[k] = v
62
+ except Exception as e:
63
+ logger.warning("dotenv load failed (%s): %s", name, e)
64
+
65
+
66
+ # Do NOT auto-load secrets on import — paper/shadow PIDs must stay keyless.
67
+
68
+
69
+ def is_live_enabled() -> bool:
70
+ live = os.getenv("LIVE_TRADING", "false").lower() == "true"
71
+ sim = os.getenv("SIMULATION_MODE", "true").lower() != "false"
72
+ return live and not sim
73
+
74
+
75
+ def approval_ok() -> tuple[bool, str]:
76
+ """LIVE always requires repo data/LIVE_APPROVED. Env cannot move or disable this."""
77
+ path = DEFAULT_APPROVAL
78
+ if path.is_file():
79
+ return True, f"approval file {path}"
80
+ return False, f"missing approval file {path}"
81
+
82
+
83
+ def bridge_config(journal_path: str | Path | None = None) -> dict:
84
+ live = is_live_enabled()
85
+ ok, reason = approval_ok() if live else (True, "dry-run")
86
+ return {
87
+ "dry_run": (not live) or (not ok),
88
+ "live_requested": live,
89
+ "approval_ok": ok,
90
+ "approval_reason": reason,
91
+ "api_key": os.getenv("COINBASE_API_KEY", ""),
92
+ "api_secret": normalize_pem_secret(os.getenv("COINBASE_API_SECRET", "")),
93
+ "use_cfm": os.getenv("USE_CFM_FUTURES", "false").lower() == "true",
94
+ "leverage": float(os.getenv("COINBASE_LEVERAGE", "1")),
95
+ "journal_path": str(journal_path or os.getenv("BRIDGE_JOURNAL", DEFAULT_JOURNAL)),
96
+ "long_only_default": True,
97
+ "portfolio_id": (os.getenv("COINBASE_PORTFOLIO_ID") or "").strip(),
98
+ }
99
+
100
+
101
+ def _journal(path: str, entry: dict):
102
+ os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
103
+ entry = {**entry, "ts": datetime.now(timezone.utc).isoformat()}
104
+ with open(path, "a") as f:
105
+ f.write(json.dumps(entry, default=str) + "\n")
106
+ logger.info("JOURNAL %s", json.dumps(entry, default=str))
107
+
108
+
109
+ def get_client(cfg: dict | None = None):
110
+ import ccxt
111
+
112
+ cfg = cfg or bridge_config()
113
+ if cfg["dry_run"]:
114
+ return ccxt.coinbase({"enableRateLimit": True})
115
+ if not (cfg["api_key"] and cfg["api_secret"]):
116
+ raise RuntimeError("Live trading requested but COINBASE_API_KEY/SECRET missing")
117
+ options: dict[str, Any] = {"fetchCurrencies": False}
118
+ pid = (cfg.get("portfolio_id") or os.getenv("COINBASE_PORTFOLIO_ID") or "").strip()
119
+ if pid:
120
+ options["portfolio"] = pid
121
+ return ccxt.coinbase(
122
+ {
123
+ "apiKey": cfg["api_key"],
124
+ "secret": cfg["api_secret"],
125
+ "enableRateLimit": True,
126
+ "options": options,
127
+ }
128
+ )
129
+
130
+
131
+ def live_order_params(
132
+ client_order_id: str,
133
+ cfg: dict | None = None,
134
+ order_type: str = "market",
135
+ ) -> dict[str, Any]:
136
+ params: dict[str, Any] = {"clientOrderId": client_order_id}
137
+ pid = ""
138
+ if cfg:
139
+ pid = str(cfg.get("portfolio_id") or "").strip()
140
+ pid = pid or (os.getenv("COINBASE_PORTFOLIO_ID") or "").strip()
141
+ if pid:
142
+ params["retail_portfolio_id"] = pid
143
+ if str(order_type).lower() == "limit":
144
+ params["timeInForce"] = "IOC"
145
+ return params
146
+
147
+
148
+ def resolved_fill(order: dict | None) -> float:
149
+ """Venue-reported fill only. Never fall back to requested size."""
150
+ if not isinstance(order, dict):
151
+ return 0.0
152
+ raw = order.get("filled")
153
+ if raw is None or raw == "":
154
+ return 0.0
155
+ try:
156
+ qty = float(raw)
157
+ except (TypeError, ValueError):
158
+ return 0.0
159
+ return qty if qty > 0 else 0.0
160
+
161
+
162
+ def _fnum(v) -> float | None:
163
+ if v is None or v == "":
164
+ return None
165
+ try:
166
+ return float(v)
167
+ except (TypeError, ValueError):
168
+ return None
169
+
170
+
171
+ def resolved_avg(order: dict | None) -> float | None:
172
+ """Venue average only. Do not use request/limit price."""
173
+ if not isinstance(order, dict):
174
+ return None
175
+ return _fnum(order.get("average"))
176
+
177
+
178
+ def resolved_cost(order: dict | None) -> float | None:
179
+ """Venue quote cost only. Do not use requested qty × ref price."""
180
+ if not isinstance(order, dict):
181
+ return None
182
+ return _fnum(order.get("cost"))
183
+
184
+
185
+ def resolved_fee(order: dict | None) -> tuple[float | None, str | None]:
186
+ """USD fee from venue. Never invent a rate."""
187
+ if not isinstance(order, dict):
188
+ return None, None
189
+ blobs: list = []
190
+ fee = order.get("fee")
191
+ if isinstance(fee, dict):
192
+ blobs.append(fee)
193
+ fees = order.get("fees")
194
+ if isinstance(fees, list):
195
+ blobs.extend(x for x in fees if isinstance(x, dict))
196
+ for blob in blobs:
197
+ ccy = str(blob.get("currency") or blob.get("code") or "").upper()
198
+ amt = _fnum(blob.get("cost"))
199
+ if amt is None:
200
+ continue
201
+ if ccy and ccy not in {"USD", "USDC", "USDT"}:
202
+ continue
203
+ return amt, (ccy or "USD")
204
+ return None, None
205
+
206
+
207
+ def normalize_ccxt_order(order: dict | None) -> dict:
208
+ """Collapse a ccxt order into journal fields. complete=False if economics missing."""
209
+ filled = resolved_fill(order)
210
+ avg = resolved_avg(order)
211
+ cost = resolved_cost(order)
212
+ fee, fee_ccy = resolved_fee(order)
213
+ if cost is None and filled > 0 and avg is not None:
214
+ cost = filled * avg
215
+ if avg is None and cost is not None and filled > 0:
216
+ avg = cost / filled
217
+ status = ""
218
+ oid = None
219
+ if isinstance(order, dict):
220
+ status = str(order.get("status") or "")
221
+ oid = order.get("id")
222
+ complete = filled > 0 and cost is not None and fee is not None and avg is not None
223
+ return {
224
+ "filled": filled,
225
+ "avg_price": avg,
226
+ "cost": cost,
227
+ "fee": fee,
228
+ "fee_currency": fee_ccy,
229
+ "status": status or None,
230
+ "order_id": oid,
231
+ "complete": complete,
232
+ }
233
+
234
+
235
+ def to_ccxt_symbol(symbol: str) -> str:
236
+ s = symbol.replace("-", "/").upper()
237
+ if "/" not in s:
238
+ s = f"{s}/USD"
239
+ return s
240
+
241
+
242
+ def to_venue_symbol(symbol: str) -> str:
243
+ """Coinbase product id: BTC/USD → BTC-USD."""
244
+ return symbol.replace("/", "-").upper()
245
+
246
+
247
+ def place_order(
248
+ symbol: str,
249
+ side: str,
250
+ quantity: float,
251
+ order_type: str = "market",
252
+ price: float | None = None,
253
+ client_order_id: str | None = None,
254
+ reduce_only: bool = False,
255
+ journal_path: str | Path | None = None,
256
+ cfg: dict | None = None,
257
+ ) -> dict[str, Any]:
258
+ """
259
+ Place order. side buy|sell. Returns normalized fill dict.
260
+ dry-run: no exchange call.
261
+ """
262
+ cfg = cfg or bridge_config(journal_path)
263
+ jpath = str(journal_path or cfg["journal_path"])
264
+ ccxt_symbol = to_ccxt_symbol(symbol)
265
+ venue_sym = to_venue_symbol(symbol)
266
+ coid = client_order_id or f"nt-{uuid.uuid4().hex[:16]}"
267
+ side_l = side.lower()
268
+
269
+ base_entry = {
270
+ "symbol": venue_sym,
271
+ "ccxt_symbol": ccxt_symbol,
272
+ "side": side_l,
273
+ "quantity": float(quantity),
274
+ "order_type": order_type,
275
+ "client_order_id": coid,
276
+ "reduce_only": reduce_only,
277
+ "ref_price": price,
278
+ }
279
+
280
+ if cfg["dry_run"]:
281
+ entry = {
282
+ **base_entry,
283
+ "action": "DRY_RUN_ORDER",
284
+ "status": "SIMULATED",
285
+ "venue": "COINBASE_SPOT",
286
+ "avg_price": price,
287
+ "filled": float(quantity),
288
+ "fee": None,
289
+ "live_requested": cfg.get("live_requested", False),
290
+ "approval_reason": cfg.get("approval_reason"),
291
+ }
292
+ _journal(jpath, entry)
293
+ logger.warning(
294
+ "[DRY-RUN] would %s %s %s coid=%s", side_l, quantity, venue_sym, coid
295
+ )
296
+ return entry
297
+
298
+ if not cfg.get("approval_ok", False):
299
+ raise RuntimeError(f"Live blocked: {cfg.get('approval_reason')}")
300
+
301
+ if str(order_type).lower() == "limit":
302
+ try:
303
+ px = float(price) if price is not None else 0.0
304
+ except (TypeError, ValueError):
305
+ px = 0.0
306
+ if not (math.isfinite(px) and px > 0):
307
+ raise ValueError("limit order requires price > 0")
308
+
309
+ client = get_client(cfg)
310
+ params: dict[str, Any] = live_order_params(coid, cfg, order_type=order_type)
311
+ try:
312
+ order = client.create_order(
313
+ ccxt_symbol, order_type, side_l, float(quantity), price, params
314
+ )
315
+ norm = normalize_ccxt_order(order)
316
+ if not norm["complete"]:
317
+ oid = order.get("id") if isinstance(order, dict) else None
318
+ for _ in range(8):
319
+ if not oid:
320
+ break
321
+ time.sleep(0.25)
322
+ try:
323
+ order = client.fetch_order(oid, ccxt_symbol)
324
+ except Exception:
325
+ continue
326
+ norm = normalize_ccxt_order(order)
327
+ if norm["complete"]:
328
+ break
329
+ entry = {
330
+ **base_entry,
331
+ "action": "LIVE_ORDER",
332
+ "status": norm["status"],
333
+ "order_id": norm["order_id"] or (order.get("id") if isinstance(order, dict) else None),
334
+ "filled": norm["filled"],
335
+ "avg_price": norm["avg_price"],
336
+ "cost": norm["cost"],
337
+ "fee": norm["fee"],
338
+ "fee_currency": norm["fee_currency"],
339
+ "complete": norm["complete"],
340
+ }
341
+ _journal(jpath, entry)
342
+ return entry
343
+ except Exception as e:
344
+ _journal(
345
+ jpath,
346
+ {**base_entry, "action": "LIVE_ORDER_FAILED", "error": str(e)},
347
+ )
348
+ logger.error("Order failed: %s", e)
349
+ raise
350
+
351
+
352
+ def query_order(
353
+ symbol: str,
354
+ client_order_id: str,
355
+ journal_path: str | Path | None = None,
356
+ cfg: dict | None = None,
357
+ ) -> dict[str, Any] | None:
358
+ """Look up an order by client_order_id. Dry-run returns None. Never places orders."""
359
+ cfg = cfg or bridge_config(journal_path)
360
+ if cfg["dry_run"]:
361
+ return None
362
+ if not cfg.get("approval_ok", False):
363
+ return None
364
+ client = get_client(cfg)
365
+ ccxt_symbol = to_ccxt_symbol(symbol)
366
+ order = None
367
+ try:
368
+ order = client.fetch_order(client_order_id, ccxt_symbol, {"clientOrderId": client_order_id})
369
+ except Exception:
370
+ try:
371
+ order = client.fetch_order(None, ccxt_symbol, {"clientOrderId": client_order_id})
372
+ except Exception as e:
373
+ logger.warning("query_order %s %s failed: %s", client_order_id, ccxt_symbol, e)
374
+ return None
375
+ if not order:
376
+ return None
377
+ norm = normalize_ccxt_order(order)
378
+ status = str(norm["status"] or "unknown").lower()
379
+ return {
380
+ "action": "LIVE_ORDER_QUERY",
381
+ "status": status,
382
+ "symbol": to_venue_symbol(symbol),
383
+ "side": (order.get("side") or "").lower(),
384
+ "quantity": float(order.get("amount") or 0.0),
385
+ "filled": norm["filled"],
386
+ "avg_price": norm["avg_price"],
387
+ "cost": norm["cost"],
388
+ "fee": norm["fee"],
389
+ "fee_currency": norm["fee_currency"],
390
+ "complete": norm["complete"],
391
+ "order_id": norm["order_id"] or order.get("id"),
392
+ "client_order_id": client_order_id,
393
+ "open": status in ("open", "pending", "new", "active"),
394
+ }
395
+
396
+
397
+ def cancel_order(
398
+ symbol: str,
399
+ client_order_id: str,
400
+ cfg: dict | None = None,
401
+ ) -> bool:
402
+ cfg = cfg or bridge_config()
403
+ if cfg["dry_run"]:
404
+ return False
405
+ client = get_client(cfg)
406
+ try:
407
+ client.cancel_order(client_order_id, to_ccxt_symbol(symbol), {"clientOrderId": client_order_id})
408
+ return True
409
+ except Exception as e:
410
+ logger.warning("cancel_order %s failed: %s", client_order_id, e)
411
+ return False
412
+
413
+
414
+ def fetch_l1(
415
+ symbol: str,
416
+ cfg: dict | None = None,
417
+ journal_path: str | Path | None = None,
418
+ ) -> dict[str, float]:
419
+ """Best bid/ask/mid from fetch_ticker. Never journals. Raises if L1 missing."""
420
+ cfg = cfg or bridge_config(journal_path)
421
+ client = get_client(cfg)
422
+ ccxt_symbol = to_ccxt_symbol(symbol)
423
+ ticker = client.fetch_ticker(ccxt_symbol)
424
+ bid = _fnum(ticker.get("bid") if isinstance(ticker, dict) else None)
425
+ ask = _fnum(ticker.get("ask") if isinstance(ticker, dict) else None)
426
+ if bid is None or ask is None or bid <= 0 or ask <= 0:
427
+ raise ValueError(f"missing bid/ask for {ccxt_symbol}")
428
+ return {"bid": bid, "ask": ask, "mid": (bid + ask) / 2.0}
429
+
430
+
431
+ def limit_buy_ioc(symbol: str, quantity: float, price: float, **kw) -> dict:
432
+ return place_order(symbol, "buy", quantity, order_type="limit", price=price, **kw)
433
+
434
+
435
+ def market_buy(symbol: str, quantity: float, **kw) -> dict:
436
+ return place_order(symbol, "buy", quantity, order_type="market", **kw)
437
+
438
+
439
+ def market_sell(symbol: str, quantity: float, reduce_only: bool = True, **kw) -> dict:
440
+ return place_order(
441
+ symbol, "sell", quantity, order_type="market", reduce_only=reduce_only, **kw
442
+ )
443
+
444
+
445
+ def close_long(symbol: str, quantity: float, **kw) -> dict:
446
+ return market_sell(symbol, quantity, reduce_only=True, **kw)
447
+
448
+
449
+ def get_balance(cfg: dict | None = None) -> dict:
450
+ cfg = cfg or bridge_config()
451
+ if cfg["dry_run"]:
452
+ return {"USD": {"free": 0.0, "total": 0.0}, "note": "DRY-RUN — no balance fetch"}
453
+ client = get_client(cfg)
454
+ return client.fetch_balance()
455
+
456
+
457
+ def status(cfg: dict | None = None) -> dict:
458
+ cfg = cfg or bridge_config()
459
+ return {
460
+ "dry_run": cfg["dry_run"],
461
+ "live_requested": cfg.get("live_requested"),
462
+ "approval_ok": cfg.get("approval_ok"),
463
+ "approval_reason": cfg.get("approval_reason"),
464
+ "venue": "COINBASE_SPOT",
465
+ "leverage": cfg["leverage"],
466
+ "live_trading_enabled": not cfg["dry_run"],
467
+ "has_keys": bool(cfg.get("api_key") and cfg.get("api_secret")),
468
+ }
469
+
470
+
471
+ # Back-compat module-level CONFIG snapshot
472
+ CONFIG = bridge_config()
473
+
474
+
475
+ if __name__ == "__main__":
476
+ print("ccxt bridge status:", status())
477
+ print(place_order("BTC-USD", "buy", 0.001, price=60000.0))
478
+ print(place_order("BTC-USD", "sell", 0.001, price=60000.0, reduce_only=True))
@@ -0,0 +1,3 @@
1
+ """Isolated CFM / CDE research package. Not spot DNA. Not the live sleeve. Not paper/live."""
2
+
3
+ STRATEGY_FAMILY = "cfm_research"
stratforge/cfm/bars.py ADDED
@@ -0,0 +1,115 @@
1
+ """5m parquet → 4h proxy bars. Own fold. Do not import short.replay or live_data_feed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ RAW_DIR = ROOT / "data" / "raw"
13
+ CFM_DIR = ROOT / "data" / "cfm"
14
+
15
+
16
+ def _frame_to_bars(df: pd.DataFrame, freq: str) -> list[dict]:
17
+ out = pd.DataFrame(
18
+ {
19
+ "open": df["open"].resample(freq).first(),
20
+ "high": df["high"].resample(freq).max(),
21
+ "low": df["low"].resample(freq).min(),
22
+ "close": df["close"].resample(freq).last(),
23
+ "volume": df["volume"].resample(freq).sum(),
24
+ }
25
+ ).dropna()
26
+ bars: list[dict] = []
27
+ for t, row in out.iterrows():
28
+ bars.append(
29
+ {
30
+ "ts": int(t.timestamp() * 1_000_000_000),
31
+ "open": float(row["open"]),
32
+ "high": float(row["high"]),
33
+ "low": float(row["low"]),
34
+ "close": float(row["close"]),
35
+ "volume": float(row["volume"]),
36
+ }
37
+ )
38
+ return bars
39
+
40
+
41
+ @lru_cache(maxsize=16)
42
+ def load_cde_4h(symbol: str) -> list[dict]:
43
+ path = CFM_DIR / f"{symbol.upper()}_CDE_1h.parquet"
44
+ if not path.is_file():
45
+ return []
46
+ df = pd.read_parquet(path)
47
+ if df.empty:
48
+ return []
49
+ df = df.copy()
50
+ df["ts"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
51
+ df = df.set_index("ts").sort_index()
52
+ return _frame_to_bars(df, "4h")
53
+
54
+
55
+ def _to_dt(s: str | datetime | None) -> datetime | None:
56
+ if s is None:
57
+ return None
58
+ if isinstance(s, datetime):
59
+ return s if s.tzinfo else s.replace(tzinfo=timezone.utc)
60
+ return datetime.strptime(str(s)[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc)
61
+
62
+
63
+ @lru_cache(maxsize=16)
64
+ def load_4h_all(symbol: str, raw_dir: str = "") -> list[dict]:
65
+ return load_4h_bars(symbol, None, None, raw_dir)
66
+
67
+
68
+ @lru_cache(maxsize=64)
69
+ def load_4h_bars(
70
+ symbol: str,
71
+ start: str | None = None,
72
+ end: str | None = None,
73
+ raw_dir: str = "",
74
+ ) -> list[dict]:
75
+ path = Path(raw_dir or RAW_DIR) / f"{symbol.upper()}_USD_5m.parquet"
76
+ if not path.is_file():
77
+ return []
78
+ df = pd.read_parquet(path)
79
+ if df.empty:
80
+ return []
81
+ df = df.copy()
82
+ df["ts"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
83
+ start_dt = _to_dt(start)
84
+ end_dt = _to_dt(end)
85
+ if end_dt is not None:
86
+ end_dt = end_dt.replace(hour=23, minute=59, second=59)
87
+ if start_dt is not None:
88
+ df = df[df["ts"] >= start_dt]
89
+ if end_dt is not None:
90
+ df = df[df["ts"] <= end_dt]
91
+ if df.empty:
92
+ return []
93
+ df = df.set_index("ts").sort_index()
94
+ out = pd.DataFrame(
95
+ {
96
+ "open": df["open"].resample("4h").first(),
97
+ "high": df["high"].resample("4h").max(),
98
+ "low": df["low"].resample("4h").min(),
99
+ "close": df["close"].resample("4h").last(),
100
+ "volume": df["volume"].resample("4h").sum(),
101
+ }
102
+ ).dropna()
103
+ bars: list[dict] = []
104
+ for t, row in out.iterrows():
105
+ bars.append(
106
+ {
107
+ "ts": int(t.timestamp() * 1_000_000_000),
108
+ "open": float(row["open"]),
109
+ "high": float(row["high"]),
110
+ "low": float(row["low"]),
111
+ "close": float(row["close"]),
112
+ "volume": float(row["volume"]),
113
+ }
114
+ )
115
+ return bars