Creating an algotrader/trading bot with Python – Part 2 (2024)

As an Amazon Associate I earn from qualifying purchases.

Post Views: 16,969

6 Min Read

Analyzing the Market Data

In my previous post, I showed you how to set up the trading interval and also how to pull the latest data for that interval. In this post, I will continue the process creating an algotrader/trading bot with Python. I will show you how analyze the data and open a trade (if it fits your trading plan). You will need to install another library called ta-lib. TA-Lib is widely used by trading software developers requiring to perform technical analysis of financial market data. An installation guide for this can be found here.

Once this is installed, lets start coding! Following on from the last post, you should have code similar to this:

import MetaTrader5 as mt5from datetime import datetime, timedeltaimport pandas as pdimport pytzimport scheduleimport timedef connect(account): account = int(account) mt5.initialize() authorized=mt5.login(account) if authorized: print("Connected: Connecting to MT5 Client") else: print("Failed to connect at account #{}, error code: {}" .format(account, mt5.last_error()))def open_position(pair, order_type, size, tp_distance=None, stop_distance=None): symbol_info = mt5.symbol_info(pair) if symbol_info is None: print(pair, "not found") return if not symbol_info.visible: print(pair, "is not visible, trying to switch on") if not mt5.symbol_select(pair, True): print("symbol_select({}}) failed, exit",pair) return print(pair, "found!") point = symbol_info.point if(order_type == "BUY"): order = mt5.ORDER_TYPE_BUY price = mt5.symbol_info_tick(pair).ask if(stop_distance): sl = price - (stop_distance * point) if(tp_distance): tp = price + (tp_distance * point) if(order_type == "SELL"): order = mt5.ORDER_TYPE_SELL price = mt5.symbol_info_tick(pair).bid if(stopDistance): sl = price + (stop_distance * point) if(tpDistance): tp = price - (tp_distance * point) request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": pair, "volume": float(size), "type": order, "price": price, "sl": sl, "tp": tp, "magic": 234000, "comment": "", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } result = mt5.order_send(request) if result.retcode != mt5.TRADE_RETCODE_DONE: print("Failed to send order :(") else: print ("Order successfully placed!")def positions_get(symbol=None): if(symbol is None): res = mt5.positions_get() else: res = mt5.positions_get(symbol=symbol) if(res is not None and res != ()): df = pd.DataFrame(list(res),columns=res[0]._asdict().keys()) df['time'] = pd.to_datetime(df['time'], unit='s') return df return pd.DataFrame()def close_position(deal_id): open_positions = positions_get() open_positions = open_positions[open_positions['ticket'] == deal_id] order_type = open_positions["type"][0] symbol = open_positions['symbol'][0] volume = open_positions['volume'][0] if(order_type == mt5.ORDER_TYPE_BUY): order_type = mt5.ORDER_TYPE_SELL price = mt5.symbol_info_tick(symbol).bid else: order_type = mt5.ORDER_TYPE_BUY price = mt5.symbol_info_tick(symbol).ask close_request={ "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": float(volume), "type": order_type, "position": deal_id, "price": price, "magic": 234000, "comment": "Close trade", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } result = mt5.order_send(close_request) if result.retcode != mt5.TRADE_RETCODE_DONE: print("Failed to close order :(") else: print ("Order successfully closed!")def close_positon_by_symbol(symbol): open_positions = positions_get(symbol) open_positions['ticket'].apply(lambda x: close_position(x)) def get_data(time_frame): pairs = ['EURUSD', 'USDCAD'] pair_data = dict() for pair in pairs: utc_from = datetime(2021, 1, 1, tzinfo=pytz.timezone('Europe/Athens')) date_to = datetime.now().astimezone(pytz.timezone('Europe/Athens')) date_to = datetime(date_to.year, date_to.month, date_to.day, hour=date_to.hour, minute=date_to.minute) rates = mt5.copy_rates_range(pair, time_frame, utc_from, date_to) rates_frame = pd.DataFrame(rates) rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') rates_frame.drop(rates_frame.tail(1).index, inplace = True) pair_data[pair] = rates_frame print(pair_data[pair]) return pair_data def run_trader(time_frame): connect(39672374) get_data(time_frame) def live_trading(): schedule.every().hour.at(":00").do(run_trader, mt5.TIMEFRAME_M15) schedule.every().hour.at(":15").do(run_trader, mt5.TIMEFRAME_M15) schedule.every().hour.at(":30").do(run_trader, mt5.TIMEFRAME_M15) schedule.every().hour.at(":45").do(run_trader, mt5.TIMEFRAME_M15) while True: schedule.run_pending() time.sleep(1)if __name__ == '__main__': live_trading()

If you are struggling with the current design, I highly recommend going back to this post to get an overview and visualization of what you are trying to build.

Let’s start by importing talib:

import MetaTrader5 as mt5from datetime import datetime, timedeltaimport pandas as pdimport timeimport pytzimport scheduleimport talib as ta

Next, you should create a new method and name it check_trades. For this method, make time_frame and pair_data arguments

def check_trades(time_frame, pair_data):

You will want to iterate over this dictionary as you will be calculating some new values!

def check_trades(time_frame, pair_data): for pair, data in pair_data.items():

The next part is to implement your strategy, for me, I will be creating a simple strategy as follows. (It goes without saying this is probably not a great strategy but useful for this tutorial):

BUY when price > 50EMA and price < 10SMA

Using Ta-lib can can calculate the 50EMA and 10SMA easily. For SMA you can use the ta.SMA(close,period) method and for EMA you can use ta.EMA(close,period) method. Provide every close price from the data you collected earlier – this can be done easily by referencing the close column in the data data frame. You will add the newly calculated SMA and EMA to new columns in the data frame:

def check_trades(time_frame, pair_data): for pair, data in pair_data.items(): data['SMA'] = ta.SMA(data['close'], 10) data['EMA'] = ta.EMA(data['close'], 50)

Here is a visualization of what the data frame looks like after adding SMA and EMA:

[1071 rows x 10 columns] time open high low close tick_volume spread real_volume SMA EMA0 2020-12-31 22:30:00 1.27277 1.27360 1.27262 1.27351 511 19 0 NaN NaN1 2020-12-31 22:45:00 1.27352 1.27370 1.27164 1.27220 1050 18 0 NaN NaN2 2020-12-31 23:00:00 1.27221 1.27221 1.27221 1.27221 1 24 0 NaN NaN3 2021-01-04 00:00:00 1.27198 1.27301 1.27196 1.27215 75 28 0 NaN NaN4 2021-01-04 00:15:00 1.27210 1.27336 1.27204 1.27324 127 12 0 NaN NaN... ... ... ... ... ... ... ... ... ... ...1066 2021-01-19 01:45:00 1.27491 1.27517 1.27489 1.27491 122 5 0 1.274976 1.2757821067 2021-01-19 02:00:00 1.27491 1.27491 1.27420 1.27427 406 0 0 1.274930 1.2757231068 2021-01-19 02:15:00 1.27427 1.27447 1.27406 1.27443 364 1 0 1.274849 1.2756721069 2021-01-19 02:30:00 1.27444 1.27444 1.27339 1.27371 503 0 0 1.274701 1.2755951070 2021-01-19 02:45:00 1.27370 1.27382 1.27353 1.27367 363 0 0 1.274572 1.275519

As you can see above – the SMA and EMA values are in the data frame. Don’t worry about the first few values being NaN – this is normal. If you are interested in how SMA is calculated, a good resource can be found here.

Reacting to the latest data

Now that we calculated everything we need for our strategy, it’s time to focus on the latest data. As mentioned before, generally speaking an algotrader/trading bot should react to new data. You will need to check the last reported tick data for this strategy. The only condition we have for opening a trade, is if the close price for the last record is above 50EMA and below 10SMA.

Start by getting the last row:

def check_trades(time_frame, pair_data): for pair, data in pair_data.items(): data['SMA'] = ta.SMA(data['close'], 10) data['EMA'] = ta.EMA(data['close'], 50) last_row = data.tail(1)

After this, you should specify the conditions of your strategy:

 for index, last in last_row.iterrows(): if(last['close'] > last['EMA'] and last['close'] < last['SMA']):

In the code snippet above, I am saying, if close > EMA and close < SMA then open a trade. The last step in this section is to open a trade if the conditions you have specified meet your trading strategy. You can use the open_position method created in a previous post.

 for index, last in last_row.iterrows(): if(last['close'] > last['EMA'] and last['close'] < last['SMA']): open_position(pair, "BUY", 1, 300, 100)

It’s time to add this method to the run_trader method. I have added a print statement which prints out the exact time the run_trader method runs. This is to help you determine if your trader is running at the correct time:

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


Testing the code

Now, it is time to test our code! When I ran the script, I got the output below. It is important to point out that no trades were opened by the trader because they did not meet my strategy.

>>> Running trader at 2021-01-19 09:00:00.619073Connected: Connecting to MT5 ClientRunning trader at 2021-01-19 09:15:00.707413Connected: Connecting to MT5 Client

Let’s take a moment and review what you created so far, first, you created a method called live_trading which is the entry point to your application. This contains information for the schedule of your trader. At every chosen interval, whether its 1 Min, 5 Min, 4 Hour’s etc you are getting the latest data with get_data. To analyze this data and act accordingly, you created a method called check_trades which will calculate any indicators needed for your strategy and also, if a trade should be opened or not based on your strategy.

Creating an algotrader/trading bot with Python – Part 2 (1)Creating an algotrader/trading bot with Python – Part 2 (2)

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 Friday to see the next part of this tutorial on creating an algotrader/trading bot with Python & MT5. 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.

Creating an algotrader/trading bot with Python – Part 2 (2024)

FAQs

Can you use Python to make a trading bot? ›

In this tutorial, you will learn how to create a cryptocurrency trading bot using Python. The bot will be able to connect to various exchanges, fetch trading data, and execute orders based on predefined strategies.

How to use Python for algo trading? ›

You can easily do this by making a function that takes in the ticker or symbol of the stock, a start date and an end date. The next function that you see, data() , then takes the ticker to get your data from the startdate to the enddate and returns it so that the get() function can continue.

Are AI trading bots illegal? ›

Legal Challenges and Ethical Considerations

While trading bots are legal, investment firms and traders are responsible for ensuring that they're used in a compliant manner.

Is Python good for making bots? ›

Python's extensive library support is what makes it an excellent choice for bot development. Depending on the kind of bot we're creating, different libraries will be required.

Do people make money with Algotrading? ›

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.

What is the best language for trading bots? ›

Python is a popular choice for developing trading bots, thanks to its simplicity and extensive libraries like Pandas, NumPy and SciPy. These libraries enable efficient data analysis, making Python a preferred language for data-driven trading strategies.

Has anyone made a successful trading bot? ›

It depends on the bot! Some lower-risk crypto trading bots boast a 99% success rate, while others execute higher-risk strategies and have a lower success rate. The main thing most investors need to consider is whether the bot they're looking at can execute their specific investment strategy successfully.

Is Python fast enough for algo trading? ›

Python, on the other hand, is an interpreted language, which can be slower compared to compiled languages like C++ and C#. However, with the help of libraries like NumPy and Pandas, Python can still achieve good performance for most algorithmic trading tasks.

Is Python better than R for algo trading? ›

While not as widely used as Python or Java in algorithmic trading, R offers unparalleled capabilities for quantitative analysis and modeling, making it suitable for developing sophisticated trading strategies.

Can Python be used for trading? ›

In addition to its technical capabilities, Python also offers several other benefits for algorithmic trading. For example, it is an open-source programming language, which means that it is free to use and can be modified to meet specific needs. This makes it accessible to traders of all skill levels and budgets.

What language is used for trading bots? ›

Python is particularly popular as there are many open-source scripts for crypto trading bots online already. API understanding and access: An API (Application Programming Interface) allows two computer programs to communicate with each other.

Is Java better than Python for trading bot? ›

The choice of programming language for your trading bot largely depends on your specific requirements, trading strategy, and personal preferences. Python is an excellent choice for beginners and those focusing on data analysis. On the other hand, Java and C++ excel in high-frequency trading environments.

Does Python algorithmic trading work? ›

Python has the most comprehensive and mature ecosystem of libraries for data science, which makes it a perfect programming language for algorithmic trading. Most strategies rely on technical indicators, time series models, or machine learning algorithms, and Python is the ideal language for implementing them.

Top Articles
Punkt für Punkt: Die sechs goldenen Regeln für den ETF-Kauf - Finanztip News
Financial Charts & Analysis Tools
Where To Go After Howling Pit Code Vein
Top 11 Best Bloxburg House Ideas in Roblox - NeuralGamer
Cintas Pay Bill
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Tyrunt
Comenity Credit Card Guide 2024: Things To Know And Alternatives
Sarpian Cat
Aktuelle Fahrzeuge von Autohaus Schlögl GmbH & Co. KG in Traunreut
R/Afkarena
978-0137606801
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Sivir Urf Runes
Fool’s Paradise movie review (2023) | Roger Ebert
Canvas Nthurston
Webcentral Cuny
Walmart stores in 6 states no longer provide single-use bags at checkout: Which states are next?
Nurse Logic 2.0 Testing And Remediation Advanced Test
FDA Approves Arcutis’ ZORYVE® (roflumilast) Topical Foam, 0.3% for the Treatment of Seborrheic Dermatitis in Individuals Aged 9 Years and Older - Arcutis Biotherapeutics
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Reptile Expo Fayetteville Nc
Dwc Qme Database
Sussyclassroom
Dcf Training Number
Soulstone Survivors Igg
Slim Thug’s Wealth and Wellness: A Journey Beyond Music
Amelia Chase Bank Murder
Arrest Gif
Panolian Batesville Ms Obituaries 2022
Jurassic World Exhibition Discount Code
Craigslist Cars And Trucks Mcallen
Melissa N. Comics
Rocksteady Steakhouse Menu
Truis Bank Near Me
Xemu Vs Cxbx
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
Arcadia Lesson Plan | Day 4: Crossword Puzzle | GradeSaver
Frcp 47
Anya Banerjee Feet
התחבר/י או הירשם/הירשמי כדי לראות.
Tgirls Philly
Gamestop Store Manager Pay
Unit 11 Homework 3 Area Of Composite Figures
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Theater X Orange Heights Florida
What Does the Death Card Mean in Tarot?
Raley Scrubs - Midtown
Supervisor-Managing Your Teams Risk – 3455 questions with correct answers
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6009

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.