- Installing Python and the MetaTrader5 package
- Overview of functions of the MetaTrader5 package for Python
- Connecting a Python script to the terminal and account
- Error checking: last_error
- Getting information about a trading account
- Getting information about the terminal
- Getting information about financial instruments
- Subscribing to order book changes
- Reading quotes
- Reading tick history
- Calculating margin requirements and evaluating profits
- Checking and sending a trade order
- Getting the number and list of active orders
- Getting the number and list of open positions
- Reading the history of orders and deals
Getting the number and list of open positions
The positions_total function returns the number of open positions.
int positions_total()
The function is an analog of PositionsTotal.
To get detailed information about each position, use the positions_get function which has multiple options. All variants return an array of named tuples TradePosition with keys corresponding to position properties (see elements of ENUM_POSITION_PROPERTY_enumerations, without the "POSITION_" prefix, in lowercase). In case of an error, the result is None.
namedtuple[] positions_get()
namedtuple[] positions_get(symbol = <"SYMBOL">)
namedtuple[] positions_get(group = <"PATTERN">)
namedtuple[] positions_get(ticket = <TICKET>)
The function without parameters returns all open positions.
The function with the symbol parameter allows the selection of positions for the specified symbol.
The function with the group parameter provides filtering by search mask with wildcards '*' (any characters are replaced) and logical negation of the condition '!'. For details see the section Getting information about financial instruments.
A version with the ticket parameters selects a position with a specific ticket (POSITION_TICKET property).
The positions_get function can be used to get all positions and their properties in one call, which makes it similar to a bunch of PositionsTotal, PositionSelect, and PositionGet functions.
In the script MQL5/Scripts/MQL5Book/Python/positionsget.py, we request positions for a specific symbol and search mask.
import MetaTrader5 as mt5
|
Here's what the result might be:
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
|