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

 
Roman:

@Almaz
The first time the copy_xxx_xxx functions are run, when the terminal has not started for some time,
functions immediately return the available result with missing history, without waiting for history swap synchronization.
It means that the first function call returns the result with missing history.
Only subsequent calls will return the correct result, when the history is swapped.
Is it possible to fix this issue? And functions copy_xxx_xxx wait for history to be swapped on the first call.

copy_ticks or copy_rates? What is the build of the terminal?

 
Roman:

@Almaz
The first time the copy_xxx_xxx functions are run, when the terminal has not started for some time,
functions immediately return the available result with missing history, without waiting for history swap synchronization.
It means that the first function call returns the result with missing history.
Only subsequent calls will return the correct result, when the history is swapped.
Is it possible to fix this issue? And the copy_xxx_xxx functions will wait for history to be swapped on the first call.

Read Organizing Data Access, it has nothing to do with the Python library. This is standard behavior, you need to handle such situations and re-request the history after the terminal swap it.

This is a one time thing, so it is not critical. You can always keep the existing history up to date if you work with the terminal from a script all the time.

Документация по MQL5: Доступ к таймсериям и индикаторам / Организация доступа к данным
Документация по MQL5: Доступ к таймсериям и индикаторам / Организация доступа к данным
  • www.mql5.com
Прежде чем ценовые данные будут доступны в терминале MetaTrader 5, их необходимо получить и обработать. Для получения данных требуется подключение к торговому серверу MetaTrader 5. Данные поступают с сервера по запросу терминала в виде экономно упакованных блоков минутных баров. Механизм обращения к серверу за данными не зависит от того, каким...
 
Almaz:

copy_ticks or copy_rates? Which build of the terminal?

Used copy_rates, but I think copy_ticks will be the same, but haven't checked.
Build 2470

 
Rashid Umarov:

Read Organize Data Access, it has nothing to do with the Python library. This is standard behaviour, you need to handle such situations and re-request the history after the terminal bounces it.

This is a one time thing, so it is not critical. You can always keep the existing history up to date if you work with the terminal from the script all the time.

I have read this section, it is related to Mql5.
Or are you implying that you need to organizeCheckLoadHistory in the same way?
Why not to introduce this function as standard? For Mql and Py library.

And in general it's strange that you allow the Copy function to receive incorrect data, without waiting for the history to be swapped out and giving the result.
 
Roman:

I read this section, it refers to Mql5.
Or are you implying that you need to organiseCheckLoadHistory in the same way?
Why not introduce this function as standard? For Mql and Py library.

And in general it's strange that you allow incorrect data in Copy function, without waiting for history swap and giving the result.

If you work in MQL5, the questions inOrganizing Access to Data section are not so special. We have studied this section far and wide. And we use it.

Why do you think it should be different for Python?

After all, the main core is MQL5 and you have to know it. And only after that you need to apply Python.

Документация по MQL5: Доступ к таймсериям и индикаторам / Организация доступа к данным
Документация по MQL5: Доступ к таймсериям и индикаторам / Организация доступа к данным
  • www.mql5.com
Прежде чем ценовые данные будут доступны в терминале MetaTrader 5, их необходимо получить и обработать. Для получения данных требуется подключение к торговому серверу MetaTrader 5. Данные поступают с сервера по запросу терминала в виде экономно упакованных блоков минутных баров. Механизм обращения к серверу за данными не зависит от того, каким...
 
Roman:

I read this section, it refers to Mql5.
Or are you implying that you need to organiseCheckLoadHistory in the same way?
Why not introduce this function as standard? For Mql and Py library.

And in general it's strange that you allow incorrect data in Copy function and do not wait for the history to be loaded and return the result.

Python library allows to request data from MetaTrader 5 terminal on the general basis regardless of the way it was requested - manually, via MQL5 or using the script from Python.

The developer of MQL5 programs and Python scripts is responsible for the logic and organization of working with data.

 

Afternoon

Is there an option to connect to the terminal via PowerShell? if anyone knows how, I would be grateful for information

No experience with python, so would like to use what I know best))

 

Good day!

I've connected libraries, python is communicating with Mt5, I'm getting account information but quotes are not loading in any way. Can you help me?

Python version 3.7.6


from datetime import datetime
import MetaTrader5 as mt5

# выведем информацию о версии MetaTrader 5
print(mt5.version())

# установим подключение к терминалу MetaTrader 5
if not mt5.initialize():
    print("initialize() failed, error code =",mt5.last_error())
    quit()

# подключимся к торговому счету без указания пароля и сервера
account=17245465
authorized=mt5.login(account)  # пароль будет взят из базы терминала, если указано помнить данные для подключения
if authorized:
    # выведем данные о торговом счете как есть
    print(mt5.account_info())
    # выведем данные о торговом счете в виде списка
    print("Show account_info()._asdict():")
    account_info_dict = mt5.account_info()._asdict()
    for prop in account_info_dict:
        print("  {}={}".format(prop, account_info_dict[prop]))
else:
    print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))

# запросим статус и параметры подключения
print(mt5.terminal_info())

# получим информацию о версии MetaTrader 5
print(mt5.version())

x= mt5.symbols_total()
print('количество всех финансовых инструментов в терминале MetaTrader 5=', x)

# получим все символы
symbols=mt5.symbols_get()
print('symbols=', symbols)

# получим бары с разных инструментов разными способами
eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M30, datetime(2020, 1, 28, 13), 1000)

# DATA
print('eurusd_rates', eurusd_rates )

# завершим подключение к MetaTrader 5
mt5.shutdown()


Result:

(0, 0, '')
AccountInfo(login=17245465, trade_mode=2, leverage=500, limit_orders=500, margin_so_mode=0, trade_allowed=False, trade_expert=True, margin_mode=2, currency_digits=2, fifo_close=False, balance=0.0, credit=0.0, profit=0.0, equity=0.0, margin=0.0, margin_free=0.0, margin_level=0.0, margin_so_call=50.0, margin_so_so=20.0, margin_initial=0.0, margin_maintenance=0.0, assets=0.0, liabilities=0.0, commission_blocked=0.0, name='xxxxxxxxxxxxx', server='Alpari-MT5', currency='USD', ...)
Show account_info()._asdict():
  login=17045461
  trade_mode=2
  leverage=500
  limit_orders=500
  margin_so_mode=0
  trade_allowed=False
  trade_expert=True
  margin_mode=2
  currency_digits=2
  fifo_close=False
  balance=0.0
  credit=0.0
  profit=0.0
  equity=0.0
  margin=0.0
  margin_free=0.0
  margin_level=0.0
  margin_so_call=50.0
  margin_so_so=20.0
  margin_initial=0.0
  margin_maintenance=0.0
  assets=0.0
  liabilities=0.0
  commission_blocked=0.0
  name=ххххххх
  server=Alpari-MT5
  currency=USD
  company=Alpari International
TerminalInfo(community_account=True, community_connection=True, connected=True, dlls_allowed=False, trade_allowed=False, tradeapi_disabled=False, email_enabled=False, ftp_enabled=False, notifications_enabled=False, mqid=False, build=2489, maxbars=100000000, codepage=1251, ping_last=95766, community_balance=0.0, retransmission=5.305821665438467, company='Alpari International', name='Alpari MT5', language='Russian', path='C:\\Program Files\\Alpari MT5', ...)
(500, 2489, '12 Jun 2020')

количество всех финансовых инструментов в терминале MetaTrader 5= 43
symbols= (SymbolInfo(custom=False, chart_mode=0, select=True, ....
eurusd_rates None

Process finished with exit code 0
Документация по MQL5: Константы, перечисления и структуры / Константы графиков / Свойства графиков
Документация по MQL5: Константы, перечисления и структуры / Константы графиков / Свойства графиков
  • www.mql5.com
Признак отрисовки ценового графика. Если установлено значение false, то отключается отрисовка любых атрибутов ценового графика и устраняются все отступы по краям графика: шкалы времени и цены, строка быстрой навигации, метки событий Календаря, значки сделок, тултипы индикаторов и баров, подокна индикаторов, гистограммы объёмов и т.д. Значение...
 
rale70:

Good day!

I've connected libraries, python is communicating with Mt5, I'm getting account information, but the quotes are not loading in any way. Can you help me?

Python version 3.7.6



Result:

Please insert code correctly (use button Code)

 
Vladimir Karputov:

Please insert the code correctly (use the button)

Thank you for the design, I will take it into account.

Reason: