When to stop a strategy and money management code snippet
Forums › ProRealTime English forum › ProOrder support › When to stop a strategy and money management code snippet
- This topic has 21 replies, 3 voices, and was last updated 3 years ago by robertogozzi.
Tagged: money management, quit
-
-
10/11/2019 at 4:35 PM #109954
Following on from a conversation about how to know when to stop an auto-trading strategy in another thread:
https://www.prorealcode.com/topic/when-to-stop-a-live-automated-system/
I decided to try and code something that could automate the whole idea. I also decided to add in some simple money management too. The code below can be added to a strategy and then ‘positionsize’ used for the number of contracts in any buy or sellshort order.
The code works by checking every so many bars how the strategy is performing. It can check the following:
- The win rate (after a minimum number of trades have happened) and then stop the strategy if the win rate is below a minimum desired win rate.
- The draw down. If equity has dropped by a set percentage or more from the maximum profit ever achieved then the strategy is stopped.
- The remaining capital. If the starting capital is reduced by a maximum allowed percentage then the strategy is stopped.
- The percentage profit increase or decrease since the last position size adjustment. If the equity has risen or dropped by the set percentage or more then position size is increased or reduced to stay the same percentage of equity as it was percentage of capital when the strategy was first started.
If using it then you have to be aware that decisions to quit or alter position size are only made on closed trades and only on every ‘barsbeforenextcheck’ bar and so a big losing trade still open is not taken into consideration and a bad losing run between checks can still wipe you out just before the strategy stops itself.
Levels should be set based on your back test performance. For example if your strategy has a win rate of 60% then you might consider having it stop if win rate is halved at 30% as it is most likely under performing and you need to re-optimise it or just decide that it was over fitted and bin it.
Hopefully this code is of use to someone.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970// Strategy Stopper and Money Management// By Vonasi// 20191011barsbeforenextcheck = 22 // number of bars between performance checksdrawdownquitting = 1 // drawdown quitting on or off (on=1 off=0)winratequit = 25 // minimum win rate allowed before quitting (0 = off)tradesbeforewrquit = 10 // number of trades required before a win rate stop of strategy is allowed to happenincrease = 1 // position size increasing on or off (on=1 off=0)decrease = 1 // position size decreasing on or off (on=1 off=0)capital = 10000 // starting capitalstartingsize = 1 // starting position sizeminpossize = 0.2 // minimum position size allowedgaintoinc = 5 // % profit rise needed before an increase in position size is madelosstodec = 5 // % loss needed before a decrease in position size is mademaxdrawdown = 25 // maximum % draw down allowed from highest ever equity before stopping strategymaxcapitaldrop = 60 // maximum % starting capital lost before stopping strategyonce positionsize = startingsizeonce psperc = positionsize / capitalif strategyprofit <> strategyprofit[1] thenhighestprofit = max(strategyprofit, highestprofit)if winratequit thencount = count + 1if strategyprofit > strategyprofit[1] thenwin = win + 1endifwinrate = win/countif count >= tradesbeforewrquit thenif winrate < winratequit/100 thenquitendifendifendifendifif barindex mod barsbeforenextcheck = 0 thenif drawdownquitting thenif highestprofit <> 0 thenif (capital + strategyprofit) <= (capital + highestprofit) - ((capital + highestprofit)*(maxdrawdown/100)) thenquitendifendifif highestprofit = 0 thenif (capital + strategyprofit) <= capital - (capital * (maxcapitaldrop/100)) thenquitendifendifendifequity = capital + strategyprofitif increase thenif equity/lastequity >= (1+(gaintoinc/100)) thenpositionsize = (max(minpossize,equity*psperc))lastequity = equityendifendifif decrease thenif equity/lastequity <= (1-(losstodec/100)) thenpositionsize = (max(minpossize,equity*psperc))lastequity = equityendifendifendif10/11/2019 at 9:27 PM #10997610/24/2019 at 11:37 AM #11105110/24/2019 at 12:07 PM #111054I also forgot to ask Vonasi, shouldn’t the last if clause on position size be minimum instead of maximum.
1234if decrease thenif equity/lastequity <= (1-(losstodec/100)) thenpositionsize = (MIN(minpossize,equity*psperc))lastequity = equity10/24/2019 at 12:43 PM #111056No. It is correct as it is. That line is to ensure that an order is never sent to market and then rejected because it is below the minimum order size allowed for the market.
Set minpossize to whatever your broker allows as the smallest bet size for the instrument that you are trading.
07/31/2021 at 9:51 AM #174433With the Vonasi code. Reconfigure only so, if the average winning trades falls below 75% (example), the following trades are performed at half € pip than the last trade that was above 75% of the average winning trades. And if the average number of winning trades is above 75% again from now on, operate again at the usual € pip. And the same for if the drawdown is higher than 25%. Please!
Serve as an example: The following code is used to operate at half € pip if the maxprofit is less than the maximum.ELEVEN MaxProfit = 0MaxProfit = max (MaxProfit, StrategyProfit)If MaxProfit> StrategyProfit ThenPositionsize = max (1, Positionsize / 2)ENDIF07/31/2021 at 9:53 AM #17443407/31/2021 at 11:53 AM #174442Firstly you have to tally all trades
Secondly you have to tally winning trades
Thirdly you have to make a percentage of winning trades
Finally you write the instructions to accomplish to get to your goal.
There you go (it won’t be accurate if accumulating positions):123456789101112131415161718192021222324252627282930DEFPARAM CumulateOrders = falseONCE AllTrades = 0ONCE WinningTrades = 0ONCE InitialLots = 2ONCE LotSize = InitialLotsMyGain = StrategyProfit// tally each tradet1 = OnMarket AND Not OnMarket[1] //it's a new tradet2 = Not OnMarket AND Not OnMarket[1] AND MyGain <> MyGain[1] //detect any 1-bar tradet3 = ShortOnMarket AND LongOnMarket[1] //it's a new trade (S & R)t4 = ShortOnMarket[1] AND LongOnMarket //it's a new trade (S & R)AllTrades = AllTrades + ((t1 OR t2 OR t3 OR t4) AND IsLastBarUpdate)// tally winning tradesIF MyGain > MyGain[1] THENWinningTrades = WinningTrades + 1ENDIF// calculate % of winning tradesIF AllTrades > 0 THENWinPerCent = WinningTrades * 100 / AllTradesIF WinPerCent < 75 THENLotSize = InitialLots * 0.5 //halve lotsizeELSELotSize = InitialLots //restore initial lotsizeENDIFENDIFIF MyLongConditions THENBUY LotSize CONTRACTS AT MarketELSIF MyShortConditions THENSELLSHORT LotSize CONTRACTS AT MarketENDIF07/31/2021 at 12:02 PM #17444407/31/2021 at 1:40 PM #174445What do you want to do in that case?
07/31/2021 at 2:19 PM #17444707/31/2021 at 5:55 PM #174460There you go:
12345678910111213141516171819202122232425262728293031DEFPARAM CumulateOrders = falseDEFPARAM PreLoadBars = 0ONCE InitialLots = 2ONCE LotSize = InitialLotsONCE MaxPoint = 0ONCE MaxDD = 0ONCE Capital = 10000ONCE p = 20IF BarIndex > p THENEquity = Capital + StrategyProfitMaxPoint = max(MaxPoint,Equity)DD = MaxPoint - EquityDDPerCent = DD / MaxPoint * 100MaxDD = max(MaxDD,DD)MaxDDPerCent = MaxDD / MaxPoint * 100Avg = average[p,0](close)IF DDPerCent > 25 THENLotSize = InitialLots * 0.5 //halve lotsizeELSELotSize = InitialLots //restore initial lotsizeENDIFIF close CROSSES OVER Avg THENbuy LotSize CONTRACTS at MarketELSIF close CROSSES UNDER Avg THENSELLSHORT LotSize CONTRACTS AT MarketENDIFset target pprofit 100set stop ploss 150ENDIFgraph DDPerCentgraph LotSize coloured(255,0,0,255)08/01/2021 at 7:13 PM #17452708/01/2021 at 7:21 PM #174528ok … a new question.
How would it be if, depending on the% drawdown, I wanted to trade with fractions of position.
That is, if there is no drawdown I operate with € 10 pip …
If the drawdown does not exceed 10% I will operate at € 10 pip.
If the drawdown is between 10%, 30% will operate with € 5 pip.
If the drawdown exceeds 30% I will operate with € 2.5 pip.
08/01/2021 at 9:13 PM #174535You cannot change the value of pips traded, ad this depends on the chosen position instrument (eg.; Dax 25€, Dax 5€ or Dax 1€).
You can change your stop loss (usually not recommended) or lot size.
-
AuthorPosts
Find exclusive trading pro-tools on