import MetaTrader5 as mt5
import pandas as pd
pd.set_option('display.max_columns', 500) # number of columns to be displayed
pd.set_option('display.width', 1500) # max table width to display
# 显示有关MetaTrader 5程序包的数据
print("MetaTrader5 package author: ",mt5.__author__)
print("MetaTrader5 package version: ",mt5.__version__)
print()
# 建立与MetaTrader 5程序端的连接
if not mt5.initialize():
print("initialize() failed, error code =",mt5.last_error())
quit()
# 获取USDCHF的未结持仓
positions=mt5.positions_get(symbol="USDCHF")
if positions==None:
print("No positions on USDCHF, error code={}".format(mt5.last_error()))
elif len(positions)>0:
print("Total positions on USDCHF =",len(positions))
# display all open positions
for position in positions:
print(position)
# 获取名称包含"*USD*"的交易品种的持仓列表
usd_positions=mt5.positions_get(group="*USD*")
if usd_positions==None:
print("No positions with group=\"*USD*\", error code={}".format(mt5.last_error()))
elif len(usd_positions)>0:
print("positions_get(group=\"*USD*\")={}".format(len(usd_positions)))
# display these positions as a table using pandas.DataFrame
df=pd.DataFrame(list(usd_positions),columns=usd_positions[0]._asdict().keys())
df['time'] = pd.to_datetime(df['time'], unit='s')
df.drop(['time_update', 'time_msc', 'time_update_msc', 'external_id'], axis=1, inplace=True)
print(df)
# 断开与MetaTrader 5程序端的连接
mt5.shutdown()
结果:
MetaTrader5程序包作者:MetaQuotes Software Corp.
MetaTrader5程序包版本:5.0.29
positions_get(group="*USD*")=5
ticket time type magic identifier reason volume price_open sl tp price_current swap profit symbol comment
0 548297723 2020-03-18 15:00:55 1 0 548297723 3 0.01 1.09301 1.11490 1.06236 1.10104 -0.10 -8.03 EURUSD
1 548655158 2020-03-18 20:31:26 0 0 548655158 3 0.01 1.08676 1.06107 1.12446 1.10099 -0.08 14.23 EURUSD
2 548663803 2020-03-18 20:40:04 0 0 548663803 3 0.01 1.08640 1.06351 1.11833 1.10099 -0.08 14.59 EURUSD
3 548847168 2020-03-19 01:10:05 0 0 548847168 3 0.01 1.09545 1.05524 1.15122 1.10099 -0.06 5.54 EURUSD
4 548847194 2020-03-19 01:10:07 0 0 548847194 3 0.02 1.09536 1.04478 1.16587 1.10099 -0.08 11.26 EURUSD
|