Realtime
WebSocket connections, live chat, and real-time updates
Real-time communication via WebSocket and chat functionality.
WebSocket Support
Connect to our WebSocket server for real-time updates including live chat, price feeds, notifications, and instant messaging.
Overview
The Realtime Service provides:
- Live chat rooms
- WebSocket connections for real-time updates
- Online/offline status
- Typing indicators
- Real-time notifications
Base Path: /v1/chatrooms
WebSocket: ws://api.yourdomain.com/v1/live
Chatrooms
Get All Chatrooms
GET /v1/chatrooms| Parameter | Type | Description |
|---|---|---|
| page | number | Page number |
| limit | number | Results per page |
| type | string | public, private, group |
{
"success": true,
"status": 200,
"data": [
{
"id": "room_123",
"name": "EUR/USD Trading Room",
"description": "Discuss EUR/USD trades and strategies",
"type": "public",
"memberCount": 234,
"activeNow": 45,
"lastMessageAt": "2025-10-21T12:00:00.000Z",
"createdBy": "user_456",
"createdAt": "2025-01-15T00:00:00.000Z"
}
],
"pagination": {
"page": 1,
"limit": 20,
"total": 15,
"pages": 1
}
}Get Chatroom Details
GET /v1/chatrooms/:chatroomIdCreate Chatroom
POST /v1/chatrooms{
"name": "Gold Trading Strategies",
"description": "Discuss XAU/USD trading",
"type": "public"
}Update Chatroom
PUT /v1/chatrooms/:chatroomIdDelete Chatroom
DELETE /v1/chatrooms/:chatroomIdNote: Only creator or admin can delete
Messages
Get Chatroom Messages
GET /v1/chatrooms/:chatroomId/messages| Parameter | Type | Description |
|---|---|---|
| page | number | Page number |
| limit | number | Results per page (max: 100) |
{
"success": true,
"status": 200,
"data": [
{
"id": "msg_789",
"chatroomId": "room_123",
"userId": "user_456",
"user": {
"firstName": "John",
"lastName": "Doe",
"avatar": "https://..."
},
"message": "EUR/USD looking bullish on the 4H chart",
"createdAt": "2025-10-21T12:00:00.000Z"
}
],
"pagination": {
"page": 1,
"limit": 50,
"total": 1234,
"pages": 25
}
}Send Message
POST /v1/chatrooms/:chatroomId/messages{
"message": "Just entered a long position on EUR/USD at 1.0850"
}{
"success": true,
"status": 201,
"data": {
"id": "msg_790",
"chatroomId": "room_123",
"userId": "user_456",
"message": "Just entered a long position on EUR/USD at 1.0850",
"createdAt": "2025-10-21T12:01:00.000Z"
}
}Room Management
Join Chatroom
POST /v1/chatrooms/:chatroomId/joinLeave Chatroom
POST /v1/chatrooms/:chatroomId/leaveWebSocket Connection
Connect
const ws = new WebSocket('ws://api.yourdomain.com/v1/live');
// Authenticate after connection
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'auth',
token: 'your-jwt-token'
}));
};
// Receive messages
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log(message);
};Subscribe to Events
// Subscribe to specific chatroom
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'chatroom',
chatroomId: 'room_123'
}));
// Subscribe to user notifications
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'notifications',
userId: 'user_456'
}));
// Subscribe to market prices
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'market',
symbols: ['EUR/USD', 'GBP/JPY', 'XAU/USD']
}));Event Types
Chat Message
{
"type": "chat:message",
"data": {
"chatroomId": "room_123",
"messageId": "msg_790",
"userId": "user_456",
"message": "EUR/USD breaking resistance!",
"timestamp": "2025-10-21T12:00:00.000Z"
}
}User Online/Offline
{
"type": "user:online",
"data": {
"userId": "user_789",
"status": "online"
}
}Market Price Update
{
"type": "market:price",
"data": {
"symbol": "EUR/USD",
"price": 1.0875,
"change": 0.0025,
"changePercent": 0.23
}
}New Post
{
"type": "post:created",
"data": {
"postId": "post_123",
"userId": "user_456",
"communityId": "community_789",
"content": "New trade idea posted!"
}
}Trade Alert
{
"type": "trade:created",
"data": {
"tradeId": "trade_456",
"symbol": "EUR/USD",
"direction": "buy",
"entryPrice": 1.0850
}
}Complete WebSocket Example
class RealtimeClient {
constructor(apiKey, token) {
this.apiKey = apiKey;
this.token = token;
this.ws = null;
this.handlers = {};
}
connect() {
this.ws = new WebSocket('ws://api.yourdomain.com/v1/live');
this.ws.onopen = () => {
console.log('**Connected');
// Authenticate
this.ws.send(JSON.stringify({
type: 'auth',
token: this.token
}));
};
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
// Route to handler
const handler = this.handlers[message.type];
if (handler) {
handler(message.data);
}
};
this.ws.onclose = () => {
console.log('Connection closed, reconnecting...');
setTimeout(() => this.connect(), 5000);
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
on(eventType, handler) {
this.handlers[eventType] = handler;
}
subscribe(channel, options = {}) {
this.ws.send(JSON.stringify({
type: 'subscribe',
channel,
...options
}));
}
sendMessage(chatroomId, message) {
this.ws.send(JSON.stringify({
type: 'chat:send',
chatroomId,
message
}));
}
}
// Usage
const client = new RealtimeClient(apiKey, token);
client.connect();
// Handle chat messages
client.on('chat:message', (data) => {
console.log(`${data.userId}: ${data.message}`);
// Update UI
});
// Handle price updates
client.on('market:price', (data) => {
console.log(`${data.symbol}: ${data.price}`);
// Update price display
});
// Subscribe to chatroom
client.subscribe('chatroom', { chatroomId: 'room_123' });
// Subscribe to market data
client.subscribe('market', { symbols: ['EUR/USD', 'GBP/JPY'] });
// Send message
client.sendMessage('room_123', 'Hello everyone!');Real-time Notifications
WebSocket also delivers real-time notifications:
{
"type": "notification:new",
"data": {
"id": "notif_123",
"title": "New Comment on Your Post",
"message": "John Doe commented on your post",
"priority": "medium"
}
}Live Sessions
For live trading sessions, webinars, or events:
{
"type": "session:started",
"data": {
"sessionId": "session_789",
"title": "Live Market Analysis",
"speakerId": "user_123",
"startedAt": "2025-10-21T14:00:00.000Z"
}
}Connection Management
Heartbeat
Send ping every 30 seconds to keep connection alive:
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);Reconnection
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
ws.onclose = () => {
if (reconnectAttempts < maxReconnectAttempts) {
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
setTimeout(() => {
reconnectAttempts++;
connect();
}, delay);
}
};
ws.onopen = () => {
reconnectAttempts = 0; // Reset on successful connection
};Performance
| Metric | Value |
|---|---|
| Max Connections per Instance | 10,000 |
| Message Latency | < 100ms |
| Connection Timeout | 60 seconds |
| Max Message Size | 64KB |
| Heartbeat Interval | 30 seconds |
Security
- **JWT authentication required
- **Room-based message filtering
- **User presence tracking
- **Rate limiting (100 messages/minute)
- **Message validation
Related Documentation
- Community API - Post updates via WebSocket
- Trading API - Live trade alerts
- Notifications - Real-time notifications