215 lines
6.7 KiB
Markdown
215 lines
6.7 KiB
Markdown
# 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 |