在 GitHub 上查看

Martini Martingale 策略

该策略实现对冲型马丁格尔。它在当前价格上下方放置止损单,当市场按指定步长朝不利方向移动时,以双倍数量在相反方向加仓。一旦累计利润超过设定目标,策略将平掉所有仓位。

细节

  • 入场条件
    • 在距当前价 Step 的位置放置买入止损和卖出止损单。
    • 其中一单成交后,另一单被取消。
  • 仓位管理
    • 记录最后一笔成交的价格。
    • 当价格相对持仓方向反向移动 Step * orderCount 时,以双倍手数在相反方向市价开单。
  • 出场条件
    • 当浮动利润达到 ProfitClose 时平掉所有仓位。
  • 多空方向:双向。
  • 止损:仅用于初始入场,无传统止损。
  • 指标:无。
  • 过滤器:无。

参数

  • Step – 绝对价格步长。
  • ProfitClose – 触发平仓的利润阈值。
  • InitialVolume – 初始下单手数。
  • CandleType – 用于价格更新的K线类型。
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>
/// Mean reversion strategy inspired by martingale.
/// Enters on RSI extremes, exits when price returns to SMA.
/// </summary>
public class MartiniMartingaleStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<int> _smaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public int SmaPeriod { get => _smaPeriod.Value; set => _smaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MartiniMartingaleStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 7)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI period", "Indicators");
		_smaPeriod = Param(nameof(SmaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("SMA Period", "SMA for mean reversion target", "Indicators");
		_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 OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		var sma = new SimpleMovingAverage { Length = SmaPeriod };

		SubscribeCandles(CandleType).Bind(rsi, sma, ProcessCandle).Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal sma)
	{
		if (candle.State != CandleStates.Finished) return;

		var close = candle.ClosePrice;

		// RSI oversold => buy
		if (rsi < 30 && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// RSI overbought => sell
		else if (rsi > 70 && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}
		// Exit long at SMA
		else if (Position > 0 && close >= sma && rsi > 50)
		{
			SellMarket();
		}
		// Exit short at SMA
		else if (Position < 0 && close <= sma && rsi < 50)
		{
			BuyMarket();
		}
	}
}