在 GitHub 上查看

Simple Pivot 策略

该策略复刻自 MetaTrader 5 专家顾问 “SimplePivot”。它持续比较当前 K 线的开盘价与上一根 K 线的枢轴价,总是保持单向持仓。 当方向改变时,策略会先平掉当前仓位,然后立刻在反向建立新的头寸。

概述

  • 交易风格:始终在场的波段逻辑。
  • 适用市场:任何能够提供所选周期 K 线数据的品种。
  • 周期:通过 Candle Type 参数设置(默认 1 小时 K 线)。
  • 下单方式:使用 Volume 参数指定数量的市价单。

工作原理

枢轴计算

  1. 首先等待至少一根完成的 K 线作为初始化。
  2. 枢轴价定义为上一根 K 线最高价与最低价的算术平均值。
  3. 保存上一根 K 线的最高价与最低价,以便在下一根 K 线收盘时立即得到新的枢轴。

方向判定

  1. 默认方向为做多。
  2. 如果当前 K 线开盘价低于上一根的最高价、同时高于枢轴价,则切换为做空方向。
  3. 当目标方向与上一笔成交方向一致时,维持原有仓位,不再重复开仓。

仓位管理

  1. 当目标方向与当前持仓不同,先通过反向市价单将仓位平掉。
  2. 平仓后立即按照 Volume 参数的数量,以市价单建立新的头寸。
  3. 每根收盘 K 线重复上述流程,策略始终保持多头或空头状态。

参数

  • Volume:每次开仓使用的数量;在换向时也用同样的数量平仓。
  • Candle Type:用于计算枢轴和入场信号的 K 线类型。默认是 1 小时周期,可根据需要调整。

额外说明

  • 策略只在 K 线完全收盘 (CandleStates.Finished) 后才评估信号,避免在形成阶段重复触发。
  • 不设置止损和止盈;只有当枢轴规则要求改变方向时才退出。
  • 由于策略始终持仓,若需要控制风险(如最大回撤或交易时段过滤),应在外部另行加入。
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>
/// Simple pivot strategy that flips position based on the previous bar pivot.
/// </summary>
public class SimplePivotStrategy : Strategy
{
	private enum TradeDirections
	{
		None,
		Long,
		Short,
	}

	private readonly StrategyParam<DataType> _candleType;

	private TradeDirections _lastDirection = TradeDirections.None;
	private decimal _previousHigh;
	private decimal _previousLow;
	private bool _hasPreviousCandle;

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

	public SimplePivotStrategy()
	{

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

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, CandleType);
	}

	protected override void OnReseted()
	{
		base.OnReseted();

		_lastDirection = TradeDirections.None;
		_previousHigh = 0m;
		_previousLow = 0m;
		_hasPreviousCandle = false;
	}

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

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

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

		if (!_hasPreviousCandle)
		{
			// Collect the very first completed candle as the seed for the pivot calculation.
			_previousHigh = candle.HighPrice;
			_previousLow = candle.LowPrice;
			_hasPreviousCandle = true;
			return;
		}

		var pivot = (_previousHigh + _previousLow) / 2m;
		var desiredDirection = TradeDirections.Long;

		// When the new open sits between the previous high and pivot we switch to a short bias.
		if (candle.OpenPrice < _previousHigh && candle.OpenPrice > pivot)
			desiredDirection = TradeDirections.Short;

		if (desiredDirection == _lastDirection && _lastDirection != TradeDirections.None)
		{
			// Keep the existing position when direction has not changed.
			_previousHigh = candle.HighPrice;
			_previousLow = candle.LowPrice;
			return;
		}

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_previousHigh = candle.HighPrice;
			_previousLow = candle.LowPrice;
			return;
		}

		CloseExistingPosition();

		if (desiredDirection == TradeDirections.Long)
		{
			// Enter a long position when the open is below the pivot.
			BuyMarket(Volume);
		}
		else
		{
			// Enter a short position when the open is above the pivot zone.
			SellMarket(Volume);
		}

		_lastDirection = desiredDirection;
		_previousHigh = candle.HighPrice;
		_previousLow = candle.LowPrice;
	}

	private void CloseExistingPosition()
	{
		if (Position > 0)
		{
			// Flip from long to flat before opening the opposite direction.
			SellMarket(Math.Abs(Position));
			_lastDirection = TradeDirections.None;
		}
		else if (Position < 0)
		{
			// Flip from short to flat before opening the opposite direction.
			BuyMarket(Math.Abs(Position));
			_lastDirection = TradeDirections.None;
		}
	}
}