Metadata-Version: 2.1
Name: quantpipe
Version: 0.1.2
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
Requires-Dist: requests>=2.28.0

# 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).

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Exit Codes](#exit-codes)
- [Commands](#commands)
  - [Signal Generation](#1-signal-generation)
  - [Backtesting](#2-backtesting)
  - [Multi-symbol Scanning](#3-multi-symbol-scan)
  - [Paper Trading](#4-paper-trading)
- [Data Formats](#data-formats)
- [Strategies](#strategies)
- [Output Formats](#output-formats)
- [CLI Reference](#cli-reference)
- [Orchestration](#orchestration-example-rulmd-9)
- [License](#license)

## Features

### Core Trading Operations

- **Signal Generation**: Generate trading signals (BUY/SELL/HOLD) from market data using technical indicators
- **Backtesting**: Test strategies on historical data with detailed performance metrics
- **Multi-symbol Scanning**: Scan multiple symbols for trading opportunities with filtering and sorting
- **Paper Trading**: Simulate trading with real-time signals supporting both LONG and SHORT positions

### Market Support

- **Binance**: OHLCV candles, single tickers, multi-ticker snapshots
- **Polymarket**: Price history, market snapshots, prediction market data
- **Uniswap**: DEX pool day data via TheGraph
- **Generic Formats**: OHLCV, price history with automatic format detection

### Technical Indicators

- **Moving Averages (MA)**: SMA and EMA with configurable periods
- **RSI**: Relative Strength Index with oversold/overbought thresholds
- **MACD**: Moving Average Convergence Divergence with histogram
- **Supertrend**: ATR-based trend following indicator
- **Stochastic Oscillator**: Momentum indicator with %K and %D lines
- **ADX**: Average Directional Index for trend strength
- **VWAP**: Volume Weighted Average Price
- **Pivot Points**: Support/resistance levels (standard, Fibonacci, Woodie)
- **Bollinger Bands**: Mean reversion with configurable bands

### Pipeline Integration

- **Seamless SeamFlux Integration**: Works with `seamflux invoke` via Unix pipes
- **JSON Envelope Output**: Machine-readable pipeline JSON format
- **Artifact Management**: Writes runs, trades, equity curves to filesystem
- **Flexible Input**: Read from stdin, file, or subprocess execution

## 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`.

## Commands

### Common Flags

| Flag | Description |
|------|-------------|
| `--data` / `-d` / `--input` / `-i` | JSON input file (mutually redundant aliases) |
| `--stdin` | Read JSON from stdin |
| `--json` | Pipeline envelope on stdout |
| `--pretty` | Pretty-print JSON (not for pipes) |
| `--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

Generate trading signals from market data with strategy-specific parameters.

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

# From Polymarket
seamflux invoke polymarket getPriceHistory --pipe \
  -p market=<TOKEN_ID> \
  -p interval=1h | \
quantpipe signal --stdin --strategy rsi --param period=14 --json

# With custom parameters
quantpipe signal --stdin --strategy macd \
  --param fast=12 --param slow=26 --param signal=9 \
  --json

# Write full payload to file
quantpipe signal --data btc_history.json --strategy ma_cross \
  --output-dir ./signals --json
```

**Signal Command Options:**

| Option | Description |
|--------|-------------|
| `--strategy` / `-s` | Strategy name (required) |
| `--param KEY=VALUE` | Strategy parameters (repeatable) |
| `--output-dir DIR` | Write full payload to `DIR/signal.json` |
| `--dry-run` | Validate without computing signal |

### 2. Backtesting

Run backtests on historical data with comprehensive performance metrics.

```bash
# Basic backtest
quantpipe backtest --data btc_history.json --strategy ma_cross --json

# With custom strategy parameters
quantpipe backtest --data btc_history.json --strategy rsi \
  --param period=14 --param oversold=25 --param overbought=75 \
  --json

# With run artifacts (creates runs/<runId>/)
quantpipe backtest --input btc_history.json --strategy ma_cross \
  --run-id "$(uuidgen)" --json

# Custom output directory
quantpipe backtest --input btc_history.json --strategy macd \
  --run-dir ./runs/my-backtest --json

# Polymarket backtest
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
```

**Backtest Artifacts:**

When `--run-dir` or `--run-id` is set, creates:

- `summary.json` — metrics + strategy + source
- `trades.csv` — closed trades with entry/exit times, prices, PnL
- `equity.csv` — equity curve over time
- `manifest.json` — inputs, strategy, package version

**Performance Metrics:**

| Metric | Description |
|--------|-------------|
| `total_trades` | Total number of completed trades |
| `winning_trades` | Number of profitable trades |
| `losing_trades` | Number of losing trades |
| `long_trades` | Number of LONG positions |
| `short_trades` | Number of SHORT positions |
| `win_rate` | Percentage of winning trades |
| `total_return` | Overall return percentage |
| `annualized_return` | Return normalized to annual |
| `max_drawdown` | Maximum peak-to-trough decline |
| `sharpe_ratio` | Risk-adjusted return metric |
| `profit_factor` | Gross profit / gross loss |

**Backtest Command Options:**

| Option | Description |
|--------|-------------|
| `--strategy` / `-s` | Strategy name (required) |
| `--param KEY=VALUE` | Strategy parameters (repeatable) |
| `--run-dir DIR` | Write artifacts to specified directory |
| `--run-id ID` | Write artifacts to `runs/<ID>/` |
| `--dry-run` | Validate without running backtest |

### 3. Multi-symbol Scan

Scan multiple symbols and generate signals with filtering and sorting.

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

# Scan with custom limit
seamflux invoke binance fetchTickers --pipe \
  -p marketType=spot | \
quantpipe scan --stdin --strategy ma_cross \
  --limit 100 --sort-by confidence --json

# No limit (output all results)
quantpipe scan --data tickers.json --strategy rsi --limit 0 --json

# Write full results to file
quantpipe scan --stdin --strategy macd \
  --output-dir ./scans --filter-signal BUY --json
```

**Scan Data Types:**

- **Binance Tickers**: Multiple symbols via `fetchTickers`
- **Binance Single Ticker**: Single symbol via `fetchTicker`
- **Polymarket Markets**: Market snapshots with outcome prices

**Scan Command Options:**

| Option | Description |
|--------|-------------|
| `--strategy` / `-s` | Strategy name (required) |
| `--param KEY=VALUE` | Strategy parameters (repeatable) |
| `--filter-signal TYPE` | Filter by BUY, SELL, or HOLD |
| `--sort-by FIELD` | Sort by `confidence`, `price`, or `symbol` (default: confidence) |
| `--limit N` | Max results after sort (default 500, `0` = unlimited) |
| `--output-dir DIR` | Write full results to `DIR/scan.json` |

### 4. Paper Trading

Simulate trading with real-time signals. Supports LONG and SHORT positions with automatic position tracking.

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

# Run once and exit
quantpipe paper \
  --exec "seamflux invoke polymarket getMarket --pipe -p slug=<market_slug>" \
  --strategy rsi --once --json

# From stdin (streaming)
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=5m -p limit=50 \
  | quantpipe paper --stdin --strategy ma_cross --json

# Shell loop alternative
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 paper trading
quantpipe paper \
  --exec "seamflux invoke polymarket getPriceHistory --pipe -p market=<TOKEN_ID> -p interval=1h" \
  --interval 3600 \
  --strategy rsi \
  --param period=14 \
  --json
```

**Position Logic:**

- `BUY` signal: Opens LONG if flat, or closes SHORT if holding one
- `SELL` signal: Opens SHORT if flat, or closes LONG if holding one
- Position changes are tracked across iterations

**Paper Trading Command Options:**

| Option | Description |
|--------|-------------|
| `--exec CMD` | Command to execute in loop (parsed with `shlex.split`) |
| `--interval SEC` | Polling interval in seconds (default 60) |
| `--exec-timeout SEC` | Timeout per execution (default 120) |
| `--once` | Run once and exit |
| `--stdin` | Read from stdin continuously |
| `--strategy` / `-s` | Strategy name (required) |
| `--param KEY=VALUE` | Strategy parameters (repeatable) |

## Data Formats

QuantPipe auto-detects data formats. Supported formats:

### Exchange Formats

#### Binance OHLCV

```json
{
  "candles": [
    [1699008000000, 35000.0, 35100.0, 34900.0, 35050.0, 100.5, ...],
    ...
  ],
  "message": "OHLCV for BTC/USDT"
}
```

#### Binance Tickers (multi-symbol)

```json
{
  "tickers": [
    {"symbol": "BTCUSDT", "last": 35000.0, "bid": 34999.0, "ask": 35001.0, ...},
    {"symbol": "ETHUSDT", "last": 2000.0, "bid": 1999.0, "ask": 2001.0, ...}
  ]
}
```

#### Binance Single Ticker

```json
{
  "symbol": "BTCUSDT",
  "last": 35000.0,
  "bid": 34999.0,
  "ask": 35001.0,
  "high": 35200.0,
  "low": 34800.0,
  "volume": 10000.0
}
```

### Prediction Market Formats

#### Polymarket Price History

```json
{
  "history": [
    {"t": 1699008000, "p": 0.55},
    {"t": 1699094400, "p": 0.58},
    ...
  ]
}
```

#### Polymarket Market Snapshot

```json
{
  "outcomePrices": ["0.45", "0.55"],
  "outcomes": ["No", "Yes"],
  "question": "Will BTC reach $100k by 2025?",
  "volumeNum": 1000000,
  "liquidityNum": 500000,
  "slug": "btc-100k-2025"
}
```

### DEX Formats

#### Uniswap Candles

```json
{
  "poolDayData": [
    {"date": 1699008000, "open": 3500.0, "high": 3600.0, "low": 3400.0, "close": 3550.0, "volumeUSD": 1000000},
    ...
  ]
}
```

### Generic Formats

#### Generic OHLCV

```json
{
  "data": [
    {"time": 1699008000000, "open": 35000.0, "high": 35100.0, "low": 34900.0, "close": 35050.0, "volume": 100.5},
    ...
  ]
}
```

#### Generic Price History

```json
{
  "prices": [
    {"timestamp": 1699008000000, "price": 35000.0},
    {"timestamp": 1699094400000, "price": 35100.0},
    ...
  ]
}
```

### Auto-Detection

QuantPipe automatically detects formats based on:

1. Field presence (`candles`, `tickers`, `history`, `outcomePrices`, etc.)
2. Data structure analysis
3. Field value types

Use `--verbose` to see detected format in logs.

## Strategies

### MA Cross (Moving Average Crossover)

Buy when fast MA crosses above slow MA, sell on reverse crossover.

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

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `fast` | 10 | Fast MA period |
| `slow` | 30 | Slow MA period |
| `ma_type` | `sma` | MA type: `sma` or `ema` |

**Signal Logic:**

- `BUY`: Fast MA crosses above Slow MA
- `SELL`: Fast MA crosses below Slow MA
- `HOLD`: No crossover detected

### RSI (Relative Strength Index)

Mean reversion strategy based on overbought/oversold levels.

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

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `period` | 14 | RSI calculation period |
| `oversold` | 30 | Oversold threshold |
| `overbought` | 70 | Overbought threshold |

**Signal Logic:**

- `BUY`: RSI <= oversold level
- `SELL`: RSI >= overbought level
- `HOLD`: RSI within neutral zone

### MACD (Moving Average Convergence Divergence)

Momentum strategy based on MACD line crossovers.

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

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `fast` | 12 | Fast EMA period |
| `slow` | 26 | Slow EMA period |
| `signal` | 9 | Signal line EMA period |

**Signal Logic:**

- `BUY`: MACD line crosses above signal line
- `SELL`: MACD line crosses below signal line
- `HOLD`: Lines aligned

### Supertrend

Trend following strategy based on ATR and price position.

```bash
quantpipe signal --stdin --strategy supertrend --param period=10 --param multiplier=3.0
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `period` | 10 | ATR calculation period |
| `multiplier` | 3.0 | ATR multiplier for bands |

**Signal Logic:**

- `BUY`: Trend changes from downtrend to uptrend
- `SELL`: Trend changes from uptrend to downtrend
- `HOLD`: No trend change

### Stochastic Oscillator

Momentum strategy based on %K and %D crossovers.

```bash
quantpipe signal --stdin --strategy stochastic --param k_period=14 --param d_period=3 --param oversold=20 --param overbought=80
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `k_period` | 14 | %K calculation period |
| `d_period` | 3 | %D (SMA of %K) period |
| `oversold` | 20 | Oversold threshold |
| `overbought` | 80 | Overbought threshold |

**Signal Logic:**

- `BUY`: %K crosses above %D in oversold zone
- `SELL`: %K crosses below %D in overbought zone
- `HOLD`: No crossover or outside extreme zones

### ADX (Average Directional Index)

Trend strength strategy using directional indicators.

```bash
quantpipe signal --stdin --strategy adx --param period=14 --param adx_threshold=25
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `period` | 14 | ADX calculation period |
| `adx_threshold` | 25 | Minimum ADX for trend signals |

**Signal Logic:**

- `BUY`: ADX > threshold and +DI crosses above -DI
- `SELL`: ADX > threshold and -DI crosses above +DI
- `HOLD`: ADX below threshold or no crossover

### VWAP (Volume Weighted Average Price)

Mean reversion strategy using VWAP crossover.

```bash
quantpipe signal --stdin --strategy vwap --param max_deviation=0.02
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `max_deviation` | 0.02 | Maximum deviation for reversion signals (2%) |

**Signal Logic:**

- `BUY`: Price crosses above VWAP, or price below VWAP with extreme deviation
- `SELL`: Price crosses below VWAP, or price above VWAP with extreme deviation
- `HOLD`: Price within deviation range

### Pivot Points

Breakout strategy using pivot support/resistance levels.

```bash
quantpipe signal --stdin --strategy pivot --param pivot_type=standard
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `pivot_type` | `standard` | Type: `standard`, `fibonacci`, `woodie` |

**Signal Logic:**

- `BUY`: Price breaks above R1 (first resistance)
- `SELL`: Price breaks below S1 (first support)
- `HOLD`: Price within pivot range

### Bollinger Bands

Mean reversion or breakout strategy using Bollinger Bands.

```bash
quantpipe signal --stdin --strategy bollinger --param period=20 --param std=2.0 --param mode=bands
```

**Parameters:**

| Parameter | Default | Description |
|-----------|---------|-------------|
| `period` | 20 | MA period for middle band |
| `std` | 2.0 | Standard deviation multiplier |
| `mode` | `bands` | `bands` (reversion) or `bands_breakout` (trend) |

**Signal Logic:**

- `BUY` (bands mode): Price touches lower band (oversold)
- `SELL` (bands mode): Price touches upper band (overbought)
- `BUY` (breakout mode): Price breaks above upper band
- `SELL` (breakout mode): Price breaks below lower band

## Output Formats

### Pipeline JSON Envelope (Machine-Readable)

All commands support `--json` for machine-readable output:

```json
{
  "schemaVersion": 1,
  "tool": "quantpipe",
  "command": "signal",
  "ok": true,
  "data": { ... },
  "runId": "optional",
  "artifacts": { "signal": "signals/signal.json" },
  "meta": { "startedAt": "2024-01-01T12:00:00.000Z", "finishedAt": "2024-01-01T12:00:01.000Z" }
}
```

**Failure Envelope:**

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

### Signal Output (`data` field)

```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": "SMA Crossover: Fast(10)=65100 crossed above Slow(30)=64900"
  },
  "indicators": { "fastMa": 65100, "slowMa": 64900 },
  "metadata": { "synthesized": false, "interval": null }
}
```

### Backtest Output (`data` field)

```json
{
  "source": {
    "symbol": "BTCUSDT",
    "market_type": "exchange",
    "type": "ohlcv",
    "bars": 500,
    "period": { "start": "2023-01-01T00:00:00Z", "end": "2024-01-01T00:00:00Z" }
  },
  "strategy": { "name": "ma_cross", "params": {"fast": 10, "slow": 30} },
  "performance": {
    "total_trades": 24,
    "winning_trades": 15,
    "losing_trades": 9,
    "long_trades": 14,
    "short_trades": 10,
    "win_rate": 0.625,
    "total_return": 0.255,
    "annualized_return": 0.12,
    "max_drawdown": -0.085,
    "sharpe_ratio": 1.85,
    "profit_factor": 1.2
  }
}
```

### Scan Output (`data.scan` field)

```json
{
  "timestamp": "2024-01-01T12:00:00Z",
  "strategy": "rsi",
  "market_type": "exchange",
  "scan": {
    "totalScanned": 500,
    "summary": { "BUY": 45, "SELL": 32, "HOLD": 423 },
    "returned": 45,
    "limit": 500,
    "truncated": false,
    "signals": [
      {
        "symbol": "BTCUSDT",
        "signal": "BUY",
        "price": 65000,
        "confidence": 0.85,
        "indicators": { "rsi": 28 }
      }
    ]
  }
}
```

### Paper Trading Output (`data` field)

```json
{
  "timestamp": "2024-01-01T12:00:00Z",
  "mode": "paper",
  "session": {
    "startedAt": "2024-01-01T10:00:00Z",
    "signalsGenerated": 5
  },
  "source": { "symbol": "BTCUSDT", "type": "ohlcv" },
  "strategy": { "name": "ma_cross", "params": {"fast": 10, "slow": 30} },
  "signal": {
    "action": "BUY",
    "price": 65000,
    "confidence": 0.85,
    "reason": "SMA Crossover: Fast(10)=65100 crossed above Slow(30)=64900"
  },
  "paperTrading": {
    "previousPosition": "FLAT",
    "currentPosition": "LONG",
    "positionChanged": true
  }
}
```

## CLI Reference

| Command | Notable Options | Description |
|---------|------------------|-------------|
| `signal` | `--input`/`--data`, `--output-dir`, `--dry-run`, `--json` | Generate trading signal |
| `backtest` | `--run-dir`, `--run-id`, `--dry-run`, `--json` | Run backtest on historical data |
| `scan` | `--limit` (default 500, `0` = unlimited), `--output-dir`, `--filter-signal`, `--sort-by`, `--json` | Scan multiple symbols |
| `paper` | `--exec`, `--exec-timeout`, `--once`, `--stdin`, `--json` | Paper trading simulation |
| `analyze` | `--method` (monte-carlo, walk-forward, regime), `--trades`, `--data`, `--json` | Advanced analysis |

## Polymarket Support

QuantPipe natively supports Polymarket prediction market data.

### Available Polymarket Methods

Use with `seamflux invoke polymarket <method>`:

| Method | Description |
|--------|-------------|
| `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 |

### Polymarket Data Handling

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

## Technical Details

### OHLCV Synthesis

For data sources that only provide price points (e.g., Polymarket), QuantPipe automatically synthesizes OHLCV candles:

- **High/Low/Open/Close**: Derived from price points within each interval
- **Volume**: Count of price points in each interval
- **Auto-interval**: Detected based on data density (1min, 5min, 1h, 1d)

### Look-Ahead Bias Prevention

Backtesting uses rolling window analysis:
- Strategy is re-initialized on each bar
- Indicators only use information available up to that point
- No future data leaks into signal generation

### Commission Modeling

Default commission of 0.1% per trade (0.2% round-trip):
- Applied at both entry and exit
- Configurable via `BacktestEngine` constructor

### Slippage and Spread Modeling

BacktestEngine supports additional transaction costs:
- `slippage`: Price impact on execution (e.g., 0.0005 for 0.05%)
- `spread`: Bid-ask spread cost (e.g., 0.0002 for 0.02%)

These are applied on top of commission for more realistic backtesting.

## Advanced Analysis

### Monte Carlo Simulation

Run Monte Carlo simulations on trade history to evaluate strategy robustness.

```bash
# Monte Carlo from trades.csv
quantpipe analyze --trades runs/backtest/trades.csv --method monte-carlo --iterations 1000 --json

# With custom initial capital
quantpipe analyze --trades runs/backtest/trades.csv --method monte-carlo --initial-capital 50000 --json
```

**Output includes:**
- Final equity distribution (mean, median, std, percentiles)
- Max drawdown distribution
- Ruin probability (probability of losing >50% of capital)

### Walk-Forward Analysis

Rolling window optimization to test strategy robustness over time.

```bash
# Walk-forward analysis
quantpipe analyze --data btc_history.json --strategy ma_cross --method walk-forward --json

# With custom parameters
quantpipe analyze --data btc_history.json --strategy rsi --method walk-forward \
  --train-ratio 0.7 --step 30 --metric sharpe_ratio --json
```

**Output includes:**
- In-sample vs out-of-sample performance per fold
- Sample decay (difference between in-sample and out-of-sample)
- Roll rate (out-of-sample / in-sample ratio)

### Regime Detection

Detect market regimes (bull, bear, sideways, high/low volatility).

```bash
# Regime detection
quantpipe analyze --data btc_history.json --method regime --json

# With custom lookback
quantpipe analyze --data btc_history.json --method regime --lookback 100 --json
```

**Regime types:**
- `bull_high_vol`, `bull_low_vol`: Upward trend with varying volatility
- `bear_high_vol`, `bear_low_vol`: Downward trend with varying volatility
- `sideways_high_vol`, `sideways`: Range-bound market

## Orchestration Example (rule.md §9)

Use **`--pipe`** when redirecting invoke output to a file so the file is the raw JSON payload (not the default `{ message, savedTo, line }` summary).

```text
seamflux invoke binance fetchOhlcv --pipe -p symbol=BTC/USDT -p interval=1d -p limit=365 > 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
