stratforge 0.1.0__tar.gz
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.
- stratforge-0.1.0/LICENSE +21 -0
- stratforge-0.1.0/PKG-INFO +51 -0
- stratforge-0.1.0/README.md +35 -0
- stratforge-0.1.0/pyproject.toml +27 -0
- stratforge-0.1.0/setup.cfg +4 -0
- stratforge-0.1.0/stratforge/__init__.py +17 -0
- stratforge-0.1.0/stratforge/ccxt_bridge.py +478 -0
- stratforge-0.1.0/stratforge/cfm/__init__.py +3 -0
- stratforge-0.1.0/stratforge/cfm/bars.py +115 -0
- stratforge-0.1.0/stratforge/cfm/download_cde.py +159 -0
- stratforge-0.1.0/stratforge/cfm/isolation.py +14 -0
- stratforge-0.1.0/stratforge/cfm/ledger.py +332 -0
- stratforge-0.1.0/stratforge/cfm/replay.py +224 -0
- stratforge-0.1.0/stratforge/cfm/run_cde_dozen.py +111 -0
- stratforge-0.1.0/stratforge/cfm/run_cde_replay.py +107 -0
- stratforge-0.1.0/stratforge/cfm/run_cde_universe.py +112 -0
- stratforge-0.1.0/stratforge/cfm/run_research.py +110 -0
- stratforge-0.1.0/stratforge/cfm/run_round2.py +78 -0
- stratforge-0.1.0/stratforge/cfm/run_validate.py +196 -0
- stratforge-0.1.0/stratforge/cfm/strats.py +427 -0
- stratforge-0.1.0/stratforge/cfm/strats_cde.py +681 -0
- stratforge-0.1.0/stratforge/cfm/test_isolation.py +43 -0
- stratforge-0.1.0/stratforge/cfm/test_ledger.py +76 -0
- stratforge-0.1.0/stratforge/cfm/test_venue.py +36 -0
- stratforge-0.1.0/stratforge/cfm/venue.py +36 -0
- stratforge-0.1.0/stratforge/live.py +15 -0
- stratforge-0.1.0/stratforge/paper_family.py +15 -0
- stratforge-0.1.0/stratforge/risk_limits.py +337 -0
- stratforge-0.1.0/stratforge/short/__init__.py +5 -0
- stratforge-0.1.0/stratforge/short/backfill_spot_gap.py +90 -0
- stratforge-0.1.0/stratforge/short/engine.py +227 -0
- stratforge-0.1.0/stratforge/short/indicators.py +58 -0
- stratforge-0.1.0/stratforge/short/ledger.py +273 -0
- stratforge-0.1.0/stratforge/short/regime_occupancy.py +156 -0
- stratforge-0.1.0/stratforge/short/regime_stretches.py +50 -0
- stratforge-0.1.0/stratforge/short/replay.py +390 -0
- stratforge-0.1.0/stratforge/short/run_backtest.py +153 -0
- stratforge-0.1.0/stratforge/short/run_regime_gates.py +105 -0
- stratforge-0.1.0/stratforge/short/run_tsmom12.py +263 -0
- stratforge-0.1.0/stratforge/short/test_short.py +269 -0
- stratforge-0.1.0/stratforge/short/test_tsmom.py +139 -0
- stratforge-0.1.0/stratforge/short/tsmom.py +160 -0
- stratforge-0.1.0/stratforge/state.py +20 -0
- stratforge-0.1.0/stratforge/strategies/bar_apply.py +36 -0
- stratforge-0.1.0/stratforge/strategies/bar_freshness.py +53 -0
- stratforge-0.1.0/stratforge/strategies/buy_protect.py +78 -0
- stratforge-0.1.0/stratforge/strategies/config_load.py +82 -0
- stratforge-0.1.0/stratforge/strategies/daily_data_feed.py +341 -0
- stratforge-0.1.0/stratforge/strategies/day_risk.py +51 -0
- stratforge-0.1.0/stratforge/strategies/display_time.py +72 -0
- stratforge-0.1.0/stratforge/strategies/live_data_feed.py +353 -0
- stratforge-0.1.0/stratforge/strategies/live_executor.py +1346 -0
- stratforge-0.1.0/stratforge/strategies/live_node.py +430 -0
- stratforge-0.1.0/stratforge/strategies/live_reconcile.py +358 -0
- stratforge-0.1.0/stratforge/strategies/node_lock.py +48 -0
- stratforge-0.1.0/stratforge/strategies/paper_executor.py +492 -0
- stratforge-0.1.0/stratforge/strategies/paper_family_node.py +304 -0
- stratforge-0.1.0/stratforge/strategies/qty_precision.py +44 -0
- stratforge-0.1.0/stratforge/strategies/research_families.py +335 -0
- stratforge-0.1.0/stratforge/strategies/research_replay.py +681 -0
- stratforge-0.1.0/stratforge/strategies/signal_engine.py +606 -0
- stratforge-0.1.0/stratforge/strategies/universe.py +60 -0
- stratforge-0.1.0/stratforge/viz/__init__.py +1 -0
- stratforge-0.1.0/stratforge/viz/projector.py +402 -0
- stratforge-0.1.0/stratforge.egg-info/PKG-INFO +51 -0
- stratforge-0.1.0/stratforge.egg-info/SOURCES.txt +92 -0
- stratforge-0.1.0/stratforge.egg-info/dependency_links.txt +1 -0
- stratforge-0.1.0/stratforge.egg-info/requires.txt +6 -0
- stratforge-0.1.0/stratforge.egg-info/top_level.txt +1 -0
- stratforge-0.1.0/tests/test_admission.py +98 -0
- stratforge-0.1.0/tests/test_buy_protect.py +120 -0
- stratforge-0.1.0/tests/test_buy_protect_live.py +404 -0
- stratforge-0.1.0/tests/test_ccxt_buy_protect.py +210 -0
- stratforge-0.1.0/tests/test_chaos_journal.py +147 -0
- stratforge-0.1.0/tests/test_coinbase_maintenance.py +221 -0
- stratforge-0.1.0/tests/test_config_load.py +116 -0
- stratforge-0.1.0/tests/test_daily_sre.py +46 -0
- stratforge-0.1.0/tests/test_display_time.py +102 -0
- stratforge-0.1.0/tests/test_donch_paper.py +219 -0
- stratforge-0.1.0/tests/test_entry_rank.py +258 -0
- stratforge-0.1.0/tests/test_feed_emit_gate.py +130 -0
- stratforge-0.1.0/tests/test_live_reconcile_parse.py +133 -0
- stratforge-0.1.0/tests/test_p0_live_safety.py +845 -0
- stratforge-0.1.0/tests/test_p1_ops.py +137 -0
- stratforge-0.1.0/tests/test_paper_executor.py +331 -0
- stratforge-0.1.0/tests/test_phase2_execution.py +262 -0
- stratforge-0.1.0/tests/test_post_nautilus_ops.py +81 -0
- stratforge-0.1.0/tests/test_qty_precision.py +44 -0
- stratforge-0.1.0/tests/test_risk_limits.py +197 -0
- stratforge-0.1.0/tests/test_signal_parity.py +92 -0
- stratforge-0.1.0/tests/test_slow_ema_underwater_exit.py +90 -0
- stratforge-0.1.0/tests/test_thin_host_cutover.py +146 -0
- stratforge-0.1.0/tests/test_viz_projector.py +349 -0
- stratforge-0.1.0/tests/test_viz_web.py +70 -0
stratforge-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jesse Griffin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stratforge
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic trading strategies: backtest, compare, promote to paper and live.
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: ccxt>=4.5.0
|
|
10
|
+
Requires-Dist: requests>=2.32.0
|
|
11
|
+
Requires-Dist: pandas>=2.2.0
|
|
12
|
+
Requires-Dist: numpy>=2.0.0
|
|
13
|
+
Requires-Dist: pyarrow>=17.0.0
|
|
14
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# stratforge
|
|
18
|
+
|
|
19
|
+
Create deterministic trading strategies with an AI agent, backtest them, compare them, and promote winning versions onto paper and live portfolios.
|
|
20
|
+
|
|
21
|
+
MIT license. A clone does not trade. Live orders need an API key, a portfolio id, and a `data/LIVE_APPROVED` file that you create. There is no silent portfolio default.
|
|
22
|
+
|
|
23
|
+
## What is in this repo
|
|
24
|
+
|
|
25
|
+
- Decision engine, public candles, paper simulator, and research replay.
|
|
26
|
+
- Order path: `ccxt_bridge`, `live_executor`, reconcile, buy-protect, `live_node`.
|
|
27
|
+
- Strategy families: trend rotation, Donchian, `short/` (`tsmom12_weekly`; bear-regime configs are rejected variants), `cfm/` (CDE nanos, isolated).
|
|
28
|
+
- Viz source. Snapshots and passwords are not in git.
|
|
29
|
+
- Generic systemd and nginx templates in `deploy/`. They use `%h` or a variable you set. They do not name a host.
|
|
30
|
+
|
|
31
|
+
## What stays on the machine that runs a book
|
|
32
|
+
|
|
33
|
+
Journals, the candle warehouse, `.env.live`, `data/LIVE_APPROVED`, halt files, viz snapshots, and htpasswd. Do not commit them.
|
|
34
|
+
|
|
35
|
+
## Run paper
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
git clone git@github.com:jag3773/stratforge.git
|
|
39
|
+
cd stratforge
|
|
40
|
+
uv venv --python 3.13 .venv
|
|
41
|
+
uv pip install -r requirements.txt
|
|
42
|
+
.venv/bin/python -m stratforge.live --config config/live_paper.json
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Paper must not load API keys. `LIVE_TRADING` stays false.
|
|
46
|
+
|
|
47
|
+
## Promote to live
|
|
48
|
+
|
|
49
|
+
See `docs/PROMOTE.md`. Do not start live from this README.
|
|
50
|
+
|
|
51
|
+
Short identity is `config/short/tsmom12_weekly.json`, not `bear_regime_cover`.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# stratforge
|
|
2
|
+
|
|
3
|
+
Create deterministic trading strategies with an AI agent, backtest them, compare them, and promote winning versions onto paper and live portfolios.
|
|
4
|
+
|
|
5
|
+
MIT license. A clone does not trade. Live orders need an API key, a portfolio id, and a `data/LIVE_APPROVED` file that you create. There is no silent portfolio default.
|
|
6
|
+
|
|
7
|
+
## What is in this repo
|
|
8
|
+
|
|
9
|
+
- Decision engine, public candles, paper simulator, and research replay.
|
|
10
|
+
- Order path: `ccxt_bridge`, `live_executor`, reconcile, buy-protect, `live_node`.
|
|
11
|
+
- Strategy families: trend rotation, Donchian, `short/` (`tsmom12_weekly`; bear-regime configs are rejected variants), `cfm/` (CDE nanos, isolated).
|
|
12
|
+
- Viz source. Snapshots and passwords are not in git.
|
|
13
|
+
- Generic systemd and nginx templates in `deploy/`. They use `%h` or a variable you set. They do not name a host.
|
|
14
|
+
|
|
15
|
+
## What stays on the machine that runs a book
|
|
16
|
+
|
|
17
|
+
Journals, the candle warehouse, `.env.live`, `data/LIVE_APPROVED`, halt files, viz snapshots, and htpasswd. Do not commit them.
|
|
18
|
+
|
|
19
|
+
## Run paper
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
git clone git@github.com:jag3773/stratforge.git
|
|
23
|
+
cd stratforge
|
|
24
|
+
uv venv --python 3.13 .venv
|
|
25
|
+
uv pip install -r requirements.txt
|
|
26
|
+
.venv/bin/python -m stratforge.live --config config/live_paper.json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Paper must not load API keys. `LIVE_TRADING` stays false.
|
|
30
|
+
|
|
31
|
+
## Promote to live
|
|
32
|
+
|
|
33
|
+
See `docs/PROMOTE.md`. Do not start live from this README.
|
|
34
|
+
|
|
35
|
+
Short identity is `config/short/tsmom12_weekly.json`, not `bear_regime_cover`.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "stratforge"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Deterministic trading strategies: backtest, compare, promote to paper and live."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"ccxt>=4.5.0",
|
|
14
|
+
"requests>=2.32.0",
|
|
15
|
+
"pandas>=2.2.0",
|
|
16
|
+
"numpy>=2.0.0",
|
|
17
|
+
"pyarrow>=17.0.0",
|
|
18
|
+
"python-dotenv>=1.0.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["."]
|
|
23
|
+
include = ["stratforge*"]
|
|
24
|
+
|
|
25
|
+
[tool.pytest.ini_options]
|
|
26
|
+
testpaths = ["tests"]
|
|
27
|
+
addopts = "-q"
|
|
@@ -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))
|