Mastering MQL4 OrderSend() Function

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

1. Introduction

MQL4 (MetaQuotes Language 4) is a programming language that runs on the MetaTrader 4 (MT4) platform and is used to create automated trading systems and custom indicators for financial markets such as FX and stocks. Among these, the OrderSend function plays a very important role.

The OrderSend function provides a basic function for sending trading orders directly from a program. By using this function, trade automation becomes possible, and trading orders can be placed based on specific conditions. Correctly understanding this function, which is used by a wide range of users from beginners to advanced users, is an essential step in mastering MQL4 programming.

In this article, we will explain the basic mechanism of the OrderSend function, detailed explanations of the arguments, actual usage examples, and precautions, step by step. By reading this article, you will be able to firmly acquire the basics for skillfully using the OrderSend function in MQL4.

“`html

2. What is the OrderSend Function?

The OrderSend function is a function for sending buy/sell orders in MQL4. It plays a role in automated trading systems in MetaTrader 4, issuing trading instructions programmatically. It is a very important function that all traders, from beginners to advanced users, utilize when building automation and advanced strategies.

The following explains the basic structure and overview of the OrderSend function.

Basic Structure of the OrderSend Function

The syntax of the OrderSend function is as follows:

int OrderSend(
   string symbol,          // 通貨ペア
   int cmd,                // 売買タイプ(注文タイプ)
   double volume,          // ロット数
   double price,           // 注文価格
   int slippage,           // スリッページ
   double stoploss,        // 損切り価格
   double takeprofit,      // 利確価格
   string comment,         // 注文コメント
   int magic,              // マジックナンバー
   datetime expiration,    // 有効期限
   color arrow_color       // 矢印の色
);

Basic Return Values

If the order is successful, the OrderSend function returns a “ticket number (int type)”. On the other hand, if it fails, it returns -1 and sets an error code. This error code can be obtained using the GetLastError function.

Roles of the OrderSend Function

  1. Automation of Trading
    By using the OrderSend function, traders can automate trading operations that they would normally perform manually with a program. This prevents human error and enables quick and efficient trading.
  2. Execution of Strategies
    By setting conditions within the program and executing orders based on those conditions, you can improve the accuracy of trading strategies. For example, it is possible to implement issuing orders when a specific price is reached or during a specific time period.
  3. Management of Multiple Positions
    By using a magic number (magic argument), you can identify and manage multiple positions, making management easier. This makes it possible to execute different strategies simultaneously.

“`

3. OrderSend Function Arguments

To effectively use the OrderSend function, it is important to thoroughly understand the meaning and role of each argument. This section explains the arguments of the OrderSend function one by one and describes their specific usage.

Detailed Explanation of Each Argument

1. symbol (Currency Pair)

Description
Specifies the currency pair to trade. For example, use a string such as "EURUSD" or "USDJPY".

Note

  • Be sure to use the currency pair displayed on the platform.
  • You can also specify a currency pair different from the current chart.

Example

OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "", 0, 0, Blue);

2. cmd (Trade Type/Order Type)

Description
Specifies the type of trade. Use the following constants:

  • OP_BUY: Buy at market price
  • OP_SELL: Sell at market price
  • OP_BUYLIMIT: Buy limit order
  • OP_SELLLIMIT: Sell limit order
  • OP_BUYSTOP: Buy stop order
  • OP_SELLSTOP: Sell stop order

Example

OrderSend("USDJPY", OP_BUY, 1.0, Ask, 3, 0, 0, "", 0, 0, Blue);

3. volume (Lot Size)

Description
Specifies the trade volume in lot size. For example, “1.0” represents 1 lot.

Note

  • The minimum lot size may vary depending on the broker, so check in advance.
  • It is important to set an appropriate lot size considering margin and risk management.

Example

OrderSend("GBPUSD", OP_SELL, 0.1, Bid, 2, 0, 0, "", 0, 0, Red);

4. price (Order Price)

Description
Specifies the price at which the order will be placed. Typically, Ask or Bid is used for market orders. For limit orders and stop orders, you must specify the price explicitly.

Note

  • For limit orders and stop orders, specify a price above or below the current price as appropriate.

Example

OrderSend("EURUSD", OP_BUYLIMIT, 1.0, 1.1000, 3, 0, 0, "", 0, 0, Blue);

5. slippage (Slippage)

Description
Specifies the allowable price deviation (slippage) when executing the order. The unit is points (not Pips).

Note

  • Slippage is more likely to occur in situations with volatile price movements, so it is important to set an appropriate tolerance.

Example

OrderSend("USDJPY", OP_SELL, 1.0, Bid, 5, 0, 0, "", 0, 0, Green);

6. stoploss (Stop Loss Price)

Description
Specifies the price at which to set the stop loss. It must be set in the opposite direction of the order price.

Note

  • Specify 0 if you do not want to set it.
  • It is recommended to set it appropriately based on your risk management strategy.

Example

OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 1.0950, 0, "", 0, 0, Blue);

7. takeprofit (Take Profit Price)

Description
Specifies the price at which to set the take profit. Set it in the same direction as the order price.

Note

  • Specify 0 if you do not want to set it.
  • Setting an appropriate profit-taking line can automate your trading strategy.

Example

OrderSend("GBPUSD", OP_SELL, 1.0, Bid, 3, 0, 1.2500, "", 0, 0, Red);

8. comment (Order Comment)

Description
Add an arbitrary comment to the order. This comment will be displayed in the trade history.

Example

OrderSend("USDJPY", OP_BUY, 1.0, Ask, 3, 0, 0, "Test Order", 0, 0, Yellow);

9. magic (Magic Number)

Description
Specifies a number to identify orders issued by the program. It is convenient for managing orders operating with Expert Advisors (EAs).

Example

OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "", 123456, 0, Blue);

10. expiration (Expiration)

Description
Sets the expiration time for the order. If the time expires, the order will be automatically deleted.

Note

  • If you do not set it,

Example

OrderSend("GBPUSD", OP_BUYLIMIT, 1.0, 1.3000, 3, 0, 0, "", 0, TimeCurrent() + 3600, Green);

11. arrowcolor (Arrow Color)

Description
Specifies the color of the arrow on the chart.

4. Order Type Details

When using the OrderSend function in MQL4, it is important to understand and set the order type (cmd argument) correctly. This section provides a detailed explanation of the characteristics and usage of each order type.

Order Type Categories

1. Market Orders

A market order is an order that is executed immediately at the current market price.

Types
  • OP_BUY: Issues a buy order at the current market price (Ask price).
  • OP_SELL: Issues a sell order at the current market price (Bid price).
Usage Example

Market orders are used when you want to enter the market quickly. For example, they are effective when following a specific trend.

Code Example

// 成行買い注文
OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Market Buy", 123456, 0, Blue);

// 成行売り注文
OrderSend("EURUSD", OP_SELL, 1.0, Bid, 3, 0, 0, "Market Sell", 123456, 0, Red);

2. Limit Orders

Limit orders are used when you want to execute an order at a more favorable price than the current market price.

Types
  • OP_BUYLIMIT: Issues a buy order at a price lower than the current price.
  • OP_SELLLIMIT: Issues a sell order at a price higher than the current price.
Usage Example

Effective for implementing counter-trend strategies or targeting retracements at specific price levels.

Code Example

// 買い指値注文
OrderSend("USDJPY", OP_BUYLIMIT, 1.0, 135.50, 3, 135.00, 136.00, "Buy Limit Order", 123456, 0, Green);

// 売り指値注文
OrderSend("USDJPY", OP_SELLLIMIT, 1.0, 136.50, 3, 137.00, 135.00, "Sell Limit Order", 123456, 0, Yellow);

3. Stop Orders

Stop orders are used when you want to execute an order at a less favorable price than the current market price.

Types
  • OP_BUYSTOP: Issues a buy order at a price higher than the current price.
  • OP_SELLSTOP: Issues a sell order at a price lower than the current price.
Usage Example

Effective for implementing trend-following strategies or when targeting a break of a specific price line.

Code Example

// 買い逆指値注文
OrderSend("GBPUSD", OP_BUYSTOP, 1.0, 1.3100, 3, 1.3000, 1.3200, "Buy Stop Order", 123456, 0, Blue);

// 売り逆指値注文
OrderSend("GBPUSD", OP_SELLSTOP, 1.0, 1.2900, 3, 1.3000, 1.2800, "Sell Stop Order", 123456, 0, Red);

Criteria for Selecting Order Types

Scenarios for Market Orders

  • When you want to follow the market momentum.
  • When you want to target the timing of a quick break through an important price level.

Scenarios for Limit Orders

  • When you anticipate a retracement from the current price.
  • When you want to enter based on a prediction of a trend reversal point.

Scenarios for Stop Orders

  • When you anticipate the continuation of a trend.
  • When you want to target a move that breaks a specific price line.

Selection Examples in Actual Scenarios

Scenario 1: Buying on a Retracement in an Uptrend

When the current price is in an uptrend and you predict that the price will temporarily decline before rising again:

  • Order Type: Limit Order (OP_BUYLIMIT)

Scenario 2: Breakout Strategy

When you predict that the price will break through a key resistance line:

  • Order Type: Stop Order (OP_BUYSTOP or OP_SELLSTOP)

5. Example Usage of the OrderSend Function

Here, we will explain how to use the OrderSend function in various trading scenarios, using specific code examples. This will clarify the image of using the OrderSend function in actual MQL4 programs.

Example 1: Market Orders

Code Example for Buy Order

The following code is an example of issuing a market buy order at the current Ask price.

Code Example

int ticket = OrderSend(
   "EURUSD",               // 通貨ペア
   OP_BUY,                 // 買い注文
   1.0,                    // ロット数
   Ask,                    // 現在価格
   3,                      // スリッページ
   0,                      // 損切り価格
   0,                      // 利確価格
   "Market Buy Order",     // コメント
   0,                      // マジックナンバー
   0,                      // 有効期限
   Blue                    // 矢印の色
);

if(ticket < 0) {
   Print("注文に失敗しました。エラーコード: ", GetLastError());
} else {
   Print("注文が成功しました。チケット番号: ", ticket);
}

Code Example for Sell Order

The following is an example of issuing a market sell order at the current Bid price.

Code Example

int ticket = OrderSend(
   "USDJPY",               // 通貨ペア
   OP_SELL,                // 売り注文
   0.5,                    // ロット数
   Bid,                    // 現在価格
   2,                      // スリッページ
   0,                      // 損切り価格
   0,                      // 利確価格
   "Market Sell Order",    // コメント
   123456,                 // マジックナンバー
   0,                      // 有効期限
   Red                     // 矢印の色
);

Example 2: Limit Orders

Code Example for Buy Limit Order

Issues a buy order at a price lower than the current price. For example, if the current price is 1.1200 and it drops to 1.1150, an order is placed.

Code Example

OrderSend(
   "EURUSD",
   OP_BUYLIMIT,
   1.0,
   1.1150,                // 指値価格
   3,
   1.1100,                // 損切り価格
   1.1200,                // 利確価格
   "Buy Limit Order",
   0,
   0,
   Green
);

Code Example for Sell Limit Order

Issues a sell order at a price higher than the current price. For example, if the current price is 1.1200 and it reaches 1.1250, an order is placed.

Code Example

OrderSend(
   "GBPUSD",
   OP_SELLLIMIT,
   0.5,
   1.1250,                // 指値価格
   2,
   1.1300,                // 損切り価格
   1.1200,                // 利確価格
   "Sell Limit Order",
   0,
   0,
   Yellow
);

Example 3: Stop Orders

Code Example for Buy Stop Order

Issues a buy order at a price higher than the current price. For example, if the current price is 1.1200 and it breaks through 1.1250, an order is placed.

Code Example

