在 GitHub 上查看

简单移动止损策略

该示例展示如何使用 StockSharp 的高级 API 通过移动止损来管理持仓。

概述

  • 在收到第一根完成的 K 线后开立一个多头仓位。
  • 启用带移动止损的仓位保护。
  • 止损价始终跟随当前价格,保持固定点差。

参数

  • TrailPoints – 止损与当前价格之间的点数距离。
  • CandleType – 策略使用的 K 线类型。

逻辑

  1. 启动后策略订阅 K 线并调用 StartProtection 启动移动止损。
  2. 第一根完成的 K 线出现后策略以市价买入。
  3. 当价格向有利方向移动时,止损价随之移动,距离保持为 TrailPoints。
  4. 当价格反向并触及移动止损时,仓位自动平仓。

此示例仅用于演示在策略中使用移动止损的基本方法。

using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Demonstrates exactly one market long entry after the first finished candle,
/// followed by the engine's fill-price-based native trailing stop.
/// </summary>
public class SimpleTrailingStopStrategy : Strategy
{
	private readonly StrategyParam<decimal> _trailPoints;
	private readonly StrategyParam<DataType> _candleType;
	private bool _submittedEntry;
	private Order _entryOrder;

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

	public SimpleTrailingStopStrategy()
	{
		_trailPoints = Param(nameof(TrailPoints), 100m).SetGreaterThanZero()
			.SetDisplay("Trail Points", "Trailing distance in security price steps", "Protection");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_submittedEntry = false;
		_entryOrder = null;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_submittedEntry = false;
		_entryOrder = null;

		StartProtection(
			takeProfit: null,
			stopLoss: new Unit(TrailPoints * (Security.PriceStep ?? 1m), UnitTypes.Absolute),
			isStopTrailing: true,
			useMarketOrders: true);

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

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

		// Mark before sending: avoid duplicate opens on synchronous fills or callbacks.
		_submittedEntry = true;
		_entryOrder = BuyMarket(Volume);
		// Do not reopen after a protective stop fills: this is a one-shot example.
	}
}