Full sync - all projects, memory, configs

This commit is contained in:
2026-03-21 20:27:59 -05:00
parent 2447677d4a
commit b33de10902
395 changed files with 1635300 additions and 459211 deletions

View File

@ -0,0 +1,189 @@
# CoinEx Live Futures Trader
**⚠️ REAL MONEY TRADING - EXTREME CAUTION REQUIRED ⚠️**
This is a live futures trading bot that connects to CoinEx and trades real money based on the paper trading strategy. Multiple safety mechanisms are implemented.
## 🛡️ Safety Features
### Kill Switch
- **Automatic Stop**: Bot automatically stops if account drops below 50% of starting balance
- **Position Closure**: Attempts to close all positions when kill switch triggers
- **Telegram Alert**: Sends immediate notification when triggered
- **Cannot be bypassed**: Checked before EVERY trading cycle
### Position Management
- **Max 3 positions** (down from 10 in paper trader)
- **Max 10x leverage** (no 15x trades allowed)
- **5% position sizing** (of current equity, ~$7.30 on $146 balance)
- **Futures only** - never touches spot trading
### Risk Controls
- **Stop Loss**: -3% on margin
- **Take Profit**: +5% on margin
- **Trailing Stop**: 2% from peak
- **Complete logging** of every trade
- **Error handling** - never crashes silently
## 📁 Files Created
- `coinex_live_trader.py` - Main trading bot
- `test_coinex_api.py` - API connection test
- `~/.config/systemd/user/coinex-live-trader.service` - Systemd service
- `~/.config/systemd/user/coinex-live-trader.timer` - 5-minute timer
- `COINEX_LIVE_TRADER.md` - This documentation
## 🚀 Getting Started
### 1. Test API Connection First
```bash
cd /home/wdjones/.openclaw/workspace/projects/crypto-signals/scripts
python3 test_coinex_api.py
```
This verifies:
- Credentials are loaded correctly
- API authentication works
- Balance, market data, and positions endpoints respond
### 2. Run Dry Run Mode
```bash
python3 coinex_live_trader.py --dry-run
```
Dry run mode does everything except place actual orders:
- ✅ Runs scanners
- ✅ Calculates position sizes
- ✅ Checks kill switch
- ✅ Logs all decisions
- ❌ No real orders placed
### 3. Live Trading (REAL MONEY)
```bash
python3 coinex_live_trader.py
```
**Only run this after thorough testing with dry-run mode!**
## 🔧 Systemd Service (DISABLED by default)
Service files are created but NOT enabled. To enable:
```bash
# Reload systemd configuration
systemctl --user daemon-reload
# Enable and start the timer
systemctl --user enable coinex-live-trader.timer
systemctl --user start coinex-live-trader.timer
# Check status
systemctl --user status coinex-live-trader.timer
```
To disable:
```bash
systemctl --user stop coinex-live-trader.timer
systemctl --user disable coinex-live-trader.timer
```
## 📊 Monitoring & Logs
### Log Files (in `/home/wdjones/.openclaw/workspace/projects/crypto-signals/data/coinex-live/`)
- `trades.log` - All trading activity
- `errors.log` - Error messages
- `trader_state.json` - Bot state (peak PnL tracking, starting balance)
### Systemd Logs
```bash
# View recent logs
journalctl --user -u coinex-live-trader.service -f
# View timer logs
journalctl --user -u coinex-live-trader.timer -f
```
### Telegram Alerts
- Position opens/closes
- Kill switch triggers
- Error notifications
- Periodic summaries
## ⚙️ Configuration
### Trading Parameters (in `coinex_live_trader.py`)
```python
POSITION_SIZE_PCT = 5.0 # 5% of equity per position
MAX_OPEN_POSITIONS = 3 # Max simultaneous positions
MAX_LEVERAGE = 10 # Leverage cap
SHORT_SCORE_THRESHOLD = 50 # Min score for shorts
LONG_SCORE_THRESHOLD = 45 # Min score for longs
TP_PCT = 5.0 # Take profit %
SL_PCT = -3.0 # Stop loss %
TRAILING_STOP_PCT = 2.0 # Trailing stop %
KILL_SWITCH_DRAWDOWN = 0.50 # 50% drawdown kill switch
```
### Scanning Logic
Uses the same short_scanner and spot scanner logic as the paper trader:
- **Short signals**: High RSI, above VWAP, overbought conditions
- **Long signals**: Low RSI, below VWAP, oversold conditions
- **Same coin list** as paper trader
## 🚨 Emergency Procedures
### Stop the Bot Immediately
```bash
# Stop the timer
systemctl --user stop coinex-live-trader.timer
# Kill any running instance
pkill -f coinex_live_trader.py
```
### Manual Position Closure
If you need to manually close positions, use the CoinEx web interface or API directly.
## 🔍 Key Differences from Paper Trader
| Feature | Paper Trader | Live Trader |
|---------|-------------|-------------|
| Position Size | Fixed $200 | 5% of equity (~$7.30) |
| Max Positions | 10 | 3 |
| Max Leverage | 15x | 10x |
| Kill Switch | None | 50% drawdown |
| Logging | Basic | Complete trade/error logs |
| Dry Run Mode | N/A | Available for testing |
## 📋 Pre-Launch Checklist
- [ ] API test passes (`test_coinex_api.py`)
- [ ] Dry run mode tested extensively
- [ ] Telegram alerts working
- [ ] Starting balance recorded in state file
- [ ] Log files created and writable
- [ ] Kill switch drawdown level confirmed (50%)
- [ ] Position sizing validated (5% = ~$7.30)
- [ ] Max positions confirmed (3)
- [ ] Leverage capped at 10x
## ⚠️ Important Warnings
1. **Real Money**: This trades with real money on real markets
2. **No Guarantees**: No strategy guarantees profits
3. **Monitor Closely**: Especially during first days of operation
4. **Market Risk**: Crypto futures are highly volatile
5. **API Risk**: Exchange issues could affect trading
6. **Kill Switch**: May not prevent all losses
7. **Test First**: Always test thoroughly in dry-run mode
## 📞 Support
- Check logs first: `trades.log` and `errors.log`
- Telegram alerts for real-time issues
- Systemd logs: `journalctl --user -u coinex-live-trader.service`
- Kill switch info in state file: `trader_state.json`
---
**Remember: This is real money trading. Start small, monitor closely, and never risk more than you can afford to lose.**

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""
Test script to verify CoinEx API connection and credentials.
Run this before using the live trader to ensure everything works.
"""
import sys
from pathlib import Path
# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from coinex_live_trader import CoinExAPI, load_coinex_credentials, setup_logging
def test_api():
"""Test CoinEx API connection and basic functionality."""
try:
print("=== CoinEx API Test ===")
# Setup logging directories
setup_logging()
print("Log directories created")
# Load credentials
print("Loading credentials...")
access_id, secret_key = load_coinex_credentials()
print(f"Access ID: {access_id[:8]}...")
# Initialize API
api = CoinExAPI(access_id, secret_key)
print("API client initialized")
# Test balance endpoint
print("\nTesting futures balance endpoint...")
balance = api.get_futures_balance()
print(f"Raw balance response: {balance}")
# Handle different response formats
if isinstance(balance, list):
if balance:
balance_data = balance[0] # Take first item if it's a list
# CoinEx uses different field names
total_balance = float(balance_data.get("available", 0)) + float(balance_data.get("frozen", 0))
available_balance = float(balance_data.get("available", 0))
else:
print("⚠️ Empty balance list returned")
total_balance = available_balance = 0
elif isinstance(balance, dict):
total_balance = float(balance.get("available", 0)) + float(balance.get("frozen", 0))
available_balance = float(balance.get("available", 0))
else:
print(f"⚠️ Unexpected balance format: {type(balance)}")
total_balance = available_balance = 0
print(f"✅ Balance retrieved successfully")
print(f" Total Balance: ${total_balance:.2f}")
print(f" Available Balance: ${available_balance:.2f}")
# Test market data endpoint
print("\nTesting market data endpoint...")
market_data = api.get_market_price("BTCUSDT")
if market_data:
print(f"✅ Market data retrieved successfully")
if isinstance(market_data, list):
print(f" Market data is a list with {len(market_data)} items")
if market_data:
print(f" First item keys: {list(market_data[0].keys()) if market_data[0] else 'Empty'}")
else:
print(f" Market data keys: {list(market_data.keys())}")
# Test positions endpoint
print("\nTesting positions endpoint...")
positions = api.get_positions()
if isinstance(positions, list):
print(f"✅ Positions retrieved successfully")
print(f" Number of open positions: {len(positions)}")
if positions:
for pos in positions[:3]: # Show first 3
market = pos.get("market", "Unknown")
side = pos.get("side", "Unknown")
amount = pos.get("amount", "0")
print(f" {market} {side} {amount}")
else:
print(f"✅ Positions endpoint working (empty/different format)")
print("\n🎉 All tests passed! API is working correctly.")
print("\nYou can now run the live trader with:")
print(" python3 coinex_live_trader.py --dry-run (for testing)")
print(" python3 coinex_live_trader.py (for live trading)")
return True
except Exception as e:
print(f"\n❌ Test failed: {e}")
# Just print error instead of using log_error which isn't available in this context
print(f"API test failed: {e}")
return False
if __name__ == "__main__":
success = test_api()
sys.exit(0 if success else 1)