Stochastic-Strategie
Einfache Strategie mit dem Stochastic-Oszillator. Eine Long-Position wird eröffnet, wenn %K über den überverkauften Schwellenwert kreuzt. Eine Short-Position wird eröffnet, wenn %K unter den überkauften Schwellenwert kreuzt. Die Standardwerte betragen 50 für beide Richtungen.
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Stochastic %K threshold-crossing reversal strategy.
/// </summary>
public class StochasticStrategy : Strategy
{
private readonly StrategyParam<int> _kPeriod;
private readonly StrategyParam<decimal> _overSold;
private readonly StrategyParam<decimal> _overBought;
private readonly StrategyParam<DataType> _candleType;
private readonly List<ICandleMessage> _candles = [];
private decimal? _previousK;
public int KPeriod { get => _kPeriod.Value; set => _kPeriod.Value = value; }
public decimal OverSold { get => _overSold.Value; set => _overSold.Value = value; }
public decimal OverBought { get => _overBought.Value; set => _overBought.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public StochasticStrategy()
{
_kPeriod = Param(nameof(KPeriod), 14).SetGreaterThanZero();
_overSold = Param(nameof(OverSold), 50m);
_overBought = Param(nameof(OverBought), 50m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_candles.Clear();
_previousK = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
_candles.Add(candle);
if (_candles.Count > KPeriod)
_candles.RemoveAt(0);
if (_candles.Count < KPeriod)
return;
var high = _candles.Max(c => c.HighPrice);
var low = _candles.Min(c => c.LowPrice);
var currentK = high == low
? 50m
: (candle.ClosePrice - low) / (high - low) * 100m;
if (_previousK is decimal previous)
{
var signal = GetSignal(previous, currentK, OverSold, OverBought);
if (signal > 0 && Position <= 0m)
BuyMarket(Volume + Math.Abs(Position));
else if (signal < 0 && Position >= 0m)
SellMarket(Volume + Math.Abs(Position));
}
_previousK = currentK;
}
internal static int GetSignal(decimal previousK, decimal currentK, decimal overSold, decimal overBought)
{
if (previousK <= overSold && currentK > overSold)
return 1;
if (previousK >= overBought && currentK < overBought)
return -1;
return 0;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
class stochastic_strategy(Strategy):
def __init__(self):
super(stochastic_strategy, self).__init__()
self._k_period = self.Param("KPeriod", 14).SetGreaterThanZero()
self._over_sold = self.Param("OverSold", 50.0)
self._over_bought = self.Param("OverBought", 50.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._candles = []
self._previous_k = None
def GetWorkingSecurities(self):
return [(self.Security, self._candle_type.Value)]
def OnReseted(self):
super(stochastic_strategy, self).OnReseted()
self._candles = []
self._previous_k = None
def OnStarted2(self, time):
super(stochastic_strategy, self).OnStarted2(time)
self.SubscribeCandles(self._candle_type.Value).Bind(self._process_candle).Start()
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
period = int(self._k_period.Value)
self._candles.append(candle)
if len(self._candles) > period:
del self._candles[0]
if len(self._candles) < period:
return
high = max(float(c.HighPrice) for c in self._candles)
low = min(float(c.LowPrice) for c in self._candles)
current_k = 50.0 if high == low else (float(candle.ClosePrice) - low) / (high - low) * 100.0
if self._previous_k is not None:
signal = self.get_signal(
self._previous_k, current_k,
float(self._over_sold.Value), float(self._over_bought.Value))
if signal > 0 and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif signal < 0 and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
self._previous_k = current_k
@staticmethod
def get_signal(previous_k, current_k, over_sold, over_bought):
if previous_k <= over_sold and current_k > over_sold:
return 1
if previous_k >= over_bought and current_k < over_bought:
return -1
return 0
def CreateClone(self):
return stochastic_strategy()