Skip to content

About

Grid trading bot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Cryptocurrency Grid Trading System

A sophisticated grid trading system designed exclusively for cryptocurrency and digital assets trading using Alpaca's paper trading environment.

Important Notice

This system is designed exclusively for cryptocurrency and digital assets trading only. All trading operations are conducted through Alpaca's paper trading environment for safety and testing purposes.

Features

  • Multiple Grid Strategies: Static, Trailing, and Hybrid grid algorithms
  • Crypto-Only Trading: Built specifically for cryptocurrency pairs
  • Real-time Market Data: Live crypto price feeds and historical data
  • Risk Management: Comprehensive risk controls and monitoring
  • Paper Trading: Safe testing environment using Alpaca's paper trading
  • Performance Analytics: Detailed statistics and performance tracking
  • Simulation Engine: Backtest strategies before live deployment

Usage

Installation

# Clone the repository
git clone <repository-url>
cd grid_trader

# Install dependencies using uv
uv sync

Environment Setup

# Copy environment template
cp .env.example .env

# Edit .env with your Alpaca paper trading credentials
ALPACA_API_KEY=your_alpaca_api_key_here
ALPACA_SECRET_KEY=your_alpaca_secret_key_here
ALPACA_BASE_URL=https://paper-api.alpaca.markets

Command Line Usage

Simulation Commands

# Basic strategy simulation
uv run python main.py simulate --base-price 50000 --steps 1000 --volatility 5

# Test with trend events
uv run python main.py trend-test --steps 1500 --volatility 7 --chart

# Available simulation arguments:
--base-price PRICE      Starting price (default: 50000)
--trend-strength TREND  Trend strength from -10 to 10 (default: 0)
--volatility VOL        Volatility from 1 to 10 (default: 5)
--sensitivity SENS      Grid sensitivity from 1 to 10 (default: 5)
--steps STEPS          Number of simulation steps (default: 1000)
--chart                Generate comparison chart

Live Crypto Trading Commands

# Start live crypto grid trading (paper trading)
uv run python main.py crypto-live --symbol BTC/USD --strategy hybrid

# Custom configuration example
uv run python main.py crypto-live \
  --symbol ETH/USD \
  --strategy trailing \
  --position-size 500 \
  --grid-levels 15 \
  --grid-spacing 0.015 \
  --max-position 25000

# Available crypto-live arguments:
--symbol SYMBOL         Crypto symbol (default: BTC/USD)
--strategy STRATEGY     Grid strategy: static, trailing, hybrid (default: hybrid)
--position-size SIZE    Position size per grid level in USD (default: 1000)
--grid-levels LEVELS    Number of grid levels (default: 10)
--grid-spacing SPACING  Grid spacing as decimal (default: 0.01 = 1%)
--max-position MAX      Maximum position size (default: 50000)
--update-interval SEC   Price update interval in seconds (default: 60)

Risk Management Commands

# Check current cryptocurrency risk exposure
uv run python main.py crypto-risk

Supported Cryptocurrency Pairs

  • BTC/USD (Bitcoin)
  • ETH/USD (Ethereum)
  • SOL/USD (Solana)
  • XRP/USD (Ripple)

Architecture

High-Level System Architecture

