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)
1 2 3 4 5 6 7 |
// hp = 50 (periods of the highest high lookback for entries purposes) // lp = 20 (periods of the lowest low lookback for trades exit) x = highest[hp](high) y = lowest[lp](low) RETURN x as "long term highest", y as "short term lowest" |
Now the ProBacktest code for the automated entries and exit :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// our tresholds for our long only strategy x = highest[50](high) y = lowest[20](low) // we are buying when close of the actual candle is above the previous 50 bars highest TradeBuy = close>x[1] // we exit our buy trade when close of the actual candle fall below the last 20 bars low TradeBuyExit = close<y[1] IF NOT LongOnMarket AND TradeBuy THEN BUY 1 CONTRACTS AT MARKET ENDIF If LongOnMarket AND TradeBuyExit THEN SELL AT MARKET ENDIF |
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.
Martingale position sizing
Now let’s figure how can result this strategy with a D’Alembert martingale pyramid :
Here is the code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
ONCE OrderSize = 1 ONCE ExitIndex = -2 // our tresholds for our long only strategy x = highest[50](high) y = lowest[20](low) // we are buying when close of the actual candle is above the previous 50 bars highest TradeBuy = close>x[1] // we exit our buy trade when close of the actual candle fall below the last 20 bars low TradeBuyExit = close<y[1] IF NOT LongOnMarket AND TradeBuy THEN BUY OrderSize CONTRACTS AT MARKET ENDIF If LongOnMarket AND TradeBuyExit THEN SELL AT MARKET ExitIndex=BarIndex ENDIF // positions sizing IF Barindex= ExitIndex+1 THEN ExitIndex =0 IF PositionPerf(1)<0 THEN OrderSize = OrderSize+1 ELSIF PositionPerf(1)>=0 THEN OrderSize =MAX(OrderSize-1,1) ENDIF ENDIF |
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..
1 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 |
What to conclude ?
Umm, interesting article. I’ll try on my backtesting learning .
Thanks for all your articles, Nicolás.
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
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?
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
You should use the GRAPH instruction to see value of your ‘coefficient’ variable over time.
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.
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.
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
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
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..
“Exitindex” variable is the bar number from when the BUY order has been exited.
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
to increase the lot size, only 1 time at the next bar and not continuously in the next ones after the trade has closed.
ha ok, so without this code the strategy incrase continuously the lot size…
Thank you
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.
You can search the forums for other martingale codes, there are many ones.
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 🙂
Sorry what do you mean by “the barindex logic”?