I couldn’t find MQL5 code for the Kelly Criterion, so I decided to write it myself; but it turned out that the Kelly Criterion only works for Bernoulli Distributions. This means it works only for fixed profits and losses, i.e. fixed SL and TP, but I rarely do.
So, based upon the work of Ralph Vince’s book The Mathematics of Money Management, and borrowing concepts from python code I found online, I created this MQL5 library for Optimal f.
I am including test(s) that I used to verify that my code gives the same results as the example in Ralph Vince’s book. That is: +9, +18, +7, +1, +10, -5, -3, -17, -7 .
Note: I set GEOM_MEAN_MIN_TRADES = 0 to have the unit tests run.
Note: This calculates Optimal f only. It does not show how to calculate a position size. That part is up to you.
Note: This code is provided for testing and edification only. UNDERSTAND THE MATHEMATICS BEFORE USING THIS ON A REAL TRADING ACCOUNT! It’s highly possible you will wipe out your account if you don’t know what you are doing.