Estrategia Golden Ratio Cubes
La estrategia Golden Ratio Cubes utiliza las matemáticas de Fibonacci para detectar rupturas. Rastrea el máximo más alto y el mínimo más bajo durante una ventana de referencia y calcula extensiones basadas en el ratio áureo (φ ≈ 1.618). Cuando el precio cierra más allá de estas extensiones, la estrategia entra en la dirección del rompimiento.
Detalles
- Criterios de entrada:
- Cierre por encima de la extensión del ratio áureo del rango reciente → Comprar.
- Cierre por debajo de la extensión del ratio áureo del rango reciente → Vender.
- Largo/Corto: Ambos.
- Criterios de salida:
- Señal de rompimiento opuesta.
- Stops: Ninguno.
- Valores predeterminados:
Lookback= 34Phi= 1.618
- Filtros:
- Categoría: Ruptura
- Dirección: Largo y Corto
- Indicadores: Highest, Lowest
- Stops: No
- Complejidad: Bajo
- Marco temporal: Cualquiera
- Estacionalidad: No
- Redes neuronales: No
- Divergencia: No
- Nivel de riesgo: Medio
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.
/// The range spans the highest high and lowest low of the previous Lookback candles. Its golden ratio extensions are
/// lowest + Phi * range above and highest - Phi * range below. A close above the upper extension buys and a close below the
/// lower extension sells; an opposite breakout reverses the position.
/// </summary>
public class GoldenRatioCubesStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<decimal> _phi;
private readonly StrategyParam<DataType> _candleType;
private Highest _highest;
private Lowest _lowest;
private decimal? _prevHighest;
private decimal? _prevLowest;
/// <summary>
/// Candles the range spans.
/// </summary>
public int Lookback
{
get => _lookback.Value;
set => _lookback.Value = value;
}
/// <summary>
/// Golden ratio of the extensions.
/// </summary>
public decimal Phi
{
get => _phi.Value;
set => _phi.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public GoldenRatioCubesStrategy()
{
_lookback = Param(nameof(Lookback), 34)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Candles the range spans", "Indicators");
_phi = Param(nameof(Phi), 1.618m)
.SetGreaterThanZero()
.SetDisplay("Phi", "Golden ratio of the extensions", "Indicators");
_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()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevHighest = null;
_prevLowest = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevHighest = null;
_prevLowest = null;
_highest = new Highest { Length = Lookback };
_lowest = new Lowest { Length = Lookback };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
// The range is measured on the candles before this one.
var rangeHigh = _prevHighest;
var rangeLow = _prevLowest;
var highest = _highest.Process(candle.HighPrice, candle.OpenTime, true).ToDecimal();
var lowest = _lowest.Process(candle.LowPrice, candle.OpenTime, true).ToDecimal();
if (_highest.IsFormed && _lowest.IsFormed)
{
_prevHighest = highest;
_prevLowest = lowest;
}
if (rangeHigh is not decimal high || rangeLow is not decimal low)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var range = high - low;
var upperExtension = low + Phi * range;
var lowerExtension = high - Phi * range;
var close = candle.ClosePrice;
if (close > upperExtension && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < lowerExtension && 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
from StockSharp.Algo.Indicators import Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class golden_ratio_cubes_strategy(Strategy):
"""
Golden Ratio Cubes Strategy.
The range spans the highest high and lowest low of the previous Lookback candles. Its golden ratio extensions are
lowest + Phi * range above and highest - Phi * range below. A close above the upper extension buys and a close below the
lower extension sells; an opposite breakout reverses the position.
"""
def __init__(self):
super(golden_ratio_cubes_strategy, self).__init__()
self._lookback = self.Param("Lookback", 34).SetGreaterThanZero().SetDisplay("Lookback", "Candles the range spans", "Indicators")
self._phi = self.Param("Phi", 1.618).SetGreaterThanZero().SetDisplay("Phi", "Golden ratio of the extensions", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._highest = None
self._lowest = None
self._prev_highest = None
self._prev_lowest = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(golden_ratio_cubes_strategy, self).OnReseted()
self._prev_highest = None
self._prev_lowest = None
def OnStarted2(self, time):
super(golden_ratio_cubes_strategy, self).OnStarted2(time)
self._prev_highest = None
self._prev_lowest = None
self._highest = Highest()
self._highest.Length = self._lookback.Value
self._lowest = Lowest()
self._lowest.Length = self._lookback.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
# The range is measured on the candles before this one.
range_high = self._prev_highest
range_low = self._prev_lowest
highest = float(process_float(self._highest, candle.HighPrice, candle.OpenTime, True).GetValue[Decimal](None))
lowest = float(process_float(self._lowest, candle.LowPrice, candle.OpenTime, True).GetValue[Decimal](None))
if self._highest.IsFormed and self._lowest.IsFormed:
self._prev_highest = highest
self._prev_lowest = lowest
if range_high is None or range_low is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
phi = float(self._phi.Value)
rng = range_high - range_low
upper_extension = range_low + phi * rng
lower_extension = range_high - phi * rng
close = float(candle.ClosePrice)
if close > upper_extension and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < lower_extension and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return golden_ratio_cubes_strategy()