Skip to content

Repository files navigation

Gate.io Market Maker Bot

A sophisticated automated market making bot for Gate.io spot trading, designed to provide liquidity while managing risk and maximizing profitability.

Python Version License Status

🎯 Features

  • Automated Market Making: Places symmetrical buy/sell orders around mid-price
  • Dynamic Spread Calculation: Adjusts spreads based on volatility, inventory, and market conditions
  • Multi-Layer Orders: Supports multiple order layers for better liquidity provision
  • Inventory Management: Automatic rebalancing to maintain target inventory levels
  • Risk Management: Comprehensive risk controls including daily loss limits, position limits, and circuit breakers
  • Paper Trading Mode: Safe testing environment with simulated trading
  • Real-time Market Data: WebSocket integration for live price updates
  • Comprehensive Logging: Detailed logging and monitoring capabilities
  • Emergency Shutdown: Graceful shutdown with state persistence

📋 Table of Contents


🔧 Requirements

System Requirements

  • Python: 3.8 or higher
  • Operating System: Windows 10/11, Linux, macOS, or WSL
  • RAM: Minimum 2GB, recommended 4GB
  • Storage: 500MB for application and logs
  • Internet: Stable connection for WebSocket data

Trading Requirements

  • Gate.io Account: Required for live trading
  • API Credentials: Gate.io API key and secret (for live trading)
  • Capital: Recommended minimum $500 for live trading
  • Knowledge: Basic understanding of market making and cryptocurrency trading

Python Package Dependencies

gate-api>=4.0.0          # Official Gate.io API SDK
pandas>=1.3.0            # Data manipulation
numpy>=1.21.0            # Numerical computations
python-dotenv>=0.19.0    # Environment variable management
websocket-client>=1.2.0  # WebSocket connections
requests>=2.26.0         # HTTP requests
pydantic>=1.8.0          # Data validation
pytest>=6.2.0            # Testing framework (optional)

🚀 Quick Start

For Beginners (Paper Trading - Safe Mode)

# 1. Clone the repository
git clone <repository-url>
cd mmviviek

# 2. Run automated setup (Windows)
.\setup_windows.ps1

# 3. Start paper trading
python run_bot.py

That's it! The bot will run in safe paper trading mode with simulated funds.

For Advanced Users (Live Trading)

# 1. Complete installation (see Installation section)
# 2. Configure .env with real API credentials
# 3. Set PAPER_TRADING=false
# 4. Test configuration
python main.py --test

# 5. Start live trading
python main.py

📦 Installation

Windows Setup

Option 1: Automated Setup (Recommended)

# Open PowerShell in the project directory
# Run the setup script
.\setup_windows.ps1

This will:

  • ✅ Create a virtual environment
  • ✅ Install all dependencies
  • ✅ Create configuration files
  • ✅ Test the installation

Option 2: Manual Setup

# 1. Create virtual environment
python -m venv venv

# 2. Activate virtual environment
.\venv\Scripts\Activate.ps1

# 3. Upgrade pip
python -m pip install --upgrade pip

# 4. Install dependencies
pip install -r requirements.txt

# 5. Create configuration file
copy .env.example .env

# 6. Edit configuration
notepad .env

Troubleshooting Windows:

If you get "execution of scripts is disabled":

# Run PowerShell as Administrator
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Linux/WSL Setup

# 1. Update system packages
sudo apt update && sudo apt upgrade -y

# 2. Install Python and pip (if not installed)
sudo apt install python3 python3-pip python3-venv -y

# 3. Clone repository
git clone <repository-url>
cd mmviviek

# 4. Create virtual environment
python3 -m venv venv

# 5. Activate virtual environment
source venv/bin/activate

# 6. Upgrade pip
pip install --upgrade pip

# 7. Install dependencies
pip install -r requirements.txt

# 8. Create configuration file
cp .env.example .env

# 9. Edit configuration
nano .env

macOS Setup

# 1. Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 2. Install Python
brew install python@3.10

# 3. Clone repository
git clone <repository-url>
cd mmviviek

# 4. Create virtual environment
python3 -m venv venv

# 5. Activate virtual environment
source venv/bin/activate

# 6. Install dependencies
pip install -r requirements.txt

# 7. Create configuration file
cp .env.example .env

# 8. Edit configuration
nano .env

Verify Installation

After installation, verify everything is working:

# Test imports
python test_imports.py

# Test configuration
python main.py --test

# Expected output:
# ✅ Configuration loaded
# ✅ API connection test passed
# ✅ Market data test passed
# ✅ All tests passed!

⚙️ Configuration Reference

Complete .env Configuration Parameters

API Configuration

Parameter Type Default Description Example
GATE_API_KEY string "" Your Gate.io API key "abc123..."
GATE_API_SECRET string "" Your Gate.io API secret "xyz789..."

Impact: Required for live trading. Leave empty for paper trading.

Security: Never commit these to version control. Keep in .env file only.

Trading Configuration

Parameter Type Range Default Description
TRADING_PAIRS string - "BTC_USDT,ETH_USDT" Comma-separated trading pairs
ORDER_LAYERS integer 1-10 3 Number of order layers per side
LAYER_SPACING float 0.0001-0.01 0.001 Spacing between layers (0.1%)
BASE_ORDER_SIZE float >0 0.01 Base order size in base currency
MIN_SPREAD float 0.0001-0.1 0.001 Minimum spread (0.1%)
MAX_SPREAD float 0.001-0.5 0.02 Maximum spread (2%)
ORDER_REFRESH_INTERVAL integer 1-300 10 Order refresh interval (seconds)
PAPER_TRADING boolean true/false true Enable paper trading mode

