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 price position relative to SMA envelopes.
/// Buys when price is below the lower envelope, sells when above upper.
/// </summary>
public class JpalonsoModokiStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _smaPeriod;
private readonly StrategyParam<decimal> _deviation;
private readonly StrategyParam<Unit> _takeProfit;
private readonly StrategyParam<Unit> _stopLoss;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int SmaPeriod { get => _smaPeriod.Value; set => _smaPeriod.Value = value; }
public decimal Deviation { get => _deviation.Value; set => _deviation.Value = value; }
public Unit TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
public Unit StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
public JpalonsoModokiStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_smaPeriod = Param(nameof(SmaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("SMA Period", "Length of the moving average", "Envelopes");
_deviation = Param(nameof(Deviation), 0.35m)
.SetDisplay("Deviation %", "Envelope deviation from SMA in percent", "Envelopes");
_takeProfit = Param(nameof(TakeProfit), new Unit(3000, UnitTypes.Absolute))
.SetDisplay("Take Profit", "Take profit in points", "Risk Management");
_stopLoss = Param(nameof(StopLoss), new Unit(5000, UnitTypes.Absolute))
.SetDisplay("Stop Loss", "Stop loss in points", "Risk Management");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(takeProfit: TakeProfit, stopLoss: StopLoss);
var sma = new SimpleMovingAverage { Length = SmaPeriod };
SubscribeCandles(CandleType)
.Bind(sma, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal ma)
{
if (candle.State != CandleStates.Finished)
return;
var upper = ma * (1 + Deviation / 100m);
var lower = ma * (1 - Deviation / 100m);
var close = candle.ClosePrice;
var buy = close <= lower;
var sell = close >= upper;
if (buy && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (sell && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
}
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class jpalonso_modoki_strategy(Strategy):
"""
SMA envelope strategy. Buys when price is below the lower envelope,
sells when above the upper. Uses StartProtection for SL/TP.
"""
def __init__(self):
super(jpalonso_modoki_strategy, self).__init__()
self._sma_period = self.Param("SmaPeriod", 20) \
.SetDisplay("SMA Period", "Length of the moving average", "Envelopes")
self._deviation = self.Param("Deviation", 0.35) \
.SetDisplay("Deviation %", "Envelope deviation from SMA in percent", "Envelopes")
self._take_profit = self.Param("TakeProfit", 3000.0) \
.SetDisplay("Take Profit", "Take profit in points", "Risk Management")
self._stop_loss = self.Param("StopLoss", 5000.0) \
.SetDisplay("Stop Loss", "Stop loss in points", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(jpalonso_modoki_strategy, self).OnStarted2(time)
tp = Unit(self._take_profit.Value, UnitTypes.Absolute)
sl = Unit(self._stop_loss.Value, UnitTypes.Absolute)
self.StartProtection(tp, sl)
sma = SimpleMovingAverage()
sma.Length = self._sma_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self._process_candle).Start()
def _process_candle(self, candle, ma_val):
if candle.State != CandleStates.Finished:
return
ma = float(ma_val)
dev = self._deviation.Value
upper = ma * (1.0 + dev / 100.0)
lower = ma * (1.0 - dev / 100.0)
close = float(candle.ClosePrice)
if close <= lower and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif close >= upper and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
def CreateClone(self):
return jpalonso_modoki_strategy()