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:
// --- 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)
buysignal = average crosses over average//rsi 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
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
//fake orders count
//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
if mfe>=takeprofit*pointsize then //testing the takeprofit
longontrading=0 //not on market anymore
if mae<=-stoploss*pointsize then //testing the stoploss
longontrading=0 //not on market anymore
//compute equity curve and its average
if ( (not onmarket and onmarket) or (tradeindex(1)=tradeindex(2) and tradeindex(1)=barindex) or (not longontrading and longontrading) ) and lastcheck<>barindex then //check if an order has just closed or not
lastcheck = barindex
if(not longontrading) 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)
strategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL
//build a loop to make the equity curve average
for i = 0 to barindex do
if strategyPNL[i]<>lastPNL then
if count=equityCurvePeriod+1 then
if last<>last then
avg = (sum/equityCurvePeriod)
if strategyPNL>avg then
realtrading=1 //activate real trading if the PnL is superior to its average
realtrading=0 //or desactivate real trading
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
//plot the fake orders activation
if longontrading then
plotLong = 0.01 //this value might be changed, depending of the strategy
plotLong = 0
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!
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.