Elliott Wave Supertrend エグジット戦略
ZigZag状のリバーサルでエントリーし、Supertrendの方向転換または固定パーセンテージのストップロスでエグジットする戦略です。
詳細
- エントリー条件:
- ロング: 価格がローカル安値を形成
- ショート: 価格がローカル高値を形成
- ロング/ショート: 両方
- エグジット条件:
- Supertrendの方向転換またはストップロスレベル
- ストップ: エントリー価格からの固定パーセンテージ
- デフォルト値:
WaveLength= 4SupertrendLength= 10SupertrendMultiplier= 3StopLossPercent= 10CandleType= TimeSpan.FromMinutes(1).TimeFrame()
- フィルター:
- カテゴリ: トレンド
- 方向: 両方
- インジケーター: Highest, Lowest, SuperTrend
- ストップ: あり
- 複雑さ: 中級
- 時間軸: 短期
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Elliott Wave Supertrend Exit strategy.
/// A candle whose low is the lowest low of the last WaveLength candles is a local low and goes long; a candle whose high
/// is the highest high of the last WaveLength candles is a local high and goes short, reversing an opposite position.
/// A long closes when the Supertrend turns down and a short when it turns up, and a percent stop limits the loss.
/// </summary>
public class ElliottWaveSupertrendExitStrategy : Strategy
{
private readonly StrategyParam<int> _waveLength;
private readonly StrategyParam<int> _supertrendLength;
private readonly StrategyParam<decimal> _supertrendMultiplier;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private Highest _highest;
private Lowest _lowest;
private bool? _prevIsUpTrend;
/// <summary>
/// Candles that define a local high or low.
/// </summary>
public int WaveLength
{
get => _waveLength.Value;
set => _waveLength.Value = value;
}
/// <summary>
/// Supertrend ATR length.
/// </summary>
public int SupertrendLength
{
get => _supertrendLength.Value;
set => _supertrendLength.Value = value;
}
/// <summary>
/// Supertrend ATR multiplier.
/// </summary>
public decimal SupertrendMultiplier
{
get => _supertrendMultiplier.Value;
set => _supertrendMultiplier.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public ElliottWaveSupertrendExitStrategy()
{
_waveLength = Param(nameof(WaveLength), 4)
.SetGreaterThanZero()
.SetDisplay("Wave Length", "Candles that define a local high or low", "Indicators");
_supertrendLength = Param(nameof(SupertrendLength), 10)
.SetGreaterThanZero()
.SetDisplay("Supertrend Length", "Supertrend ATR length", "Indicators");
_supertrendMultiplier = Param(nameof(SupertrendMultiplier), 3m)
.SetGreaterThanZero()
.SetDisplay("Supertrend Multiplier", "Supertrend ATR multiplier", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 10m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).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();
_prevIsUpTrend = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevIsUpTrend = null;
_highest = new Highest { Length = WaveLength };
_lowest = new Lowest { Length = WaveLength };
var supertrend = new SuperTrend { Length = SupertrendLength, Multiplier = SupertrendMultiplier };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(supertrend, ProcessCandle)
.Start();
StartProtection(new Unit(), StopLossPercent > 0 ? new Unit(StopLossPercent, UnitTypes.Percent) : new Unit(), useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, supertrend);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue supertrendValue)
{
if (candle.State != CandleStates.Finished)
return;
var highValue = _highest.Process(new DecimalIndicatorValue(_highest, candle.HighPrice, candle.OpenTime) { IsFinal = true });
var lowValue = _lowest.Process(new DecimalIndicatorValue(_lowest, candle.LowPrice, candle.OpenTime) { IsFinal = true });
if (!supertrendValue.IsFormed || !highValue.IsFormed || !lowValue.IsFormed)
return;
var isUpTrend = ((SuperTrendIndicatorValue)supertrendValue).IsUpTrend;
var prevIsUpTrend = _prevIsUpTrend;
_prevIsUpTrend = isUpTrend;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var localHigh = candle.HighPrice >= highValue.GetValue<decimal>();
var localLow = candle.LowPrice <= lowValue.GetValue<decimal>();
// A candle that is both the highest and the lowest of the window gives no direction.
if (localLow && !localHigh && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (localHigh && !localLow && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && prevIsUpTrend == true && !isUpTrend)
SellMarket(Position);
else if (Position < 0 && prevIsUpTrend == false && isUpTrend)
BuyMarket(-Position);
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import Highest, Lowest, SuperTrend
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class elliott_wave_supertrend_exit_strategy(Strategy):
"""
Elliott Wave Supertrend Exit strategy.
A candle whose low is the lowest low of the last WaveLength candles is a local low and goes long; a candle whose high
is the highest high of the last WaveLength candles is a local high and goes short, reversing an opposite position.
A long closes when the Supertrend turns down and a short when it turns up, and a percent stop limits the loss.
"""
def __init__(self):
super(elliott_wave_supertrend_exit_strategy, self).__init__()
self._wave_length = self.Param("WaveLength", 4).SetGreaterThanZero().SetDisplay("Wave Length", "Candles that define a local high or low", "Indicators")
self._supertrend_length = self.Param("SupertrendLength", 10).SetGreaterThanZero().SetDisplay("Supertrend Length", "Supertrend ATR length", "Indicators")
self._supertrend_multiplier = self.Param("SupertrendMultiplier", 3.0).SetGreaterThanZero().SetDisplay("Supertrend Multiplier", "Supertrend ATR multiplier", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 10.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._highest = None
self._lowest = None
self._prev_is_up_trend = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(elliott_wave_supertrend_exit_strategy, self).OnReseted()
self._prev_is_up_trend = None
def OnStarted2(self, time):
super(elliott_wave_supertrend_exit_strategy, self).OnStarted2(time)
self._prev_is_up_trend = None
self._highest = Highest()
self._highest.Length = self._wave_length.Value
self._lowest = Lowest()
self._lowest.Length = self._wave_length.Value
supertrend = SuperTrend()
supertrend.Length = self._supertrend_length.Value
supertrend.Multiplier = Decimal(self._supertrend_multiplier.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(supertrend, self._process_candle).Start()
stop_percent = Decimal(self._stop_loss_percent.Value)
stop = Unit(stop_percent, UnitTypes.Percent) if stop_percent > 0 else Unit()
self.StartProtection(Unit(), stop, useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, supertrend)
self.DrawOwnTrades(area)
def _process_candle(self, candle, supertrend_value):
if candle.State != CandleStates.Finished:
return
high_result = process_float(self._highest, candle.HighPrice, candle.OpenTime, True)
low_result = process_float(self._lowest, candle.LowPrice, candle.OpenTime, True)
if not supertrend_value.IsFormed or not high_result.IsFormed or not low_result.IsFormed:
return
is_up_trend = bool(supertrend_value.IsUpTrend)
prev_is_up_trend = self._prev_is_up_trend
self._prev_is_up_trend = is_up_trend
if not self.IsFormedAndOnlineAndAllowTrading():
return
local_high = float(candle.HighPrice) >= float(high_result)
local_low = float(candle.LowPrice) <= float(low_result)
# A candle that is both the highest and the lowest of the window gives no direction.
if local_low and not local_high and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif local_high and not local_low and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and prev_is_up_trend is True and not is_up_trend:
self.SellMarket(self.Position)
elif self.Position < 0 and prev_is_up_trend is False and is_up_trend:
self.BuyMarket(-self.Position)
def CreateClone(self):
return elliott_wave_supertrend_exit_strategy()