Tài liệu tham khảo RealMarketAPI
Dữ liệu OHLCV thời gian thực và lịch sử cho vàng, forex, tiền điện tử và chỉ số — qua REST và WebSocket.
URL cơ sở REST
https://api.realmarketapi.comURL cơ sở WebSocket
wss://api.realmarketapi.comXác thực
?apiKey=YOUR_KEYBest Practices
Understanding when to use WebSocket versus REST is the single most impactful decision for your integration. WebSocket should be your default choice for any live data; REST is a fallback for specific, bounded queries.
Prefer WebSocket for all live price data
A single persistent WebSocket connection delivers every new candle the moment it closes — with zero polling overhead, zero extra rate-limit consumption, and lower latency than any HTTP request. If you find yourself polling /api/v1/price on a timer, switch to WebSocket instead.
| Use case | WebSocket ✓ | REST ✓ |
|---|---|---|
| Live price ticker / chart | ✅ Ideal — server pushes every candle | ⚠️ Works, but wastes requests on polling |
| Trading signal engine | ✅ Near-zero latency per candle | ⚠️ Latency gap between polls |
| Real-time bid/ask spread | ✅ Updated with every frame | ❌ Not suitable |
| Historical back-fill on startup | ❌ Not designed for bulk history | ✅ Use /history with pagination |
| One-off price snapshot | ⚠️ Overhead to open a connection | ✅ Single GET is simpler |
| Backtesting / research queries | ❌ Not applicable | ✅ Use /history with date ranges |
| Available symbols lookup | ❌ Not applicable | ✅ Use GET /api/v1/symbol |
❌ Anti-patterns to avoid
- •Polling
/api/v1/priceon a short timer — every poll burns a request from your plan quota and adds HTTP round-trip latency vs a push model. - •Opening a new WebSocket per request — connect once per symbol/timeframe pair and keep the connection alive. Repeated open/close cycles exhaust rate limits.
- •No reconnect logic in production — networks drop. Always implement exponential back-off reconnection (see the reconnect pattern below).
- •Using WebSocket to fetch historical data — the WebSocket endpoint streams live candles only. Use
/api/v1/historyfor past data, then switch to WS for live updates.
✅ Recommended integration pattern
- 1.On app start, call
/api/v1/historyto back-fill the initial candle series you need for charts or indicators. - 2.Open a WebSocket connection for each symbol+timeframe pair you need to track live. Keep connections persistent.
- 3.Append each incoming WebSocket frame to your local candle series — no further REST calls needed for live data.
- 4.Implement exponential back-off reconnection so your app recovers automatically from transient network failures.
- 5.Reserve
/api/v1/priceonly for one-off snapshots or server-side jobs that do not maintain a persistent connection.
Authentication
Every request must include your apiKey as a query parameter. Generate your key from the dashboard.
| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your secret API key. Passed as a query param on all REST and WebSocket connections. |
GEThttps://api.realmarketapi.com/api/v1/price?apiKey=rm_live_XXXXXXXX&symbolCode=XAUUSD&timeFrame=M1
Timeframes
Pass one of the following values in the timeFrame query parameter. The value is case-sensitive.
M11 Minute
Ultra-short-term scalping & HFT
M55 Minutes
Short-term scalping & intraday signals
M1515 Minutes
Intraday trend confirmation & entries
H11 Hour
Session-level trend & momentum
H44 Hours
Swing setups with reduced noise
D11 Day
Higher-timeframe trend & macro direction
Symbol Codes
Pass one of the following values in the symbolCode query parameter. All codes are uppercase.
Showing 13 of 13 symbols
XAUUSDGold / US DollarXAGUSDSilver / US DollarUSDJPYUS Dollar / YenEURUSDEuro / US DollarGBPUSDBritish Pound / DollarUSDVNDUS Dollar / Vietnamese DongBTCUSDBitcoin / US DollarETHUSDEthereum / US DollarXRPUSDXRP / US DollarUSOILUS Crude Oil (WTI)UKOILBrent Crude OilUS500S&P 500 IndexUS30Dow Jones 30 Index/api/v1/price
Returns the latest completed OHLCV candle for the requested symbol and timeframe.
| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your API key. |
| symbolCode* | string | Market symbol. One of: XAUUSD, XAGUSD, USDJPY, EURUSD, GBPUSD, USDVND, BTCUSD, ETHUSD, XRPUSD, USOIL, UKOIL, US500, US30. |
| timeFrame* | string | Candle interval. One of: M1, M5, M15, H1, H4, D1. |
Request
GEThttps://api.realmarketapi.com/api/v1/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1
Response — 200 OK
{ "SymbolCode": "XAUUSD", "OpenPrice": 5168.43, "ClosePrice": 5174.00, "HighPrice": 5176.85, "LowPrice": 5165.20, "Bid": 5173.75, "Ask": 5174.25, "Volume": 1249.33, "OpenTime": "2026-03-08T09:20:00Z" }
/api/v1/history
Returns a paginated list of historical OHLCV candles for the requested symbol, timeframe, and date range.
ERR_0010_NOT_SUPPORT_HISTORICAL. View plans to see which tiers include historical access.| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your API key. |
| symbolCode* | string | Market symbol code (e.g. XAUUSD, BTCUSD). |
| timeFrame* | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
| startTime* | ISO 8601 | Range start date-time, e.g. 2026-01-01T00:00:00Z. |
| endTime* | ISO 8601 | Range end date-time, e.g. 2026-03-08T23:59:59Z. |
| pageNumber | integer | Page number, 1-based. Defaults to 1. |
| pageSize | integer | Number of candles per page. Max: 100. Defaults to 10. |
Request
GEThttps://api.realmarketapi.com/api/v1/history?apiKey=YOUR_API_KEY&symbolCode=ETHUSD&timeFrame=H1&startTime=2026-02-08T00:00:00Z&endTime=2026-03-08T00:00:00Z&pageNumber=1&pageSize=10
Response — 200 OK
{ "Data": [ { "SymbolCode": "ETHUSD", "OpenPrice": 3120.22, "ClosePrice": 3138.44, "HighPrice": 3142.07, "LowPrice": 3115.13, "Bid": 3138.30, "Ask": 3138.58, "Volume": 432.58, "OpenTime": "2026-03-08T08:00:00Z" }, { "SymbolCode": "ETHUSD", "OpenPrice": 3138.44, "ClosePrice": 3144.11, "HighPrice": 3150.90, "LowPrice": 3132.50, "Bid": 3143.97, "Ask": 3144.25, "Volume": 509.76, "OpenTime": "2026-03-08T09:00:00Z" } ], "TotalCount": 240, "CurrentPage": 1, "TotalPages": 24, "PageSize": 10 }
/api/v1/candle
Returns the latest completed OHLCV candles (most recent first) for the requested symbol and timeframe. Useful for seeding a chart with recent bars on first load without needing a date range.
ERR_0010_NOT_SUPPORT_HISTORICAL. View plans to see which tiers include historical access.| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your API key. |
| symbolCode* | string | Market symbol code (e.g. XAUUSD, BTCUSD). |
| timeFrame* | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
| pageNumber | integer | Page number, 1-based. Defaults to 1. |
| pageSize | integer | Number of candles per page. Max: 50. Defaults to 10. |
Request
GEThttps://api.realmarketapi.com/api/v1/candle?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1&pageNumber=1&pageSize=10
Response — 200 OK
{ "Data": [ { "SymbolCode": "XAUUSD", "OpenPrice": 5168.43, "ClosePrice": 5174.00, "HighPrice": 5176.85, "LowPrice": 5165.20, "Volume": 1249.33, "OpenTime": "2026-03-08T09:20:00Z" }, { "SymbolCode": "XAUUSD", "OpenPrice": 5162.80, "ClosePrice": 5168.43, "HighPrice": 5169.75, "LowPrice": 5160.50, "Volume": 986.17, "OpenTime": "2026-03-08T09:19:00Z" } ], "TotalCount": 1440 }
| Field | Type | Description |
|---|---|---|
| Data | array | Ordered list of candles, most-recent first. |
| TotalCount | integer | Total number of available candles for the symbol / timeframe. |
| SymbolCode | string | Market symbol identifier (e.g. XAUUSD). |
| OpenPrice | number | Price at candle open. |
| ClosePrice | number | Price at candle close. |
| HighPrice | number | Highest price during the candle period. |
| LowPrice | number | Lowest price during the candle period. |
| Volume | number | Traded volume during the candle period. |
| OpenTime | ISO 8601 | UTC timestamp of the candle open. |
/api/v1/symbol
Returns the list of all available symbols your API key has access to.
| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your API key. |
Request
GEThttps://api.realmarketapi.com/api/v1/symbol?apiKey=YOUR_API_KEY
Response — 200 OK
{ "Data": [ { "SymbolCode": "XAUUSD", "DisplayName": "Gold / US Dollar", "MarketClass": "Metals" }, { "SymbolCode": "BTCUSD", "DisplayName": "Bitcoin / US Dollar","MarketClass": "Crypto" }, { "SymbolCode": "US500", "DisplayName": "US 500 Index", "MarketClass": "Indices" } ], "TotalCount": 12 }
/api/v1/health
Returns the current health status of the API. No authentication required. Use this endpoint to verify connectivity or monitor API availability from your own infrastructure.
Request
GEThttps://api.realmarketapi.com/api/v1/health
Response — 200 OK
{ "Status": "Healthy", "Timestamp": "2026-03-07T15:05:05.846Z" }
| Field | Type | Description |
|---|---|---|
| Status | string | API status. Either "Healthy" or "Unhealthy". |
| Timestamp | ISO 8601 | UTC timestamp of the health check response. |
/price
Opens a persistent WebSocket connection. The server pushes a new OHLCV frame after each completed candle. The connection URL follows the same parameter convention as the REST endpoints.
⚡ Recommended approach for live data
- •Zero polling overhead — candles are pushed to you the moment they close, no repeated HTTP calls.
- •Does not count against your requests/minute quota — the persistent connection is free to hold open; only the initial handshake counts.
- •Lower latency — avoid TCP setup, TLS negotiation, and HTTP framing on every update.
- •Identical response shape — the same OHLCV JSON you already know from REST, no extra parsing needed.
| Name | Type | Description |
|---|---|---|
| apiKey* | string | Your API key. |
| symbolCode* | string | Symbol to subscribe to (e.g. XAUUSD, BTCUSD). |
| timeFrame* | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
Connect
CONNECTwss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1
Incoming frame (JSON)
{ "SymbolCode": "XAUUSD", "OpenPrice": 5168.43, "ClosePrice": 5174.00, "HighPrice": 5176.85, "LowPrice": 5165.20, "Bid": 5173.75, "Ask": 5174.25, "Volume": 1249.33, "OpenTime": "2026-03-08T09:20:00Z" }
JavaScript example
// JavaScript — WebSocket (recommended for live data)
const ws = new WebSocket(
"wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
)
ws.onopen = () => console.log("[RealMarketAPI] Connected")
ws.onmessage = ({ data }) => {
const candle = JSON.parse(data)
console.log(candle.SymbolCode, candle.ClosePrice, candle.Bid, candle.Ask)
}
ws.onerror = (e) => console.error("[RealMarketAPI] WS error", e)
ws.onclose = () => console.log("[RealMarketAPI] Disconnected")Python example
# Python — WebSocket example (websockets library)
import asyncio, json, websockets
API_KEY = "YOUR_API_KEY"
SYMBOL = "XAUUSD"
TIMEFRAME = "M1"
URI = f"wss://api.realmarketapi.com/price?apiKey={API_KEY}&symbolCode={SYMBOL}&timeFrame={TIMEFRAME}"
async def stream():
async for ws in websockets.connect(URI): # auto-reconnect
try:
async for message in ws:
candle = json.loads(message)
print(candle["SymbolCode"], candle["ClosePrice"], candle["Bid"])
except websockets.ConnectionClosed:
print("Disconnected — retrying…")
continue
asyncio.run(stream())Multiple symbols
// JavaScript — Multiple symbols over separate connections
const subscriptions = [
{ symbol: "XAUUSD", timeFrame: "M1" },
{ symbol: "BTCUSD", timeFrame: "M5" },
{ symbol: "EURUSD", timeFrame: "H1" },
]
const connections = subscriptions.map(({ symbol, timeFrame }) => {
const ws = new WebSocket(
`wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=${symbol}&timeFrame=${timeFrame}`
)
ws.onmessage = ({ data }) => handleCandle(JSON.parse(data))
return ws
})
function handleCandle(candle) {
// dispatch candle to your state / store
console.log(candle.SymbolCode, candle.TimeFrame, candle.ClosePrice)
}WebSocket — Reconnect Pattern
Network interruptions happen. A production integration must implement automatic reconnection with exponential back-off — otherwise a single dropped connection silently stops your live feed.
Back-off strategy: start at 1 s, double on each failure, cap at 30 s. Reset to 1 s on every successful onopen event. This prevents thundering-herd reconnects after a server restart.
JavaScript — auto-reconnect (production)
// JavaScript — Auto-reconnect pattern (production recommended)
const API_KEY = "YOUR_API_KEY"
const SYMBOL = "XAUUSD"
const TIMEFRAME = "M1"
const WS_URL = `wss://api.realmarketapi.com/price?apiKey=${API_KEY}&symbolCode=${SYMBOL}&timeFrame=${TIMEFRAME}`
let ws
let reconnectDelay = 1000 // start at 1 s, then back off
function connect() {
ws = new WebSocket(WS_URL)
ws.onopen = () => {
console.log("Connected")
reconnectDelay = 1000 // reset on successful connection
}
ws.onmessage = ({ data }) => {
const candle = JSON.parse(data)
// ─── handle incoming candle ────────────────────────────
console.log(candle.SymbolCode, candle.ClosePrice)
}
ws.onclose = () => {
console.warn(`Disconnected. Reconnecting in ${reconnectDelay}ms…`)
setTimeout(connect, reconnectDelay)
reconnectDelay = Math.min(reconnectDelay * 2, 30_000) // cap at 30 s
}
ws.onerror = (e) => console.error("WS error", e)
}
connect()OHLCV Response Fields
All candle objects (from /price, /history, and WebSocket) share the same shape.
| Field | Type | Description |
|---|---|---|
| SymbolCode | string | Market symbol identifier (e.g. XAUUSD). |
| OpenPrice | number | Price at the start of the candle period. |
| ClosePrice | number | Price at the end of the candle period. |
| HighPrice | number | Highest traded price within the candle. |
| LowPrice | number | Lowest traded price within the candle. |
| Bid | number | Current best bid price at the time of the candle close. |
| Ask | number | Current best ask price at the time of the candle close. |
| Volume | number | Traded volume during the candle period. |
| OpenTime | string | ISO 8601 UTC timestamp marking the candle open. |
Error Handling
All errors follow a consistent JSON shape. Check StatusCode and inspect Errors[] for field-level detail.
| Code | Status | When it happens |
|---|---|---|
400 | Bad Request | Missing or invalid query parameters. |
401 | Unauthorized | API key missing or malformed. |
403 | Forbidden | API key does not have access to this symbol or endpoint. |
429 | Too Many Requests | Rate limit exceeded for your plan. |
500 | Internal Server Error | Unexpected server error. Please retry. |
Error response shape
{ "StatusCode": 400, "Message": "Validation failed for query parameters.", "Errors": [ { "PropertyName": "timeFrame", "ErrorCode": "ERR_0007_INVALID_TIME_FRAME", "ErrorMessage": "timeFrame must be one of M1, M5, M15, H1, H4, D1" }, { "PropertyName": "symbolCode", "ErrorCode": "ERR_0008_SYMBOL_NOT_SUPPORTED", "ErrorMessage": "symbolCode BTCUSDT is not supported" } ], "TraceId": "00-7a8ab3af4fce34f3872a28ec7ca8f5e1-886d2e1bc76dc9a4-00" }
Exception Codes
When a request fails, the Errors[] array contains one or more objects with a structured ErrorCode field. Use these codes for programmatic error handling.
| HTTP | Error Code | Description |
|---|---|---|
404 | ERR_0001_DATA_NOT_FOUND | No candle data found for the requested symbol and timeframe. The market may be closed or data is unavailable for the given period. |
401 | ERR_0005_INVALID_API_KEY | The provided API key is missing, malformed, revoked, or does not match any active key in the system. |
400 | ERR_0006_INVALID_TIME_RANGE | The startTime or endTime values are missing, in the wrong format, out of chronological order, or exceed the maximum allowed range for your plan. |
400 | ERR_0007_INVALID_TIME_FRAME | The timeFrame value is not one of the supported intervals. Accepted values: M1, M5, M15, H1, H4, D1. |
403 | ERR_0008_SYMBOL_NOT_SUPPORTED | The requested symbolCode is not supported on your current plan or does not exist in the system. |
403 | ERR_0009_NOT_SUPPORT_WEBSOCKET | Your current subscription plan does not include WebSocket access. Upgrade your plan to enable real-time streaming. |
403 | ERR_0010_NOT_SUPPORT_HISTORICAL | Your current subscription plan does not include access to the historical data endpoint. Upgrade your plan to query historical candles. |
403 | ERR_0012_EMAIL_NOT_VERIFIED | Your email address has not been verified. Verify your email from the dashboard before making API requests. |