개요
MQL5 의 주문함수.
- 1개의 함수 OrderSend 에서 인자를 달리하여 진입, 정정, 취소, 청산이 이뤄진다.
함수 OrderSend : 본 함수 호출하면 브로커 서버의 응답을 받아야 리턴되는 함수.
함수 OrderSendAsync : 브로커 서버 응답대기없이 함수 호출 즉시 리턴된다.
함수 OrderSelect : 주문 선택하는 함수.
함수 OrderSend
- 주문의 진입, 수정, 취소, 청산.
함수정의.
bool OrderSend(
MqlTradeRequest& request, // query struct
MqlTradeResult& result // struct of the answer
);
반환값.
함수 실행성공시 : true
- 실행성공의 의미는 거래업체 서버에서 정상적으로 주문 "접수" 했다는 의미. <- 거래(=체결) 되었다는 의미 아님.
함수 실행 실패시 : false
- OrderSend fail 시 다양한 원인및 해결책 : http://igotit.tistory.com/1833
- 실패의 사유는 아래 함수인자의 구조체 MqlTradeResult 로 제공됨.
함수인자.
request
- 구조체 MqlTradeRequest 변수의 포인터.
- 구조체 MqlTradeRequest 아래 박스글에 별도 정리.
result
- 구조체 MqlTradeResult 타입의 포인터. OrderSend 반환값이 True 일때 주문 처리의 결과 정보들.
- 구조체 MqlTradeResult 아래 별도 정리.
구조체 MqlTradeRequest
상기 함수 OrderSend 인자로 사용되는 구조체 MqlTradeRequest 상세 정리.
구조체 MqlTradeRequest 타입 정의.
struct MqlTradeRequest
{
ENUM_TRADE_REQUEST_ACTIONS action; // Trade operation type
ulong magic; // Expert Advisor ID (magic number)
ulong order; // Order ticket
string symbol; // Trade symbol
double volume; // Requested volume for a deal in lots
double price; // Price
double stoplimit; // StopLimit level of the order
double sl; // Stop Loss level of the order
double tp; // Take Profit level of the order
ulong deviation; // Maximal possible deviation from the requested price
ENUM_ORDER_TYPE type; // Order type
ENUM_ORDER_TYPE_FILLING type_filling; // Order execution type
ENUM_ORDER_TYPE_TIME type_time; // Order expiration type
datetime expiration; // Order expiration time (for the orders of ORDER_TIME_SPECIFIED type)
string comment; // Order comment
ulong position; // Position ticket
ulong position_by; // The ticket of an opposite position
};
구조체 MqlTradeRequest 멤버변수 상세.
action
- 주문 타입. 아래 값들 중 1개 지정.
ENUM_TRADE_REQUEST_ACTIONS
Identifier | Description |
TRADE_ACTION_DEAL | Place a trade order for an immediate execution with the specified parameters (market order) |
TRADE_ACTION_PENDING | Place a trade order for the execution under specified conditions (pending order) |
TRADE_ACTION_SLTP | Modify Stop Loss and Take Profit values of an opened position |
TRADE_ACTION_MODIFY | Modify the parameters of the order placed previously |
TRADE_ACTION_REMOVE | Delete the pending order placed previously |
TRADE_ACTION_CLOSE_BY | Close a position by an opposite one |
magic
사용자 정의 주문 아이디. 활용은 개발자 목적에 맞게 임의로 숫자 할당하면됨.
- 주용도 : 동일 종목에 2개 이상의 다른 EA 를 적용하여 주문하는 경우 어떤 EA 에서의 주문인지 식별 용도 .
order
신규진입주문 아이디. 지정가 신규진입주문 수정주문시 주로 활용됨.
symbol
주문 종목. 주문수정이나 청산에서는 필요없음.
volume
주문수량. 랏단위.
price
주문가격.
stoplimit
Limit 지정가 주문에서 가격이 stoplimit 가 된 경우 주문시행됨.
sl
손절가격.
tp
익절가격.
deviation
최대 가격차 포인트 단위. MQL4 에서의 slippage 에 해당하는것.
type
주문타입. 아래 값들중 1개 지정.
ENUM_ORDER_TYPE
type_filling
주문 시행 타입. 아래 값 중 1개 지정.
ENUM_ORDER_TYPE_FILLING
type_time
주문 expiration 타입. 아래 값 중 1개 지정.
ENUM_ORDER_TYPE_TIME
expiration
주문 expiration 시간. 앞의 type_time 에서 지정한 형식의 시간을 기록해야함.
comment
주문 관련 커멘트. 사용자 필요에 맞게 아무거나 기록해도됨. 기록 가능 최대문자수 31
position
포지션의 티켓(고유아이디) . 포지션 수정시 혹은 청산시 필수 기록되어야 함. 변수 order 의 티켓(고유아이디)과 동일하다.
position_by
반대 포지션의 티켓(고유아이디). 어떤 포지션을 동일종목의 반대 포지션으로 청산하려고 할 때의 필요함.
Identifier | Description |
ORDER_TYPE_BUY | Market Buy order |
ORDER_TYPE_SELL | Market Sell order |
ORDER_TYPE_BUY_LIMIT | Buy Limit pending order |
ORDER_TYPE_SELL_LIMIT | Sell Limit pending order |
ORDER_TYPE_BUY_STOP | Buy Stop pending order |
ORDER_TYPE_SELL_STOP | Sell Stop pending order |
ORDER_TYPE_BUY_STOP_LIMIT | Upon reaching the order price, a pending Buy Limit order is placed at the StopLimit price |
ORDER_TYPE_SELL_STOP_LIMIT | Upon reaching the order price, a pending Sell Limit order is placed at the StopLimit price |
ORDER_TYPE_CLOSE_BY | Order to close a position by an opposite one |
type_filling
주문 시행 타입. 아래 값 중 1개 지정.
ENUM_ORDER_TYPE_FILLING
Identifier | Description |
ORDER_FILLING_FOK | This filling policy means that an order can be filled only in the specified amount. If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be executed. The required volume can be filled using several offers available on the market at the moment. |
ORDER_FILLING_IOC | This mode means that a trader agrees to execute a deal with the volume maximally available in the market within that indicated in the order. In case the the entire volume of an order cannot be filled, the available volume of it will be filled, and the remaining volume will be canceled. |
ORDER_FILLING_RETURN | This policy is used only for market orders (ORDER_TYPE_BUY and ORDER_TYPE_SELL), limit and stop limit orders (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT, ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT ) and only for the symbols with Market or Exchange execution. In case of partial filling a market or limit order with remaining volume is not canceled but processed further. For the activation of the ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT orders, a corresponding limit order ORDER_TYPE_BUY_LIMIT/ORDER_TYPE_SELL_LIMIT with the ORDER_FILLING_RETURN execution type is created. |
type_time
주문 expiration 타입. 아래 값 중 1개 지정.
ENUM_ORDER_TYPE_TIME
Identifier | Description |
ORDER_TIME_GTC | Good till cancel order |
ORDER_TIME_DAY | Good till current trade day order |
ORDER_TIME_SPECIFIED | Good till expired order |
ORDER_TIME_SPECIFIED_DAY | The order will be effective till 23:59:59 of the specified day. If this time is outside a trading session, the order expires in the nearest trading time. |
expiration
주문 expiration 시간. 앞의 type_time 에서 지정한 형식의 시간을 기록해야함.
comment
주문 관련 커멘트. 사용자 필요에 맞게 아무거나 기록해도됨. 기록 가능 최대문자수 31
position
포지션의 티켓(고유아이디) . 포지션 수정시 혹은 청산시 필수 기록되어야 함. 변수 order 의 티켓(고유아이디)과 동일하다.
position_by
반대 포지션의 티켓(고유아이디). 어떤 포지션을 동일종목의 반대 포지션으로 청산하려고 할 때의 필요함.
주문 타입별 필수 구조체 멤버변수.
Request Execution
This is a trade order to open a position in the Request Execution mode (trade upon requested prices). It requires to specify the following 9 fields:
- action
- symbol
- volume
- price
- sl
- tp
- deviation
- type
- type_filling
Also it is possible to specify the "magic" and "comment" field values.
Instant Execution
This is a trade order to open a position in the Instant Execution mode (trade by current prices). It requires specification of the following 9 fields:
- action
- symbol
- volume
- price
- sl
- tp
- deviation
- type
- type_filling
Also it is possible to specify the "magic" and "comment" field values.
Market Execution
This is a trade order to open a position in the Market Execution mode. It requires to specify the following 5 fields:
- action
- symbol
- volume
- type
- type_filling
Also it is possible to specify the "magic" and "comment" field values.
Exchange Execution
This is a trade order to open a position in the Exchange Execution mode. It requires to specify the following 5 fields:
- action
- symbol
- volume
- type
- type_filling
Also it is possible to specify the "magic" and "comment" field values.
SL & TP Modification
Trade order to modify the StopLoss and/or TakeProfit price levels. It requires to specify the following 4 fields:
- action
- symbol
- sl
- tp
- position
Pending Order
Trade order to place a pending order. It requires to specify the following 11 fields:
Trade order to place a pending order. It requires to specify the following 11 fields:
- action
- symbol
- volume
- price
- stoplimit
- sl
- tp
- type
- type_filling
- type_time
- expiration
Modify Pending Order
Trade order to modify the prices of a pending order. It requires to specify the following 7 fields:
Trade order to modify the prices of a pending order. It requires to specify the following 7 fields:
- action
- order
- price
- sl
- tp
- type_time
- expiration
Delete Pending Order
Trade order to delete a pending order. It requires to specify the following 2 fields:
Trade order to delete a pending order. It requires to specify the following 2 fields:
- action
- order
구조체 MqlTradeResult
- 구조체 MqlTradeResult ref. : https://www.mql5.com/en/docs/constants/structures/mqltraderesult
구조체 MqlTradeResult 타입 정의.
struct MqlTradeResult
{
uint retcode; // Operation return code
ulong deal; // Deal ticket, if it is performed
ulong order; // Order ticket, if it is placed
double volume; // Deal volume, confirmed by broker
double price; // Deal price, confirmed by broker
double bid; // Current Bid price
double ask; // Current Ask price
string comment; // Broker comment to operation (by default it is filled by description of trade server return code)
uint request_id; // Request ID set by the terminal during the dispatch
uint retcode_external; // Return code of an external trading system
};
구조체 멤버변수.
Field | Description |
retcode | Return code of a trade server |
deal | Deal ticket, if a deal has been performed. It is available for a trade operation of TRADE_ACTION_DEAL type |
order | Order ticket, if a ticket has been placed. It is available for a trade operation of TRADE_ACTION_PENDING type |
volume | Deal volume, confirmed by broker. It depends on the order filling type |
price | Deal price, confirmed by broker. It depends on the deviation field of the trade request and/or on the trade operation |
bid | The current market Bid price (requote price) |
ask | The current market Ask price (requote price) |
comment | The broker comment to operation (by default it is filled by description of trade server return code) |
request_id | Request ID set by the terminal when sending to the trade server |
retcode_external | The code of the error returned by an external trading system. The use and types of these errors depend on the broker and the external trading system, to which trading operations are sent. |
함수 OrderSendAsync
- OrderSend 와 주문 실행하는 것은 동일하나 , 아래와 같은 큰 차이점이 있다.
1. OrderSend 함수는 서버측으로 송신이후 서버의 처리결과 응답 수신 완료되어야 함수 리턴되는데, OrderSendAsync 는 서버측으로 송신이후 즉시 리턴된다.
2. OrderSend 함수는 호출이후 주문 티켓 확보가능하나, OrderSendAsync 는 호출이후 주문 티켓 확보 안된다.
3. OrderSendAsync 주문한 이후의 서버측 처리 결과는 이벤트핸들러 OnTradeTransaction 에서 수신된다. 이곳에서 주문티켓도 확보가능하다.
함수 OrderSelect
함수 OrderGetTicket
https://www.mql5.com/en/docs/trading/ordergetticket
코드예
void OnStart()
{
//--- variables for returning values from order properties
ulong ticket;
double open_price;
double initial_volume;
datetime time_setup;
string symbol;
string type;
long order_magic;
long positionID;
//--- number of current pending orders
uint total=OrdersTotal();
//--- go through orders in a loop
for(uint i=0;i<total;i++)
{
//--- return order ticket by its position in the list
if((ticket=OrderGetTicket(i))>0)
{
//--- return order properties
open_price =OrderGetDouble(ORDER_PRICE_OPEN);
time_setup =(datetime)OrderGetInteger(ORDER_TIME_SETUP);
symbol =OrderGetString(ORDER_SYMBOL);
order_magic =OrderGetInteger(ORDER_MAGIC);
positionID =OrderGetInteger(ORDER_POSITION_ID);
initial_volume=OrderGetDouble(ORDER_VOLUME_INITIAL);
type =EnumToString(ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE)));
//--- prepare and show information about the order
printf("#ticket %u %s %G %s at %G was set up at %s",
ticket, // order ticket
type, // type
initial_volume, // placed volume
symbol, // symbol
open_price, // specified open price
TimeToString(time_setup)// time of order placing
);
}
}
//---
}
상위 정리
메타트레이더 5 체계정리. 활용법/지식 : http://igotit.tistory.com/1775
첫 등록 : 2018.0813
최종 수정 : 2022.07.27
단축 주소 : https://igotit.tistory.com/1815
'트레이딩 > 메타트레이더 코딩' 카테고리의 다른 글
메타트레이더 5. MQL5. 클래스 CTrade. 주문처리. (2) | 2018.08.25 |
---|---|
메타트레이더 . MQL5 Storage. 원격저장소. 버전 관리. (0) | 2018.08.25 |
메타트레이더 5. MQL5.Code Example. OnChartEvent. mouse, key. (0) | 2018.08.24 |
메타트레이더 5. MQL5 문자열 출력함수들. (0) | 2018.08.23 |
메타트레이더 5. MetaEditor. MQL5 EA 생성. (0) | 2018.08.19 |
댓글