在 GitHub 上查看

Random Coin Toss Baseline 策略

该策略复现了经典的 GuruTrader 示例,通过掷硬币决定交易方向。 在每根完成的K线,如果没有持仓,就生成一个伪随机数作为掷硬币。 正面开多,反面开空。 每笔交易都使用固定的绝对价格距离作为止盈和止损。

参数

  • Take Profit – 距离入场价的止盈距离。
  • Stop Loss – 距离入场价的止损距离。
  • Use Time Seed – 使用当前时间作为随机种子,每次运行结果不同;关闭后使用固定种子。
  • Candle Type – 策略处理的K线类型。

交易逻辑

  1. 等待K线完成。
  2. 确认允许交易且当前没有持仓。
  3. 生成随机值并根据“掷硬币”结果选择方向。
  4. 使用预设的止盈和止损保护仓位。

警告: 本策略仅用于教育目的,禁止用于真实账户交易。

using System;
using System.Collections.Generic;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy that tosses a virtual coin to decide trade direction.
/// A long position is opened on heads, a short position on tails.
/// Closes after N candles and re-enters.
/// </summary>
public class RandomCoinTossBaselineStrategy : Strategy
{
	private readonly StrategyParam<int> _holdBars;
	private readonly StrategyParam<DataType> _candleType;

	private Random _random;
	private int _barsInPosition;

	public int HoldBars
	{
		get => _holdBars.Value;
		set => _holdBars.Value = value;
	}

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

	public RandomCoinTossBaselineStrategy()
	{
		_holdBars = Param(nameof(HoldBars), 10)
			.SetGreaterThanZero()
			.SetDisplay("Hold Bars", "Number of bars to hold position", "General");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_random = null;
		_barsInPosition = 0;
	}

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

		_random = new Random(42);
		_barsInPosition = 0;

		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;

		// Close position after holding for N bars
		if (Position != 0)
		{
			_barsInPosition++;

			if (_barsInPosition >= HoldBars)
			{
				if (Position > 0)
					SellMarket();
				else
					BuyMarket();

				_barsInPosition = 0;
			}

			return;
		}

		// Flip coin and enter
		var coin = _random.Next(2);

		if (coin == 0)
			BuyMarket();
		else
			SellMarket();

		_barsInPosition = 0;
	}
}