2 min read

How to Cancel an Order on MetaTrader 5 with Python

Learn how to cancel an open order on MetaTrader 5 with Python.
Cool little clockwork robot, using Sepia colors. Holds a red trading arrow.
Python Trading Bot

Python Trading Bot

The combination of Python and MetaTrader 5 can be incredibly powerful for your trading bot.

Bringing together the world’s most popular programming language and one of the world’s largest retail trading platforms is a game changer. In fact, TradeOxy is built on leveraging these factors to help traders!

If you’re looking to integrate MetaTrader5 (MT5) and Python together into a trading bot, you’ll need a few functions:

  1. Connecting to MetaTrader5
  2. Initializing a Symbol on MetaTrader 5
  3. Creating Trades

In this article, I’ll show you how to cancel an open order (i.e. before it executes and becomes a position)


How to Cancel an Order

I’ll assume you’ve connected to MT5.

To cancel an order on MT5, all you need is an order number. Check out my article “How to Get a List of Open Orders on MetaTrader 5 with Python” if you want to find out how to retrieve a list of order numbers.

With your order number in hand, here’s the code:

# Function to cancel an order
def cancel_order(order_number):
    # Create the request
    request = {
        "action": MetaTrader5.TRADE_ACTION_REMOVE,
        "order": order_number,
        "comment": "Order Removed"
    }
    # Send order to MT5
    order_result = MetaTrader5.order_send(request)
    return order_result

Say Hi!

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.