Files
workspace/data/tasks/coinex-upgrades-v2.md

170 lines
6.7 KiB
Markdown

# CoinEx Upgrades v2 — Task Spec
**Created:** 2026-02-27
**Owner:** Case (CSO)
**Priority:** HIGH
---
## Project A: CoinEx Futures Trading Bot — API + Config + Docker
**Repo:** `git.letsgetnashty.com/case/coinex-trader` (NEW private repo, branch: `feature/api`)
**Source:** `projects/crypto-signals/scripts/coinex_live_trader.py` (1,047 lines)
**Stack:** Python 3 + FastAPI + Uvicorn + Swagger (auto-generated)
### Current Hardcoded Config
```python
POSITION_SIZE_PCT = 5.0 # 5% equity per trade
MAX_LEVERAGE = 10 # Cap leverage at 10x
TP_PCT = 5.0 # Take profit at 5% on margin
SL_PCT = -3.0 # Stop loss at -3% on margin
KILL_SWITCH_DRAWDOWN = 0.50 # 50% drawdown kill switch
# Max positions: not explicitly set (implicit max 3)
# Thresholds: defined in scanner, not trader
```
### Requirements
#### 1. FastAPI REST API (with Swagger at /docs)
All endpoints prefixed `/api/v1/`
**Config endpoints:**
- `GET /config` — return all current config
- `PATCH /config` — partial update config (validates ranges)
- `POST /config/reset` — reset to defaults
**Config flags (all runtime-mutable):**
```json
{
"enabled": true, // global on/off toggle
"max_positions": 3,
"long_threshold": 55, // score threshold to enter long
"short_threshold": 55, // score threshold to enter short
"tp_pct": 5.0, // take profit %
"sl_pct": 3.0, // stop loss % (stored positive, applied negative)
"position_size_pct": 5.0, // % of equity per trade
"max_leverage": 10,
"leverage_rules": { // leverage by score bracket
"60+": 7,
"default": 5
},
"kill_switch_drawdown": 0.50,
"trailing_stop": true
}
```
**Account/credentials endpoints:**
- `GET /account` — return balance, equity, margin info (from CoinEx API)
- `GET /account/config` — return configured API key ID (masked), base URL
- `PUT /account/config` — update CoinEx API credentials at runtime
**Position endpoints:**
- `GET /positions` — current open positions from CoinEx
- `POST /positions/{market}/close` — manually close a position
**Status endpoints:**
- `GET /status` — bot status (enabled/disabled, uptime, last scan time, lockfile status)
- `POST /status/enable` — enable trading
- `POST /status/disable` — disable trading (graceful, doesn't close positions)
- `DELETE /status/lockfile` — clear lockfile (same as manual delete)
**Log endpoints:**
- `GET /logs` — return recent logs (query params: `limit`, `level`, `since`)
- `GET /logs/trades` — trade-specific log entries
- Logs stored in structured JSON format (not just print statements)
#### 2. Config Persistence
- Config saved to `config.json` alongside existing `trader_state.json`
- Loaded on startup, merged with defaults
- Changes via API written immediately to disk
#### 3. Structured Logging
- Replace print-based logging with Python `logging` module
- JSON-structured log entries to `trader.log` (rotated, max 10MB x 3)
- Each entry: timestamp, level, category (TRADE/SCAN/API/SYSTEM), message, metadata
- Keep Telegram alerts for critical events
#### 4. Docker
- `Dockerfile` (python:3.12-slim, pip install, uvicorn entrypoint)
- `docker-compose.yml` with env vars for all credentials
- `.dockerignore`
- Health check endpoint: `GET /health`
- Port: 8893 (configurable via PORT env var)
- Volume mount for persistent data (config.json, trader_state.json, logs)
#### 5. Git
- Create NEW private repo: `git.letsgetnashty.com/case/coinex-trader`
- Branch: `feature/api`
- Include: requirements.txt, Dockerfile, docker-compose.yml, README.md, .env.example
### Constraints
- **DO NOT change trading logic** — all entry/exit/scoring logic stays identical
- **Preserve all safety features** — kill switch, circuit breaker, lockfile, retry logic
- When `enabled: false`, scanner still runs (for dashboard data) but no trades are placed
- API must be secured: API key auth via `X-API-Key` header (configurable)
- Existing systemd timer must still work (API is additive, not replacement)
---
## Project B: CoinEx Dashboard Upgrades
**Repo:** `git.letsgetnashty.com/case/coinex-dashboard` (existing)
**Branch:** `feature/v2-upgrades`
**Stack:** Next.js 15 + Tailwind v4 + Framer Motion + ShadCN + TypeScript
### Requirements
#### 1. Account Config (Settings Page)
- New `/settings` page or settings modal
- Configure CoinEx API credentials (Access ID + Secret Key)
- Credentials stored in server memory (env vars take precedence)
- Test connection button (calls CoinEx balance endpoint)
- Show connection status indicator in header
#### 2. Signal History
- Track when each signal first appeared: `{ symbol, direction, score, firstSeen, lastSeen, stale: boolean }`
- Signal is "stale" if it's been active for > 30 minutes without score change > 5 points
- Display staleness indicator on coin cards (e.g., clock icon + time since first seen)
- History stored server-side in memory (reset on restart is OK for v1)
- WebSocket pushes signal age with each update
#### 3. Error/Issue Logging
- Server-side log ring buffer (last 200 entries)
- Log categories: API_ERROR, SCAN_ERROR, WS_ERROR, POSITION_ERROR
- Display in collapsible log panel at bottom of dashboard
- Each entry: timestamp, category, message
- New errors auto-expand the panel with a badge count
#### 4. Tooltips
All coin card elements get tooltips explaining what they are:
- **RSI**: "Relative Strength Index (0-100). <30 oversold, >70 overbought"
- **VWAP %**: "Volume-Weighted Average Price deviation. Positive = above VWAP"
- **BB Position**: "Bollinger Band position. 0 = lower band, 1 = upper band"
- **Long Score / Short Score**: "Composite score (0-80). Signal threshold: {threshold}"
- **24h Change**: "Price change over last 24 hours"
- **Leverage badge**: "Suggested leverage based on signal strength"
- Position cards: entry price, mark price, margin, unrealized P&L descriptions
- Use ShadCN Tooltip component
### Constraints
- All existing scoring logic in `lib/indicators.ts` preserved exactly
- Zero client-side Binance/CoinEx API calls (server fetches, pushes via WS)
- Dark theme maintained
- Mobile-responsive (existing layout is fine, tooltips work on tap)
---
## Pipeline
1. **Glitch** builds both projects on feature branches
2. **Hawk** reviews code + runs tests
3. **Jinx** functional QA (API endpoints, WebSocket data, config persistence)
4. **Pixel** visual QA (tooltips, layout, log panel, settings page)
5. **Forge** handles Gitea repos, Docker builds, Coolify prep
6. Ship to main branches after all pass
## Deployment Notes
- Trader bot: Docker image ready but NOT deployed to Coolify yet (D J will decide when)
- Dashboard: deploy via `tools/coolify-deploy.sh` after QA pass
- Use `coolify-deploy.sh` for dashboard, manual for trader bot