Metadata-Version: 2.4
Name: quantpipe
Version: 0.1.0
Summary: Quantitative trading toolkit for LLM AI
Home-page: https://github.com/yourusername/quantpipe
Author: Your Name
Author-email: your.email@example.com
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: pandas>=2.0.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: click>=8.0.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# QuantPipe

Quantitative trading toolkit for LLM AI, designed to work seamlessly with [SeamFlux CLI](https://github.com/seamflux/seamflux-cli) via Unix pipes.

**Contract & layout:** See the repo root [`rule.md`](../rule.md) for shared conventions with chartpipe/seamflux (stdout JSON, exit codes, `runs/<runId>/`, etc.).

**Supported pipeline JSON:** `schemaVersion` **1** (see [Pipeline JSON](#pipeline-json-machine-readable) below).

**SeamFlux CLI (current syntax):** invoke services with `seamflux invoke <service> <method> [-p key=value ...]`. For piping into QuantPipe, prefer **`seamflux invoke ... --pipe`** so stdout is the raw payload JSON (no wrapper/no extra logs). QuantPipe also accepts a one-level wrapper `{"result": { ... }}` (no `jq` required).

## Features

- **Signal Generation**: Generate trading signals from market data
- **Backtesting**: Test strategies on historical data (supports Binance, Polymarket, and more)
- **Multi-symbol Scanning**: Scan multiple symbols for trading opportunities (default cap + optional `scan.json` output)
- **Paper Trading**: Simulate trading with real-time signals (supports Binance, Polymarket prediction markets)
- **Seamless Integration**: Works with seamflux CLI for market data via pipes
- **Multi-Market Support**: Native support for crypto exchanges (Binance) and prediction markets (Polymarket)

## Installation

```bash
pip install -r requirements.txt
```

Or install in development mode:

```bash
pip install -e .
```

## Exit codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General failure (invalid arguments, I/O error) |
| 2 | Input format / JSON schema mismatch |
| 3 | Upstream dependency failed (e.g. `--exec` subprocess non-zero, timeout, missing executable) |

Also shown at the bottom of `quantpipe --help`.

## Pipeline JSON (machine-readable)

With `--json`, commands print a **single-line** JSON object (use `--pretty` only for debugging; not for pipes).

**Success (shape):**

```json
{
  "schemaVersion": 1,
  "tool": "quantpipe",
  "command": "backtest",
  "ok": true,
  "data": { },
  "runId": "optional",
  "artifacts": { "summary": "runs/abc/summary.json", "trades": "runs/abc/trades.csv", "equity": "runs/abc/equity.csv" },
  "meta": { "startedAt": "ISO-8601", "finishedAt": "ISO-8601" }
}
```

**Failure:**

```json
{
  "schemaVersion": 1,
  "tool": "quantpipe",
  "command": "signal",
  "ok": false,
  "error": { "code": "INVALID_INPUT", "message": "human readable" }
}
```

The previous ad-hoc fields now live under **`data`** (e.g. `data.signal`, `data.performance`, `data.scan`).

## Runs directory (backtest)

Write CSV/JSON artifacts for orchestration/chartpipe:

```bash
quantpipe backtest --input btc_history.json --strategy ma_cross --json --run-id "$(uuidgen)"
# or
quantpipe backtest --input btc_history.json --strategy ma_cross --json --run-dir runs/my-run
```

Creates (when `--run-dir` or `--run-id` is set):

- `summary.json` — metrics + strategy + source (same as `data` in stdout envelope)
- `trades.csv` — closed trades (`timestamp`, `side`, `price`, `size`, …)
- `equity.csv` — `timestamp`, `equity`
- `manifest.json` — inputs, strategy, package version

Paths in stdout `artifacts` are relative to the current working directory when possible.

## Usage

### Common flags

- **`--data` / `-d` / `--input` / `-i`** — JSON input file (mutually redundant aliases)
- **`--stdin`** — read JSON from stdin
- **`--json`** — pipeline envelope on stdout
- **`--verbose` / `-v`** — debug logs on **stderr** only
- **`--dry-run`** — validate input/strategy (and `paper` `--exec` argv parsing); no heavy work / no artifact writes

### 1. Signal Generation

```bash
seamflux invoke binance fetchOhlcv --pipe \
  -p symbol=BTC/USDT \
  -p interval=1h \
  -p limit=100 | \
quantpipe signal --stdin --strategy ma_cross --json
```

Optional: `--output-dir DIR` writes full payload to `DIR/signal.json`; stdout still carries the envelope with `artifacts.signal`.

### 2. Backtesting

```bash
seamflux invoke binance fetchOhlcv --pipe \
  -p symbol=BTC/USDT \
  -p interval=1d \
  -p limit=365 > btc_history.json

quantpipe backtest --input btc_history.json --strategy ma_cross --json
```

### 3. Multi-symbol Scan

```bash
seamflux invoke binance fetchTickers --pipe \
  -p marketType=spot \
  -p symbols=BTCUSDT,ETHUSDT,SOLUSDT | \
quantpipe scan --stdin --strategy rsi --filter-signal BUY --json
```

- **Default `--limit` is 500** after sorting. Use **`--limit 0`** for no cap.
- **`--output-dir DIR`** writes the full result to **`DIR/scan.json`**; stdout envelope lists `artifacts.scan` and may omit the full `signals` list when the file is written.

Single-ticker responses and Polymarket **market snapshots** are supported. See `examples/binance_single_ticker.json` and `examples/polymarket_market_snapshot.json`.

### 4. Paper Trading

`--exec` is parsed with **`shlex.split` (no shell)**. Pass a single string of arguments as you would on the command line (quoted where needed). Use **`--exec-timeout`** (seconds, default 120) for subprocess timeouts.

```bash
quantpipe paper \
  --exec "seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=5m -p limit=50" \
  --interval 300 \
  --strategy ma_cross \
  --json
```

Streaming modes (`--exec` loop or `--stdin`) emit **one JSON envelope per iteration** (NDJSON) when `--json` is set.

Shell loop alternative:

```bash
while true; do
  seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=5m -p limit=50
  sleep 300
done | quantpipe paper --stdin --strategy ma_cross --json
```

## Polymarket Support

QuantPipe natively supports Polymarket prediction market data, enabling backtesting and paper trading on prediction markets.

### Data Format

- **Price History**: `history: [{t: timestamp, p: price}, ...]` → OHLCV candles
- **Market Snapshot**: `outcomePrices`, `question` → real-time market state

### Backtesting on Polymarket

```bash
seamflux invoke polymarket getPriceHistory --pipe \
  -p market=<TOKEN_ID> \
  -p interval=1d \
  -p startDate=2025-01-01 \
  -p endDate=2025-03-01 | \
quantpipe backtest --stdin --strategy ma_cross --param fast=10 --param slow=30 --pretty
```

### Paper Trading on Polymarket

```bash
quantpipe paper \
  --exec "seamflux invoke polymarket getPriceHistory --pipe -p market=<TOKEN_ID> -p interval=1h" \
  --interval 3600 \
  --strategy rsi \
  --param period=14 \
  --json
```

### Available Polymarket Methods

Use with `seamflux invoke polymarket <method>`:

- `getPriceHistory` - Fetch historical prices (for backtesting & signals)
- `getPrice` / `getPrices` - Current market prices
- `getMidpoint` / `getMidpoints` - Current mid-market prices
- `getOrderBook` - Order book depth
- `getMarket` / `getMarkets` - Market information
- `getEvents` - Event listings

## Strategies

### MA Cross (Moving Average Crossover)

```bash
quantpipe signal --stdin --strategy ma_cross --param fast=10 --param slow=30
```

Parameters: `fast`, `slow`, `ma_type` (`sma` / `ema`).

### RSI

```bash
quantpipe signal --stdin --strategy rsi --param period=14 --param oversold=30 --param overbought=70
```

### MACD

```bash
quantpipe signal --stdin --strategy macd --param fast=12 --param slow=26 --param signal=9
```

## Output format (`data` field examples)

### Signal (`data`)

```json
{
  "timestamp": "2024-01-01T12:00:00Z",
  "validUntil": "2024-01-01T13:00:00Z",
  "source": { "format": "binance_ohlcv", "market_type": "exchange", "type": "ohlcv", "symbol": "BTCUSDT", "bars": 100 },
  "strategy": { "name": "ma_cross", "params": {"fast": 10, "slow": 30} },
  "signal": { "action": "BUY", "confidence": 0.85, "price": 65000, "reason": "..." },
  "indicators": { "fastMa": 65100, "slowMa": 64900 },
  "metadata": { "synthesized": false, "interval": null }
}
```

### Backtest (`data`)

```json
{
  "source": { "symbol": "BTCUSDT", "market_type": "exchange", "type": "ohlcv", "bars": 500, "period": {"start": "...", "end": "..."} },
  "strategy": { "name": "ma_cross", "params": {"fast": 10, "slow": 30} },
  "performance": {
    "total_trades": 24,
    "win_rate": 0.625,
    "total_return": 0.255,
    "max_drawdown": -0.085,
    "sharpe_ratio": 1.85,
    "profit_factor": 1.2
  }
}
```

## CLI reference (summary)

| Command   | Notable options |
|-----------|-----------------|
| `signal`  | `--input`/`--data`, `--output-dir`, `--dry-run`, `--json` |
| `backtest`| `--run-dir`, `--run-id`, `--dry-run`, `--json` |
| `scan`    | `--limit` (default 500, `0` = unlimited), `--output-dir`, `--json` |
| `paper`   | `--exec`, `--exec-timeout`, `--once`, `--stdin`, `--json` |

## Orchestration example (rule.md §9)

```text
seamflux invoke ... > runs/id/input.json
quantpipe backtest --input runs/id/input.json --json --run-dir runs/id
chartpipe backtest --run-dir runs/id --json
```

## License

MIT
