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

As an Amazon Associate I earn from qualifying purchases.

Post Views: 13,213

5 Min Read

In the last post on creating an algotrader/trading bot with Python, I showed you how to specify your trading strategy for opening a trade. Now, let’s think about how we can close trades. There are many ways you can close trades – You could specify that after a certain amount of time, you should close the trade automatically. Alternatively, you could provide an exit condition and when met the trade will close. Or simply, define a stop loss & take profit and let the trade do its thing.

As a reminder, the basic flow of this algotrader/trading bot is as follows:

  1. Trader begins on a specific trading interval.
  2. Latest data is retrieved from the broker.
  3. Checks to see if any trades can be closed.
  4. Applies the strategy to the latest data and checks if a trade can be open.
  5. Repeat this process.

In this post, I will show you how to close a trade within a time limit and how to implement an exit condition.

Closing trades with an exit strategy

The next step on creating an algotrader/trading bot with Python is to define an exit strategy. Now that you know what trades are open, you can start defining when to close them. Our check_trades method currently looks like this:

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

Let’s add some new code below last_row = data.tail(1). Start by getting the open positions and assigning it to a variable called open_positions passing in the pair:

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) open_positions = positions_get(pair)

Time to define our exit condition! Similarly to the open condition: BUY when price > 50EMA and price < 10SMA I will simply invert this strategy for closing the position. So, my strategy for closing will be: SELL when price < 50EMA and price > 10SMA. Let’s add that to our code. Under the current for loop add the following code:

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

Now that you have your exit condition, it is time to close any trades that match this condition and the current symbol. You can use the method close_symbol_by_pair created earlier.

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

That’s all! Now you have created an exit strategy for your trades and are closing them accordingly. In the next section, I will show you how to close a trade within a specified time limit.

Closing trades within specified time limit

So, what if your exit strategy is to close a trade regardless of price in a specified time limit? Using the time from the open_positions data frame and the current time you can calculate this. Let’s say that you set a stop loss and take profit for your trade and if neither or these have been hit after 2 hours, you want to close the trade. Let’s take a look at how you can do this.

Your check_trades function should look like this:

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) open_positions = positions_get() for index, last in last_row.iterrows(): #Exit strategy if(last['close'] < last['EMA'] and last['close'] > last['SMA']): close_positon_by_symbol(pair) #Entry strategy if(last['close'] > last['EMA'] and last['close'] < last['SMA']): open_position(pair, "BUY", 1, 300, 100)

Start by getting the current local date time. As mentioned in part 1, every broker on the MT5 platform operates on their local timezone. So, to accurately calculate how much time has passed, you will need to convert your local current time to the brokers current time. In my case, my broker is in the Europe/Athens timezone. Again, you will be using pytz to convert to the brokers timezone. A full list of time zones for pytz.timezome can be found here. Add the calculated date time below the positions_get call:

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) open_positions = positions_get() current_dt = datetime.now().astimezone(pytz.timezone('Europe/Athens'))

Now, iterate over the open positions:

 open_positions = positions_get() current_dt = datetime.now().astimezone(pytz.timezone('Europe/Athens')) for index, position in open_positions.iterrows(): # Check to see if the trade has exceeded the time limit

From the open_positions data frame, extract time and ticket column while replacing the tzinfo for position['time']:

 open_positions = positions_get() current_dt = datetime.now().astimezone(pytz.timezone('Europe/Athens')) for index, position in open_positions.iterrows(): # Check to see if the trade has exceeded the time limit trade_open_dt = position['time'].replace(tzinfo = pytz.timezone('Europe/Athens')) deal_id = position['ticket']

As mentioned earlier, I want to close my trades after 2 hours. This can be achieved by subtracting the 2 dates and comparing them to a timedelta.

 open_positions = positions_get() current_dt = datetime.now().astimezone(pytz.timezone('Europe/Athens')) for index, position in open_positions.iterrows(): # Check to see if the trade has exceeded the time limit trade_open_dt = position['time'].replace(tzinfo = pytz.timezone('Europe/Athens')) deal_id = position['ticket'] if(current_dt - trade_open_dt >= timedelta(hours = 2)):

If you want to specify minutes or even seconds for timedelta, you can do this as follows:

# Examplestimedelta(days=10)timedelta(minutes=10)timedelta(seconds=10)

If this condition is met, then you will want to close only that specific trade. Use the close_position method passing in the deal_id created in this post.

 last_row = data.tail(1) open_positions = positions_get() current_dt = datetime.now().astimezone(pytz.timezone('Europe/Athens')) for index, position in open_positions.iterrows(): # Check to see if the trade has exceeded the time limit trade_open_dt = position['time'].replace(tzinfo = pytz.timezone('Europe/Athens')) deal_id = position['ticket'] if(current_dt - trade_open_dt >= timedelta(hours = 2)): close_position(deal_id)

Now you can close your trade with a take profit or stop loss, a specific exit condition or by a time limit!

Testing the code

The easiest way to test this new functionality is to open a trade manually and wait for the exit condition to be hit or wait for the trade to exceed the specified time period. Here is the output from my test:

>>> connect(39672374)Connected: Connecting to MT5 Client>>> open_position("EURUSD", "BUY", 1, 800, 400)EURUSD found!Order successfully placed!>>> live_trading()Running trader at 2021-01-22 08:45:00.581690Connected: Connecting to MT5 ClientRunning trader at 2021-01-22 09:00:00.477947Connected: Connecting to MT5 ClientOrder successfully closed!USDCAD is not visible, trying to switch onUSDCAD found!Order successfully placed!

As you can see, I manually opened a trade at 8:45 am. It then exceeded the time limit of (15 minutes) and closed. I also had a USDCAD trade open during this time!

Creating an algotrader/trading bot with Python – Part 3 (1)Creating an algotrader/trading bot with Python – Part 3 (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 this post! In my next post, I will be talking about risk management and capital preservation. 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 3 (2024)

FAQs

Is Python good for trading bot? ›

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.

How to create a trading bot using Python? ›

In this article, we'll explore the process of writing a trading bot in Python, along with some examples to help you get started.
  1. Step 1: Define Your Strategy. ...
  2. Step 2: Connect to a Broker. ...
  3. Step 3: Set Up Your Environment. ...
  4. Step 4: Write Your Trading Algorithm. ...
  5. Step 5: Implement Risk Management. ...
  6. Step 6: Deploy Your Trading Bot.
Feb 25, 2023

How to build an Algotrading bot? ›

Below is the overview of the process:
  1. 1 Selecting a programming language. ...
  2. 2 Choose your trading platform and the asset you want to trade. ...
  3. 3 Selecting the server to build your trading bot. ...
  4. 4 Define your strategy. ...
  5. 5 Integrate with the exchange API. ...
  6. 6 Backtesting your trading bot. ...
  7. 7 Optimizing your trading bot. ...
  8. 8 Forward testing.

How difficult is it to build a trading bot? ›

Some bots are very simple, while others are expensive and complex. The programmer feeds a set of criteria for trade execution into these algorithms, and the latter scan the market data until they find the proper combination of factors to execute a sale or purchase order.

Is Python enough for algo trading? ›

An Open-Source Programming Language

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.

Is Python fast enough for 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.

Do people make money with Algotrading? ›

Yes, algorithmic traders do make money, but most of them fail to do so. Trading is very hard, whether it is discretionary or algorithmic, and you need to put in a lot of hours to master the skills and stand a chance of making money.

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.

How hard is Algotrading? ›

Algo trading can be hard, but it is not impossible to learn. It requires a strong understanding of financial markets, programming skills, and risk management. Algo traders must also be able to quickly adapt to changing market conditions.

Why do trading bots fail? ›

Factors contributing to bot failures include technical glitches, programming errors, market conditions, over-optimization, lack of human oversight, and regulatory risks.

Can you make a living off trading bots? ›

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.

What is the best language for trading bot? ›

The first step in building a crypto trading bot is selecting the appropriate programming language. Python stands out as a preferred choice due to its simplicity and extensive library support, facilitating tasks such as data analysis and algorithm implementation.

Is Python good for making bots? ›

Python, a highly favored programming language due to its readability and efficiency, is an excellent tool for creating these bots. It offers simplicity and a robust set of libraries that make bot development more accessible, even for beginners in programming.

What language is best for trading bots? ›

Programming languages: There are many programming languages that developers build crypto trading bots with, including C, JavaScript, and Python. Python is particularly popular as there are many open-source scripts for crypto trading bots online already.

Can I use Python for stock trading? ›

We can analyze the stock market, figure out trends, develop trading strategies, and set up signals to automate stock trading – all using Python! The process of algorithmic trading using Python involves a few steps such as selecting the database, installing certain libraries, and historical data extraction.

Do trading firms use Python? ›

Just because you want to break into the algorithmic trading space doesn't mean you have to use C++. Jane Street uses Ocaml, crypto firms use either Python or Java. Python gets some disrespect from C++ purists in the space but definitely has its uses.

Top Articles
Ten Percent Rule To Build Wealth
Amber Heard finally paid Johnny Depp $1 million she owed after bitter defamation battle
WALB Locker Room Report Week 5 2024
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Satyaprem Ki Katha review: Kartik Aaryan, Kiara Advani shine in this pure love story on a sensitive subject
Team 1 Elite Club Invite
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Craigslist Vermillion South Dakota
Optimal Perks Rs3
Costco in Hawthorne (14501 Hindry Ave)
[PDF] INFORMATION BROCHURE - Free Download PDF
The Blind Showtimes Near Showcase Cinemas Springdale
Ladyva Is She Married
ATV Blue Book - Values & Used Prices
Insidekp.kp.org Hrconnect
Love In The Air Ep 9 Eng Sub Dailymotion
Minecraft Jar Google Drive
Michael Shaara Books In Order - Books In Order
Tamilrockers Movies 2023 Download
SF bay area cars & trucks "chevrolet 50" - craigslist
Nordstrom Rack Glendale Photos
Ubg98.Github.io Unblocked
Hyvee Workday
Jenna Ortega’s Height, Age, Net Worth & Biography
Nz Herald Obituary Notices
Kabob-House-Spokane Photos
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Relaxed Sneak Animations
Unreasonable Zen Riddle Crossword
3 Ways to Drive Employee Engagement with Recognition Programs | UKG
Kuttymovies. Com
Khatrimmaza
Puerto Rico Pictures and Facts
Myhrconnect Kp
Watchdocumentaries Gun Mayhem 2
Pickle Juiced 1234
How to Play the G Chord on Guitar: A Comprehensive Guide - Breakthrough Guitar | Online Guitar Lessons
Indiana Wesleyan Transcripts
Western Gold Gateway
How Much Is Mink V3
Reborn Rich Ep 12 Eng Sub
Scanning the Airwaves
Rochester Ny Missed Connections
301 Priest Dr, KILLEEN, TX 76541 - HAR.com
Alpha Labs Male Enhancement – Complete Reviews And Guide
Divinity: Original Sin II - How to Use the Conjurer Class
Mitchell Kronish Obituary
Satucket Lectionary
Portal Pacjenta LUX MED
Skyward Cahokia
Wvu Workday
Epower Raley's
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5668

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.