Random Trader Strategy
Opens a long or short position randomly when no position is open. Each trade uses fixed take profit and stop loss values measured in price units.
Details
- Entry Criteria: no position and random choice
- Long/Short: Both
- Exit Criteria: price hits take profit or stop loss
- Stops: Yes
- Default Values:
Volume= 1TakeProfit= 10StopLoss= 10
- Filters:
- Category: Other
- Direction: Both
- Indicators: None
- Stops: Yes
- Complexity: Basic
- Timeframe: Tick
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: High
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Randomly buys or sells on each candle when no position is open.
/// Applies fixed take profit and stop loss via StartProtection.
/// </summary>
public class RandomTraderStrategy : Strategy
{
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<int> _cooldown;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _signalSeed;
private int _candleCount;
private int _signalState;
public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
public int Cooldown { get => _cooldown.Value; set => _cooldown.Value = value; }
public int SignalSeed { get => _signalSeed.Value; set => _signalSeed.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public RandomTraderStrategy()
{
_takeProfitPct = Param(nameof(TakeProfitPct), 2m)
.SetDisplay("Take Profit %", "Target profit percentage", "Risk");
_stopLossPct = Param(nameof(StopLossPct), 1m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_cooldown = Param(nameof(Cooldown), 25)
.SetGreaterThanZero()
.SetDisplay("Cooldown", "Candles between trades", "General");
_signalSeed = Param(nameof(SignalSeed), 42)
.SetDisplay("Signal Seed", "Deterministic seed used for direction selection", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_candleCount = 0;
_signalState = SignalSeed;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_candleCount = 0;
_signalState = SignalSeed;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent)
);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
_candleCount++;
if (Position != 0)
return;
if (_candleCount < Cooldown)
return;
_candleCount = 0;
_signalState = unchecked(_signalState * 1103515245 + 12345);
// Use a deterministic pseudo-random sequence to keep clone validation stable.
if ((_signalState & 1) == 0)
BuyMarket();
else
SellMarket();
}
}
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.Strategies import Strategy
class random_trader_strategy(Strategy):
def __init__(self):
super(random_trader_strategy, self).__init__()
self._take_profit_pct = self.Param("TakeProfitPct", 2.0) \
.SetDisplay("Take Profit %", "Target profit percentage", "Risk")
self._stop_loss_pct = self.Param("StopLossPct", 1.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._cooldown = self.Param("Cooldown", 25) \
.SetDisplay("Cooldown", "Candles between trades", "General")
self._signal_seed = self.Param("SignalSeed", 42) \
.SetDisplay("Signal Seed", "Deterministic seed used for direction selection", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._candle_count = 0
self._signal_state = 42
@property
def TakeProfitPct(self):
return self._take_profit_pct.Value
@TakeProfitPct.setter
def TakeProfitPct(self, value):
self._take_profit_pct.Value = value
@property
def StopLossPct(self):
return self._stop_loss_pct.Value
@StopLossPct.setter
def StopLossPct(self, value):
self._stop_loss_pct.Value = value
@property
def Cooldown(self):
return self._cooldown.Value
@Cooldown.setter
def Cooldown(self, value):
self._cooldown.Value = value
@property
def SignalSeed(self):
return self._signal_seed.Value
@SignalSeed.setter
def SignalSeed(self, value):
self._signal_seed.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(random_trader_strategy, self).OnStarted2(time)
self._candle_count = 0
self._signal_state = self.SignalSeed
self.SubscribeCandles(self.CandleType) \
.Bind(self.ProcessCandle) \
.Start()
self.StartProtection(
takeProfit=Unit(self.TakeProfitPct, UnitTypes.Percent),
stopLoss=Unit(self.StopLossPct, UnitTypes.Percent)
)
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished:
return
self._candle_count += 1
if self.Position != 0:
return
if self._candle_count < self.Cooldown:
return
self._candle_count = 0
self._signal_state = (self._signal_state * 1103515245 + 12345) & 0xFFFFFFFF
if (self._signal_state & 1) == 0:
self.BuyMarket()
else:
self.SellMarket()
def OnReseted(self):
super(random_trader_strategy, self).OnReseted()
self._candle_count = 0
self._signal_state = self.SignalSeed
def CreateClone(self):
return random_trader_strategy()