MartingailExpert v1.0 Stochastic 策略(C#)
概述
MartingailExpert v1.0 Stochastic 策略将 MetaTrader 4 顾问 MartingailExpert_v1_0_Stochastic.mq4
完整迁移到 StockSharp 高级 API。策略读取随机指标的 %K 与 %D 线,并在上一根已结束 K 线的数值
满足阈值条件时开仓。首单建立后,会按照马丁格尔规则追加同向市场单,使最新成交价成为整
个仓位簇的统一止盈参考。
实现过程中使用了烛线订阅、BindEx 指标绑定以及 BuyMarket/SellMarket 等高层接口;源码
中的注释全部改为英文,并严格遵守项目要求的制表符缩进。
交易逻辑
1. 入场信号
- 随机指标参数为
Length = KPeriod、K.Length = Slowing、D.Length = DPeriod,仅处理已完成的 K 线。 - 为了复现 MQL 函数
iStochastic(..., shift = 1),策略缓存上一根柱子的 %K 与 %D 值。若K_prev > D_prev且D_prev > ZoneBuy,则开多;若K_prev < D_prev且D_prev < ZoneSell,则开空。 - 首次建仓使用
BuyVolume或SellVolume,并清除相反方向的马丁格尔状态,避免混合多空序列。
2. 马丁格尔加仓
- 当
_buyOrderCount或_sellOrderCount大于零时,策略监测烛线的最低价(多头)或最高价(空头)。 - 加仓间距
StepMode = 0:价格必须相对上一次成交逆向移动StepPoints × PointSize。StepMode = 1:采用StepPoints + max(0, 2 × ordersCount − 2)的点数距离,与 MQL 中step + OrdersTotal*2 - 2的写法保持一致,并乘以根据Security.PriceStep推算的点值(对 3/5 位 小数的外汇品种会额外乘以 10)。
- 当触发价被穿越时,按照
上一单手数 × Multiplier发送新的市价单。手数会根据VolumeStep归一化,并在超出VolumeMax或低于VolumeMin时自动截断。 - 每次加仓后,共用的止盈价会调整为
lastEntryPrice ± ProfitFactorPoints × PointSize × orderCount,正负号由方向决定。
3. 止盈控制
- 一旦烛线触及目标价(多头看
High,空头看Low),策略会评估相对加权平均开仓价的收益, 相当于原版 EA 中对OrderProfit()的正收益检查。 - 若估算结果为正,就调用
SellMarket(Math.Abs(Position))或BuyMarket(Math.Abs(Position))平掉整组仓位,并重置所有马丁格尔状态。 - 如果仓位被外部因素关闭(人工操作、爆仓等),下一根
Position == 0的烛线会自动清除缓存, 保持内部状态一致。
4. 其它实现细节
- 点值来源于
Security.PriceStep;若步长等于0.00001或0.001,则乘以 10 来匹配 MetaTrader 对 “Point” 的定义。 - 在
OnStarted中调用一次StartProtection(),以启用平台的标准保护机制。 - 策略会在独立图表区域绘制烛线、随机指标和自身成交,方便回测或实时监控。
参数
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
StepPoints |
decimal | 25 |
价格逆向移动多少点后触发加仓。 |
StepMode |
int | 0 |
0:固定距离;1:固定距离 + 2 × ordersCount − 2 点。 |
ProfitFactorPoints |
decimal | 10 |
每张订单贡献的止盈点数,用于计算整组仓位的目标价。 |
Multiplier |
decimal | 1.5 |
每次加仓的手数乘数。 |
BuyVolume |
decimal | 0.01 |
首笔多单的手数。 |
SellVolume |
decimal | 0.01 |
首笔空单的手数。 |
KPeriod |
int | 200 |
随机指标 %K 的基础周期。 |
DPeriod |
int | 20 |
%D 线的平滑周期。 |
Slowing |
int | 20 |
%K 的附加平滑系数(MetaTrader slowing 参数)。 |
ZoneBuy |
decimal | 50 |
允许做多时 %D 必须高于的阈值。 |
ZoneSell |
decimal | 50 |
允许做空时 %D 必须低于的阈值。 |
CandleType |
DataType |
5 分钟 |
计算所使用的蜡烛类型。 |
目录结构
API/3991/
├── CS/
│ └── MartingailExpertV10StochasticStrategy.cs
├── README.md
├── README_zh.md
└── README_ru.md
根据任务要求,本目录暂不提供 Python 版本。
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>
/// Conversion of the "MartingailExpert v1.0 Stochastic" MetaTrader expert advisor.
/// Implements stochastic based entries with martingale averaging and cluster take profits.
/// </summary>
public class MartingailExpertV10StochasticStrategy : Strategy
{
private readonly StrategyParam<decimal> _stepPoints;
private readonly StrategyParam<int> _stepMode;
private readonly StrategyParam<decimal> _profitFactorPoints;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<int> _kPeriod;
private readonly StrategyParam<int> _dPeriod;
private readonly StrategyParam<decimal> _zoneBuy;
private readonly StrategyParam<decimal> _zoneSell;
private readonly StrategyParam<DataType> _candleType;
private StochasticOscillator _stochastic;
private decimal _pointSize;
private decimal? _prevK;
private decimal? _prevD;
private decimal _buyLastPrice;
private decimal _buyLastVolume;
private decimal _buyTotalVolume;
private decimal _buyWeightedSum;
private int _buyOrderCount;
private decimal _buyTakeProfit;
private decimal _sellLastPrice;
private decimal _sellLastVolume;
private decimal _sellTotalVolume;
private decimal _sellWeightedSum;
private int _sellOrderCount;
private decimal _sellTakeProfit;
/// <summary>
/// Distance in points that price has to travel against the latest entry before adding.
/// </summary>
public decimal StepPoints
{
get => _stepPoints.Value;
set => _stepPoints.Value = value;
}
/// <summary>
/// Step mode: 0 - fixed, 1 - fixed plus extra points per filled order.
/// </summary>
public int StepMode
{
get => _stepMode.Value;
set => _stepMode.Value = value;
}
/// <summary>
/// Profit target in points applied to every open order.
/// </summary>
public decimal ProfitFactorPoints
{
get => _profitFactorPoints.Value;
set => _profitFactorPoints.Value = value;
}
/// <summary>
/// Martingale multiplier for the next averaging order.
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Stochastic %K lookback period.
/// </summary>
public int KPeriod
{
get => _kPeriod.Value;
set => _kPeriod.Value = value;
}
/// <summary>
/// Stochastic %D smoothing length.
/// </summary>
public int DPeriod
{
get => _dPeriod.Value;
set => _dPeriod.Value = value;
}
/// <summary>
/// Minimum stochastic level that confirms long setups.
/// </summary>
public decimal ZoneBuy
{
get => _zoneBuy.Value;
set => _zoneBuy.Value = value;
}
/// <summary>
/// Maximum stochastic level that confirms short setups.
/// </summary>
public decimal ZoneSell
{
get => _zoneSell.Value;
set => _zoneSell.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="MartingailExpertV10StochasticStrategy"/>.
/// </summary>
public MartingailExpertV10StochasticStrategy()
{
_stepPoints = Param(nameof(StepPoints), 500m)
.SetGreaterThanZero()
.SetDisplay("Step", "Price step in points before averaging", "Martingale");
_stepMode = Param(nameof(StepMode), 0)
.SetDisplay("Step Mode", "0 - fixed step, 1 - step plus extra points per order", "Martingale");
_profitFactorPoints = Param(nameof(ProfitFactorPoints), 300m)
.SetGreaterThanZero()
.SetDisplay("Profit Factor", "Points multiplied by order count for take profit", "Martingale");
_multiplier = Param(nameof(Multiplier), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Multiplier", "Martingale multiplier for averaging", "Martingale");
_kPeriod = Param(nameof(KPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("%K Period", "Stochastic %K lookback", "Indicators");
_dPeriod = Param(nameof(DPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators");
_zoneBuy = Param(nameof(ZoneBuy), 50m)
.SetDisplay("Zone Buy", "%D lower bound to allow buys", "Indicators");
_zoneSell = Param(nameof(ZoneSell), 50m)
.SetDisplay("Zone Sell", "%D upper bound to allow sells", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(10).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for processing", "General");
Volume = 1;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_stochastic = null;
_pointSize = 0m;
_prevK = null;
_prevD = null;
ResetLongState();
ResetShortState();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
_pointSize = Security?.PriceStep ?? 1m;
if (_pointSize <= 0m) _pointSize = 1m;
_stochastic = new StochasticOscillator();
_stochastic.K.Length = KPeriod;
_stochastic.D.Length = DPeriod;
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_stochastic, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
var indArea = CreateChartArea();
if (indArea != null)
DrawIndicator(indArea, _stochastic);
}
base.OnStarted2(time);
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stochasticValue)
{
if (candle.State != CandleStates.Finished)
return;
if (stochasticValue is not StochasticOscillatorValue stoch)
return;
if (stoch.K is not decimal currentK || stoch.D is not decimal currentD)
return;
if (!_stochastic.IsFormed)
{
_prevK = currentK;
_prevD = currentD;
return;
}
var tradingAllowed = IsFormedAndOnlineAndAllowTrading();
ManageClusters(candle, tradingAllowed);
if (!tradingAllowed)
{
_prevK = currentK;
_prevD = currentD;
return;
}
// Entry logic: stochastic crossover in oversold/overbought zones
if (Position == 0m && _buyOrderCount == 0 && _sellOrderCount == 0
&& _prevK is decimal prevK && _prevD is decimal prevD)
{
if (prevK > prevD && prevD > ZoneBuy)
{
OpenLong(candle.ClosePrice);
}
else if (prevK < prevD && prevD < ZoneSell)
{
OpenShort(candle.ClosePrice);
}
}
_prevK = currentK;
_prevD = currentD;
}
private void ManageClusters(ICandleMessage candle, bool tradingAllowed)
{
if (Position > 0m && _buyOrderCount > 0)
{
HandleLongCluster(candle, tradingAllowed);
}
else if (Position < 0m && _sellOrderCount > 0)
{
HandleShortCluster(candle, tradingAllowed);
}
else if (Position == 0m)
{
if (_buyOrderCount > 0 || _sellOrderCount > 0)
{
ResetLongState();
ResetShortState();
}
}
}
private void HandleLongCluster(ICandleMessage candle, bool tradingAllowed)
{
if (!tradingAllowed || _pointSize <= 0m)
return;
// Check take profit first
if (_buyTakeProfit > 0m && candle.HighPrice >= _buyTakeProfit)
{
SellMarket(Math.Abs(Position));
ResetLongState();
return;
}
// Average down
var currentCount = Math.Max(1, _buyOrderCount);
var stepPts = StepMode == 0
? StepPoints
: StepPoints + Math.Max(0m, currentCount * 2m - 2m);
var addTrigger = _buyLastPrice - stepPts * _pointSize;
if (_buyLastVolume > 0m && candle.LowPrice <= addTrigger)
{
var nextVolume = Math.Max(1m, Math.Round(_buyLastVolume * Multiplier));
BuyMarket(nextVolume);
var executionPrice = candle.ClosePrice;
_buyLastVolume = nextVolume;
_buyLastPrice = executionPrice;
_buyTotalVolume += nextVolume;
_buyWeightedSum += executionPrice * nextVolume;
_buyOrderCount++;
RecalcLongTp();
}
}
private void HandleShortCluster(ICandleMessage candle, bool tradingAllowed)
{
if (!tradingAllowed || _pointSize <= 0m)
return;
// Check take profit first
if (_sellTakeProfit > 0m && candle.LowPrice <= _sellTakeProfit)
{
BuyMarket(Math.Abs(Position));
ResetShortState();
return;
}
// Average up
var currentCount = Math.Max(1, _sellOrderCount);
var stepPts = StepMode == 0
? StepPoints
: StepPoints + Math.Max(0m, currentCount * 2m - 2m);
var addTrigger = _sellLastPrice + stepPts * _pointSize;
if (_sellLastVolume > 0m && candle.HighPrice >= addTrigger)
{
var nextVolume = Math.Max(1m, Math.Round(_sellLastVolume * Multiplier));
SellMarket(nextVolume);
var executionPrice = candle.ClosePrice;
_sellLastVolume = nextVolume;
_sellLastPrice = executionPrice;
_sellTotalVolume += nextVolume;
_sellWeightedSum += executionPrice * nextVolume;
_sellOrderCount++;
RecalcShortTp();
}
}
private void OpenLong(decimal price)
{
BuyMarket(Volume);
_buyLastPrice = price;
_buyLastVolume = Volume;
_buyTotalVolume = Volume;
_buyWeightedSum = price * Volume;
_buyOrderCount = 1;
RecalcLongTp();
ResetShortState();
}
private void OpenShort(decimal price)
{
SellMarket(Volume);
_sellLastPrice = price;
_sellLastVolume = Volume;
_sellTotalVolume = Volume;
_sellWeightedSum = price * Volume;
_sellOrderCount = 1;
RecalcShortTp();
ResetLongState();
}
private void RecalcLongTp()
{
var avg = _buyTotalVolume > 0 ? _buyWeightedSum / _buyTotalVolume : _buyLastPrice;
_buyTakeProfit = avg + ProfitFactorPoints * _pointSize;
}
private void RecalcShortTp()
{
var avg = _sellTotalVolume > 0 ? _sellWeightedSum / _sellTotalVolume : _sellLastPrice;
_sellTakeProfit = avg - ProfitFactorPoints * _pointSize;
}
private void ResetLongState()
{
_buyLastPrice = 0m;
_buyLastVolume = 0m;
_buyTotalVolume = 0m;
_buyWeightedSum = 0m;
_buyOrderCount = 0;
_buyTakeProfit = 0m;
}
private void ResetShortState()
{
_sellLastPrice = 0m;
_sellLastVolume = 0m;
_sellTotalVolume = 0m;
_sellWeightedSum = 0m;
_sellOrderCount = 0;
_sellTakeProfit = 0m;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import StochasticOscillator
class martingail_expert_v10_stochastic_strategy(Strategy):
def __init__(self):
super(martingail_expert_v10_stochastic_strategy, self).__init__()
self._step_points = self.Param("StepPoints", 500.0) \
.SetDisplay("Step", "Price step in points before averaging", "Martingale")
self._step_mode = self.Param("StepMode", 0) \
.SetDisplay("Step Mode", "0 - fixed step, 1 - step plus extra points per order", "Martingale")
self._profit_factor_points = self.Param("ProfitFactorPoints", 300.0) \
.SetDisplay("Profit Factor", "Points multiplied by order count for take profit", "Martingale")
self._multiplier = self.Param("Multiplier", 1.5) \
.SetDisplay("Multiplier", "Martingale multiplier for averaging", "Martingale")
self._k_period = self.Param("KPeriod", 14) \
.SetDisplay("%K Period", "Stochastic %K lookback", "Indicators")
self._d_period = self.Param("DPeriod", 3) \
.SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators")
self._zone_buy = self.Param("ZoneBuy", 50.0) \
.SetDisplay("Zone Buy", "%D lower bound to allow buys", "Indicators")
self._zone_sell = self.Param("ZoneSell", 50.0) \
.SetDisplay("Zone Sell", "%D upper bound to allow sells", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(10))) \
.SetDisplay("Candle Type", "Timeframe used for processing", "General")
self.Volume = 1
self._point_size = 0.0
self._prev_k = None
self._prev_d = None
self._buy_last_price = 0.0
self._buy_last_volume = 0.0
self._buy_total_volume = 0.0
self._buy_weighted_sum = 0.0
self._buy_order_count = 0
self._buy_take_profit = 0.0
self._sell_last_price = 0.0
self._sell_last_volume = 0.0
self._sell_total_volume = 0.0
self._sell_weighted_sum = 0.0
self._sell_order_count = 0
self._sell_take_profit = 0.0
@property
def StepPoints(self):
return self._step_points.Value
@property
def StepMode(self):
return self._step_mode.Value
@property
def ProfitFactorPoints(self):
return self._profit_factor_points.Value
@property
def Multiplier(self):
return self._multiplier.Value
@property
def KPeriod(self):
return self._k_period.Value
@property
def DPeriod(self):
return self._d_period.Value
@property
def ZoneBuy(self):
return self._zone_buy.Value
@property
def ZoneSell(self):
return self._zone_sell.Value
@property
def CandleType(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(martingail_expert_v10_stochastic_strategy, self).OnStarted2(time)
ps = self.Security.PriceStep if self.Security is not None else None
self._point_size = float(ps) if ps is not None else 1.0
if self._point_size <= 0:
self._point_size = 1.0
self._stochastic = StochasticOscillator()
self._stochastic.K.Length = self.KPeriod
self._stochastic.D.Length = self.DPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(self._stochastic, self.ProcessCandle).Start()
def ProcessCandle(self, candle, stochastic_value):
if candle.State != CandleStates.Finished:
return
k_val = stochastic_value.K
d_val = stochastic_value.D
if k_val is None or d_val is None:
return
current_k = float(k_val)
current_d = float(d_val)
if not self._stochastic.IsFormed:
self._prev_k = current_k
self._prev_d = current_d
return
trading_allowed = self.IsFormedAndOnlineAndAllowTrading()
self._manage_clusters(candle, trading_allowed)
if not trading_allowed:
self._prev_k = current_k
self._prev_d = current_d
return
if self.Position == 0 and self._buy_order_count == 0 and self._sell_order_count == 0:
if self._prev_k is not None and self._prev_d is not None:
if self._prev_k > self._prev_d and self._prev_d > float(self.ZoneBuy):
self._open_long(float(candle.ClosePrice))
elif self._prev_k < self._prev_d and self._prev_d < float(self.ZoneSell):
self._open_short(float(candle.ClosePrice))
self._prev_k = current_k
self._prev_d = current_d
def _manage_clusters(self, candle, trading_allowed):
if self.Position > 0 and self._buy_order_count > 0:
self._handle_long_cluster(candle, trading_allowed)
elif self.Position < 0 and self._sell_order_count > 0:
self._handle_short_cluster(candle, trading_allowed)
elif self.Position == 0:
if self._buy_order_count > 0 or self._sell_order_count > 0:
self._reset_long_state()
self._reset_short_state()
def _handle_long_cluster(self, candle, trading_allowed):
if not trading_allowed or self._point_size <= 0:
return
if self._buy_take_profit > 0 and float(candle.HighPrice) >= self._buy_take_profit:
self.SellMarket(abs(self.Position))
self._reset_long_state()
return
current_count = max(1, self._buy_order_count)
step_pts = float(self.StepPoints)
if self.StepMode != 0:
step_pts = step_pts + max(0.0, current_count * 2.0 - 2.0)
add_trigger = self._buy_last_price - step_pts * self._point_size
if self._buy_last_volume > 0 and float(candle.LowPrice) <= add_trigger:
next_volume = max(1.0, float(round(float(self._buy_last_volume) * float(self.Multiplier))))
self.BuyMarket(next_volume)
execution_price = float(candle.ClosePrice)
self._buy_last_volume = next_volume
self._buy_last_price = execution_price
self._buy_total_volume += next_volume
self._buy_weighted_sum += execution_price * next_volume
self._buy_order_count += 1
self._recalc_long_tp()
def _handle_short_cluster(self, candle, trading_allowed):
if not trading_allowed or self._point_size <= 0:
return
if self._sell_take_profit > 0 and float(candle.LowPrice) <= self._sell_take_profit:
self.BuyMarket(abs(self.Position))
self._reset_short_state()
return
current_count = max(1, self._sell_order_count)
step_pts = float(self.StepPoints)
if self.StepMode != 0:
step_pts = step_pts + max(0.0, current_count * 2.0 - 2.0)
add_trigger = self._sell_last_price + step_pts * self._point_size
if self._sell_last_volume > 0 and float(candle.HighPrice) >= add_trigger:
next_volume = max(1.0, float(round(float(self._sell_last_volume) * float(self.Multiplier))))
self.SellMarket(next_volume)
execution_price = float(candle.ClosePrice)
self._sell_last_volume = next_volume
self._sell_last_price = execution_price
self._sell_total_volume += next_volume
self._sell_weighted_sum += execution_price * next_volume
self._sell_order_count += 1
self._recalc_short_tp()
def _open_long(self, price):
vol = self.Volume
self.BuyMarket(vol)
self._buy_last_price = price
self._buy_last_volume = vol
self._buy_total_volume = vol
self._buy_weighted_sum = price * vol
self._buy_order_count = 1
self._recalc_long_tp()
self._reset_short_state()
def _open_short(self, price):
vol = self.Volume
self.SellMarket(vol)
self._sell_last_price = price
self._sell_last_volume = vol
self._sell_total_volume = vol
self._sell_weighted_sum = price * vol
self._sell_order_count = 1
self._recalc_short_tp()
self._reset_long_state()
def _recalc_long_tp(self):
avg = self._buy_weighted_sum / self._buy_total_volume if self._buy_total_volume > 0 else self._buy_last_price
self._buy_take_profit = avg + float(self.ProfitFactorPoints) * self._point_size
def _recalc_short_tp(self):
avg = self._sell_weighted_sum / self._sell_total_volume if self._sell_total_volume > 0 else self._sell_last_price
self._sell_take_profit = avg - float(self.ProfitFactorPoints) * self._point_size
def _reset_long_state(self):
self._buy_last_price = 0.0
self._buy_last_volume = 0.0
self._buy_total_volume = 0.0
self._buy_weighted_sum = 0.0
self._buy_order_count = 0
self._buy_take_profit = 0.0
def _reset_short_state(self):
self._sell_last_price = 0.0
self._sell_last_volume = 0.0
self._sell_total_volume = 0.0
self._sell_weighted_sum = 0.0
self._sell_order_count = 0
self._sell_take_profit = 0.0
def OnReseted(self):
super(martingail_expert_v10_stochastic_strategy, self).OnReseted()
self._point_size = 0.0
self._prev_k = None
self._prev_d = None
self._reset_long_state()
self._reset_short_state()
def CreateClone(self):
return martingail_expert_v10_stochastic_strategy()