Dynamically calculate lot size for your algorithmic trading bot (2024)

As an Amazon Associate I earn from qualifying purchases.

Post Views: 17,180

4 Min Read

In the last post, we looked at how you can dynamically load strategies into your trader. Today, I will show you how to dynamically calculate the lot size your algorithmic trading bot. The position size of a trade will depend on a percentage of risk, you are willing to take on your account balance. E.g. if your risk percentage is 1% and you have a $5000 account then the maximum amount of money you can lose in one trade is $50.

Contents hide

1Calculate the value of one pip

3Adding new properties to the strategy json file

4Testing the code

Calculate the value of one pip

To start, you will need to install a new library called forex-python. You can install this using the command below or by going here. Forex Python is a Free Foreign exchange rates and currency conversion which we will be using to calculate the value of a pip.

pip install forex-python

After this has been installed, go to your constants.py file and import this new library as follows:

import talib as tafrom forex_python.converter import CurrencyRates

Next, let’s add a method to our constants.py file to calculate the pip value. We need to calculate the size of one pip for a given instrument. You can call this new method get_pip_value and it should take arguments of symbol and account_currency:

def get_pip_value(symbol, account_currency):

Now we need to split up our symbol into 2 currencies. I.e if we passed “EURUSD” as a symbol then we need to split it up as “EUR” and “USD”:

def get_pip_value(symbol, account_currency):symbol_1 = symbol[0:3]symbol_2 = symbol[3:6]

Finally, using the CurrencyRates module lets calculate the value of one pip and convert it to our local currency. More information on how the convert method works can be found here:

def get_pip_value(symbol, account_currency):symbol_1 = symbol[0:3]symbol_2 = symbol[3:6]c = CurrencyRates()return c.convert(symbol_2, account_currency, c.convert(symbol_1, symbol_2, 1))

Dynamically calculate the lot size for your algorithmic trading bot

Let’s have a look at your trader.py file again. You will be adding a new method called calc_position_size which takes the following arguments: symbol, strategy.

def calc_position_size(symbol, strategy):

To calculate a percentage of your balance you are willing to risk you need to actually know the current balance of your account. Retrieve this by using the acount_info method from the MT5 API. More information on this can be found here. Call this method and assign it to a variable named account. Also, add a print statement to say that you are calculating the position size for a given symbol.

def calc_position_size(symbol, strategy): print("Calculating position size for: ", symbol) account = mt5.account_info()

With this done, create a new variable named balance and get the balance from account:

 balance = float(account.balance)

Now, we need to calculate the pip value of the symbol. This is done by calling the method created earlier in constants.py. Remember, you will need to pass in the symbol and account currency for this method. Assign this to a new variable called pip_value:

 pip_value = constants.getPipValue(symbol, strategy['account_currency'])

Don’t worry about referencing account_currency in your strategy. You will be adding this entry to your strategy json file later. You will now need to calculate the lot size based of your account balance. To calculate the lot size use the following equation:

Lot size = (balance * risk) / pip value * stop loss

Your python code should look like the following:

lot_size = (float(balance) * (float(strategy["risk"])/100)) / (pip_value * strategy["stopLoss"])

Finally, round the value to 2 decimal places (as MT5 only accepts lot sizes rounded to 2 decimal places) and return:

 lot_size = round(lot_size, 2) return lot_size

Let’s go back to the check_trades methods created earlier. In that method, find where you are opening a position (open_position…) and above this method call add the following line:

 lot_size = calc_position_size(pair, strategy)

In your open_position call, replace the current lot size with the one from the variable created above:

 open_position(pair, "BUY", lot_size, float (strategy['takeProfit']), float(strategy['stopLoss']))

Adding new properties to the strategy json file

You will remember that we references 2 new properties from the strategy in this post called account_currency and risk. These properties do not exist in our strategy yet. Let’s fix that!

Go to your strategy.json file and add the account_currency property to the top of the file. In my case, I will add USD as my account currency:

{ "account_currency" : "USD", "strategy_name": "myStrategy",

After strategy_name define your risk as a percentage value. E.g. 2 = 2%:

{ "account_currency" : "USD","strategy_name": "myStrategy","pairs": ["EURUSD","USDCAD","GBPUSD" ], "risk" : 2,

Testing the code

Now let’s test our code. For this test I will simply run the trader and wait for a trade to open. The lot size should be dynamically calculated based on my account balance and risk.

C:\Users\conor\Documents\blog files>python trader.py strategyTrading bot started with strategy: strategyConnected: Connecting to MT5 ClientRunning trader at 2021-01-29 08:30:00.939338Connected: Connecting to MT5 ClientRunning trader at 2021-01-29 08:45:00.242999Connected: Connecting to MT5 ClientRunning trader at 2021-01-29 09:00:00.561294Connected: Connecting to MT5 ClientRunning trader at 2021-01-29 09:15:00.412300Connected: Connecting to MT5 ClientRunning trader at 2021-01-29 09:30:00.343254Connected: Connecting to MT5 ClientRunning trader at 2021-01-29 09:45:00.835452Connected: Connecting to MT5 ClientCalculating position size for: EURUSDOrder successfully placed!
Dynamically calculate lot size for your algorithmic trading bot (1)

As you can see above, the trader ran and opened a position on EURUSD with a calculated lot size of 5.53.

Dynamically calculate lot size for your algorithmic trading bot (2)Dynamically calculate lot size for your algorithmic trading bot (3)

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 Monday to see how you can send trading alerts to your phone via slack! 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.

Dynamically calculate lot size for your algorithmic trading bot (2024)

FAQs

How profitable can algorithmic trading be? ›

Is algo trading profitable? The answer is both yes and no. If you use the system correctly, implement the right backtesting, validation, and risk management methods, it can be profitable. However, many people don't get this entirely right and end up losing money, leading some investors to claim that it does not work.

What is the size of algorithmic trading? ›

The global algorithmic trading market size is projected to grow from USD 2.19 billion in 2023 to USD 3.56 billion by 2030, exhibiting a CAGR of 7.2% during the forecast period. North America dominated the global market with a share of 43.34% in 2022.

How can I be a good algorithmic trader? ›

Steps to Start Algo-Trading

For a start, you need to know your trade. You must be aware of where you are investing your money. A good amount of market and financial instrument research is required. If you know how to code or have an understanding of coding languages then you can explore more about algorithmic trading.

How successful are trading algorithms? ›

Yes, it is possible to make money with algorithmic trading. Algorithmic trading can provide a more systematic and disciplined approach to trading, which can help traders to identify and execute trades more efficiently than a human trader could.

Can you really make money with automated trading? ›

Conclusion. Trading bots have the potential to generate profits for traders by automating the trading process and capitalizing on market opportunities. However, their effectiveness depends on various factors, including market conditions, strategy effectiveness, risk management, and technology infrastructure.

Is algorithmic trading illegal? ›

Yes, algo trading is legal. No rules are in place by any federal or financial regulatory body that prevent an individual from algo trading.

What is optimal trading size? ›

The formula is: K = W - (1 - W) / R where K is the optimal trade size as a percentage of your capital, W is your win rate as a decimal, and R is your reward-to-risk ratio.

How much capital is required for algo trading? ›

The minimum capital required for algo trading varies from platform to platform. However, most platforms require a minimum capital of Rs. 10,000 to Rs. 20,000 to get started.

Who is the most successful algo trader? ›

He built mathematical models to beat the market. He is none other than Jim Simons. Even back in the 1980's when computers were not much popular, he was able to develop his own algorithms that can make tremendous returns. From 1988 to till date, not even a single year Renaissance Tech generated negative returns.

How much does it cost to start algorithmic trading? ›

An algorithmic trading app usually costs about $125,000 to build. However, the total cost can be as low as $100,000 or as high as $150,000.

Can you do algorithmic trading yourself? ›

A: To get started with algorithmic trading, you will need a computer, specialized software, historical and real-time market data, and a brokerage account with a broker that offers algorithmic trading services.

Do banks use algorithmic trading? ›

2.1. 2 Algorithmic Trading: Banks employ algorithmic trading strategies using bots to execute large orders across multiple markets, minimizing market impact and optimizing execution prices.

Is algorithmic trading risky? ›

One of the main risks of algorithmic trading is that it relies on complex and sophisticated technology that can malfunction, crash, or be hacked. Technical glitches can cause delays, errors, or losses in your orders, or even trigger unwanted trades that can affect your performance and the market.

How hard is algorithmic trading? ›

(But that would involve paying interest, so it's a bit more complicated) So, algo trading is at the same time difficult and easy, it is difficult because you have to learn programming, mathematics, and finance, but it is easy because it is about going into a position and then getting out of a position.

Is algorithmic trading profitable long term? ›

Yes! Algorithmic trading is profitable, provided that you get a couple of things right. These things include proper backtesting and validation methods, as well as correct risk management techniques. Unfortunately, many never get this completely right, and therefore end up losing money.

How hard is it to build a trading algorithm? ›

To create algo-trading strategies, you need to have programming skills that help you control the technical aspects of the strategy. So, being a programmer or having experience in languages such as C++, Python, Java, and R will assist you in managing data and backtest engines on your own.

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6330

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.