Send order in MetaTrader5 using Python

 

Hi all,

I am trying to use the the Python library MetaTrader5 to elaborate the data in Python and then send an order to the metatrader5.

I am not able to send an order using the function order_send(). I always receive the retcode 10013. I am struggling with this problem for days.

Could someone help me with this issue? Here's the piece of code in which the request is build.

The initilization of the mt5 works and also the other function seems to work well. I think there is somenthing wrong with the request (automatic trading in the mt5 should be already enable).

symbol = "USDJPY"
lot = 0.01
point = mt5.symbol_info(symbol).point
price = mt5.symbol_info_tick(symbol).ask
deviation = 20


request_first = { 
	"action": mt5.TRADE_ACTION_DEAL, 
	"symbol": symbol, 
	"volume": lot, 
	"type": mt5.ORDER_TYPE_BUY, 
	"price": price, 
	"sl": price - 100*point, 
	"tp": price + 100*point, 
	"deviation": deviation, 
	"type_time": mt5.ORDER_TIME_GTC, 
	"type_filling": mt5.ORDER_FILLING_RETURN, 

}
result = mt5.order_send(request=request_first)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("Order failed: {}".format(result.retcode)) else: print(result.order)
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Order Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Requests to execute trade operations are formalized as orders. Each order has a variety of properties for reading. Information on them can be obtained using functions Position identifier that is set to an order as soon as it is executed. Each executed order results in a deal that opens or modifies an already existing position. The identifier of...
 

You have at least missed the fields:

request = { 
    "action": mt5.TRADE_ACTION_DEAL, 
    "symbol": symbol, 
    "volume": lot, 
    "type": mt5.ORDER_TYPE_BUY, 
    "price": price, 
    "sl": price - 100 * point, 
    "tp": price + 100 * point, 
    "deviation": deviation, 
    "magic": 234000, 
    "comment": "python script open", 
    "type_time": mt5.ORDER_TIME_GTC, 
    "type_filling": mt5.ORDER_FILLING_RETURN, 
} 
 

Example from the help - it works:

import time 
import MetaTrader5 as mt5 
  
# display data on the MetaTrader 5 package 
print("MetaTrader5 package author: ", mt5.__author__) 
print("MetaTrader5 package version: ", mt5.__version__) 
  
# establish connection to the MetaTrader 5 terminal 
if not mt5.initialize(): 
    print("initialize() failed, error code =",mt5.last_error()) 
    quit() 
  
# prepare the buy request structure 
symbol = "USDJPY" 
symbol_info = mt5.symbol_info(symbol) 
if symbol_info is None: 
    print(symbol, "not found, can not call order_check()") 
    mt5.shutdown() 
    quit() 
  
# if the symbol is unavailable in MarketWatch, add it 
if not symbol_info.visible: 
    print(symbol, "is not visible, trying to switch on") 
    if not mt5.symbol_select(symbol,True): 
        print("symbol_select({}}) failed, exit",symbol) 
        mt5.shutdown() 
        quit() 
  
lot = 0.1 
point = mt5.symbol_info(symbol).point 
price = mt5.symbol_info_tick(symbol).ask 
deviation = 20 
request = { 
    "action": mt5.TRADE_ACTION_DEAL, 
    "symbol": symbol, 
    "volume": lot, 
    "type": mt5.ORDER_TYPE_BUY, 
    "price": price, 
    "sl": price - 100 * point, 
    "tp": price + 100 * point, 
    "deviation": deviation, 
    "magic": 234000, 
    "comment": "python script open", 
    "type_time": mt5.ORDER_TIME_GTC, 
    "type_filling": mt5.ORDER_FILLING_RETURN, 
} 
  
# send a trading request 
result = mt5.order_send(request) 
# check the execution result 
print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation)); 
if result.retcode != mt5.TRADE_RETCODE_DONE: 
    print("2. order_send failed, retcode={}".format(result.retcode)) 
    # request the result as a dictionary and display it element by element 
    result_dict=result._asdict() 
    for field in result_dict.keys(): 
        print("   {}={}".format(field,result_dict[field])) 
        # if this is a trading request structure, display it element by element as well 
        if field=="request": 
            traderequest_dict=result_dict[field]._asdict() 
            for tradereq_filed in traderequest_dict: 
                print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 
    print("shutdown() and quit") 
    mt5.shutdown() 
    quit() 
  
