GitHub で見る

Vlado戦略

Larry WilliamsのクラシックなWilliams %Rオシレーターに基づくモメンタムリバーサル戦略です。システムはオシレーターが深い売られすぎまたは買われすぎの水準に達するのを待ち、次の完成したバーでポジションを反転させます。StockSharpポートはMetaTraderの元の実装の裁量的な特性を維持しながら、すべての重要な設定をパラメーターとして公開しています。

概要

  • カテゴリ: 平均回帰オシレーター戦略。
  • 市場: 安定したローソク足データを提供する流動性の高いあらゆる商品(FXペア、指数先物、仮想通貨スポットペア)。
  • 時間軸: CandleTypeで設定可能。デフォルトは1時間足で、元の使用例に合わせています。
  • 方向: ロングとショートの両方。エンジンは常に最大1つのポジションを保持し、反対のシグナルが現れると転換します。
  • インジケーター: Williams %R(設定可能なルックバック長さとしきい値レベル付き)。

仕組み

  1. 選択したローソク足フィードを購読し、完成した各ローソク足でWilliams %Rを計算します。
  2. デフォルトの売られすぎレベル-75と買われすぎレベル-25を使用します(オシレーターの目盛りのため値は負になります)。
  3. %Rが売られすぎレベルを下回ると、戦略はロングポジションに入るか反転します。
  4. %Rが買われすぎレベルを上回ると、戦略はショートポジションに入るか反転します。
  5. 注文はVolume + Math.Abs(Position)でサイジングされるため、反転により既存ポジションを決済し、単一の成行注文で新しいポジションを開きます。
  6. 明示的なストップロスやテイクプロフィットは使用しません。リスクはインジケーターレベルと選択した時間軸によって管理されます。
  7. すべてのアクションはLogInfoを通じてログに記録され、StockSharp GUIまたはログファイルでの取引監査が容易になります。

パラメーター

  • WilliamsPeriod: オシレーターの計算に使用するローソク足の数。値が大きいほどシグナルが滑らかになり、小さいほど反応が速くなります。
  • OverboughtLevel: 市場が買われすぎと判断されるしきい値(デフォルト -25)。最適化可能。
  • OversoldLevel: 市場が売られすぎと判断されるしきい値(デフォルト -75)。最適化可能。
  • CandleType: すべての計算に適用するローソク足のタイプと時間軸。時間足、出来高ローソク足、レンジバーで動作します。
  • VolumeStrategyから継承): ベース注文サイズを定義します。口座サイズとリスク許容度に合わせて調整します。

取引ルール

  • ロングエントリー: %R <= OversoldLevelで現在のポジションがフラットまたはショートのときに発動。
  • ショートエントリー: %R >= OverboughtLevelで現在のポジションがフラットまたはロングのときに発動。
  • エグジット: 反対のシグナルが現れたときの反転注文によって暗黙的に実行。
  • ポジション管理: 常に1つのオープンポジション。アルゴリズムはピラミッディングや段階的な手仕舞いを行いません。

追加メモ

  • オシレーターが極値の間を循環できる、レンジ相場またはゆっくりとしたトレンド相場で最も効果的に機能します。
  • ライブ取引では、外部のリスク管理(資産ストップ、セッションフィルター)と組み合わせることを推奨します。
  • 実装にはチャートレンダリングが含まれます: メインエリアにはローソク足と取引が表示され、サブペインにはWilliams %Rがプロットされます。
  • さらなる研究のために設計: 各パラメーターはStockSharpのオプティマイザー内での最適化をサポートします。
using System;
using System.Collections.Generic;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Vlado momentum strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class VladoStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	/// <summary>
	/// Fast EMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <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>
	/// Initializes a new instance of the <see cref="VladoStrategy"/> class.
	/// </summary>
	public VladoStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast EMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow EMA period", "Indicator");

		_stopLossPoints = Param(nameof(StopLossPoints), 200)
			.SetNotNegative()
			.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

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

		_fast = null;
		_slow = null;
		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
		_cooldown = 0;
	}

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

		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

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

		if (!_fast.IsFormed || !_slow.IsFormed)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		// Check SL/TP
		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}

		// EMA crossover
		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();

			BuyMarket();
			_entryPrice = close;
			_cooldown = 80;
		}
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();

			SellMarket();
			_entryPrice = close;
			_cooldown = 80;
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}