Skip to content

Latest commit

 

History

History
321 lines (274 loc) · 14.3 KB

File metadata and controls

321 lines (274 loc) · 14.3 KB

How the Bot Works - Complete Explanation

🏗️ Architecture Overview

The bot is a real-time automated trading system that:

  1. Receives live market data from AsterDEX
  2. Analyzes price movements using technical indicators
  3. Generates trading signals based on strategy rules
  4. Executes trades automatically (in live mode)
  5. Manages risk and positions

Data Flow Diagram

┌─────────────────────────────────────────────────────────────┐
│                    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                                   │
└─────────────────────────────────────────────────────────────┘

Main Components

1. TickStream (AsterTickStream)

  • 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 tick events

2. VirtualBarBuilder

  • 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 closedBar when timeframe completes

3. Strategy Engine (WatermellonEngine or PeachHybridEngine)

  • 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.)

4. BotRunner

  • 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

5. RestPoller

  • 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

6. Executor (DryRunExecutor or LiveExecutor)

  • Purpose: Executes trades
  • DryRunExecutor: Only logs, doesn't trade
  • LiveExecutor: Makes real API calls to place orders

Trading Strategy Logic

Watermellon Strategy

Entry Conditions:

  • Long Signal:

    1. EMA Fast > EMA Mid > EMA Slow (bull stack)
    2. RSI > 42
    3. Rising edge (wasn't in long look before)
  • Short Signal:

    1. EMA Fast < EMA Mid < EMA Slow (bear stack)
    2. RSI < 58
    3. Rising edge (wasn't in short look before)

Peach Hybrid Strategy

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)

Risk Management

Pre-Trade Checks:

  1. Balance Check: Sufficient funds for margin?
  2. Flip Limit: Not exceeding max trades per hour
  3. Position Check: Not already in same position
  4. Emergency Stop: Trading frozen if reconciliation fails

During Trade:

  1. Stop Loss: Closes position if loss exceeds threshold
  2. Take Profit: Closes position if profit target reached
  3. Emergency Stop Loss: Always active (default 2%)

Position Management:

  1. State Reconciliation: Local state vs exchange state
  2. Order Tracking: Confirms orders are executed
  3. Position Limits: Max 1 position at a time (configurable)

Security Features

  1. KeyManager: Prevents API keys from being logged
  2. Environment Variables: All secrets in .env file
  3. HMAC Signatures: Secure API authentication
  4. Dry-Run Mode: Safe testing without real trades

Execution Flow Example

Example: Long Signal Generated

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

Continuous Operation

The bot runs in a continuous loop:

  1. WebSocket: Receives ticks 24/7
  2. Bar Building: Creates bars every 30 seconds
  3. Strategy Analysis: Evaluates each closed bar
  4. REST Polling: Syncs state every 2 seconds
  5. Position Monitoring: Checks exit conditions every bar
  6. State Persistence: Saves state to disk periodically

Key Features

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)


Getting Started

  1. Configure: Set up .env.local with API credentials
  2. Test: Run in dry-run mode first
  3. Monitor: Watch logs for signals and execution
  4. Deploy: Switch to live mode when ready
  5. 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.