How to Create a Stop Order on MetaTrader 5 with Python
Learn how to create a BUY STOP or SELL STOP order on MetaTrader 5 using Python
Learn how to create a BUY STOP or SELL STOP order on MetaTrader 5 using Python
For many years, algorithmic trading (which could lead to automated trading bots) faced high barriers to entry.
MetaTrader 4 used a C++ programming language derivative. Compute power was scarce. Access to advanced analysis was challenging — especially when the desire was to integrate multi-source signals (i.e. sentiment analysis).
All these factors meant automated trading bots were the purview of advanced programmers or corporations.
MetaTrader 5 (MT5) started to change this with their MetaTrader5 Python Library. Suddenly, a powerful Python 3 library was available for use. Combined with the power and reach of one of the world’s largest retail trading platforms, it represented a step change in access.
What would it take for Crypto, AI, and Cyber to truly change the world?
No spam. Unsubscribe anytime.
In this series, I’ve been sharing some of the basic functions you need to leverage this powerful platform. So far we’ve covered:
In this article, I’ll show you how to place a STOP order. This will include a BUY-STOP and SELL_STOP order.
P.S. To learn how to build a full MetaTrader 5 Python Trading Bot, check out my series “How to build a MetaTrader 5 Python Trading Bot” and Python Trading Bot source code on GitHub.
I’ve assumed for this article that you’ve already connected to MT5 and initialized the symbol you’d like to trade. The variables you’ll need are:
Note. If the order is not successful, I’ve included a non-breaking error notification. This is to make your trading bot more resilient.
Here’s the code:
# Function to place a trade on MT5
def place_order(order_type, symbol, volume, price, stop_loss, take_profit, comment):
# If order type SELL_STOP
if order_type == "SELL_STOP":
order_type = MetaTrader5.ORDER_TYPE_SELL_STOP
elif order_type == "BUY_STOP":
order_type = MetaTrader5.ORDER_TYPE_BUY_STOP
# Create the request
request = {
"action": MetaTrader5.TRADE_ACTION_PENDING,
"symbol": symbol,
"volume": volume,
"type": order_type,
"price": round(price, 3),
"sl": round(stop_loss, 3),
"tp": round(take_profit, 3),
"type_filling": MetaTrader5.ORDER_FILLING_RETURN,
"type_time": MetaTrader5.ORDER_TIME_GTC,
"comment": comment
}
# Send the order to MT5
order_result = MetaTrader5.order_send(request)
# Notify based on return outcomes
if order_result[0] == 10009:
print(f"Order for {symbol} successful")
else:
print(f"Error placing order. ErrorCode {order_result[0]}, Error Details: {order_result}")
return order_result
Note how the price
, stop_loss
, and take_profit
have all been rounded to 3 decimal places. This prevents invalid price
errors due to decimal places.
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