using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// EMA 6/12 crossover strategy with trailing stop management.
/// </summary>
public class Ema612CrossoverStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<decimal> _takeProfitOffset;
private readonly StrategyParam<decimal> _trailingStopOffset;
private readonly StrategyParam<decimal> _trailingStepOffset;
private ExponentialMovingAverage _fastSma;
private ExponentialMovingAverage _slowSma;
private decimal? _prevFast;
private decimal? _prevSlow;
private decimal? _entryPrice;
private decimal? _stopPrice;
private decimal? _takeProfitPrice;
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Fast moving average period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow moving average period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Take profit distance in absolute price units.
/// </summary>
public decimal TakeProfitOffset
{
get => _takeProfitOffset.Value;
set => _takeProfitOffset.Value = value;
}
/// <summary>
/// Trailing stop distance in absolute price units.
/// </summary>
public decimal TrailingStopOffset
{
get => _trailingStopOffset.Value;
set => _trailingStopOffset.Value = value;
}
/// <summary>
/// Additional distance required to move the trailing stop.
/// </summary>
public decimal TrailingStepOffset
{
get => _trailingStepOffset.Value;
set => _trailingStepOffset.Value = value;
}
/// <summary>
/// Initializes <see cref="Ema612CrossoverStrategy"/>.
/// </summary>
public Ema612CrossoverStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Candle resolution", "General");
_fastPeriod = Param(nameof(FastPeriod), 6)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Fast SMA length", "Moving Averages");
_slowPeriod = Param(nameof(SlowPeriod), 54)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Slow SMA length", "Moving Averages");
_takeProfitOffset = Param(nameof(TakeProfitOffset), 0.001m)
.SetNotNegative()
.SetDisplay("Take Profit", "Target distance in price units", "Risk");
_trailingStopOffset = Param(nameof(TrailingStopOffset), 0.005m)
.SetNotNegative()
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk");
_trailingStepOffset = Param(nameof(TrailingStepOffset), 0.0005m)
.SetNotNegative()
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetPositionState();
_prevFast = null;
_prevSlow = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (SlowPeriod <= FastPeriod)
throw new InvalidOperationException("Slow period must be greater than fast period.");
_fastSma = new ExponentialMovingAverage { Length = FastPeriod };
_slowSma = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastSma, _slowSma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastSma);
DrawIndicator(area, _slowSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastSma.IsFormed || !_slowSma.IsFormed)
return;
var bullishCross = false;
var bearishCross = false;
if (_prevFast.HasValue && _prevSlow.HasValue)
{
// Detect crossovers using previous candle values.
bullishCross = _prevSlow > _prevFast && slow < fast;
bearishCross = _prevSlow < _prevFast && slow > fast;
}
HandleExistingPosition(candle, bullishCross, bearishCross);
if (Position == 0)
{
if (bullishCross)
{
// Slow MA crossed below the fast MA - go long.
EnterLong(candle);
}
else if (bearishCross)
{
// Slow MA crossed above the fast MA - go short.
EnterShort(candle);
}
}
_prevFast = fast;
_prevSlow = slow;
}
private void HandleExistingPosition(ICandleMessage candle, bool bullishCross, bool bearishCross)
{
if (Position > 0)
{
// Update trailing stop for the long position before evaluating exits.
UpdateLongTrailing(candle);
var exit = bearishCross;
if (!exit && _takeProfitPrice.HasValue && candle.HighPrice >= _takeProfitPrice.Value)
{
// Price reached the take profit objective.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
{
// Price retraced to the trailing stop.
exit = true;
}
if (exit)
{
SellMarket(Position);
ResetPositionState();
}
}
else if (Position < 0)
{
// Update trailing stop for the short position before evaluating exits.
UpdateShortTrailing(candle);
var exit = bullishCross;
if (!exit && _takeProfitPrice.HasValue && candle.LowPrice <= _takeProfitPrice.Value)
{
// Price reached the take profit objective for the short trade.
exit = true;
}
if (!exit && _stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
{
// Price rallied back to the trailing stop level.
exit = true;
}
if (exit)
{
BuyMarket(Math.Abs(Position));
ResetPositionState();
}
}
}
private void EnterLong(ICandleMessage candle)
{
BuyMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice + TakeProfitOffset : null;
_stopPrice = null;
}
private void EnterShort(ICandleMessage candle)
{
SellMarket(Volume);
_entryPrice = candle.ClosePrice;
_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice - TakeProfitOffset : null;
_stopPrice = null;
}
private void UpdateLongTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = candle.ClosePrice - _entryPrice.Value;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice - TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || candidate - _stopPrice.Value > minAdvance)
{
// Move stop loss closer only when price progressed enough.
_stopPrice = candidate;
}
}
private void UpdateShortTrailing(ICandleMessage candle)
{
if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
return;
var gain = _entryPrice.Value - candle.ClosePrice;
var triggerDistance = TrailingStopOffset + TrailingStepOffset;
if (gain <= triggerDistance)
return;
var candidate = candle.ClosePrice + TrailingStopOffset;
var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;
if (!_stopPrice.HasValue || _stopPrice.Value - candidate > minAdvance)
{
// Move stop loss for the short only after sufficient favorable movement.
_stopPrice = candidate;
}
}
private void ResetPositionState()
{
_entryPrice = null;
_stopPrice = null;
_takeProfitPrice = null;
}
}
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
from StockSharp.Algo.Strategies import Strategy
class ema_612_crossover_strategy(Strategy):
"""
EMA 6/12 crossover strategy with trailing stop management.
Enters on EMA crossover, manages position with take profit and trailing stop.
"""
def __init__(self):
super(ema_612_crossover_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Candle resolution", "General")
self._fast_period = self.Param("FastPeriod", 6) \
.SetDisplay("Fast Period", "Fast EMA length", "Moving Averages")
self._slow_period = self.Param("SlowPeriod", 54) \
.SetDisplay("Slow Period", "Slow EMA length", "Moving Averages")
self._take_profit_offset = self.Param("TakeProfitOffset", 0.001) \
.SetDisplay("Take Profit", "Target distance in price units", "Risk")
self._trailing_stop_offset = self.Param("TrailingStopOffset", 0.005) \
.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk")
self._trailing_step_offset = self.Param("TrailingStepOffset", 0.0005) \
.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk")
self._prev_fast = None
self._prev_slow = None
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
self._fast_ema = None
self._slow_ema = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_612_crossover_strategy, self).OnReseted()
self._reset_position_state()
self._prev_fast = None
self._prev_slow = None
def OnStarted2(self, time):
super(ema_612_crossover_strategy, self).OnStarted2(time)
self._fast_ema = ExponentialMovingAverage()
self._fast_ema.Length = self._fast_period.Value
self._slow_ema = ExponentialMovingAverage()
self._slow_ema.Length = self._slow_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ema, self._slow_ema, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._fast_ema)
self.DrawIndicator(area, self._slow_ema)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
if not self._fast_ema.IsFormed or not self._slow_ema.IsFormed:
return
fast_val = float(fast_val)
slow_val = float(slow_val)
bullish_cross = False
bearish_cross = False
if self._prev_fast is not None and self._prev_slow is not None:
bullish_cross = self._prev_slow > self._prev_fast and slow_val < fast_val
bearish_cross = self._prev_slow < self._prev_fast and slow_val > fast_val
self._handle_existing_position(candle, bullish_cross, bearish_cross)
if self.Position == 0:
if bullish_cross:
self._enter_long(candle)
elif bearish_cross:
self._enter_short(candle)
self._prev_fast = fast_val
self._prev_slow = slow_val
def _handle_existing_position(self, candle, bullish_cross, bearish_cross):
if self.Position > 0:
self._update_long_trailing(candle)
do_exit = bearish_cross
if not do_exit and self._take_profit_price is not None and float(candle.HighPrice) >= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
do_exit = True
if do_exit:
self.SellMarket()
self._reset_position_state()
elif self.Position < 0:
self._update_short_trailing(candle)
do_exit = bullish_cross
if not do_exit and self._take_profit_price is not None and float(candle.LowPrice) <= self._take_profit_price:
do_exit = True
if not do_exit and self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
do_exit = True
if do_exit:
self.BuyMarket()
self._reset_position_state()
def _enter_long(self, candle):
self.BuyMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close + tp if tp > 0 else None
self._stop_price = None
def _enter_short(self, candle):
self.SellMarket()
close = float(candle.ClosePrice)
self._entry_price = close
tp = self._take_profit_offset.Value
self._take_profit_price = close - tp if tp > 0 else None
self._stop_price = None
def _update_long_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = close - self._entry_price
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close - trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or candidate - self._stop_price > min_advance:
self._stop_price = candidate
def _update_short_trailing(self, candle):
trail = self._trailing_stop_offset.Value
if trail <= 0 or self._entry_price is None:
return
close = float(candle.ClosePrice)
gain = self._entry_price - close
step = self._trailing_step_offset.Value
trigger = trail + step
if gain <= trigger:
return
candidate = close + trail
min_advance = step if step > 0 else 0.0
if self._stop_price is None or self._stop_price - candidate > min_advance:
self._stop_price = candidate
def _reset_position_state(self):
self._entry_price = None
self._stop_price = None
self._take_profit_price = None
def CreateClone(self):
return ema_612_crossover_strategy()