OrderSend(
   "USDJPY",
   OP_BUYSTOP,
   1.0,
   135.00,                // 逆指値価格
   3,
   134.50,                // 損切り価格
   135.50,                // 利確価格
   "Buy Stop Order",
   0,
   0,
   Blue
);

Code Example for Sell Stop Order

Issues a sell order at a price lower than the current price. For example, if the current price is 1.1200 and it falls below 1.1150, an order is placed.

Code Example

OrderSend(
   "EURUSD",
   OP_SELLSTOP,
   0.5,
   1.1150,                // 逆指値価格
   2,
   1.1200,                // 損切り価格
   1.1100,                // 利確価格
   "Sell Stop Order",
   0,
   0,
   Red
);

Example 4: Order Error Handling

If an order fails, you need to obtain the error code and check the cause. The following code uses the GetLastError function to retrieve error information.

Code Example

int ticket = OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Error Test", 0, 0, Blue);

if(ticket < 0) {
   int errorCode = GetLastError();
   Print("注文に失敗しました。エラーコード: ", errorCode);

   // 特定のエラーに応じた処理を追加
   if(errorCode == 134) {
      Print("証拠金不足です。ロットサイズを減らしてください。");
   } else if(errorCode == 130) {
      Print("無効なストップレベルです。価格を再確認してください。");
   }
}

Based on these examples, you can incorporate actual trading strategies into your program. In the next section, we will explain “6. Error Handling” in detail.

6. Error Handling

When using the OrderSend function in MQL4, orders may not be processed successfully. In such situations, it is important to correctly identify errors and take appropriate action. Error handling is an essential element for improving the stability and reliability of your program.

Error Detection Methods

In MQL4, check the return value of the OrderSend function, and if an error occurs, use the GetLastError function to obtain the error code.

Basic Error Check Structure

int ticket = OrderSend(
   "EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Order Test", 0, 0, Blue
);

if(ticket < 0) {
   int errorCode = GetLastError();
   Print("注文に失敗しました。エラーコード: ", errorCode);
}

If ticket returns a negative value, it means the order has failed. Then, identify the cause based on the error code.

Main Error Codes and Solutions

130: Invalid Stop Level

Cause

  • The specified stop-loss price (stoploss) or take-profit price (takeprofit) is set outside the tradable range.

Solution

  • Check the minimum stop level provided by the broker and adjust the price.
  • Normalize the price (using the NormalizeDouble function) to ensure accuracy.

Corrected Code Example

double stopLoss = NormalizeDouble(Ask - 0.0010, Digits);
double takeProfit = NormalizeDouble(Ask + 0.0020, Digits);

OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, stopLoss, takeProfit, "Normalized Price Test", 0, 0, Blue);

131: Invalid Lot Size

Cause

  • The lot size is outside the broker’s acceptable range (too small or too large).

Solution

  • Check the broker’s minimum and maximum lot sizes and specify a value within that range.

Corrected Code Example

double lotSize = 0.1;
if(lotSize < MarketInfo("EURUSD", MODE_MINLOT) || lotSize > MarketInfo("EURUSD", MODE_MAXLOT)) {
   Print("無効なロットサイズです。適切な値を設定してください。");
} else {
   OrderSend("EURUSD", OP_BUY, lotSize, Ask, 3, 0, 0, "Lot Size Test", 0, 0, Blue);
}

134: Insufficient Margin

Cause

  • There is insufficient margin to place the order.

Solution

  • Reduce the lot size or increase the margin.
  • Use the AccountFreeMargin function to check the available margin.

Corrected Code Example

double freeMargin = AccountFreeMargin();
double requiredMargin = MarketInfo("EURUSD", MODE_MARGINREQUIRED) * 1.0;

if(freeMargin < requiredMargin) {
   Print("証拠金不足です。ロットサイズを減らしてください。");
} else {
   OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Margin Test", 0, 0, Blue);
}

146: Market is Closed

Cause

  • Occurs when attempting to place an order while the market is closed.

