backtest-referee
by midomek
README.md
# Backtest Referee
**Most backtests lie: the rule gets tuned until the chart looks good. Backtest Referee makes you freeze the rule on Solana *before* you see a result, then tests it on Coingecko data it wasn't designed on and gives a PASS / FAIL / INCONCLUSIVE verdict with every check shown.**
Track: *Long Tail — AI Agents with Coingecko Data*. It works as an **MCP server for AI assistants** (Claude Code, Cursor, any MCP client) and as a **web app** for people.
## Why
An AI agent asked "does this strategy work?" will happily backtest it, tweak it, and report the best-looking variant. That number is noise. The referee is the missing guardrail:
1. **Freeze first.** A rule is turned into canonical JSON and hashed (sha-256). The hash can be written to Solana with the Memo program, so the time the rule was fixed is public and tamper-proof.
2. **Test on data the rule didn't shape.** The history is split in time: the first part is the design period, the rest is the test, reported as two halves.
3. **Fixed pass rules, decided in code, not by the user or the agent.** PASS needs, in *both* test halves: ≥ 20 trades, mean > 0, median > 0, and a better result than buying at any bar; plus a positive test result without its 3 best trades. Fewer trades = INCONCLUSIVE.
4. **Count the variants.** Re-tuned versions of the same idea share a *family hash*. When earlier variants were already tested, the referee says so: *with k tries, the best one looks good by chance.*
Every number in a verdict is traceable to Coingecko data. The agent reports the referee's numbers, not its own.
## Run it
Requires Node.js 20+ and no npm packages.
```bash
git clone https://github.com/midomek/backtest-referee && cd backtest-referee
npm start # web app on http://localhost:8788
```
Optional: `cp .env.example .env` and add a Coingecko API key (`COINGECKO_API_KEY`). Without a key it runs on public limits: coin prices up to 90 days hourly / 365 days daily, and Solana pool history up to 180 days. Keys are git-ignored.
### As an MCP server (AI agents)
```bash
claude mcp add backtest-referee -- node /absolute/path/to/backtest-referee/mcp.js
```
Then ask your assistant, for example: *"Test whether buying SOL after a 4-sigma hourly drop and holding for a day has an edge."* It will call:
| Tool | What it does |
|---|---|
| `rule_language` | the rule format, signals and pass rules |
| `register_rule` | freeze a rule → hash, plain-English description, memo text, variant number |
| `attach_onchain_proof` | verify a Solana memo transaction carrying the hash and attach it |
| `run_test` | run the backtest for a **registered** rule → verdict, checks, period stats, overfitting warning |
| `list_rules` | the registry with on-chain proofs and verdicts |
Testing an unregistered rule is refused.
### As a CLI
```bash
node src/cli.js example > rule.json
node src/cli.js register rule.json
node src/cli.js anchor <hash prefix> # optional: write the fingerprint to Solana devnet
node src/cli.js test <hash prefix>
node src/cli.js list
```
## The rule format
```json
{
"name": "Buy SOL after a 4-sigma hourly drop",
"universe": [{ "coin": "solana" }],
"interval": "hour",
"signal": { "type": "drop_sigma", "lookback": 1, "sigma": 4 },
"exit": { "hold": 24, "stop": null, "take": null },
"cost": 0.004,
"split": { "discovery": 0.6 }
}
```
- **universe:** Coingecko coin ids (`{"coin": "bitcoin"}`), Solana token addresses (`{"mint": "..."}` → deepest Solana pool), or a Coingecko category (`{"category": "xstocks-ecosystem", "top": 10}`).
- **signals:** `drop_sigma`, `drop_pct`, `rise_pct`, `ma_cross_up`, `volume_spike`, all computed from past bars only.
- **exit:** hold N bars, optional stop and take-profit (checked on closes).
- **cost:** round-trip cost subtracted from every trade.
## How Coingecko API is used
| Endpoint | Used for |
|---|---|
| `/coins/{id}/market_chart` | hourly/daily prices and volumes for coin universes |
| `/coins/markets?category=…` | category universes (e.g. tokenized stocks, Solana meme coins) |
| `/onchain/networks/solana/tokens/{mint}/pools` | deepest Solana pool for a token address |
| `/onchain/networks/solana/pools/{pool}/ohlcv/{hour,day}` | pool price history (paged with `before_timestamp`) |
Responses are cached on disk (`.cache/`), so a verdict can be reproduced exactly.
## How Solana is used
- **On-chain pre-registration:** a Memo-program transaction carrying `BTREF1 <ruleHash>` is written to Solana. Two ways:
- **mainnet, with your own wallet:** the web app builds the transaction and you sign it in Phantom (about 0.000005 SOL);
- **devnet, no wallet needed:** the server (or `node src/cli.js anchor <hash>`) signs with a local keypair that is created on first use and git-ignored. Fund it once with free test SOL at https://faucet.solana.com (network: Devnet). Example: [a frozen rule on devnet](https://solscan.io/tx/5RS4SpaU7xhTxyeoFhijUg2wmsBYyYgrnp2DoyubTy1ppzzPWQbGx3LeauNPqvij3uXd9fpnP6y6iRLiSLA59Tm8?cluster=devnet).
Either way the server verifies the memo through Solana RPC (`getTransaction`) and records the block time, so anyone can check that the rule existed before its test.
- **Solana markets:** any SPL token can be tested through its Coingecko onchain pool data.
## What the verdict looks like
```
VERDICT: INCONCLUSIVE — Too few test trades to judge (need 20 in each half).
✗ test-1: at least 20 trades (has 4)
✗ test-1: mean net return > 0 (-0.51%)
✓ test-1: beats buying at any bar (-0.51% vs -1.92%)
...
```
INCONCLUSIVE is a real answer. Most "edges" people show online would get it.
## Structure
```
mcp.js MCP server (stdio JSON-RPC, no dependencies)
server.js web app + JSON API
src/rule.js rule format, validation, canonical hash, family hash, plain-English description
src/registry.js pre-registration registry, variant counting, overfitting warning
src/engine.js backtest engine, background, fixed verdict rules
src/data.js Coingecko price series (coins, categories, Solana pools)
src/solana.js on-chain memo verification
src/anchor.js memo transactions from a local keypair (no dependencies: node:crypto ed25519)
src/cg.js Coingecko client (key handling, rate limit, disk cache)
public/ web UI (vanilla JS, Chart.js, @solana/web3.js)
```
Built from 4 Dec 2026 for the Long Tail hackathon. MIT license. Not financial advice.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues