Issues with Multiple Unwanted Orders Executed on MT5 with mt5 Python Integration

 

Hello!


I use the Python adapter for MetaTrader5, and so far everything is fine!

But running a simple strategy live made me notice something undesirable. My orders were executed several times when I only wanted to execute one.


A screenshot of the trading history is attached. Red dots represent trades that are made multiple times, not just once. As you can see, not all orders are multiples.

Ignore the SL and TP on these trades as they don't match what is written in the "SMA Strategy.py" code but all other things remain the same.


Here is the "SMA Stratregy.py"

import pandas as pd
import MetaTrader5 as mt5
import datetime



 if not mt5.initialize():
        print("initialize() failed, error code =",mt5.last_error())
        mt5.shutdown()

    
 if __name__ == '__main__':

     while True:

        to = datetime . datetime .now()
        from_ = to - datetime .timedelta(minutes= 8 )

        # Get data
        rates = mt5.copy_rates_range('EURUSD', mt5.TIMEFRAME_M1, from_, to)
        data = pd.DataFrame(rates)
        data['time']=pd.to_datetime(data['time'], unit='s')
        data = data.set_index('time')


        #  Compute SMA
        data['sma'] = data['close'].rolling( 6 ).mean()
        close = data['close'][ 7 ]
        sma = data['sma'][ 7 ]
        magic = 56500 

        # Get positions
        pos = mt5.positions_get(symbol='EURUSD')

        # Check if there are positions

        # If there are positions
         if len(pos) != 0 :
            pass
        # If there are positions
         else:  
            point = mt5.symbol_info('EURUSD').point
                # If close is higher than SMA

             if close > sma:
                # Buy
                price = mt5.symbol_info_tick('EURUSD').ask
                request = {
                    "action": mt5. TRADE_ACTION_DEAL ,
                    "symbol": 'EURUSD',
                    "volume": 0.1 ,
                    "type": mt5. ORDER_TYPE_BUY ,
                    "price": price,
                    "deviation": 10 ,
                    "tp": price + ( 30 * point),
                    "sl": price - ( 30 * point), 
                    "magic": magic,
                    "comment": "comment",
                    "type_filling": mt5.symbol_info('EURUSD').filling_mode,
                    "type_time": mt5. ORDER_TIME_GTC 
                    }
              
            # If close is lower than SMA
            elif close < sma:
              # Sell
                price = mt5.symbol_info_tick('EURUSD').bid
                request = {
                    "action": mt5. TRADE_ACTION_DEAL ,
                    "symbol": 'EURUSD',
                    "volume": 0.1 ,
                    "type": mt5. ORDER_TYPE_SELL ,
                    "price": price,
                    "deviation": 10 ,
                    "tp": price - ( 30 * point),
                    "sl": price + ( 30 * point), 
                    "magic": magic,
                    "comment": "comment",
                    "type_filling": mt5.symbol_info('EURUSD').filling_mode,
                    "type_time": mt5. ORDER_TIME_GTC 
                    }
             
            result = mt5.order_send(request)
            


Here is the trading history. Note that the multiples orders are executed in microseconds. That means, if I placed an order at 23:46:02, four trades can get executed.

It's easy to think that the orders executed  23:47:02 is as a result of the order placed at 23:46:02. It's not, because as soon as I suspect the multiple orders at 23:46:02, I close them after roughly a minute, only for the script to open another order and execute it multiple times, hence, 23:47:02. And so on for the rest of the multiple orders down the history

Please feel free to point out any wrong in my code that could lead to this. Or maybe something needs to be tinkered with in MT5.

Thank you!

Файлы:
met.png  464 kb
 
Lawal Abdulsalam:

Hello!


I use the Python adapter for MetaTrader5, and so far everything is fine!

But running a simple strategy live made me notice something undesirable. My orders were executed several times when I only wanted to execute one.


A screenshot of the trading history is attached. Red dots represent trades that are made multiple times, not just once. As you can see, not all orders are multiples.

Ignore the SL and TP on these trades as they don't match what is written in the "SMA Strategy.py" code but all other things remain the same.


Here is the "SMA Stratregy.py"


Here is the trading history. Note that the multiples orders are executed in microseconds. That means, if I placed an order at 23:46:02, four trades can get executed.

It's easy to think that the orders executed  23:47:02 is as a result of the order placed at 23:46:02. It's not, because as soon as I suspect the multiple orders at 23:46:02, I close them after roughly a minute, only for the script to open another order and execute it multiple times, hence, 23:47:02. And so on for the rest of the multiple orders down the history

Please feel free to point out any wrong in my code that could lead to this. Or maybe something needs to be tinkered with in MT5.

Thank you!

Нужно проверять результат исполнения ордера! Смотри пример https://www.mql5.com/ru/docs/python_metatrader5/mt5ordersend_py

Документация по MQL5: Python интеграция / order_send
Документация по MQL5: Python интеграция / order_send
  • www.mql5.com
order_send - Python интеграция - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Thank you! I guess it's fixed now.

But there's this other issue I have. Even though the time zone of my local computer is GMT +2 which is the same as my broker time zone on MT5; if I request for data, it usually bring displays the last 2 hours as the last bar. For example:

to = datetime.datetime.now()
from_ = to - datetime.timedelta(hours=8)
rates = mt5.copy_rates_range('EURUSD', mt5.TIMEFRAME_M1, from_, to)
rates_frame = pd.DataFrame(rates)
rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')
rates_frame = rates_frame.set_index('time')
print(rates_frame)
print(f"Time : {datetime.datetime.now()}")


Output:

                        open     high      low    close  tick_volume  spread  real_volume
time                                                                                     
2023-03-03 13:49:00  1.06175  1.06177  1.06146  1.06148           66       0            0
2023-03-03 13:50:00  1.06148  1.06152  1.06145  1.06146           46       0            0
2023-03-03 13:51:00  1.06146  1.06162  1.06142  1.06161           51       0            0
2023-03-03 13:52:00  1.06161  1.06166  1.06152  1.06153           63       0            0
2023-03-03 13:53:00  1.06153  1.06157  1.06150  1.06156           46       0            0
...                      ...      ...      ...      ...          ...     ...          ...
2023-03-03 21:44:00  1.06286  1.06287  1.06278  1.06285           29       0            0
2023-03-03 21:45:00  1.06285  1.06285  1.06280  1.06281           24       0            0
2023-03-03 21:46:00  1.06280  1.06286  1.06279  1.06280           12       0            0
2023-03-03 21:47:00  1.06280  1.06290  1.06280  1.06285           20       0            0
2023-03-03 21:48:00  1.06285  1.06299  1.06285  1.06289           57       0            0

[480 rows x 7 columns]

Time : 2023-03-03 23:48:18.593421

Thanks.