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.

🚀 Key Features

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

✅ What You Get:
  • 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);
};
🔑 API Key Required

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 ws

Then 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.

🔑 API Key Requirements

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

⚠️ API Key Requirements:
  • 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_demo for 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);
};
🔒 Connection Security

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 disconnect
  • onclose - Fired when connection is closed (manual or automatic)
  • onerror - Fired when WebSocket error occurs
  • onmessage - Fired when any message is received from server
⚠️ Important Notes:
  • 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 candles

Leave Symbol (Unsubscribe)

client.leave(symbol, timeframe);

// Example:
client.leave("BINANCE:BTCUSDT", "60");

Remove All Subscriptions

client.removeAll(); // Unsubscribe from all symbols

Symbol 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 ❌
⏱️ Supported Timeframes

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

Single Symbol
https://api-v4.fcsapi.com/
client.onconnected = () => {
    client.join("BINANCE:BTCUSDT", "60");
};
Multiple Symbols
https://api-v4.fcsapi.com/
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));
};
💡 Best Practices:
  • 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
📨 Message Processing

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 info
  • price (candle mode) - Full OHLCV data for the current candle period
  • price (askbid mode) - Real-time ask/bid prices with millisecond updates
  • message - Server notifications including room join confirmations
  • error - Error messages for failed operations
  • ping/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
    }
}
Price Data Fields:
  • 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-reconnect

Connection Status

if (client.isConnected) {
    console.log("WebSocket is connected");
}

console.log("Reconnect count:", client.countreconnects);
🧠 Smart Reconnection

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.js
  • reconnectDelay - Milliseconds to wait before reconnecting
  • reconnectlimit - Maximum reconnection attempts
  • isConnected - Boolean indicating current connection status
  • countreconnects - Number of reconnection attempts made
🎯 Environment Differences:
  • 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.

📄 Live Examples

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

💡 Best Practices:
  • 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 ws

Node.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);
}
🖥️ Server-Side Benefits

Run 24/7 without browser limitations. Perfect for trading bots, data collection, price monitoring, and backend services.

Use Cases:
  • 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

PlanPrice/MonthYearly PriceReal-time UpdatesConcurrent Connections
WebSocket Basic$99$82/month5 sec15 connections
WebSocket Pro$189$157/month2 sec40 connections
WebSocket Business$329$275/monthReal-time250 connections
WebSocket Enterprise$749$624/monthReal-time2000 connections

View complete pricing details at fcsapi.com/websocket-pricing

📊 Understanding Concurrent Connections

Concurrent connections means the number of simultaneous WebSocket connections you can maintain from any device (browser, server, mobile app, etc.).

⚠️ Important Notes:
  • 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
For enterprise or custom requirements, contact sales for tailored solutions.

Common Issues & Solutions

Quick solutions to common WebSocket connection and usage issues.

Connection Issues

IssueCauseSolution
Connection refusedInvalid API key or no socket accessCheck your API key and verify socket access is enabled
No price updatesSymbols not joined or wrong formatEnsure symbols include exchange prefix: "BINANCE:BTCUSDT"
Frequent disconnectsNetwork issues or heartbeat timeoutCheck network stability, heartbeat runs automatically
onconnected not firingCallback defined after connect()Define callbacks BEFORE calling connect()
❓ Need Help?

Contact support at support@fcsapi.com with your API key, error messages, and code samples for faster resolution.

🔍 Debugging Tips:
  • 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.

⚠️ Important Notice

Always consult licensed financial advisors before making investment decisions. This service is not a substitute for professional financial advice.

📋 Key Points:
  • 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
By using the FCS WebSocket API, you agree to our Terms of Service and Privacy Policy.