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>
/// Night session flat trading strategy that enters near range extremes.
/// </summary>
public class NightFlatTradeStrategy : Strategy
{
private readonly StrategyParam<int> _rangeLength;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _takeProfitPips;
private readonly StrategyParam<decimal> _trailingStopPips;
private readonly StrategyParam<decimal> _trailingStepPips;
private readonly StrategyParam<decimal> _diffMinPips;
private readonly StrategyParam<decimal> _diffMaxPips;
private readonly StrategyParam<int> _openHour;
private Highest _highest = null!;
private Lowest _lowest = null!;
private decimal _pipSize;
private decimal _entryPrice;
private decimal? _stopPrice;
private decimal? _takeProfitPrice;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
public decimal TrailingStopPips
{
get => _trailingStopPips.Value;
set => _trailingStopPips.Value = value;
}
public decimal TrailingStepPips
{
get => _trailingStepPips.Value;
set => _trailingStepPips.Value = value;
}
public decimal DiffMinPips
{
get => _diffMinPips.Value;
set => _diffMinPips.Value = value;
}
public decimal DiffMaxPips
{
get => _diffMaxPips.Value;
set => _diffMaxPips.Value = value;
}
public int OpenHour
{
get => _openHour.Value;
set => _openHour.Value = value;
}
/// <summary>
/// Number of candles used to form the overnight range.
/// </summary>
public int RangeLength
{
get => _rangeLength.Value;
set => _rangeLength.Value = value;
}
public NightFlatTradeStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles used for the setup", "General");
_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
.SetRange(0m, 500m)
.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk");
_trailingStopPips = Param(nameof(TrailingStopPips), 15m)
.SetRange(0m, 200m)
.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk");
_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
.SetRange(0m, 200m)
.SetDisplay("Trailing Step (pips)", "Extra advance required to shift the trailing stop", "Risk");
_diffMinPips = Param(nameof(DiffMinPips), 18m)
.SetGreaterThanZero()
.SetDisplay("Min Range (pips)", "Minimum three-candle range in pips", "Setup");
_diffMaxPips = Param(nameof(DiffMaxPips), 28m)
.SetGreaterThanZero()
.SetDisplay("Max Range (pips)", "Maximum three-candle range in pips", "Setup");
_openHour = Param(nameof(OpenHour), 0)
.SetRange(0, 23)
.SetDisplay("Open Hour", "Hour (exchange time) when entries become active", "Schedule");
_rangeLength = Param(nameof(RangeLength), 3)
.SetGreaterThanZero()
.SetDisplay("Range Length", "Number of candles composing the range", "Setup");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_highest = null!;
_lowest = null!;
_pipSize = 0m;
_entryPrice = 0m;
_stopPrice = null;
_takeProfitPrice = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_highest = new Highest { Length = RangeLength };
_lowest = new Lowest { Length = RangeLength };
var priceStep = Security?.PriceStep ?? 0m;
var decimals = Security?.Decimals;
if (priceStep <= 0m)
priceStep = 0.0001m;
_pipSize = priceStep;
if (decimals.HasValue && (decimals.Value == 3 || decimals.Value == 5))
_pipSize *= 10m;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_highest, _lowest, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _highest);
DrawIndicator(area, _lowest);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal highestValue, decimal lowestValue)
{
if (candle.State != CandleStates.Finished)
return;
// Manage active trades before scanning for new setups.
HandleExistingPosition(candle);
if (Position != 0m)
return;
if (_highest == null || _lowest == null)
return;
if (!_highest.IsFormed || !_lowest.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var diff = highestValue - lowestValue;
if (diff <= 0m)
return;
var quarter = diff / 4m;
var closePrice = candle.ClosePrice;
if (closePrice > lowestValue && closePrice <= lowestValue + quarter)
{
BuyMarket();
_entryPrice = closePrice;
_stopPrice = lowestValue - diff / 3m;
_takeProfitPrice = TakeProfitPips > 0m ? closePrice + ToPrice(TakeProfitPips) : null;
return;
}
if (closePrice < highestValue && closePrice >= highestValue - quarter)
{
SellMarket();
_entryPrice = closePrice;
_stopPrice = highestValue + diff / 3m;
_takeProfitPrice = TakeProfitPips > 0m ? closePrice - ToPrice(TakeProfitPips) : null;
}
}
private void HandleExistingPosition(ICandleMessage candle)
{
if (Position > 0m)
{
UpdateTrailingForLong(candle);
if (_stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
{
SellMarket(Math.Abs(Position));
ResetTradeState();
return;
}
if (_takeProfitPrice.HasValue && candle.HighPrice >= _takeProfitPrice.Value)
{
SellMarket(Math.Abs(Position));
ResetTradeState();
}
}
else if (Position < 0m)
{
UpdateTrailingForShort(candle);
if (_stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
{
BuyMarket(Math.Abs(Position));
ResetTradeState();
return;
}
if (_takeProfitPrice.HasValue && candle.LowPrice <= _takeProfitPrice.Value)
{
BuyMarket(Math.Abs(Position));
ResetTradeState();
}
}
}
private void UpdateTrailingForLong(ICandleMessage candle)
{
if (TrailingStopPips <= 0m || TrailingStepPips <= 0m || _stopPrice == null)
return;
var trailingDistance = ToPrice(TrailingStopPips);
var stepDistance = ToPrice(TrailingStepPips);
var advance = candle.HighPrice - _entryPrice;
if (advance < trailingDistance + stepDistance)
return;
var newStop = candle.HighPrice - trailingDistance;
if (newStop <= _stopPrice.Value || newStop - _stopPrice.Value < stepDistance)
return;
// Raise the stop only after price travels an additional step distance.
_stopPrice = newStop;
}
private void UpdateTrailingForShort(ICandleMessage candle)
{
if (TrailingStopPips <= 0m || TrailingStepPips <= 0m || _stopPrice == null)
return;
var trailingDistance = ToPrice(TrailingStopPips);
var stepDistance = ToPrice(TrailingStepPips);
var advance = _entryPrice - candle.LowPrice;
if (advance < trailingDistance + stepDistance)
return;
var newStop = candle.LowPrice + trailingDistance;
if (newStop >= _stopPrice.Value || _stopPrice.Value - newStop < stepDistance)
return;
// Lower the stop only after price moves the additional step distance in favor of the trade.
_stopPrice = newStop;
}
private decimal ToPrice(decimal pips)
{
if (pips <= 0m)
return 0m;
var pip = _pipSize > 0m ? _pipSize : 0.0001m;
return pips * pip;
}
private void ResetTradeState()
{
_entryPrice = 0m;
_stopPrice = null;
_takeProfitPrice = null;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from StockSharp.Algo.Indicators import Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Messages import DataType, CandleStates
from System import TimeSpan, Math
class night_flat_trade_strategy(Strategy):
def __init__(self):
super(night_flat_trade_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._take_profit_pips = self.Param("TakeProfitPips", 50.0)
self._trailing_stop_pips = self.Param("TrailingStopPips", 15.0)
self._trailing_step_pips = self.Param("TrailingStepPips", 5.0)
self._diff_min_pips = self.Param("DiffMinPips", 18.0)
self._diff_max_pips = self.Param("DiffMaxPips", 28.0)
self._open_hour = self.Param("OpenHour", 0)
self._range_length = self.Param("RangeLength", 3)
self._highest = None
self._lowest = None
self._pip_size = 0.0
self._entry_price = 0.0
self._stop_price = None
self._take_profit_price = None
@property
def CandleType(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(night_flat_trade_strategy, self).OnStarted2(time)
self._highest = Highest()
self._highest.Length = self._range_length.Value
self._lowest = Lowest()
self._lowest.Length = self._range_length.Value
price_step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 0.0
if price_step <= 0:
price_step = 0.0001
self._pip_size = price_step
# Check if Security has Decimals property for pip adjustment
decimals = None
if self.Security is not None:
try:
decimals = self.Security.Decimals
except:
pass
if decimals is not None and (decimals == 3 or decimals == 5):
self._pip_size *= 10.0
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(self._highest, self._lowest, self._process_candle).Start()
def _process_candle(self, candle, highest_value, lowest_value):
if candle.State != CandleStates.Finished:
return
# Manage active trades before scanning for new setups
self._handle_existing_position(candle)
if self.Position != 0:
return
if self._highest is None or self._lowest is None:
return
if not self._highest.IsFormed or not self._lowest.IsFormed:
return
hv = float(highest_value)
lv = float(lowest_value)
diff = hv - lv
if diff <= 0:
return
quarter = diff / 4.0
close_price = float(candle.ClosePrice)
if close_price > lv and close_price <= lv + quarter:
self.BuyMarket()
self._entry_price = close_price
self._stop_price = lv - diff / 3.0
self._take_profit_price = close_price + self._to_price(self._take_profit_pips.Value) if self._take_profit_pips.Value > 0 else None
return
if close_price < hv and close_price >= hv - quarter:
self.SellMarket()
self._entry_price = close_price
self._stop_price = hv + diff / 3.0
self._take_profit_price = close_price - self._to_price(self._take_profit_pips.Value) if self._take_profit_pips.Value > 0 else None
def _handle_existing_position(self, candle):
if self.Position > 0:
self._update_trailing_for_long(candle)
if self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
self.SellMarket(abs(self.Position))
self._reset_trade_state()
return
if self._take_profit_price is not None and float(candle.HighPrice) >= self._take_profit_price:
self.SellMarket(abs(self.Position))
self._reset_trade_state()
elif self.Position < 0:
self._update_trailing_for_short(candle)
if self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
self.BuyMarket(abs(self.Position))
self._reset_trade_state()
return
if self._take_profit_price is not None and float(candle.LowPrice) <= self._take_profit_price:
self.BuyMarket(abs(self.Position))
self._reset_trade_state()
def _update_trailing_for_long(self, candle):
if self._trailing_stop_pips.Value <= 0 or self._trailing_step_pips.Value <= 0 or self._stop_price is None:
return
trailing_distance = self._to_price(self._trailing_stop_pips.Value)
step_distance = self._to_price(self._trailing_step_pips.Value)
advance = float(candle.HighPrice) - self._entry_price
if advance < trailing_distance + step_distance:
return
new_stop = float(candle.HighPrice) - trailing_distance
if new_stop <= self._stop_price or new_stop - self._stop_price < step_distance:
return
self._stop_price = new_stop
def _update_trailing_for_short(self, candle):
if self._trailing_stop_pips.Value <= 0 or self._trailing_step_pips.Value <= 0 or self._stop_price is None:
return
trailing_distance = self._to_price(self._trailing_stop_pips.Value)
step_distance = self._to_price(self._trailing_step_pips.Value)
advance = self._entry_price - float(candle.LowPrice)
if advance < trailing_distance + step_distance:
return
new_stop = float(candle.LowPrice) + trailing_distance
if new_stop >= self._stop_price or self._stop_price - new_stop < step_distance:
return
self._stop_price = new_stop
def _to_price(self, pips):
if pips <= 0:
return 0.0
pip = self._pip_size if self._pip_size > 0 else 0.0001
return pips * pip
def _reset_trade_state(self):
self._entry_price = 0.0
self._stop_price = None
self._take_profit_price = None
def OnReseted(self):
super(night_flat_trade_strategy, self).OnReseted()
self._highest = None
self._lowest = None
self._pip_size = 0.0
self._entry_price = 0.0
self._stop_price = None
self._take_profit_price = None
def CreateClone(self):
return night_flat_trade_strategy()