View on GitHub
Scheduled Time Trader Strategy
This strategy submits market orders at a predefined time and protects them with fixed stop loss and take profit levels.
Trading Rules
- When the current time reaches
Trade Hour:Trade Minute:Trade Second, the strategy fires once per session.
- If
Allow Buy is enabled, a long position is opened with the specified Volume.
- If
Allow Sell is enabled, a short position is opened with the same Volume.
- Protective orders are managed via
StartProtection using point values for stop loss and take profit.
Parameters
| Name |
Description |
Volume |
Order size. |
Take Profit (ticks) |
Take profit distance from entry in ticks. |
Stop Loss (ticks) |
Stop loss distance from entry in ticks. |
Allow Buy |
Enable long trades. |
Allow Sell |
Enable short trades. |
Trade Hour |
Hour of the day to trade (0-23). |
Trade Minute |
Minute of the hour to trade (0-59). |
Trade Second |
Second of the minute to trade (0-59). |
Candle Type |
Candle series used to track time, default is 1-second candles. |
Notes
The strategy opens trades only once per run. To trade again, restart the strategy or adjust the trade time.
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>
/// EMA trend-following strategy with RSI filter.
/// </summary>
public class ScheduledTimeTraderStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevEma;
private decimal _prevClose;
private bool _hasPrev;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ScheduledTimeTraderStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA period", "Indicators");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevEma = 0;
_prevClose = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
SubscribeCandles(CandleType).Bind(ema, rsi, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue, decimal rsiValue)
{
if (candle.State != CandleStates.Finished) return;
var close = candle.ClosePrice;
if (!_hasPrev) { _prevEma = emaValue; _prevClose = close; _hasPrev = true; return; }
// Buy: close crosses above EMA and RSI confirms
if (_prevClose <= _prevEma && close > emaValue && rsiValue < 65 && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
// Sell: close crosses below EMA and RSI confirms
else if (_prevClose >= _prevEma && close < emaValue && rsiValue > 35 && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevEma = emaValue;
_prevClose = close;
}
}
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
from StockSharp.Algo.Indicators import ExponentialMovingAverage, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class scheduled_time_trader_strategy(Strategy):
def __init__(self):
super(scheduled_time_trader_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20) \
.SetDisplay("EMA Period", "EMA period", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_ema = 0.0
self._prev_close = 0.0
self._has_prev = False
@property
def ema_period(self):
return self._ema_period.Value
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(scheduled_time_trader_strategy, self).OnReseted()
self._prev_ema = 0.0
self._prev_close = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(scheduled_time_trader_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, rsi, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_value, rsi_value):
if candle.State != CandleStates.Finished:
return
close = candle.ClosePrice
if not self._has_prev:
self._prev_ema = ema_value
self._prev_close = close
self._has_prev = True
return
# Buy: close crosses above EMA and RSI confirms
if self._prev_close <= self._prev_ema and close > ema_value and rsi_value < 65 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Sell: close crosses below EMA and RSI confirms
elif self._prev_close >= self._prev_ema and close < ema_value and rsi_value > 35 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_ema = ema_value
self._prev_close = close
def CreateClone(self):
return scheduled_time_trader_strategy()