Practical use of martingale code in automated trading

 

When it comes to  automated trading, we often read that no automated strategy can be as good as a manual trading system managed by a smart trader with many years of trading knowledge behind him. That is true, and not true. Because every path lead to Rome, you know, there is not a single path to follow in trading ; while some people make a living with averaging down, some others loose everything with their bad stoplosses price levels.

Of course, i will not say that martingale money management is the way to get better and consistent profit, but it can give us an hedge on medium performance’s trading strategies that underperform some time.

As i constantly tell to my customers, automated trading need often more work than manual trading, as it relies on maths, theory, hard research and myriad of others technicals things we have to manage : slippage, good data, spread, server lags, etc.

Fortunately, ProRealTime comes with ProOrder and server side execution, we got here a very nice improvement on what represent automated trading for retails traders. No technical issues to handle, no laggy VPS or expensive server to pay, everything is managed by ProRealTime servers and that’s a very good point for us. But that’s not the subject of this article, so let’s do programming with martingale codes we can find in the ProBacktest documentation.

 

A simple trading strategy to automate

Let’s make a trading strategy with breakout entries on the last X days high. Then, positions exit will be managed by Y days low breakout.

 

The indicator code for better visualization of entries and exits : (you’ll find the ITF file attached at the end of this article)

 

Now the ProBacktest code for the automated entries and exit :

 

Good performance of a classic breakout strategy traded on Spanish IBEX35 index, with no optimised parameters, as we are using 50 and 20 periods that are quiet common.

IBEX breakout strategy performance

Martingale position sizing

Now let’s figure how can result this strategy with a D’Alembert martingale pyramid :

Here is the code :

This martingale was made famous by d’Alembert, a French 18th century mathematician. In case of loss, the position size is increased by 1 unit, in case of gain it is decreased by 1 unit. This technique of position size management is relevant only if we suppose that successive gains reduce the probability of winning again and successive losses reduce the probability of losing again.

IBEX breakout strategy performance with martingale

Of course the gain are higher, it’s a martingale sir 🙂 but loss too.. Though, 540% performance for a 50% drawdown, more than the double drawdown for 10x gain on the initial version can make us decide to study it a bit more..

For this trading strategy, on the original version without martingale, there were only 30% of winning positions. So let’s try the other version of this D’Alembert martingale theory that make an inverse position sizing while we are winning : it increased the position by 1 lot and reduced it while losing.
In the code, we just have to change the positing sizing formula :
Let’s give it a try :
IBEX breakout strategy performance with anti martingale
OK, now what we see here is clear. A 30% winning strategy that give you good result at the end of your backtest is a strategy where you can add a martingale as a money management system. Why ? Because winners are always bigger than losers so if you can already have good performance with as little as 30% winning trades, then you already have a solid strategy on your side, and increase your positing sizing will give you better results, at the end, than the original one.

What to conclude ?

Thus, is it better to increase my risk to increase my performance ? The choice is yours, no one will give you a clear answer while it is only a question of risk aversion on your side. If you can stand big drawdown you surely can have it in your trading arsenal. But remember that martingale position sizing is only a mathematical approach that will work in an universe where your time and your account balance is infinite. So since it is impossible in real life, it is largely possible that big losers will erase past good results, you must be aware of that fact, really.
So what we can conclude, at the end ? Well, good strategies merit martingale, not the bad ones.

 

 

 

