View on GitHub

Universum 3.0 Strategy

DeMarker oscillator based strategy that opens positions on each completed bar and adjusts volume using a martingale scheme.

Details

  • Entry Criteria:
    • Long: DeMarker > 0.5
    • Short: DeMarker < 0.5
  • Long/Short: Both
  • Exit Criteria:
    • Positions are closed by take profit or stop loss
  • Stops: Absolute points via TakeProfitPoints and StopLossPoints
  • Default Values:
    • DemarkerPeriod = 10
    • TakeProfitPoints = 50m
    • StopLossPoints = 50m
    • InitialVolume = 1m
    • LossesLimit = 100
    • CandleType = TimeSpan.FromMinutes(1).TimeFrame()
  • Filters:
    • Category: Trend following
    • Direction: Long & Short
    • Indicators: DeMarker
    • Stops: Yes
    • Complexity: Low
    • Timeframe: Short-term
    • Seasonality: No
    • Neural Networks: No
    • Divergence: No
    • Risk Level: High
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>
/// Universum 3.0 strategy based on DeMarker indicator with martingale volume.
/// </summary>
public class Universum30Strategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _demarkerPeriod;
	private readonly StrategyParam<decimal> _takeProfitPoints;
	private readonly StrategyParam<decimal> _stopLossPoints;
	private readonly StrategyParam<decimal> _initialVolume;
	private readonly StrategyParam<int> _lossesLimit;

	private decimal _currentVolume;
	private int _losses;
	private decimal _lastPnL;
	private decimal _previousDeMarker;
	private bool _hasPreviousDeMarker;

	/// <summary>
	/// Candle type for strategy calculation.
	/// </summary>
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	/// <summary>
	/// DeMarker indicator period.
	/// </summary>
	public int DemarkerPeriod { get => _demarkerPeriod.Value; set => _demarkerPeriod.Value = value; }

	/// <summary>
	/// Take profit distance in price points.
	/// </summary>
	public decimal TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	/// <summary>
	/// Stop loss distance in price points.
	/// </summary>
	public decimal StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }

	/// <summary>
	/// Starting order volume.
	/// </summary>
	public decimal InitialVolume { get => _initialVolume.Value; set => _initialVolume.Value = value; }

	/// <summary>
	/// Maximum allowed consecutive losses.
	/// </summary>
	public int LossesLimit { get => _lossesLimit.Value; set => _lossesLimit.Value = value; }

	/// <summary>
	/// Initializes a new instance of <see cref="Universum30Strategy"/>.
	/// </summary>
	public Universum30Strategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
			.SetDisplay("Candle Type", "Time frame for analysis", "General");

		_demarkerPeriod = Param(nameof(DemarkerPeriod), 10)
			.SetGreaterThanZero()
			.SetDisplay("DeMarker Period", "Length of DeMarker indicator", "Indicators");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 50m)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit", "Target profit in absolute points", "Risk");

		_stopLossPoints = Param(nameof(StopLossPoints), 50m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss", "Loss limit in absolute points", "Risk");

		_initialVolume = Param(nameof(InitialVolume), 1m)
			.SetGreaterThanZero()
			.SetDisplay("Initial Volume", "Base order volume", "Trading");

		_lossesLimit = Param(nameof(LossesLimit), 100)
			.SetGreaterThanZero()
			.SetDisplay("Losses Limit", "Max consecutive losses before stop", "Trading");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_currentVolume = 0m;
		_losses = 0;
		_lastPnL = 0m;
		_previousDeMarker = 0m;
		_hasPreviousDeMarker = false;
	}

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

		_currentVolume = InitialVolume;
		_losses = 0;
		_lastPnL = 0m;
		_previousDeMarker = 0m;
		_hasPreviousDeMarker = false;

		StartProtection(
			takeProfit: new Unit(TakeProfitPoints, UnitTypes.Absolute),
			stopLoss: new Unit(StopLossPoints, UnitTypes.Absolute));

		var demarker = new DeMarker { Length = DemarkerPeriod };

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

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var buySignal = _hasPreviousDeMarker && _previousDeMarker <= 0.3m && demarkerValue > 0.3m;
		var sellSignal = _hasPreviousDeMarker && _previousDeMarker >= 0.7m && demarkerValue < 0.7m;

		if (buySignal && Position <= 0)
			BuyMarket(_currentVolume + Math.Abs(Position));
		else if (sellSignal && Position >= 0)
			SellMarket(_currentVolume + Math.Abs(Position));

		_previousDeMarker = demarkerValue;
		_hasPreviousDeMarker = true;
	}

	/// <inheritdoc />
	protected override void OnPositionReceived(Position position)
	{
		base.OnPositionReceived(position);

		if (Position != 0)
			return;

		var tradePnL = PnL - _lastPnL;
		_lastPnL = PnL;

		if (tradePnL > 0)
		{
			_currentVolume = InitialVolume;
			_losses = 0;
		}
		else if (tradePnL < 0)
		{
			_currentVolume *= 2;
			_losses++;
			if (_losses >= LossesLimit)
				Stop();
		}
	}
}