MetaTrader 5 Python User Group - the summary - page 6

 

Forum on trading, automated trading systems and testing trading strategies

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

Renat Fatkhullin , 02/20/2012 00:17

Our environments are easily supported. See the compiler settings in the editor, please.

...

Tomorrow we will release a bundled new beta of the terminal and a new full-time python library. All old methods and examples are inoperative, since we rewrote api and library from scratch.

The new api set is wide and allows you to fully manage your trading and has access to open positions and transaction history.

Now you can write full-fledged robots for Metatrader directly on Python.


 

Forum on trading, automated trading systems and testing trading strategies

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

Renat Fatkhullin , 02/20/2013 17:21

New version of MetaTrader 5 for Python 5.0.18 and beta version of MetaTrader 5 build 2319:

  • beta MT5 is downloaded via Help -> Check beta version
  • python library:
    pip install --upgrade metatrader5
    

Since all api has changed, the old examples no longer work.

Here is a new functions set:

initialize(path=None)                              Establish connection with the MetaTrader 5 Terminal
wait()                                             Wait for the MetaTrader 5 Terminal to connect to a broker's server
shutdown()                                         Disconnect from the MetaTrader 5 Terminal

version ()                                          Get the MetaTrader 5 Terminal version
terminal_info()                                    Get the parameters of the MetaTrader 5 terminal
account_info()                                     Returns information of current account

copy_ticks_from(symbol, from, count, flags)                Get ticks starting from the specific date
copy_ticks_range(symbol, from, to, flags)                  Get ticks from the specified period
copy_rates_from(symbol, timeframe, from, count)            Get bars starting from the specific date
copy_rates_from_pos(symbol, timeframe, start_pos, count)   Get bars starting from the specified position
copy_rates_range(symbol, timeframe, date_from, date_to)    Get bars from the specified period

positions_total()                                          Returns the number of open positions
positions_get([symbol=\"SYMBOL\"],[ticket=TICKET])         Returns all open positions, can be filtered by symbol or ticket

orders_total()                                             Returns the number of orders
orders_get([symbol=\"SYMBOL\"],[ticket=TICKET])            Returns all orders, can be filtered by symbol or ticket

history_orders_total(from, to)                             Returns the number of orders in selected range from the history
history_orders_get(from, to)                               Returns orders in selected range from the history or filtered by position id, ticket

history_deals_total(from, to)                              Returns the number of deals in selected range from the history
history_deals_get(from, to)                                Returns deals in selected range from the history or filtered by position id, ticket

order_check(request)                                                Checks if there are enough funds to execute the required trade operation
order_send(request)                                                 Sends trade requests to a server
order_calc_margin(action, symbol, volume, price)                    Calculates the margin required for the specified order
order_calc_profit(action, symbol, volume, price_open, price_close)  Calculates the profit for the current account, in the current market conditions, based on the parameters passed

symbol_info(symbol)                                        Returns full information for a specified symbol
symbol_info_tick(symbol)                                   Returns current prices of a specified symbol
symbol_select(symbol,[enable])                             Selects a symbol in the Market Watch window or removes a symbol from the window

Example:

import MetaTrader5 as mt5
import time

mt5.initialize()
mt5.wait()

dev = 0.00010 ;
symbol = "EURUSD"
buy_price = 0

mt5.symbol_select(symbol)

time.sleep( 1 )
p = mt5.symbol_info_tick(symbol)
prev_price = p.ask

while True:
    p = mt5.symbol_info_tick(symbol)
    print(p.bid, '/' ,p.ask)
    
     if p.ask > prev_price and buy_price == 0 :
            print( "Buy " , p.ask)
            r = mt5.Buy(symbol, 0.01 )
             if r.retcode == mt5. TRADE_RETCODE_DONE :
                buy_price = p.ask;
    elif buy_price > 0 and p.ask + dev < buy_price:
        print( "Buy(close) " , p.bid)
        mt5.Close(symbol)
        buy_price = 0

    prev_price = p.ask
    time.sleep( 1 )

mt5.shutdown()

 

Forum on trading, automated trading systems and testing trading strategies

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

Renat Fatkhullin , 02/20/2013 6:09 PM

Programs in python will be launched in the terminal only in the form of scripts and will not participate in any way and will not participate in the tester of trading strategies .

This solution is for those who are engaged in deep research in python and want to:

  1. access to market information from MT5
  2. access to transaction history and open positions
  3. trade

Strategy Tester is for MQL5 programs only.

Later we will expand the library and give the opportunity to access the built-in and custom indicators from the terminal.


 
Sergey Golubev:

You have received a super-hero badge from me! Thank you!
 

Forum on trading, automated trading systems and testing trading strategies

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

Renat Fatkhullin , 02/20/14 13:49

A library for linking MT5 <-> Python with a focus on getting data.

From Python programs only requests and trade requests are going to the terminal. There is no reason to transfer mass data from python, since it does not have access to a variable MQL5 environment, but is strictly limited to the narrow interface of requests to the terminal.


Python integration has the following scope:

  1. receive market data of charts, positions and transaction history
  2. send and control trading operations
  3. run * .py files directly from the navigator
  4. attract Python developers to the Metatrader ecosystem due to ease of access to data and full-fledged trading
  5. attract narrow groups, professional groups, quantum developers from hedge funds, investment companies and banks, offering them a convenient replacement of their environment.
  6. give access to the variety of math and AI libraries available in Python

The Python library is not a replacement for MQL5 and we do not accept any requests for extension of functionality.

 

Forum on trading, automated trading systems and testing trading strategies

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

Almaz , 2020/02/14 17:18

There are no ready-made functions, but you can see how simple orders are made in __init__.py, pending orders are done similarly:

 #  internal order send
def _RawOrder(order_type, symbol, volume, price, comment=None, ticket=None):
    order = {
       "action" :     TRADE_ACTION_DEAL ,
       "symbol" :    symbol,
       "volume" :    volume,
       "type" :      order_type,
       "price" :     price,
       "deviation" : 10 ,
    }
     if comment != None:
        order[ "comment" ] = comment
     if ticket != None:
        order[ "position" ] = ticket
    r = order_send(order)
     return r

#  Buy order                
def Buy(symbol, volume, price=None, *, comment=None, ticket=None):
     #  with direct call
     if price != None:
         return _RawOrder( ORDER_TYPE_BUY , symbol, volume, price, comment, ticket)
     #  no price, we try several times with current price
     for tries in range( 10 ):
        info = symbol_info_tick(symbol)
        r = _RawOrder( ORDER_TYPE_BUY , symbol, volume, info.ask, comment, ticket)
         if r.retcode != TRADE_RETCODE_REQUOTE and r.retcode != TRADE_RETCODE_PRICE_OFF :
             break
     return r

#  Sell order
def Sell(symbol, volume, price=None, *, comment=None, ticket=None):
     #  with direct call
     if price != None:
         return _RawOrder( ORDER_TYPE_SELL , symbol, volume, price, comment, ticket)
     #  no price, we try several times with current price
     for tries in range( 10 ):
        info = symbol_info_tick(symbol)
        r = _RawOrder( ORDER_TYPE_SELL , symbol, volume, info.bid, comment, ticket)
         if r.retcode != TRADE_RETCODE_REQUOTE and r.retcode != TRADE_RETCODE_PRICE_OFF :
             break
     return r

fields passed to order_send:

action, magic, order, symbol, volume, price, stoplimit, sl, tp, deviation, type, type_filling, type_time, expiration, comment, position, position_by

they are similar: https://www.mql5.com/en/docs/trading/ordersend


 
Sergey Golubev:

2020.02.15 11:42:13.717 LiveUpdate new version build 2321 (IDE: 2321, Tester: 2321) is available


Hi, I check the beta version ,and the program repay this massage, but no "option" or "automation" to update.

Hope for your reply.


 
a378910115:
2020.02.15 11:42:13.717 LiveUpdate new version build 2321 (IDE: 2321, Tester: 2321) is available


Hi, I check the beta version ,and the program repay this massage, but no "option" or "automation" to update.

Hope for your reply.


If you are on Windows 10 64-bit for example (look at this thread if your Windows is on 32-bit: Support for 32-bit versions ends with the next MetaTrader 5 update) so connect to MetaQuotes-Demo server (open demo account with MetaQuotes-Demo), go to Help - Check Desktop Updates - Latest Beta version and wait. MT5 will be updated to the latest beta build.


if you do not need beta build (if you want to use the latest stable build) so do not connect to MetaQuotes-Demo.

Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Account Properties
  • www.mql5.com
, then each symbol positions will be closed in the same order, in which they are opened, starting with the oldest one. In case of an attempt to close positions in a different order, the trader will receive an appropriate error. There are several types of accounts that can be opened on a trade server. The type of account on which an...
 

Forum on trading, automated trading systems and testing trading strategies

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

Renat Fatkhullin , 02/20/16 10:46 a.m.

Next Friday we will make the MT5 release, while updating the documentation in parallel.

We will also edit the descriptions of old interfaces in the forum.


By default , the terminal is launched , which was the last to be launched under the user account. The directory C: \ Users \% username% \ AppData \ Roaming \ MetaQuotes \ Terminal is looked and the most recent instance is selected.

Answer codes are wrapped in tuple and are similar to answer codes in MQL5.

We will describe later in the documentation.


 

Forum on trading, automated trading systems and testing trading strategies

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

Almaz , 2020/02/17 11:10

yes, the constants prefix MT5_ is removed, here is an example of use:

from datetime import datetime
import MetaTrader5 as mt5

mt5.initialize()
mt5.wait()

print(mt5.terminal_info())
print(mt5. version ())

ticks1 = mt5.copy_ticks_from("EURAUD", datetime ( 2020 , 1 , 28 , 13 ), 10000 , mt5. COPY_TICKS_ALL )
ticks2 = mt5.copy_ticks_range("AUDUSD", datetime ( 2020 , 1 , 27 , 13 ), datetime ( 2020 , 1 , 28 , 13 , 1 ), mt5. COPY_TICKS_ALL )

rates1 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime ( 2020 , 1 , 28 , 13 ), 1000 )
rates2 = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0 , 1000 )
rates3 = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime ( 2020 , 1 , 27 , 13 ), datetime ( 2020 , 1 , 28 , 13 ))

mt5.shutdown()

print('ticks1(', len(ticks1), ')')
print('ticks2(', len(ticks2), ')')
print('rates1(', len(rates1), ')')
print('rates2(', len(rates2), ')')
print('rates3(', len(rates3), ')')

import matplotlib.pyplot as plt

plt.plot(rates2['time'], rates2['low'], 'g-')
plt.plot(rates2['time'], rates2['high'], 'r-')

plt.show()

a more complex example is an expert with trading on two moving averages without using history:

import MetaTrader5 as mt5
import time

mt5.initialize()
mt5.wait()

info = mt5.terminal_info()
if info.trade_allowed == False:
    print( "Auto-trading disabled in Terminal, enable it" )
    quit()

symbol = "EURUSD" #  currency
lot = 0.01 ;       #  buy lot
interval = 5        #  price requesting interval in sec
long_len = 11      #  long moving average length
short_len = 7      #  short moving average length
long_ma = []       #  long ma list
short_ma = []     #  short ma list
ticket = 0          #  ticket for sell

mt5.symbol_select(symbol)

#  wait some time
time.sleep( 1 )

print( "\nPreparing..." )
for i in range(long_len):
    p = mt5.symbol_info_tick(symbol)
    print(p.bid, '/' ,p.ask)
    avg = (p.ask + p.bid) / 2

    long_ma.append(avg)
     if i >= long_len - short_len:
        short_ma.append(avg)
    time.sleep(interval)

print( "\nWorking..." )
while True:
    p = mt5.symbol_info_tick(symbol)
    print(p.bid, '/' ,p.ask)
    avg = (p.ask + p.bid) / 2
    
     #  short values
    prev_short = sum(short_ma) / short_len
    short_ma.pop( 0 )
    short_ma.append(avg)
     short = sum(short_ma) / short_len
    
     #  long values
    prev_long = sum(long_ma) / long_len
    long_ma.pop( 0 )
    long_ma.append(avg)
     long = sum(long_ma) / long_len

     #  buy signal
     if prev_short < prev_long and short > long :
        print( "BUY: ([-1]:" ,prev_short, "/" ,prev_long, ", [0]:" , short , "/" , long , ")" )
        r = mt5.Buy(symbol, lot)
         if r.retcode != mt5. TRADE_RETCODE_DONE :
            print( "Buy failed: " , r)
         else :
            ticket = r.order
    elif prev_short > prev_long and short < long and ticket> 0 :
        print( "CLOSE: ([-1]:" ,prev_short, "/" ,prev_long, ", [0]:" , short , "/" , long , ")" )
        r = mt5.Sell(symbol, lot, ticket=ticket)
         if r.retcode != mt5. TRADE_RETCODE_DONE :
            print( "Sell failed: " , r)
         else :
            ticket = 0
           
    time.sleep(interval)

mt5.shutdown()

Reason: