FCS WebSocket API
FCS WebSocket API v4 provides real-time streaming data for forex, crypto, and stock markets. Unlike REST API that requires polling, WebSocket maintains a persistent connection delivering live price updates instantly as they occur. Get millisecond-level latency updates for 4,000+ currency pairs, cryptocurrencies, and stocks with minimal overhead.
Why Use WebSocket?WebSocket connections reduce latency from 5 seconds (REST polling) to under 1 second for real-time data. Perfect for live charts, trading platforms, price tickers, and real-time dashboards.
• Real-time streaming - Price updates as they happen
• Low latency - Sub-second data delivery
• Persistent connection - No repeated authentication
• Multiple symbols - Subscribe to unlimited symbols
• Auto-reconnection - Built-in connection recovery
• Tab optimization - Smart disconnect when tab inactive
- OHLCV (Open, High, Low, Close, Volume) data
- Real-time price updates every second
- Multiple timeframes: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 1D, 1W
- Support for 4,000+ symbols across forex, crypto, stocks
- Automatic reconnection on network failures
- Browser and Node.js compatible
Get Started in 3 Steps
Start receiving real-time market data in minutes. No complex setup required - just include our JavaScript library and connect.
Step 1: Include the Library
Download and include fcs-client-lib.js in your HTML file.
<script src="fcs-client-lib.js"></script>Step 2: Connect to WebSocket
Create a client instance with your API key and connect.
const client = new FCSClient("YOUR_API_KEY", "wss://ws-v4.fcsapi.com/ws");
client.connect();Step 3: Subscribe to Symbols
Join symbols to start receiving real-time updates.
client.onconnected = () => {
client.join("BINANCE:BTCUSDT", "60"); // Bitcoin 1-hour candles
};
client.onmessage = (data) => {
console.log("Price update:", data);
};You need a valid API key to connect. Get your API key from your dashboard after registration. Socket access requires a paid plan.
Library Installation
The FCS WebSocket client library works in both browser and Node.js environments. Choose your preferred installation method.
Browser Installation
Download fcs-client-lib.js and include it in your HTML:
<script src="path/to/fcs-client-lib.js"></script>Node.js Installation
For Node.js, install the ws package first:
npm install wsThen require the library:
const FCSClient = require("./fcs-client-lib.js");API Key Configuration
To use the WebSocket API, you need a valid API key:
- With Active Socket Subscription: Use your own API key from the dashboard
- For Testing/Demo: Use the demo key:
fcs_socket_demo
// Using your API key (requires active socket subscription)
const client = new FCSClient("YOUR_API_KEY");
// Using demo key for testing
const client = new FCSClient("fcs_socket_demo");Important: Standard REST API keys will NOT work with WebSocket. You must have an active socket subscription or use the demo key.
Socket Subscription Required: Your API key must have an active WebSocket subscription to connect. Regular REST API keys will be rejected.
Demo Key: Use fcs_socket_demo for testing without a subscription. Limited to demo symbols and data.
Download: fcs-client-lib.js
- Socket Subscription: Required for production use with your own API key
- REST API Keys: Will NOT work - socket access is a separate subscription
- Demo Key: Use
fcs_socket_demofor testing and development - Browser: Modern browsers with WebSocket support (Chrome, Firefox, Safari, Edge)
- Node.js: Version 12+ with ws package installed
- Network: Stable internet connection for persistent WebSocket connection
Connecting to WebSocket
Establish a WebSocket connection to start receiving real-time data. The client handles authentication, heartbeat, and reconnection automatically.
Creating Client Instance
const client = new FCSClient(apiKey, wsUrl);
// Parameters:
// apiKey (required): Your FCS API key
// wsUrl (optional): WebSocket server URL, defaults to "wss://ws-v4.fcsapi.com/ws/"Connect Method
client.connect()
.then((client) => {
console.log("Connection established");
})
.catch((err) => {
console.error("Connection failed:", err);
});Event Callbacks
// Server ready to receive commands
client.onconnected = () => {
console.log("Connected and authenticated");
// Join symbols here
};
// Automatic reconnection event
client.onreconnect = () => {
console.log("Reconnected successfully");
};
// Connection closed
client.onclose = (event) => {
console.log("Disconnected:", event.reason);
};
// WebSocket errors
client.onerror = (err) => {
console.error("WebSocket error:", err);
};All WebSocket connections use secure WSS protocol. API key is validated on connection. Invalid keys will be rejected immediately.
Response Format
Response Fields
onconnected- Fired when server is ready to receive commands (after authentication)onreconnect- Fired when connection is automatically restored after disconnectonclose- Fired when connection is closed (manual or automatic)onerror- Fired when WebSocket error occursonmessage- Fired when any message is received from server
- onconnected fires AFTER authentication, not on raw connection
- Always subscribe to symbols in onconnected callback
- Automatic reconnection preserves subscriptions
- Manual disconnect prevents auto-reconnection
- Maximum 5 reconnection attempts before giving up
Symbol Subscription
Subscribe to symbols to receive real-time price updates. You can join multiple symbols with different timeframes simultaneously.
Join Symbol (Subscribe)
client.join(symbol, timeframe);
// Examples:
client.join("BINANCE:BTCUSDT", "60"); // Bitcoin 1-hour candles
client.join("FX:EURUSD", "5"); // EUR/USD 5-minute candles
client.join("NASDAQ:AAPL", "1D"); // Apple daily candlesLeave Symbol (Unsubscribe)
client.leave(symbol, timeframe);
// Example:
client.leave("BINANCE:BTCUSDT", "60");Remove All Subscriptions
client.removeAll(); // Unsubscribe from all symbolsSymbol Format
Symbols must include exchange prefix:
// Correct formats:
"BINANCE:BTCUSDT" // Crypto
"FX:EURUSD" // Forex
"NASDAQ:AAPL" // Stock
"OKX:ETHUSDT" // Crypto from OKX
// Wrong format:
"BTCUSDT" // Missing exchange prefix ❌Minutes: 1, 5, 15, 30, 60, 120, 240
Text format: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 1D, 1W
Common: Use "60" or "1h" for 1-hour candles, "1D" for daily
Subscription Examples
client.onconnected = () => {
client.join("BINANCE:BTCUSDT", "60");
};client.onconnected = () => {
const symbols = [
{ symbol: "BINANCE:BTCUSDT", timeframe: "60" },
{ symbol: "BINANCE:ETHUSDT", timeframe: "60" },
{ symbol: "FX:EURUSD", timeframe: "15" },
{ symbol: "NASDAQ:AAPL", timeframe: "1D" }
];
symbols.forEach(s => client.join(s.symbol, s.timeframe));
};- Always join symbols AFTER onconnected fires
- Use meaningful timeframes for your use case
- Unsubscribe from unused symbols to save resources
- Subscriptions persist across reconnections automatically
- No limit on number of concurrent subscriptions
WebSocket Message Types
The WebSocket server sends different message types. Handle them in your onmessage callback to process real-time updates.
Message Handler
client.onmessage = (data) => {
switch(data.type) {
case "welcome":
console.log("Welcome:", data.message);
console.log("Client ID:", data.clientId);
console.log("Debug Info:", data.debug);
break;
case "price":
if (data.prices.mode === "candle") {
console.log("Candle Update:", data.symbol, data.prices);
} else if (data.prices.mode === "askbid") {
console.log("Ask/Bid Update:", data.prices.a, data.prices.b);
}
break;
case "message":
console.log("Server message:", data.message);
if (data.short === "joined_room") {
console.log("Joined room:", data.room);
}
break;
case "error":
console.error("Error:", data.message);
break;
}
};Price Update Modes
Price messages include two modes:
- candle: Full OHLCV data for the current candle period
- askbid: Real-time ask/bid prices between candle periods
All messages are JSON formatted. The type field indicates the message category. Price updates include two modes: candle (OHLCV data) and askbid (real-time quotes).
Response Format
Response Fields
welcome- Initial message after successful authentication with connection details and debug infoprice (candle mode)- Full OHLCV data for the current candle periodprice (askbid mode)- Real-time ask/bid prices with millisecond updatesmessage- Server notifications including room join confirmationserror- Error messages for failed operationsping/pong- Heartbeat messages (handled automatically by library)
Mini Sample Response
{
"type": "price",
"symbol": "BINANCE:BTCUSDT",
"timeframe": "15",
"prices": {
"mode": "candle",
"t": 1766076300,
"o": 88284.57,
"h": 88305.49,
"l": 88022.62,
"c": 88165.3,
"v": 83.39898
}
}- mode: "candle" (OHLCV data) or "askbid" (real-time quotes)
- Candle mode:
- • t: Unix timestamp (candle open time)
- • o: Open price
- • h: High price
- • l: Low price
- • c: Close/Current price
- • v: Volume
- Ask/Bid mode:
- • update: Unix timestamp of update
- • c: Current price
- • a: Ask price
- • b: Bid price
- • t: Current candle period timestamp
Advanced Configuration
The FCS WebSocket client includes intelligent features like automatic reconnection, tab visibility handling, and connection optimization.
Tab Visibility Management (Browser Only)
In browser environments, automatically disconnect when tab is inactive to save resources:
// Browser environment
client.focusTimeout = 3; // Disconnect after 3 minutes of inactivity
client.focusTimeout = 0; // Never disconnect (always connected)Note: In Node.js environment, focusTimeout is automatically set to 0 (never disconnect) since there is no tab visibility concept.
Automatic Reconnection
If the WebSocket connection closes unexpectedly, the library will automatically attempt to reconnect:
client.reconnectDelay = 3000; // Wait 3 seconds before reconnect
client.reconnectlimit = 5; // Max 5 reconnection attempts
// Reconnection event
client.onreconnect = () => {
console.log("Successfully reconnected!");
// All subscriptions are automatically restored
};Manual Disconnect
client.disconnect(); // Closes connection and stops auto-reconnectConnection Status
if (client.isConnected) {
console.log("WebSocket is connected");
}
console.log("Reconnect count:", client.countreconnects);The library automatically reconnects on connection failures and preserves all subscriptions. When reconnected, all previously subscribed symbols are automatically rejoined. Manual disconnects prevent auto-reconnection.
Response Format
Response Fields
focusTimeout- Minutes before disconnect when tab inactive (0 = never). Auto-set to 0 in Node.jsreconnectDelay- Milliseconds to wait before reconnectingreconnectlimit- Maximum reconnection attemptsisConnected- Boolean indicating current connection statuscountreconnects- Number of reconnection attempts made
- Browser: focusTimeout default is 3 minutes (configurable)
- Node.js: focusTimeout automatically set to 0 (never disconnect)
- Auto-reconnection: Works in both browser and Node.js environments
- Subscription persistence: All subscriptions are automatically restored after reconnection
- Trading bots: Node.js maintains persistent connection 24/7
- Manual disconnect: Use disconnect() to prevent auto-reconnection
Full Working Example
A complete, production-ready example showing all features: connection, subscription, message handling, error recovery, and real-time price display.
Try Live Demos:
• Full Featured Example - Complete implementation with UI
• Simple Example - Minimal code example
Download Source:
• Download Full Example
• Download Simple Example
• Download All (JS, NodeJS, HTML) files
- API Key Security: Never expose your API key in client-side code for production
- Error Handling: Always implement error handlers for robust operation
- Reconnection: Monitor reconnection events and notify users
- Resource Management: Unsubscribe from unused symbols to save bandwidth
- UI Feedback: Show connection status to improve user experience
- Data Validation: Validate price data before using in calculations
Server-Side WebSocket (Node.js)
Use the FCS WebSocket client in Node.js for server-side applications, trading bots, data logging, and backend integrations.
Installation
npm install wsNode.js Implementation
const FCSClient = require("./fcs-client-lib.js");
const client = new FCSClient("YOUR_API_KEY");
client.connect()
.then(() => console.log("Connected to FCS WebSocket"))
.catch(err => console.error("Connection failed:", err));
client.onconnected = () => {
console.log("Authenticated and ready");
// Subscribe to multiple symbols
client.join("BINANCE:BTCUSDT", "60");
client.join("BINANCE:ETHUSDT", "60");
client.join("FX:EURUSD", "60");
};
client.onmessage = (data) => {
if (data.type === "price") {
console.log(`${data.symbol}: $${data.prices.c}`);
// Save to database, trigger alerts, etc.
saveToDatabase(data);
}
};
function saveToDatabase(priceData) {
// Your database logic here
console.log("Saving to DB:", priceData);
}Run 24/7 without browser limitations. Perfect for trading bots, data collection, price monitoring, and backend services.
- Trading Bots: Execute trades based on real-time price movements
- Price Alerts: Send notifications when price conditions are met
- Data Logging: Store historical price data for analysis
- Arbitrage: Monitor price differences across exchanges
- Market Analysis: Real-time technical indicator calculations
WebSocket Pricing Plans
FCS WebSocket API requires a paid subscription. Choose the plan based on your update frequency needs and concurrent connection requirements.
Available Plans
| Plan | Price/Month | Yearly Price | Real-time Updates | Concurrent Connections |
|---|---|---|---|---|
| WebSocket Basic | $99 | $82/month | 5 sec | 15 connections |
| WebSocket Pro | $189 | $157/month | 2 sec | 40 connections |
| WebSocket Business | $329 | $275/month | Real-time | 250 connections |
| WebSocket Enterprise | $749 | $624/month | Real-time | 2000 connections |
View complete pricing details at fcsapi.com/websocket-pricing
Concurrent connections means the number of simultaneous WebSocket connections you can maintain from any device (browser, server, mobile app, etc.).
- Example: If you buy the $119 plan (3 connections) and have 1,000 clients, you need your own server infrastructure.
- Architecture: Your server connects to FCS WebSocket (uses 1 connection), then distributes data to your 1,000 clients via your own WebSocket/API.
- Direct Connection: Each browser or app connecting directly to FCS counts as 1 concurrent connection.
- Update Speed: Faster updates ($999 plan) provide real-time data with sub-second latency, ideal for trading platforms.
- All Plans Include: All symbols (4000+), All timeframes, Auto-reconnection, Technical support
Common Issues & Solutions
Quick solutions to common WebSocket connection and usage issues.
Connection Issues
| Issue | Cause | Solution |
|---|---|---|
| Connection refused | Invalid API key or no socket access | Check your API key and verify socket access is enabled |
| No price updates | Symbols not joined or wrong format | Ensure symbols include exchange prefix: "BINANCE:BTCUSDT" |
| Frequent disconnects | Network issues or heartbeat timeout | Check network stability, heartbeat runs automatically |
| onconnected not firing | Callback defined after connect() | Define callbacks BEFORE calling connect() |
Contact support at support@fcsapi.com with your API key, error messages, and code samples for faster resolution.
- Check browser console for error messages
- Verify API key in dashboard is active
- Ensure WebSocket access is enabled for your account
- Test connection with example HTML file first
- Check symbol format includes exchange prefix
- Monitor client.isConnected status
- Use try-catch blocks around client operations
Terms & Disclaimer
Important legal information about data usage, accuracy, and limitations of the FCS WebSocket service.
Data Accuracy
Real-time prices are indicative and sourced from multiple exchanges and liquidity providers. While we strive for accuracy, data may not be 100% accurate or suitable for high-frequency trading.
Trading Disclaimer
Prices, market data, and signals provided via WebSocket are for informational and educational purposes only. They are NOT intended for trading purposes. We bear NO responsibility for any trading losses incurred from using this data.
Service Availability
We maintain 99.9% uptime but cannot guarantee uninterrupted service. Network issues, server maintenance, or technical problems may cause temporary disconnections.
Always consult licensed financial advisors before making investment decisions. This service is not a substitute for professional financial advice.
- Data is for informational purposes only
- Not suitable as sole basis for trading decisions
- Prices may differ from actual market prices
- No liability for trading losses or missed opportunities
- Service subject to terms and conditions
- API key usage monitored for abuse prevention
