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>
/// EF Distance reversal strategy.
/// Uses a smoothed price series and ATR filter to trade turning points.
/// </summary>
public class EfDistanceStrategy : Strategy
{
private readonly StrategyParam<int> _smaPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prev;
private decimal? _prev2;
public int SmaPeriod { get => _smaPeriod.Value; set => _smaPeriod.Value = value; }
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EfDistanceStrategy()
{
_smaPeriod = Param(nameof(SmaPeriod), 10)
.SetGreaterThanZero()
.SetDisplay("SMA Period", "Period for the smoothing moving average", "Indicator");
_atrPeriod = Param(nameof(AtrPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "Period for the volatility filter", "Indicator");
_atrMultiplier = Param(nameof(AtrMultiplier), 0.5m)
.SetDisplay("ATR Multiplier", "Minimum ATR relative to price", "Indicator");
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_takeProfitPct = Param(nameof(TakeProfitPct), 4m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles for calculations", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prev = null;
_prev2 = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = SmaPeriod };
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.BindEx(ema, atr, ProcessCandle).Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue emaVal, IIndicatorValue atrVal)
{
if (candle.State != CandleStates.Finished)
return;
if (!emaVal.IsFormed || !atrVal.IsFormed)
return;
var smaValue = emaVal.ToDecimal();
var atrValue = atrVal.ToDecimal();
if (_prev is null || _prev2 is null)
{
_prev2 = _prev;
_prev = smaValue;
return;
}
if (!IsFormedAndOnlineAndAllowTrading())
return;
var atrEnough = atrValue >= AtrMultiplier / 100m * candle.ClosePrice;
if (atrEnough)
{
if (_prev < _prev2 && smaValue > _prev && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (_prev > _prev2 && smaValue < _prev && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
}
_prev2 = _prev;
_prev = smaValue;
}
}
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
from StockSharp.Algo.Indicators import ExponentialMovingAverage, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class ef_distance_strategy(Strategy):
def __init__(self):
super(ef_distance_strategy, self).__init__()
self._sma_period = self.Param("SmaPeriod", 10) \
.SetDisplay("SMA Period", "Period for the smoothing moving average", "Indicator")
self._atr_period = self.Param("AtrPeriod", 20) \
.SetDisplay("ATR Period", "Period for the volatility filter", "Indicator")
self._atr_multiplier = self.Param("AtrMultiplier", 0.5) \
.SetDisplay("ATR Multiplier", "Minimum ATR relative to price", "Indicator")
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._take_profit_pct = self.Param("TakeProfitPct", 4.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles for calculations", "General")
self._prev = None
self._prev2 = None
@property
def sma_period(self):
return self._sma_period.Value
@property
def atr_period(self):
return self._atr_period.Value
@property
def atr_multiplier(self):
return self._atr_multiplier.Value
@property
def stop_loss_pct(self):
return self._stop_loss_pct.Value
@property
def take_profit_pct(self):
return self._take_profit_pct.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ef_distance_strategy, self).OnReseted()
self._prev = None
self._prev2 = None
def OnStarted2(self, time):
super(ef_distance_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.sma_period
atr = AverageTrueRange()
atr.Length = self.atr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(ema, atr, self.process_candle).Start()
self.StartProtection(
takeProfit=Unit(self.take_profit_pct, UnitTypes.Percent),
stopLoss=Unit(self.stop_loss_pct, UnitTypes.Percent),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def process_candle(self, candle, ema_val, atr_val):
if candle.State != CandleStates.Finished:
return
if not ema_val.IsFormed or not atr_val.IsFormed:
return
sma_value = float(ema_val)
atr_value = float(atr_val)
if self._prev is None or self._prev2 is None:
self._prev2 = self._prev
self._prev = sma_value
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
atr_enough = atr_value >= float(self.atr_multiplier) / 100.0 * float(candle.ClosePrice)
if atr_enough:
if self._prev < self._prev2 and sma_value > self._prev and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif self._prev > self._prev2 and sma_value < self._prev and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev2 = self._prev
self._prev = sma_value
def CreateClone(self):
return ef_distance_strategy()