Trading Pairs Format: Use Gate.io format with underscore (e.g., BTC_USDT, ETH_USDT)

Order Layers: More layers = better liquidity but more capital required

  • Beginner: 2-3 layers
  • Advanced: 4-6 layers
  • Expert: 7-10 layers

Layer Spacing: Distance between order layers

  • Tight (0.0005 = 0.05%): High-frequency, requires more monitoring
  • Normal (0.001 = 0.1%): Balanced approach
  • Wide (0.005 = 0.5%): Conservative, less frequent fills

Base Order Size: Amount per order in base currency

  • BTC: 0.001 - 0.01 BTC
  • ETH: 0.01 - 0.1 ETH
  • Calculate based on: portfolio_value * max_position_size / order_layers

Spread Range:

  • MIN_SPREAD: Must cover fees (Gate.io: 0.05% taker, -0.015% maker)
  • MAX_SPREAD: Upper limit during high volatility
  • Recommended: MIN=0.1%, MAX=2%

Risk Configuration

Parameter Type Range Default Description
MAX_POSITION_SIZE float 0.001-0.1 0.01 Max position size (1% of portfolio)
MAX_INVENTORY_SKEW float 0.05-0.5 0.20 Max inventory deviation (±20%)
DAILY_LOSS_LIMIT float -0.1 to -0.001 -0.02 Daily loss limit (-2%)
VOLATILITY_THRESHOLD float 0.01-0.1 0.03 Volatility pause threshold (3%)
MAX_DRAWDOWN float -0.2 to -0.01 -0.05 Maximum drawdown (-5%)
POSITION_CHECK_INTERVAL integer 10-300 30 Position check interval (seconds)

Max Position Size: Percentage of portfolio per trade

  • Conservative: 0.005 (0.5%)
  • Moderate: 0.01 (1%)
  • Aggressive: 0.02 (2%)

Max Inventory Skew: Maximum deviation from 50/50 balance

  • Conservative: 0.10 (±10%)
  • Moderate: 0.20 (±20%)
  • Aggressive: 0.30 (±30%)

Daily Loss Limit: Auto-shutdown threshold

  • Conservative: -0.01 (-1%)
  • Moderate: -0.02 (-2%)
  • Aggressive: -0.05 (-5%)

Volatility Threshold: Pause trading when volatility exceeds

  • Low volatility markets: 0.02 (2%)
  • Normal markets: 0.03 (3%)
  • High volatility markets: 0.05 (5%)

Logging Configuration

Parameter Type Options Default Description
LOG_LEVEL string DEBUG/INFO/WARNING/ERROR "INFO" Logging verbosity
LOG_FILE string - "logs/marketmaker.log" Main log file path
ENABLE_CONSOLE boolean true/false true Enable console logging
ENABLE_FILE boolean true/false true Enable file logging

Log Levels:

  • DEBUG: Detailed information for debugging (verbose)
  • INFO: General information (recommended)
  • WARNING: Warning messages only
  • ERROR: Error messages only

Redis Configuration (Optional)

Parameter Type Default Description
REDIS_URL string "redis://localhost:6379" Redis connection URL
REDIS_DB integer 0 Redis database number
REDIS_KEY_PREFIX string "marketmaker:" Key prefix for Redis

Note: Redis is optional. Used for distributed state management.


📝 Configuration Examples

Example 1: Conservative Trading (Minimal Risk)

Best for: Beginners, small capital ($500-$2000), stable markets

# API Configuration
GATE_API_KEY=your_api_key_here
GATE_API_SECRET=your_api_secret_here

# Trading Configuration
TRADING_PAIRS=BTC_USDT              # Single pair to start
ORDER_LAYERS=2                       # Fewer layers
LAYER_SPACING=0.002                  # 0.2% spacing (wider)
BASE_ORDER_SIZE=0.001                # Small order size
MIN_SPREAD=0.002                     # 0.2% minimum (safe)
MAX_SPREAD=0.05                      # 5% maximum
ORDER_REFRESH_INTERVAL=30            # Less frequent updates

# Risk Configuration
MAX_POSITION_SIZE=0.005              # 0.5% per trade (very conservative)
MAX_INVENTORY_SKEW=0.10              # ±10% max deviation
DAILY_LOSS_LIMIT=-0.01               # -1% daily loss limit (strict)
VOLATILITY_THRESHOLD=0.02            # 2% volatility pause (sensitive)
MAX_DRAWDOWN=-0.03                   # -3% max drawdown

# Logging
LOG_LEVEL=INFO

# Paper Trading (start here!)
PAPER_TRADING=true

Expected Performance:

  • Daily ROI: 0.05% - 0.15%
  • Risk Level: Low
  • Capital Required: $500+
  • Monitoring: 2-3 times per day

Example 2: Moderate Trading (Balanced Risk/Reward)

Best for: Intermediate users, medium capital ($2000-$10000), normal markets

# API Configuration
GATE_API_KEY=your_api_key_here
GATE_API_SECRET=your_api_secret_here

# Trading Configuration
TRADING_PAIRS=BTC_USDT,ETH_USDT      # Multiple pairs
ORDER_LAYERS=3                        # Standard layers
LAYER_SPACING=0.001                   # 0.1% spacing (normal)
BASE_ORDER_SIZE=0.01                  # Medium order size
MIN_SPREAD=0.001                      # 0.1% minimum
MAX_SPREAD=0.02                       # 2% maximum
ORDER_REFRESH_INTERVAL=10             # Standard refresh

# Risk Configuration
MAX_POSITION_SIZE=0.01                # 1% per trade (moderate)
MAX_INVENTORY_SKEW=0.20               # ±20% max deviation
DAILY_LOSS_LIMIT=-0.02                # -2% daily loss limit
VOLATILITY_THRESHOLD=0.03             # 3% volatility pause
MAX_DRAWDOWN=-0.05                    # -5% max drawdown

# Logging
LOG_LEVEL=INFO

# Paper Trading (test first!)
PAPER_TRADING=true

Expected Performance:

  • Daily ROI: 0.1% - 0.3%
  • Risk Level: Medium
  • Capital Required: $2000+
  • Monitoring: 1-2 times per day

Example 3: Aggressive Trading (Higher Risk)

Best for: Advanced users, large capital ($10000+), volatile markets

# API Configuration
GATE_API_KEY=your_api_key_here
GATE_API_SECRET=your_api_secret_here

# Trading Configuration
TRADING_PAIRS=BTC_USDT,ETH_USDT,ADA_USDT  # Multiple pairs
ORDER_LAYERS=5                             # More layers
LAYER_SPACING=0.0005                       # 0.05% spacing (tight)
BASE_ORDER_SIZE=0.05                       # Larger order size
MIN_SPREAD=0.0008                          # 0.08% minimum (tight)
MAX_SPREAD=0.03                            # 3% maximum
ORDER_REFRESH_INTERVAL=5                   # Frequent updates

# Risk Configuration
MAX_POSITION_SIZE=0.02                     # 2% per trade (aggressive)
MAX_INVENTORY_SKEW=0.30                    # ±30% max deviation
DAILY_LOSS_LIMIT=-0.05                     # -5% daily loss limit
VOLATILITY_THRESHOLD=0.05                  # 5% volatility pause
MAX_DRAWDOWN=-0.10                         # -10% max drawdown

# Logging
LOG_LEVEL=DEBUG                            # Detailed logging

# Paper Trading (ALWAYS test first!)
PAPER_TRADING=true

Expected Performance:

  • Daily ROI: 0.2% - 0.5%
  • Risk Level: High
  • Capital Required: $10000+
  • Monitoring: Continuous (recommended)

⚠️ Warning: Aggressive settings require constant monitoring and experience!


Example 4: High-Frequency Trading (Expert Only)

Best for: Experts, very large capital ($50000+), stable infrastructure

# API Configuration
GATE_API_KEY=your_api_key_here
GATE_API_SECRET=your_api_secret_here

# Trading Configuration
TRADING_PAIRS=BTC_USDT                     # Focus on one liquid pair
ORDER_LAYERS=10                            # Maximum layers
LAYER_SPACING=0.0002                       # 0.02% spacing (very tight)
BASE_ORDER_SIZE=0.1                        # Large order size
MIN_SPREAD=0.0005                          # 0.05% minimum (very tight)
MAX_SPREAD=0.01                            # 1% maximum
ORDER_REFRESH_INTERVAL=2                   # Very frequent updates

# Risk Configuration
MAX_POSITION_SIZE=0.03                     # 3% per trade
MAX_INVENTORY_SKEW=0.40                    # ±40% max deviation
DAILY_LOSS_LIMIT=-0.10                     # -10% daily loss limit
VOLATILITY_THRESHOLD=0.08                  # 8% volatility pause
MAX_DRAWDOWN=-0.15                         # -15% max drawdown

# Logging
LOG_LEVEL=WARNING                          # Minimal logging for performance

# Paper Trading
PAPER_TRADING=false                        # Live trading only after extensive testing

Expected Performance:

  • Daily ROI: 0.3% - 1.0%
  • Risk Level: Very High
  • Capital Required: $50000+
  • Monitoring: Automated systems required

⚠️ Critical: Requires dedicated infrastructure, monitoring, and risk management!


🎮 Operational Procedures

Starting the Bot

Paper Trading Mode (Safe - Recommended for First Time)

# 1. Activate virtual environment (if using one)
# Windows:
.\venv\Scripts\Activate.ps1
# Linux/macOS:
source venv/bin/activate

# 2. Verify configuration
python main.py --test

# 3. Start the bot
python run_bot.py

# Expected output:
# 🚀 Gate.io Market Maker Bot - Quick Start
# ✅ All required packages are installed
# 🎯 Starting Market Maker Bot...
# 📊 Mode: Paper Trading
# 🎯 Market Maker Bot is now RUNNING!

Live Trading Mode (After Thorough Testing)

# 1. Ensure paper trading is disabled in .env
# PAPER_TRADING=false

# 2. Verify API credentials are set
# GATE_API_KEY=your_real_key
# GATE_API_SECRET=your_real_secret

# 3. Test configuration
python main.py --test

# 4. Start with --confirm flag (safety check)
python main.py

# 5. Monitor logs closely
tail -f logs/marketmaker.log

Pre-Flight Checklist for Live Trading:

  • Tested in paper trading for at least 24 hours
  • Reviewed all logs for errors
  • Verified API credentials
  • Set appropriate risk limits
  • Started with minimal capital
  • Have monitoring system in place
  • Understand emergency shutdown procedure

Monitoring the Bot

Real-Time Monitoring

# Watch main log (Linux/macOS)
tail -f logs/marketmaker.log

# Watch main log (Windows PowerShell)
Get-Content logs\marketmaker.log -Wait -Tail 50

# Watch trade log
tail -f logs/trades.log

# Watch specific errors
tail -f logs/marketmaker.log | grep ERROR

Check Bot Status

# Get current status
python main.py --status

# Expected output:
# 📊 Bot Status:
# Running: YES
# Paper Trading: YES
# Trading Pairs: BTC_USDT, ETH_USDT
# Uptime: 3600.5 seconds

Monitor Performance Metrics

Check the logs for:

  • Order Fill Rate: Should be >70%
  • Spread Captured: Average spread earned per trade
  • Inventory Skew: Should stay within limits
  • Daily P&L: Track profit/loss
  • Error Rate: Should be minimal

Stopping the Bot

Graceful Shutdown (Recommended)

# Press CTRL+C in the terminal running the bot
# The bot will:
# 1. Cancel all open orders
# 2. Save current state
# 3. Stop all components
# 4. Exit cleanly

# Expected output:
# ⚠️  Keyboard interrupt received
# 🛑 Stopping Market Maker Bot...
# ✅ Trading strategy stopped
# ✅ Circuit breakers stopped
# ✅ Risk manager stopped
# ⏱️  Total uptime: 3600.0 seconds
# ✅ Market Maker Bot stopped successfully

Emergency Stop

If the bot is unresponsive:

# Find the process
# Linux/macOS:
ps aux | grep python | grep main.py

# Windows:
Get-Process python

# Kill the process
# Linux/macOS:
kill -TERM <process_id>

# Windows:
Stop-Process -Name python -Force

# Check saved state
cat logs/bot_state.json

Restarting the Bot

# 1. Check logs for any errors from previous run
cat logs/marketmaker.log | tail -100

# 2. Review saved state (if available)
cat logs/bot_state.json

# 3. Clear old state (optional - if you want fresh start)
rm logs/bot_state.json

# 4. Restart the bot
python run_bot.py

# The bot will:
# - Load previous state (if available)
# - Resume from last known position
# - Reconnect to market data
# - Place new orders

Handling Emergency Situations

Scenario 1: Rapid Market Movement

Symptoms: Large price swings, high volatility

Action:

  1. Bot should automatically pause (circuit breaker)
  2. Monitor logs for circuit breaker activation
  3. Wait for market to stabilize
  4. Bot will resume automatically after cooldown

Manual Override:

# Stop the bot
CTRL+C

# Wait for market to stabilize
# Restart with wider spreads
# Edit .env: MIN_SPREAD=0.005, MAX_SPREAD=0.10
python run_bot.py

Scenario 2: API Connection Loss

Symptoms: WebSocket disconnection, API errors

Action:

  1. Bot will automatically attempt reconnection
  2. Falls back to REST API if WebSocket fails
  3. Monitor logs for reconnection attempts

Manual Override:

# Check internet connection
ping api.gateio.ws

# Restart the bot
CTRL+C
python run_bot.py

Scenario 3: Daily Loss Limit Reached

Symptoms: Bot automatically shuts down

Action:

  1. Review logs to understand what happened
  2. Analyze trades in logs/trades.log
  3. Adjust risk parameters if needed
  4. Wait until next day to restart (daily limit resets)

Review:

# Check final P&L
grep "Daily P&L" logs/marketmaker.log | tail -1

# Review all trades
cat logs/trades.log

# Analyze what went wrong
# - Was spread too tight?
# - Was market too volatile?
# - Were position sizes too large?

Scenario 4: Inventory Limit Breach

Symptoms: Trading paused, rebalancing needed

Action:

  1. Bot will pause new orders
  2. Generate rebalancing recommendation
  3. Review recommendation in logs
  4. Bot will attempt automatic rebalancing

Manual Rebalancing:

# Check current inventory
python main.py --status

# If needed, manually rebalance on Gate.io
# Then restart bot
python run_bot.py

📊 Monitoring & Logs

Log Files

The bot creates several log files in the logs/ directory:

File Purpose Rotation
marketmaker.log Main application log 10MB, 5 backups
trades.log Trade execution log 10MB, 5 backups
bot_state.json Saved state (for recovery) Overwritten on shutdown

Log Levels and What They Mean

DEBUG (Most Verbose):

2025-01-15 10:30:45 DEBUG Updated orders for BTC_USDT
2025-01-15 10:30:45 DEBUG Spread calculated: 0.15%

Use for: Development, troubleshooting

INFO (Recommended):

2025-01-15 10:30:00 INFO Market maker bot started successfully
2025-01-15 10:30:15 INFO Order placed: buy 0.001 BTC at $50000

Use for: Normal operation

WARNING:

2025-01-15 10:35:00 WARNING High volatility detected: 3.5%
2025-01-15 10:35:01 WARNING Circuit breaker triggered for BTC_USDT

Use for: Important events that need attention

ERROR:

2025-01-15 10:40:00 ERROR API connection failed: timeout
2025-01-15 10:40:01 ERROR Failed to place order: insufficient balance

Use for: Problems that need immediate attention

Key Metrics to Monitor

1. Order Fill Rate

# Check fill rate in logs
grep "fill_rate" logs/marketmaker.log | tail -1

# Target: >70%
# If lower: Spreads may be too wide

2. Spread Captured

