在 GitHub 上查看

多时间框架 Parabolic SAR

该策略结合多个时间框架上的 Parabolic SAR 信号。当价格高于所选 SAR 时做多,价格跌破 SAR 时做空。支持可选的止损、追踪止损和止盈。

详情

  • 入场条件
    • 多头:价格高于 LongSource 指定的 SAR。
    • 空头:价格低于 ShortSource 指定的 SAR。
  • 出场条件
    • 价格与 SAR 反向穿越或触发保护。
  • 指标
    • 当前时间框架的 Parabolic SAR
    • 可选的高阶与低阶时间框架 Parabolic SAR
  • 止损:通过 StartProtection 设置的止损、追踪止损和止盈(可选)。
  • 默认值
    • Acceleration = 0.02
    • MaxAcceleration = 0.2
    • StopLossPercent = 1
    • TrailingPercent = 0.5
    • TakeProfitPercent = 2
  • 过滤条件
    • 时间框架:主 5m,高阶 1d,低阶 1m
    • 指标:Parabolic SAR
    • 止损:可选
    • 复杂度:中等
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>
/// Parabolic SAR-style strategy using EMA and RSI.
/// </summary>
public class MultiTimeframeParabolicSarStrategy : Strategy
{
	private readonly StrategyParam<int> _emaLength;
	private readonly StrategyParam<int> _rsiLength;
	private readonly StrategyParam<DataType> _candleType;

	public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
	public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MultiTimeframeParabolicSarStrategy()
	{
		_emaLength = Param(nameof(EmaLength), 20)
			.SetGreaterThanZero()
			.SetDisplay("EMA", "EMA period", "Indicators");
		_rsiLength = Param(nameof(RsiLength), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI", "RSI period", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(2).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

		var ema = new ExponentialMovingAverage { Length = EmaLength };
		var rsi = new RelativeStrengthIndex { Length = RsiLength };

		var subscription = SubscribeCandles(CandleType);

		subscription
			.Bind(ema, rsi, (candle, emaVal, rsiVal) =>
			{
				if (candle.State != CandleStates.Finished)
					return;

				if (!ema.IsFormed || !rsi.IsFormed)
					return;

				// Buy when price above EMA and RSI confirms uptrend
				if (candle.ClosePrice > emaVal && rsiVal > 50 && Position <= 0)
					BuyMarket();
				// Sell when price below EMA and RSI confirms downtrend
				else if (candle.ClosePrice < emaVal && rsiVal < 50 && Position > 0)
					SellMarket();
			})
			.Start();

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