Python MT5

 

Hi, so i got the python code for sending orders to the metatrader. However, there is an issue. The buy orders work but every time i try sending a sell order fom python to  metatrader, it never sends anything. Does anyone have a solution for this?

 

Hi Tom,


I create a library that helps with the Python API, which is to reduce the boilerplate code.

Look at Expert Advisor Example, perhaps it might help you.


https://github.com/Joaopeuko/Mql5-Python-Integration


Here is how I open a sell or buy position, it is located in trade.py inside the "include" folder.


    # It is to open a Buy position.
    def open_buy_position(self, comment=""):
        point = Mt5.symbol_info(self.symbol).point
        price = Mt5.symbol_info_tick(self.symbol).ask

        self.ticket = (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0)

        request = {
            "action": Mt5.TRADE_ACTION_DEAL,
            "symbol": self.symbol,
            "volume": self.lot,
            "type": Mt5.ORDER_TYPE_BUY,
            "price": price,
            "sl": price - self.emergency_stop_loss * point,
            "tp": price + self.emergency_take_profit * point,
            "deviation": 5,
            "magic": self.magic_number,
            "comment": str(comment),
            "type_time": Mt5.ORDER_TIME_GTC,
            "type_filling": Mt5.ORDER_FILLING_RETURN,
            "position": (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0)
        }
        result = Mt5.order_send(request)
        self.request_result(price, result)

    # It is to open a Sell position.
    def open_sell_position(self, comment=""):
        point = Mt5.symbol_info(self.symbol).point
        price = Mt5.symbol_info_tick(self.symbol).bid

        self.ticket = (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0)

        request = {
            "action": Mt5.TRADE_ACTION_DEAL,
            "symbol": self.symbol,
            "volume": self.lot,
            "type": Mt5.ORDER_TYPE_SELL,
            "price": price,
            "sl": price + self.emergency_stop_loss * point,
            "tp": price - self.emergency_take_profit * point,
            "deviation": 5,
            "magic": self.magic_number,
            "comment": str(comment),
            "type_time": Mt5.ORDER_TIME_GTC,
            "type_filling": Mt5.ORDER_FILLING_RETURN,
            "position": (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0)
        }
        result = Mt5.order_send(request)
        self.request_result(price, result)