在 GitHub 上查看

随机方向策略

概述

随机方向策略 完整移植自 MetaTrader 的 “New Random” 专家顾问,提供三种不同的建仓方向选择模式。策略在任意时刻只保持一笔仓位,等待仓位完全平仓后才会评估下一次信号。通过订阅一级行情数据实时获取最新买价、卖价与成交价,并以最佳买卖价作为市价单的执行参考,同时依据点数参数自动计算止损与止盈距离,对 3 位或 5 位报价的外汇品种进行和原始脚本一致的调整。

入场模式

  1. 随机生成 – 在策略启动时使用当前时间作为随机数种子,每次机会都通过抛硬币的方式在做多和做空之间随机选择。
  2. 买-卖-买循环 – 方向严格交替,首笔交易为买单,其后依次为卖单、买单……
  3. 卖-买-卖循环 – 方向严格交替,但首笔交易为卖单,随后为买单、卖单循环往复。

参数说明

  • Random ModeMode) – 选择上述三种入场模式之一,默认使用随机生成模式。
  • Minimal Lot CountMinimalLotCount) – 以标的的最小交易量为基础的倍数。取值为 1 时下单量等于 Security.VolumeMin,更大的数字会按照最小交易量的整数倍放大。
  • Stop Loss (pips)StopLossPips) – 入场价与止损价之间的点数距离,设置为 0 表示不启用止损。
  • Take Profit (pips)TakeProfitPips) – 入场价与止盈价之间的点数距离,设置为 0 表示不启用止盈。

交易流程

  1. 订阅并监听一级行情,保存最新的买价、卖价以及成交价。
  2. 当不存在持仓且没有挂单时,根据所选模式确定下一次的交易方向。
  3. 使用当前的最佳买价或卖价发送市价单,并立即按照参数换算出止损与止盈价格。
  4. 策略始终只持有单笔仓位,直到当前仓位完全平仓后才会评估新的信号。

仓位管理

  • 多头仓位在价格跌破止损或升破止盈时平仓。
  • 空头仓位在价格升破止损或跌破止盈时平仓。
  • 比较价格时优先采用最新成交价;若暂时没有成交价,则多头使用买价、空头使用卖价作为参考。
  • 平仓后策略会重置内部状态,并根据循环模式更新下一次方向,随后等待新的行情报价。

注意事项

  • 策略不会加仓或网格化,循环模式的行为完全可预测。
  • 随机模式以系统 Tick 计数作为种子,每次运行都会产生不同的交易序列。
  • 源码中的所有注释和日志均为英文,以符合仓库的统一规范。
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>
/// Randomized entry strategy that mimics the MetaTrader "New Random" expert.
/// </summary>
public class NewRandomStrategy : Strategy
{
	/// <summary>
	/// Available direction selection modes.
	/// </summary>
	public enum RandomModes
	{
		/// <summary>Use a pseudo random generator for every entry decision.</summary>
		Generator,
		/// <summary>Alternate buy-sell-buy.</summary>
		BuySellBuy,
		/// <summary>Alternate sell-buy-sell.</summary>
		SellBuySell
	}

	private readonly StrategyParam<RandomModes> _mode;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;
	private readonly StrategyParam<DataType> _candleType;

	private Sides? _sequenceLastSide;
	private Sides? _positionSide;
	private decimal _entryPrice;
	private int _candleCount;

	/// <summary>Direction selection mode.</summary>
	public RandomModes Mode
	{
		get => _mode.Value;
		set => _mode.Value = value;
	}

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

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

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

	public NewRandomStrategy()
	{
		_mode = Param(nameof(Mode), RandomModes.Generator)
			.SetDisplay("Random Mode", "Direction selection mode", "General");

		_stopLossPoints = Param(nameof(StopLossPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pts)", "Stop loss in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 5)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit (pts)", "Take profit 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();
		_sequenceLastSide = null;
		_positionSide = null;
		_entryPrice = 0m;
		_candleCount = 0;
	}

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

		_sequenceLastSide = Mode switch
		{
			RandomModes.BuySellBuy => Sides.Sell,
			RandomModes.SellBuySell => Sides.Buy,
			_ => null
		};

		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;

		_candleCount++;
		if (_candleCount < 3)
			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 (_positionSide == Sides.Buy)
			{
				if (stopDistance > 0 && candle.LowPrice <= _entryPrice - stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.HighPrice >= _entryPrice + takeDistance)
					hit = true;
			}
			else if (_positionSide == Sides.Sell)
			{
				if (stopDistance > 0 && candle.HighPrice >= _entryPrice + stopDistance)
					hit = true;
				if (takeDistance > 0 && candle.LowPrice <= _entryPrice - takeDistance)
					hit = true;
			}

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

				_positionSide = null;
				_entryPrice = 0m;
			}
		}

		// If flat, open new random position
		if (Position == 0 && _positionSide == null)
		{
			var side = DetermineNextSide();

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

			_positionSide = side;
			_entryPrice = price;

			_sequenceLastSide = side;
		}
	}

	private Sides DetermineNextSide()
	{
		// All modes use deterministic alternating logic
		return _sequenceLastSide == Sides.Buy ? Sides.Sell : Sides.Buy;
	}
}