在 GitHub 上查看

限价马丁策略

该策略在当前价格上下同时放置买入和卖出限价单。每笔交易使用可配置的间隔,并可选择马丁加仓以弥补先前亏损。

参数

  • Step – 限价单距离当前价格的点数。
  • Stop Loss – 止损点数。
  • Take Profit – 止盈点数。
  • Use Martingale – 是否在亏损后增加手数。
  • Loss Limit – 连续亏损次数上限,超过后手数重置。
  • Volume – 基础手数。
  • Use MegaLot – 在马丁模式下倍增手数,而不是仅增加基础手数。
  • Candle Type – 用于处理的K线类型。

交易逻辑

  1. 当没有持仓和挂单时,策略在收盘价下方 Step 点放置买入限价单,在上方放置卖出限价单。
  2. 任一挂单成交后,另一侧挂单保留,保证同时只有一个方向的仓位。
  3. 持仓达到止损或止盈时平仓。
  4. 发生亏损后,根据马丁设置提高下次交易的手数。

说明

  • 策略使用StockSharp的高级API,通过 Bind 处理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>
/// Simple martingale strategy with RSI-based entries.
/// Buys when RSI is oversold, sells when overbought.
/// </summary>
public class LimitsMartinStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _oversold;
	private readonly StrategyParam<decimal> _overbought;
	private readonly StrategyParam<DataType> _candleType;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public decimal Oversold { get => _oversold.Value; set => _oversold.Value = value; }
	public decimal Overbought { get => _overbought.Value; set => _overbought.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public LimitsMartinStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "Period for RSI", "Indicators");

		_oversold = Param(nameof(Oversold), 30m)
			.SetDisplay("Oversold", "RSI oversold level", "Indicators");

		_overbought = Param(nameof(Overbought), 70m)
			.SetDisplay("Overbought", "RSI overbought level", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(rsi, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, rsi);
			DrawOwnTrades(area);
		}
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (rsiValue < Oversold && Position <= 0)
			BuyMarket();
		else if (rsiValue > Overbought && Position >= 0)
			SellMarket();
	}
}