Solution

  • Check the market hours and place orders during tradable hours.
  • Use the MarketInfo function to check the market status.

Common Error Handling Example

The following is a generic error handling code that displays an appropriate error message based on the error code.

Generic Error Handling Example

int ticket = OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Error Handling Test", 0, 0, Blue);

if(ticket < 0) {
   int errorCode = GetLastError();
   switch(errorCode) {
      case 130:
         Print("無効なストップレベルです。価格を再確認してください。");
         break;
      case 131:
         Print("無効なロットサイズです。適切な値を指定してください。");
         break;
      case 134:
         Print("証拠金不足です。ロットサイズを調整してください。");
         break;
      case 146:
         Print("市場が閉場しています。取引可能な時間帯を確認してください。");
         break;
      default:
         Print("未知のエラーが発生しました。エラーコード: ", errorCode);
         break;
   }
}

Points for Error Handling

  1. Do not ignore errors
    Improving program reliability by taking appropriate action when an error occurs.
  2. Perform pre-checks
    By checking the lot size, stop level, etc. before placing an order, you can prevent errors from occurring in the first place.
  3. Utilize log output
    Troubleshooting becomes easier by leaving detailed error information in the log using the Print function.

7. Precautions When Using the OrderSend Function

The OrderSend function is a very powerful tool for issuing trading orders in MQL4, but it requires careful attention when used. This section explains points to be aware of when using the OrderSend function and specific measures to prevent common mistakes.

Caution 1: Price Normalization (NormalizeDouble Function)

Problem

In MQL4, you may handle prices of currency pairs or instruments with different decimal places (Digits). If the calculation result of the price does not match the platform’s specifications, the order may be rejected.

Solution

You can prevent this problem by using the NormalizeDouble function to normalize (adjust the number of decimal places) the price.

Example

double stopLoss = NormalizeDouble(Ask - 0.0010, Digits);
double takeProfit = NormalizeDouble(Ask + 0.0020, Digits);

OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, stopLoss, takeProfit, "Normalized Price Test", 0, 0, Blue);

Caution 2: Stop-Loss Setting

Problem

When the market is fluctuating rapidly, slippage (price deviation at the time of order placement) may occur. If the slippage exceeds the allowable range, the order may be rejected.

Solution

You can reduce the risk of trading failure by setting an appropriate slippage value. Also, during times when rapid fluctuations are expected (such as during the release of economic indicators), it is recommended to set a wider slippage or refrain from trading, considering the risk.

Example

int slippage = 5; // 5ポイントのスリッページを許容
OrderSend("USDJPY", OP_BUY, 0.1, Ask, slippage, 0, 0, "Slippage Test", 0, 0, Green);

Caution 3: Server Response Time and Request Limits

Problem

When the broker’s server is congested, the order response time may be prolonged. Also, some brokers may generate errors if you send too many requests in a short period of time.

Solution

  • When sending multiple orders consecutively, be sure to leave an appropriate interval.
  • It is recommended to implement logic to monitor server response and incorporate a mechanism to retry in case of a timeout.

Caution 4: Checking the Minimum Stop Level

Problem

If you ignore the “minimum stop level” set by each broker, stop-loss and take-profit prices may be treated as invalid.

Solution

Use the MarketInfo function to retrieve the minimum stop level and incorporate logic to check it in advance.

Example

double minStopLevel = MarketInfo("EURUSD", MODE_STOPLEVEL) * Point;

if((Ask - minStopLevel) < NormalizeDouble(Ask - 0.0010, Digits)) {
   Print("損切り価格が最小ストップレベルを満たしていません。");
} else {
   OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, Ask - 0.0010, Ask + 0.0020, "Stop Level Check", 0, 0, Blue);
}

Caution 5: Using Magic Numbers

Problem

If multiple Expert Advisors (EAs) are running simultaneously, if you do not set a magic number, you will not be able to distinguish which EA issued which order.

Solution

Set a unique magic number for each EA and enable management of positions.

Example

