在 GitHub 上查看

Trix Candle 策略

该策略基于 Trix Candle 指标进行反转交易。该指标对蜡烛的开盘价和收盘价应用三重指数平滑,并根据平滑后的收盘价高于或低于平滑后的开盘价对蜡烛进行着色。

细节

  • 入场条件
    • 做多:前一根蜡烛为看涨(颜色 2)且当前蜡烛颜色 < 2
    • 做空:前一根蜡烛为看跌(颜色 0)且当前蜡烛颜色 > 0
  • 多空方向:多空双向
  • 出场条件
    • 多头:前一根蜡烛为看跌(颜色 0)
    • 空头:前一根蜡烛为看涨(颜色 2)
  • 止损:无
  • 默认值
    • TRIX Period = 14
    • Candle Type = 4h
    • Allow Buy Open = true
    • Allow Sell Open = true
    • Allow Buy Close = true
    • Allow Sell Close = true
  • 过滤器
    • 分类:反转
    • 方向:双向
    • 指标:Triple Exponential Moving Average
    • 止损:无
    • 复杂度:低
    • 时间框架:中期
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险级别:中
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>
/// TRIX Candle reversal strategy.
/// Opens long when bullish TRIX candle turns neutral or bearish and closes shorts.
/// Opens short when bearish TRIX candle turns neutral or bullish and closes longs.
/// </summary>
public class TrixCandleStrategy : Strategy
{
	private readonly StrategyParam<int> _trixPeriod;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<bool> _buyPosOpen;
	private readonly StrategyParam<bool> _sellPosOpen;
	private readonly StrategyParam<bool> _buyPosClose;
	private readonly StrategyParam<bool> _sellPosClose;

	private TripleExponentialMovingAverage _openTema = null!;
	private TripleExponentialMovingAverage _closeTema = null!;
	private int _prevColor;

	/// <summary>
	/// Period for TRIX smoothing.
	/// </summary>
	public int TrixPeriod { get => _trixPeriod.Value; set => _trixPeriod.Value = value; }

	/// <summary>
	/// Candle type to process.
	/// </summary>
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	/// <summary>
	/// Allow opening long positions.
	/// </summary>
	public bool BuyPosOpen { get => _buyPosOpen.Value; set => _buyPosOpen.Value = value; }

	/// <summary>
	/// Allow opening short positions.
	/// </summary>
	public bool SellPosOpen { get => _sellPosOpen.Value; set => _sellPosOpen.Value = value; }

	/// <summary>
	/// Allow closing long positions.
	/// </summary>
	public bool BuyPosClose { get => _buyPosClose.Value; set => _buyPosClose.Value = value; }

	/// <summary>
	/// Allow closing short positions.
	/// </summary>
	public bool SellPosClose { get => _sellPosClose.Value; set => _sellPosClose.Value = value; }

	/// <summary>
	/// Initialize the strategy with default parameters.
	/// </summary>
	public TrixCandleStrategy()
	{
		_trixPeriod = Param(nameof(TrixPeriod), 5)
			.SetDisplay("TRIX Period", "Period for triple exponential smoothing", "Indicators")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for processing", "General");

		_buyPosOpen = Param(nameof(BuyPosOpen), true)
			.SetDisplay("Allow Buy Open", "Enable opening long positions", "Trading");

		_sellPosOpen = Param(nameof(SellPosOpen), true)
			.SetDisplay("Allow Sell Open", "Enable opening short positions", "Trading");

		_buyPosClose = Param(nameof(BuyPosClose), true)
			.SetDisplay("Allow Buy Close", "Enable closing long positions", "Trading");

		_sellPosClose = Param(nameof(SellPosClose), true)
			.SetDisplay("Allow Sell Close", "Enable closing short positions", "Trading");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_openTema = default;
		_closeTema = default;
		_prevColor = -1;
	}

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

		_openTema = new TripleExponentialMovingAverage { Length = TrixPeriod };
		_closeTema = new TripleExponentialMovingAverage { Length = TrixPeriod };
		_prevColor = -1;

		Indicators.Add(_openTema);
		Indicators.Add(_closeTema);

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

		StartProtection(null, null);

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

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

		var openResult = _openTema.Process(new DecimalIndicatorValue(_openTema, candle.OpenPrice, candle.OpenTime) { IsFinal = true });
		var closeResult = _closeTema.Process(new DecimalIndicatorValue(_closeTema, candle.ClosePrice, candle.OpenTime) { IsFinal = true });

		if (!openResult.IsFormed || !closeResult.IsFormed)
			return;

		var openValue = openResult.ToDecimal();
		var closeValue = closeResult.ToDecimal();

		var color = 1;

		if (openValue < closeValue)
			color = 2;
		else if (openValue > closeValue)
			color = 0;

		if (_prevColor == -1)
		{
			_prevColor = color;
			return;
		}

		var buyOpen = BuyPosOpen && _prevColor == 2 && color < 2;
		var sellOpen = SellPosOpen && _prevColor == 0 && color > 0;
		var buyClose = BuyPosClose && _prevColor == 0;
		var sellClose = SellPosClose && _prevColor == 2;

		if (sellClose && Position < 0)
			BuyMarket();

		if (buyClose && Position > 0)
			SellMarket();

		if (buyOpen && Position <= 0)
			BuyMarket();

		if (sellOpen && Position >= 0)
			SellMarket();

		_prevColor = color;
	}
}