# Check average spread
grep "avg_spread_captured" logs/marketmaker.log | tail -1

# Target: >0.1%
# If lower: Market may be too competitive

3. Inventory Skew

# Check current skew
grep "inventory_skew" logs/marketmaker.log | tail -1

# Target: <±15%
# If higher: Rebalancing needed

4. Daily P&L

# Check daily profit/loss
grep "daily_pnl" logs/marketmaker.log | tail -1

# Target: Positive
# If negative: Review strategy parameters

5. Error Rate

# Count errors in last hour
grep ERROR logs/marketmaker.log | grep "$(date +%Y-%m-%d)" | wc -l

# Target: <10 per hour
# If higher: Investigate root cause

Setting Up Monitoring Alerts

Option 1: Simple Email Alerts (Linux/macOS)

# Create monitoring script
cat > monitor_bot.sh << 'EOF'
#!/bin/bash
LOG_FILE="logs/marketmaker.log"
ERROR_COUNT=$(grep ERROR $LOG_FILE | grep "$(date +%Y-%m-%d)" | wc -l)

if [ $ERROR_COUNT -gt 50 ]; then
    echo "High error count: $ERROR_COUNT" | mail -s "Bot Alert" your@email.com
fi
EOF

# Make executable
chmod +x monitor_bot.sh

# Add to crontab (run every hour)
crontab -e
# Add: 0 * * * * /path/to/monitor_bot.sh

Option 2: Telegram Notifications

# Add to your monitoring script
import requests

def send_telegram_alert(message):
    bot_token = "YOUR_BOT_TOKEN"
    chat_id = "YOUR_CHAT_ID"
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    requests.post(url, data={"chat_id": chat_id, "text": message})

# Use in your code
send_telegram_alert("⚠️ Daily loss limit approaching!")

🔧 Troubleshooting

Common Issues and Solutions

Issue 1: Import Errors

Error:

ModuleNotFoundError: No module named 'gate_api'

Solution:

# Ensure virtual environment is activated
# Windows:
.\venv\Scripts\Activate.ps1
# Linux/macOS:
source venv/bin/activate

# Reinstall dependencies
pip install -r requirements.txt

# Verify installation
python test_imports.py

Issue 2: API Connection Failures

Error:

ERROR API connection failed: 401 Unauthorized

Solutions:

A. Invalid API Credentials:

# Check .env file
cat .env | grep GATE_API

# Verify credentials on Gate.io:
# 1. Go to https://www.gate.io/myaccount/apiv4keys
# 2. Check if API key is active
# 3. Verify IP whitelist (if enabled)
# 4. Ensure API has spot trading permissions

B. Rate Limiting:

# Check for rate limit errors
grep "rate limit" logs/marketmaker.log

# Solution: Increase ORDER_REFRESH_INTERVAL in .env
# From: ORDER_REFRESH_INTERVAL=5
# To: ORDER_REFRESH_INTERVAL=15

C. Network Issues:

# Test connection
ping api.gateio.ws

# Test API endpoint
curl https://api.gateio.ws/api/v4/spot/currencies

# Check firewall/proxy settings

Issue 3: WebSocket Disconnections

Error:

WARNING WebSocket connection lost
INFO Attempting reconnection...

Solutions:

A. Temporary Network Issue (Normal):

  • Bot will automatically reconnect
  • Falls back to REST API
  • No action needed if reconnection succeeds

B. Persistent Disconnections:

# Check network stability
ping -c 100 api.gateio.ws

# Check for packet loss
# If >5% packet loss, investigate network

# Restart bot with REST API only (temporary)
# Edit market_data.py to disable WebSocket

Issue 4: Configuration Validation Errors

Error:

ValueError: min_spread must be less than max_spread

Solution:

# Check .env file for invalid values
cat .env

# Common issues:
# - MIN_SPREAD >= MAX_SPREAD
# - Negative values for positive parameters
# - Invalid trading pair format

# Fix example:
# Wrong: MIN_SPREAD=0.02, MAX_SPREAD=0.01
# Right: MIN_SPREAD=0.001, MAX_SPREAD=0.02

Issue 5: Insufficient Balance

Error:

ERROR Failed to place order: insufficient balance

Solutions:

A. Check Balances:

# Log into Gate.io
# Check Spot Account balances
# Ensure you have both base and quote currency

B. Reduce Order Sizes:

# In .env, reduce BASE_ORDER_SIZE
# From: BASE_ORDER_SIZE=0.1
# To: BASE_ORDER_SIZE=0.01

C. Reduce Order Layers:

# In .env, reduce ORDER_LAYERS
# From: ORDER_LAYERS=5
# To: ORDER_LAYERS=2

Issue 6: High Memory Usage

Symptoms: Bot using >1GB RAM

Solutions:

A. Reduce Data History:

# Edit market_data.py
# Reduce maxlen in deque
# From: deque(maxlen=1000)
# To: deque(maxlen=100)

B. Reduce Log Level:

# In .env
# From: LOG_LEVEL=DEBUG
# To: LOG_LEVEL=INFO

C. Restart Periodically:

# Add to crontab (restart daily at 3 AM)
0 3 * * * /path/to/restart_bot.sh

Issue 7: Orders Not Filling

Symptoms: Orders placed but never filled

Causes & Solutions:

A. Spreads Too Wide:

# Reduce MIN_SPREAD in .env
# From: MIN_SPREAD=0.005
# To: MIN_SPREAD=0.001

B. Prices Not Competitive:

