GitHub で見る

Reverse Day Fractal Strategy

Overview

Reverse Day Fractal is a price action strategy that looks for sharp reversals after an intraday breakout. The algorithm analyses the last three finished candles. When the current bar forms a new extreme beyond the previous two candles and closes back in the opposite direction, it treats this pattern as a failed breakout and enters a reversal trade. Protective orders are managed through configurable take-profit, stop-loss and trailing-stop distances measured in price steps.

Trading Logic

  • Bullish setup:
    • The current finished candle makes a lower low than each of the two preceding candles.
    • The candle closes above its open price, indicating a bullish rejection of the new low.
    • When these conditions are met and the strategy is allowed to trade, it opens a long position. Optionally it can close an existing short first.
  • Bearish setup:
    • The current finished candle makes a higher high than each of the two preceding candles.
    • The candle closes below its open price, indicating a bearish rejection of the new high.
    • When these conditions are satisfied it opens a short position, optionally closing an existing long first.
  • Position management: the strategy can be configured to allow only one open position at a time (default behaviour). When disabled it will reverse an existing position by adding the volume required to change the direction.
  • Risk controls: on start the strategy calls StartProtection to apply take-profit, stop-loss and trailing-stop protections using the configured point distances. When a trailing stop is enabled the protective stop will follow the price in discrete steps.

Parameters

  • Trade Volume – order volume for new entries.
  • Take Profit – distance to the profit target measured in price steps. Set to zero to disable.
  • Stop Loss – distance to the protective stop measured in price steps. Set to zero to disable.
  • Trailing Stop – trailing stop distance in price steps. Set to zero to disable.
  • Trailing Step – minimum movement (in steps) required before the trailing stop is adjusted.
  • Only One Position – when enabled the strategy ignores new signals while a position is open.
  • Candle Type – candle data type used for calculations (default: 1-hour time frame).

Notes

  • Signals are generated only on finished candles provided by the configured subscription.
  • The strategy keeps the most recent two candle extremes in memory; therefore it needs at least two completed candles after start before it can generate a signal.
  • Default parameter values replicate the original MQL4 expert advisor: 0.01 lot volume, 20-point stop loss, 10-point take profit, 25-point trailing stop and 5-point trailing step.
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;

public class ReverseDayFractalStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public ReverseDayFractalStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}