Strategy · Pine Script v4 · On the chart

Built-in Kelly ratio for position sizing

by hasnocool

This strategy plots a moving average with a range band on the price chart and places stop entries when the source crosses the upper or lower band.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code88
Settings13inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

88 lines of Pine Script v4 from Built-in Kelly ratio for dynamic position sizing.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Built-in Kelly ratio for dynamic position sizing.pine
//@version=4
strategy("Built-in Kelly ratio for position sizing", overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=10000, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)
c = close
useKelly = input(true, "Kelly Ratio Position Sizing")
krp = strategy.wintrades / strategy.closedtrades
krw =  strategy.grossprofit / strategy.wintrades
krl = strategy.grossloss / strategy.losstrades
kr = ((krp - (1-krp) / (krw/krl)) * 100) / 100
qty = 10000.0
if useKelly
    qty := 10000.0 / c
    if kr > 0
        qty := (strategy.equity * kr) / c
    
i_startTime = input(defval = timestamp("01 Mar 1900 00:00 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Mar 2221 00:00 +0000"), title = "End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
length = input(20, minval=1)
mult = input(1.0, "Multiplier")
src = input(close, title="Source")
exp = input(true, "Use Exponential MA")
BandsStyle = input("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style")
atrlength = input(10, "ATR Length")
esma(source, length)=>
    s = sma(source, length)
    e = ema(source, length)
    exp ? e : s
ma = esma(src, length)
rangema = BandsStyle == "True Range" ? rma(tr(true), length) : BandsStyle == "Average True Range" ? atr(atrlength) : rma(high - low, length)
upper = ma + rangema * mult
lower = ma - rangema * mult
crossUpper = crossover(src, upper)
crossLower = crossunder(src, lower)
bprice = 0.0
bprice := crossUpper ? high+syminfo.mintick : nz(bprice[1])
sprice = 0.0
sprice := crossLower ? low -syminfo.mintick : nz(sprice[1])
crossBcond = false
crossBcond := crossUpper ? true
     : na(crossBcond[1]) ? false : crossBcond[1]
crossScond = false
crossScond := crossLower ? true
     : na(crossScond[1]) ? false : crossScond[1]
cancelBcond = crossBcond and (src < ma or high >= bprice )
cancelScond = crossScond and (src > ma or low <= sprice )
if inDateRange
    if useKelly
        if (cancelBcond)
            strategy.cancel("Long")
        if (crossUpper)
            strategy.entry("Long", strategy.long, qty, stop=bprice, comment="Long")
        if (cancelScond)
            strategy.cancel("Short")
        if (crossLower)
            strategy.entry("Short", strategy.short, qty, stop=sprice, comment="Short")
    else
        if (cancelBcond)
            strategy.cancel("Long")
        if (crossUpper)
            strategy.entry("Long", strategy.long, stop=bprice, comment="Long")
        if (cancelScond)
            strategy.cancel("Short")
        if (crossLower)
            strategy.entry("Short", strategy.short, stop=sprice, comment="Short")
usetp = input(false, "use Take Profit")
usesl = input(false, "use Stop Loss")
tp = input(10.0, "take profit") / 100
sl = input(1.0, "stop loss") / 100
avg = strategy.position_avg_price
longprofit = avg*tp/syminfo.mintick
longloss = avg*sl/syminfo.mintick
shortprofit = avg*tp/syminfo.mintick
shortloss = avg*sl/syminfo.mintick
if usetp and not usesl
    strategy.exit("Long Exit", "Long", profit=longprofit)
    strategy.exit("Short Exit", "Short", profit=shortprofit)
if usesl and not usetp
    strategy.exit("Long Exit", "Long", loss=longloss)
    strategy.exit("Short Exit", "Short", loss=shortloss)
if usetp and usesl
    strategy.exit("Long Exit", "Long", profit=longprofit, loss=longloss)
    strategy.exit("Short Exit", "Short", profit=shortprofit, loss=shortloss)
plotchar(krp * 100, "% profitable", "")
plotchar(krw, "avg win", "")
plotchar(krl, "avg loss", "")
plotchar(strategy.equity, "Equity", "")
plotchar(qty*c, "Quantity", "")
Expand (97 lines)

Overview

Long and short orders are cancelled if price returns through the average or reaches the stored stop price. Optional Kelly sizing scales quantity from closed-trade win rate and average win versus loss when the ratio is positive. Take profit and stop loss are both off by default, so there is no protective exit unless those inputs are enabled. A start and end time limits when orders are allowed.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Moving averages, Volatility & bands, Breakout

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Kelly Ratio Position SizingbooltrueuseKelly
Start Timetimetimestamp("01 Mar 1900 00:00 +0000")i_startTime
End Timetimetimestamp("01 Mar 2221 00:00 +0000")i_endTime
lengthint20length
Multiplierfloat1.0mult
Sourcesourceclosesrc
Use Exponential MAbooltrueexp
Bands StylestringAverage True RangeBandsStyle
ATR Lengthint10atrlength
use Take Profitboolfalseusetp
use Stop Lossboolfalseusesl
take profitfloat10.0tp
Show all 13 settings
SettingTypeDefaultVariable
stop lossfloat1.0sl
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples

Keltner Channels Strategy

by TWODS-CAPITAL
37 stars

This strategy builds Keltner-style bands around an exponential or simple moving average of the chosen source. Band width uses average true range, raw true range, or a smoothed high-low range, scaled by a multiplier. When the source crosses above the upper band

Strategy v5 Volatility & bandsBreakout
Updated 3 years ago · MIT GitHub repository of Keltner Channels Strategy
16 stars

This strategy plots Donchian channels, trailing stops, and profit targets directly on the price chart. It enters breakout trades using a 55-bar Donchian channel and sizes positions according to an ATR-based risk percentage per unit. The system adds units as pr

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 10: Profit Targets

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers