This new article deals with a code snippet that can improve a strategy by stopping the real trading when the performance of the strategy decreases significantly, to simulate new orders by the code so that, as soon as the strategy performs again, restart auto trading in real time.

The simulation of trading orders is a point that has been addressed already on the site, especially in this old article of the blog equity curve trading and also in some topics of the forum.

I had not yet managed to find the time to put the idea into ProBuilder language so as to allow the first tests and application but it is now done with this new article, I hope it will arouse interest and that the bravest of you will be able to carry out tests and extensions on the subject, from this code ðŸ˜‰

## Trading is a game, a statistical simulation

Even knowing that a strategy is profitable, it often happens that the distribution of orders can act in this way:

Out of 20 orders in total, 12 were winners and we closed in loss 8 times, nothing very extraordinary, yes but if these 8 losses had been successive … What a pity! This will have the effect, very often, to no longer trust the strategy, to stop it or again to restart working on it so that it can no longer suffer from this type of series of losses.

The code that follows will allow us, for example, to stop the strategy when the performance, due to these successive losses allows us to say: “ok it’s time to take a break”.

We will simply perform an average of the last X performances to assess whether the strategy currently performs or not. If the performance falls below this average, then we simulate false orders and test them to see if the performance has returned. If so, then we will re-engage automatic trading. Easy! ðŸ™‚

## Application on a trend following strategy

A simple strategy made of moving averages crosses (7 and 21 periods), buying only, with takeprofit and fixed stoploss, let’s look at its equity curve:

(backtest performed on Mini DAX FUTURES, 5 minutes, 2 points spread).

There is uneven performance over time, but logically expected due to rather bearish periods and range areas where a trend following strategy is not suitable.

Let’s look at the cumulative performance of the orders and make an average of the last 20 performances:

When the performances fall below this blue line, we will start our “fake orders”, here is the complete 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
defparam cumulateorders=false // --- strategy settings tpratio = 2.7 stoploss = 65 takeprofit = stoploss*tpratio // --- simulated trading settings equityCurvePeriod = 20 //orders quantity for the equity curve average activateSimulatedTrading = 1 //(0= false / 1 =true) //strategies buysignal = average[7] crosses over average[21]//rsi[2] crosses over 30 if realtrading then //real trading if not longonmarket and buysignal then buy at market ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later endif set target pprofit takeprofit set stop ploss stoploss elsif not realtrading and ordercount>equityCurvePeriod then //fake trading if not longontrading and buysignal then openprice=close //fake order open price longontrading=1 //we are now on market //reset MFE & MAE values mfe=0 mae=0 //fake orders count fakeorders=fakeorders+1 endif endif //check profit n loss of the fake order if longontrading=1 then mfe = max(high-openprice,mfe) //compute the MaxFavorableExcursion mae = min(low-openprice,mae) //compute the MaxAdverseExcursion //profit achieved if mfe>=takeprofit*pointsize then //testing the takeprofit orderPNL=((openprice+takeprofit*pointsize)/openprice)-1 longontrading=0 //not on market anymore endif //shit happens! if mae<=-stoploss*pointsize then //testing the stoploss orderPNL=-(((openprice-stoploss*pointsize)/openprice)-1) longontrading=0 //not on market anymore endif endif //compute equity curve and its average if ( (not onmarket and onmarket[1]) or (tradeindex(1)=tradeindex(2) and tradeindex(1)=barindex[1]) or (not longontrading and longontrading[1]) ) and lastcheck<>barindex then //check if an order has just closed or not lastcheck = barindex if(not longontrading[1]) then //if it was a real order orderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order) endif strategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL //build a loop to make the equity curve average count=0 sum=0 lastPNL=0 for i = 0 to barindex do if strategyPNL[i]<>lastPNL then lastPNL=strategyPNL[i] count=count+1 sum=sum+strategyPNL[i] if count=equityCurvePeriod+1 then sum=sum-last last=strategyPNL[i] break // endif endif next if last<>last[1] then avg = (sum/equityCurvePeriod) endif if strategyPNL>avg then realtrading=1 //activate real trading if the PnL is superior to its average else realtrading=0 //or desactivate real trading endif if ordercount<=equityCurvePeriod or activateSimulatedTrading=0 then realtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real trading endif endif //plot the fake orders activation if longontrading then plotLong = 0.01 //this value might be changed, depending of the strategy else plotLong = 0 endif // //plot values graph strategyPNL //plot the cumulated PnL graph avg coloured(0,0,255) //plot the average of the equity curve graph plotLong coloured(0,155,0) //plot the fake orders activation |

*Explanations about the function code and how it works are inside the code itself.*

It should be noted that in order to calculate this average, it will of course be necessary to wait for a sufficient number of real orders to have taken place (ie 20 in the present case), therefore during the first 20 orders, the strategy will be trading all by itself, help! ðŸ™‚

The results are encouraging, the strategy stops trading during bad times, compare the 2 equities curves, below is the basic strategy, above the strategy with the simulated orders:

The false orders are represented by the green line at the bottom of the graph, we note the performances that accumulates well on the black curve (and on the average in blue), while there is no order really at the market!

A magic function? never lose again?

We could indeed go to that conclusion. The worst strategy deserves this feature to be added. However, a strategy that performs well in the contexts for which it has been studied and coded, should not find any use there. In any case, that’s the conclusion I draw from it.

However and in summary, I will say that indeed, this function, added to your strategy will allow you not to go beyond serious problems and could even improve these performances, in most of the cases.

Here, we can conclude that the strategy benefits from the principle of orders simulation, since we see that the equity curve follows a constant rise. Even if the actual result, it is not entirely satisfactory, we managed to significantly improve the performance!

Interested in adding to your strategy, privately? Contact our programming service.

## What is the next step ?

This concept demonstrated and coded in this article exists only at an experimental stage and should undoubtedly be experienced further by the community ðŸ™‚

In addition, fake orders are tested only once per bar when the code is read, which would not be the case with stoploss and takeprofit in real time since these levels are registered

in the order book of the broker. Also, I did not use takeprofit and dynamic stoploss, but only fixed levels … some work is still to do if we want to simulate all possibilities of a real strategy and real orders facing the market!

In the next article, I will add the code to handle short selling positions. I will also discuss the use of other calculation methods to consider whether it is whether or not to return to real positions again, using technical indicators such as the RSI calculated on the last X performances, for example.

GraHal• 6 days ago #Hey, looks well interesting, I like it a lot!

I’ll get my head around it and work it into my Systems! ðŸ™‚

Thank You Nicolas

criscolci• 3 days ago #Thanks!!!