MetaTrader 5 Python User Group - как использовать Python в Метатрейдере - страница 54

 

Обновитесь до 5.0.27

  pip install --upgrade MetaTrader5

Заупстите скрипт

import MetaTrader5 as mt5
# выведем данные о пакете MetaTrader5
print("MetaTrader5 package author: ",mt5.__author__)
print("MetaTrader5 package version: ",mt5.__version__)

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

# подключимся к торговому счету с указанием пароля и сервера
authorized=mt5.login(25115284, password="ваш_пароль",server="MetaQuotes-Demo")
if(authorized):
    # выведем данные о торговом счете
    #print(mt5.account_info())
    account_info=mt5.account_info()._asdict()
    print(account_info)
    print("Вывод каждого свойства отдельно:")
    for property in account_info:
        print("   ",property,"=",account_info[property])
else:
    print("failed to connect to trade account 25115284 with password=gqz0lbdm")

mt5.shutdown()

Результаты

MetaTrader5 package author:  MetaQuotes Software Corp.
MetaTrader5 package version:  5.0.27
{'login': 25115284, 'trade_mode': 0, 'leverage': 100, 'limit_orders': 200, 'margin_so_mode': 0, 'trade_allowed': True, 'trade_expert': True, 'margin_mode': 2, 'currency_digits': 2, 'fifo_close': False, 'balance': 97639.46, 'credit': 0.0, 'profit': -178.77, 'equity': 97460.69, 'margin': 704.8, 'margin_free': 96755.89, 'margin_level': 13828.134222474464, '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': 'MetaQuotes Dev Demo', 'server': 'MetaQuotes-Demo', 'currency': 'USD', 'company': 'MetaQuotes Software Corp.'}
Вывод каждого свойства отдельно:
    login = 25115284
    trade_mode = 0
    leverage = 100
    limit_orders = 200
    margin_so_mode = 0
    trade_allowed = True
    trade_expert = True
    margin_mode = 2
    currency_digits = 2
    fifo_close = False
    balance = 97639.46
    credit = 0.0
    profit = -178.77
    equity = 97460.69
    margin = 704.8
    margin_free = 96755.89
    margin_level = 13828.134222474464
    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 = MetaQuotes Dev Demo
    server = MetaQuotes-Demo
    currency = USD
    company = MetaQuotes Software Corp.

 
Vladimir Perervenko:

По поводу таймера можно поподробней? 

Сам не изучал, только поиск

 
Almaz:

В 5.0.27 уже есть, у всех structure sequence (аналог named tuple для C API) добавлен метод _asdict()

 mt5.symbol_info()._asdict() -big thnx, то что надо.

history_deals_get походу не попадает в structure sequence ... хех.

    deal = mt5.history_deals_get(position=order.position_id)._asdict()
AttributeError: 'tuple' object has no attribute '_asdict'

просто сильно не хватает конструкции, которая отдаст имена атрибутов, в правильно очередности. Если для history_deals_get _asdict() не реализуем или противоречит концепции - то хоты бы аналог _fields из collections.namedtuple (python), тогда можно выдернуть правильную очередность атрибутов, но не руками в цикле, а по-человечески. Пока получается, что-то типа:

       orders_deal = mt5.history_deals_get(from_date, to_date)
        orders_deal_frame = pd.DataFrame(orders_deal)
        print(orders_deal_frame.head())

 а на выходе:

          0          1           2              3   4   5   6   ...   11   12      13   14      15         16  17
0  519632807          0  1583873757  1583873757976   2   0   0  ...  0.0  0.0  1000.0  0.0
1  519653875  541985093  1583875090  1583875090615   1   0   0  ...  0.0  0.0     0.0  0.0  EURUSD  541984991
2  519654046  541985264  1583875102  1583875102086   0   0   0  ...  0.0  0.0     0.0  0.0  USDCHF  541984999
3  519654270  541985482  1583875116  1583875116676   0   0   0  ...  0.0  0.0     0.0  0.0  USDJPY  541985006
4  519654761  541985971  1583875151  1583875151725   1   0   0  ...  0.0  0.0     0.0  0.0  EURUSD  541985807

[5 rows x 18 columns]

ну или лапшакод с циклами.

 
Rashid Umarov:

Обновитесь до 5.0.27

Заупстите скрипт

Результаты

Сенкс!

Действительно удобнее в этой части стало.

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

 mt5.symbol_info()._asdict() -big thnx, то что надо.

history_deals_get походу не попадает в structure sequence ... хех.

просто сильно не хватает конструкции, которая отдаст имена атрибутов, в правильно очередности. Если для history_deals_get _asdict() не реализуем или противоречит концепции - то хоты бы аналог _fields из collections.namedtuple (python), тогда можно выдернуть правильную очередность атрибутов, но не руками в цикле, а по-человечески. Пока получается, что-то типа:

 а на выходе:

ну или лапшакод с циклами.

history_deals_get  всегда возвращает обычный Python tuple, внутри которого коллекция именованых TradeDeal. Для того чтобы работало надо обратится по какому-то индексу:

r = mt5.history_deals_get(position=544536443)
print(r[0]._asdict())
 
Дмитрий Прокопьев:

 mt5.symbol_info()._asdict() -big thnx, то что надо.

history_deals_get походу не попадает в structure sequence ... хех.


Попробуйте так:

import MetaTrader5 as mt5
# выведем данные о пакете MetaTrader5
print("MetaTrader5 package author: ",mt5.__author__)
print("MetaTrader5 package version: ",mt5.__version__)

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

# проверим наличие открытых позиций
positions=mt5.positions_total()
if(positions>0):
    print("Total positions=",positions)
    # выведем все открытые позиции
    positions=mt5.positions_get()
    count=0
    for position in positions:
        count+=1
        print(count,":",position)
        position_info=position._asdict()
        for property in position_info:
            print("   ",property,"=",position_info[property])
        if count>=5:
            break
else:
    print("Positions not found")

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

Результат

MetaTrader5 package author:  MetaQuotes Software Corp.
MetaTrader5 package version:  5.0.27
Total positions= 80
1 : TradePosition(ticket=543426097, time=1584009003, time_msc=1584009003243, time_update=1584009003, time_update_msc=1584009003243, type=1, magic=0, identifier=543426097, reason=3, volume=0.01, price_open=1.12686, sl=1.14372, tp=1.10328, price_current=1.10665, swap=-0.01, profit=20.21, symbol='EURUSD', comment='', external_id='')
    ticket = 543426097
    time = 1584009003
    time_msc = 1584009003243
    time_update = 1584009003
    time_update_msc = 1584009003243
    type = 1
    magic = 0
    identifier = 543426097
    reason = 3
    volume = 0.01
    price_open = 1.12686
    sl = 1.14372
    tp = 1.10328
    price_current = 1.10665
    swap = -0.01
    profit = 20.21
    symbol = EURUSD
    comment = 
    external_id = 
2 : TradePosition(ticket=543438758, time=1584009602, time_msc=1584009602982, time_update=1584009602, time_update_msc=1584009602982, type=1, magic=0, identifier=543438758, reason=3, volume=0.01, price_open=1.1261700000000001, sl=1.14566, tp=1.09924, price_current=1.10665, swap=-0.01, profit=19.52, symbol='EURUSD', comment='', external_id='')
    ticket = 543438758
    time = 1584009602
    time_msc = 1584009602982
    time_update = 1584009602
    time_update_msc = 1584009602982
    type = 1
    magic = 0
    identifier = 543438758
    reason = 3
    volume = 0.01
    price_open = 1.1261700000000001
    sl = 1.14566
    tp = 1.09924
    price_current = 1.10665
    swap = -0.01
    profit = 19.52
    symbol = EURUSD
    comment = 
    external_id = 
