Trade multiple strategies with your algorithmic trading bot

As an Amazon Associate I earn from qualifying purchases.

3 Min Read

In my last post, I showed you how to stop blowing up your account by using a maximum draw-down. Today, let’s have a look at how you can trade multiple strategies with your algorithmic trading bot. In trading, one strategy will not be suitable for all market conditions and it is advised to have multiple strategies. Let’s see how we can implement this into our trader.

Loading in more than one strategy

You will be passing your strategies via the command line (just like before). Although this time you will be passing two strategies. To handle this we need to modify the part of the code that reads in the strategy. Currently, it looks like this:

if __name__ == '__main__':
    current_strategy = sys.argv[1]
    print("Trading bot started with strategy:", current_strategy)
    current_strategy = strategy.load_strategy(current_strategy)
    live_trading(current_strategy)

We are only accepting one strategy here. Change this by iterating over the length of sys.argv, assigning the current_strategy from the arg and calling live_trading inside the new loop:

if __name__ == '__main__':
    for arg in sys.argv[1:]:
        current_strategy = arg
        print("Trading bot started with strategy:", current_strategy)
        current_strategy = strategy.load_strategy(current_strategy)
        live_trading(current_strategy)

You will want these strategies to execute in parallel. To do this, change the call to the live_trading method by making it multi-threaded using the threading module (this will be imported later in the tutorial):

if __name__ == '__main__':
    for arg in sys.argv[1:]:
        current_strategy = arg
        print("Trading bot started with strategy:", current_strategy)
        current_strategy = strategy.load_strategy(current_strategy)
        trading = threading.Thread(target=live_trading, args=(current_strategy,))
        trading.start()

Now you can load in multiple strategies that can trade with different criteria.

Trading more than one strategy with different accounts

Adding account number to strategy.json

Let’s say that you don’t want to trade multiple strategies on one account and instead, you want to have one strategy per account. So how can you do this? First of all, specify your accountNumber in the strategy.json file (if you don’t know how to find your account number please see this post):

{
    "accountNumber" : 123456789,
    "account_currency" : "USD",
	  "strategy_name": "myStrategy",
    ...

As you can see above, I have added my account number to the strategy.json file. Let’s go back to trader.py now.

Replacing the hardcoded account number

In Creating an algotrader/trading bot with Python – Part 1 you created a method named run_trader and inside that method you are calling connect with a hardcoded value. Go ahead and change this so that the account number is coming from your strategy:

Old code:

def run_trader(time_frame, strategy):
    print("Running trader at", datetime.now())
    connect(40461345)
    pair_data = get_data(time_frame, strategy)
    check_trades(time_frame, pair_data, strategy)

New code:

def run_trader(time_frame, strategy):
    print("Running trader at", datetime.now())
    connect(strategy['accountNumber'])
    pair_data = get_data(time_frame, strategy)
    check_trades(time_frame, pair_data, strategy)

Every time our trader runs, it will get the account number for the current strategy. If we pass multiple strategies such as strategy1, strategy2, etc, it will look for the account number of each strategy and only open trades on the specified account.

Adding the locking mechanism

The final step is to introduce a locking mechanism so that our trader can only access one account at a time. Failure to implement this locking feature may cause unexpected results.

At the top of the trader.py file you will need to import threading:

import MetaTrader5 as mt5
import threading
from datetime import datetime, timedelta
....

Just below the imports, create a new variable and name it lock, assigning threading.Lock() to it:

lock = threading.Lock()

Once this is done, find the connect method and at the beginning of the method add the line lock.acquire():

def connect(account):
    lock.acquire()
    account = int(account)
    mt5.initialize()
    ...

Next, let’s add a disconnect method with no arguments. In this method we will disconnect from MT5 and release the lock:

def disconnect():
	mt5.shutdown()
	lock.release()
	print("Disconnecting from MT5 Client")

Go back to the run_trader method and at the end of the method, call disconnect:

def run_trader(time_frame, strategy):
    print("Running trader at", datetime.now())
    connect(strategy['accountNumber'])
    pair_data = get_data(time_frame, strategy)
    check_trades(time_frame, pair_data, strategy)
    disconnect()

And that’s it! Now your trader is able to run multiple strategies over multiple accounts. This also works well if you want to trade the same strategy on multiple accounts (i.e. a trade copier).

Testing the code

To test this code, I will create a copy of my strategy file strategy.json and rename it to strategy_2.json, changing the account number to reference another account. I will wait for the trader to find a trade.

Trading bot started with strategy: strategy
Trading bot started with strategy: strategy_2
Running trader at 2021-02-14 17:32:56.092436
Connected: Connecting to MT5 Client
Running trader at 2021-02-14 17:32:59.694943
Calculating position size for:  EURUSD
EURUSD found!
Connected: Connecting to MT5 Client
Calculating position size for:  EURUSD
EURUSD found!

As you can see, both of my strategies are running and since they are identical, they opened the exact same trade but on different accounts!

That’s all for Trading multiple strategies with your algorithmic trading bot! Check back on Wednesday to see how you can convert tick data to a candlestick graph! 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.

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