Implementing Automated Trading Exit Strategies and Dynamic Position Sizing

15 Nov 2020
0 comment
0 attachment

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:

  • Performance Checks: The strategy evaluates performance every specified number of bars (barsbeforenextcheck).
  • Win Rate Check: If the win rate falls below a specified threshold after a minimum number of trades, the strategy stops.
  • Drawdown Check: The strategy stops if the drawdown exceeds a specified percentage from the highest profit recorded.
  • Capital Reduction Check: The strategy also stops if the capital reduction exceeds a specified percentage.
  • Dynamic Position Sizing: Position size is adjusted based on the percentage increase or decrease in equity. If the equity increases by a certain percentage, the position size is increased, and if it decreases by a certain percentage, the position size is decreased.

This snippet is useful for implementing automated risk management and position sizing adjustments in trading strategies to help protect capital and potentially enhance returns.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/when-to-stop-a-strategy-and-money-management-code-snippet/#post-109954

Visit Link
What is a Snippet? A snippet is a small, reusable chunk of code designed to solve specific tasks quickly. Think of it as a shortcut that helps you achieve your coding goals without reinventing the wheel. How to Use: Simply copy the snippet and paste it into your project where needed. Don't forget to tweak it to fit your context. Snippets are not just time-savers; they're also learning tools to help you become a more efficient coder.
Vonasi Master
V-oyaging ON A S-mall I-ncome
Author’s Profile

Comments

Search Snippets

Showing some results...
Sorry, no result found!

Snippets Categories

global
33
indicator
132
strategy
171

Recent Snippets

How to Build a Step-Based Trailing Stop That Moves to Break-Even First
strategy
This snippet implements a step trailing stop that advances in fixed increments once price reaches predefined profit [...]
Utilizing Arrays to Track and Compare Indicator Values Within the Same Bar in ProBuilder
indicator
This ProBuilder code snippet demonstrates how to use arrays to compare the values of an indicator (RSI in this case) [...]
Calculating Break-Even Points in ProBuilder
strategy
This ProBuilder code snippet demonstrates how to calculate the break-even point for a trading position. The break-even [...]
Implementing Time and Day Restrictions in Trading Algorithms
strategy
This code snippet demonstrates how to set restrictions on trading activities based on specific days of the week and [...]
Implementing Partial Position Closure Based on Price Retracement in ProBuilder
strategy
This code snippet demonstrates how to partially close a trading position when the price retraces to a certain level in [...]
Logo Logo
Loading...