Estrategia de Señal de Cruce de EMA
Esta estrategia opera en el cruce de dos Medias Móviles Exponenciales (EMA). Una EMA más rápida y una más lenta se calculan a partir de la serie de velas elegida. Cuando la EMA rápida cruza por encima de la EMA lenta, la estrategia puede cerrar cualquier posición corta existente y opcionalmente abrir una posición larga. Cuando la EMA rápida cruza por debajo de la EMA lenta, puede cerrar una posición larga y opcionalmente abrir una posición corta.
Para gestionar el riesgo, la estrategia permite colocar órdenes de take profit y stop loss después de abrir una nueva posición. Ambas distancias se especifican en ticks. Estas órdenes de protección se cancelan y recrean en cada nueva entrada.
La estrategia proporciona interruptores separados para habilitar o deshabilitar entradas largas y cortas, así como para cerrar independientemente posiciones largas y cortas en la señal opuesta. Todos los cálculos usan únicamente velas finalizadas.
Parámetros
- Fast Period – longitud de la EMA rápida.
- Slow Period – longitud de la EMA lenta.
- Candle Type – marco temporal de las velas usadas para los cálculos.
- Allow Buy Open – abrir largo cuando la EMA rápida cruza por encima de la EMA lenta.
- Allow Sell Open – abrir corto cuando la EMA rápida cruza por debajo de la EMA lenta.
- Allow Buy Close – cerrar largo cuando la EMA rápida cruza por debajo de la EMA lenta.
- Allow Sell Close – cerrar corto cuando la EMA rápida cruza por encima de la EMA lenta.
- Take Profit Ticks – distancia de take profit en ticks desde el precio de entrada.
- Stop Loss Ticks – distancia de stop loss en ticks desde el precio de entrada.
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>
/// Trades EMA crossovers with optional separate entry and exit permissions for long and short positions.
/// </summary>
public class EmaCrossoverSignalStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<bool> _allowBuyOpen, _allowSellOpen, _allowBuyClose, _allowSellClose;
private readonly StrategyParam<decimal> _stopLossTicks, _takeProfitTicks;
private Order _pending;
private bool _isInitialized;
private bool _wasFastAboveSlow;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public bool AllowBuyOpen { get => _allowBuyOpen.Value; set => _allowBuyOpen.Value = value; }
public bool AllowSellOpen { get => _allowSellOpen.Value; set => _allowSellOpen.Value = value; }
public bool AllowBuyClose { get => _allowBuyClose.Value; set => _allowBuyClose.Value = value; }
public bool AllowSellClose { get => _allowSellClose.Value; set => _allowSellClose.Value = value; }
public decimal StopLossTicks { get => _stopLossTicks.Value; set => _stopLossTicks.Value = value; }
public decimal TakeProfitTicks { get => _takeProfitTicks.Value; set => _takeProfitTicks.Value = value; }
public EmaCrossoverSignalStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 5)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Length of the fast EMA", "EMA");
_slowPeriod = Param(nameof(SlowPeriod), 13)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Length of the slow EMA", "EMA");
_allowBuyOpen = Param(nameof(AllowBuyOpen), true);
_allowSellOpen = Param(nameof(AllowSellOpen), true);
_allowBuyClose = Param(nameof(AllowBuyClose), true);
_allowSellClose = Param(nameof(AllowSellClose), true);
_stopLossTicks = Param(nameof(StopLossTicks), 1000m).SetNotNegative();
_takeProfitTicks = Param(nameof(TakeProfitTicks), 2000m).SetNotNegative();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for calculations", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_isInitialized = default;
_wasFastAboveSlow = default;
_pending = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_pending = null;
var step = Security?.PriceStep ?? 1m;
StartProtection(takeProfit: new Unit(TakeProfitTicks * step, UnitTypes.Absolute), stopLoss: new Unit(StopLossTicks * step, UnitTypes.Absolute), useMarketOrders: true);
var fastEma = new ExponentialMovingAverage { Length = FastPeriod };
var slowEma = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, Process)
.Start();
}
private void Process(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_isInitialized)
{
_wasFastAboveSlow = fastValue > slowValue;
_isInitialized = true;
return;
}
var isFastAboveSlow = fastValue > slowValue;
var crossing = _wasFastAboveSlow != isFastAboveSlow;
_wasFastAboveSlow = isFastAboveSlow;
if (!crossing || !IsFormedAndOnlineAndAllowTrading() || (_pending is not null && _pending.State is not (OrderStates.Done or OrderStates.Failed))) return;
if (isFastAboveSlow)
{
if (Position < 0m && AllowSellClose) _pending = BuyMarket(-Position + (AllowBuyOpen ? Volume : 0m));
else if (Position == 0m && AllowBuyOpen) _pending = BuyMarket(Volume);
}
else
{
if (Position > 0m && AllowBuyClose) _pending = SellMarket(Position + (AllowSellOpen ? Volume : 0m));
else if (Position == 0m && AllowSellOpen) _pending = SellMarket(Volume);
}
}
}
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, Unit, UnitTypes, OrderStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_crossover_signal_strategy(Strategy):
def __init__(self):
super(ema_crossover_signal_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 5) \
.SetDisplay("Fast Period", "Length of the fast EMA", "EMA")
self._slow_period = self.Param("SlowPeriod", 13) \
.SetDisplay("Slow Period", "Length of the slow EMA", "EMA")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for calculations", "General")
self._allow_buy_open = self.Param("AllowBuyOpen", True)
self._allow_sell_open = self.Param("AllowSellOpen", True)
self._allow_buy_close = self.Param("AllowBuyClose", True)
self._allow_sell_close = self.Param("AllowSellClose", True)
self._stop_loss_ticks = self.Param("StopLossTicks", 1000.0)
self._take_profit_ticks = self.Param("TakeProfitTicks", 2000.0)
self._pending = None
self._is_initialized = False
self._was_fast_above_slow = False
@property
def FastPeriod(self):
return self._fast_period.Value
@FastPeriod.setter
def FastPeriod(self, value):
self._fast_period.Value = value
@property
def SlowPeriod(self):
return self._slow_period.Value
@SlowPeriod.setter
def SlowPeriod(self, value):
self._slow_period.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(ema_crossover_signal_strategy, self).OnStarted2(time)
self._pending = None
step = self.Security.PriceStep if self.Security.PriceStep and self.Security.PriceStep > 0 else 1
self.StartProtection(takeProfit=Unit(self._take_profit_ticks.Value * step, UnitTypes.Absolute), stopLoss=Unit(self._stop_loss_ticks.Value * step, UnitTypes.Absolute), useMarketOrders=True)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.FastPeriod
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.SlowPeriod
self.SubscribeCandles(self.CandleType) \
.Bind(fast_ema, slow_ema, self.ProcessCandle) \
.Start()
def ProcessCandle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast = float(fast_value)
slow = float(slow_value)
if not self._is_initialized:
self._was_fast_above_slow = fast > slow
self._is_initialized = True
return
is_fast_above_slow = fast > slow
crossing = self._was_fast_above_slow != is_fast_above_slow
self._was_fast_above_slow = is_fast_above_slow
if not crossing or not self.IsFormedAndOnlineAndAllowTrading() or (self._pending is not None and self._pending.State not in (OrderStates.Done, OrderStates.Failed)):
return
if is_fast_above_slow:
if self.Position < 0 and self._allow_sell_close.Value:
self._pending = self.BuyMarket(-self.Position + (self.Volume if self._allow_buy_open.Value else 0))
elif self.Position == 0 and self._allow_buy_open.Value:
self._pending = self.BuyMarket(self.Volume)
else:
if self.Position > 0 and self._allow_buy_close.Value:
self._pending = self.SellMarket(self.Position + (self.Volume if self._allow_sell_open.Value else 0))
elif self.Position == 0 and self._allow_sell_open.Value:
self._pending = self.SellMarket(self.Volume)
def OnReseted(self):
super(ema_crossover_signal_strategy, self).OnReseted()
self._is_initialized = False
self._was_fast_above_slow = False
def CreateClone(self):
return ema_crossover_signal_strategy()