2 min read

How to Modify an Open Position on MetaTrader 5 with Python

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

Python Trading Bot

When MetaTrader 5 introduced the MetaTrader5 Python Library, it was a game-changer. Finally, the world’s most popular and widely used programming language could be easily integrated into one of the world’s largest retail trading platforms.

The extensive range of Python libraries and widespread availability of powerful computing platforms meant that everyday traders could integrate powerful machine learning libraries and concepts into their day-trading activities. In fact, my company Creative Appnologies, uses it extensively in our analysis programs.

These integrations mean that sometimes you need to modify an open position.


Modify An Open Position

To modify an open position, you need the following:

  1. A connection to MetaTrader 5 with Python
  2. The order number of the position
  3. Symbol
  4. New Stop Loss value
  5. New Take Profit value

Here’s the code to modify an open position:

# Function to modify an open position
def modify_position(order_number, symbol, new_stop_loss, new_take_profit):
    # Create the request
    request = {
        "action": MetaTrader5.TRADE_ACTION_SLTP,
        "symbol": symbol,
        "sl": new_stop_loss,
        "tp": new_take_profit,
        "position": order_number
    }
    # Send order to MT5
    order_result = MetaTrader5.order_send(request)
    if order_result[0] == 10009:
        return True
    else:
        return False

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.