Đọc lịch sử các lệnh và giao dịch
Việc làm việc với các lệnh và giao dịch trong lịch sử tài khoản bằng cách sử dụng các script Python cũng là điều có thể thực hiện được. Để phục vụ cho mục đích này, có các hàm history_orders_total
, history_orders_get
, history_deals_total
, và history_deals_get
.
int history_orders_total(date_from, date_to)
Hàm history_orders_total
trả về số lượng lệnh trong lịch sử giao dịch trong khoảng thời gian được chỉ định. Mỗi tham số được thiết lập bằng đối tượng datetime
hoặc dưới dạng số giây tính từ ngày 1970.01.01.
Hàm này là một tương tự của HistoryOrdersTotal
.
Hàm history_orders_get
có sẵn trong nhiều phiên bản và hỗ trợ lọc lệnh theo chuỗi con trong tên biểu tượng, mã lệnh, hoặc ID vị thế. Tất cả các biến thể trả về một mảng của các tuple có tên TradeOrder
(tên trường khớp với ENUM_ORDER_PROPERTY_enumerations mà không có tiền tố "ORDER_" và ở dạng chữ thường). Nếu không có lệnh nào phù hợp, mảng sẽ trống. Trong trường hợp xảy ra lỗi, hàm sẽ trả về None
.
namedtuple[] history_orders_get(date_from, date_to, group = PATTERN
)
namedtuple[] history_orders_get(ticket = ORDER_TICKET
)
namedtuple[] history_orders_get(position = POSITION_ID
)
Phiên bản đầu tiên chọn các lệnh trong khoảng thời gian được chỉ định (tương tự như history_orders_total
). Trong tham số tùy chọn có tên group
, bạn có thể chỉ định một mẫu tìm kiếm cho chuỗi con của tên biểu tượng (bạn có thể sử dụng các ký tự đại diện '*' và phủ định '!' trong đó, xem phần Lấy thông tin về các công cụ tài chính).
Phiên bản thứ hai được thiết kế để tìm kiếm một lệnh cụ thể bằng mã lệnh của nó.
Phiên bản cuối cùng chọn các lệnh theo ID vị thế (thuộc tính ORDER_POSITION_ID).
Bất kỳ lựa chọn nào cũng tương đương với việc gọi nhiều hàm MQL5: HistoryOrdersTotal
, HistoryOrderSelect
, và HistoryOrderGet
-functions.
Hãy xem qua ví dụ của script historyordersget.py
để biết cách lấy số lượng và danh sách các lệnh lịch sử cho các điều kiện khác nhau.
from datetime import datetime
import MetaTrader5 as mt5
import pandas as pd
pd.set_option('display.max_columns', 500) # how many columns to show
pd.set_option('display.width', 1500) # max. table width for display
...
# get the number of orders in the history for the period (total and *GBP*)
from_date = datetime(2022, 9, 1)
to_date = datetime.now()
total = mt5.history_orders_total(from_date, to_date)
history_orders=mt5.history_orders_get(from_date, to_date, group="*GBP*")
# print(history_orders)
if history_orders == None:
print("No history orders with group=\"*GBP*\", error code={}".format(mt5.last_error()))
else :
print("history_orders_get({}, {}, group=\"*GBP*\")={} of total {}".format(from_date,
to_date, len(history_orders), total))
# display all canceled historical orders for ticket position 0
position_id = 0
position_history_orders = mt5.history_orders_get(position = position_id)
if position_history_orders == None:
print("No orders with position #{}".format(position_id))
print("error code =", mt5.last_error())
elif len(position_history_orders) > 0:
print("Total history orders on position #{}: {}".format(position_id,
len(position_history_orders)))
# display received orders as is
for position_order in position_history_orders:
print(position_order)
# display these orders as a table using pandas.DataFrame
df = pd.DataFrame(list(position_history_orders),
columns = position_history_orders[0]._asdict().keys())
df.drop(['time_expiration', 'type_time', 'state', 'position_by_id', 'reason', 'volume_current',
'price_stoplimit','sl','tp', 'time_setup_msc', 'time_done_msc', 'type_filling', 'external_id'],
axis = 1, inplace = True)
df['time_setup'] = pd.to_datetime(df['time_setup'], unit='s')
df['time_done'] = pd.to_datetime(df['time_done'], unit='s')
print(df)
...
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
Kết quả của script (được rút gọn):
history_orders_get(2022-09-01 00:00:00, 2022-09-26 21:50:04, group=`*GBP*`)=15 trong tổng số 44
Tổng số lệnh lịch sử trên vị trí #0: 14
TradeOrder(ticket=1437318706, time_setup=1661348065, time_setup_msc=1661348065049, time_done=1661348083,
time_done_msc=1661348083632, time_expiration=0, type=2, type_time=0, type_filling=2, state=2, magic=0,
position_id=0, position_by_id=0, reason=3, volume_initial=0.01, volume_current=0.01, price_open=0.99301,
sl=0.0, tp=0.0, price_current=0.99311, price_stoplimit=0.0, symbol='EURUSD', comment='', external_id='')
TradeOrder(ticket=1437331579, time_setup=1661348545, time_setup_msc=1661348545750, time_done=1661348551,
time_done_msc=1661348551354, time_expiration=0, type=2, type_time=0, type_filling=2, state=2, magic=0,
position_id=0, position_by_id=0, reason=3, volume_initial=0.01, volume_current=0.01, price_open=0.99281,
sl=0.0, tp=0.0, price_current=0.99284, price_stoplimit=0.0, symbol='EURUSD', comment='', external_id='')
TradeOrder(ticket=1437331739, time_setup=1661348553, time_setup_msc=1661348553935, time_done=1661348563,
time_done_msc=1661348563412, time_expiration=0, type=2, type_time=0, type_filling=2, state=2, magic=0,
position_id=0, position_by_id=0, reason=3, volume_initial=0.01, volume_current=0.01, price_open=0.99285,
sl=0.0, tp=0.0, price_current=0.99286, price_stoplimit=0.0, symbol='EURUSD', comment='', external_id='')
...
ticket time_setup time_done type ... _initial price_open price_current symbol comment
0 1437318706 2022-08-24 13:34:25 2022-08-24 13:34:43 2 0.01 0.99301 0.99311 EURUSD
1 1437331579 2022-08-24 13:42:25 2022-08-24 13:42:31 2 0.01 0.99281 0.99284 EURUSD
2 1437331739 2022-08-24 13:42:33 2022-08-24 13:42:43 2 0.01 0.99285 0.99286 EURUSD
...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Chúng ta có thể thấy rằng trong tháng 9, chỉ có 44 lệnh, trong đó 15 lệnh bao gồm tiền tệ GBP (số lẻ do có vị thế đang mở). Lịch sử chứa 14 lệnh bị hủy.
int history_deals_total(date_from, date_to)
Hàm history_deals_total
trả về số lượng giao dịch trong lịch sử cho khoảng thời gian được chỉ định.
Hàm này là một tương tự của HistoryDealsTotal
.
Hàm history_deals_get
có nhiều dạng và được thiết kế để chọn các giao dịch với khả năng lọc theo mã lệnh hoặc ID vị thế. Tất cả các dạng của hàm trả về một mảng của các tuple có tên TradeDeal
, với các trường phản ánh các thuộc tính từ ENUM_DEAL_PROPERTY_enumerations (tiền tố "DEAL_" đã bị xóa khỏi tên trường và áp dụng chữ thường). Trong trường hợp xảy ra lỗi, chúng ta nhận được None
.
namedtuple[] history_deals_get(date_from, date_to, group = PATTERN
)
namedtuple[] history_deals_get(ticket = ORDER_TICKET
)
namedtuple[] history_deals_get(position = POSITION_ID
)
Dạng đầu tiên của hàm tương tự như yêu cầu các lệnh lịch sử bằng history_orders_get
.
Dạng thứ hai cho phép chọn các giao dịch được tạo ra bởi một lệnh cụ thể theo mã lệnh của nó (thuộc tính DEAL_ORDER).
Cuối cùng, dạng thứ ba yêu cầu các giao dịch đã hình thành một vị thế với ID đã cho (thuộc tính DEAL_POSITION_ID).
Hàm này cho phép lấy tất cả các giao dịch cùng với thuộc tính của chúng trong một lần gọi, tương tự như tập hợp các hàm HistoryDealsTotal
, HistoryDealSelect
, và HistoryDealGet
-functions.
Dưới đây là phần chính của script thử nghiệm historydealsget.py
.
thiết lập khoảng thời gian
from_date = datetime(`2020`, `1`, `1`)
to_date = datetime.now()
2
lấy các giao dịch cho các biểu tượng có tên không chứa "EUR" hoặc "GBP"
deals = mt5.history_deals_get(from_date, to_date, group=`*,!*EUR*,!*GBP*`)
nếu deals == `None`:
print(`Không có giao dịch, mã lỗi={}`.format(mt5.last_error()))
hoặc nếu len(deals) `0`:
print(`history_deals_get(from_date, to_date, group="*,!*EUR*,!*GBP*") =`,
len(deals))
# hiển thị tất cả các giao dịch nhận được như nguyên bản
cho deal trong deals:
print(` `, deal)
# hiển thị các giao dịch này dưới dạng bảng bằng pandas.DataFrame
df = pd.DataFrame(list(deals), columns = deals[`0`]._asdict().keys())
df[`time`] = pd.to_datetime(df[`time`], unit=`s`)
df.drop([`time_msc`, `commission`, `fee`], axis = `1`, inplace = `True`)
print(df)
2
3
4
5
6
7
8
9
10
11
12
13
14
Ví dụ về kết quả:
history_deals_get(from_date, to_date, group=`*,!*EUR*,!*GBP*`) = 12
TradeDeal(ticket=1109160642, order=0, time=1632188460, time_msc=1632188460852, type=2, entry=0, magic=0, position_id=0, reason=0, volume=0.0, price=0.0, commission=0.0, swap=0.0, profit=10000.0, fee=0.0, symbol='', comment='', external_id='')
TradeDeal(ticket=1250629232, order=1268074569, time=1645709385, time_msc=1645709385815, type=0, entry=0, magic=0, position_id=1268074569, reason=0, volume=0.01, price=1970.98, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250639814, order=1268085019, time=1645709950, time_msc=1645709950618, type=1, entry=1, magic=0, position_id=1268074569, reason=0, volume=0.01, price=1970.09, commission=0.0, swap=0.0, profit=-0.89, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250639928, order=1268085129, time=1645709955, time_msc=1645709955502, type=1, entry=0, magic=0, position_id=1268085129, reason=0, volume=0.01, price=1969.98, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250640111, order=1268085315, time=1645709965, time_msc=1645709965148, type=0, entry=1, magic=0, position_id=1268085129, reason=0, volume=0.01, price=1970.17, commission=0.0, swap=0.0, profit=-0.19, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250640309, order=1268085512, time=1645709973, time_msc=1645709973623, type=1, entry=0, magic=0, position_id=1268085512, reason=0, volume=0.1, price=1970.09, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250640400, order=1268085611, time=1645709978, time_msc=1645709978701, type=0, entry=1, magic=0, position_id=1268085512, reason=0, volume=0.1, price=1970.22, commission=0.0, swap=0.0, profit=-1.3, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250640616, order=1268085826, time=1645709988, time_msc=1645709988277, type=1, entry=0, magic=0, position_id=1268085826, reason=0, volume=1.1, price=1969.95, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1250640810, order=1268086019, time=1645709996, time_msc=1645709996990, type=0, entry=1, magic=0, position_id=1268085826, reason=0, volume=1.1, price=1969.88, commission=0.0, swap=0.0, profit=7.7, fee=0.0, symbol='XAUUSD', comment='', external_id='')
TradeDeal(ticket=1445796125, order=1468026008, time=1664199450, time_msc=1664199450488, type=0, entry=0, magic=234000, position_id=1468026008, reason=3, volume=0.1, price=144.132, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='USDJPY', comment='python script op', external_id='')
TradeDeal(ticket=1445796155, order=1468026041, time=1664199452, time_msc=1664199452567, type=1, entry=1, magic=234000, position_id=1468026008, reason=3, volume=0.1, price=144.124, commission=0.0, swap=0.0, profit=-0.56, fee=0.0, symbol='USDJPY', comment='python script cl', external_id='')
TradeDeal(ticket=1446217804, order=1468454363, time=1664217233, time_msc=1664217233239, type=1, entry=0, magic=0, position_id=1468454363, reason=0, volume=0.01, price=0.99145, commission=0.0, swap=0.0, profit=0.0, fee=0.0, symbol='USDCHF', comment='', external_id='')
ticket order time t… e… … position_id volume price profit symbol comment external_id
0 1109160642 0 2021-09-21 01:41:00 2 0 0 0.00 0.00000 10000.00
1 1250629232 1268074569 2022-02-24 13:29:45 0 0 1268074569 0.01 1970.98000 0.00 XAUUSD
2 1250639814 1268085019 2022-02-24 13:39:10 1 1 1268074569 0.01 1970.09000 -0.89 XAUUSD
3 1250639928 1268085129 2022-02-24 13:39:15 1 0 1268085129 0.01 1969.98000 0.00 XAUUSD
4 1250640111 1268085315 2022-02-24 13:39:25 0 1 1268085129 0.01 1970.17000 -0.19 XAUUSD
5 1250640309 1268085512 2022-02-24 13:39:33 1 0 1268085512 0.10 1970.09000 0.00 XAUUSD
6 1250640400 1268085611 2022-02-24 13:39:38 0 1 1268085512 0.10 1970.22000 -1.30 XAUUSD
7 1250640616 1268085826 2022-02-24 13:39:48 1 0 1268085826 1.10 1969.95000 0.00 XAUUSD
8 1250640810 1268086019 2022-02-24 13:39:56 0 1 1268085826 1.10 1969.88000 7.70 XAUUSD
9 1445796125 1468026008 2022-09-26 13:37:30 0 0 1468026008 0.10 144.13200 0.00 USDJPY python script op
10 1445796155 1468026041 2022-09-26 13:37:32 1 1 1468026008 0.10 144.12400 -0.56 USDJPY python script cl
11 1446217804 1468454363 2022-09-26 18:33:53 1 0 1468454363 0.01 0.99145 0.00 USDCHF
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