在 GitHub 上查看

收盘价与前一开盘价策略

该策略比较上一根完成蜡烛的收盘价与更早一根蜡烛的开盘价。 当最新收盘价高于前一开盘价时做多;当最新收盘价低于前一开盘价时做空。

入场规则

  • 做多:最近一根完成蜡烛的收盘价高于再前一根蜡烛的开盘价。
  • 做空:最近一根完成蜡烛的收盘价低于再前一根蜡烛的开盘价。

风险管理

  • 可选止损和止盈,单位为点。
  • 可选跟踪止损。

参数

  • Volume – 下单量。
  • UseStopLoss – 启用止损。
  • StopLoss – 止损距离(点)。
  • UseTakeProfit – 启用止盈。
  • TakeProfit – 止盈距离(点)。
  • UseTrailingStop – 随价格移动跟踪止损。
  • CandleType – 计算所用的蜡烛类型。

注意

  • 仅在完全形成的蜡烛上交易。
  • 出现相反信号时反向持仓。
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;

/// <summary>
/// Compares the close of the last finished candle with the open of the prior candle.
/// Buys when the latest close is significantly above the previous open, sells when below.
/// </summary>
public class CloseVsPreviousOpenStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevOpen;
	private decimal _prevPrevOpen;
	private decimal _prevClose;
	private int _barCount;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public CloseVsPreviousOpenStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevOpen = 0; _prevPrevOpen = 0; _prevClose = 0; _barCount = 0;
	}

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

		var stdev = new StandardDeviation { Length = 20 };

		SubscribeCandles(CandleType).Bind(stdev, ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;
		var open = candle.OpenPrice;
		_barCount++;

		if (_barCount >= 3 && stdevVal > 0)
		{
			var diff = _prevClose - _prevPrevOpen;

			// Only trade on significant moves (> 1 stdev)
			if (diff > stdevVal && Position <= 0)
			{
				if (Position < 0) BuyMarket();
				BuyMarket();
			}
			else if (diff < -stdevVal && Position >= 0)
			{
				if (Position > 0) SellMarket();
				SellMarket();
			}
		}

		_prevPrevOpen = _prevOpen;
		_prevOpen = open;
		_prevClose = close;
	}
}