+---------------------------------------------------------------+
|                     Grid Trading System                      |
+---------------------------------------------------------------+
|                                                               |
|  +---------------+    +---------------+    +-------------+   |
|  | CLI Interface |    | Web Interface |    | API Gateway |   |
|  |   (main.py)   |    |   (Optional)  |    |  (Future)   |   |
|  +---------------+    +---------------+    +-------------+   |
|           |                   |                    |         |
|           +-------------------+--------------------+         |
|                               |                              |
+---------------------------------------------------------------+
|                        Core Engine                           |
|                                                               |
|  +---------------+    +---------------+    +-------------+   |
|  |  Simulation   |    | Live Trading  |    |    Risk     |   |
|  |    Engine     |    |    Engine     |    |   Manager   |   |
|  |               |    |               |    |             |   |
|  | - Backtesting |    | - Real-time   |    | - Position  |   |
|  | - Performance |    | - Order Mgmt  |    |   Limits    |   |
|  | - Analytics   |    | - Portfolio   |    | - Exposure  |   |
|  +---------------+    +---------------+    +-------------+   |
|           |                   |                    |         |
+---------------------------------------------------------------+
|                      Strategy Layer                          |
|                                                               |
|  +---------------+    +---------------+    +-------------+   |
|  |  Static Grid  |    | Trailing Grid |    | Hybrid Grid |   |
|  |               |    |               |    |             |   |
|  | - Fixed levels|    | - Price-follow|    | - Adaptive  |   |
|  | - Mean revert |    | - Trend captur|    | - Intellige |   |
|  | - Range-bound |    | - Dynamic shif|    | - Trend-awa |   |
|  +---------------+    +---------------+    +-------------+   |
|           |                   |                    |         |
+---------------------------------------------------------------+
|                      Data & Broker Layer                     |
|                                                               |
|  +---------------+    +---------------+    +-------------+   |
|  |  Market Data  |    | Order Executi |    |  Portfolio  |   |
|  |   Provider    |    |    Manager    |    |   Tracking  |   |
|  |               |    |               |    |             |   |
|  | - Live feeds  |    | - Order route |    | - Positions |   |
|  | - Historical  |    | - Status trac |    | - P&L calc  |   |
|  | - Price histo |    | - Fill handli |    | - Reporting |   |
|  +---------------+    +---------------+    +-------------+   |
|           |                   |                    |         |
+---------------------------------------------------------------+
|                        Broker APIs                           |
|                                                               |
|  +-----------------------------------------------------------+ |
|  |                    Alpaca API                            | |
|  |                                                           | |
|  |  - Paper Trading Environment (Crypto Only)               | |
|  |  - Real-time Crypto Data Streams                        | |
|  |  - Order Management & Execution                         | |
|  |  - Portfolio & Account Information                      | |
|  +-----------------------------------------------------------+ |
+---------------------------------------------------------------+

Component Relationships

Strategy Selection -> Grid Configuration -> Market Data -> Order Management -> Risk Control
       |                    |                 |              |              |
   Algorithm         Grid Parameters    Price Updates    Order Execution   Position Limits
   Implementation    - Levels          - Real-time      - Buy/Sell       - Exposure Check
                     - Spacing         - Historical     - Limit/Market   - Daily Limits
                     - Center          - Validation     - Status Track   - Stop Loss

Alpaca Integration

Overview

The system integrates with Alpaca's paper trading environment specifically for cryptocurrency trading. All operations are conducted in a safe, simulated environment using real market data.

Key Integration Components

1. Authentication & Configuration

# src/grid_trader/alpaca_config.py
class AlpacaClientManager:
    - TradingClient (paper trading only)
    - CryptoHistoricalDataClient  
    - CryptoDataStream (live feeds)

2. Symbol Format Handling

# Display Format: BTC/USD -> API Format: BTCUSD
def _normalize_crypto_symbol(symbol: str) -> str:
    return symbol.replace("/", "")  # "BTC/USD" -> "BTCUSD"

def _display_crypto_symbol(api_symbol: str) -> str:
    return f"{api_symbol[:3]}/{api_symbol[3:]}"  # "BTCUSD" -> "BTC/USD"

3. Order Management

# Crypto orders use notional (USD amount) instead of quantity
request = LimitOrderRequest(
    symbol="BTCUSD",           # Normalized symbol
    notional=1000.0,           # USD amount for crypto
    side=OrderSide.BUY,
    time_in_force=TimeInForce.GTC,  # GTC for crypto (not DAY)
    limit_price=45000.0
)

4. Market Data Integration

# Real-time crypto price feeds
async def start_live_data(symbols: List[str]):
    stream = self.client_manager.crypto_stream
    # Subscribe to normalized symbols and convert back for display
    api_symbols = [self._normalize_crypto_symbol(s) for s in symbols]
    stream.subscribe_quotes(quote_handler, *api_symbols)

5. Risk Management Integration

  • Position tracking through Alpaca portfolio API
  • Real-time exposure monitoring
  • Automated risk limit enforcement
  • Paper trading safety controls

Configuration

