EMA Sticker 策略
该策略使用指数移动平均线 (EMA) 追踪短期趋势。当收盘价上穿 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()