Стратегия EMA Prediction
Стратегия основана на индикаторе EMA Prediction, который формирует сигналы при пересечении быстрых и медленных экспоненциальных средних на свече, подтверждающей направление.
Открывает длинную позицию при пересечении быстрой EMA выше медленной на бычьей свече и закрывает все короткие позиции. Открывает короткую позицию при пересечении быстрой EMA ниже медленной на медвежьей свече и закрывает все длинные позиции.
Подробности
- Условия входа:
- Лонг: быстрая EMA пересекает медленную снизу вверх и свеча бычья.
- Шорт: быстрая EMA пересекает медленную сверху вниз и свеча медвежья.
- Лонг/Шорт: Оба направления
- Условия выхода: Противоположный сигнал
- Стопы: Фиксированный тейк-профит и стоп-лосс
- Значения по умолчанию:
CandleType= 6-часовые свечиFastPeriod= 1SlowPeriod= 2StopLossTicks= 1000TakeProfitTicks= 2000
- Фильтры:
- Категория: Пересечение скользящих средних
- Направление: Оба
- Индикаторы: EMA
- Стопы: Тейк-профит и стоп-лосс
- Сложность: Базовая
- Таймфрейм: 6 часов
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Strategy based on EMA crossover prediction indicator.
/// </summary>
public class EmaPredictionStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<decimal> _takeProfitTicks;
private readonly StrategyParam<decimal> _stopLossTicks;
private decimal _prevFast;
private decimal _prevSlow;
private bool _initialized;
/// <summary>
/// Candle type for indicators.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Fast EMA period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Take profit in ticks.
/// </summary>
public decimal TakeProfitTicks
{
get => _takeProfitTicks.Value;
set => _takeProfitTicks.Value = value;
}
/// <summary>
/// Stop loss in ticks.
/// </summary>
public decimal StopLossTicks
{
get => _stopLossTicks.Value;
set => _stopLossTicks.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public EmaPredictionStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for calculations", "General");
_fastPeriod = Param(nameof(FastPeriod), 5)
.SetDisplay("Fast EMA Period", "Period of fast EMA", "Indicator")
.SetGreaterThanZero();
_slowPeriod = Param(nameof(SlowPeriod), 20)
.SetDisplay("Slow EMA Period", "Period of slow EMA", "Indicator")
.SetGreaterThanZero();
_takeProfitTicks = Param(nameof(TakeProfitTicks), 2000m)
.SetDisplay("Take Profit Ticks", "Take profit in ticks", "Risk Management")
.SetNotNegative();
_stopLossTicks = Param(nameof(StopLossTicks), 1000m)
.SetDisplay("Stop Loss Ticks", "Stop loss in ticks", "Risk Management")
.SetNotNegative();
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = default;
_prevSlow = default;
_initialized = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fast = new ExponentialMovingAverage { Length = FastPeriod };
var slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, ProcessCandle)
.Start();
var step = Security.PriceStep ?? 1m;
StartProtection(
new Unit(StopLossTicks * step, UnitTypes.Absolute),
new Unit(TakeProfitTicks * step, UnitTypes.Absolute));
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (!_initialized)
{
_prevFast = fast;
_prevSlow = slow;
_initialized = true;
return;
}
var bullish = _prevFast < _prevSlow && fast > slow && candle.OpenPrice < candle.ClosePrice;
var bearish = _prevFast > _prevSlow && fast < slow && candle.OpenPrice > candle.ClosePrice;
if (bullish && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
else if (bearish && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevFast = fast;
_prevSlow = slow;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_prediction_strategy(Strategy):
def __init__(self):
super(ema_prediction_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for calculations", "General")
self._fast_period = self.Param("FastPeriod", 5) \
.SetDisplay("Fast EMA Period", "Period of fast EMA", "Indicator")
self._slow_period = self.Param("SlowPeriod", 20) \
.SetDisplay("Slow EMA Period", "Period of slow EMA", "Indicator")
self._take_profit_ticks = self.Param("TakeProfitTicks", 2000.0) \
.SetDisplay("Take Profit Ticks", "Take profit in ticks", "Risk Management")
self._stop_loss_ticks = self.Param("StopLossTicks", 1000.0) \
.SetDisplay("Stop Loss Ticks", "Stop loss in ticks", "Risk Management")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def FastPeriod(self):
return self._fast_period.Value
@FastPeriod.setter
def FastPeriod(self, value):
self._fast_period.Value = value
@property
def SlowPeriod(self):
return self._slow_period.Value
@SlowPeriod.setter
def SlowPeriod(self, value):
self._slow_period.Value = value
@property
def TakeProfitTicks(self):
return self._take_profit_ticks.Value
@TakeProfitTicks.setter
def TakeProfitTicks(self, value):
self._take_profit_ticks.Value = value
@property
def StopLossTicks(self):
return self._stop_loss_ticks.Value
@StopLossTicks.setter
def StopLossTicks(self, value):
self._stop_loss_ticks.Value = value
def OnStarted2(self, time):
super(ema_prediction_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self.FastPeriod
slow = ExponentialMovingAverage()
slow.Length = self.SlowPeriod
self.SubscribeCandles(self.CandleType) \
.Bind(fast, slow, self.ProcessCandle) \
.Start()
ps = self.Security.PriceStep
step = float(ps) if ps is not None else 1.0
self.StartProtection(
stopLoss=Unit(self.StopLossTicks * step, UnitTypes.Absolute),
takeProfit=Unit(self.TakeProfitTicks * step, UnitTypes.Absolute)
)
def ProcessCandle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast = float(fast_value)
slow = float(slow_value)
if not self._initialized:
self._prev_fast = fast
self._prev_slow = slow
self._initialized = True
return
bullish = self._prev_fast < self._prev_slow and fast > slow and float(candle.OpenPrice) < float(candle.ClosePrice)
bearish = self._prev_fast > self._prev_slow and fast < slow and float(candle.OpenPrice) > float(candle.ClosePrice)
if bullish and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif bearish and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_fast = fast
self._prev_slow = slow
def OnReseted(self):
super(ema_prediction_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
def CreateClone(self):
return ema_prediction_strategy()