mt5.positions_total() in MetaTrader5 Python: count open positions
Returns how many positions are open on the account right now. Returns an integer. Use positions_get() to read them.
Signature
mt5.positions_total() What it does
positions_total() is a quick count of open positions. On a netting account there is at most one position per symbol; on a hedging account there can be many.
What it returns
- An integer: the number of open positions.
Example
import MetaTrader5 as mt5
if not mt5.initialize():
raise SystemExit(mt5.last_error())
if mt5.positions_total() >= 5:
print("five positions open, not adding more")
mt5.shutdown() Common mistakes
- Right after a restart the count can read 0 until the terminal has loaded the account. Do not open new trades on that 0 alone.
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 the open positions as a JSON array. Its length is the count.
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']}"
positions = requests.get(f"{base}/positions", headers=h).json()
print(len(positions), "open positions") Related functions
- mt5.positions_get() in MetaTrader5 Python: read open positions
- mt5.orders_total() in MetaTrader5 Python: count pending orders
- mt5.history_deals_total() in MetaTrader5 Python: count deals in history
Related error codes
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.