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>
/// Strategy based on XMA Candles indicator.
/// Opens a long position when smoothed candles turn bullish and
/// opens a short position when smoothed candles turn bearish.
/// </summary>
public class XmaCandlesStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<bool> _buyPosOpen;
private readonly StrategyParam<bool> _sellPosOpen;
private readonly StrategyParam<bool> _buyPosClose;
private readonly StrategyParam<bool> _sellPosClose;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private ExponentialMovingAverage _openMa;
private ExponentialMovingAverage _closeMa;
private int _prevColor = -1;
/// <summary>
/// Length of smoothing for moving averages.
/// </summary>
public int Length
{
get => _length.Value;
set => _length.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Allows opening long positions.
/// </summary>
public bool BuyPosOpen
{
get => _buyPosOpen.Value;
set => _buyPosOpen.Value = value;
}
/// <summary>
/// Allows opening short positions.
/// </summary>
public bool SellPosOpen
{
get => _sellPosOpen.Value;
set => _sellPosOpen.Value = value;
}
/// <summary>
/// Allows closing long positions.
/// </summary>
public bool BuyPosClose
{
get => _buyPosClose.Value;
set => _buyPosClose.Value = value;
}
/// <summary>
/// Allows closing short positions.
/// </summary>
public bool SellPosClose
{
get => _sellPosClose.Value;
set => _sellPosClose.Value = value;
}
/// <summary>
/// Stop loss in percent.
/// </summary>
public decimal StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Take profit in percent.
/// </summary>
public decimal TakeProfit
{
get => _takeProfit.Value;
set => _takeProfit.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <summary>
/// Initialize <see cref="XmaCandlesStrategy"/>.
/// </summary>
public XmaCandlesStrategy()
{
_length = Param(nameof(Length), 12)
.SetDisplay("Length", "Smoothing length", "Parameters")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "Parameters");
_buyPosOpen = Param(nameof(BuyPosOpen), true)
.SetDisplay("Buy Open", "Allow opening long positions", "Parameters");
_sellPosOpen = Param(nameof(SellPosOpen), true)
.SetDisplay("Sell Open", "Allow opening short positions", "Parameters");
_buyPosClose = Param(nameof(BuyPosClose), true)
.SetDisplay("Buy Close", "Allow closing long positions", "Parameters");
_sellPosClose = Param(nameof(SellPosClose), true)
.SetDisplay("Sell Close", "Allow closing short positions", "Parameters");
_stopLoss = Param(nameof(StopLoss), 2m)
.SetDisplay("Stop Loss %", "Stop loss in percent", "Protection");
_takeProfit = Param(nameof(TakeProfit), 4m)
.SetDisplay("Take Profit %", "Take profit in percent", "Protection");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevColor = -1;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevColor = -1;
_openMa = new EMA { Length = Length };
_closeMa = new EMA { Length = Length };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
StartProtection(
stopLoss: new Unit(StopLoss, UnitTypes.Percent),
takeProfit: new Unit(TakeProfit, UnitTypes.Percent)
);
}
private void ProcessCandle(ICandleMessage candle)
{
// process only finished candles
if (candle.State != CandleStates.Finished)
return;
var t = candle.ServerTime;
var openValue = _openMa.Process(candle.OpenPrice, t, true);
var closeValue = _closeMa.Process(candle.ClosePrice, t, true);
if (!_openMa.IsFormed || !_closeMa.IsFormed)
return;
var openMa = openValue.GetValue<decimal>();
var closeMa = closeValue.GetValue<decimal>();
// determine candle color based on smoothed values
var currentColor = openMa < closeMa ? 2 : openMa > closeMa ? 0 : 1;
if (currentColor == 2 && _prevColor != 2)
{
// bullish change
if (Position <= 0)
BuyMarket();
}
else if (currentColor == 0 && _prevColor != 0)
{
// bearish change
if (Position >= 0)
SellMarket();
}
_prevColor = currentColor;
}
}
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
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class xma_candles_strategy(Strategy):
def __init__(self):
super(xma_candles_strategy, self).__init__()
self._length = self.Param("Length", 12) \
.SetDisplay("Length", "Smoothing length", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "Parameters")
self._buy_pos_open = self.Param("BuyPosOpen", True) \
.SetDisplay("Buy Open", "Allow opening long positions", "Parameters")
self._sell_pos_open = self.Param("SellPosOpen", True) \
.SetDisplay("Sell Open", "Allow opening short positions", "Parameters")
self._buy_pos_close = self.Param("BuyPosClose", True) \
.SetDisplay("Buy Close", "Allow closing long positions", "Parameters")
self._sell_pos_close = self.Param("SellPosClose", True) \
.SetDisplay("Sell Close", "Allow closing short positions", "Parameters")
self._stop_loss = self.Param("StopLoss", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss in percent", "Protection")
self._take_profit = self.Param("TakeProfit", 4.0) \
.SetDisplay("Take Profit %", "Take profit in percent", "Protection")
self._open_ma = None
self._close_ma = None
self._prev_color = -1
@property
def length(self):
return self._length.Value
@property
def candle_type(self):
return self._candle_type.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
@property
def stop_loss(self):
return self._stop_loss.Value
@property
def take_profit(self):
return self._take_profit.Value
def OnReseted(self):
super(xma_candles_strategy, self).OnReseted()
self._prev_color = -1
def OnStarted2(self, time):
super(xma_candles_strategy, self).OnStarted2(time)
self._prev_color = -1
self._open_ma = ExponentialMovingAverage()
self._open_ma.Length = int(self.length)
self._close_ma = ExponentialMovingAverage()
self._close_ma.Length = int(self.length)
self.Indicators.Add(self._open_ma)
self.Indicators.Add(self._close_ma)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.process_candle).Start()
self.StartProtection(
stopLoss=Unit(float(self.stop_loss), UnitTypes.Percent),
takeProfit=Unit(float(self.take_profit), UnitTypes.Percent))
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
t = candle.OpenTime
open_result = process_float(self._open_ma, candle.OpenPrice, t, True)
close_result = process_float(self._close_ma, candle.ClosePrice, t, True)
if not self._open_ma.IsFormed or not self._close_ma.IsFormed:
return
open_ma = float(open_result)
close_ma = float(close_result)
if open_ma < close_ma:
current_color = 2
elif open_ma > close_ma:
current_color = 0
else:
current_color = 1
if current_color == 2 and self._prev_color != 2:
if self.Position <= 0:
self.BuyMarket()
elif current_color == 0 and self._prev_color != 0:
if self.Position >= 0:
self.SellMarket()
self._prev_color = current_color
def CreateClone(self):
return xma_candles_strategy()