GitHub で見る
Darvasボックス・システム戦略
概要
この戦略は、古典的なDarvas Boxesのコンセプトに基づいたブレイクアウト・アプローチを実装しています。Donchian Channelsインジケーターを使用して計算された動的な価格レンジ(ボックス)内の価格動向を監視します。価格がボックスの上限を超えて終値を付けると、ロングポジションが開かれます。価格が下限を下回って終値を付けると、ショートポジションが開かれます。オプションのストップロスとテイクプロフィットのレベルが基本的なリスク管理を提供します。
仕組み
- 各ローソク足に対して、Donchian Channelsインジケーターが指定された
BoxPeriodを使用して上限と下限を計算します。
- 戦略はブレイクアウトを検出するために、前の上限値と下限値を追跡します。
- 現在の終値が前の上限を上回った場合、戦略は以下を実行します:
- 既存のショートポジションを決済する(許可されている場合)。
- 新しいロングポジションを開く(許可されている場合)。
- 現在の終値が前の下限を下回った場合、戦略は以下を実行します:
- 既存のロングポジションを決済する(許可されている場合)。
- 新しいショートポジションを開く(許可されている場合)。
- アクティブなポジションはストップロスとテイクプロフィットの条件を監視されます。
パラメーター
- BoxPeriod (
int): 価格ボックスの構築に使用するローソク足の数。デフォルトは20。
- StopLoss (
decimal): エントリー価格からストップロスレベルまでの距離。デフォルトは1000。
- TakeProfit (
decimal): エントリー価格からテイクプロフィットレベルまでの距離。デフォルトは2000。
- AllowBuyEntry (
bool): ロングポジションの開設を有効にします。デフォルトはtrue。
- AllowSellEntry (
bool): ショートポジションの開設を有効にします。デフォルトはtrue。
- AllowBuyExit (
bool): 逆シグナルやリスクイベント時のロングポジション決済を有効にします。デフォルトはtrue。
- AllowSellExit (
bool): 逆シグナルやリスクイベント時のショートポジション決済を有効にします。デフォルトはtrue。
- CandleType (
DataType): 計算に使用するローソク足の種類。デフォルトは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;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import DonchianChannels
from StockSharp.Algo.Strategies import Strategy
class darvas_boxes_system_strategy(Strategy):
def __init__(self):
super(darvas_boxes_system_strategy, self).__init__()
self._box_period = self.Param("BoxPeriod", 20) \
.SetDisplay("Box Period", "Period for box calculation", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_upper = 0.0
self._prev_lower = 0.0
self._prev_close = 0.0
@property
def box_period(self):
return self._box_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(darvas_boxes_system_strategy, self).OnReseted()
self._prev_upper = 0.0
self._prev_lower = 0.0
self._prev_close = 0.0
def OnStarted2(self, time):
super(darvas_boxes_system_strategy, self).OnStarted2(time)
self._prev_upper = 0.0
self._prev_lower = 0.0
self._prev_close = 0.0
donchian = DonchianChannels()
donchian.Length = self.box_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(donchian, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, donchian)
self.DrawOwnTrades(area)
def process_candle(self, candle, value):
if candle.State != CandleStates.Finished:
return
upper = value.UpperBand
lower = value.LowerBand
if upper is None or lower is None:
return
upper = float(upper)
lower = float(lower)
close_price = float(candle.ClosePrice)
if self._prev_upper == 0.0:
self._prev_upper = upper
self._prev_lower = lower
self._prev_close = close_price
return
is_up_breakout = close_price > self._prev_upper and self._prev_close <= self._prev_upper
is_down_breakout = close_price < self._prev_lower and self._prev_close >= self._prev_lower
if is_up_breakout and self.Position <= 0:
self.BuyMarket()
elif is_down_breakout and self.Position >= 0:
self.SellMarket()
self._prev_upper = upper
self._prev_lower = lower
self._prev_close = close_price
def CreateClone(self):
return darvas_boxes_system_strategy()