AI Supertrend Pivot Percentile 策略
该策略结合两个 Supertrend 指标、ADX 过滤器以及 Williams %R 枢轴百分位过滤。 当价格位于两个 Supertrend 之上、ADX 显示强趋势且 Williams %R 高于 -50 时开多仓;相反条件下开空仓。
详情
- 入场条件:
- 多头: 价格高于两个 Supertrend,ADX 大于阈值,Williams %R > -50。
- 空头: 价格低于两个 Supertrend,ADX 大于阈值,Williams %R < -50。
- 多/空: 双向。
- 离场条件:
- 反向信号。
- 止损: 基于百分比的止盈和止损。
- 默认参数:
Length1= 10Factor1= 3Length2= 20Factor2= 4AdxLength= 14AdxThreshold= 20PivotLength= 14TpPercent= 2SlPercent= 1
- 过滤器:
- 类别: 趋势跟随
- 方向: 双向
- 指标: SuperTrend, ADX, Williams %R
- 止损: 是
- 复杂度: 中等
- 时间框架: 任意
- 季节性: 否
- 神经网络: 否
- 背离: 否
- 风险等级: 中等
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>
/// AI Supertrend x Pivot Percentile strategy.
/// Goes long when the close is above both Supertrends, ADX is above AdxThreshold and Williams %R is above -50, and short when
/// the close is below both Supertrends, ADX is above AdxThreshold and Williams %R is below -50. The opposite signal reverses
/// the position, and percent take-profit and stop-loss protect it.
/// </summary>
public class AiSupertrendPivotPercentileStrategy : Strategy
{
private readonly StrategyParam<int> _length1;
private readonly StrategyParam<decimal> _factor1;
private readonly StrategyParam<int> _length2;
private readonly StrategyParam<decimal> _factor2;
private readonly StrategyParam<int> _adxLength;
private readonly StrategyParam<decimal> _adxThreshold;
private readonly StrategyParam<int> _pivotLength;
private readonly StrategyParam<decimal> _tpPercent;
private readonly StrategyParam<decimal> _slPercent;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// ATR period of the first Supertrend.
/// </summary>
public int Length1
{
get => _length1.Value;
set => _length1.Value = value;
}
/// <summary>
/// Multiplier of the first Supertrend.
/// </summary>
public decimal Factor1
{
get => _factor1.Value;
set => _factor1.Value = value;
}
/// <summary>
/// ATR period of the second Supertrend.
/// </summary>
public int Length2
{
get => _length2.Value;
set => _length2.Value = value;
}
/// <summary>
/// Multiplier of the second Supertrend.
/// </summary>
public decimal Factor2
{
get => _factor2.Value;
set => _factor2.Value = value;
}
/// <summary>
/// ADX period.
/// </summary>
public int AdxLength
{
get => _adxLength.Value;
set => _adxLength.Value = value;
}
/// <summary>
/// Minimum ADX for entries.
/// </summary>
public decimal AdxThreshold
{
get => _adxThreshold.Value;
set => _adxThreshold.Value = value;
}
/// <summary>
/// Williams %R period.
/// </summary>
public int PivotLength
{
get => _pivotLength.Value;
set => _pivotLength.Value = value;
}
/// <summary>
/// Take-profit percentage.
/// </summary>
public decimal TpPercent
{
get => _tpPercent.Value;
set => _tpPercent.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal SlPercent
{
get => _slPercent.Value;
set => _slPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public AiSupertrendPivotPercentileStrategy()
{
_length1 = Param(nameof(Length1), 10)
.SetGreaterThanZero()
.SetDisplay("ST1 Length", "ATR period of the first Supertrend", "Supertrend");
_factor1 = Param(nameof(Factor1), 3m)
.SetGreaterThanZero()
.SetDisplay("ST1 Factor", "Multiplier of the first Supertrend", "Supertrend");
_length2 = Param(nameof(Length2), 20)
.SetGreaterThanZero()
.SetDisplay("ST2 Length", "ATR period of the second Supertrend", "Supertrend");
_factor2 = Param(nameof(Factor2), 4m)
.SetGreaterThanZero()
.SetDisplay("ST2 Factor", "Multiplier of the second Supertrend", "Supertrend");
_adxLength = Param(nameof(AdxLength), 14)
.SetGreaterThanZero()
.SetDisplay("ADX Length", "ADX period", "Filter");
_adxThreshold = Param(nameof(AdxThreshold), 20m)
.SetDisplay("ADX Threshold", "Minimum ADX for entries", "Filter");
_pivotLength = Param(nameof(PivotLength), 14)
.SetGreaterThanZero()
.SetDisplay("Pivot Length", "Williams %R period", "Filter");
_tpPercent = Param(nameof(TpPercent), 2m)
.SetNotNegative()
.SetDisplay("Take Profit %", "Take-profit percentage", "Risk");
_slPercent = Param(nameof(SlPercent), 1m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop-loss percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var st1 = new SuperTrend { Length = Length1, Multiplier = Factor1 };
var st2 = new SuperTrend { Length = Length2, Multiplier = Factor2 };
var adx = new AverageDirectionalIndex { Length = AdxLength };
var wpr = new WilliamsR { Length = PivotLength };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(st1, st2, adx, wpr, ProcessCandle)
.Start();
StartProtection(new Unit(TpPercent, UnitTypes.Percent), new Unit(SlPercent, UnitTypes.Percent), useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, st1);
DrawIndicator(area, st2);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
DrawIndicator(oscillators, adx);
DrawIndicator(oscillators, wpr);
}
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue st1Value, IIndicatorValue st2Value, IIndicatorValue adxValue, IIndicatorValue wprValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!st1Value.IsFormed || !st2Value.IsFormed || !adxValue.IsFormed || !wprValue.IsFormed)
return;
if (adxValue is not IAverageDirectionalIndexValue { MovingAverage: decimal adx })
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var close = candle.ClosePrice;
var st1 = st1Value.ToDecimal();
var st2 = st2Value.ToDecimal();
var wpr = wprValue.ToDecimal();
var strongTrend = adx > AdxThreshold;
var longSignal = close > st1 && close > st2 && strongTrend && wpr > -50m;
var shortSignal = close < st1 && close < st2 && strongTrend && wpr < -50m;
if (longSignal && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (shortSignal && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import SuperTrend, AverageDirectionalIndex, WilliamsR
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class ai_supertrend_pivot_percentile_strategy(Strategy):
"""
AI Supertrend x Pivot Percentile strategy.
Goes long when the close is above both Supertrends, ADX is above AdxThreshold and Williams %R is above -50, and short when
the close is below both Supertrends, ADX is above AdxThreshold and Williams %R is below -50. The opposite signal reverses
the position, and percent take-profit and stop-loss protect it.
"""
def __init__(self):
super(ai_supertrend_pivot_percentile_strategy, self).__init__()
self._length1 = self.Param("Length1", 10) \
.SetGreaterThanZero() \
.SetDisplay("ST1 Length", "ATR period of the first Supertrend", "Supertrend")
self._factor1 = self.Param("Factor1", 3.0) \
.SetGreaterThanZero() \
.SetDisplay("ST1 Factor", "Multiplier of the first Supertrend", "Supertrend")
self._length2 = self.Param("Length2", 20) \
.SetGreaterThanZero() \
.SetDisplay("ST2 Length", "ATR period of the second Supertrend", "Supertrend")
self._factor2 = self.Param("Factor2", 4.0) \
.SetGreaterThanZero() \
.SetDisplay("ST2 Factor", "Multiplier of the second Supertrend", "Supertrend")
self._adx_length = self.Param("AdxLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("ADX Length", "ADX period", "Filter")
self._adx_threshold = self.Param("AdxThreshold", 20.0) \
.SetDisplay("ADX Threshold", "Minimum ADX for entries", "Filter")
self._pivot_length = self.Param("PivotLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("Pivot Length", "Williams %R period", "Filter")
self._tp_percent = self.Param("TpPercent", 2.0) \
.SetNotNegative() \
.SetDisplay("Take Profit %", "Take-profit percentage", "Risk")
self._sl_percent = self.Param("SlPercent", 1.0) \
.SetNotNegative() \
.SetDisplay("Stop Loss %", "Stop-loss percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def OnStarted2(self, time):
super(ai_supertrend_pivot_percentile_strategy, self).OnStarted2(time)
st1 = SuperTrend()
st1.Length = self._length1.Value
st1.Multiplier = self._factor1.Value
st2 = SuperTrend()
st2.Length = self._length2.Value
st2.Multiplier = self._factor2.Value
adx = AverageDirectionalIndex()
adx.Length = self._adx_length.Value
wpr = WilliamsR()
wpr.Length = self._pivot_length.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(st1, st2, adx, wpr, self._process_candle).Start()
self.StartProtection(
Unit(Decimal(self._tp_percent.Value), UnitTypes.Percent),
Unit(Decimal(self._sl_percent.Value), UnitTypes.Percent),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, st1)
self.DrawIndicator(area, st2)
self.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, adx)
self.DrawIndicator(oscillators, wpr)
def _process_candle(self, candle, st1_value, st2_value, adx_value, wpr_value):
if candle.State != CandleStates.Finished:
return
if not st1_value.IsFormed or not st2_value.IsFormed or not adx_value.IsFormed or not wpr_value.IsFormed:
return
if adx_value.MovingAverage is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
adx = float(adx_value.MovingAverage)
close = float(candle.ClosePrice)
st1 = float(to_decimal(st1_value))
st2 = float(to_decimal(st2_value))
wpr = float(to_decimal(wpr_value))
strong_trend = adx > float(self._adx_threshold.Value)
long_signal = close > st1 and close > st2 and strong_trend and wpr > -50.0
short_signal = close < st1 and close < st2 and strong_trend and wpr < -50.0
if long_signal and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif short_signal and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return ai_supertrend_pivot_percentile_strategy()