在 GitHub 上查看

My Line Order

该策略在价格突破预设的水平线时发送市价单。用户分别指定做多和做空的触发价格以及以点为单位的风险参数。开仓后策略会跟踪止损、止盈以及可选的追踪止损。

策略适用于提前知道进场价格的情形。由于只依赖价格水平,可在任何品种和时间框架上使用。

详情

  • 入场条件
    • 多头:收盘价向上突破 BuyPrice
    • 空头:收盘价向下突破 SellPrice
  • 方向:双向。
  • 出场条件
    • StopLossPips 的止损。
    • TakeProfitPips 的止盈。
    • TrailingStopPips > 0 时启用追踪止损。
  • 止损:是,以点计。
  • 默认值
    • BuyPrice = 0(禁用)
    • SellPrice = 0(禁用)
    • TakeProfitPips = 30
    • StopLossPips = 20
    • TrailingStopPips = 0
    • CandleType = TimeSpan.FromMinutes(1)
  • 过滤器
    • 类别:手动
    • 方向:双向
    • 指标:无
    • 止损:是
    • 复杂度:基础
    • 时间框架:任意
    • 季节性:否
    • 神经网络:否
    • 背离:否
    • 风险等级:中等
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>
/// Line order strategy using SMA as dynamic support/resistance levels.
/// </summary>
public class MyLineOrderStrategy : Strategy
{
	private readonly StrategyParam<int> _smaLength;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevSma;
	private bool _hasPrev;

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

	public MyLineOrderStrategy()
	{
		_smaLength = Param(nameof(SmaLength), 14)
			.SetGreaterThanZero()
			.SetDisplay("SMA", "SMA period", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevClose = 0;
		_prevSma = 0;
		_hasPrev = false;
	}

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

		var sma = new SimpleMovingAverage { Length = SmaLength };

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

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevSma = sma;
			_hasPrev = true;
			return;
		}

		// Cross above SMA
		if (_prevClose <= _prevSma && close > sma)
		{
			if (Position < 0) BuyMarket();
			if (Position <= 0) BuyMarket();
		}
		// Cross below SMA
		else if (_prevClose >= _prevSma && close < sma)
		{
			if (Position > 0) SellMarket();
			if (Position >= 0) SellMarket();
		}

		_prevClose = close;
		_prevSma = sma;
	}
}