MetaTrader module for integration with Python, metatrader 5 documentation.

Metatrader 5 documentation


Pip install --upgrade metatrader5 get info on the current trading account


Actual forex bonuses


MetaTrader module for integration with Python, metatrader 5 documentation.


MetaTrader module for integration with Python, metatrader 5 documentation.


MetaTrader module for integration with Python, metatrader 5 documentation.


Metatrader module for integration with python


Python is a modern high-level programming language for developing scripts and applications. It contains multiple libraries for machine learning, process automation, as well as data analysis and visualization.


Metatrader package for python is designed for convenient and fast obtaining of exchange data via interprocessor communication directly from the metatrader 5 terminal. The data received this way can be further used for statistical calculations and machine learning.


Installing the package from the command line:


Pip install metatrader5


Updating the package from the command line:


Pip install --upgrade metatrader5


Functions for integrating metatrader 5 and python


Establish a connection with the metatrader 5 terminal


Connect to a trading account using specified parameters


Close the previously established connection to the metatrader 5 terminal


Return the metatrader 5 terminal version


Return data on the last error


Get info on the current trading account


Get status and parameters of the connected metatrader 5 terminal


Get the number of all financial instruments in the metatrader 5 terminal


Get all financial instruments from the metatrader 5 terminal


Get data on the specified financial instrument


Get the last tick for the specified financial instrument


Get the last tick for the specified financial instrument


Get bars from the metatrader 5 terminal starting from the specified date


Get bars from the metatrader 5 terminal starting from the specified index


Get bars in the specified date range from the metatrader 5 terminal


Get ticks from the metatrader 5 terminal starting from the specified date


Get ticks for the specified date range from the metatrader 5 terminal


Get the number of active orders.


Get active orders with the ability to filter by symbol or ticket


Return margin in the account currency to perform a specified trading operation


Return profit in the account currency for a specified trading operation


Check funds sufficiency for performing a required trading operation


Send a request to perform a trading operation.


Get the number of open positions


Get open positions with the ability to filter by symbol or ticket


Get the number of orders in trading history within the specified interval


Get orders from trading history with the ability to filter by ticket or position


Get the number of deals in trading history within the specified interval


Get deals from trading history with the ability to filter by ticket or position


Example of connecting python to metatrader 5



  1. Download the latest version of python 3.8 from https://www.Python.Org/downloads/windows

  2. When installing python, check "add python 3.8 to PATH%" to be able to run python scripts from the command line.

  3. Install the metatrader 5 module from the command line


Pip install metatrader5


Pip install matplotlib
pip install pandas


From datetime import datetime
import matplotlib.Pyplot as plt
import pandas as pd
from pandas.Plotting import register_matplotlib_converters
register_matplotlib_converters()
import metatrader5 as mt5

# connect to metatrader 5
if not mt5.Initialize ():
print ( "initialize() failed" )
mt5 . Shutdown ()

# request connection status and parameters
print ( mt5.Terminal_info ())
# get data on metatrader 5 version
print ( mt5.Version ())

# request 1000 ticks from EURAUD
euraud_ticks = mt5.Copy_ticks_from ( "EURAUD" , datetime ( 2020 ,1,28,13), 1000 , mt5.COPY_TICKS_ALL )
# request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00
audusd_ticks = mt5.Copy_ticks_range ( "AUDUSD" , datetime ( 2020 ,1,27,13), datetime ( 2020 ,1,28,13), mt5.COPY_TICKS_ALL )

# get bars from different symbols in a number of ways
eurusd_rates = mt5.Copy_rates_from ( "EURUSD" , mt5.TIMEFRAME_M1 , datetime ( 2020 ,1,28,13), 1000 )
eurgbp_rates = mt5.Copy_rates_from_pos ( "EURGBP" , mt5.TIMEFRAME_M1 , 0 , 1000 )
eurcad_rates = mt5.Copy_rates_range ( "EURCAD" , mt5.TIMEFRAME_M1 , datetime ( 2020 ,1,27, 13 ), datetime ( 2020 ,1, 28 , 13 ))

# shut down connection to metatrader 5
mt5 . Shutdown ()

#DATA
print (' euraud_ticks (', len ( euraud_ticks ), ')')
for val in euraud_ticks [: 10 ]: print ( val )

print (' audusd_ticks (', len ( audusd_ticks ), ')')
for val in audusd_ticks [: 10 ]: print ( val )

print (' eurusd_rates (', len ( eurusd_rates ), ')')
for val in eurusd_rates [: 10 ]: print ( val )

print (' eurgbp_rates (', len ( eurgbp_rates ), ')')
for val in eurgbp_rates [: 10 ]: print ( val )

print (' eurcad_rates (', len ( eurcad_rates ), ')')
for val in eurcad_rates [: 10 ]: print ( val )

#PLOT
# create dataframe out of the obtained data
ticks_frame = pd . Dataframe ( euraud_ticks )
# convert time in seconds into the datetime format
ticks_frame ['time']=pd.To_datetime( ticks_frame ['time'], unit ='s')
# display ticks on the chart
plt.Plot(ticks_frame['time'], ticks_frame[' ask '], 'r-', label=' ask ')
plt.Plot(ticks_frame['time'], ticks_frame[' bid '], 'b-', label=' bid ')

# display the legends
plt . Legend ( loc =' upper left ')

# add the header
plt . Title (' EURAUD ticks ')

# display the chart
plt . Show ()


[ 2 , ' metaquotes - demo ', ' 16167573 ']
[ 500 , 2325 , ' 19 feb 2020 ']

euraud_ticks( 1000 )
(1580209200, 1.63412, 1.63437, 0., 0, 1580209200067, 130, 0.)
(1580209200, 1.63416, 1.63437, 0., 0, 1580209200785, 130, 0.)
(1580209201, 1.63415, 1.63437, 0., 0, 1580209201980, 130, 0.)
(1580209202, 1.63419, 1.63445, 0., 0, 1580209202192, 134, 0.)
(1580209203, 1.6342, 1.63445, 0., 0, 1580209203004, 130, 0.)
(1580209203, 1.63419, 1.63445, 0., 0, 1580209203487, 130, 0.)
(1580209203, 1.6342, 1.63445, 0., 0, 1580209203694, 130, 0.)
(1580209203, 1.63419, 1.63445, 0., 0, 1580209203990, 130, 0.)
(1580209204, 1.63421, 1.63445, 0., 0, 1580209204194, 130, 0.)
(1580209204, 1.63425, 1.63445, 0., 0, 1580209204392, 130, 0.)
audusd_ticks( 40449 )
(1580122800, 0.67858, 0.67868, 0., 0, 1580122800244, 130, 0.)
(1580122800, 0.67858, 0.67867, 0., 0, 1580122800429, 4, 0.)
(1580122800, 0.67858, 0.67865, 0., 0, 1580122800817, 4, 0.)
(1580122801, 0.67858, 0.67866, 0., 0, 1580122801618, 4, 0.)
(1580122802, 0.67858, 0.67865, 0., 0, 1580122802928, 4, 0.)
(1580122809, 0.67855, 0.67865, 0., 0, 1580122809526, 130, 0.)
(1580122809, 0.67855, 0.67864, 0., 0, 1580122809699, 4, 0.)
(1580122813, 0.67855, 0.67863, 0., 0, 1580122813576, 4, 0.)
(1580122815, 0.67856, 0.67863, 0., 0, 1580122815190, 130, 0.)
(1580122815, 0.67855, 0.67863, 0., 0, 1580122815479, 130, 0.)
eurusd_rates( 1000 )
(1580149260, 1.10132, 1.10151, 1.10131, 1.10149, 44, 1, 0)
(1580149320, 1.10149, 1.10161, 1.10143, 1.10154, 42, 1, 0)
(1580149380, 1.10154, 1.10176, 1.10154, 1.10174, 40, 2, 0)
(1580149440, 1.10174, 1.10189, 1.10168, 1.10187, 47, 1, 0)
(1580149500, 1.10185, 1.10191, 1.1018, 1.10182, 53, 1, 0)
(1580149560, 1.10182, 1.10184, 1.10176, 1.10183, 25, 3, 0)
(1580149620, 1.10183, 1.10187, 1.10177, 1.10187, 49, 2, 0)
(1580149680, 1.10187, 1.1019, 1.1018, 1.10187, 53, 1, 0)
(1580149740, 1.10187, 1.10202, 1.10187, 1.10198, 28, 2, 0)
(1580149800, 1.10198, 1.10198, 1.10183, 1.10188, 39, 2, 0)
eurgbp_rates( 1000 )
(1582236360, 0.83767, 0.83767, 0.83764, 0.83765, 23, 9, 0)
(1582236420, 0.83765, 0.83765, 0.83764, 0.83765, 15, 8, 0)
(1582236480, 0.83765, 0.83766, 0.83762, 0.83765, 19, 7, 0)
(1582236540, 0.83765, 0.83768, 0.83758, 0.83763, 39, 6, 0)
(1582236600, 0.83763, 0.83768, 0.83763, 0.83767, 21, 6, 0)
(1582236660, 0.83767, 0.83775, 0.83765, 0.83769, 63, 5, 0)
(1582236720, 0.83769, 0.8377, 0.83758, 0.83764, 40, 7, 0)
(1582236780, 0.83766, 0.83769, 0.8376, 0.83766, 37, 6, 0)
(1582236840, 0.83766, 0.83772, 0.83763, 0.83772, 22, 6, 0)
(1582236900, 0.83772, 0.83773, 0.83768, 0.8377, 36, 5, 0)
eurcad_rates( 1441 )
(1580122800, 1.45321, 1.45329, 1.4526, 1.4528, 146, 15, 0)
(1580122860, 1.4528, 1.45315, 1.45274, 1.45301, 93, 15, 0)
(1580122920, 1.453, 1.45304, 1.45264, 1.45264, 82, 15, 0)
(1580122980, 1.45263, 1.45279, 1.45231, 1.45277, 109, 15, 0)
(1580123040, 1.45275, 1.4528, 1.45259, 1.45271, 53, 14, 0)
(1580123100, 1.45273, 1.45285, 1.45269, 1.4528, 62, 16, 0)
(1580123160, 1.4528, 1.45284, 1.45267, 1.45282, 64, 14, 0)
(1580123220, 1.45282, 1.45299, 1.45261, 1.45272, 48, 14, 0)
(1580123280, 1.45272, 1.45275, 1.45255, 1.45275, 74, 14, 0)
(1580123340, 1.45275, 1.4528, 1.4526, 1.4528, 94, 13, 0)



