Files
crypto_trader/docs/architecture/strategy_framework.md

4.5 KiB

Strategy Framework Architecture

This document describes the strategy framework design.

Strategy Hierarchy

BaseStrategy (Abstract)
        │
        ├──► Technical Strategies
        │       ├──► RSIStrategy
        │       ├──► MACDStrategy
        │       ├──► MovingAverageStrategy
        │       ├──► ConfirmedStrategy (Multi-Indicator)
        │       ├──► DivergenceStrategy
        │       └──► BollingerMeanReversionStrategy
        │
        ├──► Ensemble Strategies
        │       └──► ConsensusStrategy
        │
        ├──► Other Strategies
        │       ├──► DCAStrategy
        │       ├──► GridStrategy
        │       └──► MomentumStrategy
        │
        └──► CustomStrategy (user-defined)

Base Strategy Interface

All strategies implement:

class BaseStrategy(ABC):
    async def on_data(new_data: pd.DataFrame)
    async def generate_signal() -> Dict[str, Any]
    async def calculate_position_size(capital, risk) -> float
    async def start()
    async def stop()

Strategy Lifecycle

1. Initialization
   └──► __init__(parameters)
   
2. Activation
   └──► start()
   
3. Data Processing
   └──► on_data(new_data)
        └──► generate_signal()
             └──► Trading Engine
             
4. Deactivation
   └──► stop()

Strategy Registry

Manages available strategies:

StrategyRegistry
    ├──► register_strategy(name, class)
    ├──► get_strategy_class(name)
    └──► list_available()

Multi-Timeframe Support

Strategies can use multiple timeframes:

Primary Timeframe (1h)
        │
        ├──► Signal Generation
        │
        └──► Higher Timeframe (1d) - Trend Confirmation
                │
                └──► Lower Timeframe (15m) - Entry Timing

Strategy Scheduling

Strategies can be scheduled:

  • Continuous: Run on every new candle
  • Time-based: Run at specific times
  • Condition-based: Run when conditions met

Signal Generation

Signal flow:

Data Update
    │
    ▼
Indicator Calculation
    │
    ▼
Strategy Logic
    │
    ▼
Signal Generation
    │
    ├──► "buy" - Generate buy signal
    ├──► "sell" - Generate sell signal
    └──► "hold" - No action

Position Sizing

Strategies calculate position sizes:

  • Fixed Percentage: Fixed % of capital
  • Kelly Criterion: Optimal position sizing based on win rate
  • Volatility-Based: Adjusts based on market volatility (ATR)

Advanced Features

Trend Filtering

All strategies can optionally use ADX-based trend filtering:

signal = strategy.apply_trend_filter(
    signal, 
    ohlcv_data, 
    adx_period=14, 
    min_adx=25.0
)

This filters out signals when:

  • ADX < threshold (weak trend/chop)
  • Signal direction doesn't match trend direction

Multi-Indicator Confirmation

The ConfirmedStrategy requires multiple indicators to agree before generating signals, reducing false signals by 20-30%.

Divergence Detection

Divergence strategies detect price vs. indicator divergences:

  • Bullish divergence: Price lower low, indicator higher low → BUY
  • Bearish divergence: Price higher high, indicator lower high → SELL

Ensemble Methods

ConsensusStrategy aggregates signals from multiple strategies:

  • Weighted voting by strategy performance
  • Minimum consensus threshold
  • Dynamic weighting based on recent performance
  • Kelly Criterion: Optimal position sizing
  • Volatility-based: Based on ATR
  • Risk-based: Based on stop-loss distance

Strategy Parameters

Configurable parameters:

  • Strategy-specific parameters (e.g., RSI period)
  • Risk parameters (position size, stop-loss)
  • Timeframe settings
  • Symbol selection

Strategy Execution

Execution flow:

Strategy Signal
    │
    ▼
Trading Engine
    │
    ├──► Risk Check
    │
    ├──► Position Sizing
    │
    └──► Order Execution
            │
            ├──► Paper Trading
            └──► Live Trading

Strategy Performance

Performance tracking:

  • Win rate
  • Total return
  • Sharpe ratio
  • Max drawdown
  • Number of trades

Extensibility

Easy to add new strategies:

  1. Inherit from BaseStrategy
  2. Implement required methods
  3. Register with StrategyRegistry
  4. Configure and use