The bot is a real-time automated trading system that:
- Receives live market data from AsterDEX
- Analyzes price movements using technical indicators
- Generates trading signals based on strategy rules
- Executes trades automatically (in live mode)
- Manages risk and positions
┌─────────────────────────────────────────────────────────────┐
│ BOT STARTUP │
│ 1. Load configuration from .env │
│ 2. Initialize components │
│ 3. Connect to WebSocket & REST API │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ WEBSOCKET CONNECTION │
│ AsterTickStream → wss://fstream.asterdex.com/ws │
│ • Subscribes to market data stream │
│ • Receives real-time price ticks │
│ • Auto-reconnects on disconnect │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ TICK PROCESSING │
│ Each tick contains: { price, timestamp, size } │
│ • Tick arrives → VirtualBarBuilder │
│ • Aggregates ticks into 30-second bars │
│ • Creates OHLCV (Open, High, Low, Close, Volume) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BAR CLOSURE │
│ When 30 seconds pass → Bar closes │
│ • Closed bar sent to Strategy Engine │
│ • Indicators calculated (EMA, RSI) │
│ • Strategy rules evaluated │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ STRATEGY ENGINE │
│ Two strategies available: │
│ │
│ 1. WATERMELLON: │
│ • EMA Stack (8/21/48) for trend │
│ • RSI(14) for momentum │
│ • Long: Bull stack + RSI > 42 │
│ • Short: Bear stack + RSI < 58 │
│ │
│ 2. PEACH HYBRID: │
│ V1 System (Trend/Bias): │
│ • EMA stack + Micro EMAs │
│ • RSI thresholds │
│ • Min bars between signals │
│ │
│ V2 System (Momentum Surge): │
│ • RSI momentum threshold │
│ • Volume spike detection │
│ • Volume color (green/red) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ SIGNAL GENERATION │
│ If strategy conditions met → Generate signal │
│ • Signal type: "long" or "short" │
│ • Signal reason: "v1-long", "v2-short", etc. │
│ • Includes indicator values │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ RISK MANAGEMENT │
│ Before executing: │
│ • Check balance (sufficient funds?) │
│ • Check flip limit (max trades per hour?) │
│ • Check position (already in position?) │
│ • Check stop-loss/take-profit │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ ORDER EXECUTION │
│ DRY-RUN MODE: │
│ • Logs order to console │
│ • No real trades executed │
│ │
│ LIVE MODE: │
│ • Sets leverage │
│ • Places market order via REST API │
│ • Tracks order confirmation │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ POSITION MANAGEMENT │
│ • Updates local position state │
│ • Polls REST API every 2 seconds │
│ • Reconciles local vs exchange state │
│ • Monitors for stop-loss/take-profit │
│ • Handles exit conditions │
└─────────────────────────────────────────────────────────────┘
- Purpose: Connects to AsterDEX WebSocket
- What it does:
- Establishes WebSocket connection
- Subscribes to market data stream
- Receives real-time price ticks
- Handles reconnection automatically
- Emits
tickevents
- Purpose: Converts ticks into candlestick bars
- What it does:
- Receives individual ticks
- Groups ticks into time-based bars (default: 30 seconds)
- Calculates OHLCV (Open, High, Low, Close, Volume)
- Emits
closedBarwhen timeframe completes
- Purpose: Analyzes market data and generates signals
- What it does:
- Updates indicators (EMA, RSI) with each bar
- Evaluates strategy rules
- Generates "long" or "short" signals when conditions met
- Tracks state (last signals, price moves, etc.)
- Purpose: Orchestrates the entire trading process
- What it does:
- Connects all components
- Processes signals from strategy engine
- Applies risk management rules
- Executes trades through executor
- Manages position state
- Handles stop-loss/take-profit
- Purpose: Syncs with exchange via REST API
- What it does:
- Polls balance every 2 seconds
- Polls position every 2 seconds
- Reconciles local state with exchange
- Detects external position changes
- Purpose: Executes trades
- DryRunExecutor: Only logs, doesn't trade
- LiveExecutor: Makes real API calls to place orders
Entry Conditions:
-
Long Signal:
- EMA Fast > EMA Mid > EMA Slow (bull stack)
- RSI > 42
- Rising edge (wasn't in long look before)
-
Short Signal:
- EMA Fast < EMA Mid < EMA Slow (bear stack)
- RSI < 58
- Rising edge (wasn't in short look before)
V1 System (Trend/Bias):
- Uses EMA stack (8/21/48) + Micro EMAs (5/13)
- Requires:
- Bull/bear stack alignment
- Micro stack alignment
- RSI threshold (42 for long, 58 for short)
- Minimum bars between signals
- Minimum price move percentage
V2 System (Momentum Surge):
- Detects momentum bursts
- Requires:
- RSI momentum surge (≥3 points in 2 bars)
- Volume spike (≥1.5x average)
- Volume color (green for long, red for short)
- EMA direction alignment
Exit Conditions:
- RSI flattening (<1.5 points momentum)
- Volume drop (<1.2x average)
- Balance Check: Sufficient funds for margin?
- Flip Limit: Not exceeding max trades per hour
- Position Check: Not already in same position
- Emergency Stop: Trading frozen if reconciliation fails
- Stop Loss: Closes position if loss exceeds threshold
- Take Profit: Closes position if profit target reached
- Emergency Stop Loss: Always active (default 2%)
- State Reconciliation: Local state vs exchange state
- Order Tracking: Confirms orders are executed
- Position Limits: Max 1 position at a time (configurable)
- KeyManager: Prevents API keys from being logged
- Environment Variables: All secrets in .env file
- HMAC Signatures: Secure API authentication
- Dry-Run Mode: Safe testing without real trades
1. Bar closes (30 seconds passed)
EXPLANATION: The VirtualBarBuilder continuously receives price ticks from the WebSocket.
Every tick updates the current bar (high, low, close, volume). When 30 seconds have elapsed
since the bar started (elapsed >= timeframeMs), the bar is considered "closed" and a new
bar begins. The closed bar contains the final OHLCV data and triggers strategy analysis.
↓
2. Strategy engine analyzes:
- EMA Fast: 1.2909
- EMA Mid: 1.2912
- EMA Slow: 1.2908
- RSI: 57.27
- Bull stack:
- RSI > 42:
↓
3. Signal generated: { type: "long", reason: "v1-long" }
↓
4. Risk checks:
- Balance sufficient?
- Flip limit OK?
- Not already long?
↓
5. Execute order:
- Set leverage to 5x
- Place MARKET BUY order
- Size: 10000 USDT
↓
6. Update position:
- Local state: long, 10000 USDT
- Track order for confirmation
↓
7. Monitor:
- Check stop-loss every bar
- Check take-profit every bar
- Reconcile with exchange every 2 seconds
The bot runs in a continuous loop:
- WebSocket: Receives ticks 24/7
- Bar Building: Creates bars every 30 seconds
- Strategy Analysis: Evaluates each closed bar
- REST Polling: Syncs state every 2 seconds
- Position Monitoring: Checks exit conditions every bar
- State Persistence: Saves state to disk periodically
Real-time market data via WebSocket Automatic reconnection if connection drops Multiple strategies (Watermellon & Peach Hybrid) Risk management (stop-loss, take-profit, flip limits) State persistence (survives restarts) Dry-run mode (safe testing) Live mode (real trading) Position reconciliation (local vs exchange) Balance monitoring (prevents insufficient funds)
- Configure: Set up
.env.localwith API credentials - Test: Run in
dry-runmode first - Monitor: Watch logs for signals and execution
- Deploy: Switch to
livemode when ready - Monitor: Keep an eye on positions and balance
This bot is designed to be fully automated - once started, it runs continuously, making trading decisions based on the configured strategy and risk parameters.