在 GitHub 上查看

Nevalyashka 方向策略

概览

Nevalyashka 策略基于 MetaTrader 4 原始专家顾问 Nevalyashka.mq4,现被移植为 C# 版本。策略始终保持持仓状态:先开出一笔市价单,等待仓位被止损、止盈或人工平仓后,立即以相同手数反向开仓。StockSharp 实现完全复刻这一思路,并将核心配置暴露为可调参数。

交易流程

  1. 初始化

    • 启动时,策略根据合约的 PriceStep 计算点值;若品种报价精度为 3 或 5 位,则将步长放大 10 倍,以匹配 MetaTrader 中“point”的含义。
    • 调用 StartProtection 将止损、止盈距离(以点为单位)转换为价格差,并为每笔仓位自动挂上保护单。
    • 按照 InitialDirection(默认:做空)发送第一笔市价单。下单量会根据 VolumeStepMinVolumeMaxVolume 调整到可交易的手数。
  2. 仓位管理

    • OnPositionChanged 监听净仓变化。当出现新仓位时,保存实际成交量,并记录方向。
    • 仓位完全归零后,立即以相同手数在相反方向重新入场,实现持续的“翻转”动作。
  3. 失败处理

    • 如果交易所拒绝注册订单,挂起方向标志会被清空,避免旧状态阻碍后续操作,方便人工重新提交或修改参数。

通过上述流程,策略像“不倒翁”一样在多空之间来回摆动,并始终使用固定的止损/止盈控制风险。

参数说明

参数 描述 默认值 备注
StopLossPips 止损距离(点)。 50 会根据点值换算成价格差;设为 0 表示不使用止损。
TakeProfitPips 止盈距离(点)。 50 与止损一致的换算逻辑;设为 0 表示不使用止盈。
Volume 首笔交易的下单量。 1 初次成交后,之后的每次入场都会复用实际成交手数。
InitialDirection 首次下单方向。 Sell 可在 BuySell 间选择,以匹配所需的起始偏好。

实现要点

  • 策略无需订阅蜡烛或指标,仅依赖仓位与订单事件即可运行。
  • 每次入场前都会调用 IsFormedAndOnlineAndAllowTrading(),确保连接就绪并允许交易。
  • 成交量采用 MidpointRounding.AwayFromZero 方式取整,保证最小单位向上取整而不会变成零手。
  • 点值转换依赖品种元数据,而非硬编码假设,可兼容不同报价精度的外汇、CFD 或期货品种。

与 MQL 版本的差异

  • 首次方向可通过参数自定义,而原版脚本固定从做空开始。
  • 使用 StartProtection 管理止损/止盈,更易与任意 StockSharp 连接器集成。
  • 若下单失败会清理内部等待状态,避免重复提交无效请求。

这些改动使策略既保持原始理念,又能无缝融入 StockSharp 的高层 API。

using System;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Nevalyashka Direction: RSI reversal with ATR stops.
/// </summary>
public class NevalyashkaDirectionStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _rsiLength;
	private readonly StrategyParam<int> _atrLength;

	private decimal _prevRsi;
	private decimal _entryPrice;

	public NevalyashkaDirectionStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe.", "General");

		_rsiLength = Param(nameof(RsiLength), 14)
			.SetDisplay("RSI Length", "RSI period.", "Indicators");

		_atrLength = Param(nameof(AtrLength), 14)
			.SetDisplay("ATR Length", "ATR period.", "Indicators");
	}

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public int RsiLength
	{
		get => _rsiLength.Value;
		set => _rsiLength.Value = value;
	}

	public int AtrLength
	{
		get => _atrLength.Value;
		set => _atrLength.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_prevRsi = 0;
		_entryPrice = 0;
	}

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

		_prevRsi = 0;
		_entryPrice = 0;

		var rsi = new RelativeStrengthIndex { Length = RsiLength };
		var atr = new AverageTrueRange { Length = AtrLength };

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

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

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

		if (_prevRsi == 0 || atrVal <= 0)
		{
			_prevRsi = rsiVal;
			return;
		}

		var close = candle.ClosePrice;

		if (Position > 0)
		{
			if (close >= _entryPrice + atrVal * 2m || close <= _entryPrice - atrVal * 1.5m || rsiVal > 70)
			{
				SellMarket();
				_entryPrice = 0;
			}
		}
		else if (Position < 0)
		{
			if (close <= _entryPrice - atrVal * 2m || close >= _entryPrice + atrVal * 1.5m || rsiVal < 30)
			{
				BuyMarket();
				_entryPrice = 0;
			}
		}

		if (Position == 0)
		{
			if (rsiVal < 35 && _prevRsi >= 35)
			{
				_entryPrice = close;
				BuyMarket();
			}
			else if (rsiVal > 65 && _prevRsi <= 65)
			{
				_entryPrice = close;
				SellMarket();
			}
		}

		_prevRsi = rsiVal;
	}
}