order_send

터미널에서 거래 서버로 요청 : 거래 작업을 수행하기 위한, 을 보냅니다. 이 함수는 OrderSend와 유사합니다.

order_send(
   request      // 요청 구조
   );

Parameters

request

[in]  필요한 거래 작업을 설명하는 MqlTradeRequest 유형 구조. 이름이 지정되지 않은 필수 매개 변수. 요청 및 열거 내용 작성의 예가 아래에 설명되어 있습니다.

반환 값

MqlTradeResult 구조로의 실행 결과. 응답의 요청 필드에는 order_send()에 전달된 거래 요청 구조가 포함되어 있습니다. 오류에 대한 정보는 last_error()를 사용하여 얻을 수 있습니다.

MqlTradeRequest 거래 요청 구조

Field

Description

action

거래 작업 유형. 이 값은 TRADE_REQUEST_ACTIONS 열거값 중 하나일 수 있습니다

magic

EA ID. 거래 주문의 분석 처리를 수행할 수 있습니다. 거래 요청 전송 시 각 EA에서 고유 ID를 설정할 수 있습니다

order

주문 티켓. 보류 중인 주문을 수정하는 데 필요

symbol

주문이 배치된 거래 상품의 이름. 주문 수정 및 마감 포지션에는 필요하지 않음

volume

요청된 거래량(lot). 실제 거래량은 주문 실행 유형에 따라 달라집니다.

price

주문을 실행할 가격. "마켓 실행" (SYMBOL_TRADE_EXECUTION_MARKET) 유형의 계측기에 대해 TRADE_ACTION_DEAL 유형을 보유한 시장 주문의 경우 가격이 설정되지 않습니다

stoplimit

보류중 Limit 주문 당 가격이 'price' 값에 도달하면 설정됩니다(이 조건은 필수). 보류 중인 주문이 해당 시점까지 거래 시스템으로 전달되지 않습니다.

sl

A price a Stop Loss 주문은 가격이 좋지 않은 방향으로 움직일 때 활성화됩니다

tp

A price a Take Profit 주문은 가격이 유리한 방향으로 움직일 때 활성화됩니다

deviation

요청된 가격에서 허용되는 최태 편차, 다음에 지정됨:포인트

type

주문 유형. 이 값은 ORDER_TYPE 열거값 중 하나일 수 있습니다

type_filling

주문 작성 유형. 이 값은 ORDER_TYPE_FILLING 값들 중 하나일 수 있습니다

type_time

만기별 주문유형. 이 값은 ORDER_TYPE_TIME 값들 중 하나일 수 있습니다

expiration

보류 주문 만료 시간 (TIME_SPECIFIED 유형 주문용)

comment

주문에 코멘트달기

position

Position ticket. 포지션을 변경하고 닫을 때 명확한 식별을 위해 포지션을 채웁니다. 보통, 그것은 그 포지션을 오픈한 주문의 티켓과 같습니다.

position_by

반대 포지션 티켓. 반대쪽(같은 기호이지만 반대 방향으로 오픈)으로 포지션을 닫을 때 사용됩니다.

참고

거래 요청은 거래 서버에서 여러 검증 단계를 통과합니다. 먼저 필요한 모든 요청 필드의 유효성을 확인합니다. 오류가 없으면, 서버는 추가 처리를 위해 주문을 수락합니다. 거래 작업 실행에 대한 자세한 내용은 OrderSend 함수 설명을 참조하십시오.

예:

import time
import MetaTrader5 as mt5
 
# MetaTrader 5 패키지에 데이터 표시
print("MetaTrader5 패키지 저자: "mt5.__author__)
print("MetaTrader5 패키지 버전: "mt5.__version__)
 
# MetaTrader 5 터미널과의 연결 설정
if not mt5.initialize():
    print("initialize() 실패, 오류 코드 =",mt5.last_error())
    quit()
 
# 매수 요청 구조를 준비
symbol = "USDJPY"
symbol_info = mt5.symbol_info(symbol)
if symbol_info is None:
    print(심볼, "찾을 수 없음, order_check() 호출 불가")
    mt5.shutdown()
    quit()
 
# 심볼을 MarketWatch에서 사용할 수 없는 경우 추가
if not symbol_info.visible:
    print(심볼, "보이지 않음, trying to switch on")
    if not mt5.symbol_select(symbol,True):
        print("symbol_select({}}) failed, exit",symbol)
        mt5.shutdown()
        quit()
 
lot = 0.1
point = mt5.symbol_info(symbol).point
price = mt5.symbol_info_tick(symbol).ask
deviation = 20
request = {
    "action"mt5.TRADE_ACTION_DEAL,
    "symbol"symbol,
    "volume"lot,
    "type"mt5.ORDER_TYPE_BUY,
    "price"price,
    "sl"price - 100 * point,
    "tp"price + 100 * point,
    "deviation"deviation,
    "magic"234000,
    "comment""python script open",
    "type_time"mt5.ORDER_TIME_GTC,
    "type_filling"mt5.ORDER_FILLING_RETURN,
}
 
# 거래 요청 전송
result = mt5.order_send(request)
# 실행 결과 확인
print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation));
if result.retcode != mt5.TRADE_RETCODE_DONE:
    print("2. order_send failed, retcode={}".format(result.retcode))
   # 결과를 사전으로 요청하여 요소별로 표시
    result_dict=result._asdict()
    for field in result_dict.keys():
        print("   {}={}".format(field,result_dict[field]))
        # 거래 요청 구조인 경우 요소별로도 표시
        if field=="request":
            traderequest_dict=result_dict[field]._asdict()
            for tradereq_filed in traderequest_dict:
                print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
    print("shutdown() and quit")
    mt5.shutdown()
    quit()
 
print("2. order_send done, "result)
print("   opened position with POSITION_TICKET={}".format(result.order))
print("   sleep 2 seconds before closing position #{}".format(result.order))
time.sleep(2)
# 마감 요청 생성
position_id=result.order
price=mt5.symbol_info_tick(symbol).bid
deviation=20
request={
    "action"mt5.TRADE_ACTION_DEAL,
    "symbol"symbol,
    "volume"lot,
    "type"mt5.ORDER_TYPE_SELL,
    "position"position_id,
    "price"price,
    "deviation"deviation,
    "magic"234000,
    "comment""python script close",
    "type_time"mt5.ORDER_TIME_GTC,
    "type_filling"mt5.ORDER_FILLING_RETURN,
}
# 거래 요청 전송
result=mt5.order_send(request)
# 실행 결과 확인
print("3. close position #{}: sell {} {} lots at {} with deviation={} points".format(position_id,symbol,lot,price,deviation));
if result.retcode != mt5.TRADE_RETCODE_DONE:
    print("4. order_send failed, retcode={}".format(result.retcode))
    print("   result",result)
else:
    print("4. position #{} closed, {}".format(position_id,result))
   # 결과를 사전으로 요청하여 요소별로 표시
    result_dict=result._asdict()
    for field in result_dict.keys():
        print("   {}={}".format(field,result_dict[field]))
        # 거래 요청 구조인 경우 요소별로도 표시
        if field=="request":
            traderequest_dict=result_dict[field]._asdict()
            for tradereq_filed in traderequest_dict:
                print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
 
# MetaTrader 5 터미널 연결 종료
mt5.shutdown()
 
Result
MetaTrader5 패키지 작성자:  MetaQuotes Software Corp.
MetaTrader5 패키지 버전:  5.0.29
1. order_send(): by USDJPY 0.1 lots at 108.023 with deviation=20 points
2. order_send done,  OrderSendResult(retcode=10009, deal=535084512, order=557416535, volume=0.1, price=108.023, ...
   opened position with POSITION_TICKET=557416535
   sleep 2 seconds before closing position #557416535
3. close position #557416535: sell USDJPY 0.1 lots at 108.018 with deviation=20 points
4. position #557416535 closed, OrderSendResult(retcode=10009, deal=535084631, order=557416654, volume=0.1, price=...
   retcode=10009
   deal=535084631
   order=557416654
   volume=0.1
   price=108.015
   bid=108.015
   ask=108.02
   comment=Request executed
   request_id=55
   retcode_external=0
   request=TradeRequest(action=1, magic=234000, order=0, symbol='USDJPY', volume=0.1, price=108.018, stoplimit=0.0, ...
       traderequest: action=1
       traderequest: magic=234000
       traderequest: order=0
       traderequest: symbol=USDJPY
       traderequest: volume=0.1
       traderequest: price=108.018
       traderequest: stoplimit=0.0
       traderequest: sl=0.0
       traderequest: tp=0.0
       traderequest: deviation=20
       traderequest: type=1
       traderequest: type_filling=2
       traderequest: type_time=0
       traderequest: expiration=0
       traderequest: comment=python script close
       traderequest: position=557416535
       traderequest: position_by=0

더 보기

order_check, OrderSend,Trading operation types, Trading request structure, Structure of the trading request check results, Structure of the trading request result