DNSE VN301 SMA 与 EMA 交叉策略
该策略通过15周期EMA与60周期SMA的交叉交易VN301指数,并在收盘前平仓,采用百分比止损限制亏损。
测试显示年化收益约为20%,在VN30期货上表现最佳。
当EMA15上穿SMA60且价格位于EMA之上时做多;下穿且价格在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()