This code snippet is designed to automate exit strategies and adjust position sizes based on the performance of a trading strategy. It includes checks for win rate, drawdown, and capital reduction, and adjusts position sizes based on profit or loss percentages.
// Strategy Stopper and Money Management
// By Vonasi
// 20191011
barsbeforenextcheck = 22 // number of bars between performance checks
drawdownquitting = 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 happen
increase = 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 capital
startingsize = 1 // starting position size
minpossize = 0.2 // minimum position size allowed
gaintoinc = 5 // % profit rise needed before an increase in position size is made
losstodec = 5 // % loss needed before a decrease in position size is made
maxdrawdown = 25 // maximum % draw down allowed from highest ever equity before stopping strategy
maxcapitaldrop = 60 // maximum % starting capital lost before stopping strategy
once positionsize = startingsize
once psperc = positionsize / capital
if strategyprofit <> strategyprofit[1] then
highestprofit = max(strategyprofit, highestprofit)
if winratequit then
count = count + 1
if strategyprofit > strategyprofit[1] then
win = win + 1
endif
winrate = win/count
if count >= tradesbeforewrquit then
if winrate < winratequit/100 then
quit
endif
endif
endif
endif
if barindex mod barsbeforenextcheck = 0 then
if drawdownquitting then
if highestprofit <> 0 then
if (capital + strategyprofit) <= (capital + highestprofit) - ((capital + highestprofit)*(maxdrawdown/100)) then
quit
endif
endif
if highestprofit = 0 then
if (capital + strategyprofit) <= capital - (capital * (maxcapitaldrop/100)) then
quit
endif
endif
endif
equity = capital + strategyprofit
if increase then
if equity/lastequity >= (1+(gaintoinc/100)) then
positionsize = (max(minpossize,equity*psperc))
lastequity = equity
endif
endif
if decrease then
if equity/lastequity <= (1-(losstodec/100)) then
positionsize = (max(minpossize,equity*psperc))
lastequity = equity
endif
endif
endif
The code operates as follows:
This snippet is useful for implementing automated risk management and position sizing adjustments in trading strategies to help protect capital and potentially enhance returns.