MA2CCI
Стратегия пересечения скользящих средних с подтверждением CCI. Использует ATR для стоп-лосса.
Подробности
- Критерии входа:
- Лонг при пересечении быстрой SMA выше медленной и переходе CCI выше 0.
- Шорт при пересечении быстрой SMA ниже медленной и переходе CCI ниже 0.
- Лонг/Шорт: Оба направления.
- Критерии выхода: Обратное пересечение или стоп на расстоянии 1 ATR от входа.
- Стопы: Стоп-лосс по ATR от цены входа.
- Значения по умолчанию:
FastMaPeriod= 4SlowMaPeriod= 8CciPeriod= 4AtrPeriod= 4CandleType= 1 минута
- Фильтры:
- Категория: Следование тренду
- Направление: Оба
- Индикаторы: SMA, CCI, ATR
- Стопы: ATR
- Сложность: Новичок
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// MA2CCI strategy combines two EMAs with CCI and StdDev-based stop.
/// </summary>
public class MA2CCIStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastMaPeriod;
private readonly StrategyParam<int> _slowMaPeriod;
private readonly StrategyParam<int> _cciPeriod;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _prevCci;
private bool _hasPrev;
private decimal _stopPrice;
private decimal _entryPrice;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int FastMaPeriod { get => _fastMaPeriod.Value; set => _fastMaPeriod.Value = value; }
public int SlowMaPeriod { get => _slowMaPeriod.Value; set => _slowMaPeriod.Value = value; }
public int CciPeriod { get => _cciPeriod.Value; set => _cciPeriod.Value = value; }
public MA2CCIStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_fastMaPeriod = Param(nameof(FastMaPeriod), 10)
.SetGreaterThanZero()
.SetDisplay("Fast MA", "Fast moving average period", "Parameters");
_slowMaPeriod = Param(nameof(SlowMaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Slow MA", "Slow moving average period", "Parameters");
_cciPeriod = Param(nameof(CciPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "Commodity Channel Index period", "Parameters");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevSlow = 0;
_prevCci = 0;
_hasPrev = false;
_stopPrice = 0;
_entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastMa = new ExponentialMovingAverage { Length = FastMaPeriod };
var slowMa = new ExponentialMovingAverage { Length = SlowMaPeriod };
var cci = new CommodityChannelIndex { Length = CciPeriod };
var stdDev = new StandardDeviation { Length = 14 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastMa, slowMa, cci, stdDev, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastMa);
DrawIndicator(area, slowMa);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal cci, decimal stdVal)
{
if (candle.State != CandleStates.Finished)
return;
// Check stop loss
if (_stopPrice > 0)
{
if (Position > 0 && candle.LowPrice <= _stopPrice)
{
SellMarket();
_stopPrice = 0;
_entryPrice = 0;
}
else if (Position < 0 && candle.HighPrice >= _stopPrice)
{
BuyMarket();
_stopPrice = 0;
_entryPrice = 0;
}
}
if (!_hasPrev)
{
_prevFast = fast;
_prevSlow = slow;
_prevCci = cci;
_hasPrev = true;
return;
}
// Entry signals: MA crossover
if (fast > slow && _prevFast <= _prevSlow && Position <= 0)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = candle.ClosePrice - stdVal * 2;
}
else if (fast < slow && _prevFast >= _prevSlow && Position >= 0)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = candle.ClosePrice + stdVal * 2;
}
_prevFast = fast;
_prevSlow = slow;
_prevCci = cci;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import CommodityChannelIndex, ExponentialMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class ma2_cci_strategy(Strategy):
def __init__(self):
super(ma2_cci_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._fast_ma_period = self.Param("FastMaPeriod", 10) \
.SetDisplay("Fast MA", "Fast moving average period", "Parameters")
self._slow_ma_period = self.Param("SlowMaPeriod", 20) \
.SetDisplay("Slow MA", "Slow moving average period", "Parameters")
self._cci_period = self.Param("CciPeriod", 14) \
.SetDisplay("CCI Period", "Commodity Channel Index period", "Parameters")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_cci = 0.0
self._has_prev = False
self._stop_price = 0.0
self._entry_price = 0.0
@property
def candle_type(self):
return self._candle_type.Value
@property
def fast_ma_period(self):
return self._fast_ma_period.Value
@property
def slow_ma_period(self):
return self._slow_ma_period.Value
@property
def cci_period(self):
return self._cci_period.Value
def OnReseted(self):
super(ma2_cci_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_cci = 0.0
self._has_prev = False
self._stop_price = 0.0
self._entry_price = 0.0
def OnStarted2(self, time):
super(ma2_cci_strategy, self).OnStarted2(time)
fast_ma = ExponentialMovingAverage()
fast_ma.Length = self.fast_ma_period
slow_ma = ExponentialMovingAverage()
slow_ma.Length = self.slow_ma_period
cci = CommodityChannelIndex()
cci.Length = self.cci_period
std_dev = StandardDeviation()
std_dev.Length = 14
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ma, slow_ma, cci, std_dev, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ma)
self.DrawIndicator(area, slow_ma)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow, cci, std_val):
if candle.State != CandleStates.Finished:
return
# Check stop loss
if self._stop_price > 0:
if self.Position > 0 and candle.LowPrice <= self._stop_price:
self.SellMarket()
self._stop_price = 0
self._entry_price = 0
elif self.Position < 0 and candle.HighPrice >= self._stop_price:
self.BuyMarket()
self._stop_price = 0
self._entry_price = 0
if not self._has_prev:
self._prev_fast = fast
self._prev_slow = slow
self._prev_cci = cci
self._has_prev = True
return
# Entry signals: MA crossover
if fast > slow and self._prev_fast <= self._prev_slow and self.Position <= 0:
self.BuyMarket()
self._entry_price = candle.ClosePrice
self._stop_price = candle.ClosePrice - std_val * 2
elif fast < slow and self._prev_fast >= self._prev_slow and self.Position >= 0:
self.SellMarket()
self._entry_price = candle.ClosePrice
self._stop_price = candle.ClosePrice + std_val * 2
self._prev_fast = fast
self._prev_slow = slow
self._prev_cci = cci
def CreateClone(self):
return ma2_cci_strategy()