GitHub で見る
フラットトレンド戦略
概要
フラット トレンド戦略は、マルチスピード トレンド フィルター、ADX 確認、標準偏差「ジュース」ブレイクアウト フィルターを組み合わせることにより、元のフラット トレンド エキスパート アドバイザーの中核となるアイデアを再現します。この戦略は、価格がレンジフェーズを抜けて勢いが拡大する瞬間を検出することに焦点を当てており、動的なポジション保護を伴う方向性の動きに加わることができます。
取引ロジック
- トレンド フィルター – 構成可能な長さを持つ 3 つの指数移動平均 (EMA) は、トリガー、最初のフィルター、および 2 番目のフィルターを表します。各 EMA に対する傾きと価格位置は状態に変換されます。
- 強い強気(価格が EMA を超え、EMA が上昇)。
- やや強気(価格は EMA を上回るが、傾きは中立)。
- 強い弱気(価格が EMA を下回り、EMA が下落)。
- やや弱気(価格は EMA を下回るが、傾きは中立)。
- エントリールール
- ロングトレードでは、トリガーとフィルター EMA で強気の状態が必要です。 2 番目のフィルターはオプションで無視できます。厳密モードでは、強い強気状態のみの使用が強制されます。
- 空売り取引は弱気国の状況を反映しています。
- オプションの ADX 確認により、平均方向指数がしきい値を超えていることが確認され、有効にすると、+DI コンポーネントと –DI コンポーネントが取引方向と一致します。
- 「ジュース」フィルターは、価格の標準偏差がユーザー定義のブレイクアウト レベルを超えていることを検証し、フラット ボラティリティ段階での取引を防ぎます。
- 取引は、選択した日中ウィンドウに制限できます。
- 退出ルール
- トリガー EMA の反対のトレンド状態により出口が開始されます。厳密モードでは、戦略は最も強力なカウンターシグナルを待ちます。
- 価格が計算されたストップレベルに達するたびに、動的ストップの終了位置が設定されます。
リスク管理
- 初期停止 – 静的なピップ距離または平均トゥルー レンジ (ATR) 値から計算され、元の EA の ADR ベースのロジックをエミュレートします。
- トレーリングストップ – ATRに除数を掛けた値を使用して、エントリー以来の最高値(または最低値)で動きます。
- 損益分岐点 – 価格が設定された距離だけ進むと、ストップは小さなロック値だけエントリー価格を超えて移動します。
パラメーター
| 名前 |
説明 |
TriggerLength |
トリガーフィルターの EMA の長さ。 |
FilterLength1 |
最初の確認フィルターの長さは EMA です。 |
FilterLength2 |
2 番目の確認フィルターの長さは EMA です。 |
UseOnlyPrimaryIndicators |
エントリにはトリガーと最初のフィルターのみを使用します。 |
IgnoreModerateForEntry |
新しい取引には強いトレンド状態が必要です。 |
IgnoreModerateForExit |
取引を終了するには強力なカウンターシグナルが必要です。 |
UseTradingHours |
日中取引ウィンドウを有効にします。 |
TradingHourBegin / TradingHourEnd |
取引ウィンドウの開始時間と終了時間。 |
UseJuiceFilter, JuicePeriod, JuiceThreshold |
標準偏差ブレークアウト フィルター パラメーター。 |
UseAdxFilter, AdxPeriod, AdxThreshold, UseDirectionalFilter |
ADXの強度とDIの確認。 |
UseAdrForStop, StopLossPips |
初期のストップロス設定。 |
TrailingDivisor |
トレーリングストップ計算用の ATR 乗数。 |
BreakEvenPips, BreakEvenLockPips |
損益分岐点アクティベーションとロック距離。 |
AtrPeriod |
ボラティリティの推定に使用される ATR ルックバック。 |
CandleType |
プライマリローソク足の時間枠。 |
指標の概要
- 指数移動平均 (EMA) – マルチスピード傾向評価のための 3 つのインスタンス。
- 標準偏差 – 「ジュース」ボラティリティブレイクアウトフィルターをモデル化します。
- 平均トゥルーレンジ (ATR) – ストップとトレーリングのボラティリティを測定します。
- 平均方向性インデックス (ADX) – トレンドの強さと方向性を確認します。
使用上の注意
- 戦略セキュリティに
PriceStep が定義されていることを確認してください。それ以外の場合は、pip ベースの距離にデフォルトのステップ 0.0001 が使用されます。
- この戦略は成行注文 (
BuyMarket、SellMarket) を使用し、ポジションを反転するときにボリュームを自動的に調整します。
- 動的ストップは、仮想ストップレベルに触れたときにポジションを閉じることによって内部的にシミュレートされます。
- 取引ウィンドウと厳格なエントリーオプションを組み合わせて、流動性の高いセッションに集中し、不安定な期間を避けます。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Flat Trend strategy - breakout from low volatility using ATR and EMA.
/// Buys when ATR expands and price is above EMA.
/// Sells when ATR expands and price is below EMA.
/// </summary>
public class FlatTrendStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevAtr;
private decimal _prevClose;
private decimal _prevEma;
private bool _hasPrev;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public FlatTrendStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetDisplay("EMA Period", "EMA trend filter", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetDisplay("ATR Period", "ATR volatility period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
protected override void OnReseted() { base.OnReseted(); _prevAtr = 0m; _prevClose = 0m; _prevEma = 0m; _hasPrev = false; }
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_hasPrev = false;
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, atr, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal ema, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
if (!_hasPrev)
{
_prevAtr = atr;
_prevClose = close;
_prevEma = ema;
_hasPrev = true;
return;
}
// Volatility expansion: ATR increasing
var atrExpanding = atr > _prevAtr;
// Breakout above EMA with expanding volatility
if (atrExpanding && _prevClose <= _prevEma && close > ema && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Breakout below EMA with expanding volatility
else if (atrExpanding && _prevClose >= _prevEma && close < ema && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevAtr = atr;
_prevClose = close;
_prevEma = ema;
}
}
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 ExponentialMovingAverage, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class flat_trend_strategy(Strategy):
def __init__(self):
super(flat_trend_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20) \
.SetDisplay("EMA Period", "EMA trend filter", "Indicators")
self._atr_period = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "ATR volatility period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_atr = 0.0
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
@property
def ema_period(self):
return self._ema_period.Value
@property
def atr_period(self):
return self._atr_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(flat_trend_strategy, self).OnReseted()
self._prev_atr = 0.0
self._prev_close = 0.0
self._prev_ema = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(flat_trend_strategy, self).OnStarted2(time)
self._has_prev = False
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
atr = AverageTrueRange()
atr.Length = self.atr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, atr, self.process_candle).Start()
def process_candle(self, candle, ema, atr):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
ema_val = float(ema)
atr_val = float(atr)
if not self._has_prev:
self._prev_atr = atr_val
self._prev_close = close
self._prev_ema = ema_val
self._has_prev = True
return
atr_expanding = atr_val > self._prev_atr
if atr_expanding and self._prev_close <= self._prev_ema and close > ema_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif atr_expanding and self._prev_close >= self._prev_ema and close < ema_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_atr = atr_val
self._prev_close = close
self._prev_ema = ema_val
def CreateClone(self):
return flat_trend_strategy()