# Check current market spread
# Log into Gate.io
# Compare your orders with order book
# Adjust LAYER_SPACING if needed

C. Order Size Too Large:

# Reduce BASE_ORDER_SIZE
# From: BASE_ORDER_SIZE=1.0
# To: BASE_ORDER_SIZE=0.1

Issue 8: Bot Stops Unexpectedly

Check Logs:

# Find the error
tail -100 logs/marketmaker.log | grep ERROR

# Common causes:
# 1. Daily loss limit reached
# 2. Inventory limit breached
# 3. Circuit breaker triggered
# 4. System error

Solutions by Cause:

1. Daily Loss Limit:

# Review trades
cat logs/trades.log

# Adjust risk parameters
# Increase DAILY_LOSS_LIMIT (carefully!)
# Or improve strategy parameters

2. Inventory Limit:

# Check inventory skew
grep "inventory_skew" logs/marketmaker.log | tail -1

# Manually rebalance on Gate.io
# Or increase MAX_INVENTORY_SKEW

3. Circuit Breaker:

# Check volatility
grep "circuit breaker" logs/marketmaker.log

# Wait for market to stabilize
# Or increase VOLATILITY_THRESHOLD

Getting Help

If you can't resolve an issue:

  1. Check Documentation:

    • README.md (this file)
    • LIVE_API_TEST_REPORT.md
    • QUICK_START_WINDOWS.md
  2. Review Logs:

    • logs/marketmaker.log
    • logs/trades.log
  3. Run Diagnostics:

    python main.py --test
    python test_imports.py
  4. Search Issues:

    • Check GitHub issues
    • Search for error message
  5. Create Issue:

    • Include error message
    • Include relevant logs
    • Include configuration (remove API keys!)
    • Include steps to reproduce

🛡️ Safety Guidelines

Understanding Paper Trading vs Live Trading

Paper Trading (Simulation Mode)

What it is:

  • Simulated trading with fake money
  • No real orders placed on exchange
  • No real profit or loss
  • Safe for testing and learning

How it works:

  • Bot generates mock market data
  • Simulates order placement and fills
  • Tracks paper balances
  • Logs all activities as if real

When to use:

  • ✅ First time running the bot
  • ✅ Testing new configurations
  • ✅ Learning how the bot works
  • ✅ Developing new features
  • ✅ After major code changes

Configuration:

PAPER_TRADING=true  # Always start here!

Live Trading (Real Money)

What it is:

  • Real trading with real money
  • Actual orders placed on Gate.io
  • Real profit and loss
  • Requires careful monitoring

How it works:

  • Bot connects to Gate.io API
  • Places real limit orders
  • Executes real trades
  • Manages real balances

When to use:

  • ⚠️ After extensive paper trading (24+ hours)
  • ⚠️ After reviewing all logs
  • ⚠️ With proper risk management
  • ⚠️ With capital you can afford to lose
  • ⚠️ With continuous monitoring

Configuration:

PAPER_TRADING=false  # Only after thorough testing!
GATE_API_KEY=your_real_key
GATE_API_SECRET=your_real_secret

Risk Management Parameters Explained

1. Daily Loss Limit

What it does: Automatically stops the bot if daily losses exceed threshold

Example:

DAILY_LOSS_LIMIT=-0.02  # -2%

Meaning: If you lose 2% of your capital in one day, bot stops automatically

Recommendations:

  • Beginner: -0.01 (-1%)
  • Intermediate: -0.02 (-2%)
  • Advanced: -0.05 (-5%)

Why it matters: Prevents catastrophic losses during market crashes or bot malfunctions


2. Position Size Limit

What it does: Limits how much capital is used per trade

Example:

MAX_POSITION_SIZE=0.01  # 1%

Meaning: Each order uses maximum 1% of your total portfolio value

Recommendations:

  • Beginner: 0.005 (0.5%)
  • Intermediate: 0.01 (1%)
  • Advanced: 0.02 (2%)

Why it matters: Prevents over-concentration in single trades


3. Inventory Skew Limit

What it does: Prevents imbalanced inventory (too much base or quote currency)

Example:

MAX_INVENTORY_SKEW=0.20  # ±20%

Meaning: Bot maintains 50/50 balance, allows ±20% deviation

Recommendations:

  • Beginner: 0.10 (±10%)
  • Intermediate: 0.20 (±20%)
  • Advanced: 0.30 (±30%)

