Стратегия JSatl Digit System
Пример демонстрирует упрощённый перенос экспертной системы MQL5 "JSatl Digit System" на StockSharp.
Стратегия использует скользящую среднюю Jurik (JMA) для формирования цифрового состояния тренда:
- Когда цена закрытия выше JMA, состояние становится вверх.
- Когда цена закрытия ниже JMA, состояние становится вниз.
При смене состояния на вверх короткие позиции могут закрываться и/или открывается длинная позиция в зависимости от параметров. При смене состояния на вниз длинные позиции могут закрываться и/или открывается короткая позиция.
Параметры
JmaLength– период JMA.CandleType– тип свечей для расчёта.StopLossPercent– защитный стоп-лосс в процентах.TakeProfitPercent– защитный тейк-профит в процентах.BuyPosOpen,SellPosOpen,BuyPosClose,SellPosClose– включение или отключение действий по соответствующим сигналам.
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>
/// JSatl Digit System strategy based on the Jurik Moving Average.
/// Generates digital trend states to open or close positions.
/// </summary>
public class JSatlDigitSystemStrategy : Strategy
{
private readonly StrategyParam<int> _jmaLength;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<decimal> _takeProfitPercent;
private readonly StrategyParam<bool> _buyPosOpen;
private readonly StrategyParam<bool> _sellPosOpen;
private readonly StrategyParam<bool> _buyPosClose;
private readonly StrategyParam<bool> _sellPosClose;
private decimal? _lastState;
/// <summary>
/// Jurik moving average period.
/// </summary>
public int JmaLength
{
get => _jmaLength.Value;
set => _jmaLength.Value = value;
}
/// <summary>
/// Candle series type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss in percent.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Take profit in percent.
/// </summary>
public decimal TakeProfitPercent
{
get => _takeProfitPercent.Value;
set => _takeProfitPercent.Value = value;
}
/// <summary>
/// Allow opening long positions.
/// </summary>
public bool BuyPosOpen
{
get => _buyPosOpen.Value;
set => _buyPosOpen.Value = value;
}
/// <summary>
/// Allow opening short positions.
/// </summary>
public bool SellPosOpen
{
get => _sellPosOpen.Value;
set => _sellPosOpen.Value = value;
}
/// <summary>
/// Allow closing long positions.
/// </summary>
public bool BuyPosClose
{
get => _buyPosClose.Value;
set => _buyPosClose.Value = value;
}
/// <summary>
/// Allow closing short positions.
/// </summary>
public bool SellPosClose
{
get => _sellPosClose.Value;
set => _sellPosClose.Value = value;
}
public JSatlDigitSystemStrategy()
{
_jmaLength = Param(nameof(JmaLength), 5)
.SetGreaterThanZero()
.SetDisplay("JMA Length", "Period of Jurik MA", "Parameters")
.SetOptimize(2, 30, 1);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "Parameters");
_stopLossPercent = Param(nameof(StopLossPercent), 1m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percent", "Risk")
.SetOptimize(0.5m, 3m, 0.5m);
_takeProfitPercent = Param(nameof(TakeProfitPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Take Profit %", "Take profit percent", "Risk")
.SetOptimize(1m, 5m, 1m);
_buyPosOpen = Param(nameof(BuyPosOpen), true)
.SetDisplay("Buy Open", "Enable long entries", "Trading");
_sellPosOpen = Param(nameof(SellPosOpen), true)
.SetDisplay("Sell Open", "Enable short entries", "Trading");
_buyPosClose = Param(nameof(BuyPosClose), true)
.SetDisplay("Buy Close", "Enable closing longs", "Trading");
_sellPosClose = Param(nameof(SellPosClose), true)
.SetDisplay("Sell Close", "Enable closing shorts", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_lastState = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_lastState = null;
var jma = new JurikMovingAverage { Length = JmaLength };
SubscribeCandles(CandleType)
.Bind(jma, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(TakeProfitPercent * 100m, UnitTypes.Percent),
stopLoss: new Unit(StopLossPercent * 100m, UnitTypes.Percent));
}
private void ProcessCandle(ICandleMessage candle, decimal jmaValue)
{
if (candle.State != CandleStates.Finished)
return;
// Determine current digital state based on price relative to JMA
var state = candle.ClosePrice > jmaValue ? 3m : 1m;
// React only when the state changes
if (_lastState is decimal last && last == state)
return;
if (state > 2m)
{
// Uptrend: close shorts and/or open long
if (SellPosClose && Position < 0)
BuyMarket();
if (BuyPosOpen && Position <= 0)
BuyMarket();
}
else
{
// Downtrend: close longs and/or open short
if (BuyPosClose && Position > 0)
SellMarket();
if (SellPosOpen && Position >= 0)
SellMarket();
}
_lastState = state;
}
}
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 JurikMovingAverage
from StockSharp.Algo.Strategies import Strategy
class j_satl_digit_system_strategy(Strategy):
def __init__(self):
super(j_satl_digit_system_strategy, self).__init__()
self._jma_length = self.Param("JmaLength", 5) \
.SetDisplay("JMA Length", "Period of Jurik MA", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for candles", "Parameters")
self._stop_loss_percent = self.Param("StopLossPercent", 1.0) \
.SetDisplay("Stop Loss %", "Stop loss percent", "Risk")
self._take_profit_percent = self.Param("TakeProfitPercent", 2.0) \
.SetDisplay("Take Profit %", "Take profit percent", "Risk")
self._buy_pos_open = self.Param("BuyPosOpen", True) \
.SetDisplay("Buy Open", "Enable long entries", "Trading")
self._sell_pos_open = self.Param("SellPosOpen", True) \
.SetDisplay("Sell Open", "Enable short entries", "Trading")
self._buy_pos_close = self.Param("BuyPosClose", True) \
.SetDisplay("Buy Close", "Enable closing longs", "Trading")
self._sell_pos_close = self.Param("SellPosClose", True) \
.SetDisplay("Sell Close", "Enable closing shorts", "Trading")
self._last_state = None
@property
def jma_length(self):
return self._jma_length.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def stop_loss_percent(self):
return self._stop_loss_percent.Value
@property
def take_profit_percent(self):
return self._take_profit_percent.Value
@property
def buy_pos_open(self):
return self._buy_pos_open.Value
@property
def sell_pos_open(self):
return self._sell_pos_open.Value
@property
def buy_pos_close(self):
return self._buy_pos_close.Value
@property
def sell_pos_close(self):
return self._sell_pos_close.Value
def OnReseted(self):
super(j_satl_digit_system_strategy, self).OnReseted()
self._last_state = None
def OnStarted2(self, time):
super(j_satl_digit_system_strategy, self).OnStarted2(time)
self._last_state = None
jma = JurikMovingAverage()
jma.Length = int(self.jma_length)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(jma, self.process_candle).Start()
tp_val = float(self.take_profit_percent) * 100.0
sl_val = float(self.stop_loss_percent) * 100.0
self.StartProtection(
takeProfit=Unit(tp_val, UnitTypes.Percent),
stopLoss=Unit(sl_val, UnitTypes.Percent))
def process_candle(self, candle, jma_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
jma_value = float(jma_value)
state = 3.0 if close > jma_value else 1.0
if self._last_state is not None and self._last_state == state:
return
if state > 2.0:
if self.sell_pos_close and self.Position < 0:
self.BuyMarket()
if self.buy_pos_open and self.Position <= 0:
self.BuyMarket()
else:
if self.buy_pos_close and self.Position > 0:
self.SellMarket()
if self.sell_pos_open and self.Position >= 0:
self.SellMarket()
self._last_state = state
def CreateClone(self):
return j_satl_digit_system_strategy()