MetaTrader 5 Python User Group - how to use Python in Metatrader - page 58

 
Дмитрий Прокопьев:

Thank you, I've seen that example, it works.

I'm just talking about something else.


positions_get - it will return me a list of tradePosition. In principle, it's OK, you can put it in pandas and work fine.

But it's not limited to one pandas, and if you want to get something like this:

[{'ticket': 164661016, 'time': 1585075408, 'time_msc': 1585075408163, 'time_update': 1585075408, 'time_update_msc': 1585075408163, 'type': 1, 'magic': 0, 'identifier': 164661016, 'reason': 0, 'volume': 0.01, 'price_open': 120.306, 'sl': 0.0, 'tp': 0.0, 'price_current': 120.328, 'swap': 0.0, 'profit': -0.2, 'symbol': 'EURJPY', 'comment': '', 'external_id': ''}, 
{'ticket': 164661051, 'time': 1585075426, 'time_msc': 1585075426062, 'time_update': 1585075426, 'time_update_msc': 1585075426062, 'type': 0, 'magic': 0, 'identifier': 164661051, 'reason': 0, 'volume': 0.01, 'price_open': 1.07798, 'sl': 0.0, 'tp': 0.0, 'price_current': 1.07881, 'swap': 0.0, 'profit': 0.83, 'symbol': 'EURUSD', 'comment': '', 'external_id': ''}]

Look at example for positions_get, it uses several strings.

Example:

importMetaTrader5 asmt5
importpandas aspd.
pd.set_option('display.max_columns',500)# how many columns are shown
pd.set_option('display.width', 1500)# max. table width to display
# display data of MetaTrader5 package
print("MetaTrader5 package author: ",mt5.__author__)
print("MetaTrader5 package version: ",mt5.__version__)
print()
# set connection to the terminal MetaTrader 5
if notmt5.initialize():
print("initialize() failed, error code =",mt5.last_error())
quit()

# receive open positions on USDCHF
positions=mt5.positions_get(symbol="USDCHF")
ifpositions==None:
print("No positions on USDCHF, error code={}".format(mt5.last_error()))
elif len(positions)>0:
print("Total positions on USDCHF =",len(positions))
# print all open positions
for position inpositions:
print(position)

# get list of positions on symbols that contain "*USD*" in their names
usd_positions=mt5.positions_get(group="*USD*")
ifusd_positions==None:
print("No positions with group=\"*USD*\", error code={}".format(mt5.last_error()))
elif len(usd_positions)>0:
print("positions_get(group=\"*USD*\")={}".format(len(usd_positions))
# output these positions as a table using pandas.DataFrame
df=pd.DataFrame(list(usd_positions),columns=usd_positions[0]._asdict().keys())
df['time'] = pd.to_datetime(df['time'], unit='s')
df.drop(['time_update', 'time_msc', 'time_update_msc', 'external_id'], axis=1, inplace=True)

print(df)

# end connection to the terminal MetaTrader 5
mt5.shutdown()


Result:
MetaTrader5 package author: MetaQuotes Software Corp.
MetaTrader5 package version: 5.0.29

positions_get(group="*USD*")=5
tickettime type magic identifier reasonvolume price_open sl tp price_current swap profit symbol comment
0 548297723 2020-03-18 15:00:55 1 0 548297723 3 0.01 1.09301 1.11490 1.06236 1.10101 -0.10 -8.00 EURUSD
1 548655158 2020-03-18 20:31:26 0 0 548655158 3 0.01 1.08676 1.06107 1.12446 1.10098 -0.08 14.22 EURUSD
2 548663803 2020-03-18 20:40:04 0 0 548663803 3 0.01 1.08640 1.06351 1.11833 1.10098 -0.08 14.58 EURUSD
3 548847168 2020-03-19 01:10:05 0 0 548847168 3 0.01 1.09545 1.05524 1.15122 1.10098 -0.06 5.53 EURUSD
4 548847194 2020-03-19 01:10:07 0 0 548847194 3 0.02 1.09536 1.04478 1.16587 1.10098 -0.08 11.24 EURUSD

Документация по MQL5: Интеграция / MetaTrader для Python / positions_get
Документация по MQL5: Интеграция / MetaTrader для Python / positions_get
  • www.mql5.com
ticket                time  type  magic  identifier  reason  volume  price_open       sl       tp  price_current  swap  profit  symbol comment 0  548297723 2020-03-18 15:00:55     1      0   548297723       3    0.01     1.09301  1.11490  1.06236        1.10101 -0.10   -8.00  EURUSD        ...
 

Descriptions of 3 new functions have been added to the help:

In addition, the descriptions of many of the functions have been changed as they have been refined. Almost all examples have been rewritten to reflect the new functionality. However, the examples for the following functions have not been updated on the website yet, they will be a bit later:

Документация по MQL5: Интеграция / MetaTrader для Python / last_error
Документация по MQL5: Интеграция / MetaTrader для Python / last_error
  • www.mql5.com
позволяет получить код ошибки в случае неуспешного выполнения какой-либо функции библиотеки MetaTrader 5. Является аналогом GetLastError(), но используются свои коды ошибок. Возможные значения:
 
Дмитрий Прокопьев:

Gentlemen, the guys in the next thread are asking questions about the libs:

URL:https://www.mql5.com/en/forum/306742/page11#comment_15595095

Can you give me your support?

Answered in that thread

 
Rashid Umarov:

Look at the example for positions_get, several lines are used there

Thank you!

 
Rashid Umarov:

Answered in that thread

Rashid, tell me, is it possible to use the tester with MetaTrader5?

When modelling in the tester, there is one very effective element - the paralleling of simulation tasks in Local network farm or

I want to use the tester's resource with MetaTrader5.

 
Vladimir Perervenko:

Why do you need this? Can't you calculate it in Python? I'm surprised.

I'm not familiar with python at all, I'm just about to switch from lua to it, so I'm learning the stuff...
 

The help section tells you how to install and update the library - https://www.mql5.com/ru/docs/integration/python_metatrader5

Установка пакета в командной строке:

pip install MetaTrader5

Upgrade the package on the command line:

pip install --upgrade MetaTrader5



Документация по MQL5: Интеграция / MetaTrader для Python
Документация по MQL5: Интеграция / MetaTrader для Python
  • www.mql5.com
Python является современным высокоуровневым языком программирования для разработки сценариев и приложений. Содержит множество библиотек для машинного обучения, автоматизации процессов, анализа и визуализации данных. Пакет MetaTrader для Python предназначен для...
 
Rashid Umarov:

The help section tells you how to install and update the library - https://www.mql5.com/ru/docs/integration/python_metatrader5

To be honest, it's not quite clear. Because it doesn't work without VS, and what exactly is needed from VS - is not clear (because I wouldn't like to install the whole studio, as it is not needed);

If you can clarify it, that would be great.

 
Alexey Kozitsyn:

To be honest, it's not quite clear. Because it doesn't work without VS, and what exactly is needed from VS - is not clear (because I wouldn't like to install the whole studio because I don't need it);

If you elaborate on it, that would be great.

Why do you need VS? Python doesn't require VS.

Google something like window python and you're good to go.

 

Gentlemen developers, a good point was made in the next thread.

This applies to**kwargs processing, in the case of writing tests - this is a very important point.

https://www.mql5.com/en/forum/306742/page12#comment_15660939