在 GitHub 上查看

Nevalyashka 翻转策略

将 MetaTrader 专家顾问 “Nevalyashka” 直接移植到 StockSharp。策略始终在多空之间交替:先市价卖出,等待仓位被止损或止盈平仓,然后立即以相同的手数反向开仓。每次进场后都会根据设定的点数重新创建保护性订单,与原始 MQL 逻辑完全一致。

策略逻辑

  1. 初始化
    • 读取品种的最小报价步长和小数位数,计算与 MQL 版本一致的点值(3/5 位小数的品种乘以 10)。
    • 用参数 LotMultiplier 乘以交易所的 MinVolume 得到下单手数,并根据 VolumeStep 进行向上取整。
  2. 行情处理
    • 订阅盘口更新,实时获取最新买一/卖一价,相当于专家顾问中的 RefreshRates() 调用。
  3. 下单流程
    • 在获取到行情后先发出第一笔市价卖单。
    • 仓位平掉后立即反向开仓(卖单后跟随买单,买单后跟随卖单),手数保持不变。
    • 每次成交后根据点数参数提交新的止损与止盈订单。

风险管理

  • 止损:当 StopLossPips 大于 0 时,策略会在 入场价 ± StopLossPips * 点值 位置挂出保护性止损单(多单使用 SellStop,空单使用 BuyStop)。
  • 止盈:当 TakeProfitPips 大于 0 时,会在 入场价 ± TakeProfitPips * 点值 位置挂出保护性限价单(多单使用 SellLimit,空单使用 BuyLimit)。
  • 每次仓位归零都会取消旧的保护性订单,防止未平掉的挂单影响下一次反向开仓。

参数

名称 说明 默认值
LotMultiplier 乘以交易所最小交易量后的手数,最终会四舍五入到交易所的量化步长。 1
StopLossPips 止损距离(点)。设置为 0 可关闭止损。 50
TakeProfitPips 止盈距离(点)。设置为 0 可关闭止盈。 50

使用提示

  • 策略始终保持在多空之间轮换,适合节奏平缓、倾向于均值回归的市场环境。
  • 只要标的能够提供盘口最优报价即可运行,点值会根据报价精度自动调整。
  • 订单以市价形式发送,滑点控制完全交由交易所,和原始专家顾问一致。
  • 没有包含交易时段过滤、新闻过滤或移动止损,如有需要可在 TryOpenNextPositionRegisterProtectionOrders 中扩展。
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>
/// Alternating long-short strategy that mirrors the original Nevalyashka MQL logic.
/// Opens an initial sell position and flips direction each time the position is closed.
/// </summary>
public class NevalyashkaFlipStrategy : Strategy
{
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _entryPrice;
	private Sides? _currentSide;
	private Sides? _lastCompletedSide;

	/// <summary>
	/// Stop loss distance in price steps.
	/// </summary>
	public int StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take profit distance in price steps.
	/// </summary>
	public int TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

	/// <summary>
	/// Candle type for monitoring price.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="NevalyashkaFlipStrategy"/> class.
	/// </summary>
	public NevalyashkaFlipStrategy()
	{
		_stopLossPoints = Param(nameof(StopLossPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pts)", "Stop loss distance in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit (pts)", "Take profit distance in price steps", "Risk");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_entryPrice = 0m;
		_currentSide = null;
		_lastCompletedSide = null;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

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

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

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

		var step = Security?.PriceStep ?? 1m;
		var stopDistance = StopLossPoints * step;
		var takeDistance = TakeProfitPoints * step;
		var price = candle.ClosePrice;

		// Check SL/TP for current position
		if (Position != 0 && _entryPrice > 0)
		{
			var hit = false;

			if (_currentSide == Sides.Buy)
			{
				if (stopDistance > 0 && candle.LowPrice <= _entryPrice - stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.HighPrice >= _entryPrice + takeDistance)
					hit = true;
			}
			else if (_currentSide == Sides.Sell)
			{
				if (stopDistance > 0 && candle.HighPrice >= _entryPrice + stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.LowPrice <= _entryPrice - takeDistance)
					hit = true;
			}

			if (hit)
			{
				// Close position
				if (Position > 0)
					SellMarket();
				else if (Position < 0)
					BuyMarket();

				_lastCompletedSide = _currentSide;
				_currentSide = null;
				_entryPrice = 0m;
			}
		}

		// If flat, open next position
		if (Position == 0 && _currentSide == null)
		{
			// Alternate direction: start with sell, then flip
			var sideToOpen = _lastCompletedSide switch
			{
				Sides.Buy => Sides.Sell,
				Sides.Sell => Sides.Buy,
				_ => Sides.Sell,
			};

			if (sideToOpen == Sides.Buy)
				BuyMarket();
			else
				SellMarket();

			_currentSide = sideToOpen;
			_entryPrice = price;
		}
	}
}