closing MT5 terminal using Python

 

mt5.initialize()         Opens the MT5 terminal/platform if it was not already open

# shut down connection to the MetaTrader 5 terminal
mt5.shutdown()   Closes the connection


I am looking for a way of closing/shutting down the MT5 terminal/platform


 
you might want to try this

https://pywinauto.github.io/
 

MT5 terminal is 64 bit, any ideas of what else I can use.

Unless there is something I missed.

 
libby000:

mt5.initialize()         Opens the MT5 terminal/platform if it was not already open

# shut down connection to the MetaTrader 5 terminal
mt5.shutdown()   Closes the connection


I am looking for a way of closing/shutting down the MT5 terminal/platform


It should be doing that automatically... I think sometimes it works and sometime it does not. It's better to wrap mtr5.initialize/shutdown in your own context manager, and from there you can use subprocess.Popen to open and close the terminal yourself so you won't have to rely on the MetaTrade5 package to do it for you. 


import contextlib
import os
import subprocess
import sys
import time
from pathlib import Path
from pprint import pp

import MetaTrader5 as mt5
import psutil


class MyTerminalConnection:
    _min_uptime_secs = 5

    def __init__(self, path, **init_kwargs):
        self.path = str(Path(path).absolute())
        self.command_args = [self.path]
        has = init_kwargs.get
        if has('portable'):
            self.command_args.append('/portable')
        if has('login'):
            self.command_args.append(f"/login:{init_kwargs['login']}")
        if has('profile'):
            profile = init_kwargs.pop('profile')
            self.command_args.append(f'/profile:{init_kwargs[profile]}')
        if has('config'):
            config = init_kwargs.pop('config')
            self.command_args.append(f"/config:{config}")
        self.init_kwargs = {'path': self.path, **init_kwargs}

    def __enter__(self):
        try:
            self.process = subprocess.Popen(self.command_args)
            self.init_time = time.time()
            if not mt5.initialize(**self.init_kwargs):
                raise Exception('{} -> MT5 could not be initialized with {}'.format(
                    mt5.last_error(),
                    self.init_kwargs))
            return self
        except:
            self.__exit__(*sys.exc_info())

    def __exit__(self, exc_type, exc_val, exc_tb):
        mt5.shutdown()
        if (time_lapsed := time.time() - self.init_time) < self._min_uptime_secs:
            print(f'{type(self).__name__}: '
                  'Waiting for process to finish loading up before closing...')
            time.sleep(self._min_uptime_secs - time_lapsed)
        with contextlib.suppress(Exception):
            pid = self.process.pid
            self.process.terminate()
            for _ in range(5):
                if pid not in psutil.pids():
                    break
                time.sleep(.25)
                psutil.Process(pid).terminate()
            else:
                os.system("taskkill /f /im terminal64.exe")


if __name__ == '__main__':
    mt5_connected = MyTerminalConnection(
        path=r'C:\Users\nicho\Desktop\Terminal1\terminal64.exe',
        portable=True,
    )
    with mt5_connected as conn:
        print(conn.command_args)
        pp(mt5.terminal_info()._asdict())
 
Morning all, I am very new to coding. can somebody pls teach me how to close mt5 terminal after copying file to the mql5 folder, I will be very grateful.
 
Sorry, I actually mean how to close and restart the terminal after inserting file in the MQL5 folder. Thanks in advance to the experienced and benevolent member.