Bulk closing and opening using python in MT5

 

Hi guys, 


There is bulk closing in the MT5 terminal PC and mobile as well but can not see any function in python integration about this?


Can anyone help please 


Thanks

 

Python

import MetaTrader5 as mt5

# Initialize MetaTrader 5
mt5.initialize()

# Get open positions
positions = mt5.positions_get()

# Close all open positions
for position in positions:
    result = mt5.position_close(position.ticket)
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print(f"Failed to close position {position.ticket}: {result.comment}")
    else:
        print(f"Position {position.ticket} closed successfully")

# Shut down MetaTrader 5
mt5.shutdown()


Make sure you have installed the MetaTrader5 package in your Python environment before running this script.

In this example, we first initialize the MetaTrader 5 connection using mt5.initialize() . Then, we retrieve the list of open positions using mt5.positions_get() . We iterate through the list of positions, and for each position, we get the position properties using mt5.position_get_string() and then close the position using mt5.position_close() . Finally, we shut down the MetaTrader 5 connection using mt5.shutdown()

Note that this script will close all open positions on the account, so use it with caution.


Reason: