Skip to content

Repository files navigation

Binance Spot Trading Bot

Production-grade Node.js trading bot for Binance Spot with simultaneous DCA + aggressive scalping strategies.

  • Paper trading by default (risk-free testing)
  • Safe live mode (requires multiple confirmations)
  • Spot only (no leverage, no shorting)
  • Telegram notifications (trades, errors, alerts)
  • Risk management (position sizing, circuit breakers, loss limits)
  • Modular architecture (easy to extend)

Table of Contents

  1. Quick Start
  2. Architecture
  3. Strategies
  4. Configuration
  5. Running
  6. Testing
  7. Go-Live
  8. Troubleshooting

Quick Start

Prerequisites

  • Node.js 18 LTS or higher
  • Windows (tested on Windows 10+)
  • Binance account (live mode only)

Installation

# Clone or extract the bot
cd binance-spot-trading-bot

# Install dependencies
npm install

# Copy example config
Copy-Item .env.example .env

# Edit .env with your settings
notepad .env

Run (Paper Mode)

# Paper mode is the default (no API keys needed)
npm start

Run (Live Mode - Advanced)

# 1. Edit .env
# Set: TRADING_MODE=live
# Set: BINANCE_API_KEY=your_key
# Set: BINANCE_API_SECRET=your_secret
# Set: LIVE_MODE_CONFIRMED=true

# 2. Run (you'll be prompted to confirm)
npm start

# 3. When prompted:
# Type: CONFIRM_LIVE_TRADING
# Then bot starts with real trading enabled

Architecture

Components

┌─────────────────────────────────────────────────────────────┐
│                    Trading Engine (Main Loop)               │
│  • Fetches candles every 5 seconds                          │
│  • Routes to strategies (DCA + Scalping)                    │
│  • Executes orders through paper or live exchange           │
└─────────────────────────────────────────────────────────────┘
           │              │              │
           ▼              ▼              ▼
    ┌────────────┐  ┌───────────┐  ┌──────────────┐
    │ DCA        │  │ Scalping  │  │ Risk Manager │
    │ Strategy   │  │ Strategy  │  │              │
    │ (Time-based│  │ (Trend-   │  │ • Position   │
    │ + dips)    │  │  following│  │   sizing     │
    │            │  │  shorts)  │  │ • Limits     │
    └────────────┘  └───────────┘  └──────────────┘
           │              │              │
           └──────────────┼──────────────┘
                          ▼
            ┌─────────────────────────┐
            │  Exchange               │
            │  • Binance API (live)   │
            │  • Paper Engine (paper) │
            └─────────────────────────┘
                          │
            ┌─────────────┴──────────────┐
            ▼                            ▼
    ┌─────────────────┐        ┌─────────────────┐
    │ Notifications   │        │ Storage/Logs    │
    │ • Telegram      │        │ • SQLite        │
    │ • Console       │        │ • JSON logs     │
    └─────────────────┘        └─────────────────┘

Module Structure

src/
├── config/          # Configuration loading + validation
├── logger/          # Winston logging
├── indicators/      # RSI, EMA, ATR calculations
├── exchange/        # Binance API integration
├── paper/           # Paper trading engine (fees, slippage)
├── strategies/
│   ├── dca.js       # DCA strategy
│   └── scalping.js  # Scalping strategy
├── risk/            # Risk management, position sizing
├── notifiers/       # Telegram notifications
├── engine/          # Main trading orchestrator
└── index.js         # Entry point

Strategies

DCA (Dollar-Cost Averaging)

Goal: Long-term accumulation at consistent intervals + on dips.

Entry:

  • Scheduled: Every 6 hours (configurable)
  • Dip-triggered: When RSI < 30 OR price is 5% below EMA200 (configurable)

Exit:

  • Mean reversion: Close when price > EMA200 + 2% (configurable)

Config (.env):

DCA_INTERVAL_HOURS=6
DCA_RSI_DIP_THRESHOLD=30
DCA_PRICE_DIP_THRESHOLD=5
DCA_TRANCHE_SIZE_PERCENT=2
DCA_MAX_TRANCHES=4
DCA_EXIT_THRESHOLD_PERCENT=2

Scalping (Aggressive Trend-Following)

Goal: Capture 0.8% gains with tight stops, multiple times per day.

Rules:

  • Trend filter: Only trade when price > EMA200 (5m) — no shorting in downtrends
  • Entry: RSI pulls back to <30 while price > EMA200
  • Exits:
    • Take-profit: 0.8% above entry
    • Stop-loss: 0.5% below entry (hard stop)
    • Trailing stop: Activate at +0.5%, trail by 0.3%
  • Anti-chop:
    • 10-min cooldown after a loss
    • Max 8 trades/hour
    • No re-entry within 3 candles of exit

Config (.env):

SCALP_TREND_EMA_PERIOD=200
SCALP_RSI_OVERSOLD=30
SCALP_TAKE_PROFIT_PERCENT=0.8
SCALP_STOP_LOSS_PERCENT=0.5
SCALP_TRAILING_STOP_ACTIVATE_PERCENT=0.5
SCALP_TRAILING_STOP_TRAIL_PERCENT=0.3
SCALP_COOLDOWN_AFTER_LOSS_MIN=10
SCALP_MAX_TRADES_PER_HOUR=8
SCALP_NO_REENTRY_CANDLES=3

Configuration

Copy .env.example to .env and customize:

Essential Settings

# Mode: paper or live
TRADING_MODE=paper

# Symbols to trade (comma-separated)
TRADING_SYMBOLS=BTCUSDT,ETHUSDT

# Telegram (optional, but recommended for alerts)
TELEGRAM_BOT_TOKEN=<your_bot_token>
TELEGRAM_CHAT_ID=<your_chat_id>

Binance API (Live Mode Only)

BINANCE_API_KEY=<your_key>
BINANCE_API_SECRET=<your_secret>

# Confirmation flags
LIVE_MODE_CONFIRMED=true

Risk Parameters

# Per-trade risk
RISK_PER_TRADE_PERCENT=0.5

# Daily max loss (triggers circuit breaker)
RISK_DAILY_MAX_LOSS_PERCENT=3

# Max consecutive losses before cooldown
RISK_MAX_CONSECUTIVE_LOSSES=3

# Max open positions
RISK_MAX_OPEN_POSITIONS=5

Paper Mode Simulation

# Realistic fee simulation
PAPER_MAKER_FEE_PERCENT=0.1
PAPER_TAKER_FEE_PERCENT=0.1

# Slippage simulation
PAPER_SLIPPAGE_BPS=5

# Starting capital for paper trading
PAPER_STARTING_BALANCE=1000

Running

Paper Mode (Default, Safe)

npm start

Console output:

═══════════════════════════════════════════════════
  Binance Spot Trading Bot
  Mode: PAPER
  Symbols: BTCUSDT, ETHUSDT
═══════════════════════════════════════════════════

[INFO] Bot started successfully
[INFO] Exchange initialized (paper mode - no real credentials)
[INFO] Telegram notifier initialized

Live Mode (Real Money)

# 1. Edit .env
TRADING_MODE=live
LIVE_MODE_CONFIRMED=true

# 2. Verify API keys are set
BINANCE_API_KEY=xxx
BINANCE_API_SECRET=xxx

# 3. Start
npm start

# 4. Confirm when prompted:
⚠️  LIVE MODE DETECTED ⚠️
This will trade with REAL MONEY on Binance.

Type CONFIRM_LIVE_TRADING to enable live mode:

Dev Mode (Verbose Logging)

$env:LOG_LEVEL = 'debug'
npm start

Testing

Unit Tests (Indicators, Risk)

npm run test:unit

Paper Mode Integration Test (24h)

npm run test:paper

Historical Backtesting

npm run backtest

Loads historical klines and replays bot logic.


Go-Live Checklist

Before switching to live mode:

  • Paper mode ran successfully for 24+ hours
  • All trades logged correctly
  • Telegram notifications working
  • Daily max loss is conservative (3% default)
  • Position sizing reviewed (0.5% risk per trade)
  • API keys are correct and permissions checked
  • API key IP whitelist configured on Binance
  • LIVE_MODE_CONFIRMED=true is set in .env
  • Run CONFIRM_LIVE_TRADING prompt successfully
  • Initial capital is small (<100 USDT) until confident
  • Monitor first 24h closely
  • Backup config and logs daily

