GitHub で見る

Random Bias Trader Strategy

The Random Bias Trader Strategy emulates the MetaTrader "random trader" expert advisor using StockSharp's high-level API. At every finished candle the strategy flips a virtual coin and opens a position in that direction when no trade is active. Stop-loss and take-profit levels are derived either from ATR(10) or from a fixed pip distance and sized by the reward-to-risk ratio. Position size is computed from the configured risk percentage and automatically capped by the instrument volume limits. An optional breakeven trigger can move the stop-loss to the entry price once a specified pip gain is reached.

Details

  • Data: One candle subscription defined by CandleType.
  • Entry Criteria:
    • Long: No open position, coin toss returns long. Entry price equals the latest close.
    • Short: No open position, coin toss returns short. Entry price equals the latest close.
  • Exit Criteria:
    • Stop-loss: Distance equals LossPipDistance × pip size or LossAtrMultiplier × ATR(10) depending on LossType.
    • Take-profit: Stop distance multiplied by RewardRiskRatio.
    • Breakeven: When enabled, move stop to entry after BreakevenDistancePips gain.
  • Stops: Dynamic stop-loss and take-profit per trade, breakeven stop optional.
  • Default Values:
    • CandleType = 1 minute timeframe
    • RewardRiskRatio = 2.0
    • LossType = Pip
    • LossAtrMultiplier = 5.0
    • LossPipDistance = 20 pips
    • RiskPercentPerTrade = 1%
    • UseBreakeven = Enabled
    • BreakevenDistancePips = 10 pips
    • UseMaxMargin = Enabled
  • Filters:
    • Category: Randomized trend-neutral
    • Direction: Both, determined per flip
    • Indicators: ATR(10) (optional)
    • Complexity: Beginner
    • Risk level: Medium, depends on stop sizing

Notes

  • When the risk-based volume becomes too small, the strategy optionally falls back to the maximum tradable volume.
  • Stop and target levels are rounded to the instrument price step before orders are placed.
  • Breakeven logic keeps only one position open at any time, mirroring the original MetaTrader logic.
using System;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Random trade generator with ATR-based risk management.
/// Opens a random long or short position on each candle when flat,
/// with stop loss and take profit based on ATR.
/// </summary>
public class RandomBiasTraderStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _rewardRiskRatio;
	private readonly StrategyParam<decimal> _atrMultiplier;
	private readonly StrategyParam<int> _atrPeriod;

	private Random _random;
	private decimal _entryPrice;
	private int _direction; // 1=long, -1=short, 0=flat

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public decimal RewardRiskRatio
	{
		get => _rewardRiskRatio.Value;
		set => _rewardRiskRatio.Value = value;
	}

	public decimal AtrMultiplier
	{
		get => _atrMultiplier.Value;
		set => _atrMultiplier.Value = value;
	}

	public int AtrPeriod
	{
		get => _atrPeriod.Value;
		set => _atrPeriod.Value = value;
	}

	public RandomBiasTraderStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(60).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "Data");

		_rewardRiskRatio = Param(nameof(RewardRiskRatio), 3m)
			.SetDisplay("Reward/Risk", "Reward to risk ratio", "Risk");

		_atrMultiplier = Param(nameof(AtrMultiplier), 3m)
			.SetDisplay("ATR Multiplier", "ATR multiplier for stop distance", "Risk");

		_atrPeriod = Param(nameof(AtrPeriod), 14)
			.SetDisplay("ATR Period", "ATR indicator period", "Risk");
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_random = new Random(42);

		var atr = new AverageTrueRange { Length = AtrPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(atr, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, decimal atrValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (atrValue <= 0)
			return;

		var stopDistance = atrValue * AtrMultiplier;
		var takeDistance = stopDistance * RewardRiskRatio;
		var close = candle.ClosePrice;

		// Check exit for existing position
		if (_direction > 0)
		{
			if (close >= _entryPrice + takeDistance || close <= _entryPrice - stopDistance)
			{
				SellMarket();
				_direction = 0;
			}
			return;
		}
		else if (_direction < 0)
		{
			if (close <= _entryPrice - takeDistance || close >= _entryPrice + stopDistance)
			{
				BuyMarket();
				_direction = 0;
			}
			return;
		}

		// Open new random position
		if (_random.Next(4) != 0)
			return;

		if (_random.Next(2) == 0)
		{
			BuyMarket();
			_entryPrice = close;
			_direction = 1;
		}
		else
		{
			SellMarket();
			_entryPrice = close;
			_direction = -1;
		}
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		_random = null;
		_entryPrice = 0;
		_direction = 0;

		base.OnReseted();
	}
}