mt5.positions_get() in MetaTrader5 Python: read open positions

Returns the account's open positions as a tuple of named tuples, all of them or filtered by symbol, group or ticket. Returns None on failure.

Signature

mt5.positions_get()
mt5.positions_get(symbol="...")
mt5.positions_get(group="...")
mt5.positions_get(ticket=...)

What it does

positions_get() lists open positions with their size, open price, current price and profit. Give at most one filter.

Each item has fields such as ticket, identifier, symbol, type, volume, price_open, price_current, sl, tp, swap, profit and magic.

Parameters

ParameterWhat it is
symbolOnly items on this symbol. Optional.
groupOnly items whose symbol matches a filter, such as "*USD*". * is a wildcard, commas separate patterns and ! leaves one out. Optional.
ticketOnly the item with this ticket. Optional.

What it returns

  • A tuple of position records. An empty tuple means none are open.
  • None on failure. Check mt5.last_error().

Example

import MetaTrader5 as mt5

if not mt5.initialize():
    raise SystemExit(mt5.last_error())

positions = mt5.positions_get(group="*USD*")
if positions is None:
    raise SystemExit(mt5.last_error())

for p in positions:
    side = "buy" if p.type == mt5.POSITION_TYPE_BUY else "sell"
    print(p.ticket, p.symbol, side, p.volume, round(p.profit, 2))
mt5.shutdown()

Common mistakes

  • profit is the floating profit in the account currency. It does not include commission.
  • To close a position, send an opposite deal with order_send() and set position to the position's ticket.
  • Tell None apart from an empty tuple. None means the call failed, not that you are flat.

The same with Tickwire on Linux

The package needs a Windows terminal on the same machine. Tickwire runs the terminal for you and gives you a REST API, so the code below runs on Linux, macOS or a server.

Tickwire's positions route returns open positions as JSON with id, symbol, type, volume, openPrice, currentPrice, swap, commission and profit. profit includes what the position's deals have already realised, such as swap and commission. The single-position route reads one by id.

import os, requests

API = "https://api.tickwire.io"
h = {"auth-token": os.environ["TW_KEY"]}      # your Tickwire key
base = f"{API}/users/current/accounts/{os.environ['TW_ACCOUNT']}"

for p in requests.get(f"{base}/positions", headers=h).json():
    print(p["id"], p["symbol"], p["type"], p["volume"], p["profit"])

Related error codes

All MetaTrader5 Python functions

MT5 from Python, on any machine

One REST API for MT4 and MT5, with idempotent orders and an audit log. Read the MT5 Python API page or the quickstart.