Golden Ratio Cubes策略
Golden Ratio Cubes策略利用斐波那契数计算金分率扩展。策略追踪一段时间内的最高价和最低价,并基于黄金分割(φ ≈ 1.618)计算突破水平。当价格收盘突破这些水平时,按照突破方向入场。
细节
- 入场条件:
- 收盘价高于黄金分割扩展水平 → 买入。
- 收盘价低于黄金分割扩展水平 → 卖出。
- 方向:多头和空头。
- 出场条件:
- 相反方向的突破信号。
- 止损:无。
- 默认参数:
Lookback= 34Phi= 1.618
- 过滤器:
- 类型:突破
- 方向:多头和空头
- 指标:Highest, Lowest
- 止损:无
- 复杂度:低
- 时间框架:任意
- 季节性:否
- 神经网络:否
- 背离:否
- 风险等级:中等
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Golden Ratio Cubes Strategy.
/// Uses BB width as a range proxy and golden ratio extensions for breakout levels.
/// Buys when price breaks above upper golden ratio level.
/// Sells when price breaks below lower golden ratio level.
/// </summary>
public class GoldenRatioCubesStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _bbLength;
private readonly StrategyParam<decimal> _phi;
private readonly StrategyParam<int> _cooldownBars;
private BollingerBands _bb;
private ExponentialMovingAverage _ema;
private int _cooldownRemaining;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int BbLength
{
get => _bbLength.Value;
set => _bbLength.Value = value;
}
public decimal Phi
{
get => _phi.Value;
set => _phi.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
public GoldenRatioCubesStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_bbLength = Param(nameof(BbLength), 34)
.SetGreaterThanZero()
.SetDisplay("BB Length", "Bollinger Bands period", "Golden Ratio");
_phi = Param(nameof(Phi), 1.618m)
.SetDisplay("Phi", "Golden ratio multiplier", "Golden Ratio");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_bb = null;
_ema = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_bb = new BollingerBands { Length = BbLength, Width = 2.0m };
_ema = new ExponentialMovingAverage { Length = BbLength };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_bb, _ema, OnProcess)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _bb);
DrawOwnTrades(area);
}
}
private void OnProcess(ICandleMessage candle, IIndicatorValue bbValue, IIndicatorValue emaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_bb.IsFormed || !_ema.IsFormed)
return;
if (bbValue.IsEmpty || emaValue.IsEmpty)
return;
var bb = (BollingerBandsValue)bbValue;
if (bb.UpBand is not decimal upper || bb.LowBand is not decimal lower || bb.MovingAverage is not decimal mid)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
var range = upper - lower;
var price = candle.ClosePrice;
// Use BB bands directly as breakout levels
// Buy: price breaks above upper BB
if (price > upper && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_cooldownRemaining = CooldownBars;
}
// Sell: price breaks below lower BB
else if (price < lower && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_cooldownRemaining = CooldownBars;
}
// Exit long: price returns to middle
else if (Position > 0 && price < mid)
{
SellMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
// Exit short: price returns to middle
else if (Position < 0 && price > mid)
{
BuyMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
}
}
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.Indicators import BollingerBands, ExponentialMovingAverage, IndicatorHelper
from StockSharp.Algo.Strategies import Strategy
class golden_ratio_cubes_strategy(Strategy):
"""Golden Ratio Cubes Strategy."""
def __init__(self):
super(golden_ratio_cubes_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._bb_length = self.Param("BbLength", 34) \
.SetDisplay("BB Length", "Bollinger Bands period", "Golden Ratio")
self._phi = self.Param("Phi", 1.618) \
.SetDisplay("Phi", "Golden ratio multiplier", "Golden Ratio")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk")
self._bb = None
self._ema = None
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(golden_ratio_cubes_strategy, self).OnReseted()
self._bb = None
self._ema = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(golden_ratio_cubes_strategy, self).OnStarted2(time)
bb_len = int(self._bb_length.Value)
self._bb = BollingerBands()
self._bb.Length = bb_len
self._bb.Width = 2.0
self._ema = ExponentialMovingAverage()
self._ema.Length = bb_len
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(self._bb, self._ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._bb)
self.DrawOwnTrades(area)
def _on_process(self, candle, bb_value, ema_value):
if candle.State != CandleStates.Finished:
return
if not self._bb.IsFormed or not self._ema.IsFormed:
return
if bb_value.IsEmpty or ema_value.IsEmpty:
return
if bb_value.UpBand is None or bb_value.LowBand is None or bb_value.MovingAverage is None:
return
upper = float(bb_value.UpBand)
lower = float(bb_value.LowBand)
mid = float(bb_value.MovingAverage)
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
price = float(candle.ClosePrice)
cooldown = int(self._cooldown_bars.Value)
if price > upper and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._cooldown_remaining = cooldown
elif price < lower and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._cooldown_remaining = cooldown
elif self.Position > 0 and price < mid:
self.SellMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
elif self.Position < 0 and price > mid:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
def CreateClone(self):
return golden_ratio_cubes_strategy()