Skip to content

Repository files navigation

# Crypto Algorithm Suite (Mean Reversion, Bollinger, Trend, Freqtrade adapters & Backtesting)

[![CI](https://github.com/savvaniss/mean-pair/actions/workflows/ci.yml/badge.svg)](https://github.com/savvaniss/mean-pair/actions/workflows/ci.yml)

A FastAPI-based trading lab that hosts several algorithms, a lightweight listings monitor, and a full historical backtester that replays public candles from Binance (with Yahoo Finance fallback). The HTML/JavaScript dashboard in `static/` lets you start or stop live loops, edit parameters, trigger manual trades, and run backtests over arbitrary date ranges.

---

## Core Algorithms

### Mean Reversion (HBAR ↔ DOGE ratio)
- Trades the ratio `HBARUSDC / DOGEUSDC` with configurable `z_entry` / `z_exit`, moving-window size, and optional fixed ratio thresholds.
- Tracks current asset, quantities, realized/unrealized PnL, and logs every trade.
- Supports Binance testnet or mainnet via environment flags and manual trade overrides.

### Single-Coin Bollinger Bands
- Trades any symbol against USDC/USDT/BTC (e.g., `BNBUSDC`, `ETHUSDT`).
- Configurable window, standard-deviation width, max position size, stop-loss/take-profit, and cooldown between entries.
- Streams status, trades, and band/price history for charting.

### Trend Following
- Simple moving-average crossover with ATR-based trailing stops.
- Parameterized fast/slow windows and ATR multiplier per symbol/interval.

### Freqtrade Adapter Examples
- Ships lightweight adapters mirroring several Freqtrade snippets:
  - `pattern_recognition` (talib candle patterns)
  - `strategy001` / `strategy002` / `strategy003` (EMA, RSI, stochastic, Bollinger confluences)
  - `supertrend` (multi-supertrend agreement)
- Each adapter maintains position state, indicator snapshots, and trade logs for the UI.

### Listings Monitor
- Collectors for Binance plus additional CEX/DEX feeds with normalized fields (exchange, network, base/quote, source URL).
- UI table with filters for exchange type, name, network, search text, and time windows.

---

## Historical Backtesting

The `/backtest` API and dashboard tab can simulate any supported algorithm against public market data:
- **Data sources:** Binance public klines with interval-aware pagination; automatic Yahoo Finance fallback if Binance data is missing.
- **Date control:** Run lookbacks by days or specify exact `start_date`/`end_date` windows (e.g., "last August").
- **Supported strategies:** mean reversion (pair), Bollinger (single symbol), trend following, and all Freqtrade adapters.
- **Outputs:** structured trades, equity curve, final balance, return %, win rate, and max drawdown returned to the UI.
- **Configurable bankroll:** per-run `starting_balance` for consistent PnL baselines.

---

## Dashboard

The single-page dashboard (served from `/`) includes:
- Live strategy status cards with balances, prices, PnL, and last signals.
- Inline configuration editors for mean reversion, Bollinger, trend, and Freqtrade adapters.
- Manual trading controls (e.g., HBAR↔DOGE swaps, Bollinger manual exits).
- Strategy-specific trade history tables and charts.
- **Backtesting tab** with strategy selector, date pickers, and validation that requires the right inputs per algorithm before submitting.
- `/listings` page that renders the listings monitor with dynamic filters and polling.

Static assets live in `static/` and are served directly by FastAPI.

---

## Project Structure

```
mean-pair/
├── app.py                   # FastAPI app wiring and router registration
├── config.py                # Default configuration and helper utilities
├── database.py              # SQLAlchemy models and database setup
├── engines/                 # Trading/backtesting engines
│   ├── backtester.py        # Public-candle backtester for all strategies
│   ├── bollinger.py         # Bollinger Band live engine
│   ├── common.py            # Shared pricing/stat helpers
│   ├── freqtrade_algos.py   # Freqtrade adapter strategies
│   ├── mean_reversion.py    # HBAR/DOGE ratio engine
│   ├── trend_following.py   # Moving-average/ATR trend engine
│   └── listings_*           # Listings collectors (Binance, CEX, DEX)
├── routes/                  # FastAPI routers (auth, strategies, backtesting, listings)
│   ├── backtesting.py       # `/backtest` entrypoint
│   ├── bollinger.py         # Bollinger config/status endpoints
│   ├── mean_reversion.py    # Mean reversion controls
│   ├── trend_following.py   # Trend controls
│   └── listings.py          # Listings monitor APIs
├── static/                  # Front-end assets (dashboard, charts, backtesting UI)
│   ├── index.html
│   └── js/
├── tests/                   # Pytest coverage for engines and routes
├── Dockerfile               # Container build for the FastAPI service
└── docker-compose.yml       # Local stack orchestration (app + Postgres)
```

---

## Environment Variables

Provide via `.env` (Docker Compose injects Postgres defaults):

```
# Mean Reversion keys
BINANCE_TESTNET_API_KEY=
BINANCE_TESTNET_API_SECRET=
BINANCE_MAINNET_API_KEY=
BINANCE_MAINNET_API_SECRET=

# Bollinger/trend/freqtrade keys (optional)
BINANCE_BOLL_TESTNET_API_KEY=
BINANCE_BOLL_TESTNET_API_SECRET=
BINANCE_BOLL_MAINNET_API_KEY=
BINANCE_BOLL_MAINNET_API_SECRET=

# Environment: "testnet" or "mainnet"
ENV=testnet

# Internal flags (used by CI)
BOT_DISABLE_THREADS=0
DISABLE_BINANCE_CLIENT=0
LISTINGS_DISABLE_SCHEDULER=0
LISTINGS_REFRESH_SECONDS=60
LISTINGS_RETENTION_MINUTES=240
AUTH_ALLOW_REGISTRATION=1

# Database
DATABASE_URL=postgresql+psycopg2://meanpair:meanpair@db:5432/meanpair
```

Set `AUTH_ALLOW_REGISTRATION=0` to disable self-service sign-up and restrict access to pre-created accounts only.

---

## Running Locally

Install dependencies:

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

Start the development server:

```
uvicorn app:app --reload
```

Open the dashboard:

```
http://localhost:8000
```

---

## Running with Docker

Build and start the stack:

```
docker-compose up --build -d
```

Services:
- FastAPI app: http://localhost:8000
- PostgreSQL database: available inside the Docker network at `db:5432`

---

## API Endpoints (selection)

### Strategies

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/status` | Mean-reversion status (prices, ratio, PnL) |
| GET | `/next_signal` | Next mean-reversion action preview |
| GET | `/config` | Get mean-reversion config |
| POST | `/config` | Update mean-reversion config |
| POST | `/start` | Start mean-reversion loop |
| POST | `/stop` | Stop mean-reversion loop |
| POST | `/manual_trade` | Manual HBAR↔DOGE trade |
| GET | `/trades` | Mean-reversion trades |
| GET | `/boll_config` | Get Bollinger config |
| POST | `/boll_config` | Update Bollinger config |
| GET | `/boll_status` | Current Bollinger status |
| GET | `/boll_history` | Band/MA/price history |
| GET | `/boll_trades` | Bollinger trades |
| POST | `/bollinger_manual_sell` | Manual Bollinger exit |
| GET | `/trend_status` | Trend-following status |
| POST | `/trend_config` | Update trend config |
| GET | `/algo_status` | Freqtrade adapter status (per strategy) |
| POST | `/algo_config` | Update Freqtrade adapter config |

### Backtesting

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/backtest` | Simulate mean reversion, Bollinger, trend, or Freqtrade adapters over a date range with Binance/Yahoo candles |

### Listings Monitor

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/listings/latest` | Latest normalized listings with filters |
| GET | `/api/listings/health` | Collector health / last run |
| GET | `/listings` | UI for the listings table |

---

## Testing & CI

Run all tests locally:

```
pytest
```

CI runs on every push/pull request via `.github/workflows/ci.yml`, using flags to keep builds offline:

```
DISABLE_BINANCE_CLIENT=1
BOT_DISABLE_THREADS=1
```

---

## License

MIT License © 2025 Savvaniss

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages