Real-time
WebSocket streams
5 streams of realtime market and intelligence data over one persistent connection.
Why WebSocket
- Base URL
- wss://api.realmarketapi.com
- Auth
- apiKey query parameter
- Format
- JSON
No polling overhead
Candles are pushed to you the moment they close. No repeated HTTP calls.
Market-aware usage
Open sockets can stay connected, but request usage follows billable market updates during active sessions rather than idle connection time.
Lower latency
Avoid TCP setup, TLS negotiation, and HTTP framing on each update.
Multiple stream shapes
Price, candles, order-flow imbalance, market-wide, and multi-timeframe streams all use plain JSON payloads.
All streams
| Stream | Name | Plan |
|---|---|---|
| WSS/price | Latest Price Stream | Plus+ |
| WSS/candles | Rolling Candles Stream | Plus+ |
| WSS/market | Market Snapshot Stream | Plus+ |
| WSS/multi-timeframe | Multi-Timeframe Trend Stream | Pro+ |
| WSS/orderflow/imbalance | Order Flow Imbalance Stream | Pro+ |
Market Streams
Latest Price Stream
Streams one live OHLCV candle frame for a single symbol/timeframe whenever the current candle closes.
Query parameters
| Name | Type | Description |
|---|---|---|
| apiKeyrequired | string | Your API authentication key. |
| symbolCoderequired | string | Trading symbol (e.g. XAUUSD, EURUSD, BTCUSD). |
| timeFramerequired | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
Response fields
| Field | Type | Description |
|---|---|---|
| SymbolCode | string | Symbol identifier. |
| OpenPrice | number | Open price of the candle. |
| ClosePrice | number | Close price of the candle. |
| HighPrice | number | Highest price in the candle. |
| LowPrice | number | Lowest price in the candle. |
| Bid | number | Best bid price. |
| Ask | number | Best ask price. |
| Volume | number | Trade volume. |
| OpenTime | ISO 8601 | Candle open time (UTC). |
CONNECT wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1{
"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-11T09:20:00Z"
}Rolling Candles Stream
Streams the rolling 100-candle window for a symbol/timeframe. Each message is a full array with the newest candle at index 0.
Unlike /price, this stream does not include Bid or Ask. Each frame is a JSON array of up to 100 OHLCV candles; the first element is always the newest candle.
Query parameters
| Name | Type | Description |
|---|---|---|
| apiKeyrequired | string | Your API authentication key. |
| symbolCoderequired | string | Trading symbol (e.g. XAUUSD, EURUSD, BTCUSD). |
| timeFramerequired | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
Response fields
| Field | Type | Description |
|---|---|---|
| [] | candle[] | Array of up to 100 candles, newest first. |
| [].SymbolCode | string | Symbol identifier. |
| [].OpenPrice | number | Open price. |
| [].ClosePrice | number | Close price. |
| [].HighPrice | number | Highest price. |
| [].LowPrice | number | Lowest price. |
| [].Volume | number | Volume for this candle. |
| [].OpenTime | ISO 8601 | Candle open time (UTC). |
CONNECT wss://api.realmarketapi.com/candles?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1[
{
"SymbolCode": "XAUUSD",
"OpenPrice": 5174.00,
"ClosePrice": 5176.00,
"HighPrice": 5178.50,
"LowPrice": 5173.20,
"Volume": 1312.10,
"OpenTime": "2026-03-11T09:21:00Z"
},
{
"SymbolCode": "XAUUSD",
"OpenPrice": 5168.43,
"ClosePrice": 5174.00,
"HighPrice": 5176.85,
"LowPrice": 5165.20,
"Volume": 1249.33,
"OpenTime": "2026-03-11T09:20:00Z"
}
// … up to 100 candles total, newest first
]Code examples
// Node.js / Browser — /candles endpoint (list of 100 candles, newest first)
const ws = new WebSocket(
"wss://api.realmarketapi.com/candles?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
)
ws.onopen = () => console.log("[RealMarketAPI] Candles stream connected")
ws.onmessage = ({ data }) => {
const candles = JSON.parse(data) // array, candles[0] is newest
console.log(`Received ${candles.length} candles`)
console.log("Latest:", candles[0].SymbolCode, candles[0].ClosePrice)
}
ws.onerror = (err) => console.error("[RealMarketAPI] Error", err)
ws.onclose = () => console.log("[RealMarketAPI] Disconnected")# Python — /candles endpoint (requires: pip install websockets)
import asyncio, json, websockets
API_KEY = "YOUR_API_KEY"
SYMBOL = "XAUUSD"
TIMEFRAME = "M1"
URI = f"wss://api.realmarketapi.com/candles?apiKey={API_KEY}&symbolCode={SYMBOL}&timeFrame={TIMEFRAME}"
async def stream():
async with websockets.connect(URI) as ws:
print("[RealMarketAPI] Candles stream connected")
async for message in ws:
candles = json.loads(message) # list, candles[0] is newest
print(f"Received {len(candles)} candles")
print("Latest:", candles[0]["SymbolCode"], candles[0]["ClosePrice"])
asyncio.run(stream())// C# — /candles endpoint (built-in .NET WebSockets)
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
const string apiKey = "YOUR_API_KEY";
const string symbol = "XAUUSD";
const string timeFrame = "M1";
var uri = new Uri($"wss://api.realmarketapi.com/candles?apiKey={apiKey}&symbolCode={symbol}&timeFrame={timeFrame}");
using var ws = new ClientWebSocket();
await ws.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("[RealMarketAPI] Candles stream connected");
var buffer = new byte[65536];
while (ws.State == WebSocketState.Open)
{
var result = await ws.ReceiveAsync(buffer, CancellationToken.None);
var json = Encoding.UTF8.GetString(buffer, 0, result.Count);
var candles = JsonDocument.Parse(json).RootElement; // array, [0] is newest
Console.WriteLine($"Received {candles.GetArrayLength()} candles");
Console.WriteLine($"Latest: {candles[0].GetProperty("SymbolCode")} Close={candles[0].GetProperty("ClosePrice")}");
}// Java — /candles endpoint (requires: org.java-websocket:Java-WebSocket)
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import java.net.URI;
public class WsCandles extends WebSocketClient {
public WsCandles(URI uri) { super(uri); }
@Override public void onOpen(ServerHandshake h) { System.out.println("Candles stream connected"); }
@Override public void onMessage(String msg) {
JSONArray candles = new JSONArray(msg); // candles.get(0) is newest
System.out.println("Received " + candles.length() + " candles");
System.out.println("Latest: " + candles.getJSONObject(0).getString("SymbolCode")
+ " " + candles.getJSONObject(0).getDouble("ClosePrice"));
}
@Override public void onClose(int c, String r, boolean i) { System.out.println("Closed: " + r); }
@Override public void onError(Exception e) { e.printStackTrace(); }
public static void main(String[] args) throws Exception {
var uri = new URI("wss://api.realmarketapi.com/candles?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1");
new WsCandles(uri).connect();
}
}// Go — /candles endpoint (requires: github.com/gorilla/websocket)
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gorilla/websocket"
)
type Candle struct {
SymbolCode string `json:"SymbolCode"`
ClosePrice float64 `json:"ClosePrice"`
OpenTime string `json:"OpenTime"`
}
func main() {
url := "wss://api.realmarketapi.com/candles?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil { log.Fatal(err) }
defer conn.Close()
fmt.Println("[RealMarketAPI] Candles stream connected")
for {
_, msg, err := conn.ReadMessage()
if err != nil { log.Println("Disconnected:", err); break }
var candles []Candle
json.Unmarshal(msg, &candles) // candles[0] is newest
fmt.Printf("Received %d candles. Latest: %s %.2f\n",
len(candles), candles[0].SymbolCode, candles[0].ClosePrice)
}
}Market Snapshot Stream
Streams market-wide snapshots across all symbols available on your plan over one persistent WebSocket connection.
Query parameters
| Name | Type | Description |
|---|---|---|
| apiKeyrequired | string | Your API authentication key. |
Response fields
| Field | Type | Description |
|---|---|---|
| [] | OHLCV[] | Array of latest candles for all symbols in your plan. |
| [].SymbolCode | string | Symbol identifier. |
| [].OpenPrice | number | Open price of the candle. |
| [].ClosePrice | number | Close price of the candle. |
| [].HighPrice | number | Highest price in the candle. |
| [].LowPrice | number | Lowest price in the candle. |
| [].Bid | number | Best bid price. |
| [].Ask | number | Best ask price. |
| [].Volume | number | Trade volume. |
| [].OpenTime | ISO 8601 | Candle open time (UTC). |
CONNECT wss://api.realmarketapi.com/market?apiKey=YOUR_API_KEY[
{
"SymbolCode": "XAUUSD",
"OpenPrice": 2348.12,
"ClosePrice": 2351.84,
"HighPrice": 2354.00,
"LowPrice": 2346.10,
"Bid": 2351.70,
"Ask": 2352.30,
"Volume": 1284.47,
"OpenTime": "2026-03-08T09:20:00Z"
},
{
"SymbolCode": "EURUSD",
"OpenPrice": 1.09320,
"ClosePrice": 1.09365,
"HighPrice": 1.09390,
"LowPrice": 1.09305,
"Bid": 1.09362,
"Ask": 1.09368,
"Volume": 842.31,
"OpenTime": "2026-03-08T09:20:00Z"
}
// ... one OHLCV object per accessible symbol
]Intelligence Streams
Multi-Timeframe Trend Stream
Streams per-timeframe trend classification for one symbol in a single frame (no timeFrame query parameter required).
Query parameters
| Name | Type | Description |
|---|---|---|
| apiKeyrequired | string | Your API authentication key. |
| symbolCoderequired | string | Trading symbol (e.g. XAUUSD, EURUSD, BTCUSD). |
Response fields
| Field | Type | Description |
|---|---|---|
| symbolCode | string | Symbol identifier. |
| calculatedAt | ISO 8601 | Analysis timestamp (UTC). |
| timeframes | object | Dictionary keyed by timeframe. |
| timeframes[key] | string | StrongBullish | Bullish | Neutral | Bearish | StrongBearish. |
CONNECT wss://api.realmarketapi.com/multi-timeframe?apiKey=YOUR_API_KEY&symbolCode=XAUUSD{
"symbolCode": "XAUUSD",
"calculatedAt": "2026-03-08T09:20:00Z",
"timeframes": {
"M1": "Bullish",
"M5": "Bullish",
"M15": "StrongBullish",
"H1": "Neutral",
"H4": "Bearish",
"D1": "StrongBearish"
}
}Order Flow Imbalance Stream
Streams bullish/bearish order-flow imbalance metrics and recent large-body imbalance zones for one symbol/timeframe.
Query parameters
| Name | Type | Description |
|---|---|---|
| apiKeyrequired | string | Your API authentication key. |
| symbolCoderequired | string | Trading symbol (e.g. XAUUSD, EURUSD, BTCUSD). |
| timeFramerequired | string | Candle interval: M1 · M5 · M15 · H1 · H4 · D1. |
Response fields
| Field | Type | Description |
|---|---|---|
| symbolCode | string | Symbol identifier. |
| timeFrame | string | Requested timeframe. |
| calculatedAt | ISO 8601 | Calculation timestamp (UTC). |
| currentImbalance | string | Bullish | Bearish | Neutral. |
| bullishRatio | number | Percentage of bullish candles in the analysis window. |
| bearishRatio | number | Percentage of bearish candles in the analysis window. |
| recentImbalanceZones | array | Recent large-body imbalance candles. |
| recentImbalanceZones[].openTime | ISO 8601 | Candle open timestamp. |
| recentImbalanceZones[].open | number | Candle open price. |
| recentImbalanceZones[].close | number | Candle close price. |
| recentImbalanceZones[].direction | string | Bullish | Bearish. |
| recentImbalanceZones[].bodyMultiplier | number | Body size relative to average. |
| recentImbalanceZones[].volume | number | Volume of the zone candle. |
CONNECT wss://api.realmarketapi.com/orderflow/imbalance?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1{
"symbolCode": "XAUUSD",
"timeFrame": "M1",
"calculatedAt": "2026-03-08T09:20:00Z",
"currentImbalance": "Bullish",
"bullishRatio": 64.0,
"bearishRatio": 36.0,
"recentImbalanceZones": [
{
"openTime": "2026-03-08T09:18:00Z",
"open": 2349.80,
"close": 2351.10,
"direction": "Bullish",
"bodyMultiplier": 2.30,
"volume": 3840.0
}
]
}Multiple symbols
/price, /candles and /orderflow/imbalance streams subscribe to one symbol or symbol-and-timeframe pair. For broader coverage use /multi-timeframe for one symbol across all timeframes, or /market for plan-wide snapshots on a single connection.Tip
// JavaScript — multiple symbol subscriptions (one connection per symbol/TF pair)
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) {
console.log(candle.SymbolCode, candle.OpenTime, candle.ClosePrice)
}# Python — multiple subscriptions with asyncio
import asyncio, json, websockets
API_KEY = "YOUR_API_KEY"
SUBS = [
("XAUUSD", "M1"),
("BTCUSD", "M5"),
("EURUSD", "H1"),
]
async def stream(symbol, timeframe):
uri = f"wss://api.realmarketapi.com/price?apiKey={API_KEY}&symbolCode={symbol}&timeFrame={timeframe}"
async for ws in websockets.connect(uri):
try:
async for message in ws:
candle = json.loads(message)
print(f"{candle['SymbolCode']:10} {candle['ClosePrice']}")
except websockets.ConnectionClosed:
continue
async def main():
await asyncio.gather(*[stream(s, tf) for s, tf in SUBS])
asyncio.run(main())// C# — multiple subscriptions concurrently
using System.Net.WebSockets;
using System.Text;
const string apiKey = "YOUR_API_KEY";
var subs = new[] {
("XAUUSD", "M1"),
("BTCUSD", "M5"),
("EURUSD", "H1"),
};
var tasks = subs.Select(async sub =>
{
var (symbol, tf) = sub;
var uri = new Uri($"wss://api.realmarketapi.com/price?apiKey={apiKey}&symbolCode={symbol}&timeFrame={tf}");
using var ws = new ClientWebSocket();
await ws.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine($"Connected: {symbol}/{tf}");
var buf = new byte[4096];
while (ws.State == WebSocketState.Open)
{
var r = await ws.ReceiveAsync(buf, CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(buf, 0, r.Count));
}
});
await Task.WhenAll(tasks);# Ruby — multiple subscriptions with threads
require 'websocket-client-simple'
require 'json'
API_KEY = 'YOUR_API_KEY'
SUBS = [
['XAUUSD', 'M1'],
['BTCUSD', 'M5'],
['EURUSD', 'H1'],
]
threads = SUBS.map do |symbol, timeframe|
Thread.new do
url = "wss://api.realmarketapi.com/price?apiKey=#{API_KEY}&symbolCode=#{symbol}&timeFrame=#{timeframe}"
ws = WebSocket::Client::Simple.connect(url)
ws.on(:message) do |msg|
candle = JSON.parse(msg.data)
puts "#{candle['SymbolCode']} #{candle['ClosePrice']}"
end
sleep 1 while ws.open?
end
end
threads.each(&:join)// Dart — multiple subscriptions concurrently
import 'dart:io';
import 'dart:convert';
const apiKey = 'YOUR_API_KEY';
const subs = [
('XAUUSD', 'M1'),
('BTCUSD', 'M5'),
('EURUSD', 'H1'),
];
Future<void> streamSymbol(String symbol, String timeFrame) async {
final url = 'wss://api.realmarketapi.com/price?apiKey=$apiKey&symbolCode=$symbol&timeFrame=$timeFrame';
final ws = await WebSocket.connect(url);
await for (final msg in ws) {
final candle = jsonDecode(msg as String) as Map<String, dynamic>;
print('${candle['SymbolCode']} ${candle['ClosePrice']}');
}
}
Future<void> main() async {
await Future.wait([for (final (s, tf) in subs) streamSymbol(s, tf)]);
}Code examples
// Node.js / Browser — basic WebSocket connection
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 = (err) => console.error("[RealMarketAPI] Error", err)
ws.onclose = () => console.log("[RealMarketAPI] Disconnected")# Python — requires: pip install websockets
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 with websockets.connect(URI) as ws:
print("[RealMarketAPI] Connected")
async for message in ws:
candle = json.loads(message)
print(candle["SymbolCode"], candle["ClosePrice"], candle["Bid"])
asyncio.run(stream())// C# — System.Net.WebSockets (built-in .NET)
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
const string apiKey = "YOUR_API_KEY";
const string symbol = "XAUUSD";
const string timeFrame = "M1";
var uri = new Uri($"wss://api.realmarketapi.com/price?apiKey={apiKey}&symbolCode={symbol}&timeFrame={timeFrame}");
using var ws = new ClientWebSocket();
await ws.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("[RealMarketAPI] Connected");
var buffer = new byte[4096];
while (ws.State == WebSocketState.Open)
{
var result = await ws.ReceiveAsync(buffer, CancellationToken.None);
var json = Encoding.UTF8.GetString(buffer, 0, result.Count);
var candle = JsonDocument.Parse(json).RootElement;
Console.WriteLine($"{candle.GetProperty("SymbolCode")} Close={candle.GetProperty("ClosePrice")}");
}// Java 11+ — requires: org.java-websocket:Java-WebSocket
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class WsBasic extends WebSocketClient {
public WsBasic(URI uri) { super(uri); }
@Override public void onOpen(ServerHandshake h) { System.out.println("Connected"); }
@Override public void onMessage(String msg) { System.out.println(msg); }
@Override public void onClose(int c, String r, boolean i) { System.out.println("Closed: " + r); }
@Override public void onError(Exception e) { e.printStackTrace(); }
public static void main(String[] args) throws Exception {
var uri = new URI("wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1");
new WsBasic(uri).connect();
}
}// Go — requires: github.com/gorilla/websocket
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gorilla/websocket"
)
func main() {
url := "wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil { log.Fatal(err) }
defer conn.Close()
fmt.Println("[RealMarketAPI] Connected")
for {
_, msg, err := conn.ReadMessage()
if err != nil { log.Println("Disconnected:", err); break }
var candle map[string]interface{}
json.Unmarshal(msg, &candle)
fmt.Println(candle["SymbolCode"], candle["ClosePrice"])
}
}# Ruby — requires: gem install websocket-client-simple
require 'websocket-client-simple'
require 'json'
url = "wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1"
ws = WebSocket::Client::Simple.connect(url)
ws.on(:open) { puts '[RealMarketAPI] Connected' }
ws.on(:message) do |msg|
candle = JSON.parse(msg.data)
puts "#{candle['SymbolCode']} #{candle['ClosePrice']} Bid:#{candle['Bid']}"
end
ws.on(:error) { |e| puts "[RealMarketAPI] Error: #{e.message}" }
ws.on(:close) { puts '[RealMarketAPI] Disconnected' }
loop { sleep 1 }// Dart — built-in WebSocket support (dart:io)
import 'dart:io';
import 'dart:convert';
void main() async {
final ws = await WebSocket.connect(
'wss://api.realmarketapi.com/price?apiKey=YOUR_API_KEY&symbolCode=XAUUSD&timeFrame=M1',
);
print('[RealMarketAPI] Connected');
await for (final message in ws) {
final candle = jsonDecode(message as String) as Map<String, dynamic>;
print('${candle['SymbolCode']} ${candle['ClosePrice']} Bid:${candle['Bid']}');
}
}Auto-reconnect pattern
Back-off strategy
- Start at 1 second on the first disconnect.
- Double the delay on each consecutive failure.
- Cap at 30 seconds to bound the maximum wait.
- Reset to 1 second on every successful
onopenevent.
// JavaScript — auto-reconnect with exponential back-off (production)
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 delay = 1_000 // start at 1 s
function connect() {
ws = new WebSocket(WS_URL)
ws.onopen = () => {
console.log("Connected")
delay = 1_000 // reset on successful connection
}
ws.onmessage = ({ data }) => {
const candle = JSON.parse(data)
console.log(candle.SymbolCode, candle.ClosePrice)
}
ws.onclose = () => {
console.warn(`Disconnected. Reconnecting in ${delay}ms…`)
setTimeout(connect, delay)
delay = Math.min(delay * 2, 30_000) // cap at 30 s
}
ws.onerror = (e) => console.error("WS error", e)
}
connect()# Python — auto-reconnect pattern (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():
# websockets.connect() has built-in retry with exponential back-off
async for ws in websockets.connect(URI):
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())// C# — auto-reconnect with exponential back-off
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
const string apiKey = "YOUR_API_KEY";
const string symbol = "XAUUSD";
const string timeFrame = "M1";
var uri = new Uri($"wss://api.realmarketapi.com/price?apiKey={apiKey}&symbolCode={symbol}&timeFrame={timeFrame}");
int delayMs = 1_000;
while (true)
{
try
{
using var ws = new ClientWebSocket();
await ws.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("Connected");
delayMs = 1_000;
var buf = new byte[4096];
while (ws.State == WebSocketState.Open)
{
var r = await ws.ReceiveAsync(buf, CancellationToken.None);
var json = Encoding.UTF8.GetString(buf, 0, r.Count);
var c = JsonDocument.Parse(json).RootElement;
Console.WriteLine($"{c.GetProperty("SymbolCode")} {c.GetProperty("ClosePrice")}");
}
}
catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); }
Console.WriteLine($"Reconnecting in {delayMs}ms…");
await Task.Delay(delayMs);
delayMs = Math.Min(delayMs * 2, 30_000);
}// Java — auto-reconnect with exponential back-off
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class WsReconnect extends WebSocketClient {
private int delayMs = 1_000;
public WsReconnect(URI uri) { super(uri); }
@Override public void onOpen(ServerHandshake h) {
System.out.println("Connected");
delayMs = 1_000;
}
@Override public void onMessage(String msg) { System.out.println(msg); }
@Override public void onClose(int c, String reason, boolean remote) {
System.out.println("Closed: " + reason + ". Reconnecting in " + delayMs + "ms…");
new Thread(() -> {
try { Thread.sleep(delayMs); } catch (InterruptedException ignored) {}
delayMs = Math.min(delayMs * 2, 30_000);
reconnect();
}).start();
}
@Override public void onError(Exception e) { e.printStackTrace(); }
}# Ruby — auto-reconnect with exponential back-off
require 'websocket-client-simple'
require 'json'
API_KEY = 'YOUR_API_KEY'
SYMBOL = 'XAUUSD'
TIMEFRAME = 'M1'
URL = "wss://api.realmarketapi.com/price?apiKey=#{API_KEY}&symbolCode=#{SYMBOL}&timeFrame=#{TIMEFRAME}"
delay = 1.0
loop do
begin
ws = WebSocket::Client::Simple.connect(URL)
ws.on(:open) { delay = 1.0; puts 'Connected' }
ws.on(:message) do |msg|
candle = JSON.parse(msg.data)
puts "#{candle['SymbolCode']} #{candle['ClosePrice']}"
end
ws.on(:close) { puts 'Disconnected' }
sleep 1 while ws.open?
rescue => e
puts "Error: #{e.message}"
end
puts "Reconnecting in #{delay}s…"
sleep delay
delay = [delay * 2, 30.0].min
end// Dart — auto-reconnect with exponential back-off
import 'dart:io';
import 'dart:convert';
const apiKey = 'YOUR_API_KEY';
const symbol = 'XAUUSD';
const timeFrame = 'M1';
const url = 'wss://api.realmarketapi.com/price?apiKey=$apiKey&symbolCode=$symbol&timeFrame=$timeFrame';
Future<void> main() async {
var delayMs = 1000;
while (true) {
try {
final ws = await WebSocket.connect(url);
print('Connected');
delayMs = 1000;
await for (final message in ws) {
final candle = jsonDecode(message as String) as Map<String, dynamic>;
print('${candle['SymbolCode']} ${candle['ClosePrice']}');
}
} catch (e) {
print('Error: $e');
}
print('Reconnecting in ${delayMs}ms…');
await Future.delayed(Duration(milliseconds: delayMs));
delayMs = (delayMs * 2).clamp(0, 30000);
}
}Try it in the Playground
Open a live WebSocket stream in the browser and inspect each frame.