3 : TradePosition(ticket=543438858, time=1584009610, time_msc=1584009610242, time_update=1584009610, time_update_msc=1584009610242, type=1, magic=0, identifier=543438858, reason=3, volume=0.02, price_open=1.12622, sl=1.14531, tp=1.09973, price_current=1.10665, swap=-0.02, profit=39.14, symbol='EURUSD', comment='', external_id='')
    ticket = 543438858
    time = 1584009610
    time_msc = 1584009610242
    time_update = 1584009610
    time_update_msc = 1584009610242
    type = 1
    magic = 0
    identifier = 543438858
    reason = 3
    volume = 0.02
    price_open = 1.12622
    sl = 1.14531
    tp = 1.09973
    price_current = 1.10665
    swap = -0.02
    profit = 39.14
    symbol = EURUSD
    comment = 
    external_id = 
4 : TradePosition(ticket=543521116, time=1584014410, time_msc=1584014410921, time_update=1584014410, time_update_msc=1584014410921, type=1, magic=0, identifier=543521116, reason=3, volume=0.02, price_open=1.1245, sl=1.14334, tp=1.09808, price_current=1.10665, swap=-0.02, profit=35.7, symbol='EURUSD', comment='', external_id='')
    ticket = 543521116
    time = 1584014410
    time_msc = 1584014410921
    time_update = 1584014410
    time_update_msc = 1584014410921
    type = 1
    magic = 0
    identifier = 543521116
    reason = 3
    volume = 0.02
    price_open = 1.1245
    sl = 1.14334
    tp = 1.09808
    price_current = 1.10665
    swap = -0.02
    profit = 35.7
    symbol = EURUSD
    comment = 
    external_id = 
5 : TradePosition(ticket=543686473, time=1584024008, time_msc=1584024008400, time_update=1584024008, time_update_msc=1584024008400, type=1, magic=0, identifier=543686473, reason=3, volume=0.01, price_open=1.12238, sl=1.13967, tp=1.09793, price_current=1.10665, swap=-0.01, profit=15.73, symbol='EURUSD', comment='', external_id='')
    ticket = 543686473
    time = 1584024008
    time_msc = 1584024008400
    time_update = 1584024008
    time_update_msc = 1584024008400
    type = 1
    magic = 0
    identifier = 543686473
    reason = 3
    volume = 0.01
    price_open = 1.12238
    sl = 1.13967
    tp = 1.09793
    price_current = 1.10665
    swap = -0.01
    profit = 15.73
    symbol = EURUSD
    comment = 
    external_id = 
 
Almaz:

history_deals_get  всегда возвращает обычный Python tuple, внутри которого коллекция именованых TradeDeal. Для того чтобы работало надо обратится по какому-то индексу:

Ага, спасибо большое, это уже по аналогии нашел. Сенкс.

А вдруг, в будущих релизах появится возможность не только выбирать с history_deals_get  (и аналогов) именованные tuple, но и скажем list[_asdict()] будет просто

фантастично. ;) Спасибо.

 
Rashid Umarov:

Попробуйте так:

Результат

Спасибо! Все получается.

Да и спасибо, что реагируете на :) пожелания в доработке либы.

 
Rashid Umarov:

Обновитесь до 5.0.27

Заупстите скрипт

Результаты

День добрый.

Рашид, а по либе MetaTrader5 есть где-то на сайте, что-то типа Product Update Announcement?

Чтобы можно было отслеживать, когда и какие изменения вышли.

А то планировать рефакторинг чуть сложно.


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

День добрый.

Рашид, а по либе MetaTrader5 есть где-то на сайте, что-то типа Product Update Announcement?

Чтобы можно было отслеживать, когда и какие изменения вышли.

А то планировать рефакторинг чуть сложно.


Я смотрю Pypi.  Разработчики ждут от нас замечаний для продолжения/улучшения. Но пока не видно активности пользователей в этой области. 

В отдельной ветке думаю нужно обсудить общие вопросы инфраструктуры для комплексов торговых систем(терминал(МТ4/МТ5)<-> ТС(на разных ЯП) <_> базы данных разные. Различные конфигурации , проблемы, сложности, преимущества. как подготовлюсь выложу.

Удачи

Причина обращения: