Прорыв наклона MA
Стратегия MA Slope Breakout отслеживает скорость изменения скользящей средней. Сильный рост наклона намекает на зарождение нового тренда.
Тестирование показывает среднегодичную доходность около 124%. Стратегию лучше запускать на рынке Форекс.
Сделка открывается, когда наклон превышает обычный уровень на несколько стандартных отклонений и выполняется в направлении ускорения с защитным стопом.
Стратегия интересна активным трейдерам, стремящимся получить ранний доступ к тренду. Позиции закрываются, когда наклон возвращается к нормальным значениям. Значение по умолчанию MaLength = 20.
Подробности
- Условие входа: Индикатор превышает среднее значение на величину коэффициента отклонения.
- Лонг/Шорт: Оба направления.
- Условие выхода: Индикатор возвращается к среднему.
- Стопы: Да.
- Значения по умолчанию:
MaLength= 20LookbackPeriod= 20DeviationMultiplier= 2mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Прорыв
- Направление: Оба
- Индикаторы: MA
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Краткосрочный
- Сезонность: Нет
- Нейронные сети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy based on Moving Average Slope breakout
/// Enters positions when the slope of MA exceeds average slope plus a multiple of standard deviation
/// </summary>
public class MaSlopeBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<decimal> _deviationMultiplier;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private SimpleMovingAverage _sma;
private decimal _prevMaValue;
private decimal _currentSlope;
private decimal _avgSlope;
private decimal _stdDevSlope;
private decimal[] _slopes;
private int _currentIndex;
private bool _isInitialized;
/// <summary>
/// Moving Average length
/// </summary>
public int MaLength
{
get => _maLength.Value;
set => _maLength.Value = value;
}
/// <summary>
/// Lookback period for slope statistics calculation
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Standard deviation multiplier for breakout detection
/// </summary>
public decimal DeviationMultiplier
{
get => _deviationMultiplier.Value;
set => _deviationMultiplier.Value = value;
}
/// <summary>
/// Candle type
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss percentage
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Constructor
/// </summary>
public MaSlopeBreakoutStrategy()
{
_maLength = Param(nameof(MaLength), 20)
.SetGreaterThanZero()
.SetDisplay("MA Length", "Period for Moving Average", "Indicator Parameters")
.SetOptimize(10, 50, 5);
_lookbackPeriod = Param(nameof(LookbackPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Period for slope statistics calculation", "Strategy Parameters")
.SetOptimize(10, 50, 5);
_deviationMultiplier = Param(nameof(DeviationMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("Deviation Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters")
.SetOptimize(1m, 3m, 0.5m);
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevMaValue = 0;
_currentSlope = 0;
_avgSlope = 0;
_stdDevSlope = 0;
_currentIndex = 0;
_isInitialized = false;
_slopes = new decimal[LookbackPeriod];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
_sma = new SMA { Length = MaLength };
_slopes = new decimal[LookbackPeriod];
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_sma, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _sma);
DrawOwnTrades(area);
}
// Set up position protection
StartProtection(
takeProfit: null, // We'll handle exits via strategy logic
stopLoss: new Unit(StopLossPercent, UnitTypes.Percent)
);
base.OnStarted2(time);
}
private void ProcessCandle(ICandleMessage candle, decimal maValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Check if indicator is formed
if (!_sma.IsFormed)
return;
// Calculate the slope
if (!_isInitialized)
{
_prevMaValue = maValue;
_isInitialized = true;
return;
}
// Calculate current slope (simple difference for now)
_currentSlope = maValue - _prevMaValue;
// Store slope in array and update index
_slopes[_currentIndex] = _currentSlope;
_currentIndex = (_currentIndex + 1) % LookbackPeriod;
// Calculate statistics once we have enough data
if (!IsFormedAndOnlineAndAllowTrading())
return;
CalculateStatistics();
// Trading logic
if (Math.Abs(_avgSlope) > 0) // Avoid division by zero
{
// Long signal: slope exceeds average + k*stddev (slope is positive and we don't have a long position)
if (_currentSlope > 0 &&
_currentSlope > _avgSlope + DeviationMultiplier * _stdDevSlope &&
Position <= 0)
{
// Cancel existing orders
CancelActiveOrders();
// Enter long position
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
LogInfo($"Long signal: Slope {_currentSlope} > Avg {_avgSlope} + {DeviationMultiplier}*StdDev {_stdDevSlope}");
}
// Short signal: slope exceeds average + k*stddev in negative direction (slope is negative and we don't have a short position)
else if (_currentSlope < 0 &&
_currentSlope < _avgSlope - DeviationMultiplier * _stdDevSlope &&
Position >= 0)
{
// Cancel existing orders
CancelActiveOrders();
// Enter short position
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
LogInfo($"Short signal: Slope {_currentSlope} < Avg {_avgSlope} - {DeviationMultiplier}*StdDev {_stdDevSlope}");
}
// Exit conditions - when slope returns to average
if (Position > 0 && _currentSlope < _avgSlope)
{
// Exit long position
SellMarket(Math.Abs(Position));
LogInfo($"Exit long: Slope {_currentSlope} < Avg {_avgSlope}");
}
else if (Position < 0 && _currentSlope > _avgSlope)
{
// Exit short position
BuyMarket(Math.Abs(Position));
LogInfo($"Exit short: Slope {_currentSlope} > Avg {_avgSlope}");
}
}
// Store current MA value for next slope calculation
_prevMaValue = maValue;
}
private void CalculateStatistics()
{
// Reset statistics
_avgSlope = 0;
decimal sumSquaredDiffs = 0;
// Calculate average
for (int i = 0; i < LookbackPeriod; i++)
{
_avgSlope += _slopes[i];
}
_avgSlope /= LookbackPeriod;
// Calculate standard deviation
for (int i = 0; i < LookbackPeriod; i++)
{
decimal diff = _slopes[i] - _avgSlope;
sumSquaredDiffs += diff * diff;
}
_stdDevSlope = (decimal)Math.Sqrt((double)(sumSquaredDiffs / LookbackPeriod));
}
}
import clr
import math
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ma_slope_breakout_strategy(Strategy):
"""
MA slope breakout. Enters when slope exceeds avg + k*stddev.
"""
def __init__(self):
super(ma_slope_breakout_strategy, self).__init__()
self._ma_length = self.Param("MaLength", 20).SetDisplay("MA Length", "SMA period", "Indicators")
self._lookback = self.Param("LookbackPeriod", 20).SetDisplay("Lookback", "Slope stats period", "Strategy")
self._dev_mult = self.Param("DeviationMultiplier", 2.0).SetDisplay("Dev Mult", "Stddev multiplier", "Strategy")
self._sl_pct = self.Param("StopLossPercent", 2.0).SetDisplay("SL %", "Stop loss percent", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Timeframe", "General")
self._prev_ma = 0.0
self._slopes = None
self._current_index = 0
self._is_init = False
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ma_slope_breakout_strategy, self).OnReseted()
self._prev_ma = 0.0
self._slopes = [0.0] * int(self._lookback.Value)
self._current_index = 0
self._is_init = False
def OnStarted2(self, time):
super(ma_slope_breakout_strategy, self).OnStarted2(time)
lb = int(self._lookback.Value)
self._slopes = [0.0] * lb
self._current_index = 0
sma = SimpleMovingAverage()
sma.Length = self._ma_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
self.StartProtection(None, Unit(self._sl_pct.Value, UnitTypes.Percent))
def _process_candle(self, candle, ma_val):
if candle.State != CandleStates.Finished:
return
ma = float(ma_val)
if not self._is_init:
self._prev_ma = ma
self._is_init = True
return
current_slope = ma - self._prev_ma
lb = int(self._lookback.Value)
if self._slopes is None or len(self._slopes) != lb:
self._slopes = [0.0] * lb
self._current_index = 0
# Store slope in circular array
self._slopes[self._current_index] = current_slope
self._current_index = (self._current_index + 1) % lb
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_ma = ma
return
# Calculate statistics
avg_slope = sum(self._slopes) / lb
sum_sq = sum((s - avg_slope) ** 2 for s in self._slopes)
std_slope = math.sqrt(sum_sq / lb)
dm = float(self._dev_mult.Value)
if abs(avg_slope) > 0:
# Long signal
if current_slope > 0 and current_slope > avg_slope + dm * std_slope and self.Position <= 0:
self.CancelActiveOrders()
vol = self.Volume + Math.Abs(self.Position)
self.BuyMarket(vol)
# Short signal
elif current_slope < 0 and current_slope < avg_slope - dm * std_slope and self.Position >= 0:
self.CancelActiveOrders()
vol = self.Volume + Math.Abs(self.Position)
self.SellMarket(vol)
# Exit conditions
if self.Position > 0 and current_slope < avg_slope:
self.SellMarket(Math.Abs(self.Position))
elif self.Position < 0 and current_slope > avg_slope:
self.BuyMarket(Math.Abs(self.Position))
self._prev_ma = ma
def CreateClone(self):
return ma_slope_breakout_strategy()