GitHub で見る

Darvasボックス・システム戦略

概要

この戦略は、古典的なDarvas Boxesのコンセプトに基づいたブレイクアウト・アプローチを実装しています。Donchian Channelsインジケーターを使用して計算された動的な価格レンジ(ボックス)内の価格動向を監視します。価格がボックスの上限を超えて終値を付けると、ロングポジションが開かれます。価格が下限を下回って終値を付けると、ショートポジションが開かれます。オプションのストップロスとテイクプロフィットのレベルが基本的なリスク管理を提供します。

仕組み

  1. 各ローソク足に対して、Donchian Channelsインジケーターが指定されたBoxPeriodを使用して上限と下限を計算します。
  2. 戦略はブレイクアウトを検出するために、前の上限値と下限値を追跡します。
  3. 現在の終値が前の上限を上回った場合、戦略は以下を実行します:
    • 既存のショートポジションを決済する(許可されている場合)。
    • 新しいロングポジションを開く(許可されている場合)。
  4. 現在の終値が前の下限を下回った場合、戦略は以下を実行します:
    • 既存のロングポジションを決済する(許可されている場合)。
    • 新しいショートポジションを開く(許可されている場合)。
  5. アクティブなポジションはストップロスとテイクプロフィットの条件を監視されます。

パラメーター

  • BoxPeriod (int): 価格ボックスの構築に使用するローソク足の数。デフォルトは20。
  • StopLoss (decimal): エントリー価格からストップロスレベルまでの距離。デフォルトは1000。
  • TakeProfit (decimal): エントリー価格からテイクプロフィットレベルまでの距離。デフォルトは2000。
  • AllowBuyEntry (bool): ロングポジションの開設を有効にします。デフォルトはtrue
  • AllowSellEntry (bool): ショートポジションの開設を有効にします。デフォルトはtrue
  • AllowBuyExit (bool): 逆シグナルやリスクイベント時のロングポジション決済を有効にします。デフォルトはtrue
  • AllowSellExit (bool): 逆シグナルやリスクイベント時のショートポジション決済を有効にします。デフォルトはtrue
  • CandleType (DataType): 計算に使用するローソク足の種類。デフォルトは4時間足。

使用方法

  1. 戦略を銘柄に適用し、希望するパラメーター値を設定します。
  2. 戦略を開始します。設定されたローソク足シリーズを購読し、受信データを処理します。
  3. ブレイクアウト条件が満たされると、成行注文でトレードが実行されます。
  4. オプションのストップロスとテイクプロフィットレベルがオープンポジションを管理します。

注意事項

  • 戦略はインジケーター値とローソク足データを接続するために、BindExを使用した高レベルAPIを使います。
  • 内部コレクションは使用せず、インジケーター値はバインディングコールバックを通じてアクセスされます。
  • 信頼性の高いシグナルを確保するため、完成したローソク足のみが処理されます。
  • コード内のコメントは、要件に従い英語で記述されています。
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>
/// Darvas Boxes breakout strategy using Donchian Channels.
/// Opens long position when price breaks above the upper box line.
/// Opens short position when price breaks below the lower box line.
/// </summary>
public class DarvasBoxesSystemStrategy : Strategy
{
	private readonly StrategyParam<int> _boxPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevUpper;
	private decimal _prevLower;
	private decimal _prevClose;

	public int BoxPeriod
	{
		get => _boxPeriod.Value;
		set => _boxPeriod.Value = value;
	}

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

	public DarvasBoxesSystemStrategy()
	{
		_boxPeriod = Param(nameof(BoxPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Box Period", "Period for box calculation", "Indicators")
			.SetOptimize(10, 40, 5);

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevUpper = 0m;
		_prevLower = 0m;
		_prevClose = 0m;
	}

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

		_prevUpper = 0m;
		_prevLower = 0m;
		_prevClose = 0m;

		var donchian = new DonchianChannels { Length = BoxPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(donchian, ProcessCandle)
			.Start();

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

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue value)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (value is not IDonchianChannelsValue box)
			return;

		if (box.UpperBand is not decimal upper || box.LowerBand is not decimal lower)
			return;

		if (_prevUpper == 0m)
		{
			_prevUpper = upper;
			_prevLower = lower;
			_prevClose = candle.ClosePrice;
			return;
		}

		var isUpBreakout = candle.ClosePrice > _prevUpper && _prevClose <= _prevUpper;
		var isDownBreakout = candle.ClosePrice < _prevLower && _prevClose >= _prevLower;

		if (isUpBreakout && Position <= 0)
			BuyMarket();
		else if (isDownBreakout && Position >= 0)
			SellMarket();

		_prevUpper = upper;
		_prevLower = lower;
		_prevClose = candle.ClosePrice;
	}
}