EMAクロスオーバー・トレーリングストップ戦略
EMAクロスオーバー・トレーリングストップ戦略は、短期EMAが長期EMAを上抜けしたときにロングポジションを開き、下抜けしたときにショートポジションを開きます。エントリー後の最高値または最安値に基づくトレーリングストップは、価格が設定したパーセンテージ分反転したときにポジションを決済します。
詳細
- エントリー条件: 短期EMAが長期EMAをクロスする。
- ロング/ショート: 両方向。
- エグジット条件: 逆クロスまたはトレーリングストップ。
- ストップ: エントリー後の最高値/最安値を使用したトレーリングストップ。
- デフォルト値:
ShortLength = 9LongLength = 21TrailStopPercent = 1
- フィルター:
- カテゴリ: トレンドフォロー
- 方向: 両方
- インジケーター: EMA
- ストップ: トレーリングストップ
- 複雑さ: 基本
- 時間軸: 短期
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// EMA crossover trailing stop strategy.
/// The short EMA crossing above the long EMA goes long and crossing below goes short, reversing an opposite position.
/// A percent trailing stop follows the best price since entry and closes the position when price reverses by TrailStopPercent.
/// </summary>
public class EmaCrossoverTrailingStopStrategy : Strategy
{
private readonly StrategyParam<int> _shortLength;
private readonly StrategyParam<int> _longLength;
private readonly StrategyParam<decimal> _trailStopPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevShort;
private decimal? _prevLong;
/// <summary>
/// Short EMA length.
/// </summary>
public int ShortLength
{
get => _shortLength.Value;
set => _shortLength.Value = value;
}
/// <summary>
/// Long EMA length.
/// </summary>
public int LongLength
{
get => _longLength.Value;
set => _longLength.Value = value;
}
/// <summary>
/// Trailing stop percentage.
/// </summary>
public decimal TrailStopPercent
{
get => _trailStopPercent.Value;
set => _trailStopPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public EmaCrossoverTrailingStopStrategy()
{
_shortLength = Param(nameof(ShortLength), 9)
.SetGreaterThanZero()
.SetDisplay("Short EMA", "Short EMA length", "Indicators");
_longLength = Param(nameof(LongLength), 21)
.SetGreaterThanZero()
.SetDisplay("Long EMA", "Long EMA length", "Indicators");
_trailStopPercent = Param(nameof(TrailStopPercent), 1m)
.SetNotNegative()
.SetDisplay("Trailing Stop %", "Trailing stop percentage from the best 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();
_prevShort = null;
_prevLong = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevShort = null;
_prevLong = null;
var shortEma = new ExponentialMovingAverage { Length = ShortLength };
var longEma = new ExponentialMovingAverage { Length = LongLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(shortEma, longEma, ProcessCandle)
.Start();
if (TrailStopPercent > 0m)
StartProtection(new Unit(), new Unit(TrailStopPercent, UnitTypes.Percent), isStopTrailing: true, useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, shortEma);
DrawIndicator(area, longEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal shortValue, decimal longValue)
{
if (candle.State != CandleStates.Finished)
return;
var prevShort = _prevShort;
var prevLong = _prevLong;
_prevShort = shortValue;
_prevLong = longValue;
if (prevShort is not decimal ps || prevLong is not decimal pl)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (ps <= pl && shortValue > longValue && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (ps >= pl && shortValue < longValue && Position >= 0)
SellMarket(Volume + Math.Abs(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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_crossover_trailing_stop_strategy(Strategy):
"""
EMA crossover trailing stop strategy.
The short EMA crossing above the long EMA goes long and crossing below goes short, reversing an opposite position.
A percent trailing stop follows the best price since entry and closes the position when price reverses by TrailStopPercent.
"""
def __init__(self):
super(ema_crossover_trailing_stop_strategy, self).__init__()
self._short_length = self.Param("ShortLength", 9).SetGreaterThanZero().SetDisplay("Short EMA", "Short EMA length", "Indicators")
self._long_length = self.Param("LongLength", 21).SetGreaterThanZero().SetDisplay("Long EMA", "Long EMA length", "Indicators")
self._trail_stop_percent = self.Param("TrailStopPercent", 1.0).SetNotNegative().SetDisplay("Trailing Stop %", "Trailing stop percentage from the best price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_short = None
self._prev_long = None
def OnReseted(self):
super(ema_crossover_trailing_stop_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(ema_crossover_trailing_stop_strategy, self).OnStarted2(time)
self._reset_state()
short_ema = ExponentialMovingAverage()
short_ema.Length = self._short_length.Value
long_ema = ExponentialMovingAverage()
long_ema.Length = self._long_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(short_ema, long_ema, self._process_candle).Start()
trail = float(self._trail_stop_percent.Value)
if trail > 0:
self.StartProtection(Unit(), Unit(Decimal(trail), UnitTypes.Percent), isStopTrailing=True, useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, short_ema)
self.DrawIndicator(area, long_ema)
self.DrawOwnTrades(area)
def _process_candle(self, candle, short_value, long_value):
if candle.State != CandleStates.Finished:
return
short_v = float(short_value)
long_v = float(long_value)
prev_short = self._prev_short
prev_long = self._prev_long
self._prev_short = short_v
self._prev_long = long_v
if prev_short is None or prev_long is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if prev_short <= prev_long and short_v > long_v and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif prev_short >= prev_long and short_v < long_v and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return ema_crossover_trailing_stop_strategy()