Simple Pivot 策略
该策略复刻自 MetaTrader 5 专家顾问 “SimplePivot”。它持续比较当前 K 线的开盘价与上一根 K 线的枢轴价,总是保持单向持仓。 当方向改变时,策略会先平掉当前仓位,然后立刻在反向建立新的头寸。
概述
- 交易风格:始终在场的波段逻辑。
- 适用市场:任何能够提供所选周期 K 线数据的品种。
- 周期:通过 Candle Type 参数设置(默认 1 小时 K 线)。
- 下单方式:使用 Volume 参数指定数量的市价单。
工作原理
枢轴计算
- 首先等待至少一根完成的 K 线作为初始化。
- 枢轴价定义为上一根 K 线最高价与最低价的算术平均值。
- 保存上一根 K 线的最高价与最低价,以便在下一根 K 线收盘时立即得到新的枢轴。
方向判定
- 默认方向为做多。
- 如果当前 K 线开盘价低于上一根的最高价、同时高于枢轴价,则切换为做空方向。
- 当目标方向与上一笔成交方向一致时,维持原有仓位,不再重复开仓。
仓位管理
- 当目标方向与当前持仓不同,先通过反向市价单将仓位平掉。
- 平仓后立即按照 Volume 参数的数量,以市价单建立新的头寸。
- 每根收盘 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;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
from indicator_extensions import *
class simple_pivot_strategy(Strategy):
def __init__(self):
super(simple_pivot_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Type of candles", "Data")
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, value): self._candle_type.Value = value
def OnReseted(self):
super(simple_pivot_strategy, self).OnReseted()
self._prev_high = 0
self._prev_low = 0
self._has_prev = False
self._last_dir = 0 # 1=long, -1=short
def OnStarted2(self, time):
super(simple_pivot_strategy, self).OnStarted2(time)
self._prev_high = 0
self._prev_low = 0
self._has_prev = False
self._last_dir = 0
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(self.OnProcess).Start()
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
if not self._has_prev:
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
self._has_prev = True
return
pivot = (self._prev_high + self._prev_low) / 2.0
open_price = float(candle.OpenPrice)
desired = 1 # long
if open_price < self._prev_high and open_price > pivot:
desired = -1 # short
if desired == self._last_dir and self._last_dir != 0:
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
return
# Close existing
if self.Position > 0:
self.SellMarket()
elif self.Position < 0:
self.BuyMarket()
if desired == 1:
self.BuyMarket()
else:
self.SellMarket()
self._last_dir = desired
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
def CreateClone(self):
return simple_pivot_strategy()