Trading platform — user manual


The trading platform is the trader's working tool, providing all the necessary features for a successful online trading. It includes trading, technical analysis of prices and fundamental analysis, automated trading and trading from mobile devices. In addition to forex symbols, options futures and stocks can be traded from the platform.


All types of orders, price charts, technical and fundamental analysis, algorithmic and mobile trading


MetaTrader module for integration with Python, metatrader 5 documentation.


The platform provides a wide set of trading tools.


It supports four order execution modes: instant, request, market and exchange execution.


All types of orders are available in the platform, including market, pending and stop-orders. With such a diversity of order types and available execution modes, traders can implement various trading strategies for successful performance in the currency markets and stock exchanges.


The platform also features one-click trading and provides functions for trading straight from the chart.


MetaTrader module for integration with Python, metatrader 5 documentation.


MetaTrader module for integration with Python, metatrader 5 documentation.
A


The trading platform provides powerful analytical functions. 82 different analytical tools are available for analyzing currency and stock prices, including technical indicators and graphical objects.


The analytical resources of the trading platform are not limited to the built-in indicators only. The trader can additionally use the free code base of technical indicators and the market of trading applications.


There are 21 timeframes, from a minute to a month one, available for each financial instrument. Up to 100 charts of financial instruments can be open at the same time.


Virtually any trading strategy can be formalized and implemented in the form of an expert advisor, which can automatically trade for you. A trading robot never gets tired or suffers from stress; it accurately follows its algorithm and is much more responsive to market changes.


The trading platform provides all the necessary tools for expert advisor development: the powerful MQL5 language with an integrated development environment, a multicurrency tester for testing and optimizing strategies, and the code base of free trading robots.