Why it matters: Prevents directional exposure (you're market making, not speculating!)


4. Volatility Circuit Breaker

What it does: Pauses trading during extreme volatility

Example:

VOLATILITY_THRESHOLD=0.03  # 3%

Meaning: If 5-minute volatility exceeds 3%, bot pauses

Recommendations:

  • Stable markets: 0.02 (2%)
  • Normal markets: 0.03 (3%)
  • Volatile markets: 0.05 (5%)

Why it matters: Protects against flash crashes and extreme price movements


Safe Testing Procedure

Phase 1: Paper Trading (1-3 days)

# Day 1: Initial Testing
1. Set PAPER_TRADING=true
2. Start with conservative settings
3. Run for 24 hours
4. Review logs every 4 hours
5. Check for errors

# Day 2: Stress Testing
1. Increase order layers
2. Reduce spreads slightly
3. Monitor performance
4. Test emergency shutdown (CTRL+C)
5. Verify state recovery

# Day 3: Final Validation
1. Test with target configuration
2. Run for 24 hours uninterrupted
3. Analyze all metrics
4. Verify risk limits work
5. Document any issues

Phase 2: Live Trading with Minimal Capital (1 week)

# Week 1: Minimal Capital Test
1. Set PAPER_TRADING=false
2. Deposit minimal capital ($100-$500)
3. Use conservative settings
4. Monitor continuously for first 24 hours
5. Check logs 3-4 times daily
6. Verify all trades are correct
7. Test emergency stop in live mode

Phase 3: Scale Up Gradually (1 month)

# Month 1: Gradual Scaling
Week 1: $500 capital
Week 2: $1000 capital (if successful)
Week 3: $2000 capital (if successful)
Week 4: $5000 capital (if successful)

# Monitor:
- Daily P&L
- Fill rates
- Error rates
- Risk metrics

Capital Allocation Recommendations

Beginner ($500 - $2000)

Total Capital: $1000
├── BTC_USDT: $500 (50%)
│   ├── BTC: $250
│   └── USDT: $250
└── ETH_USDT: $500 (50%)
    ├── ETH: $250
    └── USDT: $250

Configuration:
- ORDER_LAYERS=2
- BASE_ORDER_SIZE=0.001 BTC / 0.01 ETH
- MAX_POSITION_SIZE=0.005 (0.5%)

Intermediate ($2000 - $10000)

Total Capital: $5000
├── BTC_USDT: $2500 (50%)
│   ├── BTC: $1250
│   └── USDT: $1250
├── ETH_USDT: $2000 (40%)
│   ├── ETH: $1000
│   └── USDT: $1000
└── Reserve: $500 (10%)

Configuration:
- ORDER_LAYERS=3
- BASE_ORDER_SIZE=0.01 BTC / 0.1 ETH
- MAX_POSITION_SIZE=0.01 (1%)

Advanced ($10000+)

Total Capital: $20000
├── BTC_USDT: $8000 (40%)
├── ETH_USDT: $6000 (30%)
├── ADA_USDT: $4000 (20%)
└── Reserve: $2000 (10%)

Configuration:
- ORDER_LAYERS=5
- BASE_ORDER_SIZE=0.05 BTC / 0.5 ETH
- MAX_POSITION_SIZE=0.02 (2%)

When to Use Emergency Stop

Immediate Emergency Stop Required:

  1. Unexpected Behavior:

    • Bot placing orders at wrong prices
    • Orders much larger than configured
    • Rapid balance depletion
  2. Market Events:

    • Flash crash (>20% drop in minutes)
    • Exchange issues reported
    • Regulatory news affecting trading
  3. Technical Issues:

    • API errors increasing rapidly
    • WebSocket constantly disconnecting
    • System running out of memory
  4. Risk Limit Breaches:

    • Daily loss approaching limit
    • Inventory severely imbalanced
    • Multiple circuit breakers triggered

How to Emergency Stop:

# Method 1: Graceful (Preferred)
CTRL+C in terminal

# Method 2: Force Stop
# Find process ID
ps aux | grep python | grep main.py

# Kill process
kill -TERM <process_id>

# Method 3: Nuclear Option (Last Resort)
# Windows:
Stop-Process -Name python -Force

# Linux:
killall -9 python

After Emergency Stop:

  1. Don't Panic: Take a breath
  2. Review Logs: Understand what happened
  3. Check Exchange: Verify all orders cancelled
  4. Analyze Trades: Review trades.log
  5. Identify Cause: Find root issue
  6. Fix Problem: Adjust configuration
  7. Test in Paper Mode: Before restarting live

⚡ Performance Tuning

Optimizing for Different Goals

Goal 1: Maximum Profit

Strategy: Tight spreads, frequent trading

MIN_SPREAD=0.0008          # Very tight
MAX_SPREAD=0.01
ORDER_LAYERS=7             # Many layers
LAYER_SPACING=0.0003       # Close together
ORDER_REFRESH_INTERVAL=3   # Frequent updates

Pros: Higher profit potential Cons: Higher risk, more monitoring needed Best for: Experienced traders, stable markets


Goal 2: Maximum Safety

Strategy: Wide spreads, conservative sizing

MIN_SPREAD=0.003           # Wide
MAX_SPREAD=0.05
ORDER_LAYERS=2             # Few layers
LAYER_SPACING=0.005        # Far apart
ORDER_REFRESH_INTERVAL=30  # Infrequent updates
MAX_POSITION_SIZE=0.003    # Very small
DAILY_LOSS_LIMIT=-0.005    # Strict limit

Pros: Lower risk, less monitoring Cons: Lower profit potential Best for: Beginners, volatile markets


Goal 3: Balanced Approach

Strategy: Moderate spreads, balanced risk

MIN_SPREAD=0.001           # Normal
MAX_SPREAD=0.02
ORDER_LAYERS=3             # Standard
LAYER_SPACING=0.001        # Normal spacing
ORDER_REFRESH_INTERVAL=10  # Standard updates
MAX_POSITION_SIZE=0.01     # Moderate
DAILY_LOSS_LIMIT=-0.02     # Reasonable

Pros: Good balance of risk/reward Cons: Requires regular monitoring Best for: Most users, normal markets


Market-Specific Tuning

High Liquidity Markets (BTC_USDT, ETH_USDT)

# Can use tighter spreads
MIN_SPREAD=0.0008
ORDER_LAYERS=5
LAYER_SPACING=0.0005

# More frequent updates
ORDER_REFRESH_INTERVAL=5

Low Liquidity Markets (Altcoins)

# Need wider spreads
MIN_SPREAD=0.005
ORDER_LAYERS=2
LAYER_SPACING=0.01

# Less frequent updates
ORDER_REFRESH_INTERVAL=30

Volatile Markets

# Wider spreads for protection
MIN_SPREAD=0.002
MAX_SPREAD=0.05

# Smaller positions
MAX_POSITION_SIZE=0.005

# Stricter circuit breakers
VOLATILITY_THRESHOLD=0.02

Stable Markets

# Tighter spreads for more trades
MIN_SPREAD=0.0008
MAX_SPREAD=0.015

# Larger positions
MAX_POSITION_SIZE=0.015

# Relaxed circuit breakers
VOLATILITY_THRESHOLD=0.05

❓ FAQ

General Questions

Q: Is this bot profitable? A: Profitability depends on market conditions, configuration, and capital. In normal markets, expect 0.1%-0.3% daily ROI. Past performance doesn't guarantee future results.

Q: How much capital do I need? A: Minimum $500 recommended. Optimal: $2000-$10000. More capital = better diversification and risk management.

Q: Do I need programming knowledge? A: No. Basic configuration editing is enough. However, understanding Python helps for customization.

Q: Can I run multiple bots? A: Yes, but each needs separate API credentials and configuration. Not recommended for beginners.

Q: Does it work 24/7? A: Yes, designed for continuous operation. Recommended to run on a VPS or dedicated machine.


Technical Questions

Q: Why use paper trading first? A: To test configuration, understand bot behavior, and verify everything works before risking real money.

Q: How often should I check the bot? A: Paper trading: Daily. Live trading: 2-3 times daily minimum. More frequently when starting.

Q: What happens if my internet disconnects? A: Bot will attempt to reconnect. If it can't, it will stop. Orders remain on exchange until manually cancelled.

Q: Can I change configuration while bot is running? A: No. Stop the bot, edit .env, then restart.

Q: How do I update the bot? A: Pull latest code, review changes, test in paper mode, then deploy.


Trading Questions

Q: What's the difference between order layers? A: More layers = more orders at different prices = better liquidity provision but more capital needed.

Q: Why is my fill rate low? A: Spreads may be too wide. Try reducing MIN_SPREAD slightly.

Q: Why is inventory imbalanced? A: Market direction. Bot will automatically rebalance when threshold is reached.

Q: Can I trade multiple pairs? A: Yes. Add to TRADING_PAIRS: BTC_USDT,ETH_USDT,ADA_USDT

Q: What fees does Gate.io charge? A: Maker: -0.015% (rebate), Taker: 0.05%. Bot uses maker orders primarily.


Risk Questions

Q: Can I lose money? A: Yes. All trading involves risk. Use proper risk management and only invest what you can afford to lose.

Q: What's the maximum I can lose in a day? A: Limited by DAILY_LOSS_LIMIT. Set to -0.02 = maximum 2% daily loss before auto-shutdown.

Q: Is my API key safe? A: Yes, if stored in .env file and not committed to version control. Never share your API secret.

Q: What if the bot malfunctions? A: Risk limits will trigger emergency shutdown. Always monitor logs and set conservative limits.

Q: Should I use all my capital? A: No. Keep 10-20% in reserve. Never invest more than you can afford to lose.


⚠️ Risk Warning

Important Disclaimers

CRYPTOCURRENCY TRADING INVOLVES SIGNIFICANT RISK

  • ❌ This bot is provided "AS-IS" without any warranties
  • ❌ Past performance does not guarantee future results
  • ❌ You can lose some or all of your invested capital
  • ❌ Only invest money you can afford to lose completely
  • ❌ The developers are not responsible for any losses
  • ❌ This is not financial advice

Risks You Should Understand

  1. Market Risk: Cryptocurrency prices are highly volatile
  2. Technical Risk: Software bugs, API failures, connectivity issues
  3. Exchange Risk: Exchange downtime, hacks, regulatory issues
  4. Configuration Risk: Incorrect settings can lead to losses
  5. Liquidity Risk: Unable to exit positions quickly
  6. Regulatory Risk: Changing regulations may affect trading

Best Practices

DO:

  • Start with paper trading
  • Use conservative settings initially
  • Monitor the bot regularly
  • Keep detailed records
  • Use proper risk management
  • Test thoroughly before live trading
  • Keep software updated
  • Secure your API credentials

DON'T:

  • Invest more than you can afford to lose
  • Use maximum leverage or position sizes
  • Ignore warning signs or errors
  • Share your API credentials
  • Run without monitoring
  • Skip paper trading phase
  • Panic during normal market volatility

📄 License

MIT License - See LICENSE file for details


🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Test thoroughly
  4. Submit a pull request

📞 Support

  • Documentation: This README and other .md files
  • Issues: GitHub Issues
  • Logs: Check logs/ directory first
  • Testing: Run python main.py --test

🙏 Acknowledgments

  • Gate.io for providing the API
  • Python community for excellent libraries
  • Contributors and testers

Remember: Always test in paper trading mode first. Never invest more than you can afford to lose. Trading cryptocurrencies carries significant risk.

Happy Trading! 🚀


Last Updated: January 2025 Version: 1.0.0 Status: Production Ready

About

Gate.io Market Maker Bot - A sophisticated automated market making bot for Gate.io spot trading, designed to provide liquidity while managing risk and maximizing profitability.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages