chore: Organize workspace structure - move docs, workflows, scripts to subdirectories
Organization: - Created docs/ with setup/, guides/, history/ subdirectories - Created workflows/ with trading/, analytics/, telegram/, archive/ subdirectories - Created scripts/ with docker/, setup/, testing/ subdirectories - Created tests/ for TypeScript test files - Created archive/ for unused reference files Moved files: - 17 documentation files → docs/ - 16 workflow JSON files → workflows/ - 10 shell scripts → scripts/ - 4 test files → tests/ - 5 unused files → archive/ Updated: - README.md with new file structure and documentation paths Deleted: - data/ (empty directory) - screenshots/ (empty directory) Critical files remain in root: - telegram_command_bot.py (active bot - used by Dockerfile) - watch-restart.sh (systemd service dependency) - All Dockerfiles and docker-compose files - All environment files Validation: Containers running (trading-bot-v4, telegram-trade-bot, postgres) API responding (positions endpoint tested) Telegram bot functional (/status command tested) All critical files present in root No code changes - purely organizational. System continues running without interruption. Recovery: git revert HEAD or git reset --hard cleanup-before
This commit is contained in:
107
docs/history/EXIT_ORDERS_TEST_RESULTS.md
Normal file
107
docs/history/EXIT_ORDERS_TEST_RESULTS.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Exit Orders Test Results ✅
|
||||
|
||||
## Test Details
|
||||
- **Date:** October 26, 2025
|
||||
- **Position Size:** $10 base × 5x leverage = $50 notional
|
||||
- **Symbol:** SOL-PERP
|
||||
- **Direction:** LONG
|
||||
- **Entry Price:** $197.4950
|
||||
|
||||
## Results: SUCCESS ✅
|
||||
|
||||
### Transaction Signatures
|
||||
|
||||
**Entry Order:**
|
||||
```
|
||||
2Bio8oUhhNXkYxY9g5RsR3KUpb3mCX3ZWrQoqFTZ9DQY7rq5w7reCwu8qyHEq1cZdBK5TRo7n9qhC9nj7HtUvWKG
|
||||
```
|
||||
[View on Solscan](https://solscan.io/tx/2Bio8oUhhNXkYxY9g5RsR3KUpb3mCX3ZWrQoqFTZ9DQY7rq5w7reCwu8qyHEq1cZdBK5TRo7n9qhC9nj7HtUvWKG)
|
||||
|
||||
**TP1 Order (75% at +0.5%):**
|
||||
```
|
||||
4G8rXJ5vhLZAhNaNJ46qwbDoMEhxab7kTibaQtrBHuSkzmd6FPtLyELbt7Lc8CpTLMtN1ut9sjz9F9o1FhRhgzLU
|
||||
```
|
||||
Target: $198.4825
|
||||
[View on Solscan](https://solscan.io/tx/4G8rXJ5vhLZAhNaNJ46qwbDoMEhxab7kTibaQtrBHuSkzmd6FPtLyELbt7Lc8CpTLMtN1ut9sjz9F9o1FhRhgzLU)
|
||||
|
||||
**TP2 Order (100% at +2.5%):**
|
||||
```
|
||||
5Zo56K8ZLkz3uEVVuQUakZQ3uMCQSXrkWG1EwtxSZVQB2pxQwKp2gbPUGEDyPZobyBv4TYMEBGf5kBpLWfCPYMEr
|
||||
```
|
||||
Target: $202.4324
|
||||
[View on Solscan](https://solscan.io/tx/5Zo56K8ZLkz3uEVVuQUakZQ3uMCQSXrkWG1EwtxSZVQB2pxQwKp2gbPUGEDyPZobyBv4TYMEBGf5kBpLWfCPYMEr)
|
||||
|
||||
**Stop Loss Order (at -0.9%):**
|
||||
```
|
||||
5U9ZxYFyD99j8MXcthqqjy6DjACqedEWfidWsCb69RtQfSe7iBYvRWrFJVJ5PGe2nJYtvRrMo2szuDCD8ztBrebs
|
||||
```
|
||||
Target: $195.7175
|
||||
[View on Solscan](https://solscan.io/tx/5U9ZxYFyD99j8MXcthqqjy6DjACqedEWfidWsCb69RtQfSe7iBYvRWrFJVJ5PGe2nJYtvRrMo2szuDCD8ztBrebs)
|
||||
|
||||
## Verification
|
||||
|
||||
### Check on Drift UI
|
||||
Visit [https://app.drift.trade/](https://app.drift.trade/) and connect with wallet:
|
||||
```
|
||||
3dG7wayp7b9NBMo92D2qL2sy1curSC4TTmskFpaGDrtA
|
||||
```
|
||||
|
||||
You should see:
|
||||
1. Active SOL-PERP position (~0.2532 SOL)
|
||||
2. Three open orders (TP1, TP2, SL) showing as "Limit" orders with "Reduce Only" flag
|
||||
3. Orders should be visible in the "Orders" tab
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### What Changed
|
||||
1. **lib/drift/orders.ts:** Added `placeExitOrders()` function that creates reduce-only LIMIT orders
|
||||
2. **app/api/trading/execute/route.ts:** Calls `placeExitOrders()` after opening position
|
||||
3. **config/trading.ts:** Added `takeProfit1SizePercent` and `takeProfit2SizePercent` config fields
|
||||
|
||||
### Order Types Used
|
||||
- **Entry:** Market order (immediate execution)
|
||||
- **Exit orders:** Reduce-only LIMIT orders
|
||||
- Reduce-only = can only close position, not increase it
|
||||
- LIMIT = visible in order book, executes when price reached
|
||||
- Alternative: Trigger-market orders (more guaranteed execution but may slip)
|
||||
|
||||
### Position Manager
|
||||
The bot still runs the position manager which:
|
||||
- Monitors price in real-time via Pyth
|
||||
- Will also close positions via market orders when targets hit
|
||||
- Acts as a backup/fallback if LIMIT orders don't fill
|
||||
|
||||
## Risk Assessment
|
||||
✅ **Safe for production** with following considerations:
|
||||
|
||||
1. **LIMIT order risk:** May not fill if market gaps past price (e.g., flash crash through stop loss)
|
||||
2. **Solution:** Position manager provides backup via market orders
|
||||
3. **Recommendation:** For more safety-critical stops, consider implementing trigger-market orders
|
||||
|
||||
## Next Steps (Optional Enhancements)
|
||||
|
||||
1. **Add trigger-market for SL:** More guaranteed execution on stop loss
|
||||
2. **Order cancellation:** Cancel old orders when position closes manually
|
||||
3. **Multiple timeframes:** Support different TP/SL per timeframe
|
||||
4. **Dynamic sizing:** Adjust TP sizes based on signal strength
|
||||
|
||||
## Test Command
|
||||
```bash
|
||||
cd /home/icke/traderv4
|
||||
./test-exit-orders.sh
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
```bash
|
||||
# Check logs
|
||||
docker logs trading-bot-v4 -f
|
||||
|
||||
# Check position manager status
|
||||
curl http://localhost:3001/api/status
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Status: TESTED AND WORKING ✅**
|
||||
|
||||
The implementation successfully places on-chain TP/SL orders that are visible in the Drift UI. All three exit orders were placed successfully in the live test with real funds.
|
||||
328
docs/history/PHASE_1_COMPLETE.md
Normal file
328
docs/history/PHASE_1_COMPLETE.md
Normal file
@@ -0,0 +1,328 @@
|
||||
# Trading Bot v4 - Phase 1 Complete! 🎉
|
||||
|
||||
## ✅ What's Been Built
|
||||
|
||||
### Core Components
|
||||
|
||||
1. **Configuration System** (`v4/config/trading.ts`)
|
||||
- Trading parameters (leverage, stops, targets)
|
||||
- Market configurations (SOL, BTC, ETH)
|
||||
- Environment variable support
|
||||
- Validation and merging logic
|
||||
|
||||
2. **Drift Integration** (`v4/lib/drift/`)
|
||||
- `client.ts` - Drift SDK client wrapper
|
||||
- `orders.ts` - Market order execution (open/close)
|
||||
- Account health monitoring
|
||||
- Position tracking
|
||||
- Oracle price feeds
|
||||
|
||||
3. **API Endpoints** (`v4/app/api/trading/`)
|
||||
- `execute/route.ts` - Execute trades from n8n
|
||||
- `check-risk/route.ts` - Pre-trade risk validation
|
||||
- Authentication with API keys
|
||||
- Error handling
|
||||
|
||||
4. **Documentation**
|
||||
- `SETUP.md` - Detailed setup instructions
|
||||
- `.env.example` - Environment template
|
||||
- `test-drift-v4.ts` - Integration test script
|
||||
|
||||
### n8n Integration
|
||||
|
||||
- ✅ Workflow JSON exported (`n8n-workflow-v4.json`)
|
||||
- ✅ TradingView webhook → n8n → Trading Bot flow
|
||||
- ✅ Multi-channel notifications (Telegram/Discord)
|
||||
- ✅ Risk checks before execution
|
||||
- ✅ Trade confirmation messages
|
||||
|
||||
## 🎯 How It Works
|
||||
|
||||
### Signal Flow
|
||||
|
||||
```
|
||||
1. TradingView Alert (5min chart, green/red dot)
|
||||
↓
|
||||
2. Webhook to n8n (with secret validation)
|
||||
↓
|
||||
3. n8n extracts signal data
|
||||
↓
|
||||
4. n8n calls /api/trading/check-risk
|
||||
↓
|
||||
5. If approved, n8n calls /api/trading/execute
|
||||
↓
|
||||
6. Bot opens position on Drift Protocol
|
||||
↓
|
||||
7. n8n sends Telegram/Discord notification
|
||||
↓
|
||||
8. Trade is live! (monitoring in Phase 2)
|
||||
```
|
||||
|
||||
### Example Trade Execution
|
||||
|
||||
```
|
||||
Signal: BUY SOLUSDT @ $100.00
|
||||
|
||||
Configuration:
|
||||
- Position: $1,000
|
||||
- Leverage: 10x
|
||||
- Total: $10,000
|
||||
|
||||
Order Placement:
|
||||
✅ Market buy executed
|
||||
✅ Fill price: $100.02 (0.02% slippage)
|
||||
✅ Size: 99.98 SOL
|
||||
|
||||
Targets Set:
|
||||
🔴 Stop Loss: $98.52 (-1.5% = -$150 account loss)
|
||||
🟡 TP1 (50%): $100.72 (+0.7% = +$70 account gain)
|
||||
🟢 TP2 (50%): $101.52 (+1.5% = +$150 account gain)
|
||||
|
||||
Status: Position active, monitoring will start in Phase 2
|
||||
```
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
### Test Your Setup
|
||||
|
||||
```bash
|
||||
# 1. Navigate to v4 directory
|
||||
cd v4
|
||||
|
||||
# 2. Run integration test
|
||||
npx tsx test-drift-v4.ts
|
||||
|
||||
# Expected output:
|
||||
# ✅ Config loaded
|
||||
# ✅ Drift service initialized
|
||||
# ✅ USDC Balance: $XXX.XX
|
||||
# ✅ Account health: ...
|
||||
# ✅ All tests passed!
|
||||
```
|
||||
|
||||
### Test API Endpoints
|
||||
|
||||
```bash
|
||||
# 1. Start Next.js server
|
||||
npm run dev
|
||||
|
||||
# 2. Test risk check
|
||||
curl -X POST http://localhost:3000/api/trading/check-risk \
|
||||
-H "Authorization: Bearer YOUR_API_SECRET_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"symbol":"SOL-PERP","direction":"long"}'
|
||||
|
||||
# Expected: {"allowed":true,"details":"All risk checks passed"}
|
||||
```
|
||||
|
||||
### Test Full Flow (CAREFUL!)
|
||||
|
||||
```bash
|
||||
# This will open a REAL position!
|
||||
curl -X POST http://localhost:3000/api/trading/execute \
|
||||
-H "Authorization: Bearer YOUR_API_SECRET_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"symbol": "SOLUSDT",
|
||||
"direction": "long",
|
||||
"timeframe": "5",
|
||||
"signalStrength": "strong"
|
||||
}'
|
||||
```
|
||||
|
||||
## 🚧 What's Missing (Phase 2)
|
||||
|
||||
### Critical Components
|
||||
|
||||
1. **Price Monitoring System**
|
||||
- Pyth WebSocket integration
|
||||
- Real-time price updates (every 2s)
|
||||
- Price cache management
|
||||
|
||||
2. **Position Manager**
|
||||
- Track active trades
|
||||
- Monitor P&L in real-time
|
||||
- Handle multiple concurrent positions
|
||||
|
||||
3. **Auto Exit Logic**
|
||||
- Check SL/TP1/TP2 conditions
|
||||
- Execute market closes automatically
|
||||
- Move SL to breakeven after TP1
|
||||
- Lock profit at triggers
|
||||
|
||||
4. **Risk Manager**
|
||||
- Daily P&L tracking
|
||||
- Trades per hour limiting
|
||||
- Cooldown enforcement
|
||||
- Account health monitoring
|
||||
|
||||
5. **Database Integration**
|
||||
- Save trades to PostgreSQL
|
||||
- Trade history
|
||||
- P&L reporting
|
||||
- Performance analytics
|
||||
|
||||
6. **Notifications**
|
||||
- Telegram trade updates
|
||||
- Discord rich embeds
|
||||
- Email reports
|
||||
- Exit notifications
|
||||
|
||||
## 📝 Setup Checklist
|
||||
|
||||
Before going live:
|
||||
|
||||
- [ ] `.env.local` configured with all required variables
|
||||
- [ ] Drift wallet funded with USDC
|
||||
- [ ] Drift account initialized at drift.trade
|
||||
- [ ] Test script passes (`npx tsx v4/test-drift-v4.ts`)
|
||||
- [ ] n8n workflow imported and activated
|
||||
- [ ] n8n environment variables set
|
||||
- [ ] Telegram bot configured
|
||||
- [ ] TradingView alert created
|
||||
- [ ] Test alert triggered successfully
|
||||
- [ ] Small test trade executed successfully ($100)
|
||||
- [ ] Position verified in Drift UI
|
||||
|
||||
## 🎬 Quick Start Guide
|
||||
|
||||
### 1. Environment Setup
|
||||
|
||||
```bash
|
||||
# Copy environment template
|
||||
cp v4/.env.example .env.local
|
||||
|
||||
# Edit .env.local and add:
|
||||
# - DRIFT_WALLET_PRIVATE_KEY
|
||||
# - API_SECRET_KEY
|
||||
# - SOLANA_RPC_URL (if not already set)
|
||||
```
|
||||
|
||||
### 2. Test Drift Connection
|
||||
|
||||
```bash
|
||||
npx tsx v4/test-drift-v4.ts
|
||||
```
|
||||
|
||||
### 3. Configure n8n
|
||||
|
||||
```
|
||||
1. Import n8n-workflow-v4.json
|
||||
2. Set TRADING_BOT_API_URL
|
||||
3. Set API_SECRET_KEY
|
||||
4. Set TRADINGVIEW_WEBHOOK_SECRET
|
||||
5. Configure Telegram credentials
|
||||
6. Activate workflow
|
||||
```
|
||||
|
||||
### 4. Configure TradingView
|
||||
|
||||
```
|
||||
1. Create alert on 5min chart
|
||||
2. Set webhook URL: https://your-n8n.com/webhook/tradingview-signal?secret=SECRET
|
||||
3. Set message format (see SETUP.md)
|
||||
4. Enable "Webhook URL" notification
|
||||
5. Test alert
|
||||
```
|
||||
|
||||
### 5. Start Trading!
|
||||
|
||||
```
|
||||
Manually trigger TradingView alert
|
||||
↓
|
||||
Check n8n execution logs
|
||||
↓
|
||||
Verify position opened in Drift
|
||||
↓
|
||||
Monitor position at drift.trade
|
||||
↓
|
||||
Manually close for now (Phase 2 will auto-close)
|
||||
```
|
||||
|
||||
## 💡 Important Notes
|
||||
|
||||
### Current Limitations
|
||||
|
||||
1. **No automatic exits** - You must manually close positions or wait for Drift's liquidation
|
||||
2. **No price monitoring** - Bot doesn't track prices after entry
|
||||
3. **No risk limits** - All trades are approved (risk check is placeholder)
|
||||
4. **No trade history** - Trades aren't saved to database yet
|
||||
|
||||
### Workarounds for Phase 1
|
||||
|
||||
1. **Monitor positions manually** at https://drift.trade
|
||||
2. **Set up Drift UI alerts** for your TP/SL levels
|
||||
3. **Close positions manually** when targets hit
|
||||
4. **Track trades in a spreadsheet** for now
|
||||
5. **Use small position sizes** ($100-500 recommended)
|
||||
|
||||
## 🔐 Security Reminders
|
||||
|
||||
- ✅ `.env.local` is gitignored (don't commit it!)
|
||||
- ✅ API keys should be random (use `openssl rand -hex 32`)
|
||||
- ✅ Use a dedicated wallet for trading
|
||||
- ✅ Keep private keys secure
|
||||
- ✅ Start with small positions
|
||||
- ✅ Monitor closely during testing
|
||||
|
||||
## 📊 Recommended Testing Strategy
|
||||
|
||||
### Week 1: Paper Testing
|
||||
- Use $100 position size
|
||||
- Trade 5-10 times
|
||||
- Manually close all positions
|
||||
- Track results in spreadsheet
|
||||
|
||||
### Week 2: Small Live
|
||||
- Increase to $300 position size
|
||||
- Let some positions hit TP/SL naturally
|
||||
- Monitor slippage and execution
|
||||
- Verify n8n notifications
|
||||
|
||||
### Week 3: Scale Up
|
||||
- Gradually increase to $500-1000
|
||||
- Add more symbols
|
||||
- Fine-tune parameters
|
||||
- Prepare for Phase 2 (auto-exits)
|
||||
|
||||
## 🎯 Next Development Priorities
|
||||
|
||||
### Phase 2 Features (in order)
|
||||
|
||||
1. **Pyth Price Monitor** (critical for auto-exits)
|
||||
2. **Position Manager** (track active trades)
|
||||
3. **Auto Exit Logic** (SL/TP execution)
|
||||
4. **Database Integration** (trade history)
|
||||
5. **Risk Manager** (daily limits)
|
||||
6. **Enhanced Notifications** (trade updates)
|
||||
|
||||
Want me to build Phase 2 next?
|
||||
|
||||
## 📞 Support
|
||||
|
||||
If you encounter issues:
|
||||
|
||||
1. Check `v4/SETUP.md` for troubleshooting
|
||||
2. Review `TRADING_BOT_V4_MANUAL.md` for full documentation
|
||||
3. Test with `v4/test-drift-v4.ts`
|
||||
4. Check Drift UI for account status
|
||||
5. Review n8n execution logs
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Congratulations!
|
||||
|
||||
You now have a clean, working Trading Bot v4 foundation with:
|
||||
- ✅ Drift Protocol integration
|
||||
- ✅ n8n automation
|
||||
- ✅ TradingView webhooks
|
||||
- ✅ Market order execution
|
||||
- ✅ Telegram notifications
|
||||
|
||||
**The bot can now execute trades automatically when TradingView signals come in!**
|
||||
|
||||
Ready to test it? Follow the Quick Start Guide above.
|
||||
|
||||
Want to add auto-exits? Let me know and I'll build Phase 2!
|
||||
|
||||
🚀 Happy trading!
|
||||
531
docs/history/PHASE_2_COMPLETE.md
Normal file
531
docs/history/PHASE_2_COMPLETE.md
Normal file
@@ -0,0 +1,531 @@
|
||||
# Trading Bot v4 - Phase 2 Complete! 🎉
|
||||
|
||||
## ✅ What's New in Phase 2
|
||||
|
||||
### 🎯 Fully Automated Trading System
|
||||
|
||||
**Phase 1** could only open positions. **Phase 2** adds:
|
||||
- ✅ Real-time price monitoring (Pyth Network WebSocket)
|
||||
- ✅ Automatic exit execution (TP1/TP2/SL)
|
||||
- ✅ Smart position management
|
||||
- ✅ Dynamic stop-loss adjustments
|
||||
- ✅ Emergency stops
|
||||
|
||||
**The bot is now 100% autonomous!**
|
||||
|
||||
---
|
||||
|
||||
## 📦 New Components
|
||||
|
||||
### 1. Pyth Price Monitor (`lib/pyth/price-monitor.ts`)
|
||||
|
||||
**Real-time price feeds with dual approach:**
|
||||
- WebSocket subscription (sub-second updates)
|
||||
- RPC polling fallback (every 2s)
|
||||
- Price caching for instant access
|
||||
- Multi-symbol support
|
||||
|
||||
```typescript
|
||||
// Monitors SOL, BTC, ETH prices simultaneously
|
||||
// Updates every ~400ms via Pyth WebSocket
|
||||
// Falls back to polling if WebSocket stalls
|
||||
```
|
||||
|
||||
### 2. Position Manager (`lib/trading/position-manager.ts`)
|
||||
|
||||
**Tracks and manages active trades:**
|
||||
- Monitors multiple positions simultaneously
|
||||
- Checks exit conditions every 2 seconds
|
||||
- Executes market closes automatically
|
||||
- Tracks P&L in real-time
|
||||
- Handles TP1 partial closes
|
||||
|
||||
```typescript
|
||||
// Manages the complete trade lifecycle:
|
||||
// Entry → Monitoring → TP1 (50%) → SL to BE → TP2 (50%) → Exit
|
||||
```
|
||||
|
||||
### 3. Positions API (`app/api/trading/positions/route.ts`)
|
||||
|
||||
**GET endpoint for monitoring:**
|
||||
- View all active trades
|
||||
- Real-time P&L
|
||||
- Monitoring status
|
||||
- Trade statistics
|
||||
|
||||
```bash
|
||||
GET /api/trading/positions
|
||||
# Returns all active positions with live P&L
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Complete Trade Flow
|
||||
|
||||
### Signal to Exit (Fully Automated)
|
||||
|
||||
```
|
||||
1. TradingView Alert
|
||||
↓
|
||||
2. n8n Webhook
|
||||
↓
|
||||
3. Risk Check
|
||||
↓
|
||||
4. Execute Trade (API)
|
||||
↓
|
||||
5. Drift Position Opened
|
||||
↓
|
||||
6. Position Manager Activated
|
||||
↓
|
||||
7. Pyth Price Monitor Started
|
||||
↓
|
||||
8. Price Checked Every 2 Seconds
|
||||
↓
|
||||
9a. TP1 Hit → Close 50%, SL to Breakeven
|
||||
↓
|
||||
9b. TP2 Hit → Close Remaining 50%
|
||||
↓
|
||||
OR
|
||||
↓
|
||||
9c. SL Hit → Close 100%
|
||||
↓
|
||||
10. Position Closed Automatically
|
||||
↓
|
||||
11. Remove from Monitoring
|
||||
```
|
||||
|
||||
### Example Auto-Exit Scenario
|
||||
|
||||
```
|
||||
Entry: BUY SOL @ $100.00
|
||||
Position: $10,000 (10x leverage)
|
||||
|
||||
Target Prices:
|
||||
- SL: $98.50 (-1.5%)
|
||||
- TP1: $100.70 (+0.7%)
|
||||
- TP2: $101.50 (+1.5%)
|
||||
- Emergency: $98.00 (-2.0%)
|
||||
|
||||
--- Price moves to $100.72 ---
|
||||
|
||||
✅ TP1 TRIGGERED!
|
||||
- Close 50% position ($5,000)
|
||||
- Realized P&L: +$70 (+7% account)
|
||||
- Move SL to $100.15 (breakeven)
|
||||
- Trade is now RISK-FREE
|
||||
|
||||
--- Price continues to $101.52 ---
|
||||
|
||||
✅ TP2 TRIGGERED!
|
||||
- Close remaining 50% ($5,000)
|
||||
- Realized P&L: +$150 (+15% account)
|
||||
- Total P&L: +$220 (+22% account)
|
||||
- Position fully closed
|
||||
|
||||
✅ TRADE COMPLETE (fully automated!)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Phase 2
|
||||
|
||||
### 1. Test Price Monitor
|
||||
|
||||
```bash
|
||||
# Create test script
|
||||
cat > v4/test-price-monitor.ts << 'EOF'
|
||||
import { getPythPriceMonitor } from './lib/pyth/price-monitor'
|
||||
|
||||
async function test() {
|
||||
const monitor = getPythPriceMonitor()
|
||||
|
||||
await monitor.start({
|
||||
symbols: ['SOL-PERP'],
|
||||
onPriceUpdate: (update) => {
|
||||
console.log(`💰 ${update.symbol}: $${update.price.toFixed(4)}`)
|
||||
},
|
||||
})
|
||||
|
||||
// Run for 30 seconds
|
||||
await new Promise(resolve => setTimeout(resolve, 30000))
|
||||
|
||||
await monitor.stop()
|
||||
}
|
||||
|
||||
test()
|
||||
EOF
|
||||
|
||||
# Run test
|
||||
npx tsx v4/test-price-monitor.ts
|
||||
|
||||
# Expected output:
|
||||
# 💰 SOL-PERP: $140.2350
|
||||
# 💰 SOL-PERP: $140.2351
|
||||
# 💰 SOL-PERP: $140.2348
|
||||
# (updates every ~1-2 seconds)
|
||||
```
|
||||
|
||||
### 2. Test Position Manager
|
||||
|
||||
```bash
|
||||
# Create test script
|
||||
cat > v4/test-position-manager.ts << 'EOF'
|
||||
import { getPositionManager } from './lib/trading/position-manager'
|
||||
|
||||
async function test() {
|
||||
const manager = getPositionManager()
|
||||
|
||||
// Add fake trade for testing
|
||||
await manager.addTrade({
|
||||
id: 'test-1',
|
||||
positionId: 'test-sig',
|
||||
symbol: 'SOL-PERP',
|
||||
direction: 'long',
|
||||
entryPrice: 140.0,
|
||||
entryTime: Date.now(),
|
||||
positionSize: 10000,
|
||||
leverage: 10,
|
||||
stopLossPrice: 137.9,
|
||||
tp1Price: 140.98,
|
||||
tp2Price: 142.1,
|
||||
emergencyStopPrice: 137.2,
|
||||
currentSize: 10000,
|
||||
tp1Hit: false,
|
||||
slMovedToBreakeven: false,
|
||||
slMovedToProfit: false,
|
||||
realizedPnL: 0,
|
||||
unrealizedPnL: 0,
|
||||
peakPnL: 0,
|
||||
priceCheckCount: 0,
|
||||
lastPrice: 140.0,
|
||||
lastUpdateTime: Date.now(),
|
||||
})
|
||||
|
||||
console.log('✅ Trade added to manager')
|
||||
console.log('📊 Status:', manager.getStatus())
|
||||
|
||||
// Monitor for 60 seconds
|
||||
await new Promise(resolve => setTimeout(resolve, 60000))
|
||||
|
||||
// Close all
|
||||
await manager.closeAll()
|
||||
}
|
||||
|
||||
test()
|
||||
EOF
|
||||
|
||||
# Run test
|
||||
npx tsx v4/test-position-manager.ts
|
||||
|
||||
# Expected: Price monitoring starts, updates every 2s
|
||||
```
|
||||
|
||||
### 3. Test Full Flow (Live Trade)
|
||||
|
||||
```bash
|
||||
# 1. Start your server
|
||||
npm run dev
|
||||
|
||||
# 2. Trigger a TradingView alert
|
||||
# (or use curl to simulate)
|
||||
|
||||
curl -X POST http://localhost:3000/api/trading/execute \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"symbol": "SOLUSDT",
|
||||
"direction": "long",
|
||||
"timeframe": "5"
|
||||
}'
|
||||
|
||||
# 3. Check positions
|
||||
curl http://localhost:3000/api/trading/positions \
|
||||
-H "Authorization: Bearer YOUR_API_KEY"
|
||||
|
||||
# 4. Watch the logs for auto-exits!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 API Endpoints
|
||||
|
||||
### Execute Trade (from Phase 1)
|
||||
```bash
|
||||
POST /api/trading/execute
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
|
||||
{
|
||||
"symbol": "SOLUSDT",
|
||||
"direction": "long",
|
||||
"timeframe": "5"
|
||||
}
|
||||
|
||||
# Now automatically adds to position manager!
|
||||
```
|
||||
|
||||
### Get Active Positions (NEW)
|
||||
```bash
|
||||
GET /api/trading/positions
|
||||
Authorization: Bearer YOUR_API_KEY
|
||||
|
||||
# Response:
|
||||
{
|
||||
"success": true,
|
||||
"monitoring": {
|
||||
"isActive": true,
|
||||
"tradeCount": 2,
|
||||
"symbols": ["SOL-PERP", "BTC-PERP"]
|
||||
},
|
||||
"positions": [{
|
||||
"id": "trade-123",
|
||||
"symbol": "SOL-PERP",
|
||||
"direction": "long",
|
||||
"entryPrice": 140.00,
|
||||
"currentPrice": 140.52,
|
||||
"unrealizedPnL": 52.00,
|
||||
"profitPercent": 0.37,
|
||||
"accountPnL": 3.7,
|
||||
"tp1Hit": false,
|
||||
...
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Features
|
||||
|
||||
### 1. Smart Exit Logic
|
||||
|
||||
**TP1 Hit (50% close):**
|
||||
- Automatically closes 50% of position
|
||||
- Moves SL to breakeven (+0.15% for fees)
|
||||
- Trade becomes risk-free
|
||||
- Lets remaining 50% run
|
||||
|
||||
**Profit Lock (+1.0%):**
|
||||
- When price reaches +1.0% profit
|
||||
- Moves SL to +0.4% profit
|
||||
- Guarantees minimum profit even if reverses
|
||||
|
||||
**Emergency Stop (-2.0%):**
|
||||
- Hard stop at -2% (before normal SL)
|
||||
- Protects against flash crashes
|
||||
- Closes 100% immediately
|
||||
|
||||
### 2. Real-Time Monitoring
|
||||
|
||||
**Price Updates:**
|
||||
- Pyth WebSocket: ~400ms latency
|
||||
- RPC Fallback: 2-second polling
|
||||
- Caching for instant access
|
||||
|
||||
**Exit Checks:**
|
||||
- Evaluated every 2 seconds
|
||||
- Prioritized (Emergency > SL > TP1 > TP2)
|
||||
- Market orders for instant execution
|
||||
|
||||
### 3. Multi-Position Support
|
||||
|
||||
**Can monitor:**
|
||||
- Multiple symbols simultaneously (SOL, BTC, ETH)
|
||||
- Multiple positions per symbol
|
||||
- Different strategies per position
|
||||
- Independent exit conditions
|
||||
|
||||
---
|
||||
|
||||
## 📝 Updated Setup Checklist
|
||||
|
||||
**Phase 1 (Required):**
|
||||
- [x] Drift integration working
|
||||
- [x] n8n webhook configured
|
||||
- [x] TradingView alerts set up
|
||||
- [x] API endpoints tested
|
||||
|
||||
**Phase 2 (New):**
|
||||
- [ ] Install Pyth SDK: `npm install @pythnetwork/price-service-client`
|
||||
- [ ] Test price monitor: `npx tsx v4/test-price-monitor.ts`
|
||||
- [ ] Test position manager: `npx tsx v4/test-position-manager.ts`
|
||||
- [ ] Execute test trade with auto-exits
|
||||
- [ ] Monitor first automated exit
|
||||
- [ ] Verify TP1 → SL adjustment works
|
||||
|
||||
---
|
||||
|
||||
## 💡 Configuration
|
||||
|
||||
### Risk Parameters (Optimized for 5min)
|
||||
|
||||
```env
|
||||
# Position sizing
|
||||
MAX_POSITION_SIZE_USD=1000
|
||||
LEVERAGE=10
|
||||
|
||||
# Exit targets (optimized for DEX)
|
||||
STOP_LOSS_PERCENT=-1.5 # -15% account
|
||||
TAKE_PROFIT_1_PERCENT=0.7 # +7% account (50% close)
|
||||
TAKE_PROFIT_2_PERCENT=1.5 # +15% account (50% close)
|
||||
EMERGENCY_STOP_PERCENT=-2.0 # -20% hard stop
|
||||
|
||||
# Dynamic adjustments
|
||||
BREAKEVEN_TRIGGER_PERCENT=0.4 # Move SL at +4% account
|
||||
PROFIT_LOCK_TRIGGER_PERCENT=1.0 # Move SL at +10% account
|
||||
PROFIT_LOCK_PERCENT=0.4 # Lock +4% profit
|
||||
|
||||
# Monitoring
|
||||
PRICE_CHECK_INTERVAL_MS=2000 # Check every 2s
|
||||
SLIPPAGE_TOLERANCE=1.0 # 1% max slippage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚧 What's Still Missing (Phase 3)
|
||||
|
||||
### Optional Enhancements:
|
||||
|
||||
1. **Database Integration**
|
||||
- Save trades to PostgreSQL
|
||||
- Historical P&L tracking
|
||||
- Performance analytics
|
||||
|
||||
2. **Risk Manager**
|
||||
- Daily P&L limits
|
||||
- Trades per hour enforcement
|
||||
- Cooldown periods
|
||||
- Account health checks
|
||||
|
||||
3. **Notifications**
|
||||
- Telegram: Entry/Exit alerts
|
||||
- Discord: Rich trade embeds
|
||||
- Email: Daily reports
|
||||
|
||||
4. **Web Dashboard**
|
||||
- View active trades
|
||||
- P&L charts
|
||||
- Trade history
|
||||
- Manual controls
|
||||
|
||||
**Note:** These are optional. The bot is fully functional without them!
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Important Notes
|
||||
|
||||
### Current Status
|
||||
|
||||
✅ **Fully Automated:**
|
||||
- Opens positions from TradingView signals
|
||||
- Monitors prices in real-time
|
||||
- Closes positions at TP/SL automatically
|
||||
- No manual intervention needed
|
||||
|
||||
✅ **Production Ready:**
|
||||
- Tested with live trades
|
||||
- Handles multiple positions
|
||||
- Robust error handling
|
||||
- WebSocket with fallback
|
||||
|
||||
### Recommendations
|
||||
|
||||
1. **Start Small:** Use $100-300 positions first
|
||||
2. **Monitor Closely:** Watch first 5-10 automated exits
|
||||
3. **Check Logs:** Review price updates and exit decisions
|
||||
4. **Verify Fills:** Confirm on Drift UI after exits
|
||||
5. **Adjust Parameters:** Fine-tune based on results
|
||||
|
||||
### Testing Strategy
|
||||
|
||||
**Week 1: Supervised Auto-Trading**
|
||||
- Execute 5-10 trades
|
||||
- Watch each auto-exit in real-time
|
||||
- Verify SL moves to breakeven after TP1
|
||||
- Check slippage on closes
|
||||
|
||||
**Week 2: Full Automation**
|
||||
- Let bot run unsupervised
|
||||
- Check positions 2-3x per day
|
||||
- Review daily P&L
|
||||
- Adjust parameters if needed
|
||||
|
||||
**Week 3: Scale Up**
|
||||
- Increase position size
|
||||
- Add more symbols
|
||||
- Fine-tune timing
|
||||
- Prepare statistics
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Congratulations!
|
||||
|
||||
**You now have a FULLY AUTOMATED trading bot!**
|
||||
|
||||
Features:
|
||||
- ✅ Auto-entry (TradingView → n8n → Drift)
|
||||
- ✅ Real-time monitoring (Pyth WebSocket)
|
||||
- ✅ Auto-exit (TP1/TP2/SL with market orders)
|
||||
- ✅ Smart risk management (breakeven, profit lock)
|
||||
- ✅ Multi-position support
|
||||
- ✅ Emergency stops
|
||||
|
||||
**The bot handles everything from signal to exit!**
|
||||
|
||||
---
|
||||
|
||||
## 📞 Next Steps
|
||||
|
||||
1. **Install Pyth SDK:**
|
||||
```bash
|
||||
npm install @pythnetwork/price-service-client
|
||||
```
|
||||
|
||||
2. **Test price monitoring:**
|
||||
```bash
|
||||
npx tsx v4/test-price-monitor.ts
|
||||
```
|
||||
|
||||
3. **Execute a test trade:**
|
||||
- Trigger TradingView alert
|
||||
- Watch for auto-execution
|
||||
- Monitor price checks in logs
|
||||
- Wait for automatic exit
|
||||
|
||||
4. **Scale up:**
|
||||
- Start with small positions
|
||||
- Monitor first 10 trades
|
||||
- Increase size gradually
|
||||
- Add more symbols
|
||||
|
||||
**Ready to let it run? The bot's got this! 🚀**
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### "Price monitor not starting"
|
||||
- Check SOLANA_RPC_URL is set
|
||||
- Verify Pyth Hermes is accessible
|
||||
- Try: `curl https://hermes.pyth.network/api/`
|
||||
|
||||
### "Position not auto-closing"
|
||||
- Check position manager logs
|
||||
- Verify price is actually hitting targets
|
||||
- Check Drift has liquidity
|
||||
- Review slippage tolerance
|
||||
|
||||
### "WebSocket disconnecting"
|
||||
- Normal - will reconnect automatically
|
||||
- Polling fallback takes over
|
||||
- Check RPC provider limits
|
||||
|
||||
### "Exits too slow"
|
||||
- Normal DEX lag (1-3 seconds)
|
||||
- Market orders execute ASAP
|
||||
- Check slippage on closes
|
||||
- Consider tighter targets
|
||||
|
||||
---
|
||||
|
||||
**Phase 2 Complete! 🎊**
|
||||
|
||||
*Time to watch the bot trade on its own!*
|
||||
564
docs/history/PHASE_2_SUMMARY.md
Normal file
564
docs/history/PHASE_2_SUMMARY.md
Normal file
@@ -0,0 +1,564 @@
|
||||
# 🎉 Phase 2 Complete Summary
|
||||
|
||||
## What We Built
|
||||
|
||||
Phase 2 transforms the trading bot from **manual monitoring** to **fully autonomous trading**!
|
||||
|
||||
### Before Phase 2:
|
||||
- ✅ Could open positions from TradingView signals
|
||||
- ❌ Required manual monitoring
|
||||
- ❌ Required manual exit execution
|
||||
- ❌ No real-time price tracking
|
||||
|
||||
### After Phase 2:
|
||||
- ✅ Opens positions automatically
|
||||
- ✅ Monitors prices in real-time
|
||||
- ✅ Executes exits automatically (TP1/TP2/SL)
|
||||
- ✅ Adjusts stop-loss dynamically
|
||||
- ✅ Handles multiple positions
|
||||
- ✅ Emergency stops for protection
|
||||
|
||||
**The bot now runs completely on its own!** 🚀
|
||||
|
||||
---
|
||||
|
||||
## 📦 New Components
|
||||
|
||||
### 1. Pyth Price Monitor (`lib/pyth/price-monitor.ts`)
|
||||
- **260 lines** of production-ready code
|
||||
- WebSocket connection to Pyth Hermes
|
||||
- RPC polling fallback (every 2s)
|
||||
- Multi-symbol support (SOL, BTC, ETH)
|
||||
- Price caching for instant access
|
||||
- Automatic reconnection
|
||||
- Error handling and logging
|
||||
|
||||
**Key Features**:
|
||||
- Sub-second WebSocket updates (~400ms latency)
|
||||
- Reliable fallback if WebSocket fails
|
||||
- Monitors multiple markets simultaneously
|
||||
- Cached prices for instant queries
|
||||
|
||||
### 2. Position Manager (`lib/trading/position-manager.ts`)
|
||||
- **460+ lines** of autonomous trading logic
|
||||
- Tracks all active trades
|
||||
- Monitors prices every 2 seconds
|
||||
- Executes market orders automatically
|
||||
- Smart stop-loss adjustments
|
||||
- Real-time P&L calculations
|
||||
|
||||
**Key Features**:
|
||||
- **TP1 Logic**: Closes 50% at +0.7%, moves SL to breakeven
|
||||
- **TP2 Logic**: Closes remaining 50% at +1.5%
|
||||
- **Stop Loss**: Closes 100% at -1.5%
|
||||
- **Emergency Stop**: Hard stop at -2.0%
|
||||
- **Profit Lock**: Moves SL to +0.4% when price hits +1.0%
|
||||
- **Multi-Position**: Handles multiple trades across symbols
|
||||
|
||||
### 3. Positions API (`app/api/trading/positions/route.ts`)
|
||||
- Query active positions
|
||||
- Real-time P&L
|
||||
- Monitoring status
|
||||
- Trade statistics
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Complete Autonomous Flow
|
||||
|
||||
```
|
||||
1. TradingView Alert (5-min chart signal)
|
||||
↓
|
||||
2. n8n Webhook Receives Signal
|
||||
↓
|
||||
3. Risk Validation Check
|
||||
↓
|
||||
4. Execute Trade API Called
|
||||
↓
|
||||
5. Drift Position Opened (Market Order)
|
||||
↓
|
||||
6. Position Manager Activated ⭐ NEW
|
||||
↓
|
||||
7. Pyth Price Monitor Started ⭐ NEW
|
||||
↓
|
||||
8. Price Checked Every 2 Seconds ⭐ NEW
|
||||
↓
|
||||
┌─────────────────┐
|
||||
│ Exit Monitoring │
|
||||
└─────────────────┘
|
||||
↓
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
↓ ↓
|
||||
TP1 (+0.7%) SL (-1.5%)
|
||||
Close 50% Close 100%
|
||||
Move SL to BE Exit Trade
|
||||
↓
|
||||
Price Continues
|
||||
↓
|
||||
TP2 (+1.5%)
|
||||
Close 50%
|
||||
Trade Complete!
|
||||
```
|
||||
|
||||
**No manual intervention required at any step!**
|
||||
|
||||
---
|
||||
|
||||
## 💰 Example Trade Scenario
|
||||
|
||||
### Entry
|
||||
```
|
||||
Signal: BUY SOL @ $140.00
|
||||
Position: $1,000
|
||||
Leverage: 10x
|
||||
Notional: $10,000
|
||||
|
||||
Targets:
|
||||
- SL: $137.90 (-1.5% = -$150 account)
|
||||
- TP1: $140.98 (+0.7% = +$70 account)
|
||||
- TP2: $142.10 (+1.5% = +$150 account)
|
||||
- Emergency: $137.20 (-2.0% = -$200 account)
|
||||
```
|
||||
|
||||
### TP1 Hit (+0.7%)
|
||||
```
|
||||
✅ Price reaches $140.98
|
||||
|
||||
Automatic Actions:
|
||||
1. Close 50% position ($5,000)
|
||||
2. Realized P&L: +$70 (+7% account)
|
||||
3. Move SL to $140.21 (breakeven + 0.15%)
|
||||
4. Trade now RISK-FREE
|
||||
|
||||
Status:
|
||||
- Remaining Position: $5,000
|
||||
- Realized Profit: +$70
|
||||
- New SL: Breakeven (no risk!)
|
||||
```
|
||||
|
||||
### TP2 Hit (+1.5%)
|
||||
```
|
||||
✅ Price reaches $142.10
|
||||
|
||||
Automatic Actions:
|
||||
1. Close remaining 50% ($5,000)
|
||||
2. Realized P&L: +$150 (+15% account)
|
||||
|
||||
Final Results:
|
||||
- Total P&L: +$220 (+22% account)
|
||||
- Win Rate: 100%
|
||||
- Risk: $0 (was risk-free after TP1)
|
||||
- Trade Duration: ~15-45 minutes
|
||||
```
|
||||
|
||||
### Alternative: TP1 → SL at Breakeven
|
||||
```
|
||||
✅ TP1 hit, closed 50%, SL moved to BE
|
||||
❌ Price reverses, hits $140.21
|
||||
|
||||
Automatic Actions:
|
||||
1. Close remaining 50% at breakeven
|
||||
|
||||
Final Results:
|
||||
- Total P&L: +$70 (+7% account)
|
||||
- Win Rate: 100%
|
||||
- Risk: $0 (SL was at breakeven)
|
||||
```
|
||||
|
||||
### Worst Case: Direct SL Hit
|
||||
```
|
||||
❌ Price drops to $137.90
|
||||
|
||||
Automatic Actions:
|
||||
1. Close 100% position immediately
|
||||
|
||||
Final Results:
|
||||
- Total P&L: -$150 (-15% account)
|
||||
- Loss contained to plan
|
||||
- No emotional decisions
|
||||
- Move on to next trade
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Features
|
||||
|
||||
### Smart Risk Management
|
||||
|
||||
**TP1 Profit Taking (50%)**:
|
||||
- Locks in partial profit
|
||||
- Reduces position risk
|
||||
- Moves SL to breakeven
|
||||
- Lets remaining position run
|
||||
|
||||
**Dynamic Stop-Loss**:
|
||||
- **After TP1**: Moves to breakeven (+0.15% for fees)
|
||||
- **At +1.0% profit**: Moves to +0.4% profit
|
||||
- **Never moves backward**: Only forward
|
||||
- **Protects gains**: Ensures minimum profit
|
||||
|
||||
**Emergency Protection**:
|
||||
- Hard stop at -2.0%
|
||||
- Executes before normal SL
|
||||
- Protects against flash crashes
|
||||
- No questions asked
|
||||
|
||||
### Real-Time Monitoring
|
||||
|
||||
**Price Updates**:
|
||||
- Pyth WebSocket: ~400ms latency
|
||||
- RPC Polling: 2-second intervals
|
||||
- Cached for instant access
|
||||
- Reliable fallback system
|
||||
|
||||
**Exit Checks**:
|
||||
- Every 2 seconds
|
||||
- Prioritized: Emergency > SL > TP1 > TP2
|
||||
- Market orders for instant execution
|
||||
- Slippage tolerance: 1%
|
||||
|
||||
**Multi-Position**:
|
||||
- Track multiple symbols
|
||||
- Independent strategies
|
||||
- Different parameters per trade
|
||||
- Simultaneous monitoring
|
||||
|
||||
---
|
||||
|
||||
## 📊 API Endpoints
|
||||
|
||||
### POST /api/trading/execute
|
||||
**Executes trade and starts monitoring**
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"symbol": "SOLUSDT",
|
||||
"direction": "long",
|
||||
"timeframe": "5"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Position opened and monitoring started",
|
||||
"trade": {
|
||||
"id": "trade-1234567890",
|
||||
"symbol": "SOL-PERP",
|
||||
"direction": "long",
|
||||
"entryPrice": 140.235,
|
||||
"positionSize": 1000,
|
||||
"leverage": 10,
|
||||
"stopLossPrice": 137.90,
|
||||
"tp1Price": 140.98,
|
||||
"tp2Price": 142.10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/trading/positions
|
||||
**Query active positions**
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"monitoring": {
|
||||
"isActive": true,
|
||||
"tradeCount": 2,
|
||||
"symbols": ["SOL-PERP", "BTC-PERP"]
|
||||
},
|
||||
"positions": [{
|
||||
"id": "trade-1234567890",
|
||||
"symbol": "SOL-PERP",
|
||||
"direction": "long",
|
||||
"entryPrice": 140.235,
|
||||
"currentPrice": 140.521,
|
||||
"unrealizedPnL": 20.36,
|
||||
"profitPercent": 0.20,
|
||||
"accountPnL": 2.04,
|
||||
"tp1Hit": false,
|
||||
"slMovedToBreakeven": false,
|
||||
"positionSize": 10000,
|
||||
"currentSize": 10000,
|
||||
"leverage": 10,
|
||||
"stopLossPrice": 137.90,
|
||||
"tp1Price": 140.98,
|
||||
"tp2Price": 142.10,
|
||||
"entryTime": 1234567890000,
|
||||
"lastUpdateTime": 1234567892000,
|
||||
"priceCheckCount": 42
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Phase 2
|
||||
|
||||
Three comprehensive test scripts included:
|
||||
|
||||
### 1. test-price-monitor.ts
|
||||
Tests Pyth price monitoring
|
||||
- WebSocket connection
|
||||
- Update frequency
|
||||
- Multi-symbol support
|
||||
- Fallback system
|
||||
|
||||
```bash
|
||||
npx tsx v4/test-price-monitor.ts
|
||||
```
|
||||
|
||||
### 2. test-position-manager.ts
|
||||
Tests position tracking and logic
|
||||
- Trade tracking
|
||||
- Exit condition checks
|
||||
- Multi-position handling
|
||||
- Status reporting
|
||||
|
||||
```bash
|
||||
npx tsx v4/test-position-manager.ts
|
||||
```
|
||||
|
||||
### 3. test-full-flow.ts
|
||||
End-to-end test with real trade
|
||||
- Complete autonomous flow
|
||||
- Real Drift execution
|
||||
- Live monitoring
|
||||
- Automatic exits
|
||||
|
||||
```bash
|
||||
npx tsx v4/test-full-flow.ts
|
||||
```
|
||||
|
||||
See `TESTING.md` for detailed testing guide.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Documentation
|
||||
|
||||
### New Documents:
|
||||
- ✅ `PHASE_2_COMPLETE.md` - Feature overview
|
||||
- ✅ `TESTING.md` - Comprehensive testing guide
|
||||
- ✅ Updated `SETUP.md` - Phase 2 setup
|
||||
|
||||
### Existing Documents (Updated):
|
||||
- ✅ `TRADING_BOT_V4_MANUAL.md` - Complete manual
|
||||
- ✅ `QUICKSTART_V4.md` - Quick start guide
|
||||
- ✅ `N8N_SETUP_GUIDE.md` - n8n configuration
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
### Environment Variables
|
||||
```env
|
||||
# Required
|
||||
DRIFT_WALLET_PRIVATE_KEY=your_base58_key
|
||||
SOLANA_RPC_URL=your_rpc_url
|
||||
API_KEY=your_secret_key
|
||||
|
||||
# Optional (Defaults shown)
|
||||
MAX_POSITION_SIZE_USD=1000
|
||||
LEVERAGE=10
|
||||
STOP_LOSS_PERCENT=-1.5
|
||||
TAKE_PROFIT_1_PERCENT=0.7
|
||||
TAKE_PROFIT_2_PERCENT=1.5
|
||||
EMERGENCY_STOP_PERCENT=-2.0
|
||||
BREAKEVEN_TRIGGER_PERCENT=0.4
|
||||
PROFIT_LOCK_TRIGGER_PERCENT=1.0
|
||||
PROFIT_LOCK_PERCENT=0.4
|
||||
PRICE_CHECK_INTERVAL_MS=2000
|
||||
SLIPPAGE_TOLERANCE=1.0
|
||||
```
|
||||
|
||||
### Risk Parameters
|
||||
Optimized for 5-minute scalping with 10x leverage:
|
||||
|
||||
- **Position**: $1,000 account capital
|
||||
- **Leverage**: 10x ($10,000 notional)
|
||||
- **SL**: -1.5% position = -$150 account (15%)
|
||||
- **TP1**: +0.7% position = +$70 account (7%)
|
||||
- **TP2**: +1.5% position = +$150 account (15%)
|
||||
- **Emergency**: -2.0% position = -$200 hard stop (20%)
|
||||
|
||||
**Max Risk per Trade**: 15% of account
|
||||
**Max Reward per Trade**: 22% of account (if both TPs hit)
|
||||
**Risk/Reward Ratio**: 1:1.47
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Production Ready
|
||||
|
||||
### What's Working:
|
||||
- ✅ Fully autonomous trading
|
||||
- ✅ Real-time price monitoring
|
||||
- ✅ Automatic exit execution
|
||||
- ✅ Multi-position support
|
||||
- ✅ Dynamic risk management
|
||||
- ✅ Emergency protection
|
||||
- ✅ Robust error handling
|
||||
- ✅ Comprehensive logging
|
||||
|
||||
### What's Optional (Phase 3):
|
||||
- ⏳ Database persistence
|
||||
- ⏳ Trade history
|
||||
- ⏳ Risk manager enforcement
|
||||
- ⏳ Enhanced notifications
|
||||
- ⏳ Performance analytics
|
||||
- ⏳ Web dashboard
|
||||
|
||||
**You can start trading NOW!**
|
||||
|
||||
---
|
||||
|
||||
## 📈 Expected Performance
|
||||
|
||||
### Target Metrics (5-Min Scalping):
|
||||
- **Win Rate**: 60-70% (realistic for DEX)
|
||||
- **Avg Win**: +7% to +22% account
|
||||
- **Avg Loss**: -15% account
|
||||
- **Trades/Day**: 5-15 (depends on signals)
|
||||
- **Daily Target**: +2% to +5% account
|
||||
- **Max Drawdown**: -15% per trade, -30% daily
|
||||
|
||||
### Sample Day:
|
||||
```
|
||||
Trade 1: +7% (TP1 only)
|
||||
Trade 2: +22% (TP1 + TP2)
|
||||
Trade 3: -15% (SL)
|
||||
Trade 4: +7% (TP1 only)
|
||||
Trade 5: +22% (TP1 + TP2)
|
||||
|
||||
Daily P&L: +43% 🎉
|
||||
```
|
||||
|
||||
### Risk Management:
|
||||
- Max 1-2 concurrent positions
|
||||
- 10-minute cooldown between trades
|
||||
- Max 6 trades per hour
|
||||
- Max -15% loss per trade
|
||||
- Daily stop at -30%
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Next Steps
|
||||
|
||||
### Week 1: Supervised Trading
|
||||
1. Run test scripts to validate
|
||||
2. Execute 5-10 small trades ($10-50)
|
||||
3. Watch each auto-exit in real-time
|
||||
4. Verify SL moves after TP1
|
||||
5. Check P&L matches Drift UI
|
||||
|
||||
### Week 2: Scale Up
|
||||
1. Increase to $100-300 positions
|
||||
2. Add more symbols (BTC, ETH)
|
||||
3. Reduce monitoring frequency
|
||||
4. Trust the automation
|
||||
5. Track win rate and P&L
|
||||
|
||||
### Week 3: Full Automation
|
||||
1. Let bot run unsupervised
|
||||
2. Check positions 2-3x per day
|
||||
3. Review daily P&L reports
|
||||
4. Adjust parameters if needed
|
||||
5. Prepare statistics for Phase 3
|
||||
|
||||
---
|
||||
|
||||
## 🐛 Known Limitations
|
||||
|
||||
1. **WebSocket may disconnect**
|
||||
- Normal behavior
|
||||
- Automatically reconnects
|
||||
- Polling fallback takes over
|
||||
- No impact on monitoring
|
||||
|
||||
2. **DEX Slippage**
|
||||
- Market orders have 1% tolerance
|
||||
- Large positions may slip more
|
||||
- Stick to small-mid size
|
||||
- Check fills on Drift UI
|
||||
|
||||
3. **RPC Rate Limits**
|
||||
- Some RPCs limit requests
|
||||
- Use paid RPC for production
|
||||
- Helius recommended
|
||||
- Fallback between sources
|
||||
|
||||
4. **No Position Persistence**
|
||||
- Positions stored in memory
|
||||
- Server restart = lose tracking
|
||||
- Phase 3 adds database
|
||||
- Won't lose Drift positions (safe)
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security Reminders
|
||||
|
||||
1. **Private Key Security**
|
||||
- Never commit to git
|
||||
- Use dedicated trading wallet
|
||||
- Keep small balances
|
||||
- Backup securely
|
||||
|
||||
2. **API Key Protection**
|
||||
- Strong random key
|
||||
- Not in public code
|
||||
- Rotate regularly
|
||||
- Monitor usage
|
||||
|
||||
3. **Position Sizing**
|
||||
- Start small ($10-50)
|
||||
- Max 2-5% of portfolio
|
||||
- Never risk more than 20%
|
||||
- Scale gradually
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Congratulations!
|
||||
|
||||
You now have a **fully autonomous trading bot**!
|
||||
|
||||
### What You Built:
|
||||
- ✅ 700+ lines of production code
|
||||
- ✅ Real-time price monitoring
|
||||
- ✅ Automatic position management
|
||||
- ✅ Smart risk management
|
||||
- ✅ Multi-position support
|
||||
- ✅ Comprehensive testing
|
||||
- ✅ Full documentation
|
||||
|
||||
### What It Does:
|
||||
- Receives TradingView signals
|
||||
- Opens positions on Drift
|
||||
- Monitors prices in real-time
|
||||
- Executes exits automatically
|
||||
- Adjusts stops dynamically
|
||||
- Protects your capital
|
||||
- **Runs 24/7 without supervision!**
|
||||
|
||||
---
|
||||
|
||||
## 📞 Support
|
||||
|
||||
### Documentation:
|
||||
- `PHASE_2_COMPLETE.md` - This file
|
||||
- `TESTING.md` - Testing guide
|
||||
- `SETUP.md` - Setup instructions
|
||||
- `TRADING_BOT_V4_MANUAL.md` - Complete manual
|
||||
|
||||
### Common Issues:
|
||||
- See `TESTING.md` troubleshooting section
|
||||
- Check `.env.local` configuration
|
||||
- Review console logs
|
||||
- Verify Drift UI matches
|
||||
|
||||
---
|
||||
|
||||
**Phase 2 is COMPLETE! Time to watch it trade! 🚀**
|
||||
|
||||
*Remember: Start small, monitor closely, scale gradually!*
|
||||
289
docs/history/QUICKREF_PHASE2.md
Normal file
289
docs/history/QUICKREF_PHASE2.md
Normal file
@@ -0,0 +1,289 @@
|
||||
# 🚀 Phase 2 Quick Reference
|
||||
|
||||
## What's New
|
||||
|
||||
✅ **Fully Autonomous Trading**
|
||||
- Opens positions from signals
|
||||
- Monitors prices in real-time
|
||||
- Closes automatically at TP/SL
|
||||
- Adjusts stops dynamically
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Install
|
||||
```bash
|
||||
./install-phase2.sh
|
||||
```
|
||||
|
||||
### 2. Configure
|
||||
```bash
|
||||
# Edit .env.local:
|
||||
DRIFT_WALLET_PRIVATE_KEY=your_key
|
||||
SOLANA_RPC_URL=your_rpc
|
||||
API_KEY=your_secret
|
||||
```
|
||||
|
||||
### 3. Test
|
||||
```bash
|
||||
cd v4
|
||||
|
||||
# Test price monitoring
|
||||
npx tsx test-price-monitor.ts
|
||||
|
||||
# Test position manager
|
||||
npx tsx test-position-manager.ts
|
||||
|
||||
# Test full flow (REAL TRADE!)
|
||||
npx tsx test-full-flow.ts
|
||||
```
|
||||
|
||||
### 4. Trade
|
||||
```bash
|
||||
# Start server
|
||||
npm run dev
|
||||
|
||||
# Trigger TradingView alert
|
||||
# Bot handles everything!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Features
|
||||
|
||||
### Smart Exits
|
||||
- **TP1 (+0.7%)**: Close 50%, move SL to breakeven
|
||||
- **TP2 (+1.5%)**: Close remaining 50%
|
||||
- **SL (-1.5%)**: Close 100%
|
||||
- **Emergency (-2.0%)**: Hard stop
|
||||
|
||||
### Dynamic SL
|
||||
- After TP1: Move to breakeven
|
||||
- At +1.0% profit: Move to +0.4%
|
||||
- Never moves backward
|
||||
- Protects all gains
|
||||
|
||||
### Real-Time
|
||||
- Pyth WebSocket (~400ms)
|
||||
- Polling fallback (2s)
|
||||
- Checks every 2 seconds
|
||||
- Market orders for speed
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Execute Trade
|
||||
```bash
|
||||
POST /api/trading/execute
|
||||
{
|
||||
"symbol": "SOLUSDT",
|
||||
"direction": "long",
|
||||
"timeframe": "5"
|
||||
}
|
||||
```
|
||||
|
||||
### Get Positions
|
||||
```bash
|
||||
GET /api/trading/positions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Trade Example
|
||||
|
||||
### Entry
|
||||
```
|
||||
Signal: LONG SOL @ $140.00
|
||||
Position: $1,000 (10x = $10,000)
|
||||
SL: $137.90 (-1.5% = -$150)
|
||||
TP1: $140.98 (+0.7% = +$70)
|
||||
TP2: $142.10 (+1.5% = +$150)
|
||||
```
|
||||
|
||||
### TP1 Hit
|
||||
```
|
||||
✅ Price: $140.98
|
||||
→ Close 50% (+$70)
|
||||
→ Move SL to $140.21 (breakeven)
|
||||
→ Risk = $0
|
||||
```
|
||||
|
||||
### TP2 Hit
|
||||
```
|
||||
✅ Price: $142.10
|
||||
→ Close 50% (+$150)
|
||||
→ Total P&L: +$220 (+22%)
|
||||
→ Trade complete!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
- [ ] Run install-phase2.sh
|
||||
- [ ] Configure .env.local
|
||||
- [ ] Test price monitor (no risk)
|
||||
- [ ] Test position manager (no risk)
|
||||
- [ ] Test full flow with $10-50 position
|
||||
- [ ] Watch first 5-10 auto-exits
|
||||
- [ ] Verify on Drift UI
|
||||
- [ ] Scale up gradually
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Risk Parameters
|
||||
```env
|
||||
MAX_POSITION_SIZE_USD=1000
|
||||
LEVERAGE=10
|
||||
STOP_LOSS_PERCENT=-1.5
|
||||
TAKE_PROFIT_1_PERCENT=0.7
|
||||
TAKE_PROFIT_2_PERCENT=1.5
|
||||
EMERGENCY_STOP_PERCENT=-2.0
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
```env
|
||||
PRICE_CHECK_INTERVAL_MS=2000
|
||||
SLIPPAGE_TOLERANCE=1.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Cannot find module"
|
||||
```bash
|
||||
npm install @pythnetwork/price-service-client
|
||||
```
|
||||
|
||||
### "Drift service not initialized"
|
||||
```bash
|
||||
# Check .env.local has:
|
||||
DRIFT_WALLET_PRIVATE_KEY=...
|
||||
SOLANA_RPC_URL=...
|
||||
```
|
||||
|
||||
### "WebSocket disconnected"
|
||||
```
|
||||
Normal - will reconnect automatically
|
||||
Polling fallback handles updates
|
||||
```
|
||||
|
||||
### "Position not closing"
|
||||
```
|
||||
Check:
|
||||
1. Is price hitting targets?
|
||||
2. Are logs showing price checks?
|
||||
3. Is position manager running?
|
||||
|
||||
Most likely: Targets not hit yet!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Targets
|
||||
|
||||
### 5-Minute Scalping
|
||||
- **Win Rate**: 60-70%
|
||||
- **Avg Win**: +7% to +22%
|
||||
- **Avg Loss**: -15%
|
||||
- **Daily Target**: +2% to +5%
|
||||
- **Trades/Day**: 5-15
|
||||
|
||||
### Example Day
|
||||
```
|
||||
Trade 1: +7% (TP1)
|
||||
Trade 2: +22% (TP1+TP2)
|
||||
Trade 3: -15% (SL)
|
||||
Trade 4: +7% (TP1)
|
||||
Trade 5: +22% (TP1+TP2)
|
||||
Daily: +43% 🎉
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Safety Rules
|
||||
|
||||
1. **Start small**: $10-50 positions
|
||||
2. **Monitor closely**: First 10 trades
|
||||
3. **Verify exits**: Check Drift UI
|
||||
4. **Scale gradually**: Increase 2x weekly
|
||||
5. **Max risk**: Never > 20% per trade
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- `PHASE_2_COMPLETE.md` - Full features
|
||||
- `PHASE_2_SUMMARY.md` - Overview
|
||||
- `TESTING.md` - Testing guide
|
||||
- `SETUP.md` - Setup instructions
|
||||
- `TRADING_BOT_V4_MANUAL.md` - Complete manual
|
||||
|
||||
---
|
||||
|
||||
## What's Next (Phase 3)
|
||||
|
||||
- Database integration
|
||||
- Trade history persistence
|
||||
- Risk manager enforcement
|
||||
- Enhanced notifications
|
||||
- Performance analytics
|
||||
- Web dashboard
|
||||
|
||||
**But you can trade NOW!**
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
### Common Commands
|
||||
```bash
|
||||
# Install Phase 2
|
||||
./install-phase2.sh
|
||||
|
||||
# Test monitoring
|
||||
cd v4 && npx tsx test-price-monitor.ts
|
||||
|
||||
# Test manager
|
||||
cd v4 && npx tsx test-position-manager.ts
|
||||
|
||||
# Test full flow
|
||||
cd v4 && npx tsx test-full-flow.ts
|
||||
|
||||
# Start server
|
||||
npm run dev
|
||||
|
||||
# Check positions
|
||||
curl http://localhost:3000/api/trading/positions \
|
||||
-H "Authorization: Bearer YOUR_API_KEY"
|
||||
```
|
||||
|
||||
### Files Changed
|
||||
```
|
||||
New:
|
||||
+ v4/lib/pyth/price-monitor.ts
|
||||
+ v4/lib/trading/position-manager.ts
|
||||
+ v4/app/api/trading/positions/route.ts
|
||||
+ v4/test-price-monitor.ts
|
||||
+ v4/test-position-manager.ts
|
||||
+ v4/test-full-flow.ts
|
||||
+ v4/PHASE_2_COMPLETE.md
|
||||
+ v4/PHASE_2_SUMMARY.md
|
||||
+ v4/TESTING.md
|
||||
+ install-phase2.sh
|
||||
|
||||
Updated:
|
||||
~ v4/app/api/trading/execute/route.ts
|
||||
~ v4/SETUP.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Phase 2 Complete! Let the bot trade! 🚀**
|
||||
|
||||
*Start small, monitor closely, scale gradually!*
|
||||
66
docs/history/STATUS_COMMAND_QUICKREF.txt
Normal file
66
docs/history/STATUS_COMMAND_QUICKREF.txt
Normal file
@@ -0,0 +1,66 @@
|
||||
╔════════════════════════════════════════════════════════════════╗
|
||||
║ TELEGRAM /status COMMAND ║
|
||||
║ ✅ READY TO USE ║
|
||||
╚════════════════════════════════════════════════════════════════╝
|
||||
|
||||
📱 HOW TO USE
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
1. Open your Telegram bot chat
|
||||
2. Send: /status
|
||||
3. Get instant position info!
|
||||
|
||||
📊 WHAT YOU'LL SEE
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
✅ Current P&L ($ and % of account)
|
||||
✅ Entry price & current price
|
||||
✅ TP1, TP2, and SL levels with status
|
||||
✅ Position size & leverage
|
||||
✅ Trade age in minutes
|
||||
|
||||
🎯 EXAMPLE OUTPUT
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
🟢 SOL-PERP 📈 LONG
|
||||
|
||||
💰 P&L: $3.50 (+0.70% account)
|
||||
📊 Price Change: +0.07%
|
||||
|
||||
Entry: $142.5000
|
||||
Current: $142.6000
|
||||
|
||||
Targets:
|
||||
TP1: $143.4975 ⏳
|
||||
TP2: $144.6375
|
||||
SL: $140.3625
|
||||
|
||||
Position: $500.00 @ 10x
|
||||
Age: 5 min
|
||||
|
||||
🔧 TECHNICAL STATUS
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
✅ Container: telegram-trade-bot (Running)
|
||||
✅ Network: Connected to trading-bot-v4
|
||||
✅ API: Authenticated & tested
|
||||
✅ Command: /status handler active
|
||||
|
||||
📝 ALL COMMANDS
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
/status → Show current position
|
||||
/buySOL → Long SOL
|
||||
/sellSOL → Short SOL
|
||||
/buyBTC → Long BTC
|
||||
/sellBTC → Short BTC
|
||||
/buyETH → Long ETH
|
||||
/sellETH → Short ETH
|
||||
|
||||
🔐 SECURITY
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
✅ Only works in YOUR chat (579304651)
|
||||
✅ API authentication required
|
||||
✅ Internal Docker network
|
||||
✅ No internet exposure
|
||||
|
||||
🎉 READY!
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
Open Telegram and send /status to try it now!
|
||||
|
||||
Next: Open a position, then check /status to see it in action! 🚀
|
||||
172
docs/history/TELEGRAM_STATUS_IMPLEMENTATION.md
Normal file
172
docs/history/TELEGRAM_STATUS_IMPLEMENTATION.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# Telegram /status Command - Implementation Summary
|
||||
|
||||
## ✅ **Feature Complete**
|
||||
|
||||
You can now send `/status` in your Telegram channel to get real-time information about your open position on Drift Protocol.
|
||||
|
||||
---
|
||||
|
||||
## 📊 What You'll See
|
||||
|
||||
### When No Position Is Open:
|
||||
```
|
||||
📊 No open positions
|
||||
|
||||
All clear! Ready for new signals.
|
||||
```
|
||||
|
||||
### When You Have an Open Position:
|
||||
```
|
||||
🟢 SOL-PERP 📈 LONG
|
||||
|
||||
💰 P&L: $3.50 (+0.70% account)
|
||||
📊 Price Change: +0.07%
|
||||
|
||||
Entry: $142.5000
|
||||
Current: $142.6000
|
||||
|
||||
Targets:
|
||||
TP1: $143.4975 ✅ (if hit)
|
||||
TP2: $144.6375 ⏳
|
||||
SL: $140.3625
|
||||
|
||||
Position: $500.00 @ 10x
|
||||
Age: 5 min
|
||||
```
|
||||
|
||||
### Legend:
|
||||
- 🟢 = Profit | 🔴 = Loss | ⚪ = Breakeven
|
||||
- 📈 = Long | 📉 = Short
|
||||
- ✅ = Target hit | ⏳ = Pending
|
||||
|
||||
---
|
||||
|
||||
## 🚀 How to Use
|
||||
|
||||
1. Open your Telegram bot chat
|
||||
2. Send: `/status`
|
||||
3. Get instant position info!
|
||||
|
||||
You can send it anytime - while trading, after hours, whenever you want to check your position.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 What Changed
|
||||
|
||||
### Files Modified:
|
||||
1. **`telegram_command_bot.py`**
|
||||
- Added `status_command()` function
|
||||
- Fetches data from trading bot API
|
||||
- Formats beautiful status messages
|
||||
|
||||
2. **`docker-compose.telegram-bot.yml`**
|
||||
- Added `TRADING_BOT_URL` environment variable
|
||||
- Added `API_SECRET_KEY` environment variable
|
||||
|
||||
3. **`.env.telegram-bot`**
|
||||
- Added trading bot URL (internal Docker network)
|
||||
- Added API secret key for authentication
|
||||
|
||||
### New Environment Variables:
|
||||
```bash
|
||||
TRADING_BOT_URL=http://trading-bot-v4:3000
|
||||
API_SECRET_KEY=2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Verification
|
||||
|
||||
**Container Status:**
|
||||
```bash
|
||||
docker ps | grep telegram-trade-bot
|
||||
# Output: Up About a minute
|
||||
```
|
||||
|
||||
**Bot Logs:**
|
||||
```bash
|
||||
docker logs telegram-trade-bot --tail 10
|
||||
# Shows: ✅ Commands: /status - Show open positions
|
||||
```
|
||||
|
||||
**API Connectivity Test:**
|
||||
```bash
|
||||
docker exec telegram-trade-bot python3 -c "import requests; r=requests.get('http://trading-bot-v4:3000/api/trading/positions', headers={'Authorization': 'Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb'}); print(r.status_code)"
|
||||
# Output: 200 ✅
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Live Example Use Cases
|
||||
|
||||
### Morning Check:
|
||||
```
|
||||
You: /status
|
||||
Bot: 🟢 SOL-PERP 📈 LONG
|
||||
💰 P&L: $8.25 (+1.65% account)
|
||||
TP1: $143.50 ✅
|
||||
Runner position active!
|
||||
```
|
||||
|
||||
### During Volatile Move:
|
||||
```
|
||||
You: /status
|
||||
Bot: 🔴 SOL-PERP 📈 LONG
|
||||
💰 P&L: -$3.75 (-0.75% account)
|
||||
Current: $141.80
|
||||
SL: $140.36 (still safe!)
|
||||
```
|
||||
|
||||
### Multiple Times Per Day:
|
||||
- Check before meetings
|
||||
- Monitor during lunch
|
||||
- Quick check before bed
|
||||
- Anytime you're curious!
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Security
|
||||
|
||||
✅ **Only works in YOUR Telegram chat** (TELEGRAM_CHAT_ID=579304651)
|
||||
✅ **Requires API authentication** (API_SECRET_KEY)
|
||||
✅ **Internal Docker network** (not exposed to internet)
|
||||
✅ **Same security as main trading bot**
|
||||
|
||||
---
|
||||
|
||||
## 📝 Available Commands
|
||||
|
||||
Your Telegram bot now supports:
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `/status` | Show current open position |
|
||||
| `/buySOL` | Open long SOL position |
|
||||
| `/sellSOL` | Open short SOL position |
|
||||
| `/buyBTC` | Open long BTC position |
|
||||
| `/sellBTC` | Open short BTC position |
|
||||
| `/buyETH` | Open long ETH position |
|
||||
| `/sellETH` | Open short ETH position |
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Ready to Use!
|
||||
|
||||
Your Telegram bot is running and ready. Just send `/status` to try it out!
|
||||
|
||||
**Container:** `telegram-trade-bot` ✅ Running
|
||||
**Network:** Connected to `trading-bot-v4` ✅
|
||||
**API:** Authenticated and tested ✅
|
||||
**Commands:** `/status` handler active ✅
|
||||
|
||||
---
|
||||
|
||||
## 📚 Documentation Updated
|
||||
|
||||
- ✅ `TELEGRAM_BOT_README.md` - Updated with /status usage
|
||||
- ✅ `TEST_STATUS_COMMAND.md` - Testing guide
|
||||
- ✅ `TELEGRAM_STATUS_IMPLEMENTATION.md` - This file
|
||||
|
||||
---
|
||||
|
||||
**Next time you open a position, send `/status` to see it in action!** 🚀
|
||||
110
docs/history/TEST_STATUS_COMMAND.md
Normal file
110
docs/history/TEST_STATUS_COMMAND.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Testing the /status Command
|
||||
|
||||
## ✅ Feature Implemented
|
||||
|
||||
The Telegram bot now supports the `/status` command to show current open positions.
|
||||
|
||||
## What It Shows
|
||||
|
||||
When you send `/status` in your Telegram chat, you'll receive:
|
||||
|
||||
### If No Positions Are Open:
|
||||
```
|
||||
📊 No open positions
|
||||
|
||||
All clear! Ready for new signals.
|
||||
```
|
||||
|
||||
### If Position Is Open:
|
||||
```
|
||||
🟢 SOL-PERP 📈 LONG
|
||||
|
||||
💰 P&L: $3.50 (+0.70% account)
|
||||
📊 Price Change: +0.07%
|
||||
|
||||
Entry: $142.5000
|
||||
Current: $142.6000
|
||||
|
||||
Targets:
|
||||
TP1: $143.4975 ⏳
|
||||
TP2: $144.6375
|
||||
SL: $140.3625
|
||||
|
||||
Position: $500.00 @ 10x
|
||||
Age: 5 min
|
||||
```
|
||||
|
||||
### Emojis Used:
|
||||
- 🟢 Green = Position in profit
|
||||
- 🔴 Red = Position in loss
|
||||
- ⚪ White = Breakeven
|
||||
- 📈 = Long position
|
||||
- 📉 = Short position
|
||||
- ✅ = Target hit
|
||||
- ⏳ = Target pending
|
||||
|
||||
## Technical Details
|
||||
|
||||
### How It Works:
|
||||
1. User sends `/status` in Telegram
|
||||
2. Bot calls `GET /api/trading/positions` on trading-bot-v4:3000
|
||||
3. Bot parses response and formats position data
|
||||
4. Bot sends formatted message back to user
|
||||
|
||||
### Files Modified:
|
||||
- `telegram_command_bot.py` - Added `status_command()` handler
|
||||
- `docker-compose.telegram-bot.yml` - Added environment variables
|
||||
- `.env.telegram-bot` - Added `TRADING_BOT_URL` and `API_SECRET_KEY`
|
||||
|
||||
### Environment Variables Required:
|
||||
```bash
|
||||
TRADING_BOT_URL=http://trading-bot-v4:3000
|
||||
API_SECRET_KEY=<same as main .env file>
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### 1. Test from Terminal (API):
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_SECRET_KEY" \
|
||||
http://localhost:3001/api/trading/positions | jq .
|
||||
```
|
||||
|
||||
### 2. Test from Telegram:
|
||||
- Open your Telegram bot chat
|
||||
- Send: `/status`
|
||||
- Should receive position info or "No open positions"
|
||||
|
||||
### 3. Test with Active Position:
|
||||
- Execute a test trade first:
|
||||
- Send `/buySOL` or use settings page "Test LONG"
|
||||
- Then send `/status`
|
||||
- Should see full position details
|
||||
|
||||
## Verification
|
||||
|
||||
✅ Container running:
|
||||
```bash
|
||||
docker ps | grep telegram-trade-bot
|
||||
```
|
||||
|
||||
✅ Logs showing /status handler:
|
||||
```bash
|
||||
docker logs telegram-trade-bot --tail 20
|
||||
```
|
||||
|
||||
✅ Network connectivity:
|
||||
```bash
|
||||
docker exec telegram-trade-bot python3 -c "import requests; r=requests.get('http://trading-bot-v4:3000/api/trading/positions', headers={'Authorization': 'Bearer YOUR_KEY'}); print(r.status_code)"
|
||||
```
|
||||
|
||||
Should output: `200`
|
||||
|
||||
## Next Steps
|
||||
|
||||
You can now monitor your positions in real-time from your phone!
|
||||
|
||||
Just send `/status` anytime to check:
|
||||
- Current P&L
|
||||
- How close you are to TP/SL
|
||||
- How long the trade has been open
|
||||
Reference in New Issue
Block a user