mt5.copy_rates_from_pos() in MetaTrader5 Python: get the latest bars by position
Copies bars of one symbol and timeframe counted from a bar position, where 0 is the bar that is still forming. Returns a numpy array, or None on failure.
Signature
mt5.copy_rates_from_pos(symbol, timeframe, start_pos, count) What it does
copy_rates_from_pos() counts bars back from now instead of from a date. Position 0 is the current bar, 1 is the last closed bar, and so on.
It is the simplest way to get "the last N bars" for an indicator or a signal.
Parameters
| Parameter | What it is |
|---|---|
symbol | The symbol name. Required. |
timeframe | A timeframe constant such as mt5.TIMEFRAME_M1, mt5.TIMEFRAME_H1 or mt5.TIMEFRAME_D1. |
start_pos | The position of the first bar to copy. 0 is the bar that is still forming. |
count | How many bars to return. |
What it returns
- A numpy structured array, one row per bar, with the fields
time,open,high,low,close,tick_volume,spreadandreal_volume.timeis the bar's open time in seconds. Noneon failure. Checkmt5.last_error().
Example
import MetaTrader5 as mt5
if not mt5.initialize():
raise SystemExit(mt5.last_error())
# Start at 1 to skip the bar that has not closed yet
rates = mt5.copy_rates_from_pos("XAUUSD", mt5.TIMEFRAME_M15, 1, 20)
if rates is None:
raise SystemExit(mt5.last_error())
closes = rates["close"]
print("20-bar average close:", closes.mean())
mt5.shutdown() Common mistakes
- Bar 0 is not finished. Its close is the latest price and keeps changing. Start at 1 when your logic needs closed bars only.
- Bar and tick times are the broker's server clock written as if it were UTC. On most servers that is two or three hours ahead of true UTC. Add the broker's offset before you compare them with real UTC times.
- The "Max. bars in chart" setting caps how far back you can go.
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.
Leave out startTime on Tickwire's candles route and it returns the latest bars. The current-candles route returns only the bar that is still forming.
Tickwire's candles route returns up to limit bars (1000 at most) that open at or before startTime, oldest first, as JSON. Each bar has a UTC time and a brokerTime, so there is no clock to guess. MT5 accounts have 21 timeframes, from 1m to 1mn; MT4 accounts have 9.
GET /users/current/accounts/{account_id}/historical-market-data/symbols/{symbol}/timeframes/{timeframe}/candlesGET /users/current/accounts/{account_id}/symbols/{symbol}/current-candles/{timeframe}
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']}"
bars = requests.get(f"{base}/historical-market-data/symbols/XAUUSD/timeframes/15m/candles",
params={"limit": 21}, headers=h).json()
closed = bars[:-1] # the last one may still be forming
print(sum(b["close"] for b in closed) / len(closed)) Related functions
- mt5.copy_rates_from() in MetaTrader5 Python: get bars back from a date
- mt5.copy_rates_range() in MetaTrader5 Python: get bars between two dates
- mt5.symbol_info_tick() in MetaTrader5 Python: get the latest bid and ask
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.