Timer Trade
Timer Trade alternates between long and short positions at fixed time intervals. A timer triggers market orders, and each position is automatically protected with stop-loss and take-profit.
Details
- Entry Criteria: Timer event.
- Long/Short: Both directions.
- Exit Criteria: Stop-loss or take-profit.
- Stops: Yes, via StartProtection.
- Default Values:
TimerInterval= TimeSpan.FromSeconds(30)Volume= 1StopLossLevel= 10 pointsTakeProfitLevel= 50 points
- Filters:
- Category: Timer
- Direction: Both
- Indicators: None
- Stops: Yes
- Complexity: Beginner
- Timeframe: Any
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy that alternates buy and sell orders on each candle close.
/// Each position is protected with stop-loss and take-profit via manual tracking.
/// </summary>
public class TimerTradeStrategy : Strategy
{
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<DataType> _candleType;
private bool _isBuyNext = true;
private decimal _entryPrice;
public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public TimerTradeStrategy()
{
_stopLoss = Param(nameof(StopLoss), 300m)
.SetDisplay("Stop Loss", "Stop loss in price units", "Risk")
.SetGreaterThanZero();
_takeProfit = Param(nameof(TakeProfit), 200m)
.SetDisplay("Take Profit", "Take profit in price units", "Risk")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for strategy", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_isBuyNext = true;
_entryPrice = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_isBuyNext = true;
_entryPrice = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var price = candle.ClosePrice;
// Check SL/TP for existing position
if (Position > 0)
{
if (candle.LowPrice <= _entryPrice - StopLoss || candle.HighPrice >= _entryPrice + TakeProfit)
{
SellMarket();
_isBuyNext = !_isBuyNext;
return;
}
}
else if (Position < 0)
{
if (candle.HighPrice >= _entryPrice + StopLoss || candle.LowPrice <= _entryPrice - TakeProfit)
{
BuyMarket();
_isBuyNext = !_isBuyNext;
return;
}
}
// Open new position when flat
if (Position == 0)
{
if (_isBuyNext)
BuyMarket();
else
SellMarket();
_entryPrice = price;
_isBuyNext = !_isBuyNext;
}
}
}
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.Strategies import Strategy
class timer_trade_strategy(Strategy):
"""Alternating buy/sell on each candle with SL/TP management."""
def __init__(self):
super(timer_trade_strategy, self).__init__()
self._stop_loss = self.Param("StopLoss", 300.0).SetGreaterThanZero().SetDisplay("Stop Loss", "Stop loss in price units", "Risk")
self._take_profit = self.Param("TakeProfit", 200.0).SetGreaterThanZero().SetDisplay("Take Profit", "Take profit in price units", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Timeframe for strategy", "General")
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, value): self._candle_type.Value = value
def OnReseted(self):
super(timer_trade_strategy, self).OnReseted()
self._is_buy_next = True
self._entry_price = 0
def OnStarted2(self, time):
super(timer_trade_strategy, self).OnStarted2(time)
self._is_buy_next = True
self._entry_price = 0
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, sub)
self.DrawOwnTrades(area)
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
low = float(candle.LowPrice)
high = float(candle.HighPrice)
sl = self._stop_loss.Value
tp = self._take_profit.Value
# Check SL/TP
if self.Position > 0:
if low <= self._entry_price - sl or high >= self._entry_price + tp:
self.SellMarket()
self._is_buy_next = not self._is_buy_next
return
elif self.Position < 0:
if high >= self._entry_price + sl or low <= self._entry_price - tp:
self.BuyMarket()
self._is_buy_next = not self._is_buy_next
return
# Open new position when flat
if self.Position == 0:
if self._is_buy_next:
self.BuyMarket()
else:
self.SellMarket()
self._entry_price = close
self._is_buy_next = not self._is_buy_next
def CreateClone(self):
return timer_trade_strategy()