Built-in Kelly Ratio
Channel breakout strategy using a moving average and ATR bands with position sizing based on the Kelly ratio.
Details
- Entry Criteria: Price crossing above or below ATR-based bands.
- Long/Short: Both.
- Exit Criteria: Optional take profit and stop loss.
- Stops: Optional.
- Default Values:
Length= 20Multiplier= 1AtrLength= 10UseEma= trueUseKelly= trueUseTakeProfit= falseUseStopLoss= falseTakeProfit= 10StopLoss= 1CandleType= TimeSpan.FromMinutes(1)
- Filters:
- Category: Breakout
- Direction: Both
- Indicators: MA, ATR
- Stops: Optional
- Complexity: Basic
- Timeframe: Intraday (1m)
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Channel breakout strategy with Kelly ratio position sizing.
/// Uses EMA crossover for trend direction.
/// </summary>
public class BuiltInKellyRatioStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public BuiltInKellyRatioStrategy()
{
_fastLength = Param(nameof(FastLength), 120)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators");
_slowLength = Param(nameof(SlowLength), 450)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0m;
_prevSlow = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastLength };
var slowEma = new ExponentialMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastEma);
DrawIndicator(area, slowEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevFast == 0m || _prevSlow == 0m)
{
_prevFast = fast;
_prevSlow = slow;
return;
}
if (_prevFast <= _prevSlow && fast > slow && Position <= 0)
{
BuyMarket();
}
else if (_prevFast >= _prevSlow && fast < slow && Position >= 0)
{
SellMarket();
}
_prevFast = fast;
_prevSlow = slow;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class built_in_kelly_ratio_strategy(Strategy):
"""
Channel breakout strategy with Kelly ratio position sizing.
Uses EMA crossover for trend direction.
"""
def __init__(self):
super(built_in_kelly_ratio_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 120) \
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators")
self._slow_length = self.Param("SlowLength", 450) \
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
@property
def fast_length(self):
return self._fast_length.Value
@fast_length.setter
def fast_length(self, value):
self._fast_length.Value = value
@property
def slow_length(self):
return self._slow_length.Value
@slow_length.setter
def slow_length(self, value):
self._slow_length.Value = value
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(built_in_kelly_ratio_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
def OnStarted2(self, time):
super(built_in_kelly_ratio_strategy, self).OnStarted2(time)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.fast_length
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.slow_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ema, slow_ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ema)
self.DrawIndicator(area, slow_ema)
self.DrawOwnTrades(area)
def on_process(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
if self._prev_fast == 0.0 or self._prev_slow == 0.0:
self._prev_fast = fast_value
self._prev_slow = slow_value
return
if self._prev_fast <= self._prev_slow and fast_value > slow_value and self.Position <= 0:
self.BuyMarket()
elif self._prev_fast >= self._prev_slow and fast_value < slow_value and self.Position >= 0:
self.SellMarket()
self._prev_fast = fast_value
self._prev_slow = slow_value
def CreateClone(self):
return built_in_kelly_ratio_strategy()