# Required environment variables
ALPACA_API_KEY=your_paper_trading_key
ALPACA_SECRET_KEY=your_paper_trading_secret  
ALPACA_BASE_URL=https://paper-api.alpaca.markets

# Trading configuration
DEFAULT_SYMBOL=BTC/USD
DEFAULT_POSITION_SIZE=1000
MAX_POSITION_SIZE=50000

Algorithms

1. Static Grid Strategy (src/grid_trader/static_strategy.py)

Concept: Fixed grid levels that never move, ideal for range-bound markets.

Implementation:

class StaticGridStrategy(BaseGridStrategy):
    def update_grid(self, current_price: float, price_history: List[float], time: int):
        pass  # Grid never adjusts

Characteristics:

  • Grid levels remain constant regardless of price movement
  • Best performance in sideways/ranging markets
  • Can be "left behind" in strong trending markets
  • Simple and predictable behavior
  • Lower maintenance overhead

Use Cases:

  • Stable cryptocurrency pairs with predictable ranges
  • Markets with high mean reversion tendency
  • Conservative trading approach
  • When avoiding trend-following risks

2. Trailing Grid Strategy (src/grid_trader/trailing_strategy.py)

Concept: Entire grid shifts to follow price movements and capture trends.

Implementation:

def update_grid(self, current_price: float, price_history: List[float], time: int):
    sensitivity = self.config.sensitivity / 10
    
    if current_price > self.grid_range.max_price * (1 - 0.002 * sensitivity):
        # Shift grid up
        shift = (current_price - self.config.grid_center) * 0.5
        self.config.grid_center += shift
        # Update all order prices

Characteristics:

  • Grid center follows price direction
  • Captures trending market movements
  • Risk of missing reversals
  • Dynamic position adjustment
  • Higher turnover in volatile markets

Use Cases:

  • Trending cryptocurrency markets
  • Volatile assets with clear directional bias
  • When trend-following is preferred
  • Markets with sustained price movements

3. Hybrid Grid Strategy (src/grid_trader/hybrid_strategy.py)

Concept: Intelligent adaptation based on trend detection and market conditions.

Implementation:

def calculate_trend_bias(self, price_history: List[float]) -> TrendBias:
    if len(price_history) < 40:
        return TrendBias.NEUTRAL
        
    recent = price_history[-20:]
    older = price_history[-40:-20]
    recent_avg = np.mean(recent)
    older_avg = np.mean(older)
    
    if recent_avg > older_avg * 1.002:
        return TrendBias.BULLISH
    elif recent_avg < older_avg * 0.998:
        return TrendBias.BEARISH
    else:
        return TrendBias.NEUTRAL

def update_grid(self, current_price: float, price_history: List[float], time: int):
    self.trend_bias = self.calculate_trend_bias(price_history)
    
    # Adjust spacing based on trend
    spacing = (0.008 if self.trend_bias == TrendBias.BULLISH else 
               0.015 if self.trend_bias == TrendBias.BEARISH else 0.01)

Characteristics:

  • Trend-aware grid spacing adjustment
  • Combines mean reversion and trend following
  • Dynamic parameter optimization
  • Market condition adaptation
  • Balance between static and trailing approaches

Algorithm Details:

  • Trend Detection: 20-period vs 40-period moving average comparison
  • Dynamic Spacing:
    • Bullish: Tighter spacing below (0.8%), wider above (1.5%)
    • Bearish: Wider spacing below (1.5%), tighter above (0.8%)
    • Neutral: Standard spacing (1.0%)
  • Grid Adjustment: Gradual center movement (10% of price deviation)
  • Rebalancing: Every 50 time periods or when orders are exhausted

Use Cases:

  • All market conditions (most versatile)
  • When market regime is uncertain
  • Long-term automated trading
  • Risk-balanced approach

Algorithm Performance Comparison

Strategy Range Markets Trending Markets Volatility Complexity
Static Excellent Poor Low Simple
Trailing Poor Excellent High Medium
Hybrid Good Good Medium Complex

Simulation

Overview

The simulation engine allows backtesting and performance analysis of grid trading strategies without real money or API connections.

Simulation Features

