GitHub で見る
ローソク足 Stochastic 確認戦略
この戦略は、StockSharp の高レベル API 内に MetaTrader エキスパートアドバイザー Expert_CP_Stoch を再現します。日本のローソク足反転パターンと%D確率オシレーターフィルターをブレンドして、エントリーとタイムエグジットを確認します。システムは完了したローソク足をそれぞれスキャンし、3 本の足を遡って強気または弱気の形成を検出し、取引を開始する前に確率シグナルラインが売られすぎまたは買われすぎのゾーンにあることを要求します。反対のパターンが現れるか、確率ラインが設定可能な出口境界を横切ると、ポジションは閉じられます。
デフォルト設定は元のエキスパートを反映しています: %K 期間 33、%D 期間 37、減速 30、30 で売られすぎ、70 で買われすぎ、20/80 で出口クロスオーバー レベル。 StockSharp の確率オシレーターは高値/安値/終値データを使用するため、動作は元の STO_LOWHIGH 設定に対応します。ローソク足パターン認識は、最後の 12 個のボディ (デフォルト) に依存して、パターン フィルターで使用される平均ローソク足サイズを計算します。
詳細
- エントリー基準:
- ロング: 強気パターン (スリー ホワイト ソルジャー、ピアス ライン、モーニング ドージ、強気巻き込み、強気ハラミ、モーニング スター、強気ミーティング ライン) の 1 つが検出され、かつ、以前に閉じられたバーの確率的 %D 値が売られすぎのしきい値 (デフォルト 30) を下回っています。
- ショート: 弱気パターン (三黒烏、暗雲覆い、夕童子、弱気巻き込み、弱気ハラミ、イブニングスター、弱気ミーティングライン) の 1 つが検出され、かつ、以前に閉じられたバーの確率的 %D 値が買われすぎのしきい値 (デフォルト 70) を上回っています。
- 終了基準:
- ロング: 弱気パターンが現れたとき、または %D が出口境界の上限 (デフォルト 80) または下限境界 (デフォルト 20) を下回ったときに直ちに終了します。
- ショート: 強気のパターンが現れたとき、または %D が出口境界の下限 (デフォルト 20) または上限境界 (デフォルト 80) を超えたときに直ちに終了します。
- ロング/ショート: 対称ルールで両方向に取引します。
- ストップ: 固定のストップロス/ターゲットはありません。イグジットはパターンの反転と確率的交差に依存します。必要に応じて、ランチャーにポートフォリオ保護を追加できます。
- デフォルト値:
Body Average Period = パターン認定のための基準身体サイズの計算に使用される 12 個のキャンドル。
Stochastic %K = 33、Stochastic %D = 37、Stochastic Smoothing = 30。
Oversold Threshold = 30、Overbought Threshold = 70。
Lower Exit Level = 20、Upper Exit Level = 80。
- フィルター:
- カテゴリ: パターン認識 + オシレーター確認。
- 方向性:ロング&ショート。
- インジケーター: Stochastic オシレーター、複数のローソク足パターン。
- ストップ: パターン/オシレーターのみが終了します (機械的なストップ/ターゲットはありません)。
- 複雑さ: 高 (履歴平均による複数条件のパターン検出)。
- タイムフレーム: 任意のタイムフレームで機能します。デフォルトは時間足ローソク足です。
- 季節性:なし。
- ニューラルネットワーク: いいえ。
- 発散: 明示的な発散はありません。オシレーターレベルによる確認。
- 危険レベル: ハードストップがないため中~高。
仕組み
- 選択したローソク足シリーズをサブスクライブし、確率オシレーター (%K、%D、減速) をバインドします。
- 過去 3 つの完了したローソク足とローソク体/終値の移動平均を保持して、MetaTrader のパターン ライブラリ ロジックを複製します。
- 完成したすべてのローソク足の強気/弱気パターン グループを評価します。各パターンは、元の数学的定義 (平均ボディ チェック、中間点の関係、ギャップ要件など) に厳密に従っています。
- 前の 2 つのローソク足から確率的 %D 値を取得して、売られすぎ/買われすぎの状態とクロスオーバーを検出します。
- パターンとオシレーター条件の両方が一致した場合、StockSharp の高レベルの
BuyMarket/SellMarket メソッドを使用して市場ポジションをオープンまたはクローズします。
- オプションで、ストップロス管理が必要な場合は、ランチャーから外部リスク モジュール (例:
StartProtection) を有効にすることができます。
実用上の注意
- シグナルを期待する前に、少なくとも
Body Average Period + 3 個の過去のローソク足を戦略にフィードしてください。それ以外の場合、平均ボディが定義されていないため、パターン チェックは false を返します。
- 確率的フィルターは 前の ローソク足の %D 値を使用し、MetaTrader のシグナルが
StochSignal(1) を評価した方法を再現します。
- ローソク足のパターン認識はギャップや相対的なローソク足のサイズに敏感であるため、流動性が薄い金融商品や合成データでは結果が異なる場合があります。
- 最適化を高速化するために、ローソク足の定義をそのまま維持しながら、売られすぎ/買われすぎのしきい値と確率的期間を微調整できます。
- STO_CLOSECLOSE の動作 (終値/終値ストキャスティクス) が必要な場合は、将来の機能強化で StockSharp のオシレーターを終値のみの計算用に構成されたものに置き換えてください。
namespace StockSharp.Samples.Strategies;
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
/// <summary>
/// Candlestick + Stochastic strategy.
/// Buys on bullish engulfing with low stochastic, sells on bearish engulfing with high stochastic.
/// </summary>
public class CandlestickStochasticStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _stochPeriod;
private readonly StrategyParam<decimal> _stochLow;
private readonly StrategyParam<decimal> _stochHigh;
private readonly StrategyParam<int> _signalCooldownCandles;
private ICandleMessage _prevCandle;
private int _candlesSinceTrade;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int StochPeriod { get => _stochPeriod.Value; set => _stochPeriod.Value = value; }
public decimal StochLow { get => _stochLow.Value; set => _stochLow.Value = value; }
public decimal StochHigh { get => _stochHigh.Value; set => _stochHigh.Value = value; }
public int SignalCooldownCandles { get => _signalCooldownCandles.Value; set => _signalCooldownCandles.Value = value; }
public CandlestickStochasticStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
_stochPeriod = Param(nameof(StochPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Stoch Period", "Stochastic K period", "Indicators");
_stochLow = Param(nameof(StochLow), 40m)
.SetDisplay("Stoch Low", "Stochastic oversold level", "Signals");
_stochHigh = Param(nameof(StochHigh), 60m)
.SetDisplay("Stoch High", "Stochastic overbought level", "Signals");
_signalCooldownCandles = Param(nameof(SignalCooldownCandles), 4)
.SetGreaterThanZero()
.SetDisplay("Signal Cooldown", "Bars to wait between trades", "Trading");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevCandle = null;
_candlesSinceTrade = SignalCooldownCandles;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevCandle = null;
_candlesSinceTrade = SignalCooldownCandles;
var rsi = new RelativeStrengthIndex { Length = StochPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(rsi, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal stochValue)
{
if (candle.State != CandleStates.Finished) return;
if (_candlesSinceTrade < SignalCooldownCandles)
_candlesSinceTrade++;
if (_prevCandle != null)
{
var bullishEngulf = _prevCandle.OpenPrice > _prevCandle.ClosePrice &&
candle.ClosePrice > candle.OpenPrice &&
candle.ClosePrice > _prevCandle.OpenPrice &&
candle.OpenPrice < _prevCandle.ClosePrice;
var bearishEngulf = _prevCandle.ClosePrice > _prevCandle.OpenPrice &&
candle.OpenPrice > candle.ClosePrice &&
candle.OpenPrice > _prevCandle.ClosePrice &&
candle.ClosePrice < _prevCandle.OpenPrice;
if (bullishEngulf && stochValue < StochLow && Position <= 0 && _candlesSinceTrade >= SignalCooldownCandles)
{
BuyMarket();
_candlesSinceTrade = 0;
}
else if (bearishEngulf && stochValue > StochHigh && Position >= 0 && _candlesSinceTrade >= SignalCooldownCandles)
{
SellMarket();
_candlesSinceTrade = 0;
}
}
_prevCandle = candle;
}
}
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 RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class candlestick_stochastic_strategy(Strategy):
def __init__(self):
super(candlestick_stochastic_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30)))
self._stoch_period = self.Param("StochPeriod", 14)
self._stoch_low = self.Param("StochLow", 40.0)
self._stoch_high = self.Param("StochHigh", 60.0)
self._signal_cooldown_candles = self.Param("SignalCooldownCandles", 4)
self._prev_candle = None
self._candles_since_trade = 4
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def StochPeriod(self):
return self._stoch_period.Value
@StochPeriod.setter
def StochPeriod(self, value):
self._stoch_period.Value = value
@property
def StochLow(self):
return self._stoch_low.Value
@StochLow.setter
def StochLow(self, value):
self._stoch_low.Value = value
@property
def StochHigh(self):
return self._stoch_high.Value
@StochHigh.setter
def StochHigh(self, value):
self._stoch_high.Value = value
@property
def SignalCooldownCandles(self):
return self._signal_cooldown_candles.Value
@SignalCooldownCandles.setter
def SignalCooldownCandles(self, value):
self._signal_cooldown_candles.Value = value
def OnReseted(self):
super(candlestick_stochastic_strategy, self).OnReseted()
self._prev_candle = None
self._candles_since_trade = self.SignalCooldownCandles
def OnStarted2(self, time):
super(candlestick_stochastic_strategy, self).OnStarted2(time)
self._prev_candle = None
self._candles_since_trade = self.SignalCooldownCandles
rsi = RelativeStrengthIndex()
rsi.Length = self.StochPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(rsi, self._process_candle).Start()
def _process_candle(self, candle, stoch_value):
if candle.State != CandleStates.Finished:
return
if self._candles_since_trade < self.SignalCooldownCandles:
self._candles_since_trade += 1
stoch_val = float(stoch_value)
if self._prev_candle is not None:
bullish_engulf = (float(self._prev_candle.OpenPrice) > float(self._prev_candle.ClosePrice) and
float(candle.ClosePrice) > float(candle.OpenPrice) and
float(candle.ClosePrice) > float(self._prev_candle.OpenPrice) and
float(candle.OpenPrice) < float(self._prev_candle.ClosePrice))
bearish_engulf = (float(self._prev_candle.ClosePrice) > float(self._prev_candle.OpenPrice) and
float(candle.OpenPrice) > float(candle.ClosePrice) and
float(candle.OpenPrice) > float(self._prev_candle.ClosePrice) and
float(candle.ClosePrice) < float(self._prev_candle.OpenPrice))
if bullish_engulf and stoch_val < self.StochLow and self.Position <= 0 and self._candles_since_trade >= self.SignalCooldownCandles:
self.BuyMarket()
self._candles_since_trade = 0
elif bearish_engulf and stoch_val > self.StochHigh and self.Position >= 0 and self._candles_since_trade >= self.SignalCooldownCandles:
self.SellMarket()
self._candles_since_trade = 0
self._prev_candle = candle
def CreateClone(self):
return candlestick_stochastic_strategy()