mt5.order_send() returns None - page 2

 
ricmarchao:

Thanks for sharing this code ! I am able to close orders, for example a buy, by doing a sell and then doing a close_by...but when I look at the history of the deals these operations are missing


do you also have this problem?

from_date=dt.datetime(2000,1,1)

to_date=dt.datetime.now()


history_deals=mt5.history_deals_get(from_date, to_date)

history_deals_df=pd.DataFrame(list(history_deals),columns=history_deals[0]._asdict().keys())


Problem is here

list(history_deals)

You need to convert the namedtuples being returned to dict. I added a helper function to the pymt5adapter package to help with that. 

import pymt5adapter as mta
import pandas as pd


def main():
    deals = mta.history_deals_get()
    deals = mta.as_dict_all(deals)
    history_deals_df = pd.DataFrame(deals, columns=deals[0].keys())
    print(history_deals_df)

if __name__ == '__main__':
    with mta.connected():
        main()

...and if you only want to work exclusively with dict return types for all functions you can modify the API via the context manager kwarg "return_as_dict".

import pymt5adapter as mta
import pandas as pd


def main():
    deals = mta.history_deals_get()
    history_deals_df = pd.DataFrame(deals, columns=deals[0].keys())
    print(history_deals_df)

if __name__ == '__main__':
    with mta.connected(return_as_dict=True):
        main()


 

 
nicholi shen:

That's how you close either with MT5. In fact, there is even a Close function included in the MetaTrader5 module so your code could be greatly reduced and refactored to something like this. 

It's very usful.Thank you
 

Hi All


I'm new and am trying to create a python bot. I found codes on MT5 forum that execute trades, however it always returns None.

Would you guys know what is the problem, as I cant seem to know why its always returning None when i have all the required paramenters.

def open_trade(action, symbol, lot, sl_points, tp_points, deviation):
    '''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
    '''
    # prepare the buy request structure
    symbol_info = get_info(symbol)

    if action == 'buy':
        trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
    elif action =='sell':
        trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    point = mt5.symbol_info(symbol).point

    action_request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": trade_type,
        "price": price,
        "sl": price - sl_points * point,
        "tp": price + tp_points * point,
        "deviation": deviation,
        "magic": ea_magic_number,
        "comment": "sent by python",
        "type_time": mt5.ORDER_TIME_GTC, # good till cancelled
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    # send a trading request
    result = mt5.order_send(action_request)
    return result, action_request
trade = open_trade('buy', currency, 10, 500, 2000, 10)
print(trade)

======================================

C:\Users\andyq\PycharmProjects\BinanceTrading\venv\Scripts\python.exe "C:/Users/andyq/PycharmProjects/BinanceTrading/data preparation.py"
(None, {'action': 1, 'symbol': 'GBPUSD', 'volume': 10, 'type': 0, 'price': 1.26224, 'sl': 1.26174, 'tp': 1.26424, 'deviation': 10, 'magic': 9986989, 'comment': 'sent by python', 'type_time': 0, 'type_filling': 2})

Process finished with exit code 0
Documentation on MQL5: Integration / MetaTrader for Python / order_send
Documentation on MQL5: Integration / MetaTrader for Python / order_send
  • www.mql5.com
# request the result as a dictionary and display it element by element     # request the result as a dictionary and display it element by element 2. order_send done,  OrderSendResult(retcode=10009, deal=535084512, order=557416535, volume=0.1, price=108.023, ...
 

I was also having the problem of result = None.

I got an answer when I changed the type of the value that I was putting at request.volume from int to float, for example:

#lots variable here is actually an int..
request['volume'] = float(lots)

After casting to float, it worked. (you might as well already use a variable that is a float)

Hope it helps anybody.

 

had the same problem when working with a Pandas Dataframe. fix it by changing the data type of position_ticket. initially it was sent as <class 'numpy.int64'>, it was changed to type <class 'int'>.

 
same thing.. what am i to do? :(

import
MetaTrader5 as mt5

<Deleted> 

 
Andrew Rebane #:
same thing.. what am i to do? :(

import
MetaTrader5 as mt5

<Deleted> 

Please edit your post and use the code button (Alt+S) when pasting code.

EDIT your original post, please do not just post the code correctly in a new post.

 
jfftonsic #:

I was also having the problem of result = None.

I got an answer when I changed the type of the value that I was putting at request.volume from int to float, for example:

After casting to float, it worked. (you might as well already use a variable that is a float)

Hope it helps anybody.

this works for me
Thanks!

 

Just want to add that I had the same problem of getting None returned after calling order_send.

My problem was the comment was too long. I am not sure what the limit is, but it cannot be too long.

 

Guys, I did it this way and it worked                 

close_requisicao = {
      "action": mt5.TRADE_ACTION_DEAL,
      "symbol": ativo.nome(),
      "volume": float(df_posicoes.loc[operacao, "volume"]),
      "type": typetrade,
      "position": int(df_posicoes.loc[operacao, "ticket"]),
      "price": float(df_posicoes.loc[operacao, "price_current"]),
      "deviation": 50,
      "magic": int(df_posicoes.loc[operacao, "magic"]),
      "comment": df_posicoes.loc[operacao, "comment"],
      "type_time": mt5.ORDER_TIME_GTC,
      "type_filling": mt5.ORDER_FILLING_IOC,
    }
Reason: