MetaTrader 5 Python User Group - Come usare Python in Metatrader - pagina 54

 

Aggiornamento alla 5.0.27

  pip install --upgrade MetaTrader5

Backup dello script

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()

Risultato

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:

Puoi dirmi di più sul timer?

Non ho controllato personalmente, solo una ricerca

 
Almaz:

5.0.27 ha già, tutte le strutture di sequenza (analogo della tupla nominata per l'API C) aggiunto il metodo _asdict()

mt5.symbol_info()._asdict() -big thnx, quello che ci serve.

history_deals_get non sembra essere nella sequenza della struttura ... heh.

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

Manca solo un costrutto che dia i nomi degli attributi, nell'ordine corretto. Se perhistory_deals_get_asdict() non è realizzabile o contraddice il concetto - almeno un analogo di _fields fromcollections.namedtuple (python), allora possiamo tirare l'ordine corretto degli attributi, non manualmente in loop, ma manualmente. Finora funziona qualcosa come:

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

e l'uscita:

          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]

Beh, o noodlecode con i loop.

 
Rashid Umarov:

Aggiornamento alla 5.0.27

Backup dello script

Risultati

Sens!

Davvero confortevole in questa parte.

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

mt5.symbol_info()._asdict() -big thnx, questo è tutto.

history_deals_get non sembra cadere nella sequenza della struttura ... heh.

Manca solo un costrutto che dia i nomi degli attributi, nell'ordine corretto. Se perhistory_deals_get_asdict() non è realizzabile o contraddice il concetto - almeno un analogo di _fields fromcollections.namedtuple (python), allora possiamo tirare l'ordine corretto degli attributi, non manualmente in loop, ma manualmente. Finora funziona qualcosa come:

e l'uscita:

O il codice noodle con i loop.

history_deals_get restituisce sempre una normale tupla Python con una collezione di TradeDeal nominati al suo interno. Per farlo funzionare, è necessario accedere a qualche indice:

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

mt5.symbol_info()._asdict() -big thnx, quello che ci serve.

history_deals_get non sembra cadere nella sequenza della struttura ... heh.


Prova in questo modo:

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()

Risultato

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 restituisce sempre una normale tupla Python con una collezione di TradeDeal nominati al suo interno. Per farlo funzionare, abbiamo bisogno di accedere a qualche indice:

Aha, grazie mille, ho già trovato questo per analogia. Sens.

E se, nelle versioni future, sarà possibile non solo selezionare tuple nominate con history_deals_get(e analoghi), ma anche dire list[_asdict()] sarà solo

fantastico. ;) Grazie.

 
Rashid Umarov:

Prova in questo modo:

Risultato

Grazie! Funziona.

Oh, e grazie per aver risposto ai :) suggerimenti per migliorare il lib.

 
Rashid Umarov:

Aggiornamento alla 5.0.27

Backup dello script

Risultati

Pomeriggio.

Rashid, c'è una sorta di annuncio di aggiornamento delprodotto da qualche parte sul sito MetaTrader5?

Vorrei sapere quando e quali cambiamenti sono stati attuati.

È un po' difficile pianificare il refactoring.


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

Buon pomeriggio.

Rashid, c'è un annuncio di aggiornamento delprodotto da qualche parte sul sito web?

In modo da poter tenere traccia di quali modifiche sono state fatte e quando.

È un po' difficile pianificare il refactoring.


Sto guardando Pypi. Gli sviluppatori stanno aspettando i nostri commenti per continuare/migliorare. Ma finora non vediamo alcuna attività degli utenti in questo settore.

Penso che abbiamo bisogno di discutere in un ramo separato i problemi di infrastruttura generale per i sistemi di trading complessi (terminale (MT4/МТ5) <-> TS (su diversi IP) <_> diversi database. Diverse configurazioni, problemi, difficoltà, vantaggi.

Buona fortuna