Auf GitHub ansehen

Uptrick X PineIndicators: Z-Score Flow Strategy

A trend-following strategy using z-score, EMA, and RSI filters.

Details

  • Entry Criteria: Z-score crosses buy/sell thresholds with trend and RSI confirmation
  • Long/Short: Both
  • Exit Criteria: Opposite signal based on selected mode
  • Stops: No
  • Default Values:
    • ZScorePeriod = 100
    • EmaTrendLen = 50
    • RsiLen = 14
    • RsiEmaLen = 8
    • ZBuyLevel = -2
    • ZSellLevel = 2
    • CooldownBars = 10
    • SlopeIndex = 30
  • Filters:
    • Category: Trend
    • Direction: Both
    • Indicators: SMA, EMA, RSI, StandardDeviation
    • Stops: No
    • Complexity: Advanced
    • Timeframe: Intraday
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk level: Medium
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>
/// Z-Score Flow strategy using RSI momentum with EMA trend filter.
/// </summary>
public class UptrickXPineIndicatorsZScoreFlowStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _zScorePeriod;
	private readonly StrategyParam<decimal> _zBuyLevel;
	private readonly StrategyParam<decimal> _zSellLevel;

	private decimal _prevRsi;
	private decimal _prevFast;
	private decimal _prevSlow;
	private int _cooldown;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int ZScorePeriod { get => _zScorePeriod.Value; set => _zScorePeriod.Value = value; }
	public decimal ZBuyLevel { get => _zBuyLevel.Value; set => _zBuyLevel.Value = value; }
	public decimal ZSellLevel { get => _zSellLevel.Value; set => _zSellLevel.Value = value; }

	public UptrickXPineIndicatorsZScoreFlowStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");

		_zScorePeriod = Param(nameof(ZScorePeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Z-Score Period", "Period for Z-Score calculation", "General");

		_zBuyLevel = Param(nameof(ZBuyLevel), -2m)
			.SetDisplay("Z Buy Level", "Z-Score buy threshold", "General");

		_zSellLevel = Param(nameof(ZSellLevel), 2m)
			.SetDisplay("Z Sell Level", "Z-Score sell threshold", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevRsi = 0;
		_prevFast = 0;
		_prevSlow = 0;
		_cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rsi = new RelativeStrengthIndex { Length = 14 };
		var emaFast = new ExponentialMovingAverage { Length = 8 };
		var emaSlow = new ExponentialMovingAverage { Length = 21 };

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(rsi, emaFast, emaSlow, ProcessCandle).Start();

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

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

		if (_prevRsi == 0 || _prevFast == 0 || _prevSlow == 0)
		{
			_prevRsi = rsiVal;
			_prevFast = emaFast;
			_prevSlow = emaSlow;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevRsi = rsiVal;
			_prevFast = emaFast;
			_prevSlow = emaSlow;
			return;
		}

		var hist = emaFast - emaSlow;
		var histUp = hist > 0m;
		var histDown = hist < 0m;

		var rsiCrossUp = _prevRsi <= 50m && rsiVal > 50m;
		var rsiCrossDown = _prevRsi >= 50m && rsiVal < 50m;

		// Exit
		if (Position > 0 && rsiCrossDown)
		{
			SellMarket();
			_cooldown = 80;
		}
		else if (Position < 0 && rsiCrossUp)
		{
			BuyMarket();
			_cooldown = 80;
		}

		// Entry
		if (Position == 0)
		{
			if (rsiCrossUp && histUp)
			{
				BuyMarket();
				_cooldown = 80;
			}
			else if (rsiCrossDown && histDown)
			{
				SellMarket();
				_cooldown = 80;
			}
		}

		_prevRsi = rsiVal;
		_prevFast = emaFast;
		_prevSlow = emaSlow;
	}
}