在 GitHub 上查看
Envelope MA 空头策略
概述
Envelope MA 空头策略 是将 MetaTrader 专家顾问 EnvelopeMA.mq4(编号 9533)移植到 StockSharp 的 C# 实现。策略在 15 分钟蜡烛图上运行,只做空头方向。它使用高价的指数移动平均(EMA)生成包络线,同时计算两条基于低价的 EMA,并通过三组不同参数的抛物线 SAR 进行过滤。当价格回调至包络下半部分时,策略会在包络下轨附近挂出卖出止损单;订单成交后,使用固定的止损/止盈距离和指标条件管理仓位。
指标与信号
- 包络基线: 取蜡烛最高价的 EMA(
EnvelopePeriod,默认 280),通过 EnvelopeDeviation(默认 0.08%)生成上下轨,下轨作为挂单价格。
- 快 EMA: 针对蜡烛最低价计算的 EMA(
FastMaPeriod,默认 6),用于判断动能是否允许继续向下突破。
- 慢 EMA(滞后一根): 针对蜡烛最低价计算的 EMA(
SlowMaPeriod,默认 18),并使用前一根柱子的数值来模拟 MetaTrader 中的移位参数,用于进场和出场判断。
- 三条抛物线 SAR: 分别使用 0.03/0.5、0.015/0.6 和 0.02/0.2 的加速度参数。三条 SAR 同时位于价格上方时,才能触发基于指标的离场。
策略仅在蜡烛收盘时做出决策。当快 EMA、滞后慢 EMA 以及收盘价同时位于包络上下轨之间时,会在包络下轨位置提交卖出止损挂单。如果挂单在大约五根蜡烛的有效期内未成交,则自动撤销。
仓位管理
- 保护价格: 成交后根据预设的
StopLossPips 与 TakeProfitPips 计算止损和止盈价格,并在每根已完成的蜡烛上使用最高价/最低价近似追踪,模拟原始 EA 的行为。
- 指标离场: 当快慢 EMA 与收盘价全部低于入场价,三条 SAR 仍在价格上方,同时快 EMA 再次上穿滞后的慢 EMA 时,视为趋势反转,立即平空。
- 止损上移: 入场至少四根蜡烛后,如果这段时间的最高价比入场价低了至少三个最小价位,且收盘价跌破包络下轨,则将止损价调整到当前包络下轨。
风控
- 净值保护:
LiquidityThreshold(默认 0.58)表示账户净值与初始余额的下限比例。当净值比例跌破该值时,策略会平掉所有空头仓位并取消挂单。
- 挂单有效期: 每笔卖出止损单的有效期大约为五根监控蜡烛,超时未成交自动撤单,避免过期信号触发。
参数
| 参数 |
说明 |
默认值 |
CandleType |
使用的蜡烛类型/周期。 |
15 分钟蜡烛 |
EnvelopePeriod |
包络线使用的 EMA 周期。 |
280 |
EnvelopeDeviation |
包络线宽度(百分比)。 |
0.08 |
FastMaPeriod |
低价快 EMA 周期。 |
6 |
SlowMaPeriod |
低价慢 EMA 周期(向后移一根)。 |
18 |
StopLossPips |
入场价到止损的距离(点数)。 |
25 |
TakeProfitPips |
入场价到止盈的距离(点数)。 |
25 |
TradeVolume |
挂单及市价单的交易量。 |
1 |
LiquidityThreshold |
净值/余额比的最低值,低于该值会清空空头。 |
0.58 |
迁移说明
- 原 EA 中基于余额、保证金或 Counter-Pips 的手数算法,改为直接使用
TradeVolume 参数,符合 StockSharp 的下单模式。
- MetaTrader 的挂单到期时间在 StockSharp 中通过策略内部记录与检测实现,因为标准订单结构没有相同的字段。
- 止损与止盈触发通过蜡烛的高低价近似模拟盘中触发点,以保持与 MQL 实现对收盘价处理方式一致。
using System;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Envelope MA Short: EMA band reversion with ATR stops.
/// </summary>
public class EnvelopeMaShortStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _bandPercent;
private decimal _entryPrice;
public EnvelopeMaShortStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_emaLength = Param(nameof(EmaLength), 20)
.SetDisplay("EMA Length", "EMA period.", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period.", "Indicators");
_bandPercent = Param(nameof(BandPercent), 1.0m)
.SetDisplay("Band %", "Band width percent.", "Indicators");
}
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal BandPercent { get => _bandPercent.Value; set => _bandPercent.Value = value; }
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_entryPrice = 0;
var ema = new ExponentialMovingAverage { Length = EmaLength };
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ema, atr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null) { DrawCandles(area, subscription); DrawIndicator(area, ema); DrawOwnTrades(area); }
}
private void ProcessCandle(ICandleMessage candle, decimal emaVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished) return;
if (atrVal <= 0 || emaVal <= 0) return;
var close = candle.ClosePrice;
var factor = BandPercent / 100m;
var upper = emaVal * (1m + factor);
var lower = emaVal * (1m - factor);
if (Position > 0)
{
if (close >= emaVal || close <= _entryPrice - atrVal * 1.5m) { SellMarket(); _entryPrice = 0; }
}
else if (Position < 0)
{
if (close <= emaVal || close >= _entryPrice + atrVal * 1.5m) { BuyMarket(); _entryPrice = 0; }
}
if (Position == 0)
{
if (close < lower) { _entryPrice = close; BuyMarket(); }
else if (close > upper) { _entryPrice = close; SellMarket(); }
}
}
}
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.Strategies import Strategy
from StockSharp.Algo.Indicators import ExponentialMovingAverage, AverageTrueRange
class envelope_ma_short_strategy(Strategy):
def __init__(self):
super(envelope_ma_short_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe.", "General")
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Length", "EMA period.", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period.", "Indicators")
self._band_percent = self.Param("BandPercent", 1.0) \
.SetDisplay("Band %", "Band width percent.", "Indicators")
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def EmaLength(self):
return self._ema_length.Value
@property
def AtrLength(self):
return self._atr_length.Value
@property
def BandPercent(self):
return self._band_percent.Value
def OnStarted2(self, time):
super(envelope_ma_short_strategy, self).OnStarted2(time)
self._entry_price = 0.0
self._ema = ExponentialMovingAverage()
self._ema.Length = self.EmaLength
self._atr = AverageTrueRange()
self._atr.Length = self.AtrLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._ema, self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, ema_val, atr_val):
if candle.State != CandleStates.Finished:
return
ev = float(ema_val)
av = float(atr_val)
if av <= 0 or ev <= 0:
return
close = float(candle.ClosePrice)
factor = float(self.BandPercent) / 100.0
upper = ev * (1.0 + factor)
lower = ev * (1.0 - factor)
if self.Position > 0:
if close >= ev or close <= self._entry_price - av * 1.5:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if close <= ev or close >= self._entry_price + av * 1.5:
self.BuyMarket()
self._entry_price = 0.0
if self.Position == 0:
if close < lower:
self._entry_price = close
self.BuyMarket()
elif close > upper:
self._entry_price = close
self.SellMarket()
def OnReseted(self):
super(envelope_ma_short_strategy, self).OnReseted()
self._entry_price = 0.0
def CreateClone(self):
return envelope_ma_short_strategy()