Стратегия DNSE VN301 SMA & EMA Cross
Стратегия торгует индекс VN301 на пересечении EMA(15) и SMA(60). Перед завершением торговой сессии позиции закрываются, а процентный стоп ограничивает убыток.
Тесты показывают среднегодовую доходность около 20%. Лучше всего работает на фьючерсах VN30.
Лонг открывается при пересечении EMA15 выше SMA60 и цене выше EMA. Шорт открывается при обратном пересечении. Позиции закрываются при обратном сигнале, достижении максимального убытка или по времени окончания сессии.
Детали
- Условия входа:
- Покупка: EMA15 пересекает SMA60 снизу вверх и цена ≥ EMA15 до окончания сессии.
- Продажа: EMA15 пересекает SMA60 сверху вниз и цена ≤ EMA15.
- Длинные/короткие: Оба направления.
- Условия выхода:
- Обратное пересечение, максимальный убыток или окончание сессии.
- Стопы: Да, процентный лимит убытка.
- Фильтры:
- Время окончания сессии.
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>
/// SMA and EMA crossover strategy for VN301 index.
/// </summary>
public class DnseVn301SmaEmaCrossStrategy : Strategy
{
private readonly StrategyParam<int> _sessionCloseHour;
private readonly StrategyParam<int> _sessionCloseMinute;
private readonly StrategyParam<int> _minutesBeforeClose;
private readonly StrategyParam<decimal> _maxLossPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _prevEma15;
private decimal _prevSma60;
public int SessionCloseHour { get => _sessionCloseHour.Value; set => _sessionCloseHour.Value = value; }
public int SessionCloseMinute { get => _sessionCloseMinute.Value; set => _sessionCloseMinute.Value = value; }
public int MinutesBeforeClose { get => _minutesBeforeClose.Value; set => _minutesBeforeClose.Value = value; }
public decimal MaxLossPercent { get => _maxLossPercent.Value; set => _maxLossPercent.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public DnseVn301SmaEmaCrossStrategy()
{
_sessionCloseHour = Param(nameof(SessionCloseHour), 14)
.SetDisplay("Close Hour", "Session close hour", "General");
_sessionCloseMinute = Param(nameof(SessionCloseMinute), 30)
.SetDisplay("Close Minute", "Session close minute", "General");
_minutesBeforeClose = Param(nameof(MinutesBeforeClose), 5)
.SetDisplay("Minutes Before Close", "Exit minutes before close", "General");
_maxLossPercent = Param(nameof(MaxLossPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Max Loss %", "Stop loss percentage", "Risk");
_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)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0;
_prevEma15 = 0;
_prevSma60 = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema15 = new ExponentialMovingAverage { Length = 15 };
var sma60 = new SimpleMovingAverage { Length = 60 };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ema15, sma60, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal ema15, decimal sma60)
{
if (candle.State != CandleStates.Finished)
return;
var crossUp = ema15 > sma60 && _prevEma15 <= _prevSma60;
var crossDown = ema15 < sma60 && _prevEma15 >= _prevSma60;
_prevEma15 = ema15;
_prevSma60 = sma60;
if (crossUp && Position <= 0)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
}
else if (crossDown && Position >= 0)
{
SellMarket();
_entryPrice = candle.ClosePrice;
}
if (Position > 0)
{
if (crossDown || candle.ClosePrice <= _entryPrice * (1 - MaxLossPercent / 100m))
SellMarket();
}
else if (Position < 0)
{
if (crossUp || candle.ClosePrice >= _entryPrice * (1 + MaxLossPercent / 100m))
BuyMarket();
}
}
private void ClosePosition()
{
if (Position > 0)
SellMarket();
else if (Position < 0)
BuyMarket();
}
}
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, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class dnse_vn301_sma_ema_cross_strategy(Strategy):
def __init__(self):
super(dnse_vn301_sma_ema_cross_strategy, self).__init__()
self._session_close_hour = self.Param("SessionCloseHour", 14) \
.SetDisplay("Close Hour", "Session close hour", "General")
self._session_close_minute = self.Param("SessionCloseMinute", 30) \
.SetDisplay("Close Minute", "Session close minute", "General")
self._minutes_before_close = self.Param("MinutesBeforeClose", 5) \
.SetDisplay("Minutes Before Close", "Exit minutes before close", "General")
self._max_loss_percent = self.Param("MaxLossPercent", 2.0) \
.SetDisplay("Max Loss %", "Stop loss percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._entry_price = 0.0
self._prev_ema15 = 0.0
self._prev_sma60 = 0.0
@property
def session_close_hour(self):
return self._session_close_hour.Value
@property
def session_close_minute(self):
return self._session_close_minute.Value
@property
def minutes_before_close(self):
return self._minutes_before_close.Value
@property
def max_loss_percent(self):
return self._max_loss_percent.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(dnse_vn301_sma_ema_cross_strategy, self).OnReseted()
self._entry_price = 0.0
self._prev_ema15 = 0.0
self._prev_sma60 = 0.0
def OnStarted2(self, time):
super(dnse_vn301_sma_ema_cross_strategy, self).OnStarted2(time)
ema15 = ExponentialMovingAverage()
ema15.Length = 15
sma60 = SimpleMovingAverage()
sma60.Length = 60
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema15, sma60, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema15, sma60):
if candle.State != CandleStates.Finished:
return
cross_up = ema15 > sma60 and self._prev_ema15 <= self._prev_sma60
cross_down = ema15 < sma60 and self._prev_ema15 >= self._prev_sma60
self._prev_ema15 = ema15
self._prev_sma60 = sma60
if cross_up and self.Position <= 0:
self.BuyMarket()
self._entry_price = candle.ClosePrice
elif cross_down and self.Position >= 0:
self.SellMarket()
self._entry_price = candle.ClosePrice
if self.Position > 0:
if cross_down or candle.ClosePrice <= self._entry_price * (1 - self.max_loss_percent / 100):
self.SellMarket()
elif self.Position < 0:
if cross_up or candle.ClosePrice >= self._entry_price * (1 + self.max_loss_percent / 100):
self.BuyMarket()
def close_position(self):
if self.Position > 0:
self.SellMarket()
elif self.Position < 0:
self.BuyMarket()
def CreateClone(self):
return dnse_vn301_sma_ema_cross_strategy()