MetaTrader 5 Python User Group - the summary - page 10

 

Hi,

I see the symbol_info_tick, but what about a symbol_info per timeframe to get the last price.

Is there some example script that gets the latest prices into the dataframe and then opens a Buy or Sell based on a param? for python with MT5

Thank you
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
 
Дмитрий Прокопьев:

Hm ... I had no difficulty installing.


The message about updating the pip showing constantly, but this has nothing to do lib installation.

Pls, show error logs. Without seeing the error is difficult to say something.

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

Pls, show the output of python -V, in virtualenv and without virtualenv

And pls, try installing using the command python3 -m pip install MetaTrader5, and show pls output of the command.

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

Pls, show the output of python -V, in virtualenv and without virtualenv

And pls, try installing using the command python3 -m pip install MetaTrader5, and show pls output of the command.

It's the same. Nothing changes. The only way to remedy is to upgrade pip inside venv using  easy_install -U pip

 
nicholi shen:

It's the same. Nothing changes. The only way to remedy is to upgrade pip inside venv using  easy_install -U pip

Don't understanding ... Need to watch the local installation of python, variable PATH etc., it is not right ...

 

Forum on trading, automated trading systems and testing trading strategies

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

Rashid Umarov , 2020.03.13 09:42

Update to 5.0.27

  pip install --upgrade MetaTrader5

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

results

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:

Is is possible to get the symbol of the chart that a python script is dropped on, like Symbol() in an MQL program?

 
nicholi shen:

Is is possible to get the symbol of the chart that a python script is dropped on, like Symbol() in an MQL program?

Maybe you need to use the symbol_select or symbol_info function:

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

example script to close all open positions reduce exposure in the fastest way possible on either netted or hedged accounts


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:

example script to close all open positions reduce exposure in the fastest way possible on either netted or hedged accounts. 


Are these the effects of yesterday's market storm? ;)

Reason: