La estrategia Night Stochastic opera únicamente durante la tranquila sesión nocturna de 21:00 a 06:00. Utiliza la línea %K del Stochastic Oscillator para detectar condiciones de sobreventa y sobrecompra.
Cuando el oscilador cae por debajo del nivel de sobreventa se abre una posición larga. Cuando sube por encima del nivel de sobrecompra se abre una posición corta. Cada operación está protegida por niveles fijos de stop loss y take profit medidos en puntos de precio.
Detalles
Criterios de entrada:
Largo: %K < StochOversold y el tiempo está entre 21:00 y 06:00.
Corto: %K > StochOverbought y el tiempo está entre 21:00 y 06:00.
Largo/Corto: Ambas direcciones.
Criterios de salida: Posición cerrada por stop loss o take profit predefinidos.
Stops: Sí, utiliza stop loss y take profit fijos.
Valores predeterminados:
StopLossPoints = 40
TakeProfitPoints = 20
StochOversold = 30
StochOverbought = 70
CandleType = marco temporal de 15 minutos
Filtros:
Categoría: Basado en indicadores
Dirección: Ambos
Indicadores: Stochastic Oscillator
Marco temporal: Corto plazo
Ventana de trading: 21:00-06:00 hora del servidor
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Night trading strategy based on the Stochastic Oscillator.
/// Trades only during night hours when the market is quiet.
/// </summary>
public class NightStrategy : Strategy
{
private readonly StrategyParam<decimal> _stochOversold;
private readonly StrategyParam<decimal> _stochOverbought;
private readonly StrategyParam<DataType> _candleType;
public decimal StochOversold { get => _stochOversold.Value; set => _stochOversold.Value = value; }
public decimal StochOverbought { get => _stochOverbought.Value; set => _stochOverbought.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public NightStrategy()
{
_stochOversold = Param(nameof(StochOversold), 30m)
.SetDisplay("Stochastic Oversold", "Oversold level for %K", "Indicators");
_stochOverbought = Param(nameof(StochOverbought), 70m)
.SetDisplay("Stochastic Overbought", "Overbought level for %K", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Time frame for candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var stochastic = new StochasticOscillator();
stochastic.K.Length = 14;
stochastic.D.Length = 3;
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(stochastic, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, stochastic);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stochValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var stoch = (IStochasticOscillatorValue)stochValue;
if (stoch.K is not decimal kValue)
return;
// Trade only during night hours 21:00-06:00
var hour = candle.OpenTime.Hour;
var isNight = hour >= 21 || hour < 6;
if (!isNight)
return;
if (kValue < StochOversold && Position <= 0)
BuyMarket();
else if (kValue > StochOverbought && Position >= 0)
SellMarket();
}
}
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 StochasticOscillator
from StockSharp.Algo.Strategies import Strategy
class night_strategy(Strategy):
def __init__(self):
super(night_strategy, self).__init__()
self._stoch_oversold = self.Param("StochOversold", 30.0) \
.SetDisplay("Stochastic Oversold", "Oversold level for %K", "Indicators")
self._stoch_overbought = self.Param("StochOverbought", 70.0) \
.SetDisplay("Stochastic Overbought", "Overbought level for %K", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Time frame for candles", "General")
@property
def stoch_oversold(self):
return self._stoch_oversold.Value
@property
def stoch_overbought(self):
return self._stoch_overbought.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(night_strategy, self).OnReseted()
def OnStarted2(self, time):
super(night_strategy, self).OnStarted2(time)
stochastic = StochasticOscillator()
stochastic.K.Length = 14
stochastic.D.Length = 3
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(stochastic, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, stochastic)
self.DrawOwnTrades(area)
def process_candle(self, candle, stoch_value):
if candle.State != CandleStates.Finished:
return
k = stoch_value.K
if k is None:
return
k_value = float(k)
# Trade only during night hours 21:00-06:00
hour = candle.OpenTime.Hour
is_night = hour >= 21 or hour < 6
if not is_night:
return
if k_value < float(self.stoch_oversold) and self.Position <= 0:
self.BuyMarket()
elif k_value > float(self.stoch_overbought) and self.Position >= 0:
self.SellMarket()
def CreateClone(self):
return night_strategy()