Vortex 指标交叉策略
该策略利用 Vortex 指标的 VI+ 与 VI- 交叉进行交易。 当 VI+ 上穿 VI- 时做多;当 VI- 上穿 VI+ 时做空。 止损和止盈以价格步长自动管理。
参数
- Vortex Length – Vortex 指标周期。
- Candle Type – 计算指标的蜡烛时间框架。
- Stop Loss – 以价格步长表示的止损。
- Take Profit – 以价格步长表示的止盈。
细节
- 指标: Vortex
- 方向: 多空
- 时间框架: 可配置
- 风险管理: 通过
StartProtection设置止损和止盈。
using System;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Vortex indicator cross strategy.
/// Goes long when VI+ crosses above VI- and short on the opposite signal.
/// </summary>
public class VortexIndicatorCrossStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _stopLoss;
private readonly StrategyParam<int> _takeProfit;
private readonly StrategyParam<decimal> _minSpread;
private readonly StrategyParam<int> _cooldownBars;
private decimal _prevPlus;
private decimal _prevMinus;
private bool _isInitialized;
private int _barsSinceTrade;
/// <summary>
/// Vortex indicator period length.
/// </summary>
public int Length
{
get => _length.Value;
set => _length.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss in price steps.
/// </summary>
public int StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Take profit in price steps.
/// </summary>
public int TakeProfit
{
get => _takeProfit.Value;
set => _takeProfit.Value = value;
}
/// <summary>
/// Minimum VI spread required for a signal.
/// </summary>
public decimal MinSpread
{
get => _minSpread.Value;
set => _minSpread.Value = value;
}
/// <summary>
/// Bars to wait after a completed trade.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initializes parameters.
/// </summary>
public VortexIndicatorCrossStrategy()
{
_length = Param(nameof(Length), 14)
.SetGreaterThanZero()
.SetDisplay("Vortex Length", "Period for Vortex indicator", "General")
.SetOptimize(7, 28, 7);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for Vortex calculation", "General");
_stopLoss = Param(nameof(StopLoss), 1200)
.SetDisplay("Stop Loss", "Protective stop in price steps", "General");
_takeProfit = Param(nameof(TakeProfit), 2500)
.SetDisplay("Take Profit", "Target profit in price steps", "General");
_minSpread = Param(nameof(MinSpread), 0.08m)
.SetDisplay("Min Spread", "Minimum VI spread required for entry", "General");
_cooldownBars = Param(nameof(CooldownBars), 2)
.SetDisplay("Cooldown Bars", "Bars to wait after a completed trade", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevPlus = 0m;
_prevMinus = 0m;
_isInitialized = false;
_barsSinceTrade = CooldownBars;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(
stopLoss: new Unit(StopLoss, UnitTypes.Absolute),
takeProfit: new Unit(TakeProfit, UnitTypes.Absolute));
var vortex = new VortexIndicator { Length = Length };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(vortex, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue vortexValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var typed = (VortexIndicatorValue)vortexValue;
if (typed.PlusVi is not decimal viPlus || typed.MinusVi is not decimal viMinus)
return;
if (_barsSinceTrade < CooldownBars)
_barsSinceTrade++;
if (!_isInitialized)
{
_prevPlus = viPlus;
_prevMinus = viMinus;
_isInitialized = true;
return;
}
var spread = Math.Abs(viPlus - viMinus);
var longSignal = _prevPlus <= _prevMinus && viPlus > viMinus && spread >= MinSpread;
var shortSignal = _prevPlus >= _prevMinus && viPlus < viMinus && spread >= MinSpread;
if (_barsSinceTrade >= CooldownBars)
{
if (longSignal && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
_barsSinceTrade = 0;
}
else if (shortSignal && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
_barsSinceTrade = 0;
}
}
_prevPlus = viPlus;
_prevMinus = viMinus;
}
}
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, Unit, UnitTypes, CandleStates
from StockSharp.Algo.Indicators import VortexIndicator
from StockSharp.Algo.Strategies import Strategy
class vortex_indicator_cross_strategy(Strategy):
def __init__(self):
super(vortex_indicator_cross_strategy, self).__init__()
self._length = self.Param("Length", 14) \
.SetDisplay("Vortex Length", "Period for Vortex indicator", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Timeframe for Vortex calculation", "General")
self._stop_loss = self.Param("StopLoss", 1200) \
.SetDisplay("Stop Loss", "Protective stop in price steps", "General")
self._take_profit = self.Param("TakeProfit", 2500) \
.SetDisplay("Take Profit", "Target profit in price steps", "General")
self._min_spread = self.Param("MinSpread", 0.08) \
.SetDisplay("Min Spread", "Minimum VI spread required for entry", "General")
self._cooldown_bars = self.Param("CooldownBars", 2) \
.SetDisplay("Cooldown Bars", "Bars to wait after a completed trade", "General")
self._prev_plus = 0.0
self._prev_minus = 0.0
self._is_initialized = False
self._bars_since_trade = 0
@property
def Length(self):
return self._length.Value
@Length.setter
def Length(self, value):
self._length.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def StopLoss(self):
return self._stop_loss.Value
@StopLoss.setter
def StopLoss(self, value):
self._stop_loss.Value = value
@property
def TakeProfit(self):
return self._take_profit.Value
@TakeProfit.setter
def TakeProfit(self, value):
self._take_profit.Value = value
@property
def MinSpread(self):
return self._min_spread.Value
@MinSpread.setter
def MinSpread(self, value):
self._min_spread.Value = value
@property
def CooldownBars(self):
return self._cooldown_bars.Value
@CooldownBars.setter
def CooldownBars(self, value):
self._cooldown_bars.Value = value
def OnStarted2(self, time):
super(vortex_indicator_cross_strategy, self).OnStarted2(time)
vortex = VortexIndicator()
vortex.Length = self.Length
subscription = self.SubscribeCandles(self.CandleType)
subscription \
.BindEx(vortex, self.ProcessCandle) \
.Start()
self.StartProtection(
stopLoss=Unit(self.StopLoss, UnitTypes.Absolute),
takeProfit=Unit(self.TakeProfit, UnitTypes.Absolute))
def ProcessCandle(self, candle, vortex_value):
if candle.State != CandleStates.Finished:
return
plus_raw = vortex_value.PlusVi
minus_raw = vortex_value.MinusVi
if plus_raw is None or minus_raw is None:
return
vi_plus = float(plus_raw)
vi_minus = float(minus_raw)
if self._bars_since_trade < self.CooldownBars:
self._bars_since_trade += 1
if not self._is_initialized:
self._prev_plus = vi_plus
self._prev_minus = vi_minus
self._is_initialized = True
return
spread = abs(vi_plus - vi_minus)
long_signal = self._prev_plus <= self._prev_minus and vi_plus > vi_minus and spread >= float(self.MinSpread)
short_signal = self._prev_plus >= self._prev_minus and vi_plus < vi_minus and spread >= float(self.MinSpread)
if self._bars_since_trade >= self.CooldownBars:
pos = self.Position
if long_signal and pos <= 0:
self.BuyMarket(self.Volume + abs(pos))
self._bars_since_trade = 0
elif short_signal and pos >= 0:
self.SellMarket(self.Volume + abs(pos))
self._bars_since_trade = 0
self._prev_plus = vi_plus
self._prev_minus = vi_minus
def OnReseted(self):
super(vortex_indicator_cross_strategy, self).OnReseted()
self._prev_plus = 0.0
self._prev_minus = 0.0
self._is_initialized = False
self._bars_since_trade = self.CooldownBars
def CreateClone(self):
return vortex_indicator_cross_strategy()