GitHub で見る

ランダムコイントス ベースライン戦略

この戦略は、コイントスによってトレード方向を決定するクラシックなGuruTraderのサンプルを再現します。 各完了ローソク足において、ポジションが開いていない場合、疑似乱数が生成されコイントスとして扱われます。 表ならロングポジション、裏ならショートポジションが開かれます。 各トレードは絶対価格単位で測定された固定のテイクプロフィットとストップロスの距離を適用します。

パラメーター

  • Take Profit – テイクプロフィット注文を設定するためのエントリー価格からの距離。
  • Stop Loss – ストップロス注文を設定するためのエントリー価格からの距離。
  • Use Time Seed – 毎回異なる結果を得るために現在時刻でランダムジェネレーターをシード。無効時は固定シードが使用される。
  • Candle Type – 戦略が処理するローソク足の種類。

トレードロジック

  1. 完了したローソク足を待つ。
  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;
	}
}