抛物线SAR警报策略
该策略监控抛物线SAR(Stop and Reverse)指标以识别趋势反转。当SAR值从价格上方翻到下方时,被视为看涨信号并开多单;当SAR从价格下方翻到上方时,则开空单。
默认加速因子0.02和最大加速0.2为经典设置,控制SAR靠近价格的速度。较高的数值会使指标反应更快,但可能带来更多虚假信号。策略只处理已完成的K线,并保存前一个SAR和收盘价,以在不访问历史值的情况下确定交叉。
策略默认没有止损或止盈,仅在出现相反信号时平仓。如有需要,可以启用框架提供的保护机制。
细节
- 入场条件:Parabolic SAR与收盘价交叉。
- 多头/空头:两者。
- 出场条件:相反信号。
- 止损:未定义。
- 默认值:
InitialAcceleration= 0.02MaxAcceleration= 0.2CandleType= 5 分钟
- 过滤器:
- 类别:趋势跟随
- 方向:双向
- 指标:Parabolic SAR
- 止损:可选
- 复杂度:基础
- 时间框架:日内
- 季节性:无
- 神经网络:无
- 背离:无
- 风险等级:中
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>
/// Parabolic SAR Alert Strategy.
/// Opens long or short positions when Parabolic SAR flips relative to price.
/// </summary>
public class ParabolicSarAlertStrategy : Strategy
{
private readonly StrategyParam<decimal> _initialAcceleration;
private readonly StrategyParam<decimal> _maxAcceleration;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevSar;
private decimal _prevClose;
private bool _initialized;
public decimal InitialAcceleration { get => _initialAcceleration.Value; set => _initialAcceleration.Value = value; }
public decimal MaxAcceleration { get => _maxAcceleration.Value; set => _maxAcceleration.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ParabolicSarAlertStrategy()
{
_initialAcceleration = Param(nameof(InitialAcceleration), 0.02m)
.SetDisplay("Initial Acceleration", "Initial acceleration factor for Parabolic SAR", "SAR Settings");
_maxAcceleration = Param(nameof(MaxAcceleration), 0.2m)
.SetDisplay("Max Acceleration", "Maximum acceleration factor for Parabolic SAR", "SAR Settings");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevSar = 0;
_prevClose = 0;
_initialized = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var parabolicSar = new ParabolicSar
{
Acceleration = InitialAcceleration,
AccelerationMax = MaxAcceleration
};
SubscribeCandles(CandleType)
.Bind(parabolicSar, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal sarValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_initialized)
{
_prevSar = sarValue;
_prevClose = candle.ClosePrice;
_initialized = true;
return;
}
var crossUp = _prevSar > _prevClose && sarValue < candle.ClosePrice;
var crossDown = _prevSar < _prevClose && sarValue > candle.ClosePrice;
if (crossUp && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (crossDown && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevSar = sarValue;
_prevClose = candle.ClosePrice;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ParabolicSar
from StockSharp.Algo.Strategies import Strategy
class parabolic_sar_alert_strategy(Strategy):
def __init__(self):
super(parabolic_sar_alert_strategy, self).__init__()
self._initial_acceleration = self.Param("InitialAcceleration", 0.02) \
.SetDisplay("Initial Acceleration", "Initial acceleration factor for Parabolic SAR", "SAR Settings")
self._max_acceleration = self.Param("MaxAcceleration", 0.2) \
.SetDisplay("Max Acceleration", "Maximum acceleration factor for Parabolic SAR", "SAR Settings")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_sar = 0.0
self._prev_close = 0.0
self._initialized = False
@property
def initial_acceleration(self):
return self._initial_acceleration.Value
@property
def max_acceleration(self):
return self._max_acceleration.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(parabolic_sar_alert_strategy, self).OnReseted()
self._prev_sar = 0.0
self._prev_close = 0.0
self._initialized = False
def OnStarted2(self, time):
super(parabolic_sar_alert_strategy, self).OnStarted2(time)
parabolic_sar = ParabolicSar()
parabolic_sar.Acceleration = self.initial_acceleration
parabolic_sar.AccelerationMax = self.max_acceleration
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(parabolic_sar, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, sar_value):
if candle.State != CandleStates.Finished:
return
if not self._initialized:
self._prev_sar = sar_value
self._prev_close = candle.ClosePrice
self._initialized = True
return
cross_up = self._prev_sar > self._prev_close and sar_value < candle.ClosePrice
cross_down = self._prev_sar < self._prev_close and sar_value > candle.ClosePrice
if cross_up and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif cross_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_sar = sar_value
self._prev_close = candle.ClosePrice
def CreateClone(self):
return parabolic_sar_alert_strategy()