Эта стратегия использует экспоненциальное скользящее среднее (EMA) для отслеживания краткосрочных трендов. Длинная позиция открывается при пересечении цены закрытия выше EMA, короткая — при пересечении ниже. Фиксированные уровни стоп‑лосса и тейк‑профита помогают управлять риском.
Детали
Условия входа:
Покупка: Close > EMA.
Продажа: Close < EMA.
Направление: Обе стороны.
Условия выхода:
Противоположный сигнал или достижение заданных стоп‑уровней.
Стопы: Да, опциональный стоп‑лосс и тейк‑профит в ценовых единицах.
Значения по умолчанию:
Период EMA = 5.
Стоп‑лосс = 0.001.
Тейк‑профит = 0.001.
Фильтры:
Категория: Следование тренду
Направление: Обе
Индикаторы: Один
Стопы: Да
Сложность: Простая
Таймфрейм: Краткосрочный
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>
/// Simple EMA-based trend following strategy.
/// Buys when price crosses above EMA, sells on opposite cross.
/// </summary>
public class EmaStickerStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
private bool _wasAbove;
private bool _hasPrev;
public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EmaStickerStrategy()
{
_maPeriod = Param(nameof(MaPeriod), 10)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "Length of the EMA", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_wasAbove = false;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = MaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
var isAbove = candle.ClosePrice > emaValue;
if (!_hasPrev)
{
_wasAbove = isAbove;
_hasPrev = true;
return;
}
// Cross above EMA -> buy
if (isAbove && !_wasAbove)
{
if (Position < 0)
BuyMarket();
if (Position <= 0)
BuyMarket();
}
// Cross below EMA -> sell
else if (!isAbove && _wasAbove)
{
if (Position > 0)
SellMarket();
if (Position >= 0)
SellMarket();
}
_wasAbove = isAbove;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_sticker_strategy(Strategy):
def __init__(self):
super(ema_sticker_strategy, self).__init__()
self._ma_period = self.Param("MaPeriod", 10) \
.SetDisplay("EMA Period", "Length of the EMA", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._was_above = False
self._has_prev = False
@property
def ma_period(self):
return self._ma_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_sticker_strategy, self).OnReseted()
self._was_above = False
self._has_prev = False
def OnStarted2(self, time):
super(ema_sticker_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ma_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_value):
if candle.State != CandleStates.Finished:
return
is_above = candle.ClosePrice > ema_value
if not self._has_prev:
self._was_above = is_above
self._has_prev = True
return
# Cross above EMA -> buy
if is_above and not self._was_above:
if self.Position < 0:
self.BuyMarket()
if self.Position <= 0:
self.BuyMarket()
# Cross below EMA -> sell
elif not is_above and self._was_above:
if self.Position > 0:
self.SellMarket()
if self.Position >= 0:
self.SellMarket()
self._was_above = is_above
def CreateClone(self):
return ema_sticker_strategy()