MetaTrader module for integration with Python, metatrader 5 documentation.


MetaTrader module for integration with Python, metatrader 5 documentation.


Smartphones and tablets are indispensable in trading when you are away from your computer.


Use special trading platform versions on your iphone/ipad and android devices to trade in the financial markets on the go.


You will certainly appreciate the functionality of the mobile trading platforms that include the full support for the trading functions, broad analytical capabilities with technical indicators and other graphical objects. Of course, all these features are available from anywhere in the world 24 hours a day.


Use the mobile platform to read financial news and internal emails, as well as for instant messaging with the participants of the most popular website for traders MQL5.Community.


The platform provides powerful trading tools and a variety of additional services.


Social trading is available through the signals service. This is an easy way to copy deals of experienced traders. Choose from thousands of signal, subscribe in a couple of clicks and the selected provider's deals will be automatically copied to your account.


Market is a store where you can purchase or download for free cutting-edge trading robots and technical indicators. An application can be purchased straight from the platform. The purchase procedure is simple and secure.


If you cannot find the desired app, order one from professional developers in freelance. The service provides secure cooperation between the customer and the developer — a payment for an application is transferred only after the approval of the resulting program.


To ensure 24/7 operation of your trading robots and copied signals, rent a virtual hosting straight from your platform.



Мощная платформа для форекса и фондовых рынков


Успешный трейдинг на финансовых рынках начинается с удобной и функциональной торговой платформы. И metatrader 5 — это лучший выбор для современного трейдера!


MetaTrader module for integration with Python, metatrader 5 documentation.


Metatrader 5 — это институциональная мультирыночная платформа для торговли, технического анализа, использования автоматических торговых систем (торговых роботов) и копирования торговых сделок других трейдеров. С metatrader 5 вы можете торговать на валютном рынке (форекс, forex), фондовых биржах и фьючерсами (futures) одновременно.


Встроенный metatrader market — лучшее место, чтобы купить или арендовать торгового робота и технический индикатор


Подпишитесь на сигнал успешного трейдера, и пусть ваша платформа торгует за вас!


Торгуйте на финансовых рынках в режиме 24/5 при помощи смартфона или планшета


Заказывайте торговых роботов и технические индикаторы у опытных программистов за разумную плату


Арендуйте виртуальный хостинг для бесперебойной работы ваших роботов и подписок на торговые сигналы


Торгуйте на финансовых рынках через любой браузер в windows, mac OS X и linux


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


Дополнительные сервисы делают широкие возможности платформы поистине безграничными. В metatrader 5 встроены маркет торговых роботов, биржа разработчиков торговых стратегий, сервис копирования сделок других трейдеров и аренда виртуальной платформы (форексный VPS). Используйте их все, чтобы получить запредельные возможности в трейдинге!


MetaTrader module for integration with Python, metatrader 5 documentation.


Благодаря всем преимуществам metatrader 5 выбрали миллионы пользователей со всего мира. Специально для них мы создали крупнейшее сообщество трейдеров и приглашаем вас тоже присоединиться к MQL5.Community. Там вы сможете: бесплатно скачать тысячи торговых роботов, подписаться на торговые сигналы других трейдеров, обсудить перспективные торговые стратегии и многое другое.


Присоединяйтесь и вы узнаете, насколько много у вас единомышленников!


Скачайте metatrader 5 и убедитесь в этом сами!


Новости


Каждый начинающий трейдер мечтает стабильно и много зарабатывать на финансовых рынках. MQL5 сервисы дают уникальные возможности заработка разработчикам и трейдерам в любой стране мира, а новичкам позволяют найти свой путь в мире алготрейдинга. И эти сервисы доступны миллионам трейдеров прямо из торгового терминала metatrader.


Инвестиционная компания с международной лицензией JFD group добавила к своему мультирыночному предложению новую линейку продуктов на платформе metatrader 5. Теперь все европейские клиенты компании смогут торговать шестью биржевыми фондами ishares (ETF) без комиссии. Выбранные ETF котируются на фондовых биржах германии (XETRA), США (NYSE arca) и великобритании (XLON).


