Kiểm tra và gửi lệnh giao dịch
Nếu cần, bạn có thể giao dịch trực tiếp từ một kịch bản Python. Cặp hàm order_check
và order_send
cho phép bạn kiểm tra trước và sau đó thực hiện một hoạt động giao dịch.
Đối với cả hai hàm, tham số duy nhất là cấu trúc yêu cầu TradeRequest
(nó có thể được khởi tạo dưới dạng từ điển trong Python, xem ví dụ). Các trường của cấu trúc hoàn toàn giống với MqlTradeRequest
.
OrderCheckResult order_check(request)
Hàm order_check
kiểm tra tính chính xác của các trường yêu cầu giao dịch và sự đủ tiền để hoàn thành hoạt động giao dịch cần thiết.
Kết quả của hàm được trả về dưới dạng cấu trúc OrderCheckResult
. Nó lặp lại cấu trúc của MqlTradeCheckResult
nhưng bổ sung thêm trường request
với một bản sao của yêu cầu ban đầu.
Hàm order_check
là tương tự của OrderCheck
.
Ví dụ (MQL5/Scripts/MQL5Book/python/ordercheck.py
):
import MetaTrader5 as mt5
# thiết lập kết nối với terminal MetaTrader 5
# lấy đơn vị tiền tệ của tài khoản để biết thông tin
account_currency = mt5.account_info().currency
print("Account currency:", account_currency)
# lấy các thuộc tính cần thiết của ký hiệu giao dịch
symbol = "USDJPY"
symbol_info = mt5.symbol_info(symbol)
if symbol_info is None:
print(symbol, "not found, can not call order_check()")
mt5.shutdown()
quit()
point = mt5.symbol_info(symbol).point
# nếu ký hiệu không có trong Market Watch, thêm nó vào
if not symbol_info.visible:
print(symbol, "is not visible, trying to switch on")
if not mt5.symbol_select(symbol, True):
print("symbol_select({}) failed, exit", symbol)
mt5.shutdown()
quit()
# chuẩn bị cấu trúc yêu cầu dưới dạng từ điển
request = \
{
"action": mt5.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": 1.0,
"type": mt5.ORDER_TYPE_BUY,
"price": mt5.symbol_info_tick(symbol).ask,
"sl": mt5.symbol_info_tick(symbol).ask - 100 * point,
"tp": mt5.symbol_info_tick(symbol).ask + 100 * point,
"deviation": 10,
"magic": 234000,
"comment": "python script",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
# chạy kiểm tra và hiển thị kết quả nguyên bản
result = mt5.order_check(request)
print(result) # [?đây không có trong nhật ký trợ giúp?]
# chuyển đổi kết quả thành từ điển và xuất từng phần tử
result_dict = result._asdict()
for field in result_dict.keys():
print(" {}={}".format(field, result_dict[field]))
# nếu đây là cấu trúc của yêu cầu giao dịch, thì cũng xuất từng phần tử
if field == "request":
traderequest_dict = result_dict[field]._asdict()
for tradereq_filed in traderequest_dict:
print(" traderequest: {}={}".format(tradereq_filed,
traderequest_dict[tradereq_filed]))
# chấm dứt kết nối với terminal
mt5.shutdown()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Kết quả:
Account currency: USD
OrderCheckResult(retcode=0, balance=10000.17, equity=10000.17, profit=0.0, margin=1000.0,...
retcode=0
balance=10000.17
equity=10000.17
profit=0.0
margin=1000.0
margin_free=9000.17
margin_level=1000.017
comment=Done
request=TradeRequest(action=1, magic=234000, order=0, symbol='USDJPY', volume=1.0, price=144.128,...
traderequest: action=1
traderequest: magic=234000
traderequest: order=0
traderequest: symbol=USDJPY
traderequest: volume=1.0
traderequest: price=144.128
traderequest: stoplimit=0.0
traderequest: sl=144.028
traderequest: tp=144.228
traderequest: deviation=10
traderequest: type=0
traderequest: type_filling=2
traderequest: type_time=0
traderequest: expiration=0
traderequest: comment=python script
traderequest: position=0
traderequest: position_by=0
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
OrderSendResult order_send(request)
Hàm order_send
gửi một yêu cầu từ terminal đến máy chủ giao dịch để thực hiện một hoạt động giao dịch.
Kết quả của hàm được trả về dưới dạng cấu trúc OrderSendResult
. Nó lặp lại cấu trúc của MqlTradeResult
nhưng bổ sung thêm trường request
với một bản sao của yêu cầu ban đầu.
Hàm này là tương tự của OrderSend
.
Ví dụ (MQL5/Scripts/MQL5Book/python/ordersend.py
):
import time
import MetaTrader5 as mt5
# thiết lập kết nối với terminal MetaTrader 5
...
# gán các thuộc tính của ký hiệu đang làm việc
symbol = "USDJPY"
symbol_info = mt5.symbol_info(symbol)
if symbol_info is None:
print(symbol, "not found, can not trade")
mt5.shutdown()
quit()
# nếu ký hiệu không có trong Market Watch, thêm nó vào
if not symbol_info.visible:
print(symbol, "is not visible, trying to switch on")
if not mt5.symbol_select(symbol, True):
print("symbol_select({}) failed, exit", symbol)
mt5.shutdown()
quit()
# chuẩn bị cấu trúc yêu cầu để mua
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,
}
# gửi yêu cầu giao dịch để mở vị thế
result = mt5.order_send(request)
# kiểm tra kết quả thực hiện
print("1. order_send(): by {} {} lots at {}".format(symbol, lot, price));
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("2. order_send failed, retcode={}".format(result.retcode))
# yêu cầu kết quả dưới dạng từ điển và hiển thị từng phần tử
result_dict = result._asdict()
for field in result_dict.keys():
print(" {}={}".format(field, result_dict[field]))
# nếu đây là cấu trúc của yêu cầu giao dịch, thì cũng xuất từng phần tử
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)
# tạo yêu cầu để đóng
position_id = result.order
price = mt5.symbol_info_tick(symbol).bid
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,
}
# gửi yêu cầu giao dịch để đóng vị thế
result = mt5.order_send(request)
# kiểm tra kết quả thực hiện
print("3. close position #{}: sell {} {} lots at {}".format(position_id,
symbol, lot, price));
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))
# yêu cầu kết quả dưới dạng từ điển và hiển thị từng phần tử
result_dict = result._asdict()
for field in result_dict.keys():
print(" {}={}".format(field, result_dict[field]))
# nếu đây là cấu trúc của yêu cầu giao dịch, thì cũng xuất từng phần tử
if field == "request":
traderequest_dict = result_dict[field]._asdict()
for tradereq_filed in traderequest_dict:
print(" traderequest: {}={}".format(tradereq_filed,
traderequest_dict[tradereq_filed]))
# chấm dứt kết nối với terminal
mt5.shutdown()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
Kết quả:
1. order_send(): by USDJPY 0.1 lots at 144.132
2. order_send done, OrderSendResult(retcode=10009, deal=1445796125, order=1468026008, volume=0.1, price=144.132,...
opened position with POSITION_TICKET=1468026008
sleep 2 seconds before closing position #1468026008
3. close position #1468026008: sell USDJPY 0.1 lots at 144.124
4. position #1468026008 closed, OrderSendResult(retcode=10009, deal=1445796155, order=1468026041, volume=0.1, price=144.124,...
retcode=10009
deal=1445796155
order=1468026041
volume=0.1
price=144.124
bid=144.124
ask=144.132
comment=Request executed
request_id=2
retcode_external=0
request=TradeRequest(action=1, magic=234000, order=0, symbol='USDJPY', volume=0.1, price=144.124, stoplimit=0.0,...
traderequest: action=1
traderequest: magic=234000
traderequest: order=0
traderequest: symbol=USDJPY
traderequest: volume=0.1
traderequest: price=144.124
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=1468026008
traderequest: position_by=0
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34