Cycles/docs/strategy_manager.md
Vasily.onl 235098c045 Add strategy management system with multiple trading strategies
- Introduced a new strategies module containing the StrategyManager class to orchestrate multiple trading strategies.
- Implemented StrategyBase and StrategySignal as foundational components for strategy development.
- Added DefaultStrategy for meta-trend analysis and BBRSStrategy for Bollinger Bands + RSI trading.
- Enhanced documentation to provide clear usage examples and configuration guidelines for the new system.
- Established a modular architecture to support future strategy additions and improvements.
2025-05-23 16:41:08 +08:00

9.1 KiB

TCP Cycles Strategy Management System

The Strategy Manager system provides a flexible framework for implementing, combining, and managing multiple trading strategies within the TCP Cycles project.

🏗️ Architecture

Module Structure

cycles/
├── strategies/              # Strategy management module
│   ├── __init__.py         # Module exports and version info
│   ├── base.py             # Base classes (StrategyBase, StrategySignal)
│   ├── default_strategy.py # Meta-trend strategy implementation
│   ├── bbrs_strategy.py    # Bollinger Bands + RSI strategy
│   └── manager.py          # StrategyManager and orchestration
├── Analysis/               # Technical analysis tools
├── utils/                  # Utility functions
├── backtest.py            # Backtesting engine
└── charts.py              # Charting and visualization

Core Components

  1. StrategyBase: Abstract base class that all strategies inherit from
  2. StrategySignal: Represents trading signals with confidence levels and metadata
  3. DefaultStrategy: Implementation of the meta-trend strategy using Supertrend indicators
  4. BBRSStrategy: Implementation of the Bollinger Bands + RSI strategy with market regime detection
  5. StrategyManager: Orchestrates multiple strategies and combines their signals

Signal Types

  • "ENTRY": Strategy suggests entering a position
  • "EXIT": Strategy suggests exiting a position
  • "HOLD": Strategy suggests no action

📋 Configuration

Single Strategy Configuration

Default Strategy Only:

{
    "start_date": "2025-03-01",
    "stop_date": "2025-03-15", 
    "initial_usd": 10000,
    "timeframes": ["15min"],
    "stop_loss_pcts": [0.03, 0.05],
    "strategies": [
        {
            "name": "default",
            "weight": 1.0,
            "params": {}
        }
    ],
    "combination_rules": {
        "entry": "any",
        "exit": "any",
        "min_confidence": 0.5
    }
}

BBRS Strategy Only:

{
    "strategies": [
        {
            "name": "bbrs", 
            "weight": 1.0,
            "params": {
                "bb_width": 0.05,
                "bb_period": 20,
                "rsi_period": 14,
                "strategy_name": "MarketRegimeStrategy"
            }
        }
    ]
}

Multiple Strategy Configuration

{
    "strategies": [
        {
            "name": "default",
            "weight": 0.6,
            "params": {}
        },
        {
            "name": "bbrs",
            "weight": 0.4, 
            "params": {
                "bb_width": 0.05,
                "strategy_name": "MarketRegimeStrategy"
            }
        }
    ],
    "combination_rules": {
        "entry": "weighted_consensus",
        "exit": "any",
        "min_confidence": 0.6
    }
}

🔧 Combination Rules

Entry Signal Combination Methods

  • "any": Enter if ANY strategy signals entry above min_confidence
  • "all": Enter only if ALL strategies signal entry above min_confidence
  • "majority": Enter if more than 50% of strategies signal entry
  • "weighted_consensus": Enter based on weighted average confidence

Exit Signal Combination Methods

  • "any": Exit if ANY strategy signals exit (recommended for risk management)
  • "all": Exit only if ALL strategies agree on exit
  • "priority": Exit based on priority: STOP_LOSS > SELL_SIGNAL > others

Parameters

  • min_confidence: Minimum confidence threshold (0.0 to 1.0)
  • weight: Strategy weight for weighted calculations

🚀 Usage Examples

Running with Default Strategy

python main.py config_default.json

Running with BBRS Strategy

python main.py config_bbrs.json

Running with Combined Strategies

python main.py config_combined.json

Running without Config (Interactive)

python main.py

Programmatic Usage

from cycles.strategies import create_strategy_manager

# Create strategy manager from config
config = {
    "strategies": [
        {"name": "default", "weight": 0.7, "params": {}},
        {"name": "bbrs", "weight": 0.3, "params": {"bb_width": 0.05}}
    ],
    "combination_rules": {
        "entry": "weighted_consensus",
        "exit": "any",
        "min_confidence": 0.6
    }
}

strategy_manager = create_strategy_manager(config)

⚙️ Strategy Parameters

Default Strategy Parameters

  • stop_loss_pct: Stop loss percentage (default: 0.03)

BBRS Strategy Parameters

  • bb_width: Bollinger Band width (default: 0.05)
  • bb_period: Bollinger Band period (default: 20)
  • rsi_period: RSI period (default: 14)
  • trending_rsi_threshold: RSI thresholds for trending market [low, high]
  • trending_bb_multiplier: BB multiplier for trending market
  • sideways_rsi_threshold: RSI thresholds for sideways market [low, high]
  • sideways_bb_multiplier: BB multiplier for sideways market
  • strategy_name: Strategy implementation name
  • SqueezeStrategy: Enable squeeze strategy (boolean)
  • stop_loss_pct: Stop loss percentage (default: 0.05)

🔌 Adding New Strategies

1. Create Strategy Class

Create a new file in cycles/strategies/ (e.g., my_strategy.py):

from .base import StrategyBase, StrategySignal

class MyStrategy(StrategyBase):
    def __init__(self, weight=1.0, params=None):
        super().__init__("my_strategy", weight, params)
    
    def initialize(self, backtester):
        # Initialize your strategy indicators
        self.initialized = True
    
    def get_entry_signal(self, backtester, df_index):
        # Implement entry logic
        if entry_condition:
            return StrategySignal("ENTRY", confidence=0.8)
        return StrategySignal("HOLD", confidence=0.0)
    
    def get_exit_signal(self, backtester, df_index):
        # Implement exit logic
        if exit_condition:
            return StrategySignal("EXIT", confidence=1.0, 
                                metadata={"type": "MY_EXIT"})
        return StrategySignal("HOLD", confidence=0.0)

2. Register Strategy

Update cycles/strategies/manager.py in the _load_strategies method:

elif name == "my_strategy":
    from .my_strategy import MyStrategy
    strategies.append(MyStrategy(weight, params))

3. Export Strategy

Update cycles/strategies/__init__.py:

from .my_strategy import MyStrategy

__all__ = [
    # ... existing exports ...
    'MyStrategy'
]

📊 Performance Features

Strategy Analysis

  • Individual strategy performance tracking
  • Combined strategy performance metrics
  • Signal quality analysis
  • Confidence level monitoring

Plotting Support

  • Automatic chart generation for BBRS strategies
  • Meta-trend visualization for default strategy
  • Combined signal overlays
  • Performance comparison charts

🔄 Backward Compatibility

The system maintains full backward compatibility:

  • Existing code using single strategies works unchanged
  • Legacy strategy functions are preserved in main.py
  • Default behavior matches original implementation
  • Gradual migration path available

📚 Best Practices

1. Risk Management

  • Use "any" exit rule for faster risk exits
  • Set appropriate stop loss percentages per strategy
  • Monitor combined drawdown vs individual strategies

2. Signal Quality

  • Set appropriate min_confidence based on strategy reliability
  • Test individual strategies thoroughly before combining
  • Monitor signal frequency and quality

3. Weight Distribution

  • Balance strategy weights based on historical performance
  • Consider strategy correlation when setting weights
  • Regularly rebalance based on changing market conditions

4. Testing & Validation

  • Backtest individual strategies first
  • Test combinations on historical data
  • Validate on out-of-sample data

5. Monitoring

  • Log strategy initialization and errors
  • Track individual vs combined performance
  • Monitor signal generation frequency

🔍 Troubleshooting

Strategy Not Found Error

ValueError: Unknown strategy: my_strategy

Solution: Ensure strategy is registered in manager.py _load_strategies method

No Signals Generated

Possible Causes:

  • Strategy initialization failed
  • Data insufficient for strategy requirements
  • min_confidence threshold too high

Solution: Check logs, verify data, adjust confidence threshold

Poor Combined Performance

Analysis Steps:

  1. Review individual strategy performance
  2. Check strategy correlation and overlap
  3. Adjust weights and combination rules
  4. Consider market regime compatibility

Import Errors

ImportError: cannot import name 'StrategyManager'

Solution: Use correct import path: from cycles.strategies import StrategyManager

📞 Support

For issues, feature requests, or contributions:

  1. Check existing documentation and examples
  2. Review troubleshooting section
  3. Examine configuration files for proper syntax
  4. Ensure all dependencies are installed

Version: 1.0.0
Last Updated: January 2025
TCP Cycles Project