Торговая платформа metatrader 5 получила главный приз в номинации «лучшая торговая платформа» на крупнейшей ближневосточной B2B/B2C-выставке the forex expo dubai, которая прошла 16 и 17 декабря.



MQL4 reference


Metaquotes language 4 (MQL4) is a built-in language for programming trading strategies. This language is developed by metaquotes software corp. Based on their long experience in the creation of online trading platforms. Using this language, you can create your own expert advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies. Besides, using MQL4 you can create your own technical indicators (custom indicators), scripts and libraries.


MQL4 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade orders and controlling them. The metaeditor (text editor) that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily.


The brief guide contains functions, operations, reserved words, and other language constructions divided into categories, and allows finding the description of every used element of the language.


Programs written in metaquotes language 4 have different features and purposes:



  • Expert advisor is a mechanical trading system linked up to a certain chart. An expert advisor starts to run when an event happens that can be handled by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event, chart event and custom events.
    An expert advisor can both inform you about a possibility to trade and automatically trade on an account sending orders directly to a trade server. Expert advisors are stored in terminal_directory\MQL4\experts.

  • Custom indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only.
    Custom indicators are stored in terminal_directory \MQL4\indicators

  • Script is a program intended for a single execution of some actions. Unlike expert advisors, scripts do not process any actions, except for the start event (this requires the onstart handler function in a script). Scripts are stored in terminal_directory\MQL4\scripts

  • Library is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves.
    Libraries are stored in terminal_directory\MQL4\libraries

  • Include file is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of expert advisors, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions.
    Include files can be stored in the same directory as a source file - in this case the #include directive with double quotes is used. Another place to store include files is terminal_directory\MQL4\include, in this case the #include directive is used with angle brackets.




Community


Contents


Introduction


Command line


How to.


Log in to write your own article


How to export data from metatrader 5


In this tutorial we will show you how to export available data from metatrader 5 to CSV file.


Open metatrader 5 and the right click on symbol in market watch:


MetaTrader module for integration with Python, metatrader 5 documentation.


Click on symbols


MetaTrader module for integration with Python, metatrader 5 documentation.


Click on specific symbol


MetaTrader module for integration with Python, metatrader 5 documentation.


Click on bars tab


MetaTrader module for integration with Python, metatrader 5 documentation.


Select data range and click on request


Please note that data download can take some time


MetaTrader module for integration with Python, metatrader 5 documentation.


Then you will see the bars and you have to select them


MetaTrader module for integration with Python, metatrader 5 documentation.


Click on export


MetaTrader module for integration with Python, metatrader 5 documentation.


Choose folder for saving data


MetaTrader module for integration with Python, metatrader 5 documentation.


Please, note that available data in metatrader could be short. It depends what is your broker offering.


Facebook twitter blog sign up to our newsletter -->


Risk disclosure:
futures and forex trading contains substantial risk and is not for every investor. An investor could potentially lose all or more than the initial investment. Risk capital is money that can be lost without jeopardizing ones’ financial security or life style. Only risk capital should be used for trading and only those with sufficient risk capital should consider trading. Past performance is not necessarily indicative of future results.


Hypothetical performance disclosure:
hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown; in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program. One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk of actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all which can adversely affect trading results.



Welcome to MQL5.Community!


MQL5.Community features uniques services for users of metatrader 5 and metatrader 4 trading platforms: the webterminal for a full-featured technical analysis and trading, a social trading platform (with copy trading signals), the market of trading applications, the virtual hosting service, and much more.


It provides all visitors with an opportunity to freely communicate and discuss issues related to programming in metaquotes language 5 (MQL5) and metaquotes language 4 (MQL4), trading, automated trading systems, strategy testing and use of technical indicators in metatrader 5 and metatrader 4.


You will find here the full description of the language, articles on different topics, the forum, automated trading programs written in MQL4/MQL5, and many other things. Communicate with the authors of articles and applications or ask questions in the forum where you will certainly receive an answer from your fellow traders.



Metatrader® 5 trading platform


Metaquotes language 5 (MQL5) is the integrated programming language for developing indicators and trading strategies for the free-of-charge online trading platform named metatrader 5. Over a hundred of brokerage companies and banks use the platform to provide their services to customers.


