在 GitHub 上查看

Pending Order

该策略在指定时间段内围绕当前买卖价放置四个挂单:买入限价、卖出限价、买入止损和卖出止损。挂单与市场价格保持可配置的距离,并为每个订单设置固定的止损和止盈。

详情

  • 入场条件:在允许的时间内按 Distance 个跳动点距当前买/卖价放置挂单。
  • 多空方向:双向。
  • 出场条件:基于入场价的止盈或止损。
  • 止损/止盈:有。
  • 默认值
    • StartHour = 6
    • EndHour = 20
    • TakeProfit = 20
    • StopLoss = 100
    • Distance = 15
    • CandleType = TimeSpan.FromMinutes(1)
  • 筛选
    • 类型:震荡
    • 方向:双向
    • 指标:无
    • 止损:有
    • 复杂度:基础
    • 周期:日内 (1m)
    • 季节性:否
    • 神经网络:否
    • 背离:否
    • 风险级别:低
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>
/// Strategy that buys or sells based on price breaking above/below
/// a previous candle's range by a configurable offset.
/// </summary>
public class PendingOrderStrategy : Strategy
{
	private readonly StrategyParam<decimal> _distance;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevHigh;
	private decimal? _prevLow;

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

	public PendingOrderStrategy()
	{
		_distance = Param(nameof(Distance), 50m)
			.SetDisplay("Distance", "Offset from prev candle range for entry", "General");

		_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();
		_prevHigh = _prevLow = null;
	}

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

		var sma = new ExponentialMovingAverage { Length = 5 };

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

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_prevHigh = candle.HighPrice;
			_prevLow = candle.LowPrice;
			return;
		}

		if (_prevHigh is decimal ph && _prevLow is decimal pl)
		{
			var breakUp = ph + Distance;
			var breakDown = pl - Distance;

			if (candle.ClosePrice > breakUp && Position <= 0)
				BuyMarket();
			else if (candle.ClosePrice < breakDown && Position >= 0)
				SellMarket();
		}

		_prevHigh = candle.HighPrice;
		_prevLow = candle.LowPrice;
	}
}