Группа пользователей MetaTrader 5 Python - краткое содержание - страница 10

 

Привет,

Я вижу symbol_info_tick, но как насчет symbol_info на таймфрейм, чтобы получить последнюю цену.

Есть ли какой-нибудь пример скрипта, который получает последние цены в датафрейм и затем открывает покупку или продажу на основе параметра? для python с MT5

Спасибо
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Positioning Constants
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Positioning Constants
  • www.mql5.com
Constants, Enumerations and Structures / Chart Constants / Positioning Constants - Reference on algorithmic/automated trading language for MetaTrader 5
 
Дмитрий Прокопьев:

Хм... У меня не возникло никаких трудностей с установкой.


Постоянно появляется сообщение об обновлении pip, но это никак не связано с установкой.

Пожалуйста, покажите журналы ошибок. Не видя ошибки сложно что-то сказать.

(venv) C:\Users\nicholi\PycharmProjects\mt5_doesnt_work_with_pip_inside_virualenv>pip --version
pip 19.0.3 from C:\Users\nicholi\PycharmProjects\mt5_doesnt_work_with_pip_inside_virualenv\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip (python
3.8)

(venv) C:\Users\nicholi\PycharmProjects\mt5_doesnt_work_with_pip_inside_virualenv>pip install MetaTrader5
Collecting MetaTrader5
  Could not find a version that satisfies the requirement MetaTrader5 (from versions: )
No matching distribution found for MetaTrader5

 
nicholi shen:

Пожалуйста, покажите вывод команды python -V в virtualenv и без virtualenv.

И, пожалуйста, попробуйте установитьMetaTrader5 командой python3-mpip install , и покажите pls вывод команды.

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

Пожалуйста, покажите вывод python -V, в virtualenv и без virtualenv

И, пожалуйста, попробуйте установитьMetaTrader5 командой python3 -mpip install , и покажите pls вывод команды.

Все то же самое. Ничего не меняется. Единственный способ исправить ситуацию - обновить pip внутри venv с помощью easy_install -U pip

 
nicholi shen:

Все остается неизменным. Ничего не меняется. Единственный способ исправить ситуацию - обновить pip внутри venv с помощью easy_install -U pip

Не понимаю... Нужно следить за локальной установкой python, переменной PATH и т.д., это не правильно ...

 

Форум о трейдинге, автоматизированных торговых системах и тестировании торговых стратегий

MetaTrader 5 Python User Group - как использовать Python в Metatrader

Рашид Умаров, 2020.03.13 09:42

Обновитесь до версии 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.


 
Sergey Golubev:

Можно ли получить символ графика, на который падает скрипт python, подобно Symbol() в MQL-программе?

 
nicholi shen:

Можно ли получить символ графика, на который падает скрипт python, подобно Symbol() в MQL-программе?

Возможно, нужно использовать функцию symbol_select или symbol_info:

https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolinfo_py

Documentation on MQL5: Integration / MetaTrader for Python / symbol_info
Documentation on MQL5: Integration / MetaTrader for Python / symbol_info
  • www.mql5.com
Return info in the form of a named tuple structure (namedtuple). Return None in case of an error. The info on the error can be obtained using last_error().
 

пример скрипта для закрытия всех открытых позиций, уменьшающего экспозицию самым быстрым способом на нетто- или хеджированных счетах.


import MetaTrader5 as mt5


def raw_order(**kwargs):
    return mt5.order_send(kwargs)


def open_position_symbols():
    symbols = sorted(
        set(p.symbol for p in mt5.positions_get()),
        key=lambda s: abs(net_position(mt5.positions_get(symbol=s))),
        reverse=True
    )
    return symbols


def net_position(positions):
    return sum(-p.volume if p.type else p.volume for p in positions)


def flatten(symbol):
    positions = mt5.positions_get(symbol=symbol)
    net_pos = net_position(positions)
    if net_pos == 0:
        return mt5.TRADE_RETCODE_DONE
    info = mt5.symbol_info_tick(symbol)
    order_type, price, comment = (
        (mt5.ORDER_TYPE_SELL, info.bid, "flatten long"),
        (mt5.ORDER_TYPE_BUY, info.ask, "flatten short")
    )[net_pos < 0]
    result = raw_order(
        action=mt5.TRADE_ACTION_DEAL,
        type=order_type,
        symbol=symbol,
        volume=abs(net_pos),
        price=price,
        comment=comment,
    )
    return result.retcode


def reconcile(symbol):
    positions = mt5.positions_get(symbol=symbol)
    if not positions:
        return mt5.TRADE_RETCODE_DONE
    try:
        long = next(p for p in positions if not p.type)
        short = next(p for p in positions if p.type)
    except StopIteration:
        return mt5.TRADE_RETCODE_ERROR
    result = raw_order(
        action=mt5.TRADE_ACTION_CLOSE_BY,
        position=long.ticket,
        position_by=short.ticket,
    )
    if result.retcode == mt5.TRADE_RETCODE_DONE:
        return reconcile(symbol)
    return mt5.TRADE_RETCODE_ERROR


def close_all():
    symbols = open_position_symbols()
    for symbol in symbols:
        if (retcode := flatten(symbol)) != mt5.TRADE_RETCODE_DONE:
            print(f"CloseAllError: did not flatten {symbol}, error code={retcode}")
    for symbol in symbols:
        if (retcode := reconcile(symbol)) != mt5.TRADE_RETCODE_DONE:
            print(f"CloseAllError: could not reconcile {symbol}, error code={retcode}")


if __name__ == "__main__":
    try:
        if mt5.initialize():
            close_all()
    finally:
        mt5.shutdown()

 
nicholi shen:

пример скрипта для закрытия всех открытых позиций, уменьшающего экспозицию самым быстрым способом на нетто- или хеджированных счетах.


Это последствия вчерашнего рыночного шторма? ;)

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