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;
using StockSharp.Algo;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy that opens trades when the close price crosses a configured level.
/// Converted from the MQL4 expert advisor BT_v4.
/// </summary>
public class AppPriceLevelCrossStrategy : Strategy
{
private readonly StrategyParam<decimal> _appPrice;
private readonly StrategyParam<bool> _buyOnly;
private readonly StrategyParam<decimal> _fixedVolume;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private readonly StrategyParam<bool> _enableMoneyManagement;
private readonly StrategyParam<decimal> _lotBalancePercent;
private readonly StrategyParam<decimal> _minLot;
private readonly StrategyParam<decimal> _maxLot;
private readonly StrategyParam<int> _lotPrecision;
private readonly StrategyParam<DataType> _candleType;
private decimal? _previousClose;
/// <summary>
/// Initializes strategy parameters with defaults mirroring the MQL version.
/// </summary>
public AppPriceLevelCrossStrategy()
{
_appPrice = Param(nameof(AppPrice), 65000m)
.SetDisplay("App Price", "Reference level that generates trades when the close crosses it", "Trading");
_buyOnly = Param(nameof(BuyOnly), true)
.SetDisplay("Buy Only", "Enable to trade only long entries (set to false for sell-only mode)", "Trading");
_fixedVolume = Param(nameof(FixedVolume), 0.1m)
.SetGreaterThanZero()
.SetDisplay("Fixed Volume", "Lot size used when money management is disabled", "Risk");
_stopLossPoints = Param(nameof(StopLossPoints), 140)
.SetDisplay("Stop Loss (points)", "Distance in price points for the protective stop (0 disables)", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 180)
.SetDisplay("Take Profit (points)", "Distance in price points for the profit target (0 disables)", "Risk");
_enableMoneyManagement = Param(nameof(EnableMoneyManagement), false)
.SetDisplay("Enable MM", "Toggle balance-based position sizing", "Risk");
_lotBalancePercent = Param(nameof(LotBalancePercent), 10m)
.SetDisplay("Balance %", "Percentage of balance used to compute the lot when MM is enabled", "Risk");
_minLot = Param(nameof(MinLot), 0.1m)
.SetDisplay("Minimum Lot", "Lower bound for the calculated lot size", "Risk");
_maxLot = Param(nameof(MaxLot), 5m)
.SetDisplay("Maximum Lot", "Upper bound for the calculated lot size", "Risk");
_lotPrecision = Param(nameof(LotPrecision), 1)
.SetDisplay("Lot Precision", "Number of decimal places to round the calculated lot size", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for signal generation", "General");
}
/// <summary>
/// Target price level for the close-cross rule.
/// </summary>
public decimal AppPrice
{
get => _appPrice.Value;
set => _appPrice.Value = value;
}
/// <summary>
/// When true only long trades are allowed; set to false to trade only shorts.
/// </summary>
public bool BuyOnly
{
get => _buyOnly.Value;
set => _buyOnly.Value = value;
}
/// <summary>
/// Fixed lot size used when money management is disabled.
/// </summary>
public decimal FixedVolume
{
get => _fixedVolume.Value;
set => _fixedVolume.Value = value;
}
/// <summary>
/// Stop-loss distance expressed in price points.
/// </summary>
public int StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Take-profit distance expressed in price points.
/// </summary>
public int TakeProfitPoints
{
get => _takeProfitPoints.Value;
set => _takeProfitPoints.Value = value;
}
/// <summary>
/// Enables the balance-percentage position sizing block.
/// </summary>
public bool EnableMoneyManagement
{
get => _enableMoneyManagement.Value;
set => _enableMoneyManagement.Value = value;
}
/// <summary>
/// Percentage of account balance used for lot calculation when MM is active.
/// </summary>
public decimal LotBalancePercent
{
get => _lotBalancePercent.Value;
set => _lotBalancePercent.Value = value;
}
/// <summary>
/// Minimum allowed lot for the calculated value.
/// </summary>
public decimal MinLot
{
get => _minLot.Value;
set => _minLot.Value = value;
}
/// <summary>
/// Maximum allowed lot for the calculated value.
/// </summary>
public decimal MaxLot
{
get => _maxLot.Value;
set => _maxLot.Value = value;
}
/// <summary>
/// Decimal precision applied to the calculated lot size.
/// </summary>
public int LotPrecision
{
get => _lotPrecision.Value;
set => _lotPrecision.Value = value;
}
/// <summary>
/// Candle type used to evaluate the cross conditions.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
// Reset stored close value so the next formed candle rebuilds the history.
_previousClose = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var dummySma = new SimpleMovingAverage { Length = 2 };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(dummySma, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
var step = Security?.PriceStep ?? 1m;
if (TakeProfitPoints > 0 || StopLossPoints > 0)
{
var takeDistance = TakeProfitPoints > 0 ? new Unit(TakeProfitPoints * step, UnitTypes.Absolute) : new Unit(0m);
var stopDistance = StopLossPoints > 0 ? new Unit(StopLossPoints * step, UnitTypes.Absolute) : new Unit(0m);
StartProtection(takeProfit: takeDistance, stopLoss: stopDistance);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
var previousClose = _previousClose;
_previousClose = candle.ClosePrice;
// Need at least one completed candle to compare against the configured level.
if (previousClose is null)
return;
var crossedAbove = candle.ClosePrice > AppPrice && previousClose <= AppPrice;
var crossedBelow = candle.ClosePrice < AppPrice && previousClose >= AppPrice;
if (crossedAbove)
{
ExecuteBuy();
}
else if (crossedBelow)
{
ExecuteSell();
}
}
private void ExecuteBuy()
{
// Skip if we already hold a long position.
if (Position > 0)
return;
var baseVolume = CalculateBaseVolume();
if (baseVolume <= 0m)
return;
var volume = baseVolume;
if (Position < 0)
volume += Math.Abs(Position);
volume = AlignVolume(volume);
if (volume <= 0m)
return;
BuyMarket(volume);
}
private void ExecuteSell()
{
// Skip if we already hold a short position.
if (Position < 0)
return;
var baseVolume = CalculateBaseVolume();
if (baseVolume <= 0m)
return;
var volume = baseVolume;
if (Position > 0)
volume += Math.Abs(Position);
volume = AlignVolume(volume);
if (volume <= 0m)
return;
SellMarket(volume);
}
private decimal CalculateBaseVolume()
{
if (!EnableMoneyManagement)
return FixedVolume;
var balance = Portfolio?.CurrentValue ?? Portfolio?.BeginValue;
if (balance is null || balance <= 0m)
return FixedVolume;
var divisor = LotPrecision == 2 ? 100m : 1000m;
if (LotPrecision <= 0)
divisor = 1m;
var precision = LotPrecision;
if (precision < 0)
precision = 0;
var volume = LotBalancePercent / 100m * balance.Value / divisor;
volume = Math.Round(volume, precision, MidpointRounding.AwayFromZero);
if (volume < MinLot)
volume = MinLot;
if (volume > MaxLot)
volume = MaxLot;
return volume;
}
private decimal AlignVolume(decimal volume)
{
var security = Security;
if (security == null)
return volume;
var minVolume = security.MinVolume ?? 0m;
var maxVolume = security.MaxVolume ?? decimal.MaxValue;
var step = security.VolumeStep ?? 0m;
if (minVolume > 0m && volume < minVolume)
volume = minVolume;
if (maxVolume > 0m && volume > maxVolume)
volume = maxVolume;
if (step > 0m)
{
var steps = Math.Round(volume / step, MidpointRounding.AwayFromZero);
volume = steps * step;
}
return volume;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import SimpleMovingAverage
class app_price_level_cross_strategy(Strategy):
def __init__(self):
super(app_price_level_cross_strategy, self).__init__()
self._app_price = self.Param("AppPrice", 65000.0) \
.SetDisplay("App Price", "Reference level that generates trades when the close crosses it", "Trading")
self._buy_only = self.Param("BuyOnly", True) \
.SetDisplay("Buy Only", "Enable to trade only long entries", "Trading")
self._fixed_volume = self.Param("FixedVolume", 0.1) \
.SetDisplay("Fixed Volume", "Lot size used when money management is disabled", "Risk")
self._stop_loss_points = self.Param("StopLossPoints", 140) \
.SetDisplay("Stop Loss (points)", "Distance in price points for the protective stop", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 180) \
.SetDisplay("Take Profit (points)", "Distance in price points for the profit target", "Risk")
self._enable_money_management = self.Param("EnableMoneyManagement", False) \
.SetDisplay("Enable MM", "Toggle balance-based position sizing", "Risk")
self._lot_balance_percent = self.Param("LotBalancePercent", 10.0) \
.SetDisplay("Balance %", "Percentage of balance used to compute the lot when MM is enabled", "Risk")
self._min_lot = self.Param("MinLot", 0.1) \
.SetDisplay("Minimum Lot", "Lower bound for the calculated lot size", "Risk")
self._max_lot = self.Param("MaxLot", 5.0) \
.SetDisplay("Maximum Lot", "Upper bound for the calculated lot size", "Risk")
self._lot_precision = self.Param("LotPrecision", 1) \
.SetDisplay("Lot Precision", "Number of decimal places to round the calculated lot size", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Timeframe used for signal generation", "General")
self._previous_close = None
@property
def AppPrice(self):
return self._app_price.Value
@property
def BuyOnly(self):
return self._buy_only.Value
@property
def FixedVolume(self):
return self._fixed_volume.Value
@property
def StopLossPoints(self):
return self._stop_loss_points.Value
@property
def TakeProfitPoints(self):
return self._take_profit_points.Value
@property
def EnableMoneyManagement(self):
return self._enable_money_management.Value
@property
def LotBalancePercent(self):
return self._lot_balance_percent.Value
@property
def MinLot(self):
return self._min_lot.Value
@property
def MaxLot(self):
return self._max_lot.Value
@property
def LotPrecision(self):
return self._lot_precision.Value
@property
def CandleType(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(app_price_level_cross_strategy, self).OnStarted2(time)
self._dummy_sma = SimpleMovingAverage()
self._dummy_sma.Length = 2
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._dummy_sma, self.ProcessCandle).Start()
step = 1.0
if self.Security is not None and self.Security.PriceStep is not None:
step = float(self.Security.PriceStep)
if step <= 0:
step = 1.0
tp_pts = int(self.TakeProfitPoints)
sl_pts = int(self.StopLossPoints)
if tp_pts > 0 or sl_pts > 0:
take_dist = Unit(tp_pts * step, UnitTypes.Absolute) if tp_pts > 0 else Unit(0)
stop_dist = Unit(sl_pts * step, UnitTypes.Absolute) if sl_pts > 0 else Unit(0)
self.StartProtection(take_dist, stop_dist)
def ProcessCandle(self, candle, sma_value):
if candle.State != CandleStates.Finished:
return
previous_close = self._previous_close
close_price = float(candle.ClosePrice)
self._previous_close = close_price
if previous_close is None:
return
app_price = float(self.AppPrice)
crossed_above = close_price > app_price and previous_close <= app_price
crossed_below = close_price < app_price and previous_close >= app_price
if crossed_above:
self._execute_buy()
elif crossed_below:
self._execute_sell()
def _execute_buy(self):
if self.Position > 0:
return
base_volume = self._calculate_base_volume()
if base_volume <= 0:
return
volume = base_volume
if self.Position < 0:
volume += Math.Abs(self.Position)
volume = self._align_volume(volume)
if volume <= 0:
return
self.BuyMarket(volume)
def _execute_sell(self):
if self.Position < 0:
return
base_volume = self._calculate_base_volume()
if base_volume <= 0:
return
volume = base_volume
if self.Position > 0:
volume += Math.Abs(self.Position)
volume = self._align_volume(volume)
if volume <= 0:
return
self.SellMarket(volume)
def _calculate_base_volume(self):
if not self.EnableMoneyManagement:
return float(self.FixedVolume)
balance = 0.0
if self.Portfolio is not None:
cv = self.Portfolio.CurrentValue
if cv is not None and float(cv) > 0:
balance = float(cv)
elif self.Portfolio.BeginValue is not None and float(self.Portfolio.BeginValue) > 0:
balance = float(self.Portfolio.BeginValue)
if balance <= 0:
return float(self.FixedVolume)
precision = int(self.LotPrecision)
if precision <= 0:
divisor = 1.0
precision = 0
elif precision == 2:
divisor = 100.0
else:
divisor = 1000.0
volume = float(self.LotBalancePercent) / 100.0 * balance / divisor
volume = round(volume, precision)
min_lot = float(self.MinLot)
max_lot = float(self.MaxLot)
if volume < min_lot:
volume = min_lot
if volume > max_lot:
volume = max_lot
return volume
def _align_volume(self, volume):
if self.Security is not None:
min_vol = self.Security.MinVolume
max_vol = self.Security.MaxVolume
step = self.Security.VolumeStep
min_v = float(min_vol) if min_vol is not None else 0.0
max_v = float(max_vol) if max_vol is not None else 0.0
s = float(step) if step is not None else 0.0
if min_v > 0 and volume < min_v:
volume = min_v
if max_v > 0 and volume > max_v:
volume = max_v
if s > 0:
volume = round(volume / s) * s
return volume
def OnReseted(self):
super(app_price_level_cross_strategy, self).OnReseted()
self._previous_close = None
def CreateClone(self):
return app_price_level_cross_strategy()