fortell-rules 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.
- fortell_rules-0.1.0/LICENSE +21 -0
- fortell_rules-0.1.0/PKG-INFO +148 -0
- fortell_rules-0.1.0/README.md +131 -0
- fortell_rules-0.1.0/fortell_rules/__init__.py +37 -0
- fortell_rules-0.1.0/fortell_rules/adapters/__init__.py +51 -0
- fortell_rules-0.1.0/fortell_rules/adapters/backtrader_adapter.py +67 -0
- fortell_rules-0.1.0/fortell_rules/adapters/common.py +98 -0
- fortell_rules-0.1.0/fortell_rules/adapters/freqtrade_adapter.py +54 -0
- fortell_rules-0.1.0/fortell_rules/adapters/generic.py +26 -0
- fortell_rules-0.1.0/fortell_rules/adapters/vectorbt_adapter.py +69 -0
- fortell_rules-0.1.0/fortell_rules/grader.py +393 -0
- fortell_rules-0.1.0/fortell_rules/rules.py +101 -0
- fortell_rules-0.1.0/fortell_rules/terms.py +182 -0
- fortell_rules-0.1.0/fortell_rules/trades.py +130 -0
- fortell_rules-0.1.0/fortell_rules.egg-info/PKG-INFO +148 -0
- fortell_rules-0.1.0/fortell_rules.egg-info/SOURCES.txt +20 -0
- fortell_rules-0.1.0/fortell_rules.egg-info/dependency_links.txt +1 -0
- fortell_rules-0.1.0/fortell_rules.egg-info/requires.txt +6 -0
- fortell_rules-0.1.0/fortell_rules.egg-info/top_level.txt +1 -0
- fortell_rules-0.1.0/pyproject.toml +27 -0
- fortell_rules-0.1.0/setup.cfg +4 -0
- fortell_rules-0.1.0/test/test_kit.py +268 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fortell
|
|
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,148 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fortell-rules
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Score a strategy against Fortell's Evaluation rules before paying (Harness Blueprint).
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://fortell.finance
|
|
7
|
+
Project-URL: Documentation, https://fortell.finance/skill.md
|
|
8
|
+
Project-URL: Download, https://fortell.finance/rules-kit.zip
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Provides-Extra: vectorbt
|
|
13
|
+
Requires-Dist: vectorbt; extra == "vectorbt"
|
|
14
|
+
Provides-Extra: backtrader
|
|
15
|
+
Requires-Dist: backtrader; extra == "backtrader"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# Fortell Rules Kit
|
|
19
|
+
|
|
20
|
+
Part of the **Fortell Trading Agent Harness Builder Blueprint** (the "Harness Blueprint").
|
|
21
|
+
|
|
22
|
+
**Fortell gives capability, never strategy.** This kit lets any backtest engine score a strategy
|
|
23
|
+
against a Fortell **Evaluation** tier's rules and return the verdict **exactly as Fortell judges
|
|
24
|
+
it** — so an agent can test a strategy *before* it pays for an Evaluation.
|
|
25
|
+
|
|
26
|
+
It does not trade, hold a key, or send a transaction. It reads a tier's rules and a list of
|
|
27
|
+
trades, and returns pass / fail / active with a reason.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## What it does
|
|
32
|
+
|
|
33
|
+
Given a tier's rules and your backtest's closed trades (and, if you have it, an equity curve), it
|
|
34
|
+
grades every rule the live Perps Evaluation grader grades:
|
|
35
|
+
|
|
36
|
+
- **max loss** — measured on **equity including open profit and loss** vs the start, the way the
|
|
37
|
+
live grader measures it (a dip on an *open* position's mark can breach it);
|
|
38
|
+
- **profit target**;
|
|
39
|
+
- **consistency** — the best single day may not be more than a set share of the profit (net or
|
|
40
|
+
gross, by the tier's terms version);
|
|
41
|
+
- **window / days** and the **early door**;
|
|
42
|
+
- **minimum order size**, **minimum hold**, and the **leverage / notional** rails it records;
|
|
43
|
+
- **count and quality** (the lower-confidence-bound F-score over your trades);
|
|
44
|
+
- the **daily-loss** rule and the **auto-close** behaviour.
|
|
45
|
+
|
|
46
|
+
The grader is a byte-for-byte mirror of `packages/core/src/perp-evaluation.ts`
|
|
47
|
+
(`gradePerpEvaluation`). A parity test runs the same fixtures through the shipped TypeScript
|
|
48
|
+
grader and through this kit and requires identical verdicts (see `scripts/parity.mts`).
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
Pure Python 3.10+. The core has **no dependencies**; each engine adapter imports its engine
|
|
53
|
+
lazily, only when you call it.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
# Download https://fortell.finance/rules-kit.zip. Check it first:
|
|
57
|
+
shasum -a 256 rules-kit.zip # must equal the hash in https://fortell.finance/rules-kit.zip.sha256
|
|
58
|
+
unzip rules-kit.zip && cd fortell-rules
|
|
59
|
+
pip install . # optional engine extras: pip install ".[vectorbt]" or ".[backtrader]"
|
|
60
|
+
python3 -c "import fortell_rules; print(fortell_rules.__version__)"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## 10-line example
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from fortell_rules import Deal, Terms, grade
|
|
67
|
+
|
|
68
|
+
terms = Terms.from_usd(start_usd=1000, window_secs=14*86_400,
|
|
69
|
+
profit_target_pct=5, max_loss_pct=6, best_day_share_pct=50, min_order_usd=5)
|
|
70
|
+
|
|
71
|
+
deals = [ # your backtest's CLOSED trades (margin and PnL in USD -> micro-units)
|
|
72
|
+
Deal("PHOENIX-PERP-BTC", opened_at=0, closed_at=3_600, margin_micro=100_000_000, net_pnl_micro=30_000_000),
|
|
73
|
+
Deal("PHOENIX-PERP-BTC", opened_at=90_000, closed_at=93_600, margin_micro=100_000_000, net_pnl_micro=30_000_000),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
v = grade(terms, deals, started_at=0, now=14*86_400)
|
|
77
|
+
print(v.status, v.profit_micro, v.best_day_bps) # "passed" 60000000 5000
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
All money is in **micro-units** (6 decimals): `$1 = 1_000_000`. Keeping every amount an integer is
|
|
81
|
+
what lets this kit match the on-chain grader, which never uses a float for money.
|
|
82
|
+
|
|
83
|
+
## Getting a tier's rules (never hard-code them)
|
|
84
|
+
|
|
85
|
+
Load a tier's rules from the public catalogue and pass the row straight through — unknown keys are
|
|
86
|
+
ignored:
|
|
87
|
+
|
|
88
|
+
- **Fortell MCP**: call `fortell_challenge_catalog` and take the tier you want to test against.
|
|
89
|
+
- **Public API**: the tier catalogue endpoint.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import json, urllib.request
|
|
93
|
+
from fortell_rules import Terms
|
|
94
|
+
|
|
95
|
+
row = json.load(urllib.request.urlopen("https://<fortell-api>/tiers/<tier>")) # or the MCP result
|
|
96
|
+
terms = Terms.from_mapping(row) # reads startBalance, windowSecs, minProfitBps, ... as-is
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`Terms.from_usd(...)` is only a convenience for a quick, hand-entered tier; prefer a real
|
|
100
|
+
catalogue row for a faithful grade.
|
|
101
|
+
|
|
102
|
+
## Getting candles (for your backtest)
|
|
103
|
+
|
|
104
|
+
This kit does **not** download market data. Use what Fortell already serves:
|
|
105
|
+
|
|
106
|
+
- **Fortell MCP** `fortell_price_history` (the public candle endpoint) for Phoenix Perps markets,
|
|
107
|
+
and `fortell_perps_markets` for the market list and tick sizes.
|
|
108
|
+
|
|
109
|
+
Feed those candles to your own engine (VectorBT, Backtrader, Freqtrade, …); then hand the engine's
|
|
110
|
+
trade list to this kit through an adapter.
|
|
111
|
+
|
|
112
|
+
## Adapters
|
|
113
|
+
|
|
114
|
+
Each adapter turns an engine's output into the kit's `Deal` list (and, where the engine has one,
|
|
115
|
+
an equity curve of `EquityMark`). An adapter **only reshapes data** — it never grades and never
|
|
116
|
+
invents a margin (a perps backtest that did not model margin must say what margin to grade at).
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from fortell_rules.adapters import (
|
|
120
|
+
deals_from_vectorbt, # a vectorbt Portfolio
|
|
121
|
+
deals_from_backtrader, # a list of Backtrader closed Trades (or dicts)
|
|
122
|
+
deals_from_freqtrade_json, # a Freqtrade backtest-result JSON file
|
|
123
|
+
deals_from_csv, # a plain CSV / list of trades
|
|
124
|
+
)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
See `examples/adapters_example.py`. In this repo's CI the adapters are tested against **mocked**
|
|
128
|
+
engine objects (the shape each engine returns), not the real libraries; the conversion logic is
|
|
129
|
+
what the tests pin.
|
|
130
|
+
|
|
131
|
+
## What it CANNOT model (read this)
|
|
132
|
+
|
|
133
|
+
A backtest pass is **never a guarantee** that an Evaluation will pass. This kit scores the rules;
|
|
134
|
+
it does not reproduce a live market. It cannot model:
|
|
135
|
+
|
|
136
|
+
- **live slippage** and the actual fill price your order would get;
|
|
137
|
+
- **funding** over the hold (it uses the PnL your backtest already computed);
|
|
138
|
+
- **liquidity** and partial fills at size;
|
|
139
|
+
- **fill timing** and the exact mark the risk engine reads.
|
|
140
|
+
|
|
141
|
+
Use it as a filter — "this strategy would not even clear the rules on historical data" is a strong
|
|
142
|
+
*no*; "it cleared the rules" is a *maybe*, not a *yes*.
|
|
143
|
+
|
|
144
|
+
## Running the tests
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
node scripts/gate.mjs # python unit + adapter tests, then the parity harness
|
|
148
|
+
```
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# Fortell Rules Kit
|
|
2
|
+
|
|
3
|
+
Part of the **Fortell Trading Agent Harness Builder Blueprint** (the "Harness Blueprint").
|
|
4
|
+
|
|
5
|
+
**Fortell gives capability, never strategy.** This kit lets any backtest engine score a strategy
|
|
6
|
+
against a Fortell **Evaluation** tier's rules and return the verdict **exactly as Fortell judges
|
|
7
|
+
it** — so an agent can test a strategy *before* it pays for an Evaluation.
|
|
8
|
+
|
|
9
|
+
It does not trade, hold a key, or send a transaction. It reads a tier's rules and a list of
|
|
10
|
+
trades, and returns pass / fail / active with a reason.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## What it does
|
|
15
|
+
|
|
16
|
+
Given a tier's rules and your backtest's closed trades (and, if you have it, an equity curve), it
|
|
17
|
+
grades every rule the live Perps Evaluation grader grades:
|
|
18
|
+
|
|
19
|
+
- **max loss** — measured on **equity including open profit and loss** vs the start, the way the
|
|
20
|
+
live grader measures it (a dip on an *open* position's mark can breach it);
|
|
21
|
+
- **profit target**;
|
|
22
|
+
- **consistency** — the best single day may not be more than a set share of the profit (net or
|
|
23
|
+
gross, by the tier's terms version);
|
|
24
|
+
- **window / days** and the **early door**;
|
|
25
|
+
- **minimum order size**, **minimum hold**, and the **leverage / notional** rails it records;
|
|
26
|
+
- **count and quality** (the lower-confidence-bound F-score over your trades);
|
|
27
|
+
- the **daily-loss** rule and the **auto-close** behaviour.
|
|
28
|
+
|
|
29
|
+
The grader is a byte-for-byte mirror of `packages/core/src/perp-evaluation.ts`
|
|
30
|
+
(`gradePerpEvaluation`). A parity test runs the same fixtures through the shipped TypeScript
|
|
31
|
+
grader and through this kit and requires identical verdicts (see `scripts/parity.mts`).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
Pure Python 3.10+. The core has **no dependencies**; each engine adapter imports its engine
|
|
36
|
+
lazily, only when you call it.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# Download https://fortell.finance/rules-kit.zip. Check it first:
|
|
40
|
+
shasum -a 256 rules-kit.zip # must equal the hash in https://fortell.finance/rules-kit.zip.sha256
|
|
41
|
+
unzip rules-kit.zip && cd fortell-rules
|
|
42
|
+
pip install . # optional engine extras: pip install ".[vectorbt]" or ".[backtrader]"
|
|
43
|
+
python3 -c "import fortell_rules; print(fortell_rules.__version__)"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## 10-line example
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from fortell_rules import Deal, Terms, grade
|
|
50
|
+
|
|
51
|
+
terms = Terms.from_usd(start_usd=1000, window_secs=14*86_400,
|
|
52
|
+
profit_target_pct=5, max_loss_pct=6, best_day_share_pct=50, min_order_usd=5)
|
|
53
|
+
|
|
54
|
+
deals = [ # your backtest's CLOSED trades (margin and PnL in USD -> micro-units)
|
|
55
|
+
Deal("PHOENIX-PERP-BTC", opened_at=0, closed_at=3_600, margin_micro=100_000_000, net_pnl_micro=30_000_000),
|
|
56
|
+
Deal("PHOENIX-PERP-BTC", opened_at=90_000, closed_at=93_600, margin_micro=100_000_000, net_pnl_micro=30_000_000),
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
v = grade(terms, deals, started_at=0, now=14*86_400)
|
|
60
|
+
print(v.status, v.profit_micro, v.best_day_bps) # "passed" 60000000 5000
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
All money is in **micro-units** (6 decimals): `$1 = 1_000_000`. Keeping every amount an integer is
|
|
64
|
+
what lets this kit match the on-chain grader, which never uses a float for money.
|
|
65
|
+
|
|
66
|
+
## Getting a tier's rules (never hard-code them)
|
|
67
|
+
|
|
68
|
+
Load a tier's rules from the public catalogue and pass the row straight through — unknown keys are
|
|
69
|
+
ignored:
|
|
70
|
+
|
|
71
|
+
- **Fortell MCP**: call `fortell_challenge_catalog` and take the tier you want to test against.
|
|
72
|
+
- **Public API**: the tier catalogue endpoint.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import json, urllib.request
|
|
76
|
+
from fortell_rules import Terms
|
|
77
|
+
|
|
78
|
+
row = json.load(urllib.request.urlopen("https://<fortell-api>/tiers/<tier>")) # or the MCP result
|
|
79
|
+
terms = Terms.from_mapping(row) # reads startBalance, windowSecs, minProfitBps, ... as-is
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`Terms.from_usd(...)` is only a convenience for a quick, hand-entered tier; prefer a real
|
|
83
|
+
catalogue row for a faithful grade.
|
|
84
|
+
|
|
85
|
+
## Getting candles (for your backtest)
|
|
86
|
+
|
|
87
|
+
This kit does **not** download market data. Use what Fortell already serves:
|
|
88
|
+
|
|
89
|
+
- **Fortell MCP** `fortell_price_history` (the public candle endpoint) for Phoenix Perps markets,
|
|
90
|
+
and `fortell_perps_markets` for the market list and tick sizes.
|
|
91
|
+
|
|
92
|
+
Feed those candles to your own engine (VectorBT, Backtrader, Freqtrade, …); then hand the engine's
|
|
93
|
+
trade list to this kit through an adapter.
|
|
94
|
+
|
|
95
|
+
## Adapters
|
|
96
|
+
|
|
97
|
+
Each adapter turns an engine's output into the kit's `Deal` list (and, where the engine has one,
|
|
98
|
+
an equity curve of `EquityMark`). An adapter **only reshapes data** — it never grades and never
|
|
99
|
+
invents a margin (a perps backtest that did not model margin must say what margin to grade at).
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from fortell_rules.adapters import (
|
|
103
|
+
deals_from_vectorbt, # a vectorbt Portfolio
|
|
104
|
+
deals_from_backtrader, # a list of Backtrader closed Trades (or dicts)
|
|
105
|
+
deals_from_freqtrade_json, # a Freqtrade backtest-result JSON file
|
|
106
|
+
deals_from_csv, # a plain CSV / list of trades
|
|
107
|
+
)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
See `examples/adapters_example.py`. In this repo's CI the adapters are tested against **mocked**
|
|
111
|
+
engine objects (the shape each engine returns), not the real libraries; the conversion logic is
|
|
112
|
+
what the tests pin.
|
|
113
|
+
|
|
114
|
+
## What it CANNOT model (read this)
|
|
115
|
+
|
|
116
|
+
A backtest pass is **never a guarantee** that an Evaluation will pass. This kit scores the rules;
|
|
117
|
+
it does not reproduce a live market. It cannot model:
|
|
118
|
+
|
|
119
|
+
- **live slippage** and the actual fill price your order would get;
|
|
120
|
+
- **funding** over the hold (it uses the PnL your backtest already computed);
|
|
121
|
+
- **liquidity** and partial fills at size;
|
|
122
|
+
- **fill timing** and the exact mark the risk engine reads.
|
|
123
|
+
|
|
124
|
+
Use it as a filter — "this strategy would not even clear the rules on historical data" is a strong
|
|
125
|
+
*no*; "it cleared the rules" is a *maybe*, not a *yes*.
|
|
126
|
+
|
|
127
|
+
## Running the tests
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
node scripts/gate.mjs # python unit + adapter tests, then the parity harness
|
|
131
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""
|
|
2
|
+
fortell_rules - score a strategy against Fortell's EVALUATION rules before you pay.
|
|
3
|
+
|
|
4
|
+
Fortell gives capability, never strategy. This kit lets ANY backtest engine (VectorBT,
|
|
5
|
+
Backtrader, Freqtrade, or a plain list of trades) check a run against a Perps Evaluation tier's
|
|
6
|
+
rules and return the verdict exactly as Fortell judges it.
|
|
7
|
+
|
|
8
|
+
A backtest pass is NOT a guarantee that an Evaluation will pass: a backtest cannot model live
|
|
9
|
+
slippage, funding, liquidity or fill timing. See the README.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .grader import RuleDetail, Verdict, grade, grade_history, mark_latch_breached, realised_banked
|
|
14
|
+
from .rules import GradeRules, perp_grade_rules, rule_settings_of
|
|
15
|
+
from .terms import RuleSettings, Terms
|
|
16
|
+
from .trades import Deal, EquityMark, Quality, perp_return_quality, perp_scored_sample
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Terms",
|
|
20
|
+
"RuleSettings",
|
|
21
|
+
"Deal",
|
|
22
|
+
"EquityMark",
|
|
23
|
+
"Quality",
|
|
24
|
+
"Verdict",
|
|
25
|
+
"RuleDetail",
|
|
26
|
+
"GradeRules",
|
|
27
|
+
"grade",
|
|
28
|
+
"grade_history",
|
|
29
|
+
"perp_grade_rules",
|
|
30
|
+
"rule_settings_of",
|
|
31
|
+
"perp_scored_sample",
|
|
32
|
+
"perp_return_quality",
|
|
33
|
+
"realised_banked",
|
|
34
|
+
"mark_latch_breached",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Thin adapters: a backtest engine's output -> the kit's ``Deal`` / ``EquityMark`` list.
|
|
3
|
+
|
|
4
|
+
Each adapter imports its engine LAZILY (only when called), so importing ``fortell_rules`` never
|
|
5
|
+
requires VectorBT, Backtrader, Freqtrade or pandas. An adapter only RESHAPES data; it never
|
|
6
|
+
grades and never invents a number the engine did not give (margin, in particular - a perps
|
|
7
|
+
backtest that did not model margin must say what margin to assume; see each adapter).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from .common import (
|
|
12
|
+
deals_from_records,
|
|
13
|
+
equity_marks_from_series,
|
|
14
|
+
to_epoch_seconds,
|
|
15
|
+
usd_to_micro,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"deals_from_records",
|
|
20
|
+
"equity_marks_from_series",
|
|
21
|
+
"to_epoch_seconds",
|
|
22
|
+
"usd_to_micro",
|
|
23
|
+
"deals_from_vectorbt",
|
|
24
|
+
"deals_from_backtrader",
|
|
25
|
+
"deals_from_freqtrade_json",
|
|
26
|
+
"deals_from_csv",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def deals_from_vectorbt(*args, **kwargs):
|
|
31
|
+
from .vectorbt_adapter import deals_from_vectorbt as f
|
|
32
|
+
|
|
33
|
+
return f(*args, **kwargs)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def deals_from_backtrader(*args, **kwargs):
|
|
37
|
+
from .backtrader_adapter import deals_from_backtrader as f
|
|
38
|
+
|
|
39
|
+
return f(*args, **kwargs)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def deals_from_freqtrade_json(*args, **kwargs):
|
|
43
|
+
from .freqtrade_adapter import deals_from_freqtrade_json as f
|
|
44
|
+
|
|
45
|
+
return f(*args, **kwargs)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def deals_from_csv(*args, **kwargs):
|
|
49
|
+
from .generic import deals_from_csv as f
|
|
50
|
+
|
|
51
|
+
return f(*args, **kwargs)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Backtrader adapter.
|
|
3
|
+
|
|
4
|
+
Backtrader closes trades through a ``Trade`` object. The simplest capture is a tiny analyzer
|
|
5
|
+
that records each closed trade; this adapter maps either that analyzer's list or a raw list of
|
|
6
|
+
Backtrader ``Trade`` objects to ``Deal`` rows.
|
|
7
|
+
|
|
8
|
+
Backtrader's ``trade.pnlcomm`` is PnL after commission. Margin is not modelled, so pass
|
|
9
|
+
``margin_usd`` or ``margin_fn(trade) -> usd`` (the trade's ``price * size`` is the 1x fallback).
|
|
10
|
+
|
|
11
|
+
A ready-to-use analyzer is provided (``ClosedTradeRecorder``); import ``backtrader`` yourself to
|
|
12
|
+
add it to a Cerebro run. Nothing here imports backtrader.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any, Callable, Iterable, List, Optional
|
|
17
|
+
|
|
18
|
+
from ..trades import Deal
|
|
19
|
+
from .common import to_epoch_seconds, usd_to_micro
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def deals_from_backtrader(
|
|
23
|
+
trades: Iterable[Any],
|
|
24
|
+
*,
|
|
25
|
+
margin_usd: Optional[float] = None,
|
|
26
|
+
margin_fn: Optional[Callable[[Any], float]] = None,
|
|
27
|
+
market_id: str = "BACKTEST",
|
|
28
|
+
) -> List[Deal]:
|
|
29
|
+
"""Map Backtrader closed ``Trade`` objects (or ``{...}`` dicts from the recorder) to ``Deal``."""
|
|
30
|
+
out: List[Deal] = []
|
|
31
|
+
for tr in trades:
|
|
32
|
+
g = _getter(tr)
|
|
33
|
+
size = float(g("size", default=0.0) or 0.0)
|
|
34
|
+
price = float(g("price", default=0.0) or 0.0)
|
|
35
|
+
pnl = float(g("pnlcomm", "pnl", default=0.0))
|
|
36
|
+
if margin_fn is not None:
|
|
37
|
+
margin = usd_to_micro(margin_fn(tr))
|
|
38
|
+
elif margin_usd is not None:
|
|
39
|
+
margin = usd_to_micro(margin_usd)
|
|
40
|
+
else:
|
|
41
|
+
margin = usd_to_micro(abs(price * size))
|
|
42
|
+
out.append(
|
|
43
|
+
Deal(
|
|
44
|
+
market_id=str(g("market_id", "data_name", "symbol", default=market_id)),
|
|
45
|
+
opened_at=to_epoch_seconds(g("dtopen_iso", "dtopen", "opened_at", "open_time")),
|
|
46
|
+
closed_at=to_epoch_seconds(g("dtclose_iso", "dtclose", "closed_at", "close_time")),
|
|
47
|
+
margin_micro=max(1, margin),
|
|
48
|
+
net_pnl_micro=usd_to_micro(pnl),
|
|
49
|
+
lots=int(abs(size)),
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _getter(obj: Any):
|
|
56
|
+
is_map = isinstance(obj, dict)
|
|
57
|
+
|
|
58
|
+
def g(*keys: str, default: Any = None) -> Any:
|
|
59
|
+
for k in keys:
|
|
60
|
+
if is_map:
|
|
61
|
+
if k in obj and obj[k] is not None:
|
|
62
|
+
return obj[k]
|
|
63
|
+
elif hasattr(obj, k) and getattr(obj, k) is not None:
|
|
64
|
+
return getattr(obj, k)
|
|
65
|
+
return default
|
|
66
|
+
|
|
67
|
+
return g
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Shared adapter helpers: units and timestamps, and a generic record -> Deal mapping."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Iterable, List, Mapping, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
from ..trades import Deal, EquityMark
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def usd_to_micro(usd: float) -> int:
|
|
10
|
+
"""Dollars -> micro-units (6 decimals). Rounded to the nearest micro-unit."""
|
|
11
|
+
return int(round(float(usd) * 1_000_000))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def to_epoch_seconds(ts: Any) -> int:
|
|
15
|
+
"""Accept an int/float epoch (seconds or milliseconds), an ISO-8601 string, or a
|
|
16
|
+
datetime/pandas Timestamp, and return whole epoch seconds."""
|
|
17
|
+
if isinstance(ts, bool):
|
|
18
|
+
raise TypeError("timestamp must not be a bool")
|
|
19
|
+
if isinstance(ts, (int, float)):
|
|
20
|
+
v = float(ts)
|
|
21
|
+
# Heuristic: values that large are milliseconds.
|
|
22
|
+
if v > 1e12:
|
|
23
|
+
v /= 1000.0
|
|
24
|
+
return int(v)
|
|
25
|
+
# datetime / pandas.Timestamp
|
|
26
|
+
if hasattr(ts, "timestamp"):
|
|
27
|
+
return int(ts.timestamp())
|
|
28
|
+
if isinstance(ts, str):
|
|
29
|
+
s = ts.strip()
|
|
30
|
+
# A numeric string (common in CSV) is an epoch, not an ISO date.
|
|
31
|
+
try:
|
|
32
|
+
return to_epoch_seconds(float(s) if ("." in s or "e" in s.lower()) else int(s))
|
|
33
|
+
except ValueError:
|
|
34
|
+
pass
|
|
35
|
+
from datetime import datetime
|
|
36
|
+
|
|
37
|
+
return int(datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp())
|
|
38
|
+
raise TypeError(f"cannot read a timestamp from {type(ts)!r}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _get(rec: Mapping[str, Any], *keys: str, default: Any = None) -> Any:
|
|
42
|
+
for k in keys:
|
|
43
|
+
if k in rec and rec[k] is not None:
|
|
44
|
+
return rec[k]
|
|
45
|
+
return default
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def deals_from_records(records: Iterable[Mapping[str, Any]]) -> List[Deal]:
|
|
49
|
+
"""Map a list of trade dicts to ``Deal``. Recognised keys (first found wins):
|
|
50
|
+
|
|
51
|
+
- market: ``market_id`` | ``market`` | ``symbol`` | ``pair``
|
|
52
|
+
- open: ``opened_at`` | ``open_time`` | ``entry_time`` | ``open_date``
|
|
53
|
+
- close: ``closed_at`` | ``close_time`` | ``exit_time`` | ``close_date``
|
|
54
|
+
- margin: ``margin_micro`` (int) | ``margin_usd`` | ``stake_amount`` | ``margin``
|
|
55
|
+
- pnl: ``net_pnl_micro`` (int) | ``net_pnl_usd`` | ``pnl_usd`` | ``profit_abs`` | ``pnl``
|
|
56
|
+
|
|
57
|
+
Margin is required and never invented: a perps backtest that did not model margin must supply
|
|
58
|
+
the margin it wants each trade graded at (margin decides the min-order and quality filters).
|
|
59
|
+
"""
|
|
60
|
+
out: List[Deal] = []
|
|
61
|
+
for rec in records:
|
|
62
|
+
margin_micro = _get(rec, "margin_micro")
|
|
63
|
+
if margin_micro is not None:
|
|
64
|
+
margin = int(margin_micro)
|
|
65
|
+
else:
|
|
66
|
+
margin_usd = _get(rec, "margin_usd", "stake_amount", "margin")
|
|
67
|
+
if margin_usd is None:
|
|
68
|
+
raise ValueError(
|
|
69
|
+
"each trade needs a margin: pass margin_micro or margin_usd "
|
|
70
|
+
"(the kit never invents margin)"
|
|
71
|
+
)
|
|
72
|
+
margin = usd_to_micro(margin_usd)
|
|
73
|
+
pnl_micro = _get(rec, "net_pnl_micro")
|
|
74
|
+
if pnl_micro is not None:
|
|
75
|
+
pnl = int(pnl_micro)
|
|
76
|
+
else:
|
|
77
|
+
pnl = usd_to_micro(_get(rec, "net_pnl_usd", "pnl_usd", "profit_abs", "pnl", default=0.0))
|
|
78
|
+
out.append(
|
|
79
|
+
Deal(
|
|
80
|
+
market_id=str(_get(rec, "market_id", "market", "symbol", "pair", default="UNKNOWN")),
|
|
81
|
+
opened_at=to_epoch_seconds(_get(rec, "opened_at", "open_time", "entry_time", "open_date")),
|
|
82
|
+
closed_at=to_epoch_seconds(_get(rec, "closed_at", "close_time", "exit_time", "close_date")),
|
|
83
|
+
margin_micro=margin,
|
|
84
|
+
net_pnl_micro=pnl,
|
|
85
|
+
reason=str(_get(rec, "reason", default="trader")),
|
|
86
|
+
lots=int(_get(rec, "lots", default=0)),
|
|
87
|
+
final=bool(_get(rec, "final", default=True)),
|
|
88
|
+
hedge_ratio_bps=int(_get(rec, "hedge_ratio_bps", default=0)),
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def equity_marks_from_series(times: Sequence[Any], equity_usd: Sequence[float]) -> List[EquityMark]:
|
|
95
|
+
"""An equity curve (parallel time and dollar-equity sequences) -> ``EquityMark`` list."""
|
|
96
|
+
if len(times) != len(equity_usd):
|
|
97
|
+
raise ValueError("times and equity_usd must be the same length")
|
|
98
|
+
return [EquityMark(t=to_epoch_seconds(a), nav_micro=usd_to_micro(b)) for a, b in zip(times, equity_usd)]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Freqtrade adapter: a backtest-result JSON (the file ``freqtrade backtesting --export trades``
|
|
3
|
+
writes) -> the kit's ``Deal`` list.
|
|
4
|
+
|
|
5
|
+
Freqtrade reports ``profit_abs`` (PnL in stake currency, after fees) and ``stake_amount`` (the
|
|
6
|
+
money committed), which maps to the kit's margin. No engine import: this reads JSON only.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any, List, Mapping
|
|
12
|
+
|
|
13
|
+
from ..trades import Deal
|
|
14
|
+
from .common import to_epoch_seconds, usd_to_micro
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def deals_from_freqtrade_result(result: Mapping[str, Any], *, strategy: str | None = None) -> List[Deal]:
|
|
18
|
+
"""Map a parsed Freqtrade backtest result dict to ``Deal`` rows.
|
|
19
|
+
|
|
20
|
+
The file nests trades under ``strategy.<name>.trades``; pass ``strategy`` to pick one, else
|
|
21
|
+
the first strategy is used.
|
|
22
|
+
"""
|
|
23
|
+
trades = _find_trades(result, strategy)
|
|
24
|
+
out: List[Deal] = []
|
|
25
|
+
for tr in trades:
|
|
26
|
+
out.append(
|
|
27
|
+
Deal(
|
|
28
|
+
market_id=str(tr.get("pair", "UNKNOWN")),
|
|
29
|
+
opened_at=to_epoch_seconds(tr.get("open_date", tr.get("open_timestamp"))),
|
|
30
|
+
closed_at=to_epoch_seconds(tr.get("close_date", tr.get("close_timestamp"))),
|
|
31
|
+
margin_micro=max(1, usd_to_micro(float(tr.get("stake_amount", 0.0)))),
|
|
32
|
+
net_pnl_micro=usd_to_micro(float(tr.get("profit_abs", 0.0))),
|
|
33
|
+
reason=str(tr.get("exit_reason", "trader")),
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def deals_from_freqtrade_json(path: str, *, strategy: str | None = None) -> List[Deal]:
|
|
40
|
+
"""Read a Freqtrade backtest-result JSON file and map its trades to ``Deal`` rows."""
|
|
41
|
+
with open(path, encoding="utf-8") as fh:
|
|
42
|
+
return deals_from_freqtrade_result(json.load(fh), strategy=strategy)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _find_trades(result: Mapping[str, Any], strategy: str | None) -> list:
|
|
46
|
+
if "trades" in result and isinstance(result["trades"], list):
|
|
47
|
+
return result["trades"]
|
|
48
|
+
strat = result.get("strategy")
|
|
49
|
+
if isinstance(strat, Mapping) and strat:
|
|
50
|
+
if strategy is not None:
|
|
51
|
+
return list(strat[strategy].get("trades", []))
|
|
52
|
+
first = next(iter(strat.values()))
|
|
53
|
+
return list(first.get("trades", []))
|
|
54
|
+
raise ValueError("no trades found in the Freqtrade result (expected result['strategy'][name]['trades'])")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Plain CSV / list-of-trades adapter. No engine import."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
from typing import Any, Iterable, List, Mapping
|
|
6
|
+
|
|
7
|
+
from ..trades import Deal
|
|
8
|
+
from .common import deals_from_records
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def deals_from_list(records: Iterable[Mapping[str, Any]]) -> List[Deal]:
|
|
12
|
+
"""A list of trade dicts -> ``Deal`` list (see ``deals_from_records`` for the keys)."""
|
|
13
|
+
return deals_from_records(records)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def deals_from_csv(path: str) -> List[Deal]:
|
|
17
|
+
"""A CSV whose header names the columns ``deals_from_records`` recognises.
|
|
18
|
+
|
|
19
|
+
A column named ``margin_usd`` (or ``margin_micro``) and one named ``pnl_usd`` (or
|
|
20
|
+
``net_pnl_micro``) are required, plus open/close timestamps and a market/symbol.
|
|
21
|
+
"""
|
|
22
|
+
with open(path, newline="", encoding="utf-8") as fh:
|
|
23
|
+
rows = list(csv.DictReader(fh))
|
|
24
|
+
# Drop empty strings so numeric fallbacks apply.
|
|
25
|
+
cleaned = [{k: v for k, v in row.items() if v is not None and v != ""} for row in rows]
|
|
26
|
+
return deals_from_records(cleaned)
|