获取未平仓仓位的数量和清单

positions_total 函数返回未平仓仓位的数量。

int positions_total()

该函数类似于 PositionsTotal

为获取每个仓位的详细信息,可以使用 positions_get 函数,该函数有多个选项。所有变量都返回一个命名元组 TradePosition 的数组,其索引对应仓位特性(参见 ENUM_POSITION_PROPERTY_enumerations 的元素,不带 "POSITION_" 前缀,小写)。如果出现错误,则结果为 None

namedtuple[] positions_get()

namedtuple[] positions_get(symbol = <"SYMBOL">)

namedtuple[] positions_get(group = <"PATTERN">)

namedtuple[] positions_get(ticket = <TICKET>)

不含参数的函数返回所有未平仓仓位。

包含 symbol 参数的函数允许选择指定符号的仓位。

包含 group 参数的函数通过搜索掩码提供筛选,该掩码使用通配符 '*'(替换任何字符)和条件逻辑非 '!'。有关详细信息,参见 获取有关金融工具的信息一节。

包含 ticket 参数的版本使用特定票证选择仓位(POSITION_TICKET 特性)。

positions_get 函数可用于在一次调用中获取所有仓位及其特性,这使它类似于 PositionsTotalPositionSelectPositionGet 之类的函数

MQL5/Scripts/MQL5Book/Python/positionsget.py 脚本中,我们请求特定交易品种的仓位和搜索掩码。

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 to display
   
# let's establish a connection to the MetaTrader 5 terminal
if not mt5.initialize():
   print("initialize() failed, error code =", mt5.last_error())
   quit()
   
# get open positions on 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)
   
# get a list of positions on symbols whose names contain "*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 the 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)
   
# complete the connection to the MetaTrader 5 terminal
mt5.shutdown()

结果可能是这样的:

Total positions on USDCHF = 1

TradePosition(ticket=1468454363, time=1664217233, time_msc=1664217233239, time_update=1664217233,

time_update_msc=1664217233239, type=1, magic=0, identifier=1468454363, reason=0, volume=0.01, price_open=0.99145,

sl=0.0, tp=0.0, price_current=0.9853, swap=-0.01, profit=6.24, symbol='USDCHF', comment='', external_id='')

positions_get(group="*USD*") = 2

ticket time type ... identifier volume price_open ..._current swap profit symbol comment

0 1468454363 2022-09-26 18:33:53 1 ...1468454363 0.01 0.99145 ...0.98530 -0.01 6.24 USDCHF

1 1468475849 2022-09-26 18:44:00 0 ...1468475849 0.01 1.06740 ...1.08113 0.00 13.73 GBPUSD