Metadata-Version: 2.4
Name: fortell-rules
Version: 0.1.0
Summary: Score a strategy against Fortell's Evaluation rules before paying (Harness Blueprint).
License-Expression: MIT
Project-URL: Homepage, https://fortell.finance
Project-URL: Documentation, https://fortell.finance/skill.md
Project-URL: Download, https://fortell.finance/rules-kit.zip
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: vectorbt
Requires-Dist: vectorbt; extra == "vectorbt"
Provides-Extra: backtrader
Requires-Dist: backtrader; extra == "backtrader"
Dynamic: license-file

# Fortell Rules Kit

Part of the **Fortell Trading Agent Harness Builder Blueprint** (the "Harness Blueprint").

**Fortell gives capability, never strategy.** This kit lets any backtest engine score a strategy
against a Fortell **Evaluation** tier's rules and return the verdict **exactly as Fortell judges
it** — so an agent can test a strategy *before* it pays for an Evaluation.

It does not trade, hold a key, or send a transaction. It reads a tier's rules and a list of
trades, and returns pass / fail / active with a reason.

---

## What it does

Given a tier's rules and your backtest's closed trades (and, if you have it, an equity curve), it
grades every rule the live Perps Evaluation grader grades:

- **max loss** — measured on **equity including open profit and loss** vs the start, the way the
  live grader measures it (a dip on an *open* position's mark can breach it);
- **profit target**;
- **consistency** — the best single day may not be more than a set share of the profit (net or
  gross, by the tier's terms version);
- **window / days** and the **early door**;
- **minimum order size**, **minimum hold**, and the **leverage / notional** rails it records;
- **count and quality** (the lower-confidence-bound F-score over your trades);
- the **daily-loss** rule and the **auto-close** behaviour.

The grader is a byte-for-byte mirror of `packages/core/src/perp-evaluation.ts`
(`gradePerpEvaluation`). A parity test runs the same fixtures through the shipped TypeScript
grader and through this kit and requires identical verdicts (see `scripts/parity.mts`).

## Install

Pure Python 3.10+. The core has **no dependencies**; each engine adapter imports its engine
lazily, only when you call it.

```bash
# Download https://fortell.finance/rules-kit.zip. Check it first:
shasum -a 256 rules-kit.zip        # must equal the hash in https://fortell.finance/rules-kit.zip.sha256
unzip rules-kit.zip && cd fortell-rules
pip install .                      # optional engine extras: pip install ".[vectorbt]" or ".[backtrader]"
python3 -c "import fortell_rules; print(fortell_rules.__version__)"
```

## 10-line example

```python
from fortell_rules import Deal, Terms, grade

terms = Terms.from_usd(start_usd=1000, window_secs=14*86_400,
                       profit_target_pct=5, max_loss_pct=6, best_day_share_pct=50, min_order_usd=5)

deals = [  # your backtest's CLOSED trades (margin and PnL in USD -> micro-units)
    Deal("PHOENIX-PERP-BTC", opened_at=0,      closed_at=3_600,  margin_micro=100_000_000, net_pnl_micro=30_000_000),
    Deal("PHOENIX-PERP-BTC", opened_at=90_000, closed_at=93_600, margin_micro=100_000_000, net_pnl_micro=30_000_000),
]

v = grade(terms, deals, started_at=0, now=14*86_400)
print(v.status, v.profit_micro, v.best_day_bps)   # "passed" 60000000 5000
```

All money is in **micro-units** (6 decimals): `$1 = 1_000_000`. Keeping every amount an integer is
what lets this kit match the on-chain grader, which never uses a float for money.

## Getting a tier's rules (never hard-code them)

Load a tier's rules from the public catalogue and pass the row straight through — unknown keys are
ignored:

- **Fortell MCP**: call `fortell_challenge_catalog` and take the tier you want to test against.
- **Public API**: the tier catalogue endpoint.

```python
import json, urllib.request
from fortell_rules import Terms

row = json.load(urllib.request.urlopen("https://<fortell-api>/tiers/<tier>"))  # or the MCP result
terms = Terms.from_mapping(row)        # reads startBalance, windowSecs, minProfitBps, ... as-is
```

`Terms.from_usd(...)` is only a convenience for a quick, hand-entered tier; prefer a real
catalogue row for a faithful grade.

## Getting candles (for your backtest)

This kit does **not** download market data. Use what Fortell already serves:

- **Fortell MCP** `fortell_price_history` (the public candle endpoint) for Phoenix Perps markets,
  and `fortell_perps_markets` for the market list and tick sizes.

Feed those candles to your own engine (VectorBT, Backtrader, Freqtrade, …); then hand the engine's
trade list to this kit through an adapter.

## Adapters

Each adapter turns an engine's output into the kit's `Deal` list (and, where the engine has one,
an equity curve of `EquityMark`). An adapter **only reshapes data** — it never grades and never
invents a margin (a perps backtest that did not model margin must say what margin to grade at).

```python
from fortell_rules.adapters import (
    deals_from_vectorbt,        # a vectorbt Portfolio
    deals_from_backtrader,      # a list of Backtrader closed Trades (or dicts)
    deals_from_freqtrade_json,  # a Freqtrade backtest-result JSON file
    deals_from_csv,             # a plain CSV / list of trades
)
```

See `examples/adapters_example.py`. In this repo's CI the adapters are tested against **mocked**
engine objects (the shape each engine returns), not the real libraries; the conversion logic is
what the tests pin.

## What it CANNOT model (read this)

A backtest pass is **never a guarantee** that an Evaluation will pass. This kit scores the rules;
it does not reproduce a live market. It cannot model:

- **live slippage** and the actual fill price your order would get;
- **funding** over the hold (it uses the PnL your backtest already computed);
- **liquidity** and partial fills at size;
- **fill timing** and the exact mark the risk engine reads.

Use it as a filter — "this strategy would not even clear the rules on historical data" is a strong
*no*; "it cleared the rules" is a *maybe*, not a *yes*.

## Running the tests

```bash
node scripts/gate.mjs        # python unit + adapter tests, then the parity harness
```