Safe Switching Procedure

  1. Paper → Live Transition:

    # 1. Verify paper mode stats
    npm run test:paper
    
    # 2. Review logs/combined.log
    
    # 3. Edit .env:
    # TRADING_MODE=live
    # LIVE_MODE_CONFIRMED=true
    # BINANCE_API_KEY=xxx
    # BINANCE_API_SECRET=xxx
    
    # 4. Start with small capital first
    # 5. Run with TELEGRAM_BOT_TOKEN set for alerts
    npm start
  2. Pause if Issues:

    # Edit .env:
    # PAUSE_TRADING=true
    # (or SIGINT: Ctrl+C)
  3. Revert to Paper:

    # Edit .env:
    # TRADING_MODE=paper
    npm start

Telegram Integration

Setup

  1. Create bot:

    • Message @BotFather on Telegram
    • /newbot → Follow prompts → Get token
  2. Get chat ID:

  3. Add to .env:

    TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
    TELEGRAM_CHAT_ID=987654321
  4. Test:

    # Should receive a test message on first run
    npm start

Message Examples

Entry Alert:

🔔 DCA ENTRY

Symbol: BTCUSDT
Side: BUY
Quantity: 0.00123456
Price: $45,250.00

Exit Alert:

✅ SCALP EXIT (TAKE_PROFIT)

Symbol: ETHUSDT
Entry: $2,500.00
Exit: $2,520.00
Quantity: 0.10000000
PnL: +$20.00 (+0.80%)

Circuit Breaker Alert:

🛑 CIRCUIT BREAKER TRIGGERED

Reason: Daily max loss exceeded
Daily Loss: $30.00
Consecutive Losses: 3
Status: Trading PAUSED

Troubleshooting

"Failed to initialize Binance exchange"

Live mode: Verify API keys in .env and network connectivity.

Paper mode: Should work offline. Check .env is valid.

"Rate limit exceeded"

Binance has rate limits (1200 weight/min). Bot respects this; reduce SCALP_MAX_TRADES_PER_HOUR if hitting limits.

"Insufficient balance"

Paper mode: Increase PAPER_STARTING_BALANCE in .env. Live mode: Deposit more USDT to Binance account.

"Order never fills"

Live mode: Limit orders may not fill in volatile markets. Bot uses market orders for faster execution.

Paper mode: Fills are simulated; no issue.

Telegram not sending

  1. Verify TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID
  2. Test manually:
    curl -X POST "https://api.telegram.org/bot<TOKEN>/sendMessage" `
      -d "chat_id=<CHAT_ID>&text=Test"
  3. Check firewall/network

Performance slow

  • Reduce CANDLE_FETCH_INTERVAL_SEC in .env (default 5s)
  • Reduce TRADING_SYMBOLS to fewer pairs

Performance Notes

Paper Mode: Simulates realistic fees (0.1% taker/maker) and slippage (5 bps).

Live Mode: Subject to real Binance fees, network latency, market gaps, and partial fills.

Expected Drawdown: 3–5% on aggressive strategies during choppy markets.

Best Conditions: Trending markets (uptrend for DCA, clear uptrend for scalping).

Worst Conditions: Choppy sideways markets (scalping gets whipsawed by false signals).


Security Notes

  • Never commit .env to version control (contains secrets)
  • API key permissions: Use Read-only for testing; minimize permissions for live
  • IP whitelist: Add bot IP to Binance API key settings
  • Audit logs: Review logs/combined.log and logs/error.log regularly

Disclaimer

⚠️ This bot is for educational purposes. Trading crypto involves risk of financial loss. The developer(s) are not liable for losses. Test in paper mode first. Start with small capital. Use at your own risk.


License

MIT


Support

  • Issues: Check logs/error.log
  • Questions: Review ARCHITECTURE.md and code comments
  • Improvements: Feel free to fork and extend

Happy trading! 🚀

Remember: Past performance ≠ future results. Manage risk carefully.

About

Dual-strategy Binance Spot trading bot (DCA + Scalping)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages