Skip to main content
Glama
mcp-trading-research

mcp-trading-research

README.md
# mcp-trading-research

An [MCP](https://modelcontextprotocol.io) server (stdio) that gives an AI client three research tools for OHLCV candle data: **validation**, **technical indicators** and a **look-ahead-safe backtester**.

> **Research tool, not financial advice.** It places no orders, talks to no broker and makes no claim that any strategy is or will be profitable. All numbers shown here come from synthetic sample data.

## Problem

When an LLM "analyses" price data it often does it from memory or with ad-hoc code: unvalidated candles, indicators with unclear formulas, and backtests that quietly trade on information from the future. This server gives the model deterministic, documented tools instead, and makes the most common backtest mistake (look-ahead) structurally hard to commit.

## Install

Requires Python 3.11+ (developed and tested on 3.14) and the official `mcp` SDK (v2.x, installed automatically).

```bash
git clone <this repository> && cd mcp-trading-research
python3 -m venv .venv
.venv/bin/pip install .                      # or: pip install -r requirements.lock && pip install --no-deps .
.venv/bin/mcp-trading-research --help
```

`requirements.lock` (runtime) and `requirements-dev.lock` (runtime + pytest, ruff, mypy) are `pip freeze` output from the venv used to develop and test this repo (macOS, Python 3.14).

## Register in an MCP client

The server speaks MCP over stdio. Give it a data directory only if you want it to read CSV files; without one, only inline `candles` work.

Claude Desktop / any client using the `mcpServers` JSON format (use absolute paths):

```json
{
  "mcpServers": {
    "trading-research": {
      "command": "/absolute/path/to/mcp-trading-research/.venv/bin/mcp-trading-research",
      "args": ["--data-dir", "/absolute/path/to/mcp-trading-research/data"]
    }
  }
}
```

Claude Code: `claude mcp add trading-research -- /absolute/path/.venv/bin/mcp-trading-research --data-dir /absolute/path/data`

The data directory can also be set with the `MCP_TRADING_DATA_DIR` environment variable (`--data-dir` wins).

These client configs follow each client's documented format but were not run inside Claude Desktop or Claude Code for this repo; the server itself was exercised end to end with the MCP Python SDK client (see Tests).

## Tools

Every tool takes **exactly one** of `candles` (inline list of `{timestamp, open, high, low, close, volume}`) or `csv_path` (relative to the data directory). Timestamps are ISO-8601 strings or numbers.

### `validate_ohlcv`

Returns a structured issue list. Checks: monotonic timestamps (duplicates and out-of-order reported separately), `high >= max(open, close)`, `low <= min(open, close)`, no NaN/inf/non-numeric values, prices > 0, `volume >= 0`, all fields present. Codes: `MISSING_FIELD`, `NOT_A_NUMBER`, `BAD_TIMESTAMP`, `DUPLICATE_TIMESTAMP`, `NON_MONOTONIC_TIMESTAMP`, `NON_POSITIVE_PRICE`, `HIGH_BELOW_BODY`, `LOW_ABOVE_BODY`, `NEGATIVE_VOLUME`, `NOT_AN_OBJECT`.

Call: `validate_ohlcv(candles=[{"timestamp":"2024-01-01","open":10,"high":12,"low":9,"close":11,"volume":5}, {"timestamp":"2024-01-01","open":11,"high":10,"low":9,"close":11.5,"volume":-3}])`

Real output:

```json
{
  "valid": false,
  "row_count": 2,
  "issue_count": 3,
  "issue_counts_by_code": {"DUPLICATE_TIMESTAMP": 1, "HIGH_BELOW_BODY": 1, "NEGATIVE_VOLUME": 1},
  "issues": [
    {"index": 1, "code": "DUPLICATE_TIMESTAMP", "field": "timestamp", "message": "duplicate timestamp: '2024-01-01'"},
    {"index": 1, "code": "NEGATIVE_VOLUME", "field": "volume", "message": "volume must be >= 0, got -3.0"},
    {"index": 1, "code": "HIGH_BELOW_BODY", "field": "high", "message": "high 10.0 < max(open, close) 11.5"}
  ],
  "issues_truncated": false
}
```

(The server returns this as indented JSON; compacted here.) `compute_indicators` and `run_backtest` refuse to run on invalid data and return the same issue structure with `"valid": false`.

### `compute_indicators`

`indicators`: list of `{"name": "sma"|"ema"|"rsi"|"atr", "period": N}`; optional `last_n` limits output rows. Values inside the warm-up window are `null`, rounded to 8 decimals.

Formulas (n = period), all computed from closes unless noted, and `out[t]` only reads bars `0..t`:

| Indicator | Definition |
|---|---|
| SMA | `mean(close[t-n+1..t])`, first value at `t = n-1` |
| EMA | `alpha = 2/(n+1)`; seed `EMA[n-1] = SMA[n-1]`; `EMA[t] = alpha*close[t] + (1-alpha)*EMA[t-1]` |
| RSI (Wilder) | seed `avgGain/avgLoss` = mean of the first n changes; then `avg[t] = (avg[t-1]*(n-1) + x[t]) / n`; `RSI = 100 - 100/(1 + avgGain/avgLoss)`; if `avgLoss = 0`: 100 (or 50 if also `avgGain = 0`); first value at `t = n` |
| ATR (Wilder) | `TR[0] = high-low`, `TR[t] = max(high-low, abs(high-prevClose), abs(low-prevClose))`; seed `ATR[n-1] = mean(TR[0..n-1])`; then `ATR[t] = (ATR[t-1]*(n-1) + TR[t]) / n` |

Call: `compute_indicators(indicators=[{"name":"sma","period":3},{"name":"atr","period":3}], candles=[...5 candles...])`

Real output (5 hand-made candles, trimmed to the `indicators` field):

```json
{"sma_3": [null, null, 10.76666667, 11.1, 11.43333333],
 "atr_3": [null, null, 1.4, 1.5, 1.5]}
```

On the bundled sample file (`csv_path="sample_ohlcv.csv"`, `last_n=3`, SMA 20 and RSI 14):

```json
{"timestamps": ["2024-09-04", "2024-09-05", "2024-09-06"],
 "indicators": {"sma_20": [77.2595, 77.353, 77.5145],
                "rsi_14": [48.28056637, 53.036485, 53.23149425]}}
```

### `run_backtest`

Long-only SMA crossover on a single asset. Parameters: `fast_period` (10), `slow_period` (30), `fee_rate` (0.001 per side), `slippage_rate` (0.0005), `initial_cash` (10000), `include_equity` (true).

Rules:

1. At the close of bar `t` the strategy sees bars `0..t` and wants to be long if `SMA(fast) > SMA(slow)`, flat otherwise.
2. If that changes the position, the order **fills at the open of bar `t+1`**. Buys fill at `open*(1+slippage)`, sells at `open*(1-slippage)`; the fee is `fee_rate * notional` per side. Each entry invests all cash.
3. A signal on the final bar cannot execute and is dropped (`dropped_final_signal`).
4. A position still open on the last bar is closed at that bar's close (with slippage and fee), marked `exit_reason: "end_of_data"`, and the last equity point is net of that exit.
5. Equity is `cash + qty * close[t]`. `max_drawdown` is the largest peak-to-trough fall as a fraction of the peak, with the starting capital counting as the first peak.

Call: `run_backtest(csv_path="sample_ohlcv.csv", include_equity=false)`

Real output (synthetic data, so the numbers carry no information about any market; first of 4 trades shown):

```json
{
  "valid": true,
  "strategy": {"name": "sma_crossover", "fast_period": 10, "slow_period": 30,
               "rule": "long while SMA(fast) > SMA(slow) at bar t close; order fills at open of bar t+1"},
  "config": {"initial_cash": 10000.0, "fee_rate": 0.001, "slippage_rate": 0.0005},
  "bar_count": 250,
  "number_of_trades": 4,
  "total_return": 0.02602581,
  "max_drawdown": 0.14450199,
  "final_equity": 10260.25811799,
  "total_fees": 83.11732542,
  "dropped_final_signal": false,
  "trades": [
    {"entry_signal_bar": 29, "entry_bar": 30, "entry_time": "2024-01-31", "entry_price": 117.768855,
     "exit_signal_bar": 62, "exit_bar": 63, "exit_time": "2024-03-04", "exit_price": 125.946995,
     "quantity": 84.827266, "fees": 20.67374924, "pnl": 673.05550796, "return_pct": 0.06730555,
     "exit_reason": "signal"}
  ]
}
```

#### Look-ahead protection

* Strategies get a `History` view of bars `0..t`. Reading `history[t+1]` raises `LookAheadError`; a test with a strategy that peeks at tomorrow's close asserts the backtest is rejected.
* A perturbation test replaces every bar after index `k` with different data and asserts that signals and equity up to `k`, and all fills up to `k`, are identical.
* Tests with hand-computed fills assert the entry price equals the next bar's open, and that changing only the open of bar `t+1` moves the fill but not the signal.
* I also checked that these tests catch the bug they target: temporarily making the engine hand the strategy bar `t+1` made 6 tests fail (mutation check, not part of the suite).

`History` is a guard, not a sandbox: a Python strategy can still capture the full list in a closure. The MCP tool only exposes the built-in SMA crossover, so MCP clients cannot supply code.

## CSV access

CSV loading is off unless a data directory is configured (`--data-dir` or `MCP_TRADING_DATA_DIR`). `csv_path` is resolved with symlinks followed and must land inside that directory; `..` traversal, absolute paths elsewhere, and symlinks (file or directory) that point outside are rejected. Only regular `.csv` files up to 10 MB and 200,000 rows are read. Expected header: `timestamp,open,high,low,close,volume`. There is a small check-then-open race window (a path could be swapped between resolution and read); do not point the server at a directory that untrusted processes can write to.

`data/sample_ohlcv.csv` holds 250 **synthetic** daily candles (seeded random walk, `scripts/generate_sample_data.py`). It is not market data.

## Limitations

* Single asset, long-only, all-in sizing, one rule family (SMA crossover). No shorting, leverage, position sizing, stops or portfolio logic.
* No liquidity or market-impact model: fills assume the full size trades at the open price plus a fixed slippage fraction. No partial fills, spreads, borrow costs, funding, taxes or gaps beyond what the open already shows.
* No survivorship, delisting, corporate-action or dividend handling; prices are used as supplied.
* No timezone, session or calendar handling: timestamps are only checked for order and uniqueness. Naive ISO timestamps are treated as UTC.
* Validation cannot tell whether supplied prices are real or correctly adjusted.
* Backtest results are in-sample by construction and say nothing about future performance. Parameters are not optimised or cross-validated here.
* Indicators are pure Python and meant for research-sized data (inline limit 50,000 candles, CSV limit 200,000 rows), not high-frequency volumes.
* Tested on macOS with Python 3.14 only.

## Tests

```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements-dev.lock && .venv/bin/pip install --no-deps -e .
.venv/bin/ruff check . && .venv/bin/ruff format --check .
.venv/bin/mypy
.venv/bin/pytest
.venv/bin/python scripts/smoke_stdio.py   # prints real stdio responses from the server
```

No test uses the network. `tests/test_server_stdio.py` starts the server as a subprocess and drives it with the SDK's stdio client (initialize, list tools, call all three tools, error paths).

## License

MIT, see [LICENSE](LICENSE). Contributions: see [CONTRIBUTING.md](CONTRIBUTING.md).