SpiceTrader: Adaptive Cryptocurrency Trading Bot
I’ve always been curious whether algorithmic trading actually works. Not from a “get rich quick” perspective, but from an engineering challenge standpoint: can you build a system that adapts to changing market conditions instead of blindly following a single strategy? That question led me to build SpiceTrader.
The Core Problem with Trading Bots
Most trading bots are inflexible. They execute one strategy regardless of market conditions. A mean reversion bot keeps buying dips even when the market is trending down. A trend-following bot keeps chasing momentum even when the market enters a choppy range. Each strategy works brilliantly in the right conditions and fails spectacularly in the wrong ones.
The challenge isn’t finding a strategy that works. It’s building a system that recognizes when market conditions change and adapts accordingly.
How SpiceTrader Works
SpiceTrader is a Python-based trading system for the Kraken cryptocurrency exchange that analyzes market conditions every 30 minutes and automatically selects the optimal trading strategy from five available approaches.
The system follows a detection-selection-execution pipeline:
- Market Analysis: Calculate technical indicators (ADX, Choppiness Index, ATR, price range)
- State Classification: Identify which of seven market states currently applies
- Strategy Selection: Map the detected state to the optimal strategy
- Trade Execution: Execute trades according to the selected strategy’s rules
Seven Market States
The bot classifies markets into distinct states based on technical analysis:
- Strong Trend: ADX above 25 indicates clear directional movement
- Moderate Trend: ADX between 20-25 shows developing momentum
- Range-Bound: Low ADX with 10-15% price oscillation
- Volatile Breakout: High ATR with price breaking support/resistance levels
- Choppy: Choppiness Index above 61.8 indicates directionless movement
- Low Volatility: Price ranges below 5% suggest consolidation
Each state maps to the strategy most likely to profit in those conditions.
Five Trading Strategies
Mean Reversion operates in range-bound markets by buying when RSI shows oversold conditions below the lower Bollinger Band and selling at overbought levels near the upper band. This works when prices oscillate predictably between support and resistance.
SMA Crossover captures trends using 10-period and 30-period simple moving averages. Buy signals trigger when the fast SMA crosses above the slow SMA, indicating upward momentum. Sell signals occur on downward crosses. This performs best during strong directional movements.
MACD detects momentum shifts in moderate trends by comparing the MACD line against the signal line. Bullish crosses generate buy signals, bearish crosses generate sells. This catches trend changes earlier than moving average systems.
Breakout capitalizes on volatile movements by detecting volume surges (150% above average) combined with price breaks beyond recent ranges. This strategy profits from momentum after support or resistance violations.
Grid Trading operates in low-volatility conditions by placing buy orders below current price and sell orders above, capturing small profits from oscillations within tight ranges.
Risk Management
The system implements multiple safety mechanisms to prevent catastrophic losses:
Position Limits
- Individual coins capped at 25% of portfolio value
- Total positions limited to 75% of account balance
- Remaining 25% held as reserve for market opportunities
Strategy Switch Protection
- Switches require three consecutive confirmations across 90 minutes
- One-hour cooldown between consecutive changes
- Maximum four strategy switches per coin per day
- Prevents rapid oscillation between strategies
Fee-Aware Trading
The bot accounts for Kraken’s trading fees in every decision. Round-trip costs average 0.52% for market orders or 0.32% for limit orders. The system:
- Calculates minimum profit thresholds after fee deduction
- Skips trades that would be unprofitable after fees
- Tracks cumulative fee impact across all positions
- Displays net profit/loss after fee calculations
Dry-Run Mode
All trading defaults to simulation mode. Positions are tracked, trades are logged, but no real money moves. This lets you test strategies and verify the system behaves correctly before risking capital.
Multi-Coin Architecture
The multi-coin implementation manages independent analysis for BTC, SOL, ETH, and XMR simultaneously. Each coin receives separate market state classification and can operate under different strategies concurrently.
For example, Bitcoin might be running the SMA Crossover strategy in a trending market while Ethereum executes Mean Reversion in a range-bound state. The portfolio-level position sizing ensures overall risk stays within acceptable limits regardless of how many coins are actively trading.
Technical Implementation
Market Analysis Pipeline
The system calculates multiple technical indicators every 30 minutes:
- RSI (Relative Strength Index) for overbought/oversold conditions
- Bollinger Bands for volatility and mean reversion signals
- ADX (Average Directional Index) for trend strength measurement
- Choppiness Index for directionality assessment
- MACD for momentum detection
- ATR (Average True Range) for volatility quantification
These indicators feed into the market state classifier, which assigns confidence scores to each possible state and selects the best match.
Database Tracking
Every action gets logged to SQLite:
- Individual trade records with entry/exit prices and fees
- Position metrics including unrealized P&L
- Strategy switches with timestamps and reasoning
- Daily and weekly performance summaries
This historical data enables performance analysis and strategy refinement over time.
Configuration Management
Behavior is controlled through environment variables in .env files:
# Trading Configuration
TRADING_PAIR=XBT/USD
POSITION_SIZE=0.01
DRY_RUN=true
# Kraken API Credentials
API_KEY=your_api_key
API_SECRET=your_api_secret
# Technical Indicator Thresholds
RSI_OVERSOLD=35
RSI_OVERBOUGHT=65
ADX_STRONG_TREND=25
This keeps credentials separate from code and makes parameter tuning straightforward.
What I Learned
Building SpiceTrader taught me several things about algorithmic trading:
1. Strategy selection matters more than strategy optimization. A mediocre strategy applied in the right market conditions outperforms a perfect strategy applied to the wrong conditions.
2. False signals are expensive. Every strategy switch based on noise instead of genuine market state changes incurs unnecessary fees. The confirmation requirements and cooldown periods exist because early versions oscillated too rapidly.
3. Backtesting lies. Historical data always looks cleaner than real-time markets. Live trading introduces execution delays, fee impacts, and psychological factors that don’t exist in backtests.
4. Risk management is non-negotiable. Position limits and stop-losses aren’t optional safety features. They’re fundamental to survival when the system makes inevitable mistakes.
Performance Expectations
I built this as a proof of concept and learning exercise, not as a money-making machine. Cryptocurrency markets are volatile, efficient, and unforgiving. Most retail traders lose money, and most trading bots do worse.
SpiceTrader demonstrates that adaptive strategy selection is technically feasible. Whether it’s profitable over the long term remains an open question that requires extensive live testing with real capital.
Getting Started
The code is open source under the AGPL-3.0 license and available on GitHub.
Setup requires:
- Python 3.8 or higher
- Kraken API credentials with trading permissions
- Configuration of environment variables in
.env
Start in dry-run mode and monitor for at least 24-48 hours before considering live trading. Use minimum position sizes if you do go live, and maintain strict exit strategies.
What’s Next
Future enhancements I’m considering:
- Additional strategies for different market conditions
- Machine learning for market state classification
- Support for other exchanges beyond Kraken
- Backtesting framework for strategy validation
- Web dashboard for monitoring and manual intervention
The interesting challenge is improving market state detection. Current indicators work reasonably well, but better classification would reduce false strategy switches and improve overall performance.
The Honest Assessment
Will SpiceTrader make money? I don’t know. That’s not really the point. The goal was to build a system that intelligently adapts to market conditions rather than rigidly following a single approach.
From an engineering perspective, it works. The market analyzer correctly identifies different states, the strategy selector maps those states to appropriate approaches, and the risk management prevents catastrophic losses.
Whether that translates to profitable trading is something only extensive live operation will determine. If you build your own version, treat it as an experiment and never risk more than you can afford to lose entirely.