在 GitHub 上查看
虚拟移动止损 Level1 策略
概述
虚拟移动止损策略 是 MetaTrader 专家顾问 Virtual Trailing Stop.mq5(MQL ID 21362)的 C# 版本。原始 EA 只负责管理已经存在的仓位的止损与止盈。本策略在 StockSharp 高级 API 上重现了同样的逻辑:实时监听买一/卖一价格,并在触发止损、止盈或追踪止损条件时通过市价单平仓。
与开仓型策略不同,本实现永远不会主动开立新头寸。它适合与其他自动化开仓模块或人工交易结合使用,在 StockSharp 环境中复制 MetaTrader 风格的“虚拟”移动止损。
交易逻辑
- Level1 行情 – 订阅 level1 数据并持续保存最新的买价和卖价。
- 点值换算 – 用户输入均以“点”(pip) 表示。策略将其乘以
PriceStep,对于 3 或 5 位小数的外汇品种额外乘以 10,以匹配 MetaTrader 对 pip 的定义。
- 止损检查 – 多头:若买价跌破
开仓价 − 止损;空头:若卖价升破 开仓价 + 止损,立即平仓。
- 止盈检查 – 多头:若买价升破
开仓价 + 止盈;空头:若卖价跌破 开仓价 − 止盈,立即平仓。
- 追踪启动 – 当浮盈达到
TrailingStart 点时,建立追踪止损水平(多头:买价 − TrailingStop,空头:卖价 + TrailingStop)。
- 追踪更新 – 每当浮盈至少增加
TrailingStep 点时,追踪价格随之移动;将该参数设为 0 表示每个有利跳动都会更新。
- 追踪离场 – 当价格触及追踪价并且交易仍为盈利状态时(对应源代码中的
Profit()>0 判断),立即平仓。
策略不会挂出真正的止损/止盈委托,所有离场均通过市价单完成,以保持“虚拟”止损的概念。
参数
| 参数 |
说明 |
默认值 |
StopLossPips |
止损距离(pip)。设置为 0 可关闭硬止损。 |
0 |
TakeProfitPips |
止盈距离(pip)。设置为 0 可关闭止盈。 |
0 |
TrailingStopPips |
当前价格与追踪价之间的距离(pip)。 |
5 |
TrailingStartPips |
启动追踪所需的最小浮盈(pip)。 |
5 |
TrailingStepPips |
每次移动追踪价所需的最小增幅(pip)。设为 0 表示连续追踪。 |
1 |
所有参数均基于 StrategyParam 实现,可用于优化。
实现细节
- 仅依赖 level1 数据 (
DataType.Level1),不创建 MetaTrader 式的图形对象。
- 点值换算依赖
Security.PriceStep 与 Security.Decimals,若交易所未提供这些元数据则退化为点值 1。
- 多头与空头分别维护独立的追踪价格,保证对称性。
- 原 EA 在测试模式下会自动开多空测试仓位,StockSharp 版本由于采用净头寸模型,故省略该功能。
使用建议
- 绑定到已经持仓或将由其他模块建仓的证券/投资组合上。
- 与人工交易或其他策略的入场逻辑组合,便于在 Designer、Shell 或 Runner 中复现 MetaTrader 式的仓位管理。
- 交易非外汇资产时,应根据最小跳动价调整 pip 参数;例如将
TrailingStopPips = 1 可以实现一步价差的追踪。
文件说明
CS/VirtualTrailingStopLevel1Strategy.cs – 策略源码。
README.md、README_zh.md、README_ru.md – 多语言文档。
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>
/// Virtual Trailing Stop Level1 strategy (simplified). Uses EMA with
/// percentage-based trailing stop for position management.
/// </summary>
public class VirtualTrailingStopLevel1Strategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<decimal> _trailingPercent;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
public decimal TrailingPercent
{
get => _trailingPercent.Value;
set => _trailingPercent.Value = value;
}
public VirtualTrailingStopLevel1Strategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
_emaLength = Param(nameof(EmaLength), 15)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period", "Indicators");
_trailingPercent = Param(nameof(TrailingPercent), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Trailing %", "Trailing stop percent", "Risk");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaLength };
decimal highSinceEntry = 0;
decimal lowSinceEntry = decimal.MaxValue;
decimal prevClose = 0;
decimal prevEma = 0;
var hasPrev = false;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, (ICandleMessage candle, decimal emaVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!hasPrev)
{
prevClose = candle.ClosePrice;
prevEma = emaVal;
hasPrev = true;
return;
}
if (!IsFormedAndOnlineAndAllowTrading())
{
prevClose = candle.ClosePrice;
prevEma = emaVal;
return;
}
var close = candle.ClosePrice;
// Trailing stop management
if (Position > 0)
{
if (candle.HighPrice > highSinceEntry) highSinceEntry = candle.HighPrice;
if (close < highSinceEntry * (1m - TrailingPercent / 100m))
{
SellMarket();
highSinceEntry = 0;
lowSinceEntry = decimal.MaxValue;
return;
}
}
else if (Position < 0)
{
if (candle.LowPrice < lowSinceEntry) lowSinceEntry = candle.LowPrice;
if (close > lowSinceEntry * (1m + TrailingPercent / 100m))
{
BuyMarket();
highSinceEntry = 0;
lowSinceEntry = decimal.MaxValue;
return;
}
}
// Entry based on EMA
var bullishCross = prevClose <= prevEma && close > emaVal;
var bearishCross = prevClose >= prevEma && close < emaVal;
if (bullishCross && Position <= 0)
{
BuyMarket();
highSinceEntry = candle.HighPrice;
lowSinceEntry = decimal.MaxValue;
}
else if (bearishCross && Position >= 0)
{
SellMarket();
lowSinceEntry = candle.LowPrice;
highSinceEntry = 0;
}
prevClose = close;
prevEma = emaVal;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
}
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 virtual_trailing_stop_level1_strategy(Strategy):
def __init__(self):
super(virtual_trailing_stop_level1_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candles", "General")
self._ema_length = self.Param("EmaLength", 15) \
.SetDisplay("EMA Length", "EMA period", "Indicators")
self._trailing_percent = self.Param("TrailingPercent", 1.5) \
.SetDisplay("Trailing %", "Trailing stop percent", "Risk")
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@property
def EmaLength(self):
return self._ema_length.Value
@property
def TrailingPercent(self):
return self._trailing_percent.Value
def OnReseted(self):
super(virtual_trailing_stop_level1_strategy, self).OnReseted()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(virtual_trailing_stop_level1_strategy, self).OnStarted2(time)
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
ema = ExponentialMovingAverage()
ema.Length = self.EmaLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, ema_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
ev = float(ema_value)
if not self._has_prev:
self._prev_close = close
self._prev_ema = ev
self._has_prev = True
return
if self.Position > 0:
if high > self._high_since_entry:
self._high_since_entry = high
if close < self._high_since_entry * (1.0 - self.TrailingPercent / 100.0):
self.SellMarket()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = close
self._prev_ema = ev
return
elif self.Position < 0:
if low < self._low_since_entry:
self._low_since_entry = low
if close > self._low_since_entry * (1.0 + self.TrailingPercent / 100.0):
self.BuyMarket()
self._high_since_entry = 0.0
self._low_since_entry = 1e18
self._prev_close = close
self._prev_ema = ev
return
bullish_cross = self._prev_close <= self._prev_ema and close > ev
bearish_cross = self._prev_close >= self._prev_ema and close < ev
if bullish_cross and self.Position <= 0:
self.BuyMarket()
self._high_since_entry = high
self._low_since_entry = 1e18
elif bearish_cross and self.Position >= 0:
self.SellMarket()
self._low_since_entry = low
self._high_since_entry = 0.0
self._prev_close = close
self._prev_ema = ev
def CreateClone(self):
return virtual_trailing_stop_level1_strategy()