int magicNumber = 123456; // 一意のマジックナンバー
OrderSend("GBPUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Magic Number Test", magicNumber, 0, Yellow);

Caution 6: Time of Day and Liquidity

Problem

During periods of low liquidity (e.g., early morning Japan time) or just before the close on weekends, spreads may widen or orders may be difficult to execute.

Solution

  • Specify the tradable time period in the program and avoid sending orders during certain times.
  • Use the TimeCurrent function to obtain the current server time and restrict trading depending on the conditions.

Example

datetime currentTime = TimeCurrent();
if(TimeHour(currentTime) >= 22 || TimeHour(currentTime) < 2) {
   Print("現在は取引を控える時間帯です。");
} else {
   OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, 0, 0, "Time Restriction Test", 0, 0, Blue);
}

Caution 7: Debugging and Logging

Problem

If the program does not function as expected, it can be difficult to identify the cause of the problem.

Solution

  • Use the Print function to log the output of important variables and functions.
  • Check the Experts tab and Journal tab for logs and check for any abnormalities.

Example

double stopLoss = NormalizeDouble(Ask - 0.0010, Digits);
Print("Stop Loss: ", stopLoss);

int ticket = OrderSend("EURUSD", OP_BUY, 1.0, Ask, 3, stopLoss, 0, "Debug Test", 0, 0, Blue);
if(ticket < 0) {
   Print("注文に失敗しました。エラーコード: ", GetLastError());
}

Proper design, taking these precautions into account, is necessary to make effective use of the OrderSend function. In the next section, “8. Summary,” we will summarize the contents so far.

8. Summary

The OrderSend function in MQL4 is a central feature that supports the automation of trading in MetaTrader 4, and is essential for realizing efficient trading strategies. In this article, we have thoroughly explained the basics and applications of the OrderSend function, and have covered the knowledge necessary to construct successful automated trading programs.

Key Points of the OrderSend Function

1. Basic Structure of the OrderSend Function

  • The OrderSend function is a function for issuing trading orders from a program, and you can flexibly set the order details by specifying various arguments.
  • As an example, settings such as currency pair (symbol), order type (cmd), lot size (volume), and price (price) are necessary.

2. Types of Orders and Usage Scenarios

  • Market orders are suitable for placing orders at the market price immediately.
  • Limit orders are effective for counter-trend strategies, and stop orders are effective for trend-following strategies or breakout strategies.

3. Detailed Understanding of Arguments

  • By appropriately setting each argument (e.g., stoploss and takeprofit), you can control the strategy in more detail.
  • It is important to utilize the NormalizeDouble function for accurate price setting.

4. Examples of Usage and Practical Code

  • We have introduced specific code examples of market orders, limit orders, and stop orders.
  • We have shown the application scenarios in each case and provided knowledge that is useful for actual trading.

5. Error Handling

  • It is important to utilize the GetLastError function to identify errors and implement appropriate handling methods based on the error code.
  • We have explained how to avoid common errors such as lot size, stop levels, and insufficient margin, with specific examples.

6. Points to Note When Using

  • We have explained points to note in practice, such as price normalization, slippage settings, and consideration of server response time.
  • We have introduced practical measures to ensure program stability, such as magic number and trading time management.

Advice for Utilizing the OrderSend Function

  1. Planned Design
  • Programs that use the OrderSend function require careful design, considering trading strategies and risk management.
  1. Logging and Debugging
  • Regularly check trading history and logs, and be ready to respond quickly if an error occurs.
  1. Understanding the Market
  • Check the broker’s trading conditions (spread, stop level, lot size, etc.) in advance and design the program accordingly.
  1. Continuous Improvement
  • By regularly updating the program in response to changes in market conditions and strategies, you can aim for better results.

We hope that through this article, your understanding of the OrderSend function has deepened and that a foundation has been laid for constructing practical MQL4 programs. As a next step, try creating your own EA (Expert Advisor) by applying the code introduced in this article to your own trading strategy.

We support your successful automated trading life!

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

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


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

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

This website uses cookies.