Download the metatrader 5 platform for free right now! Do you want to manage your account from everywhere? The mobile platform version will help you to analyze market data and perform trades when you are away from your PC.


Services


The website homepage features the most popular trading signals, products from the market of trading applications, orders for the development of trading robots, latest articles and forum discussions.


Webterminal


Web-browser versions of the client terminal for the metatrader 5 and metatrader 4 trading platforms. Trade in financial markets from your browser, using an extensive toolkit for technical analysis. The user interface of the webterminal is available in all popular languages.


Documentation


This section features the most current description of all language functions, with notes on syntax and examples. The entire documentation can be downloaded in PDF or CHM format.


Codebase


The largest library of applications for metatrader 5 and metatrader 4 available as source codes. Here, you can download expert advisors, indicators, scripts and libraries for free. After registration, you will be able to post your developments here, as well as discuss different features and methods of using your programs.


Articles


An extensive selection of unique articles on MQL5 and MQL4 programming. Read to articles to learn about various technologies, mechanisms and programming algorithms.


Freelance


You can order desired trading applications from professional freelance developers. Are you an experienced MQL5/MQL4 developer? Are you familiar with financial trading specifics? Start executing freelance orders in the biggest automated trading freelance service.


Market


The MQL5.Community market features a wide selection of trading applications for the metatrader 5 and metatrader 4 platform, which enable traders to avoid routine operations and focus on really important things. Any application types, including technical indicators, trading robots, control panels and analysis systems, can be found in the market.


Signals


Choose a signal you are interested in and subscribe to it in a few clicks. Monitored accounts are provided with detailed statistics and trading history. Sell your trading system signals to thousands of subscribers around the world.


Virtual hosting


The virtual hosting services enables round-the-clock operation of the trading platform. Rent a virtual server straight from the platform to copy trading signals and let your robots operate 24 hours a day. A significant advantage of the service is the possibility to select a server that is closest to your broker's server, and thus to minimize network latency during trading.


Forum


Any questions related to the development and use of automated trading systems and trading ideas can be discussed in the forum. Communicate and share your experience with fellow traders from anywhere in the world or reach out to the metatrader platform developers. If you have a question, post it here, and you will certainly receive help.


MQL5 cloud network


The MQL5 cloud network enables fast optimization of trading robots. The calculations that would take months, can be completed in a few minutes using the computing power of thousands of computers. Provide resources of your computer for the cloud network and earn money.


Trademarks


All rights to the following trademarks belong to metaquotes software corp. In the russian federation and in other countries. The absence of a name or logo in this list does not constitute a waiver of any and all intellectual property rights that metaquotes software corp. Has established in any of its product, feature, or service names or logos.



  • Optimize and lead®

  • Metatrader®

  • Metatrader 5®

  • Metaquotes®

  • Metaquotes software®

  • MQL5®

  • MQL4®

  • MT4®

  • MT5®



For further details, please check metaquotes software corp.' trademark and graphics/screenshots usage guidelines.


Warning


MQL5 services mean services, including, but not limited to, MQL5 market, MQL5 signals and MQL5 freelance available on the mql5.Com website and managed by metaquotes ltd. Metaquotes ltd is not a registered investment advisor, broker/dealer, financial analyst, financial bank, securities broker or financial planner. Metaquotes ltd is a technology provider which among other things facilitates the sharing of trade information via the internet.


Users of the service may use the trade information to formulate their own investment decisions which could be to copy the trades of others. All information on the MQL5.Com is provided for information purposes only. The information is not intended to be and does not constitute financial advice or any other advice, is general in nature and not specific to you.


Before using the company's information to make an investment decision, you should seek the advice of a qualified and registered securities professional and undertake your own due diligence. None of the information on our site is intended as investment advice, as an offer or solicitation of an offer to buy or sell, or as a recommendation, endorsement, or sponsorship of any security, company, or fund. The company is not responsible for any investment decision made by you. You are responsible for your own investment research and investment decisions.


Registration


Register and get access to all resources provided by MQL5.Community. This will allow you to post messages in forums, add comments, publish your own applications, and much more.



