Optimize strategies (#23)
* Update Tradingbox + set limit price * Change discord message
This commit is contained in:
177
docs/StrategyCombo-README.md
Normal file
177
docs/StrategyCombo-README.md
Normal file
@@ -0,0 +1,177 @@
|
||||
# Strategy Combination System
|
||||
|
||||
## Overview
|
||||
|
||||
The improved `TradingBox` strategy combination system provides sophisticated logic for combining multiple trading strategies with different purposes and behaviors. The system is designed around three distinct strategy types, each serving a specific role in the trading decision process.
|
||||
|
||||
## Strategy Types
|
||||
|
||||
### 1. Signal Strategies (`SignalType.Signal`)
|
||||
- **Purpose**: Generate rare, precise entry signals when specific conditions are met
|
||||
- **Behavior**: Sparse signal generation - only fire when opportunity is detected
|
||||
- **Examples**: RSI Divergence, MACD Cross, Chandelier Exit
|
||||
- **Weight**: High priority in final decision
|
||||
|
||||
### 2. Trend Strategies (`SignalType.Trend`)
|
||||
- **Purpose**: Identify overall market direction on every candlestick
|
||||
- **Behavior**: Continuous output (Long/Short/Neutral for each candle)
|
||||
- **Examples**: EMA Trend, SuperTrend, Moving Average Cross
|
||||
- **Weight**: Supporting role, validates signal direction
|
||||
|
||||
### 3. Context Strategies (`SignalType.Context`)
|
||||
- **Purpose**: Provide market context to prevent trades in unfavorable conditions
|
||||
- **Behavior**: Act as filters/guards (allow/block trades)
|
||||
- **Examples**: Volatility filters, Volume filters, Time-based restrictions
|
||||
- **Weight**: Veto power - can block otherwise valid signals
|
||||
|
||||
## Combination Logic
|
||||
|
||||
### Basic Flow
|
||||
1. **Context Validation**: All context strategies must allow the trade (configurable)
|
||||
2. **Signal Analysis**: Evaluate entry signals using majority voting
|
||||
3. **Trend Analysis**: Determine overall market direction
|
||||
4. **Final Decision**: Combine signal and trend with confidence scoring
|
||||
|
||||
### Decision Matrix
|
||||
|
||||
| Signal Direction | Trend Direction | Result | Confidence |
|
||||
|-----------------|----------------|---------|------------|
|
||||
| Long/Short | Same | Execute | High |
|
||||
| Long/Short | Neutral/None | Execute | Medium |
|
||||
| Long/Short | Opposite | Execute* | Low |
|
||||
| None | Long/Short | Execute | Medium/Low |
|
||||
| None | None | No Trade | N/A |
|
||||
|
||||
*_Depends on `AllowSignalTrendOverride` configuration_
|
||||
|
||||
## Configuration Options
|
||||
|
||||
The system uses `StrategyComboConfig` to customize behavior:
|
||||
|
||||
```csharp
|
||||
var config = new StrategyComboConfig
|
||||
{
|
||||
// Trend agreement thresholds
|
||||
TrendStrongAgreementThreshold = 0.66m, // 66% for strong trend
|
||||
|
||||
// Signal agreement thresholds
|
||||
SignalAgreementThreshold = 0.5m, // 50% majority for signals
|
||||
|
||||
// Override behavior
|
||||
AllowSignalTrendOverride = true, // Allow signals to override trends
|
||||
|
||||
// Quality filters
|
||||
MinimumConfidence = Confidence.Low, // Minimum confidence to trade
|
||||
MinimumContextConfidence = Confidence.Medium, // Minimum context quality required
|
||||
|
||||
// Defaults
|
||||
DefaultExchange = TradingExchanges.Binance
|
||||
};
|
||||
```
|
||||
|
||||
### Context Strategy Behavior
|
||||
|
||||
Context strategies now work with **confidence levels** rather than allow/block decisions:
|
||||
|
||||
- **High Confidence**: Ideal market conditions (e.g., low volatility)
|
||||
- **Medium Confidence**: Normal market conditions
|
||||
- **Low Confidence**: Elevated risk conditions (trade with caution)
|
||||
- **No Confidence**: Poor conditions (blocks trading)
|
||||
|
||||
All context strategies must meet the `MinimumContextConfidence` threshold for trades to proceed.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Usage (Default Configuration)
|
||||
```csharp
|
||||
var signal = TradingBox.GetSignal(candles, strategies, previousSignals);
|
||||
```
|
||||
|
||||
### Advanced Usage (Custom Configuration)
|
||||
```csharp
|
||||
var config = new StrategyComboConfig
|
||||
{
|
||||
TrendStrongAgreementThreshold = 0.75m, // Require 75% trend agreement
|
||||
MinimumConfidence = Confidence.Medium, // Only trade medium+ confidence
|
||||
MinimumContextConfidence = Confidence.High, // Only trade in ideal conditions
|
||||
AllowSignalTrendOverride = false // Don't allow trend conflicts
|
||||
};
|
||||
|
||||
var signal = TradingBox.GetSignal(candles, strategies, previousSignals, config);
|
||||
```
|
||||
|
||||
### Typical Strategy Combinations
|
||||
|
||||
#### Conservative Setup
|
||||
- 1 Signal Strategy (RSI Divergence)
|
||||
- 2 Trend Strategies (EMA Trend, SuperTrend)
|
||||
- 1 Context Strategy (Volatility Filter)
|
||||
|
||||
#### Aggressive Setup
|
||||
- 2 Signal Strategies (MACD Cross, Chandelier Exit)
|
||||
- 1 Trend Strategy (EMA Trend)
|
||||
- No Context Strategies
|
||||
|
||||
#### Scalping Setup
|
||||
- 3 Signal Strategies (Quick signals)
|
||||
- 1 Trend Strategy (Short-term trend)
|
||||
- 2 Context Strategies (Volume + Time filters)
|
||||
|
||||
## Key Improvements
|
||||
|
||||
### 1. **Flexible Requirements**
|
||||
- No longer requires ALL strategies to produce signals
|
||||
- Different logic for different strategy types
|
||||
- Configurable thresholds and behavior
|
||||
|
||||
### 2. **Intelligent Voting**
|
||||
- Majority voting for signals and trends
|
||||
- Weighted decisions based on strategy type
|
||||
- Handles neutral/conflicting signals gracefully
|
||||
|
||||
### 3. **Confidence Scoring**
|
||||
- Dynamic confidence based on agreement levels
|
||||
- Considers signal-trend alignment
|
||||
- Configurable minimum confidence thresholds
|
||||
|
||||
### 4. **Context Awareness**
|
||||
- Context strategies provide market condition quality through confidence levels
|
||||
- Configurable minimum context confidence thresholds
|
||||
- Simplified logic: all context strategies must meet minimum confidence
|
||||
- No more complex unanimous vs. majority requirements
|
||||
|
||||
### 5. **Trend Reversal Support**
|
||||
- Signal strategies can override trend direction
|
||||
- Useful for catching trend reversals
|
||||
- Configurable override behavior
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Strategy Selection
|
||||
1. **Use 1-2 Signal strategies** for entry precision
|
||||
2. **Use 1-3 Trend strategies** for direction confirmation
|
||||
3. **Use 0-2 Context strategies** for risk management
|
||||
|
||||
### Configuration Tuning
|
||||
1. **Start with defaults** and adjust based on backtesting
|
||||
2. **Higher thresholds** = fewer but higher quality signals
|
||||
3. **Lower thresholds** = more signals but potentially more noise
|
||||
|
||||
### Testing Recommendations
|
||||
1. **Backtest different configurations** on historical data
|
||||
2. **Monitor confidence distributions** in live trading
|
||||
3. **Adjust thresholds** based on performance metrics
|
||||
|
||||
## Migration from Old System
|
||||
|
||||
The new system is backward compatible:
|
||||
- Existing calls to `GetSignal()` work unchanged
|
||||
- Old unanimous agreement logic is still available via configuration
|
||||
- New overloads provide additional control when needed
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
- Strategy evaluation is optimized for efficiency
|
||||
- Signal caching prevents duplicate calculations
|
||||
- Configurable quality filters reduce unnecessary trades
|
||||
- Separate validation logic for different strategy types
|
||||
215
docs/VolatilityControlledTradingScenario.md
Normal file
215
docs/VolatilityControlledTradingScenario.md
Normal file
@@ -0,0 +1,215 @@
|
||||
# Volatility-Controlled Trading Scenario
|
||||
|
||||
## Overview
|
||||
|
||||
This scenario combines the **STCStrategy** (Signal) with the **StDevContext** (Context) to create a sophisticated trading system that identifies trend reversals while respecting market volatility conditions.
|
||||
|
||||
## Strategy Components
|
||||
|
||||
### STCStrategy (Signal Type)
|
||||
- **Purpose**: Detects trend reversals using Schaff Trend Cycle indicator
|
||||
- **Signals**:
|
||||
- Long when STC crosses above 25 (oversold recovery)
|
||||
- Short when STC crosses below 75 (overbought decline)
|
||||
- **Confidence**: Medium for all signals
|
||||
|
||||
### StDevContext (Context Type)
|
||||
- **Purpose**: Evaluates market volatility to determine trading conditions
|
||||
- **Z-Score Ranges**:
|
||||
- `|Z| ≤ 0.5`: **High Confidence** - Very stable conditions, ideal for trading
|
||||
- `0.5 < |Z| ≤ 1.0`: **Medium Confidence** - Normal volatility, good for trading
|
||||
- `1.0 < |Z| ≤ 1.5`: **Low Confidence** - Elevated volatility, trade with caution
|
||||
- `|Z| > 1.5`: **No Confidence** - High volatility, avoid trading
|
||||
|
||||
## Implementation
|
||||
|
||||
### Basic Setup
|
||||
|
||||
```csharp
|
||||
// Initialize strategies
|
||||
var stcStrategy = new STCStrategy(
|
||||
name: "STC Reversal",
|
||||
cyclePeriods: 10, // Cycle length for STC calculation
|
||||
fastPeriods: 12, // Fast EMA period
|
||||
slowPeriods: 26 // Slow EMA period
|
||||
);
|
||||
|
||||
var volatilityFilter = new StDevContext(
|
||||
name: "Volatility Filter",
|
||||
period: 20 // Period for standard deviation calculation
|
||||
);
|
||||
|
||||
// Set up strategies
|
||||
var strategies = new HashSet<IStrategy> { stcStrategy, volatilityFilter };
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```csharp
|
||||
// Conservative configuration (safer trading)
|
||||
var conservativeConfig = new StrategyComboConfig
|
||||
{
|
||||
MinimumContextConfidence = Confidence.High, // Only trade in very stable conditions
|
||||
MinimumConfidence = Confidence.Medium, // Only trade medium+ confidence signals
|
||||
AllowSignalTrendOverride = true // Allow reversal signals
|
||||
};
|
||||
|
||||
// Aggressive configuration (more trading opportunities)
|
||||
var aggressiveConfig = new StrategyComboConfig
|
||||
{
|
||||
MinimumContextConfidence = Confidence.Low, // Trade in elevated volatility
|
||||
MinimumConfidence = Confidence.Low, // Accept lower confidence signals
|
||||
AllowSignalTrendOverride = true
|
||||
};
|
||||
|
||||
// Balanced configuration (recommended starting point)
|
||||
var balancedConfig = new StrategyComboConfig
|
||||
{
|
||||
MinimumContextConfidence = Confidence.Medium, // Require normal volatility conditions
|
||||
MinimumConfidence = Confidence.Medium, // Standard confidence requirements
|
||||
AllowSignalTrendOverride = true // Allow trend reversals
|
||||
};
|
||||
```
|
||||
|
||||
### Trading Logic
|
||||
|
||||
```csharp
|
||||
public Signal GetTradingSignal(HashSet<Candle> candles, StrategyComboConfig config)
|
||||
{
|
||||
// Update strategies with latest candle data
|
||||
foreach (var strategy in strategies)
|
||||
{
|
||||
strategy.UpdateCandles(candles);
|
||||
}
|
||||
|
||||
// Get combined signal
|
||||
var signal = TradingBox.GetSignal(
|
||||
candles,
|
||||
strategies,
|
||||
new HashSet<Signal>(), // Previous signals
|
||||
config,
|
||||
loopbackPeriod: 1 // Check only latest candle
|
||||
);
|
||||
|
||||
return signal;
|
||||
}
|
||||
```
|
||||
|
||||
### Complete Example
|
||||
|
||||
```csharp
|
||||
public class VolatilityControlledTradingBot
|
||||
{
|
||||
private readonly STCStrategy _stcStrategy;
|
||||
private readonly StDevContext _volatilityFilter;
|
||||
private readonly StrategyComboConfig _config;
|
||||
|
||||
public VolatilityControlledTradingBot()
|
||||
{
|
||||
_stcStrategy = new STCStrategy("STC Reversal", 10, 12, 26);
|
||||
_volatilityFilter = new StDevContext("Volatility Filter", 20);
|
||||
|
||||
_config = new StrategyComboConfig
|
||||
{
|
||||
MinimumContextConfidence = Confidence.Medium,
|
||||
MinimumConfidence = Confidence.Medium,
|
||||
AllowSignalTrendOverride = true
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<Signal> AnalyzeMarket(List<Candle> candles)
|
||||
{
|
||||
// Ensure we have enough data
|
||||
if (candles.Count < 50) // Need sufficient history for both strategies
|
||||
return null;
|
||||
|
||||
var strategies = new HashSet<IStrategy> { _stcStrategy, _volatilityFilter };
|
||||
|
||||
// Update strategies
|
||||
foreach (var strategy in strategies)
|
||||
{
|
||||
strategy.UpdateCandles(candles.ToHashSet());
|
||||
}
|
||||
|
||||
// Get trading signal
|
||||
var signal = TradingBox.GetSignal(
|
||||
candles.ToHashSet(),
|
||||
strategies,
|
||||
new HashSet<Signal>(),
|
||||
_config
|
||||
);
|
||||
|
||||
// Log decision process
|
||||
if (signal != null)
|
||||
{
|
||||
Console.WriteLine($"Trade Signal Generated:");
|
||||
Console.WriteLine($" Direction: {signal.Direction}");
|
||||
Console.WriteLine($" Confidence: {signal.Confidence}");
|
||||
Console.WriteLine($" Date: {signal.Date}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("No trade signal - conditions not met");
|
||||
}
|
||||
|
||||
return signal;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Loopback Period Recommendations
|
||||
|
||||
### For this Scenario:
|
||||
- **Loopback Period: 1-3 candles**
|
||||
- STC reversals are typically captured immediately
|
||||
- Volatility context is current market condition
|
||||
- Short loopback prevents stale signals
|
||||
|
||||
### Considerations:
|
||||
- **Market Timeframe**:
|
||||
- 5m-15m charts: Use loopback = 1
|
||||
- 1h-4h charts: Use loopback = 2-3
|
||||
- Daily charts: Use loopback = 1-2
|
||||
|
||||
## Expected Behavior
|
||||
|
||||
### High Volatility Conditions (Z-Score > 1.5)
|
||||
- StDevContext returns `Confidence.None`
|
||||
- No trades executed regardless of STC signals
|
||||
- Protects against whipsaw movements
|
||||
|
||||
### Normal Volatility Conditions (|Z-Score| ≤ 1.0)
|
||||
- StDevContext returns `Confidence.Medium` or `Confidence.High`
|
||||
- STC signals are evaluated normally
|
||||
- Trades executed when STC crosses thresholds
|
||||
|
||||
### Low Volatility Conditions (|Z-Score| ≤ 0.5)
|
||||
- StDevContext returns `Confidence.High`
|
||||
- Ideal conditions for trend reversal trading
|
||||
- Higher probability of successful STC signals
|
||||
|
||||
## Performance Tuning
|
||||
|
||||
### STC Parameters:
|
||||
- **cyclePeriods**: 8-15 (shorter = more sensitive)
|
||||
- **fastPeriods**: 9-15 (standard EMA settings)
|
||||
- **slowPeriods**: 21-30 (standard EMA settings)
|
||||
|
||||
### Volatility Parameters:
|
||||
- **period**: 14-21 (standard volatility lookback)
|
||||
- **Z-Score thresholds**: Adjust based on asset volatility characteristics
|
||||
|
||||
## Risk Management
|
||||
|
||||
1. **Position Sizing**: Reduce size when volatility confidence is low
|
||||
2. **Stop Losses**: Tighter stops in high volatility periods
|
||||
3. **Take Profits**: Quicker profit-taking when volatility increases
|
||||
4. **Market Hours**: Consider time-based context strategies for optimal trading windows
|
||||
|
||||
## Backtesting Recommendations
|
||||
|
||||
1. Test different volatility thresholds on historical data
|
||||
2. Evaluate performance across various market conditions
|
||||
3. Monitor the distribution of context confidence levels
|
||||
4. Analyze signal quality vs. market volatility correlation
|
||||
5. Compare performance with and without volatility filtering
|
||||
Reference in New Issue
Block a user