私をクロスさせないで
垂直シフトを伴うEMAクロスオーバー戦略。
詳細
- エントリー条件:
- ロング: シフトされた短期EMAがシフトされた長期EMAを上抜け。
- ショート: シフトされた短期EMAがシフトされた長期EMAを下抜け。
- ロング/ショート: 両方向。
- エグジット条件: 逆方向のクロスオーバー。
- ストップ: いいえ。
- デフォルト値:
ShortEmaLength= 9LongEmaLength= 21ShiftAmount= -50CandleType= TimeSpan.FromMinutes(1)
- フィルター:
- カテゴリ: トレンド
- 方向: 両方
- インジケーター: EMA
- ストップ: いいえ
- 複雑さ: 基本
- 時間軸: イントラデイ (1m)
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Dont Make Me Cross strategy.
/// Both EMAs are shifted vertically by ShiftAmount. A cross of the shifted short EMA above the shifted long EMA goes long,
/// a cross below goes short, and the opposite cross reverses the position.
/// </summary>
public class DontMakeMeCrossStrategy : Strategy
{
private readonly StrategyParam<int> _shortEmaLength;
private readonly StrategyParam<int> _longEmaLength;
private readonly StrategyParam<decimal> _shiftAmount;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevShort;
private decimal? _prevLong;
/// <summary>
/// Short EMA period.
/// </summary>
public int ShortEmaLength
{
get => _shortEmaLength.Value;
set => _shortEmaLength.Value = value;
}
/// <summary>
/// Long EMA period.
/// </summary>
public int LongEmaLength
{
get => _longEmaLength.Value;
set => _longEmaLength.Value = value;
}
/// <summary>
/// Vertical shift added to both EMAs.
/// </summary>
public decimal ShiftAmount
{
get => _shiftAmount.Value;
set => _shiftAmount.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public DontMakeMeCrossStrategy()
{
_shortEmaLength = Param(nameof(ShortEmaLength), 9)
.SetGreaterThanZero()
.SetDisplay("Short EMA", "Short EMA period", "Indicators");
_longEmaLength = Param(nameof(LongEmaLength), 21)
.SetGreaterThanZero()
.SetDisplay("Long EMA", "Long EMA period", "Indicators");
_shiftAmount = Param(nameof(ShiftAmount), -50m)
.SetDisplay("Shift Amount", "Vertical shift added to both EMAs", "Indicators");
_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 = ShortEmaLength };
var longEma = new ExponentialMovingAverage { Length = LongEmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(shortEma, longEma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, shortEma);
DrawIndicator(area, longEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue shortValue, IIndicatorValue longValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!shortValue.IsFormed || !longValue.IsFormed)
return;
var shortEma = shortValue.GetValue<decimal>() + ShiftAmount;
var longEma = longValue.GetValue<decimal>() + ShiftAmount;
var prevShort = _prevShort;
var prevLong = _prevLong;
_prevShort = shortEma;
_prevLong = longEma;
if (prevShort is not decimal ps || prevLong is not decimal pl)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var crossUp = ps <= pl && shortEma > longEma;
var crossDown = ps >= pl && shortEma < longEma;
if (crossUp && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (crossDown && 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
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class dont_make_me_cross_strategy(Strategy):
"""
Dont Make Me Cross strategy.
Both EMAs are shifted vertically by ShiftAmount. A cross of the shifted short EMA above the shifted long EMA goes long,
a cross below goes short, and the opposite cross reverses the position.
"""
def __init__(self):
super(dont_make_me_cross_strategy, self).__init__()
self._short_ema_length = self.Param("ShortEmaLength", 9).SetGreaterThanZero().SetDisplay("Short EMA", "Short EMA period", "Indicators")
self._long_ema_length = self.Param("LongEmaLength", 21).SetGreaterThanZero().SetDisplay("Long EMA", "Long EMA period", "Indicators")
self._shift_amount = self.Param("ShiftAmount", -50.0).SetDisplay("Shift Amount", "Vertical shift added to both EMAs", "Indicators")
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(dont_make_me_cross_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(dont_make_me_cross_strategy, self).OnStarted2(time)
self._reset_state()
short_ema = ExponentialMovingAverage()
short_ema.Length = self._short_ema_length.Value
long_ema = ExponentialMovingAverage()
long_ema.Length = self._long_ema_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(short_ema, long_ema, self._process_candle).Start()
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
if not short_value.IsFormed or not long_value.IsFormed:
return
shift = Decimal(self._shift_amount.Value)
short_ema = short_value.GetValue[Decimal](None) + shift
long_ema = long_value.GetValue[Decimal](None) + shift
prev_short = self._prev_short
prev_long = self._prev_long
self._prev_short = short_ema
self._prev_long = long_ema
if prev_short is None or prev_long is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
cross_up = prev_short <= prev_long and short_ema > long_ema
cross_down = prev_short >= prev_long and short_ema < long_ema
if cross_up and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif cross_down and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return dont_make_me_cross_strategy()