Metatrader 5


Metatester 5 agents


One of the big improvements of the new metatrader 5 strategy tester is the possibility to use individual calculation frameworks ( agents ) to distribute the load within the multiple (remote) cores and as result, to greatly increase the speed of trading strategies optimization / calculation. The agents can be installed on remote computers in your local home/work network or on other internet-connected pc's around the world.


Thus, the time for optimization using multiple cpu core's is greatly reduced. The metatrader 5 strategy tester automatically assigns each agent the testing parameters and the interval to for the next passage. As said above, you can use any available pc, both on a local network and via the internet. To do this you need to install on the remote computers that you want to use the metatester.Exe utility. This utility is part of the metatrader 5 installation package, so there's no need for a separate download. Simply install the metatrader 5 terminal.


The remote agent receives the required testing history from the tester, so there's no need for multiple requests to the broker servers. Access to remote agents is securely protected by a password. Within the agents the following security mechanisms are implemented:


- fully encrypted network protocol between the client terminal and the remote agent with a compression of traffic;
- password protection;
- ability to specify a list of IP addresses from which connection to the client terminal is allowed;
- only local agents can use the DLL with the appropriate terminal resolution. DLL call is prohibited on remote agents;
- the transmitted EA's code is never stored on the agent's HDD, but is instead transferred in a transformed state, which is inaccessible by the dump. On remote agents, messages of expert advisors (print() function), as well time of trade operation execution, are not recorded to the journal;
- the agent does not know the name of the EA and doesn't store the miscalculation results on the HDD;
- the agent is protected by a security shield from dissemble and modification.


Here is a detailed guide how to use the remote agents. I'm going to use the dual-core cpu on my laptop as a remote agent on my desktop pc.


1. Open the metatester.Exe utility on the computer that you want to use for the remote-agent service. The metatester agents manager program metatester.Exe is located in the metatrader 5 installation folder ( default: C:\program files\metatrader 5\metatester.Exe


MetaTrader module for integration with Python, metatrader 5 documentation.

2. Specify a password and a port range for the remote agent connection. The best option is to choose port numbers that are not used by other programs. You can find a list of standard and unassigned ports here: iana.Org port numbers


MetaTrader module for integration with Python, metatrader 5 documentation.

In my example i'm using the 4435-4436 port range. Press the "add" button. The number of available local agents must be equal to the number of logical cores of the processor. In my case, i have a dual core intel cpu, so i installed 2 remote-agent services. Also, write down your ip address stated above ( in my case, 192.168.1.12 )


3. Now go to the computer where you will be using the metatrader 5 strategy tester and the remote agents. Open metatester 5 and go to the "agents" tab. You will see the "local" and "remote" tabs. The local cpu is listed on the "local" tab. Via the context menu on the "remote" tab you can add the remote agents:


MetaTrader module for integration with Python, metatrader 5 documentation.

A pop-up window will appear. You must input the password, ip address and port number that you specified earlier. In my case, i use the ip address:port number 192.168.1.12:4435 for the remote agent 1 and 192.168.1.12:4436 for the remote second agent.


4. In case you have a firewall installed on the computer with the remote-agents service running, allow the connection. You may also open the ports on your router if they are closed. I'm using the comodo firewall program, so i had to allow the outgoing connection:


MetaTrader module for integration with Python, metatrader 5 documentation.

5. After you have added all remote agents you can test them by running a EA optimization. In my case the remote agents were successfully activated


As said above, all agents are shown in a table divided into two parts - local and remote agents. The "hardware" column contains information about the type of the processor, CPU clock, RAM size and internal performance rate (the higher the rate is, the the more powerful the hardware is); CPU usage — indicator of the core usage level; status — the status of the agent: busy, ready, unavailable.


MetaTrader module for integration with Python, metatrader 5 documentation.

You can add as many remote agents as you want, so you can build your own supercomputer. The metatrader 5 strategy tester provides a solutions with the remote agents feature for complex expert advisor optimization, which traders would not dream of being able to solve without access to supercomputers.



Community


Contents


Introduction


Command line


How to.


Log in to write your own article


How to export data from quant data manager and import to metatrader 5


Metatrader 5 now allows import custom symbols and import tick and minutes data.


STEP 1: check detailed tutorial step by step how to download data from dukascopy.


STEP 2: export data from quant data manager


MetaTrader module for integration with Python, metatrader 5 documentation.


Export data from quant data manager



  1. Select date range – all time range

  2. Set correct spread in our case we are using fixed spread 8 points which is 0.8 pips. You can choose also compute spread from tick data. Please, note that in exported data you will see spread value in points not pips.

  3. Choose output path


MetaTrader module for integration with Python, metatrader 5 documentation.


Please, note that metatrader 5 doesn’t support compute higher timeframe from tick data. If you want to do it backtest with tick data precision, you need to always import M1 a tick data. Compute for higher timeframes is available only from M1 data.


Let’s import data to metatrader 5


Step 1 – open metatrader 5 and click with right mouse button to the market watch or press shortcut ctrl+U


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 2 – create custom symbol. You can copy symbol setting from your broker.


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 3 – setup the symbol name and right spread to symbol settings


Note: if you are using variable spread from tick data you have to set up floating spread instead of fixed spread 8 points


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 4 – click on show symbol


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 5 – click on bars and import bars


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 6 – choose CSV file with exported data from quant data manager


MetaTrader module for integration with Python, metatrader 5 documentation.


Now you can see progress about data importing


MetaTrader module for integration with Python, metatrader 5 documentation.


Step 7 – if you will successful, you will see window with imported data. You should see white window as you can see on this screen.


Note: if the window with imported data will be red, the backtest will not be with 99 % data quality.


MetaTrader module for integration with Python, metatrader 5 documentation.


That’s it, happy backtesting :)


