Stop blowing up your account with algo trading

As an Amazon Associate I earn from qualifying purchases.

3 Min Read

In my last post of this series, I showed you how to report daily statistics for your algorithmic trading bot. Today, let’s see how you can stop your strategy and trading automatically when you have reached your maximum drawdown and stop blowing up your account with algo trading!

What is a maximum drawdown?

Maximum drawdown is the amount of percentage or dollar value you are willing to lose on an account before you it stop trading. E.g. if I have an account with an initial balance of $1000 and a maximums drawdown of 50% – If my account reaches $500 the account will stop trading. This technique stops you from blowing your entire account. More information on maximum drawdown can be found here.

Add the maximum drawdown and account balance to your strategy

Open the strategy.json file and at the end of the file add a variable named maximumDrawdown and assign a value of 0.5. After this, create another variable named initialBalance and add your initial balance:

{
  "account_currency" : "USD",
	"strategy_name": "myStrategy",
	"pairs": [
		"EURUSD",
		"USDCAD",
		"GBPUSD"
    ],
    "risk" : 2,
    "maxLosses" : 3,
    "takeProfit": 700.0,
    "stopLoss": 300.0,
	"movingAverages": {
        "SMA": {
            "val": 10,
            "aboveBelow": "below"
        },
        "EMA": {
            "val": 50,
            "aboveBelow": "above"
        }
    },
    "maximumDrawdown" : 0.5,
    "initialBalance" : 100000
}

Checking maximum drawdown

Now that you have added the maximumDrawdown and initalBalance to your strategy, you will need to implement a monitor to check the current balance on the account. Create a new method named check_max_drawdown with the argument strategy.

Get the initial balance from your strategy and assign it to variable named initial_balance:

def check_max_drawdown(strategy):
    inital_balance = strategy['initalBalance']

Similarly, get the maximum drawdown from your strategy and assign it to a variable named max_drawdown:

def check_max_drawdown(strategy):
    inital_balance = strategy['initalBalance']
    max_drawdown = strategy['maximumDrawdown']

Now, you will need to get the current balance of the account. Do this by calling get_account_info (more detail about this method can be found here) and extract the balance from the dictionary, returned from this method:

def check_max_drawdown(strategy):
    print("Checking maximum drawdown...")
    inital_balance = strategy['initalBalance']
    max_drawdown = strategy['maximumDrawdown']
    account_info = get_account_info()
    current_balance = account_info['balance']

At this point, we have everything we need to calculate if the maximum drawdown has been breached. The formula for the maximum drawdown is as follows:

initial_balance * max_drawdown

If your current balance is less than initial_balance * max_drawdown, then the maximum drawdown has been breached, all trading should stop and all current positions should be closed. Start by creating this condition:

    if(current_balance < (inital_balance * max_drawdown)):

Inside the condition, it is a good idea to send a notification via slack that the maximum drawdown has been reached:

    if(current_balance < (inital_balance * max_drawdown)):
        print("Maximum drawdown has been reached! Trading halted.")
        send_notification("Maximum drawdown has been reached! Trading halted.")

The last thing to do is close all of your open trades. Get your current open positions using the method positions_get and assign this to a variable named open_positions.

    if(current_balance < (inital_balance * max_drawdown)):
        print("Maximum drawdown has been reached! Trading halted.")
        send_notification("Maximum drawdown has been reached! Trading halted.")

        open_positions = positions_get()

Now iterate over the open_positions data frame, extracting the ticket (deal_id) and passing this into the close_position method:

    if(current_balance < (inital_balance * max_drawdown)):
        print("Maximum drawdown has been reached! Trading halted.")
        send_notification("Maximum drawdown has been reached! Trading halted.")

        open_positions = positions_get()
        for index, position in open_positions.iterrows():
            deal_id = position['ticket']
            close_position(deal_id):
        exit()     

Checking the maximum drawdown on a schedule

The last step in this tutorial is to make sure your newly created check_max_drawdown method gets called periodically. You can do this by adding this to the schedule in the live_trading method.

How often you want to check for your maximum drawdown depends on your preference. The more frequent the better. I have decided to check my maximum drawdown every 15 minutes:

schedule.every(15).do(check_max_drawdown)

Your live_trading method should now look like this:

def live_trading(strategy):
    schedule.every().hour.at(":00").do(run_trader, mt5.TIMEFRAME_M15, strategy)
    schedule.every().hour.at(":15").do(run_trader, mt5.TIMEFRAME_M15, strategy)
    schedule.every().hour.at(":30").do(run_trader, mt5.TIMEFRAME_M15, strategy)
    schedule.every().hour.at(":45").do(run_trader, mt5.TIMEFRAME_M15, strategy)
    schedule.every(4).hours.at(":00").do(send_stats)
    schedule.every().day.at("19:00").do(send_daily_stats)
    schedule.every(15).minutes.do(check_max_drawdown)

Whether you’re starting to dabble into the world of trading or you are a seasoned trader, Mark Douglas’ Trading in the Zone is an absolute must read. This book focuses more on the psychology of trading which is underestimated by most traders today. A great book if you are trying to improve your trading mindset, become consistent and removing your emotion from trading. Trading in the Zone @ Amazon.

That’s all for Stop blowing up your account with algo trading ! Check back on Monday to see how you can trade a strategy on multiple accounts at the same time! As always, if you have any questions or comments please feel free to post them below. Additionally, if you run into any issues please let me know.

1 thought on “Stop blowing up your account with algo trading”

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to my newsletter to keep up to date with my latest posts

Holler Box