print("2. order_send done, ", result) 
print("   opened position with POSITION_TICKET={}".format(result.order)) 
print("   sleep 2 seconds before closing position #{}".format(result.order)) 
time.sleep(2) 
# create a close request 
position_id=result.order 
price=mt5.symbol_info_tick(symbol).bid 
deviation=20 
request={ 
    "action": mt5.TRADE_ACTION_DEAL, 
    "symbol": symbol, 
    "volume": lot, 
    "type": mt5.ORDER_TYPE_SELL, 
    "position": position_id, 
    "price": price, 
    "deviation": deviation, 
    "magic": 234000, 
    "comment": "python script close", 
    "type_time": mt5.ORDER_TIME_GTC, 
    "type_filling": mt5.ORDER_FILLING_RETURN, 
} 
# send a trading request 
result=mt5.order_send(request) 
# check the execution result 
print("3. close position #{}: sell {} {} lots at {} with deviation={} points".format(position_id,symbol,lot,price,deviation)); 
if result.retcode != mt5.TRADE_RETCODE_DONE: 
    print("4. order_send failed, retcode={}".format(result.retcode)) 
    print("   result",result) 
else: 
    print("4. position #{} closed, {}".format(position_id,result)) 
    # request the result as a dictionary and display it element by element 
    result_dict=result._asdict() 
    for field in result_dict.keys(): 
        print("   {}={}".format(field,result_dict[field])) 
        # if this is a trading request structure, display it element by element as well 
        if field=="request": 
            traderequest_dict=result_dict[field]._asdict() 
            for tradereq_filed in traderequest_dict: 
                print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 
  
# shut down connection to the MetaTrader 5 terminal 
mt5.shutdown() 
Files:
order_send.py  5 kb
 

Thank you very much for your reply. The example in the help works well, thank you.

However it works also without magic and comments. So, I do not understand the difference in the request.

Anyway, I will check it!

Thank you again, your solution works!!!!

 

Hello Francesco and Vladimir, thanks for your post!!!

I am runing your code, and i have 2 errors.

1) Trade Disabled

I have enabled:

but still not working.

2) NameError: name 'quit' is not defined

Can you help me?

 
luisaoisdead:

Hello Francesco and Vladimir, thanks for your post!!!

I am runing your code, and i have 2 errors.

1) Trade Disabled

I have enabled:

but still not working.

2) NameError: name 'quit' is not defined

Can you help me?

You should use exit() from REPL (which you would only use for simple prototyping) and sys.exit() from scripts because quit and exit were only ever intended to be used from the REPL. Also, I made a library to wrap the MetaTraer5 package which has some extra sugar buit-in. for example:

>>> import pymt5adapter as mta
>>> from pymt5adapter.order import Order
>>> mta.initialize()
True
>>> order = Order.as_buy(symbol='EURUSD', volume=0.1)
>>> order
Order(action=1, symbol=EURUSD, volume=0.1, type=0)
>>> r = order.send()
>>> r
OrderSendResult(retcode=10009, deal=63876888, order=657807713, volume=0.1, price=1.1391, bid=1.1390500000000001, ask=1.1391, comment='Request executed', request_id=1, retcode_external=0, request=TradeRequest(action=1, magic=0, order=0, symbol='EURUSD', volume=0.1, price=1.1391, stoplimit=0.0, sl=0.0, tp=0.0, deviation=0, type=0, type_filling=0, type_time=0, expiration=0, comment='', position=0, position_by=0))
>>> p = mta.positions_get(symbol='EURUSD')
>>> p
(TradePosition(ticket=6286807713, time=1594957069, time_msc=1594957069290, time_update=1594957069, time_update_msc=1594957069290, type=0, magic=0, identifier=632427713, reason=3, volume=0.1, price_open=1.1391, sl=0.0, tp=0.0, price_current=1.13902, swap=0.0, profit=-0.7, symbol='EURUSD', comment='', external_id=''),)
>>> close_order = Order.as_flatten(p[0])
>>> close_order
Order(action=1, magic=0, symbol=EURUSD, volume=0.1, type=1, position=6523687713)
>>> close_order.send()
OrderSendResult(retcode=10009, deal=637279941, order=657808756, volume=0.1, price=1.13912, bid=1.13912, ask=1.13918, comment='Request executed', request_id=2, retcode_external=0, request=TradeRequest(action=1, magic=0, order=0, symbol='EURUSD', volume=0.1, price=1.13912, stoplimit=0.0, sl=0.0, tp=0.0, deviation=0, type=1, type_filling=0, type_time=0, expiration=0, comment='', position=657807713, position_by=0))
>>> p = mta.positions_get(symbol='EURUSD')
>>> p
()
>>> mta.shutdown()
True
>>> exit()

C:\Users\User>
 
nicholish en:

You should use exit() from REPL (which you would only use for simple prototyping) and sys.exit() from scripts because quit and exit were only ever intended to be used from the REPL. Also, I made a library to wrap the MetaTraer5 package which has some extra sugar buit-in. for example:

Thanks!!!

sys.exit, work great!!!!

but i still get the message "Trade Disable" in Metatrader.

i enabled:

and 

i am missing something?

thanks again.

 
luisaoisdead:

Thanks!!!

sys.exit, work great!!!!

but i still get the message "Trade Disable" in Metatrader.

i enabled:

and 

i am missing something?

thanks again.

Most likely you are on an ECN account and you are trying to trade a symbol that is disabled. eg. The ECN symbol is "USDJPYi" and you're trying to trade "USDJPY". Run the following code and if it outputs "SYMBOL_TRADE_MODE.DISABLED" then that's your issue. 

import pymt5adapter as mta

with mta.connected():
    s = mta.symbol_info('USDJPY')
    print(mta.SYMBOL_TRADE_MODE(s.trade_mode))
 
nicholish en:

Most likely you are on an ECN account and you are trying to trade a symbol that is disabled. eg. The ECN symbol is "USDJPYi" and you're trying to trade "USDJPY". Run the following code and if it outputs "SYMBOL_TRADE_MODE.DISABLED" then that's your issue. 

Thanks!!!

you where right.

USDJPY SYMBOL_TRADE_MODE.DISABLED

EPU20 SYMBOL_TRADE_MODE.FULL


But I still get no retcode. 

if result.retcode != mt5.TRADE_RETCODE_DONE:


AttributeError: 'NoneType' object has no attribute 'retcode'

 

Update to the latest version of pymt5adapter

pip install -U pymt5adapter

Run the following and upload the log results found in your CWD/my_mt5_log.log

import logging

import pymt5adapter as mta


def main():
    """Paste your code here"""


if __name__ == '__main__':
    logger = mta.get_logger('my_mt5_log.log', loglevel=logging.DEBUG)
    with mta.connected(raise_on_errors=True, logger=logger):
        main()
 

LOG FILE

2020-07-23 13:55:31,237 INFO    Terminal Initialize Success     {"type":"terminal_connection_state","state":true}
2020-07-23 13:55:31,237 INFO    Init TerminalInfo       {"type":"init_terminal_info","terminal_info":{"community_account":true,"community_connection":true,"connected":true,"dlls_allowed":false,"trade_allowed":true,"tradeapi_disabled":false,"email_enabled":false,"ftp_enabled":false,"notifications_enabled":false,"mqid":false,"build":2530,"maxbars":100000,"codepage":1252,"ping_last":176935,"community_balance":0.0,"retransmission":0.0,"company":"MetaQuotes Software Corp.","name":"MetaTrader 5","language":"Spanish","path":"C:\\Program Files\\MetaTrader 5","data_path":"C:\\Users\\LuisaoRocks\\AppData\\Roaming\\MetaQuotes\\Terminal\\D0E8209F77C8CF37AD8BF550E51FF075","commondata_path":"C:\\Users\\LuisaoRocks\\AppData\\Roaming\\MetaQuotes\\Terminal\\Common"}}
2020-07-23 13:55:31,237 INFO    Init AccountInfo        {"type":"init_account_info","account_info":{"login":1170093,"trade_mode":0,"leverage":100,"limit_orders":0,"margin_so_mode":0,"trade_allowed":true,"trade_expert":true,"margin_mode":0,"currency_digits":2,"fifo_close":false,"balance":95727.66,"credit":0.0,"profit":0.0,"equity":95727.66,"margin":0.0,"margin_free":95727.66,"margin_level":0.0,"margin_so_call":50.0,"margin_so_so":30.0,"margin_initial":0.0,"margin_maintenance":0.0,"assets":0.0,"liabilities":0.0,"commission_blocked":0.0,"name":"Lu is","server":"AMPGlobalUSA-Demo","currency":"USD","company":"AMP Global Clearing LLC"}}
2020-07-23 13:55:31,245 CRITICAL        UNCAUGHT EXCEPTION: 'NoneType' object has no attribute 'retcode'        {"type":"exception","last_error":[-2,"Invalid \"volume\" argument"],"exception":{"type":"AttributeError","message":"'NoneType' object has no attribute 'retcode'"}}
2020-07-23 13:55:31,246 INFO    Terminal Shutdown       {"type":"terminal_connection_state","state":false}

ORDER_SEND

#https://www.mql5.com/en/forum/343594
import time 
import MetaTrader5 as mt5 
import sys
import logging
import pymt5adapter as mta
# display data on the MetaTrader 5 package 
print("MetaTrader5 package author: ", mt5.__author__) 
print("MetaTrader5 package version: ", mt5.__version__) 
  

def main():  
    # establish connection to the MetaTrader 5 terminal 
    if not mt5.initialize(): 
        print("initialize() failed, error code =",mt5.last_error()) 
        sys.exit() 
      
    # prepare the buy request structure 
    symbol = "EPU20" 
    symbol_info = mt5.symbol_info(symbol) 
    if symbol_info is None: 
        print(symbol, "not found, can not call order_check()") 
        mt5.shutdown() 
        sys.exit() 
      
    # if the symbol is unavailable in MarketWatch, add it 
    if not symbol_info.visible: 
        print(symbol, "is not visible, trying to switch on") 
        if not mt5.symbol_select(symbol,True): 
            print("symbol_select({}}) failed, exit",symbol) 
            mt5.shutdown() 
            sys.exit() 
      
    lot = 1 
    point = mt5.symbol_info(symbol).point 
    price = mt5.symbol_info_tick(symbol).ask 
    deviation = 20 
    request = { 
        "action": mt5.TRADE_ACTION_DEAL, 
        "symbol": symbol, 
        "volume": lot, 
        "type": mt5.ORDER_TYPE_BUY, 
        "price": price, 
        "sl": price - 100 * point, 
        "tp": price + 100 * point, 
        "deviation": deviation, 
        "magic": 234000, 
        "comment": "python script open", 
        "type_time": mt5.ORDER_TIME_GTC, 
        "type_filling": mt5.ORDER_FILLING_RETURN 
    }     
    
    
    
    
    
    # send a trading request 
    result = mt5.order_send(request) 
    # check the execution result 
    print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation)); 
    if result.retcode != mt5.TRADE_RETCODE_DONE: 
        print("2. order_send failed, retcode={}".format(result.retcode)) 
        # request the result as a dictionary and display it element by element 
        result_dict=result._asdict() 
        for field in result_dict.keys(): 
            print("   {}={}".format(field,result_dict[field])) 
            # if this is a trading request structure, display it element by element as well 
            if field=="request": 
                traderequest_dict=result_dict[field]._asdict() 
                for tradereq_filed in traderequest_dict: 
                    print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 
        print("shutdown() and quit") 
        mt5.shutdown() 
        sys.exit()
  
    print("2. order_send done, ", result) 
    print("   opened position with POSITION_TICKET={}".format(result.order)) 
    print("   sleep 2 seconds before closing position #{}".format(result.order)) 
    time.sleep(2) 
    # create a close request 
    position_id=result.order 
    price=mt5.symbol_info_tick(symbol).bid 
    deviation=20 
    request={ 
        "action": mt5.TRADE_ACTION_DEAL, 
        "symbol": symbol, 
        "volume": lot, 
        "type": mt5.ORDER_TYPE_SELL, 
        "position": position_id, 
        "price": price, 
        "deviation": deviation, 
        "magic": 234000, 
        "comment": "python script close", 
        "type_time": mt5.ORDER_TIME_GTC, 
        "type_filling": mt5.ORDER_FILLING_RETURN,
    } 
    # send a trading request 
    result=mt5.order_send(request) 
    # check the execution result 
    print("3. close position #{}: sell {} {} lots at {} with deviation={} points".format(position_id,symbol,lot,price,deviation)); 
    if result.retcode != mt5.TRADE_RETCODE_DONE: 
        print("4. order_send failed, retcode={}".format(result.retcode)) 
        print("   result",result) 
    else: 
        print("4. position #{} closed, {}".format(position_id,result)) 
        # request the result as a dictionary and display it element by element 
        result_dict=result._asdict() 
        for field in result_dict.keys(): 
            print("   {}={}".format(field,result_dict[field])) 
            # if this is a trading request structure, display it element by element as well 
            if field=="request": 
                traderequest_dict=result_dict[field]._asdict() 
                for tradereq_filed in traderequest_dict: 
                    print("traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed])) 

if __name__ == '__main__':
    logger = mta.get_logger('my_mt5_logV3.log', loglevel=logging.DEBUG)
    with mta.connected(raise_on_errors=True, logger=logger):
        main()
# shut down connection to the MetaTrader 5 terminal 
mt5.shutdown() 

and metatrader capture

if i make a manual trade....

thanks for your time!!!

Reason: