Creating a strategy for your algorithmic trading bot – Part 1

As an Amazon Associate I earn from qualifying purchases.

4 Min Read

Today you will be creating a strategy for your algorithmic trading bot. By now, you should have a trader that can connect to a broker via MetaTrader 5, open/close trades and apply entry and exit strategies. If you don’t, I recommend you check out the beginning of this series before continuing. You might remember from my previous post that the strategy I provided was very simple and probably not the best strategy.

Today I am going to show you how to create dynamic strategies for your trading bot. This section is broken up into numerous parts as it is quite complex. Let’s get started!

Loading the strategy from a json file

Since the strategies that we will be making are in json, you will need to import the json library. But before this, let’s create a new file called strategy.py. You will also want to create a strategies folder (this is where you will be storing your strategies). In the strategy.py file you will import json and os.

import json
import os

Define the strategies directory path as a variable – name the variable strategy_dir. You will now want to create a method called load_strategy. This method will have a parameter called strategy_name.

def load_strategy(strategy_name):

Now, you need to write code to load in the strategy json file. To do this, we will open the file with with open(.. and you will use the json_load method from the json library to store the json as a dictionary.

def load_strategy(strategy_name):
    with open(strategy_dir + strategy_name + '.json') as json_file:
        data = json.load(json_file)
        return data

Writing a simple strategy in the json file

Let’s take a break from coding and think about the things we will need in our strategy. When creating a strategy for your algorithmic trading bot, you want the strategies to be dynamic and easily changed. Start by creating a json file in the strategies folder and name it myStrategy.json. If you are unfamiliar with json, I recommend you read this article. Start by creating the opening and closing brackets for the json:

{
}

Add your strategy name:

{
	"strategy_name": "myStrategy",
}

In our strategy, we can define all the pairs that interest us. I have added EURUSD, USDCAD and GBPUSD as an example:

{
	"strategy_name": "myStrategy",
	"pairs": [
		"EURUSD",
		"USDCAD",
		"GBPUSD"
	],
}

You can also add a stop loss and take profit to your strategy:

{
	"strategy_name": "myStrategy",
	"pairs": [
		"EURUSD",
		"USDCAD",
		"GBPUSD"
	],
    "takeProfit": 700.0,
    "stopLoss": 300.0,
}

You will remember from my previous post that I used EMA and SMA to define my entry and exit conditions. Let’s add this to your strategy. You will first create a moving_averages key then add SMA with keys val and aboveBelow and do the same for EMA. This is saying, you want to calculate SMA 10 and the close price should be below this value. Similarly for EMA, you want to calculate EMA 50 and the close price should be above this value.

    "movingAverages": {
        "SMA": {
            "val": 10,
            "aboveBelow": "below"
        },
        "EMA": {
            "val": 50,
            "aboveBelow": "above"
        }
    }
}

You can use this json validator to check that your json file is valid. After this has been done, let’s get back to coding!

Creating the constants file

Go ahead and create another python file and name it constants.py. This is where you will be storing references to your ta-lib functions. Just for now import ta-lib as ta. If you need to install ta-lib check out this post:

import talib as ta

Now, let’s define some lambda expressions for moving averages functions in ta-lib. This is best stored in a dictionary. You will need to pass in the close and time period for each function:

movingAveragesFunctions = {
	'SMA' : lambda close, timeP: ta.SMA(close, timeP),
	'EMA' : lambda close, timeP: ta.EMA(close, timeP),
	'WMA' : lambda close, timeP: ta.WMA(close, timeP),
	'linearReg' : lambda close, timeP: ta.LINEARREG(close, timeP),
	'TRIMA' : lambda close, timeP: ta.TRIMA(close, timeP),
	'DEMA' : lambda close, timeP: ta.DEMA(close, timeP),
	'HT_TRENDLINE' : lambda close, timeP: ta.HT_TRENDLINE(close, timeP),
	'TSF' : lambda close, timeP: ta.TSF(close, timeP)
}

Testing the code

Let’s run strategy.py and test the code. Call the load_strategy method with the argument ‘strategy'. You should see your strategy created in json in the form of a dictionary if successful.

>>> load_strategy('strategy')
{'strategy_name': 'myStrategy', 'pairs': ['EURUSD', 'USDCAD', 'GBPUSD'], 
'takeProfit': 700.0, 'stopLoss': 300.0, 'movingAverages': {'SMA': {'val': 10, 'aboveBelow': 'below'},
 'EMA': {'val': 50, 'aboveBelow': 'above'}}}

If you are interested in learning more about algo trading and trading systems, I highly recommend reading this book. I have taken some of my own trading ideas and strategies from this book. It also provided me a great insight into effective back testing. Check it out here.

That’s all for now! Check back on Wednesday to see how you can integrate this code into your trading bot. 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.

2 thoughts on “Creating a strategy for your algorithmic trading bot – Part 1”

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