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
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env python3
2
+ """Download Coinbase Advanced Trade public candles for CDE nanos (BIP/ETP/…).
3
+
4
+ Public GET /api/v3/brokerage/market/products/{id}/candles
5
+ Research only. No keys. Not a live adapter.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ import urllib.parse
13
+ import urllib.request
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+
17
+ import pandas as pd
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+ OUT = ROOT / "data" / "cfm"
21
+ UA = {"User-Agent": "pro-trader-cfm-research/1.0"}
22
+ PRODUCTS = {
23
+ "BTC": "BIP-20DEC30-CDE",
24
+ "ETH": "ETP-20DEC30-CDE",
25
+ "SOL": "SLP-20DEC30-CDE",
26
+ "XRP": "XPP-20DEC30-CDE",
27
+ }
28
+
29
+
30
+ def _get(url: str) -> dict:
31
+ req = urllib.request.Request(url, headers=UA)
32
+ for attempt in range(5):
33
+ try:
34
+ with urllib.request.urlopen(req, timeout=30) as r:
35
+ return json.loads(r.read().decode())
36
+ except Exception:
37
+ if attempt == 4:
38
+ raise
39
+ time.sleep(2 + attempt * 3)
40
+ return {}
41
+
42
+
43
+ def fetch_chunk(product_id: str, start: int, end: int, gran: str = "ONE_HOUR") -> list[dict]:
44
+ url = (
45
+ f"https://api.coinbase.com/api/v3/brokerage/market/products/"
46
+ f"{urllib.parse.quote(product_id, safe='')}/candles"
47
+ f"?start={int(start)}&end={int(end)}&granularity={gran}&limit=300"
48
+ )
49
+ js = _get(url)
50
+ return list(js.get("candles") or [])
51
+
52
+
53
+ def download_hourly(symbol: str, product_id: str) -> Path:
54
+ OUT.mkdir(parents=True, exist_ok=True)
55
+ path = OUT / f"{symbol}_CDE_1h.parquet"
56
+ now = int(time.time())
57
+ have_max = 0
58
+ rows: list[dict] = []
59
+ if path.is_file():
60
+ old = pd.read_parquet(path)
61
+ if not old.empty:
62
+ have_max = int(old["timestamp"].max() // 1000)
63
+ rows = old.to_dict("records")
64
+ print(f"{symbol} resume after {datetime.fromtimestamp(have_max, timezone.utc)}")
65
+ t = now
66
+ empty_streak = 0
67
+ while t > 1_700_000_000: # 2023-ish floor; listing is 2025
68
+ a = t - 12 * 86400
69
+ if have_max and t <= have_max + 3600:
70
+ break
71
+ chunk = fetch_chunk(product_id, max(a, have_max + 1) if have_max else a, t)
72
+ time.sleep(0.35)
73
+ if not chunk:
74
+ empty_streak += 1
75
+ print(f"{symbol} empty {datetime.fromtimestamp(a, timezone.utc).date()}")
76
+ if empty_streak >= 3:
77
+ break
78
+ t = a
79
+ continue
80
+ empty_streak = 0
81
+ ts_list = [int(c["start"]) for c in chunk]
82
+ print(
83
+ f"{symbol} {datetime.fromtimestamp(min(ts_list), timezone.utc)} -> "
84
+ f"{datetime.fromtimestamp(max(ts_list), timezone.utc)} n={len(chunk)}"
85
+ )
86
+ for c in chunk:
87
+ rows.append(
88
+ {
89
+ "timestamp": int(c["start"]) * 1000,
90
+ "open": float(c["open"]),
91
+ "high": float(c["high"]),
92
+ "low": float(c["low"]),
93
+ "close": float(c["close"]),
94
+ "volume": float(c["volume"]),
95
+ "product_id": product_id,
96
+ }
97
+ )
98
+ t = min(ts_list)
99
+ if len(chunk) < 50 and t < now - 86400:
100
+ # listing edge
101
+ more = fetch_chunk(product_id, t - 86400, t, "ONE_HOUR")
102
+ if len(more) <= 1:
103
+ break
104
+ df = pd.DataFrame(rows)
105
+ if df.empty:
106
+ print(f"{symbol} no rows")
107
+ return path
108
+ df = df.drop_duplicates(subset=["timestamp"]).sort_values("timestamp")
109
+ df.to_parquet(path, index=False)
110
+ t0 = datetime.fromtimestamp(int(df["timestamp"].iloc[0]) / 1000, timezone.utc)
111
+ t1 = datetime.fromtimestamp(int(df["timestamp"].iloc[-1]) / 1000, timezone.utc)
112
+ print(f"wrote {path} rows={len(df)} {t0} -> {t1}")
113
+ return path
114
+
115
+
116
+ def snapshot_venue() -> Path:
117
+ out = OUT / "live_snapshot.json"
118
+ snap: dict = {"ts_unix": int(time.time()), "products": {}}
119
+ for sym, pid in PRODUCTS.items():
120
+ js = _get(f"https://api.coinbase.com/api/v3/brokerage/market/products/{urllib.parse.quote(pid, safe='')}")
121
+ fpd = js.get("future_product_details") or {}
122
+ snap["products"][sym] = {
123
+ "product_id": pid,
124
+ "price": js.get("price"),
125
+ "funding_rate": fpd.get("funding_rate"),
126
+ "funding_interval": fpd.get("funding_interval"),
127
+ "funding_time": fpd.get("funding_time"),
128
+ "intraday_margin_rate": fpd.get("intraday_margin_rate"),
129
+ "overnight_margin_rate": fpd.get("overnight_margin_rate"),
130
+ "contract_size": fpd.get("contract_size"),
131
+ "open_interest": fpd.get("open_interest"),
132
+ "index_price": fpd.get("index_price"),
133
+ "settlement_price": fpd.get("settlement_price"),
134
+ }
135
+ time.sleep(0.2)
136
+ out.write_text(json.dumps(snap, indent=2) + "\n")
137
+ print("wrote", out)
138
+ return out
139
+
140
+
141
+ def _products() -> dict[str, str]:
142
+ uni = ROOT / "config" / "cfm" / "universe_cde.json"
143
+ if uni.is_file():
144
+ raw = json.loads(uni.read_text())
145
+ return {k: v["product_id"] for k, v in (raw.get("symbols") or {}).items()}
146
+ return dict(PRODUCTS)
147
+
148
+
149
+ def main() -> None:
150
+ products = _products()
151
+ global PRODUCTS
152
+ PRODUCTS = products
153
+ snapshot_venue()
154
+ for sym, pid in products.items():
155
+ download_hourly(sym, pid)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
@@ -0,0 +1,14 @@
1
+ """Hard wall: cfm/ must not import the spot host or the short book."""
2
+
3
+ FORBIDDEN = (
4
+ "strategies",
5
+ "ccxt_bridge",
6
+ "risk_limits",
7
+ "short",
8
+ "paper_executor",
9
+ "live_node",
10
+ "research_replay",
11
+ "live_executor",
12
+ "live_reconcile",
13
+ "signal_engine",
14
+ )
@@ -0,0 +1,332 @@
1
+ """CFM-style futures ledger (long and short).
2
+
3
+ Equity = cash + unrealized. Opening posts initial margin and a fee; it does
4
+ not spend the full notional. Funding is a constant debit (never a credit).
5
+ Overnight IM default 25% (4x). 10x advertised leverage is not used on 4h holds.
6
+
7
+ PAPER / RESEARCH ONLY. No exchange calls.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+
14
+
15
+ DEFAULT_MULT = {"BTC": 0.01, "ETH": 0.10, "SOL": 5.0, "XRP": 500.0}
16
+
17
+
18
+ @dataclass
19
+ class Lot:
20
+ symbol: str
21
+ side: str # LONG | SHORT
22
+ qty: float
23
+ entry: float
24
+ ts: int
25
+ margin: float
26
+ fee_open: float
27
+ stop_px: float | None = None
28
+
29
+
30
+ @dataclass
31
+ class FuturesLedger:
32
+ start_usd: float
33
+ max_leverage: float = 4.0
34
+ fee_rate: float = 0.0004
35
+ funding_per_8h: float = 0.00003
36
+ funding_interval_hours: float = 8.0
37
+ maintenance_frac_of_im: float = 0.50
38
+ integer_contracts: bool = True
39
+ multipliers: dict[str, float] = field(default_factory=lambda: dict(DEFAULT_MULT))
40
+ cash: float = 0.0
41
+ lots: dict[str, Lot] = field(default_factory=dict)
42
+ last_price: dict[str, float] = field(default_factory=dict)
43
+ last_ts: int = 0
44
+ last_funding_ts: int = 0
45
+ trades: int = 0
46
+ wins: int = 0
47
+ losses: int = 0
48
+ liquidations: int = 0
49
+ stop_exits: int = 0
50
+ fees_paid: float = 0.0
51
+ funding_paid: float = 0.0
52
+ closed: list[dict] = field(default_factory=list)
53
+ events: list[dict] = field(default_factory=list)
54
+
55
+ def __post_init__(self) -> None:
56
+ self.cash = float(self.start_usd)
57
+ if float(self.max_leverage) > 4.0 + 1e-9:
58
+ raise ValueError("research max_leverage cannot exceed overnight 4x")
59
+
60
+ def update_price(self, symbol: str, price: float, ts: int = 0) -> None:
61
+ self.last_price[symbol.upper()] = float(price)
62
+ if ts:
63
+ self.last_ts = int(ts)
64
+
65
+ def unrealized(self, symbol: str | None = None) -> float:
66
+ total = 0.0
67
+ items = [(symbol.upper(), self.lots[symbol.upper()])] if symbol else list(self.lots.items())
68
+ for sym, lot in items:
69
+ mark = float(self.last_price.get(sym, lot.entry))
70
+ total += self._upnl(lot, mark)
71
+ return float(total)
72
+
73
+ @staticmethod
74
+ def _upnl(lot: Lot, mark: float) -> float:
75
+ if lot.side == "SHORT":
76
+ return (lot.entry - mark) * lot.qty
77
+ return (mark - lot.entry) * lot.qty
78
+
79
+ def margin_used(self) -> float:
80
+ return float(sum(l.margin for l in self.lots.values()))
81
+
82
+ def equity(self) -> float:
83
+ return float(self.cash + self.unrealized())
84
+
85
+ def available(self) -> float:
86
+ return float(self.equity() - self.margin_used())
87
+
88
+ def im_pct(self) -> float:
89
+ return 1.0 / max(float(self.max_leverage), 1e-9)
90
+
91
+ def mm_pct_notional(self) -> float:
92
+ return self.im_pct() * float(self.maintenance_frac_of_im)
93
+
94
+ def floor_qty(self, symbol: str, qty: float) -> float:
95
+ if not self.integer_contracts:
96
+ return max(0.0, float(qty))
97
+ mult = float(self.multipliers.get(symbol.upper()) or 0.0)
98
+ if mult <= 0:
99
+ return 0.0
100
+ n = int(abs(qty) / mult)
101
+ return float(n * mult)
102
+
103
+ def apply_funding(self, ts: int) -> None:
104
+ if self.last_funding_ts <= 0:
105
+ self.last_funding_ts = int(ts)
106
+ return
107
+ elapsed = int(ts) - self.last_funding_ts
108
+ hours = max(float(self.funding_interval_hours), 1e-9)
109
+ step = int(hours * 3600 * 1_000_000_000)
110
+ if elapsed < step:
111
+ return
112
+ n_steps = elapsed // step
113
+ rate = float(self.funding_per_8h) * n_steps
114
+ charged = 0.0
115
+ for sym, lot in self.lots.items():
116
+ mark = float(self.last_price.get(sym, lot.entry))
117
+ charged += abs(lot.qty * mark) * rate
118
+ if charged > 0:
119
+ self.cash -= charged
120
+ self.funding_paid += charged
121
+ self.events.append({"type": "FUNDING", "ts": int(ts), "debit": charged, "steps": int(n_steps)})
122
+ self.last_funding_ts += n_steps * step
123
+
124
+ def _liq_price(self, lot: Lot) -> float | None:
125
+ """Price where equity = MM * current notional, other lots marked at last."""
126
+ mm = self.mm_pct_notional()
127
+ others = 0.0
128
+ for sym, l in self.lots.items():
129
+ if l is lot:
130
+ continue
131
+ others += self._upnl(l, float(self.last_price.get(sym, l.entry)))
132
+ # cash + others + upnl(p) = mm * qty * p
133
+ # long: cash+others + (p-entry)*q = mm*q*p
134
+ q = lot.qty
135
+ if q <= 0:
136
+ return None
137
+ base = self.cash + others
138
+ if lot.side == "LONG":
139
+ # base - entry*q + p*q = mm*q*p => base - entry*q = p*q*(mm-1)
140
+ den = q * (mm - 1.0)
141
+ if abs(den) < 1e-18:
142
+ return None
143
+ return (base - lot.entry * q) / den
144
+ # short: base + (entry-p)*q = mm*q*p => base + entry*q = p*q*(mm+1)
145
+ den = q * (mm + 1.0)
146
+ if abs(den) < 1e-18:
147
+ return None
148
+ return (base + lot.entry * q) / den
149
+
150
+ def maybe_liquidate_bar(self, symbol: str, high: float, low: float, ts: int) -> dict | None:
151
+ sym = symbol.upper()
152
+ lot = self.lots.get(sym)
153
+ if lot is None:
154
+ return None
155
+ lp = self._liq_price(lot)
156
+ if lp is None or lp <= 0:
157
+ return None
158
+ hit = False
159
+ px = None
160
+ if lot.side == "LONG" and low <= lp:
161
+ hit, px = True, max(float(low), float(lp))
162
+ elif lot.side == "SHORT" and high >= lp:
163
+ hit, px = True, min(float(high), float(lp))
164
+ if not hit or px is None or px <= 0:
165
+ return None
166
+ self.update_price(sym, px, ts)
167
+ rec = self.close(sym, px, ts, reason="liquidation")
168
+ if rec:
169
+ rec["liquidation"] = True
170
+ self.liquidations += 1
171
+ return rec
172
+
173
+ def maybe_stop_bar(self, symbol: str, high: float, low: float, ts: int) -> dict | None:
174
+ sym = symbol.upper()
175
+ lot = self.lots.get(sym)
176
+ if lot is None or lot.stop_px is None:
177
+ return None
178
+ sp = float(lot.stop_px)
179
+ hit = False
180
+ px = None
181
+ if lot.side == "LONG" and low <= sp:
182
+ hit, px = True, sp
183
+ elif lot.side == "SHORT" and high >= sp:
184
+ hit, px = True, sp
185
+ if not hit or px is None:
186
+ return None
187
+ self.update_price(sym, px, ts)
188
+ rec = self.close(sym, px, ts, reason="stop")
189
+ if rec:
190
+ rec["stop"] = True
191
+ self.stop_exits += 1
192
+ return rec
193
+
194
+ def close(self, symbol: str, price: float, ts: int, reason: str) -> dict | None:
195
+ sym = symbol.upper()
196
+ lot = self.lots.pop(sym, None)
197
+ if lot is None:
198
+ return None
199
+ px = float(price)
200
+ pnl = self._upnl(lot, px)
201
+ fee = abs(lot.qty * px) * float(self.fee_rate)
202
+ self.cash += pnl - fee
203
+ self.fees_paid += fee
204
+ self.trades += 1
205
+ if pnl - fee >= 0:
206
+ self.wins += 1
207
+ else:
208
+ self.losses += 1
209
+ rec = {
210
+ "type": "CLOSE",
211
+ "symbol": sym,
212
+ "side": lot.side,
213
+ "qty": lot.qty,
214
+ "entry": lot.entry,
215
+ "exit": px,
216
+ "pnl": pnl - fee,
217
+ "fee": fee,
218
+ "reason": reason,
219
+ "ts": int(ts),
220
+ }
221
+ self.closed.append(rec)
222
+ self.events.append(rec)
223
+ return rec
224
+
225
+ def open_pos(
226
+ self,
227
+ symbol: str,
228
+ side: str,
229
+ price: float,
230
+ ts: int,
231
+ target_notional: float,
232
+ reason: str,
233
+ stop_px: float | None = None,
234
+ ) -> dict | None:
235
+ sym = symbol.upper()
236
+ side = side.upper()
237
+ if side not in ("LONG", "SHORT"):
238
+ return None
239
+ if sym in self.lots:
240
+ return None
241
+ px = float(price)
242
+ if px <= 0 or target_notional <= 0:
243
+ return None
244
+ eq = self.equity()
245
+ if eq <= 0:
246
+ return None
247
+ fee_pad = 1.0 + float(self.fee_rate)
248
+ max_notional = max(0.0, self.available() * float(self.max_leverage) / fee_pad)
249
+ notional = min(float(target_notional), max_notional)
250
+ qty = self.floor_qty(sym, notional / px)
251
+ if qty <= 0:
252
+ return None
253
+ notional = qty * px
254
+ fee = notional * float(self.fee_rate)
255
+ margin = notional / max(float(self.max_leverage), 1e-9)
256
+ if fee + 1e-9 > self.cash:
257
+ return None
258
+ if margin > self.available() + 1e-6:
259
+ return None
260
+ self.cash -= fee
261
+ self.fees_paid += fee
262
+ self.lots[sym] = Lot(
263
+ symbol=sym,
264
+ side=side,
265
+ qty=qty,
266
+ entry=px,
267
+ ts=int(ts),
268
+ margin=margin,
269
+ fee_open=fee,
270
+ stop_px=stop_px,
271
+ )
272
+ rec = {
273
+ "type": "OPEN",
274
+ "symbol": sym,
275
+ "side": side,
276
+ "qty": qty,
277
+ "price": px,
278
+ "margin": margin,
279
+ "fee": fee,
280
+ "reason": reason,
281
+ "ts": int(ts),
282
+ }
283
+ self.events.append(rec)
284
+ self.trades += 1
285
+ return rec
286
+
287
+ def flatten_all(self, prices: dict[str, float], ts: int, reason: str) -> None:
288
+ for sym in list(self.lots.keys()):
289
+ px = float(prices.get(sym, self.last_price.get(sym, 0.0)))
290
+ if px > 0:
291
+ self.close(sym, px, ts, reason=reason)
292
+
293
+ def set_stop(self, symbol: str, stop_px: float | None) -> None:
294
+ lot = self.lots.get(symbol.upper())
295
+ if lot is not None:
296
+ lot.stop_px = stop_px
297
+
298
+ def rebalance(
299
+ self,
300
+ symbol: str,
301
+ side: str,
302
+ price: float,
303
+ ts: int,
304
+ target_notional: float,
305
+ reason: str,
306
+ stop_px: float | None = None,
307
+ ) -> None:
308
+ """Match target side/notional. Closes and reopens when side or size changes by >= 1 lot."""
309
+ sym = symbol.upper()
310
+ side = side.upper()
311
+ px = float(price)
312
+ self.update_price(sym, px, ts)
313
+ if side == "FLAT" or target_notional <= 0:
314
+ if sym in self.lots:
315
+ self.close(sym, px, ts, reason=reason + "_flat")
316
+ return
317
+ lot = self.lots.get(sym)
318
+ want_qty = self.floor_qty(sym, float(target_notional) / px)
319
+ if want_qty <= 0:
320
+ if lot:
321
+ self.close(sym, px, ts, reason=reason + "_flat")
322
+ return
323
+ if lot and lot.side == side:
324
+ mult = float(self.multipliers.get(sym) or 0.0) or 1.0
325
+ if abs(lot.qty - want_qty) < 0.5 * mult:
326
+ lot.stop_px = stop_px
327
+ lot.margin = (lot.qty * px) / max(float(self.max_leverage), 1e-9)
328
+ return
329
+ self.close(sym, px, ts, reason=reason + "_resize")
330
+ elif lot:
331
+ self.close(sym, px, ts, reason=reason + "_flip")
332
+ self.open_pos(sym, side, px, ts, want_qty * px, reason=reason, stop_px=stop_px)