MQL Programming for Beginners: Build EAs & Custom Indicators

※記事内に広告を含む場合があります。
目次

1. Introduction

What is MQL Programming?

MQL (MetaQuotes Language) is a dedicated programming language used in the MetaTrader trading platform. MetaTrader is widely used to automate trading in financial markets and to execute analysis tools and trading strategies through programming.
Learning MQL programming allows traders to automate their own trading strategies and operate more efficiently.

The Importance of Automated Trading and Trading Strategies

In financial markets, rapid decision-making is crucial. However, manual trading by humans can be affected by emotions and lack of consistency. This is where automated trading comes in handy. Automated trading can execute trades based on pre-programmed strategies and continuously monitor the market 24 hours a day.

2. Overview of MQL Programming

History of MQL and Its Relationship with MetaTrader

MQL is a scripting language developed by MetaQuotes specifically for MetaTrader. There are two main versions, MetaTrader 4 (MT4) and MetaTrader 5 (MT5), each with its own language specifications, MQL4 and MQL5.

Differences Between MQL4 and MQL5 and How to Choose

  • MQL4:
  • Used on MetaTrader 4.
  • Simple structure, suitable for beginners.
  • Specialized for automating trading strategies.
  • MQL5:
  • Used on MetaTrader 5.
  • Allows more advanced programs (e.g., multithreading support).
  • Can utilize market depth (DOM: Depth of Market).

Choose which language to learn based on your trading goals and the platform you use.

3. Preparation for Starting MQL Programming

Required Tools and Installation Steps

  1. MetaTrader Download:
    Download MT4 or MT5 from the official MetaTrader website.
  2. Using MetaEditor:
    MetaEditor is the official tool provided as the development environment for MQL programs. It becomes available when you install MetaTrader.
  3. Create an Account:
    Register a demo or real account to simulate a real trading environment.

Prerequisites for MQL Programming That Beginners Should Know

  • Basic programming concepts (e.g., variables, conditional branching, loops).
  • Understanding a C-like syntax is important.

Basic Syntax to Learn First

int start() {
   // Program entry point
   Print("Let's start MQL programming!");
   return 0;
}

The above is a simple program example. The start() function serves as the main entry point for an MQL program.

4. Practical Program Creation

Simple EA Creation Example for Beginners

An Expert Advisor (EA) is a program that automates trading strategies. Below is an example of a simple EA code.

//+------------------------------------------------------------------+
//| Basic structure of Expert Advisor                               |
//+------------------------------------------------------------------+
int start() {
   // Retrieve current price of currency pair
   double price = Bid;

   // Simple condition: trade when current price is below a specific value
   if(price < 1.1000) {
      OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0, "Buy Order", 0, 0, Green);
   }
   return 0;
}

In this program, a buy order is placed when the price falls below a specific value (e.g., 1.1000). Write the code in MetaEditor and run it on MetaTrader after compiling.

Creating and Using Custom Indicators

Custom indicators are tools that support trading decision-making. Below is a simple example that draws a moving average line.

//+------------------------------------------------------------------+
//| Custom Indicator                                                 |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Blue

double Buffer[];

int init() {
   SetIndexBuffer(0, Buffer);
   return 0;
}

int start() {
   for(int i = 0; i < Bars; i++) {
      Buffer[i] = iMA(NULL, 0, 14, 0, MODE_SMA, PRICE_CLOSE, i);
   }
   return 0;
}

This code draws a 14-period simple moving average (SMA). Using the indicator can improve the accuracy of trade decisions.

Concrete Example of Creating Scripts to Automate Actual Trading Strategies

A script is a program that executes a specific task only once. Below is an example script that closes all current positions in one go.

//+------------------------------------------------------------------+
//| All Position Close Script                                       |
//+------------------------------------------------------------------+
int start() {
   for(int i = OrdersTotal() - 1; i >= 0; i--) {
      if(OrderSelect(i, SELECT_BY_POS) && OrderType() <= OP_SELL) {
         OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 3, Red);
      }
   }
   return 0;
}

This script immediately closes all open positions. It is a useful tool during emergencies or when adjusting trading strategies.

Detailed Explanation with Code Samples

  • Simple Structure: For beginners, it is ideal to start with one condition and one action.
  • Using Real-Time Data: By leveraging MetaTrader’s real-time data, you can immediately see the results.
  • Reference for Step-Up: Based on these examples, customize them to fit your trading style.

5. Debugging and Optimization Techniques

Debugging: Common Errors and Their Solutions

MQL programming can encounter errors in code. Below are common errors and how to address them.

1. Compile Errors

Error content: messages such as ‘unexpected token’ or ‘semicolon expected’.
Solution:

  • Check that the code does not miss semicolons (
  • Check that function brackets ({}) and conditional branches are properly closed.

2. Runtime Errors

Error content: the program behaves unexpectedly during execution.
Solution:

  • Use the Print() function to output the values at each step.
  • Check that conditional branches or loops are not causing infinite loops.

3. Function Misuse

Error content: ‘invalid function parameters’ or ‘wrong arguments count’.
Solution:

  • Check the MQL official documentation and review whether the function parameters are correct.
  • Check for spelling mistakes in the function name.

How to Use Debugging Features in MetaEditor

MetaEditor includes tools to streamline debugging.

1. Setting Breakpoints

When a breakpoint is set, the program execution can be paused at a specific point.
Method:

  1. Right-click the code line you want to debug.
  2. Select ‘Set Breakpoint’.

2. Step Execution

Execute the program one line at a time and verify each line’s behavior. This allows you to pinpoint where errors occur.

3. Variable Monitoring

Feature to check variable values in real time during execution. Adding necessary variables to the debug window is convenient.

Optimization: Ways to Improve Performance

1. Backtesting Using the Strategy Tester

The Strategy Tester is a tool that verifies the performance of an EA (Expert Advisor) using historical data.

Steps:

  1. Select ‘Tools’ → ‘Strategy Tester’ in MetaTrader.
  2. Select the EA and set the currency pair and period to test.
  3. Review the results and analyze the strategy’s effectiveness.

2. Parameter Optimization

Adjust the variables set in the EA to achieve optimal results.
Example: the period of moving averages or the width of stop loss.

3. Reducing Unnecessary Calculations

MQL programs run in real time, so reducing unnecessary calculations is important.

  • Avoid unnecessary loops.
  • Clarify necessary conditional branches.

Tools Useful During Debugging

  • Print() function: The most basic way to verify program behavior.
  • Alert() function: Displays an alert when a specific event occurs.
  • ErrorDescription() function: Tool to retrieve detailed error messages.

6. Mastering Advanced Techniques

Extending Functionality with External Libraries (DLLs)

In MQL programs, using external DLLs (Dynamic Link Libraries) enables advanced processing beyond standard MQL capabilities. For example, you can implement custom calculation algorithms or integrate with external databases.

Examples of Using DLLs

  • Advanced Statistical Analysis: Compute complex statistics that MQL cannot handle via Python or R scripts.
  • Database Connection: Connect to an external SQL database to store trade history.

Precautions When Using DLLs

  1. Security Risks: Executing external DLLs should be done cautiously. Use DLLs obtained from trusted sources.
  2. Platform Compatibility: DLLs only run on Windows, so they are not usable on other operating systems.
  3. Using the #import directive:
    The following is an example of code to import an external DLL into the program.
   #import "myLibrary.dll"
   double CalculateSomething(double input);
   #import

Data Integration with Other Tools

1. Integration with Python

Python is a powerful tool for data analysis and machine learning. By calling Python scripts from an MQL program, you can achieve the following integrations.

  • Real-Time Data Analysis: Use Python to analyze data sent from MQL and reflect the results in trading.
  • Visualization: Use Python libraries (e.g., Matplotlib) to visualize trade history and market data.

2. Integration with Excel

In MetaTrader, it is common to export data in CSV format and analyze it in Excel. Using Excel macros, you can achieve the following integrations.

  • Automatic Aggregation of Trade History: Analyze trade history exported from MQL in Excel.
  • Strategy Simulation: Input conditions in Excel and reflect the results in the MQL program.

3. Integration with External Services Using APIs

You can use APIs from external trading platforms or data services (e.g., Alpha Vantage, Yahoo Finance) to obtain real-time data.

Developing Advanced EAs

Multi-Timeframe Analysis

By developing an EA that considers multiple timeframes (e.g., 1-minute and 1-hour charts) simultaneously, you can achieve a more reliable trading strategy.

double M15_MA = iMA(NULL, PERIOD_M15, 14, 0, MODE_SMA, PRICE_CLOSE, 0);
double H1_MA = iMA(NULL, PERIOD_H1, 14, 0, MODE_SMA, PRICE_CLOSE, 0);

if(M15_MA > H1_MA) {
   // Process buy signal
}

Automatic Lot Calculation

As part of money management, create an EA that dynamically calculates lot size based on account balance.

double CalculateLot(double riskPercent) {
   double freeMargin = AccountFreeMargin();
   return (freeMargin * riskPercent) / 100000;
}

7. FAQ Section

How to Learn MQL Programming Efficiently?

To learn MQL programming efficiently, we recommend the following steps:

  1. Read the official documentation thoroughly: The official documentation provided by MetaQuotes is optimal for understanding the basic syntax and detailed functions of MQL.
  2. Analyze sample code: Analyze the default EAs and indicators provided by MetaTrader to understand their structure.
  3. Use online tutorials: Practical learning is possible with video and blog-style tutorials.

What are the handy shortcuts in MetaEditor?

Here are some handy shortcuts to use MetaEditor efficiently:

  • F7 key: Compile the code.
  • F5 key: Start debugging the program.
  • Ctrl + Space: Enable code completion.
  • Ctrl + H: Use the search and replace function.

By using these, you can significantly improve your workflow efficiency.

What pitfalls should be avoided in EA development?

When developing an EA (Expert Advisor), please pay attention to the following points:

  1. Avoid over-optimization: Strategies overly based on past data may not work in future market conditions.
  2. Insufficient money management: If you don’t set lot size and stop loss appropriately, there’s a risk of large losses.
  3. Insufficient testing: It’s important to conduct sufficient practical tests over a long period in a demo account, not just on past data.

Where can I learn MQL for free?

Let’s use the following free resources to learn MQL:

  • MetaQuotes official documentation: Covers from basics to advanced.
  • Online forum: The MQL5 Community Forum is convenient as a place to ask questions and share code.
  • YouTube tutorials: There are many free videos specialized in MQL programming.

What tools are helpful during debugging?

Here are tools to help make debugging smoother:

  1. MetaEditor’s debugging features:
  • Check code behavior with breakpoints and step execution.
  1. Print() function:
  • Use log output to verify variable values and condition behavior.
  1. Strategy Tester:
  • Simulate EA performance and identify errors.

What should you be careful about when migrating from MQL4 to MQL5?

MQL4 and MQL5 are not fully compatible. Please check the following points when migrating:

  1. Differences in syntax:
  • In MQL5, event-driven structures such as OnStart() and OnTick() are adopted.
  1. Function changes:
  • Some MQL4 functions are deprecated in MQL5.
  1. Multithreading support:
  • MQL5 allows multithreaded processing, improving EA efficiency, but the code structure may become more complex.

8. Summary

Expanding Trading Strategy Possibilities with MQL Programming

By mastering MQL programming, you can automate your own trading strategies and go beyond the limitations of manual trading.

  • By leveraging automated trading systems (EAs), you can execute trades that are not influenced by emotions.
  • By creating custom indicators, you can gain unique market insights that conventional tools cannot provide.

MQL is a programming language exclusive to MetaTrader, but its versatility and powerful features hold the potential to significantly broaden a trader’s skill set.

Learning Resources to Move from Beginner to the Next Step

Use the following resources to further improve your MQL programming skills:

  1. Official Documentation:
    MQL4 Official Site and MQL5 Official Site provide detailed information on all syntax and functions.
  2. Community Forum:
  • On the MQL5 forum, you can receive advice from other developers and share code samples.
  1. Video Tutorials:
    Searching for “MQL programming beginner” on YouTube and other sites will yield free Japanese-language courses.
  2. Specialized Books:
    Japanese books on MQL and MetaTrader guides are helpful when learning systematically.

Reference Books

Amazon.co.jp: FXで勝ち組を目指す!メタトレーダーを使ったEA開発マスターガイド (現代の錬金術師シリーズ…

How to Keep Your Motivation While Continuing to Learn

Learning MQL programming can take time, but by focusing on the following points, you can maintain your motivation:

  • Set small goals: Start by creating simple scripts or indicators to gain a sense of accomplishment.
  • Test in real trades: Use a demo account to experience how the program works.
  • Build on successful experiences: Create simple EAs or indicators and gradually improve them, accumulating results.

In Conclusion

Through this article, we have outlined a path to learn MQL programming from basics to advanced. Whether you are just starting or already learning, use this knowledge to build your own trading strategy. Balancing programming and trading skills takes time, but the possibilities are limitless.

Related sites

EXPO blog 投資の翼

Keyword MQL(MetaQuotes Language) MQL言語とは MQL(MetaQuotes Lang…

EXPO blog 投資の翼

Keyword EA開発 EAの基本構成 EA(エキスパートアドバイザー)は、MetaTraderで動作する自動売買プロ…

※記事内に広告を含む場合があります。
佐川 直弘: MetaTraderを活用したFX自動売買の開発で15年以上の経験を持つ日本のパイオニア🔧

トレーデンシー大会'15世界1位🥇、EA-1グランプリ準優勝🥈の実績を誇り、ラジオ日経出演経験もあり!
現在は、株式会社トリロジーの役員として活動中。
【財務省近畿財務局長(金商)第372号】に登録
され、厳しい審査を経た信頼性の高い投資助言者です。


【主な活動内容】
・高性能エキスパートアドバイザー(EA)の開発と提供
・最新トレーディング技術と市場分析の共有
・FX取引の効率化と利益最大化を目指すプロの戦略紹介

トレーダー向けに役立つ情報やヒントを発信中!

This website uses cookies.