Your MT5 as an API
Your MetaTrader 5 runs 24/7 on HostMT5. Your code can run anywhere (your laptop, a notebook, a server) and use it from any language: years of candles and ticks, live prices, account and positions, orders, Expert Advisors. AI assistants get the same through MCP, and TradingView or Skynet alerts become trades through webhooks.
HTTPS JSON for history and orders. One WebSocket for live quotes, candles, account and fills.
Python and JavaScript clients, examples in C#, Java, Go, PHP, and an OpenAPI spec for the rest.
Claude, ChatGPT, Cursor and others run your whole account: data, orders, EAs, kill switch.
Quick start
- Create a free HostMT5 account and add your MT5 account (any broker, demo or real). It logs in and stays online 24/7.
- Dashboard → AI & API → New API key. Pick Trading (everything) or Read only (data, no orders). The key is shown once.
- Call the API. Every call names an account by its
idfromGET /api/v1/accounts.
curl https://hostmt5.com/api/v1/accounts -H "Authorization: Bearer mc_your_key"
curl "https://hostmt5.com/api/v1/accounts/1/bars?symbol=EURUSD&timeframe=H1&count=500" \
-H "Authorization: Bearer mc_your_key"
# download hostmt5.py from https://hostmt5.com/sdk/hostmt5.py (no packages needed; streaming: pip install websockets)
from hostmt5 import HostMT5
api = HostMT5("mc_your_key")
print(api.accounts()) # [{'id': 1, 'login': '...', 'server': '...', 'status': 'online'}]
acc = api.account(1)
bars = acc.bars("EURUSD", "H1", count=500) # oldest first: time, open, high, low, close, tick_volume, spread
df = acc.bars_df("XAUUSD", "M15", count=5000) # the same as a pandas DataFrame
// Node 18+: download https://hostmt5.com/sdk/hostmt5.js next to your script
import { HostMT5 } from './hostmt5.js';
const api = new HostMT5(process.env.HOSTMT5_KEY);
const acc = api.account(1);
const bars = await acc.bars('EURUSD', 'H1', { count: 500 });
console.log(bars.at(-1));
using System.Net.Http.Headers;
using System.Text.Json;
var http = new HttpClient { BaseAddress = new Uri("https://hostmt5.com") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "mc_your_key");
var json = await http.GetStringAsync("/api/v1/accounts/1/bars?symbol=EURUSD&timeframe=H1&count=500");
var bars = JsonDocument.Parse(json).RootElement.GetProperty("bars");
foreach (var b in bars.EnumerateArray()) Console.WriteLine($"{b.GetProperty("time")} {b.GetProperty("close")}");
import java.net.URI;
import java.net.http.*;
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder(URI.create("https://hostmt5.com/api/v1/accounts/1/bars?symbol=EURUSD&timeframe=H1&count=500"))
.header("Authorization", "Bearer mc_your_key").build();
var res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body()); // {"symbol":"EURUSD","timeframe":"H1","bars":[{"time":...,"open":...}, ...]}
req, _ := http.NewRequest("GET", "https://hostmt5.com/api/v1/accounts/1/bars?symbol=EURUSD&timeframe=H1&count=500", nil)
req.Header.Set("Authorization", "Bearer mc_your_key")
res, err := http.DefaultClient.Do(req)
if err != nil { log.Fatal(err) }
defer res.Body.Close()
var out struct{ Bars []struct{ Time int64; Open, High, Low, Close float64 } }
json.NewDecoder(res.Body).Decode(&out)
fmt.Println(len(out.Bars), out.Bars[len(out.Bars)-1].Close)
$ch = curl_init("https://hostmt5.com/api/v1/accounts/1/bars?symbol=EURUSD&timeframe=H1&count=500");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer mc_your_key"]]);
$data = json_decode(curl_exec($ch), true);
echo end($data["bars"])["close"];
Keys and limits
Send the key as Authorization: Bearer mc_… (or X-API-Key: mc_…). The developer API takes keys only, never browser cookies, so no other web site can use your session.
| Key type | Can |
|---|---|
| Trading | Everything: data, orders, closing, stop / resume trading, EAs, account and copy-trading changes. |
| Read only | Account, positions, history, symbols, quotes, candles, ticks, live stream, EA list, source and logs. Any change is refused with 403. |
Limits per key: 1,200 data requests and 120 trading requests a minute. Over that you get 429 with Retry-After. One stream carries any number of price updates, so stream live prices instead of polling them. Up to 10 streams per user.
SDKs and examples
| hostmt5.py | Python 3.8+ client: every endpoint, bars_df() for pandas, history() pages years of candles, stream() for live data (needs pip install websockets). |
| hostmt5.js | JavaScript (Node 18+, Deno, Bun): every endpoint and for await live stream. |
| sma_cross.py · sma_cross.js | A moving-average crossover running on your computer, acting on each closed candle. |
| stream_prices.py | Live quotes, candles and account updates printed as they arrive. |
| export_history.py | Years of candles to CSV, for backtests or Excel. |
| API reference · openapi.json | Every endpoint with its parameters, responses and errors. The OpenAPI 3 spec behind it is the .json file. Import it into Postman, or generate a client for C#, Java, Go, PHP, Rust, Kotlin, Swift, R… with openapi-generator. |
Account
| Call | Returns |
|---|---|
GET /api/v1/accounts | Your hosted accounts: id, label, login, server, status, trading_stopped. |
GET /api/v1/accounts/{id} | Balance, equity, margin, margin_free, margin_level, profit, currency, leverage, real (live or demo), hedging, algo_trading. |
GET /api/v1/accounts/{id}/positions | Open positions: ticket, symbol, side, volume, price_open, price_current, sl, tp, profit, swap, magic, comment, time. ?symbol= filters. |
GET /api/v1/accounts/{id}/orders | Pending orders. |
GET /api/v1/accounts/{id}/deals | Trade history: ?days=30 or ?from=2026-01-01&to=…, optional symbol. |
GET /api/v1/me | The key's owner, scope and limits. |
Market data
| Call | Parameters |
|---|---|
GET /accounts/{id}/bars | symbol, timeframe (M1 M2 M3 M4 M5 M6 M10 M12 M15 M20 M30 H1 H2 H3 H4 H6 H8 H12 D1 W1 MN1), then either count (newest bars, up to 50,000; the last bar is still forming), from + to (a period), to + count (bars ending at to: page back in time with it), or from + count. Each bar: time, open, high, low, close, tick_volume, spread, real_volume. History reaches back 500,000 bars per symbol and timeframe (M1 about 1.4 years, M5 about 7 years, M15 and above as far as your broker has); each call returns up to 50,000, so page back with to or use history(). Asking for more returns the bars that exist; a period older than that returns no bars and a note saying where the history starts. |
GET /accounts/{id}/ticks | symbol; count (newest, up to 100,000), or from + to, or from + count; kind = all, info (bid/ask changes) or trade (exchange trades). Each tick: time, time_msc, bid, ask, last, volume, flags. |
GET /accounts/{id}/quotes | symbols=EURUSD,XAUUSD. Bid, ask, spread, digits, point, lot limits and time (ms). Symbols are added to Market Watch if needed. |
GET /accounts/{id}/symbols | Every symbol your broker offers; ?search=gold matches name or description. |
GET /accounts/{id}/symbols/{symbol} | Everything MT5 knows about one symbol: contract size, lot min/max/step, tick size and value, swaps, stops level, margin, currencies, current tick. |
acc = HostMT5("mc_your_key").account(1)
week = acc.bars("XAUUSD", "M5", start="2026-11-16", end="2026-11-21") # a period
older = acc.bars("XAUUSD", "M5", count=20000, end=week[0]["time"] - 1) # the 20,000 bars before it
everything = acc.history("EURUSD", "H1", "2023-01-01") # pages for you
ticks = acc.ticks("EURUSD", count=10000)
const week = await acc.bars('XAUUSD', 'M5', { from: '2026-11-16', to: '2026-11-21' });
const older = await acc.bars('XAUUSD', 'M5', { count: 20000, to: week[0].time - 1 });
const ticks = await acc.ticks('EURUSD', { count: 10000 });
curl -G https://hostmt5.com/api/v1/accounts/1/bars -H "Authorization: Bearer mc_your_key" \
-d symbol=XAUUSD -d timeframe=M5 -d from=2026-11-16 -d to=2026-11-21
Trading
| Call | Body / parameters |
|---|---|
POST /accounts/{id}/orders | symbol, side buy|sell, volume (lots), type market (default) | limit | stop with price. Stops: sl/tp prices, or sl_pips/tp_pips, or sl_points/tp_points from the entry. comment. client_id: the same id again within 10 minutes returns the first result instead of trading twice, so retries are safe. Returns ticket, price, sl, tp. |
PUT /accounts/{id}/positions/{ticket} | sl, tp (leave one out to keep it; 0 removes it). |
DELETE /accounts/{id}/positions/{ticket} | Close it; ?volume=0.05 closes part. |
POST /accounts/{id}/positions/close | Close many: {} = all, {"symbol":"EURUSD"}, {"side":"buy"}. |
DELETE /accounts/{id}/orders/{ticket} | Delete a pending order. |
GET /accounts/{id}/activity | Your API activity log: the last trade calls sent with your keys on this account (REST, live stream, MCP), newest first, with the outcome (filled, placed, done, refused, unconfirmed, bad request, rate limited) and the ticket or the reason. Requests refused before they reached MT5 are included. ?limit= up to 200 (the last 200 are kept). The same log is in Dashboard > AI & API. |
t = acc.buy("EURUSD", 0.01, sl_pips=20, tp_pips=40, client_id="signal-123")
print(t["ticket"], t["price"])
acc.modify(t["ticket"], sl=1.0950)
acc.close(t["ticket"], volume=0.005) # half
acc.sell_limit("XAUUSD", 0.02, 2700, sl=2712)
acc.close_all(symbol="EURUSD")
const t = await acc.buy('EURUSD', 0.01, { sl_pips: 20, tp_pips: 40, client_id: 'signal-123' });
await acc.modify(t.ticket, { sl: 1.0950 });
await acc.close(t.ticket);
curl https://hostmt5.com/api/v1/accounts/1/orders -H "Authorization: Bearer mc_your_key" \
-H "Content-Type: application/json" \
-d '{"symbol":"EURUSD","side":"buy","volume":0.01,"sl_pips":20,"tp_pips":40,"client_id":"signal-123"}'
var body = new StringContent("""{"symbol":"EURUSD","side":"buy","volume":0.01,"sl_pips":20,"tp_pips":40}""",
System.Text.Encoding.UTF8, "application/json");
var res = await http.PostAsync("/api/v1/accounts/1/orders", body);
Console.WriteLine(await res.Content.ReadAsStringAsync()); // {"ok":true,"ticket":...,"price":...}
var order = HttpRequest.newBuilder(URI.create("https://hostmt5.com/api/v1/accounts/1/orders"))
.header("Authorization", "Bearer mc_your_key").header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"symbol\":\"EURUSD\",\"side\":\"buy\",\"volume\":0.01,\"sl_pips\":20}"))
.build();
System.out.println(client.send(order, HttpResponse.BodyHandlers.ofString()).body());
body := strings.NewReader(`{"symbol":"EURUSD","side":"buy","volume":0.01,"sl_pips":20,"tp_pips":40}`)
req, _ := http.NewRequest("POST", "https://hostmt5.com/api/v1/accounts/1/orders", body)
req.Header.Set("Authorization", "Bearer mc_your_key")
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
io.Copy(os.Stdout, res.Body)
$ch = curl_init("https://hostmt5.com/api/v1/accounts/1/orders");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer mc_your_key", "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["symbol" => "EURUSD", "side" => "buy", "volume" => 0.01, "sl_pips" => 20])]);
print_r(json_decode(curl_exec($ch), true));
A market order answers with the filled ticket and price. A limit or stop order answers the same way with "type":"limit" / "stop", and the price is the order's price:
{"ok": true, "ticket": 2439987501, "symbol": "EURUSD", "side": "buy", "type": "market", "volume": 0.01,
"price": 1.05412, "sl": 1.05212, "tp": 1.05812, "comment": "", "client_id": "signal-123"}
Sending the same client_id again within 10 minutes returns that first result with "duplicate": true and opens nothing. Modify answers {"ok":true,"ticket","sl","tp"}, close answers {"ok":true,"ticket","closed_volume"} and cancel answers {"ok":true,"ticket"}.
API activity log
Every trade call made with your keys on an account is logged with how it ended: orders, stop/target changes, closes, cancels and stop/resume. That covers calls from REST, the live stream and an AI assistant over MCP. Calls refused before they reached MT5 are logged too, such as a wrong field or a read-only key trying to trade. So if a bot says it traded and nothing happened, the log shows why. A read-only key can read the log.
for x in acc.activity(limit=20):
print(x["via"], x["op"], x["outcome"], x["what"], "→", x["result"])
for (const x of await acc.activity(20)) console.log(x.via, x.op, x.outcome, x.what, '→', x.result);
curl "https://hostmt5.com/api/v1/accounts/1/activity?limit=20" -H "Authorization: Bearer mc_your_key"
{"account_id": 1, "activity": [
{"at": 1764252301.4, "via": "rest", "key": "mc_7Hq2xP", "op": "order", "what": "SELL 0.01 XAUUSD",
"outcome": "bad request", "result": "side: Input should be 'buy' or 'sell' (got 'SELL')"},
{"at": 1764252288.9, "via": "rest", "key": "mc_7Hq2xP", "op": "order", "what": "buy 0.5 XAUUSD sl_pips 20",
"outcome": "refused", "result": "Broker refused: No money"},
{"at": 1764252240.2, "via": "stream", "key": "mc_7Hq2xP", "op": "order", "what": "buy 0.01 EURUSD id signal-123",
"outcome": "filled", "result": "#2439987501 @ 1.05412"},
{"at": 1764252100.7, "via": "mcp", "key": "mc_Zp41kR", "op": "trading", "what": "stop trading + close positions",
"outcome": "done", "result": "trading stopped, positions closed 2"}
]}
| Field | Meaning |
|---|---|
at | Unix time in seconds (UTC). |
via | rest, stream (an order op on the WebSocket) or mcp (an AI assistant). |
key | The start of the API key that made the call, so you can tell your bots apart. |
op | order, modify, close, close_many, cancel, trading. |
what | What was sent, in short. |
outcome | filled (market order) · placed (pending order) · done · refused (by the broker, MT5 or a key without trade rights) · bad request (failed the parameter checks, never reached MT5) · rate limited · unconfirmed (MT5 didn't answer in time: check your positions before retrying, or retry with the same client_id). |
result | The ticket and price, or the reason it failed. |
Stop / resume trading
POST /api/v1/accounts/{id}/trading with {"enabled": false} is the kill switch:
- MT5's Algo Trading goes off, so every EA stops opening and closing trades. It stays off after restarts, the watchdog and reboots.
- The account's TradingView webhook is paused and copy trading into it is paused.
- Add
"close_positions": trueand/or"cancel_orders": trueto flatten as well.
{"enabled": true} switches Algo Trading back on and restores exactly what the stop paused. Orders you send through the API still work while trading is stopped. GET /accounts/{id} shows trading_stopped.
Every account at once
One call acts on all your accounts (or a list of ids). Each account uses its own broker's symbol name (XAUUSD also matches XAUUSD.m or XAUUSD.pro), they run in parallel, and each reports its own result, so one refusal never stops the others. Every account's part is in its activity log.
GET /portfolio | Every account: balance, equity, floating profit, open trades, lots, symbols, real or demo, Algo Trading, and totals per currency. |
POST /bulk/orders | {"accounts":"all","symbol":"XAUUSD","side":"buy","volume":0.1,"sl_pips":50}. Lots: volume for all, volumes per account ({"3":0.05}), or "per_10k_balance":true to size by each balance. Stops as distances, because prices differ between brokers. client_id makes a retry safe on every account. |
POST /bulk/close | {"accounts":"all"} closes everything; add symbol and/or side, and "cancel_orders":true to delete pending orders too. |
POST /bulk/trading | The kill switch for many accounts: {"accounts":"all","enabled":false,"close_positions":true}; "enabled":true resumes. |
Backtests and optimisation
MT5's own Strategy Tester runs on the server that hosts the account, with its broker's symbols and price history, in a sandbox copy of the terminal that cannot trade. A start returns a job id at once; ask for the result with ?wait= or poll.
POST /accounts/{id}/backtests | expert (as list_eas shows it, e.g. Uploaded\MyEA), symbol, timeframe, from / to (YYYY-MM-DD), model ohlc_m1 (default) | open_prices | every_tick | real_ticks, deposit, currency, leverage, inputs. To optimise, give inputs as {"start","step","stop"} with "optimization": "complete" (up to 20,000 combinations) or "genetic", a criterion, and "forward": "third" to check the best settings on the part of the period kept out. |
GET /backtests/{job}?wait=90 | status queued | running | done | error. Done: result.metrics (net_profit, profit_factor, equity_dd_pct, trades, wins_pct, sharpe, recovery_factor…), result.deals, and for an optimisation result.passes, best first, each with its inputs and forward result. |
GET /backtests · DELETE /backtests/{job} | Your recent tests; stop one. |
curl https://hostmt5.com/api/v1/accounts/1/backtests -H "Authorization: Bearer mc_your_key" -H "Content-Type: application/json" \
-d '{"expert":"Uploaded\\MyEA","symbol":"EURUSD","timeframe":"H1","from":"2026-01-01","to":"2026-11-27",
"optimization":"complete","forward":"third","inputs":{"Period":{"start":5,"step":5,"stop":50},"Lots":0.1}}'
In the dashboard, EA Builder does all of this by chat: it writes the EA, compiles it, backtests and optimises it, shows the report (equity curve, every trade, every pass, a share link) and runs it on your accounts. Actions on real-money accounts always ask you first.
Expert Advisors
EAs run inside your hosted MT5, 24/7, with no computer of yours on. Write them yourself or let an AI write them, then upload, compile and run them through the API.
GET /accounts/{id}/eas | experts you can attach, attached = running ones with id, symbol, timeframe, inputs. |
POST /accounts/{id}/eas | {"filename":"MyEA.mq5","source":"…MQL5…"}: compiled on the server (about 5 s), and compile errors come back as 422 with line numbers. Or {"filename":"MyEA.ex5","data_base64":"…"}. Returns the name, e.g. Uploaded\MyEA. |
GET /accounts/{id}/eas/source?name= | The MQL5 source of an uploaded .mq5, to change it. |
GET /accounts/{id}/eas/inputs?name=&symbol= | Inputs and defaults before attaching. |
POST /accounts/{id}/eas/attach | {"name","symbol","timeframe","inputs":{"Lots":"0.05"}}. Runs it on its own chart in about 1-2 s. The first attach of a newly uploaded EA takes about 30 s: MT5 restarts once to see the new file, and your other EAs come back by themselves. |
PUT /accounts/{id}/eas/{ea_id} | {"inputs":{…}}. Only that EA restarts. |
DELETE /accounts/{id}/eas/{ea_id} | Stop and remove one EA. |
GET /accounts/{id}/logs?kind=experts|journal&lines=200 | MT5's logs: what EAs print and their errors, or logins, orders and connection events (EA loaded / removed, Algo Trading on / off). MT5 writes EA output to its log with a short delay. |
WebSocket stream
Connect to wss://hostmt5.com/api/v1/stream?account={id} with the Authorization header. Browsers can't set headers, so they send {"op":"auth","key":"mc_…","account":1} as the first message instead. The server sends {"type":"ready"}, then events. It sends a heartbeat every 15 s.
| You send | You get |
|---|---|
{"op":"subscribe","symbols":["EURUSD","XAUUSD"]} | {"type":"quote","symbol","bid","ask","spread","time"} on every price change (up to 100 symbols). |
{"op":"candles","symbol":"EURUSD","timeframe":"M1"} | {"type":"candle","bar":{…},"closed":false} as the bar forms. When a new bar starts, the finished one arrives once with "closed":true, which is the moment to run bar-close logic. Up to 20 per stream. |
(on by default) {"op":"account","on":false} turns it off | account (balance, equity, margin, profit) when it changes; positions and orders when one opens, closes or changes. |
{"op":"order","id":"a1","symbol":"EURUSD","side":"buy","volume":0.01} | {"type":"order_result","id":"a1","order":{ticket,…}}. Same fields as POST /orders. |
{"op":"unsubscribe",…} · {"op":"candles_off",…} · {"op":"ping"} | Confirmations and pong. Errors arrive as {"type":"error","id","op","message"}, e.g. {"type":"error","id":"a1","op":"order","message":"Invalid order: side: Input should be 'buy' or 'sell' (got 'SELL')"}. Stream orders are in the activity log as via: stream. |
for ev in acc.stream(symbols=["EURUSD"], candles=[("EURUSD", "M5")]): # reconnects by itself
if ev["type"] == "quote":
print(ev["symbol"], ev["bid"], ev["ask"])
elif ev["type"] == "candle" and ev["closed"]:
print("bar closed", ev["bar"]) # run your strategy here
for await (const ev of acc.stream({ symbols: ['EURUSD'], candles: [['EURUSD', 'M5']] })) {
if (ev.type === 'quote') console.log(ev.symbol, ev.bid, ev.ask);
if (ev.type === 'candle' && ev.closed) console.log('bar closed', ev.bar);
}
using var ws = new System.Net.WebSockets.ClientWebSocket();
ws.Options.SetRequestHeader("Authorization", "Bearer mc_your_key");
await ws.ConnectAsync(new Uri("wss://hostmt5.com/api/v1/stream?account=1"), default);
var sub = System.Text.Encoding.UTF8.GetBytes("""{"op":"subscribe","symbols":["EURUSD"]}""");
await ws.SendAsync(sub, System.Net.WebSockets.WebSocketMessageType.Text, true, default);
var buf = new byte[1 << 16];
while (true) {
var r = await ws.ReceiveAsync(buf, default);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(buf, 0, r.Count));
}
// go get github.com/gorilla/websocket
h := http.Header{"Authorization": {"Bearer mc_your_key"}}
c, _, err := websocket.DefaultDialer.Dial("wss://hostmt5.com/api/v1/stream?account=1", h)
if err != nil { log.Fatal(err) }
c.WriteJSON(map[string]any{"op": "subscribe", "symbols": []string{"EURUSD"}})
for {
var ev map[string]any
if err := c.ReadJSON(&ev); err != nil { log.Fatal(err) }
fmt.Println(ev["type"], ev["symbol"], ev["bid"])
}
MCP server for AI assistants
Give an AI assistant your HostMT5 and it can do almost anything you can do in the dashboard: read accounts, prices and history, trade, write MQL5 EAs and compile, run and tune them, read their logs, stop and resume trading, set up copy trading, webhooks and alerts.
| URL | https://hostmt5.com/mcp with header Authorization: Bearer mc_… (Streamable HTTP). |
| URL-only apps | https://hostmt5.com/mcp/mc_your_key. The URL then is the password, so keep it private. |
| Local (stdio) apps | mcp_server.py: Python 3.8+, no packages. It forwards to the URL above. |
claude mcp add --transport http hostmt5 https://hostmt5.com/mcp --header "Authorization: Bearer mc_your_key"
// Settings → Developer → Edit config (claude_desktop_config.json)
{
"mcpServers": {
"hostmt5": {
"command": "python",
"args": ["C:/Users/you/Downloads/mcp_server.py"],
"env": { "HOSTMT5_KEY": "mc_your_key" }
}
}
}
Claude.ai: Settings → Connectors → Add custom connector
ChatGPT: Settings → Connectors → Advanced → Developer mode → Create
Server URL: https://hostmt5.com/mcp/mc_your_key
// ~/.cursor/mcp.json
{
"mcpServers": {
"hostmt5": {
"url": "https://hostmt5.com/mcp",
"headers": { "Authorization": "Bearer mc_your_key" }
}
}
}
// .vscode/mcp.json
{
"servers": {
"hostmt5": {
"type": "http",
"url": "https://hostmt5.com/mcp",
"headers": { "Authorization": "Bearer mc_your_key" }
}
}
}
Then ask, for example: “Show my open positions on every account”, “Write an EA that buys XAUUSD on an H1 RSI cross under 30, compile it and attach it to my demo with 0.01 lots”, “Stop all trading on my real account and close everything”, “Copy account 1 to account 3 at half size”.
Tools
TradingView webhooks
Each account has a secret URL https://hostmt5.com/hook/… (Dashboard → AI & API). Paste it into a TradingView alert under Notifications → Webhook URL. The alert message is the order. No key is needed: the secret URL picks the account, so treat it like a password, and use New URL if it leaks. The webhook answers within 3 s. Every call shows in the dashboard log.
| Field | Meaning |
|---|---|
action | buy, sell, buy_limit, sell_limit, buy_stop, sell_stop (with price), close (symbol or ticket; pct for part), close_buy, close_sell, close_all, close_partial (volume lots, oldest first), flip_buy / flip_sell (close everything on the symbol, then open), modify (new stops), cancel, cancel_buy, cancel_sell, breakeven, ping. |
symbol | TradingView's {{ticker}} works: OANDA:EURUSD becomes your broker's EURUSD, including suffixes like EURUSD.pro. |
volume / risk_pct | Lots, or % of balance lost if the stop is hit. |
| stops | One form per side: sl/tp prices, sl_pips/tp_pips, sl_points/tp_points, or sl_pct/tp_pct (% of the entry). |
id · spread | A repeated id within 10 minutes is ignored. Skip the trade if the spread is wider than this many pips. |
Webhook settings (per account): pause, default lots, max lots, allowed symbols, symbol map (GOLD=XAUUSD), max spread, and close opposite (a buy first closes that symbol's sells and the other way round, so one strategy alert reverses the position). Unknown JSON fields are refused, so a typo can't trade differently from what you meant.
{"action":"{{strategy.order.action}}","symbol":"{{ticker}}","volume":0.1,"sl_pips":20,"tp_pips":40,"id":"{{timenow}}"}
Skynet alerts
Alerts written for Skynet (skynet.sbs, including its MT5 Alert Generator) work on HostMT5 unchanged. To connect them:
- Dashboard → AI & API → Create webhook on the MT5 account and copy the URL.
- In each TradingView alert, replace the Skynet webhook URL with the HostMT5 URL. Keep the message as it is.
- Skynet closes the opposite side before a new entry. To get the same here, open Settings on the webhook and tick Close opposite positions.
- Send
{"action":"ping"}once. The log shows pong with your balance, and nothing is traded.
| Skynet sends | HostMT5 does |
|---|---|
buy long enterlong golong · sell short entershort goshort | Market buy / sell |
buylimit selllimit buystop sellstop | Pending order at price |
close exit flat closeposition exitlong exitshort | Close the symbol's positions |
closeall flatten closeeverything | Close every position |
closebuy closelong · closesell closeshort | Close only buys / only sells |
closepartial partialclose reduce scaleout takepartial | Close volume lots, oldest position first |
flipbuy fullyalgobuy reversebuy · flipsell … | Close everything on the symbol, then buy / sell |
modify setsltp · cancel cancelall · ping test | New stops · delete pending orders · answer without trading |
Skynet's field names are accepted too: order/signal/type for the action, instrument, size/amount, stop/stoploss/stop_loss, takeprofit/take_profit/target, limit/stopprice, sl_pct/tp_pct and their variants, and strategy/alert as the comment. The KEY=VALUE; text format works too:
{"action":"flipbuy","symbol":"EURUSD","volume":0.1}
{"action":"buylimit","symbol":"EURUSD","volume":0.1,"price":1.0800,"sl":1.0750,"tp":1.0900}
{"action":"closepartial","symbol":"XAUUSD","volume":0.05}
{"action":"{{strategy.order.action}}","symbol":"{{ticker}}","volume":0.1,"comment":"{{strategy.order.id}}"}
ACTION=buy;SYMBOL=EURUSD;VOL=0.1;SL=200;TP=400;ID=a1
PineConnector alerts
PineConnector-style messages work as they are, including the licence id at the start: 123456,buy,EURUSD,vol_lots=0.1,sl_pips=20,tp_pips=40. The older risk=, sl=, tp= work as well. Plain words work too: buy EURUSD 0.1 sl_pips=20.
Errors
Errors are JSON, and detail is always one readable string, so print(r.json()["detail"]) always works:
{"detail": "Broker refused: No money"}
A request that fails the parameter checks (a missing field, "side": "SELL" instead of "sell", broken JSON) is a 422 that also carries the list of problems in errors. Several problems are joined with ; in detail:
{"detail": "side: Input should be 'buy' or 'sell' (got 'SELL')",
"errors": [{"loc": ["body", "side"], "msg": "Input should be 'buy' or 'sell'", "type": "literal_error", "input": "SELL"}]}
{"detail": "volume: Field required",
"errors": [{"loc": ["body", "volume"], "msg": "Field required", "type": "missing", "input": {"symbol": "EURUSD", "side": "buy"}}]}
Every refused trade call is also written to your API activity log, so a bot that ignores its replies still leaves a trace.
400 422 | Bad parameters, or the broker / terminal refused (the broker's reason is in detail, e.g. Broker refused: Invalid stops). |
401 403 | Missing or wrong key / read-only key used for a change. |
404 | Not your account, unknown symbol or ticket. |
409 | The account is not online (stopped, or not logged in yet). |
429 | Rate limit: wait Retry-After seconds. |
503 504 | The terminal is restarting or slow. Retry in a few seconds. The SDKs retry reads, and orders with client_id are safe to retry. |
Times and symbols
- Bar, tick and deal times are MT5's own: broker server time written as Unix seconds, the same numbers MetaTrader 5 and its Python package use.
from/totake the same, or ISO dates like2026-11-20or2026-11-20T09:30. Quote times are milliseconds. - Symbols are your broker's exact names (
XAUUSD,XAUUSD.m,GOLD…). Find them with/symbols?search=. - History depth: the 500,000 newest bars of each symbol and timeframe, as far back as your broker serves them (M1 about 1.4 years, M5 about 7 years). Each call returns up to 50,000 bars; page back with
to, or lethistory()do it. The first request for very old data can take a minute while MT5 downloads it from the broker; the clients retry by themselves.
Questions: [email protected] · HostMT5 · Guides · Terms