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
35
indicator
133
strategy
171

Recent Snippets

How to Create a Simple MTF Trend Dashboard with EMA and SMA
indicator
This indicator builds a compact multi-timeframe (MTF) dashboard that shows whether price is trading above or below a [...]
How to Display Per-Bar Volume Accumulation in Real Time (Intrabar Updates)
global
This snippet tracks and displays the current bar’s accumulated volume while the bar is still forming, instead of only [...]
Ticks Counter: Count Tick Updates Per Bar on Tick or Time Charts
global
This snippet counts how many tick updates have occurred for the current bar by incrementing a per-bar counter on each [...]
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) [...]
Logo Logo
Loading...