Share this

  1. Andres • 10/31/2015 #

    Umm, interesting article. I’ll try on my backtesting learning . 
    Thanks for all  your  articles, Nicolás. 

  2. absent1980 • 10/31/2015 #

    Can anyone help please with non martingale coding? I need to increase maxrisk after every win by adding a proportion of the strategy profit. Tried this coding but it doesn’t work as expected.
    if positionperf(1)>0 then
    coefficient = coefficient+0.05
    else
    coefficient = 0
    endif

    if strategyprofit > 0 then
    maxrisk = round(equity*Risk)+(strategyprofit*coefficient)
    else
    maxrisk = round(equity*Risk)
    endif
     

    • Nicolas • 10/31/2015 #

      I don’t see the whole code of your formula, but I guess your ‘equity’ variable has already strategyprofit in its own calculation. Otherwise, I don’t see anything wrong, what is your problem exactly?

  3. absent1980 • 10/31/2015 #

    I think it may be missing resetting ‘coefficient’ to zero after a loss. The idea is that you preserve you capital and don’t risk more than 1% of the initial capital but instead risk more of your strategy profit. On backtesting it either bursts with massive gains or loses all capital, depending on a win/loss ratio of the system. Here is a code for money management:
    Capital = 10000
    Risk = 0.01
    stopLoss = ATR*x

    REM Calculate contracts
    equity = Capital + StrategyProfit

    if positionperf(1)>0 then
    coefficient = coefficient+0.02
    else
    coefficient = 0
    endif

    if strategyprofit > 0 then
    maxrisk = 100+(strategyprofit*coefficient)
    else
    maxrisk = round(equity*Risk)
    endif
     

    • Nicolas • 10/31/2015 #

      You should use the GRAPH instruction to see value of your ‘coefficient’ variable over time.

  4. absent1980 • 10/31/2015 #

    Just done what you suggested, even more confusing now. Coefficient value jumps from 0 to 12 after two wins, then drops to 0.2 after a loss and goes to 21 after a next win. Two wins suppose to produce a coefficient of 0.06, not 12, and coefficient value should not take into consideration all previous wins, just wins after a last loss. Also it would be useful to cap max coefficient to let say 0.06.

    • Nicolas • 10/31/2015 #

      It’s because you are calculating your coefficient variable at each new bar, despite the fact that you do not want to launch a new trade. You should calculate this variable only once in your trades conditions.

  5. JohnScher • 10/31/2015 #

    Looking for  a little help with martingale
    Martingale Pyramid should be stop at last at reached final a fixed profit of (maybe) 100 dollar
    small strategie before integrate the martingale
    IF TEMA [1) crosses over TEMA [4] then
    buy 1 contract at market
    Endif
    Set target $profit 100
    Set stop $loss 10
     
    And now the martingale to integratev (not correct code lines, sure, i m absolute beginner, hope you can understand what i want to use)
    Target StrategyProfit 100 Dollar
    at first Set StrategyProfit = 0
    If after first trade strategyprofit <0 then// (after first trade = – 10)
    set positionsize new = corrrect postionsize to get: the Target StratgegyProfit + the loss from first trade
    then start trade again
    If second trade loss so do again
    find correct positionsize to get : the Target StratgegyProfit + the loss from first + loss from second trade
    and so again again until
    IF StrategyProfit = 100 or StrategyProfit = – 100 Then
    Quit //strategy
     
    In this way above you win sometime 100 Dollar or you losse 100 Dollar (but not more, and the danger of martingale is limited
    result: + 100 dollar you have won
    result: – 100 dollar you strategy isn´t quite good
     
    all numbers above are examples to variabel at any strategy
     
    Can understand? Can help?
    kind johnscher
     
     
     

  6. Kenneth Kvistad • 10/31/2015 #

    How can you make this strategy reset every run up?
    Lets say:
    We add one contract every win on top of the one from previous win.
    And if we loose we take 1 contract of, but how can we make this martingale reset if we loose first time.
    10win and x contracts but when it losses first time with x contracts it starts to trade 1 contract again until it wins again and starts over?
    I dont whant the program to avrage down —1 but resett to defalt contract lets say 1contract.
     

    2
    3
    4
    5
    6
    7
    8
    9

    // positions sizing
    IF Barindex= ExitIndex+1 THEN
       ExitIndex =0
    IF PositionPerf(1)<0 THEN
       OrderSize =MAX(OrderSize–1,1)
    ELSIF PositionPerf(1)>=0 THEN
       OrderSize = OrderSize+1
    ENDIF
    ENDIF

  7. SAM • 10/31/2015 #

    Hy Nicolas,
    I try to learn the programming logic alone … (I’m not a programmer). So I apologize for the trivial questions
    I have read your “Martingala code”. I don’t understand 2 line of code
    a)IF Barindex= ExitIndex+1 THEN
    ExitIndex =0 what is the meaning of this code, because you have to set up a “Entriindex”?
    Thank you so mutch..

    • Nicolas • 10/31/2015 #

      “Exitindex” variable is the bar number from when the BUY order has been exited.

  8. SAM • 10/31/2015 #

    of course, in fact in the previous code (frome line 17 to 19) when there is the exit from the buy we fix Entryindex = barindex.
    But why is necessary write the code:
    IF Barindex= ExitIndex+1 THEN
    ExitIndex =0
    Thanks

    • Nicolas • 10/31/2015 #

      to increase the lot size, only 1 time at the next bar and not continuously in the next ones after the trade has closed.

  9. SAM • 10/31/2015 #

    ha ok, so without this code the strategy incrase continuously the lot size…
    Thank you

  10. conwol • 10/31/2015 #

    How can the code be adjusted to allow short trades also? I tried and I am getting bigger position size for short positions both when I lose and win.

    • Nicolas • 10/31/2015 #

      You can search the forums for other martingale codes, there are many ones.

  11. lilo789 • 10/31/2015 #

    Hi Nicolas thank you very much for this algo that I tried with an Ichimoku kinko hyo strat.
    Do you have an idea on how to set the barindex logic with a //SET STOP %LOSS sl
    //SET TARGET %PROFIT tp ? thank you very much 🙂

    • Nicolas • 10/31/2015 #

      Sorry what do you mean by “the barindex logic”?

avatar
Register or

Top