Backtest from metatrader 5 with 0 % quality modeling


MetaTrader module for integration with Python, metatrader 5 documentation.


Backtest from metatrader 5 with 99 % quality modeling


MetaTrader module for integration with Python, metatrader 5 documentation.


Facebook twitter blog sign up to our newsletter -->


Risk disclosure:
futures and forex trading contains substantial risk and is not for every investor. An investor could potentially lose all or more than the initial investment. Risk capital is money that can be lost without jeopardizing ones’ financial security or life style. Only risk capital should be used for trading and only those with sufficient risk capital should consider trading. Past performance is not necessarily indicative of future results.


Hypothetical performance disclosure:
hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown; in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program. One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk of actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all which can adversely affect trading results.



MQL4 reference


Metaquotes language 4 (MQL4) is a built-in language for programming trading strategies. This language is developed by metaquotes software corp. Based on their long experience in the creation of online trading platforms. Using this language, you can create your own expert advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies. Besides, using MQL4 you can create your own technical indicators (custom indicators), scripts and libraries.


MQL4 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade orders and controlling them. The metaeditor (text editor) that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily.


The brief guide contains functions, operations, reserved words, and other language constructions divided into categories, and allows finding the description of every used element of the language.


Programs written in metaquotes language 4 have different features and purposes:



  • Expert advisor is a mechanical trading system linked up to a certain chart. An expert advisor starts to run when an event happens that can be handled by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event, chart event and custom events.
    An expert advisor can both inform you about a possibility to trade and automatically trade on an account sending orders directly to a trade server. Expert advisors are stored in terminal_directory\MQL4\experts.

  • Custom indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only.
    Custom indicators are stored in terminal_directory \MQL4\indicators

  • Script is a program intended for a single execution of some actions. Unlike expert advisors, scripts do not process any actions, except for the start event (this requires the onstart handler function in a script). Scripts are stored in terminal_directory\MQL4\scripts

  • Library is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves.
    Libraries are stored in terminal_directory\MQL4\libraries

  • Include file is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of expert advisors, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions.
    Include files can be stored in the same directory as a source file - in this case the #include directive with double quotes is used. Another place to store include files is terminal_directory\MQL4\include, in this case the #include directive is used with angle brackets.






So, let's see, what we have: metatrader for python - integration - MQL5 reference - reference on algorithmic/automated trading language for metatrader 5 at metatrader 5 documentation

Contents of the article




No comments:

Post a Comment