111 lines
4.4 KiB
Markdown
111 lines
4.4 KiB
Markdown
# Multi-Currency Spot Trader (OKX + TA + Optional DeepSeek)
|
||
|
||
A pragmatic, menu-driven spot trading system for OKX.
|
||
It fetches market data, computes robust technical signals, optionally blends an AI opinion, sizes positions under strict risk constraints, and executes market orders with dynamic trailing stops and full state persistence.
|
||
|
||
## Features
|
||
|
||
- **OKX official SDK** spot trading (market orders)
|
||
- **Technical stack**: RSI/KDJ/MACD/Bollinger/ATR/MA/Stochastic + reversal detectors
|
||
- **Decisioning**: TA weighted score + (optional) DeepSeek AI JSON action
|
||
- **Risk control**: max portfolio allocations, fixed SL/TP, **trailing stops** that ratchet up
|
||
- **Persistence**: SQLite for positions, trades, trailing stop state
|
||
- **Multi-symbol orchestration** with a simple CLI control panel
|
||
|
||
## Project layout
|
||
|
||
```
|
||
apiratelimiter.py # tiny per-API rate limiter
|
||
database_manager.py # SQLite schema + CRUD for positions/trades/dynamic stops
|
||
deepseekanalyzer.py # optional AI integration (BUY/SELL/HOLD + sell proportion)
|
||
multistrategyrunner.py # threads per symbol, lifecycle, status
|
||
okxapiclient.py # OKX SDK wrapper: candles, prices, balances, orders
|
||
okxtrading2.0.py # CLI entrypoint (menu)
|
||
riskmanager.py # portfolio sizing, limits, trailing parameters
|
||
technicalanalyzer.py # indicators, signals, reversal detectors
|
||
tradingstrategy.py # analysis→decision matrix→execution loop per symbol
|
||
```
|
||
|
||
## Requirements
|
||
|
||
- Python 3.10+
|
||
- Packages: `okx` (official SDK), `pandas`, `numpy`, `python-dotenv` (optional), plus stdlib.
|
||
- An OKX API key with **trading permissions** for **spot**.
|
||
> By default `tdMode` is set to `"cross"` and instruments are fetched with `instType='SPOT'`.
|
||
|
||
## Quick start
|
||
|
||
1) **Install deps**
|
||
|
||
```bash
|
||
python -m venv .venv && source .venv/bin/activate
|
||
pip install okx pandas numpy python-dotenv
|
||
```
|
||
|
||
2) **Set environment variables**
|
||
|
||
Create `.env` (or export in your shell):
|
||
|
||
```dotenv
|
||
# OKX (required)
|
||
OKX_API_KEY=...
|
||
OKX_SECRET_KEY=...
|
||
OKX_PASSWORD=...
|
||
|
||
# Optional AI
|
||
DEEPSEEK_API_KEY=...
|
||
|
||
# Risk/sizing (defaults shown)
|
||
MAX_TOTAL_POSITION=1 # 100% portfolio cap
|
||
MAX_SINGLE_POSITION=0.3 # 30% per symbol cap
|
||
STOP_LOSS=0.05 # fixed SL 5%
|
||
TAKE_PROFIT=0.15 # fixed TP 15%
|
||
TRAILING_STOP_PERCENT=0.03 # 3% trail width
|
||
MONITOR_INTERVAL=300 # seconds between trail checks
|
||
DB_PATH=trading_system.db # sqlite path
|
||
```
|
||
|
||
3) **Run the control panel**
|
||
|
||
```bash
|
||
python okxtrading2.0.py
|
||
```
|
||
|
||
You’ll see a menu:
|
||
|
||
- `Start All Strategies` — launch threads for all configured symbols
|
||
- `Start/Stop Specific Strategy` — control a single market
|
||
- `View System Status` — running flags, active symbols, stored positions
|
||
- `Manual Position Sync` — reconcile on-exchange balances to local state
|
||
- `Toggle Debug Mode` — echo OKX HTTP call codes
|
||
|
||
## How it trades (in one pass)
|
||
|
||
1. **Market data**: fetch latest candles for the symbol (`1H` by default).
|
||
2. **Indicators**: compute RSI/KDJ/MACD/BB/ATR/MA/Stochastic and reversal hints.
|
||
3. **Signals**: produce a weighted TA score and optional **DeepSeek** action.
|
||
4. **Decision matrix**: combine AI, TA, support/resistance, market state into a total score → `BUY/SELL/HOLD` + confidence.
|
||
5. **Sizing & risk**: compute size from portfolio constraints and market context (vol/trend/USDT ratio).
|
||
6. **Execution**:
|
||
- `BUY`: market buy using **quote amount (USDT)**; respects exchange **minSz**.
|
||
- `SELL`: market sell using **base amount**; optional AI estimates a **sell proportion** (with sensible fallbacks).
|
||
7. **Stops & persistence**:
|
||
- Save position/trades to **SQLite**.
|
||
- Set/ratchet **trailing stop** (and a symmetric dynamic take-profit band).
|
||
- Background monitor checks triggers every `MONITOR_INTERVAL` seconds.
|
||
|
||
## Configuration
|
||
|
||
- **Symbols & cadence**: edit `symbol_configs` in `multistrategyrunner.py`:
|
||
```python
|
||
'ETH-USDT': {'name': 'Ethereum', 'interval': 1800, 'timeframe': '1H'}
|
||
```
|
||
- **Risk knobs**: tweak env vars in `.env` (caps, SL/TP, trailing %).
|
||
- **Database**: change `DB_PATH` to relocate the SQLite file.
|
||
|
||
## Operational notes
|
||
|
||
- **AI is optional**: if `DEEPSEEK_API_KEY` is missing, system runs purely on TA with deterministic fallbacks.
|
||
- **Min trade sizes**: on buy, system checks if `estimated_base_amount >= minSz`; on sell, blocks dust/too-small partials.
|
||
- **Graceful shutdown**: Ctrl-C or menu exit triggers strategy/thread stops and monitor shutdown; state is persisted.
|