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

As an Amazon Associate I earn from qualifying purchases.

Post Views: 17,109

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 to calculate a lot size? ›

Lot Size = (Risk Amount / (Stop Loss in pips * Pip Value)). Here, the risk amount is the capital at risk, the stop loss in pips is the predetermined exit level if the trade goes against the trader, and the pip value is the value of each pip movement in the trading account's base currency.

What is a dynamic position size? ›

Dynamic position sizing means that you adjust the size of your trades according to the changing market conditions, such as price, volatility, trend, or indicators. This allows you to take advantage of favorable opportunities and reduce your exposure when the risk is high.

Is algo trading legal? ›

Is it legal for retail investors to perform algo-trading in India? Yes, algo-trading is completely legal in India, and it does not matter whether you are a retail investor or an institution.

How profitable is algorithmic trading? ›

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.

How many lots can I trade with $1000? ›

With 1:100 leverage, your need to choose ($500 * 0.02) / 100,000 * 100 = 0.01 lots. With $1000 on your account, you will be able to trade ($1000 * 0.02) 100,000 * 100 = 0.02 lots.

How do you get dynamic positioning? ›

To become a DP operator you need training certificates and practical training. In total, you will spend 120 days operating a DP vessel. Depending on your working position, further certificates such as BOSIET (Basic Offshore Safety Induction and Emergency Training) might be required.

How does dynamic positioning work? ›

The DP System maintains a vessel's desired position and/or heading by use of the DP control computer which automates the control of vital power and propulsion systems in order to control 3 of 6 axes of a vessel's movement: • surge (aft and forward), • sway (side to side), and • yaw (heading).

How do you calculate position size fast? ›

The Position Size Trading Formula

Here's how to calculate position size in trading by using a simple formula: The number of units that you buy is equal to the equity that you have in your account multiplied by the risk per trade that you want to take, divided by the risk per unit.

Has anyone made money from algorithmic trading? ›

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.

Why does algo trading fail? ›

There are many reasons why Algo trading fails like the algorithm strategy is not being tested properly before the implementation. Or accurate data is not used to develop the stock trading algorithm software that fails to give profits to traders, let's find out more.

What is the difference between algo trading and bot trading? ›

Algorithms set stop-loss parameters that are optimal for the chosen strategy. This avoids exceeding financial limits and ensures effective risk management. In addition, automated bots allow traders to test and optimize their strategies on historical data.

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.

What is the best algorithmic trading software? ›

Here's my list of the best brokers for algo trading:
  • IC Markets - Best overall choice for algorithmic trading.
  • FXCM - Excellent resources for algo-driven API trading.
  • Interactive Brokers - Algo orders and API for algo trading across markets.
  • Pepperstone - Multiple platforms for algorithmic trading.
Mar 30, 2024

Which strategy is best for algo trading? ›

  1. Trend Following. Trend following, often serving as a navigational tool for many algorithmic traders, stands as a strategy as enduring as the market itself. ...
  2. Volatility. ...
  3. Quote stuffing. ...
  4. Trading Range. ...
  5. Inter-market spreading. ...
  6. Black swan events. ...
  7. Index Fund Rebalancing. ...
  8. Mean Reversion.
Feb 24, 2024

What is lot size with example? ›

A simple example of lot size is: when we buy a pack of six chocolates, it refers to buying a single lot of chocolate. Description: In the stock market, lot size refers to the number of shares you buy in one transaction.

How do I calculate lot size to acres? ›

Acreage is the area of a land in acres. To calculate the acreage, the length and width of the land, which is usually given in feet, is multiplied to get the area in square feet. Then, this area in square feet is converted to acres by using the conversion factor of 43560.

What does 0.01 lot size mean? ›

A 0.01 lot size is known as a micro lot. This lot size accounts for 1,000 base currency units in every forex trade, determining the amount of a particular currency.

Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 5548

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.