1. Price Generation Engine (src/grid_trader/simulation.py)

def generate_price_movement(self):
    trend = self.config.trend_strength / 1000
    volatility = self.config.volatility / 200
    noise = (np.random.random() - 0.5) * volatility
    
    self.current_price = self.current_price * (1 + trend + noise)
    # Price boundaries: 70% to 130% of base price
    self.current_price = np.clip(
        self.current_price,
        self.config.base_price * 0.7,
        self.config.base_price * 1.3
    )

2. Strategy Comparison

Run all three strategies simultaneously with identical market conditions:

# Compare strategies in neutral market
uv run python main.py simulate --trend-strength 0 --volatility 5 --steps 1000

# Test in bullish trend
uv run python main.py simulate --trend-strength 5 --volatility 6 --steps 1000

# Test with trend events
uv run python main.py trend-test --steps 1500 --volatility 7

3. Performance Analytics (src/grid_trader/analytics.py)

Metrics Calculated:

  • Total profit/loss
  • Number of completed trades
  • Grid efficiency (trades per time period)
  • Win rate estimation
  • Average trade profit

Visualization:

# Generate performance charts
uv run python main.py simulate --chart --steps 1000
uv run python main.py trend-test --chart --steps 1500

Chart Outputs:

  • Price history comparison
  • Profit by strategy
  • Trade count comparison
  • Grid efficiency metrics

4. Simulation Configuration

@dataclass
class SimulationConfig:
    base_price: float = 50000.0      # Starting price
    trend_strength: float = 0.0       # -10 to +10 (bearish to bullish)
    volatility: int = 5               # 1 to 10 (low to high)
    sensitivity: int = 5              # 1 to 10 (grid adjustment sensitivity)
    max_history: int = 150           # Price history length
    simulation_steps: int = 1000     # Number of simulation steps

5. Advanced Simulation Features

Trend Event Testing:

def create_trend_event(self, duration: int = 100):
    direction = 1 if np.random.random() > 0.5 else -1
    self.config.trend_strength = direction * 8
    # Run trend for specified duration
    # Then return to neutral

Custom Scenarios:

  • Market crash simulation (large negative trend)
  • Bull run testing (sustained positive trend)
  • High volatility periods
  • Range-bound market conditions
  • Mixed trend scenarios

6. Simulation Results Analysis

Sample Output:

============================================================
GRID TRADING SIMULATION REPORT
============================================================
Simulation Time: 1000 periods
Final Price: $52,341.18

STATIC GRID STRATEGY
------------------------------
Completed Trades: 12
Total Profit: $2,341.18
Grid Efficiency: 1.2%

TRAILING GRID STRATEGY  
------------------------------
Completed Trades: 8
Total Profit: $1,876.45
Grid Efficiency: 0.8%

HYBRID GRID STRATEGY
------------------------------
Completed Trades: 15
Total Profit: $3,127.92
Grid Efficiency: 1.5%
Trend Bias: BULLISH

BEST PERFORMING STRATEGY: Hybrid Grid
Best Profit: $3,127.92

How to Use Simulations

1. Basic Strategy Testing

# Test default configuration
uv run python main.py simulate

# Test specific market conditions
uv run python main.py simulate --trend-strength 3 --volatility 7 --steps 2000

2. Strategy Optimization

# Test different sensitivities
uv run python main.py simulate --sensitivity 3 --steps 1000
uv run python main.py simulate --sensitivity 7 --steps 1000

# Test various volatility levels
uv run python main.py simulate --volatility 3 --steps 1000
uv run python main.py simulate --volatility 8 --steps 1000

3. Trend Event Analysis

# Simulate sudden market movements
uv run python main.py trend-test --steps 1500

# High volatility with trend events
uv run python main.py trend-test --volatility 8 --steps 2000

4. Performance Visualization

# Generate comparison charts
uv run python main.py simulate --chart --steps 1000
uv run python main.py trend-test --chart --steps 1500

# Charts saved as PNG files:
# - simulation_results.png
# - trend_test_results.png

The simulation engine provides a comprehensive testing environment to understand strategy behavior before deploying with real market data and paper trading through Alpaca.

About

Grid trading bot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages