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>
/// Strategy based on zero crossing of the price derivative.
/// The derivative is calculated as momentum divided by period.
/// When the derivative switches sign, the position is reversed.
/// </summary>
public class DerivativeZeroCrossStrategy : Strategy
{
private readonly StrategyParam<int> _derivativePeriod;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevDerivative;
public int DerivativePeriod
{
get => _derivativePeriod.Value;
set => _derivativePeriod.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 DerivativeZeroCrossStrategy()
{
_derivativePeriod = Param(nameof(DerivativePeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Derivative Period", "Smoothing period for derivative", "Indicator");
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
.SetGreaterThanZero();
_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevDerivative = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var momentum = new Momentum { Length = DerivativePeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(momentum, (candle, momValue) =>
{
if (candle.State != CandleStates.Finished)
return;
var derivative = momValue / DerivativePeriod * 100m;
if (_prevDerivative is null)
{
_prevDerivative = derivative;
return;
}
var prev = _prevDerivative.Value;
// Derivative crossed up through zero -> buy
if (prev <= 0m && derivative > 0m)
{
if (Position < 0) BuyMarket();
if (Position <= 0) BuyMarket();
}
// Derivative crossed down through zero -> sell
else if (prev >= 0m && derivative < 0m)
{
if (Position > 0) SellMarket();
if (Position >= 0) SellMarket();
}
_prevDerivative = derivative;
}).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, momentum);
DrawOwnTrades(area);
}
}
}
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 Momentum
from StockSharp.Algo.Strategies import Strategy
class derivative_zero_cross_strategy(Strategy):
def __init__(self):
super(derivative_zero_cross_strategy, self).__init__()
self._derivative_period = self.Param("DerivativePeriod", 14) \
.SetDisplay("Derivative Period", "Smoothing period for derivative", "Indicator")
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._take_profit_pct = self.Param("TakeProfitPct", 3.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", "General")
self._prev_derivative = None
@property
def derivative_period(self):
return self._derivative_period.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(derivative_zero_cross_strategy, self).OnReseted()
self._prev_derivative = None
def OnStarted2(self, time):
super(derivative_zero_cross_strategy, self).OnStarted2(time)
momentum = Momentum()
momentum.Length = self.derivative_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(momentum, 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, momentum)
self.DrawOwnTrades(area)
def process_candle(self, candle, mom_value):
if candle.State != CandleStates.Finished:
return
mom_value = float(mom_value)
derivative = mom_value / float(self.derivative_period) * 100.0
if self._prev_derivative is None:
self._prev_derivative = derivative
return
prev = self._prev_derivative
if prev <= 0.0 and derivative > 0.0:
if self.Position < 0:
self.BuyMarket()
if self.Position <= 0:
self.BuyMarket()
elif prev >= 0.0 and derivative < 0.0:
if self.Position > 0:
self.SellMarket()
if self.Position >= 0:
self.SellMarket()
self._prev_derivative = derivative
def CreateClone(self):
return derivative_zero_cross_strategy()