WebSocket API/Getting Started

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 forex, crypto and stock symbols with minimal overhead; the markets you can stream depend on your plan. Plans start at $99/month (see WebSocket pricing), and the free demo key fcs_socket_demo is available for testing.

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 streamingPrice updates as they happen
Low latencySub-second data delivery
Persistent connectionNo repeated authentication
Multiple symbolsSubscribe to unlimited symbols
Auto-reconnectionBuilt-in connection recovery
Tab optimizationSmart disconnect when tab inactive

What You Get:

  • OHLCV (Open, High, Low, Close, Volume) data
  • Price updates from 5-second to real-time, depending on your plan
  • Multiple timeframes: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 1D, 1W
  • Support for 100,000+ symbols across forex, crypto, stocks, indices and commodities
  • Automatic reconnection on network failures
  • Browser and Node.js compatible
Getting Started/Quick Start

Get Started in 3 Steps

Start receiving real-time market data in minutes. No complex setup required - just include our JavaScript library and connect.

  1. Step 1: Include the Library

    Download and include fcs-client-lib.js in your HTML file.

    <script src="fcs-client-lib.js"></script>
  2. 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();
  3. 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 with your own key requires a paid WebSocket plan (from $99/month); for testing use the free demo key fcs_socket_demo.

Core Concepts/Installation

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 SubscriptionRequired for production use with your own API key
REST API KeysWill NOT work - socket access is a separate subscription
Demo KeyUse fcs_socket_demo for testing and development
BrowserModern browsers with WebSocket support (Chrome, Firefox, Safari, Edge)
Node.jsVersion 12+ with ws package installed
NetworkStable internet connection for persistent WebSocket connection
Core Concepts/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

onconnectedFired when server is ready to receive commands (after authentication)
onreconnectFired when connection is automatically restored after disconnect
oncloseFired when connection is closed (manual or automatic)
onerrorFired when WebSocket error occurs
onmessageFired 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
Core Concepts/Subscribe/Unsub

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
Core Concepts/Message Types

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

welcomeInitial 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
messageServer notifications including room join confirmations
errorError messages for failed operations
ping/pongHeartbeat 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
Core Concepts/Advanced Features

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

focusTimeoutMinutes before disconnect when tab inactive (0 = never). Auto-set to 0 in Node.js
reconnectDelayMilliseconds to wait before reconnecting
reconnectlimitMaximum reconnection attempts
isConnectedBoolean indicating current connection status
countreconnectsNumber of reconnection attempts made

Environment Differences

BrowserfocusTimeout default is 3 minutes (configurable)
Node.jsfocusTimeout automatically set to 0 (never disconnect)
Auto-reconnectionWorks in both browser and Node.js environments
Subscription persistenceAll subscriptions are automatically restored after reconnection
Trading botsNode.js maintains persistent connection 24/7
Manual disconnectUse disconnect() to prevent auto-reconnection
Examples/Complete Example

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 SecurityNever expose your API key in client-side code for production
Error HandlingAlways implement error handlers for robust operation
ReconnectionMonitor reconnection events and notify users
Resource ManagementUnsubscribe from unused symbols to save bandwidth
UI FeedbackShow connection status to improve user experience
Data ValidationValidate price data before using in calculations
Examples/Node.js Example

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 BotsExecute trades based on real-time price movements
Price AlertsSend notifications when price conditions are met
Data LoggingStore historical price data for analysis
ArbitrageMonitor price differences across exchanges
Market AnalysisReal-time technical indicator calculations
Plans & Support/Pricing

WebSocket Pricing Plans

Production use of the FCS WebSocket API requires a paid subscription from $99/month, and the free demo key fcs_socket_demo is for testing only. Choose the plan based on your update frequency needs, concurrent connection requirements and the markets you need.

Available Plans

PlanPrice/MonthYearly PriceReal-time UpdatesConcurrent ConnectionsMarkets
WebSocket Basic$99$82/month5 sec15 connectionsForex
WebSocket Pro$189$157/month2 sec40 connectionsForex, Crypto
WebSocket Business$329$275/monthreal-time250 connectionsForex, Crypto, Stocks, Commodities
WebSocket Enterprise$749$624/monthreal-time2000 connectionsAll markets

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

ExampleIf you buy the WebSocket Basic plan ($99/month, 15 connections) and have 1,000 clients, you need your own server infrastructure.
ArchitectureYour server connects to FCS WebSocket (uses 1 connection), then distributes data to your 1,000 clients via your own WebSocket/API.
Direct ConnectionEach browser or app connecting directly to FCS counts as 1 concurrent connection.
Update SpeedFaster updates (WebSocket Business plan from $329/month) provide real-time data with sub-second latency, ideal for trading platforms.
All Plans IncludeAll timeframes, Auto-reconnection, Technical support. The markets each plan streams are listed in the Markets column above.

For enterprise or custom requirements, contact sales for tailored solutions.

Plans & Support/Troubleshooting

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 [email protected] 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
Plans & Support/Disclaimer

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

Plans & Support/FAQ

WebSocket API FAQ

What is FCS API WebSocket?

FCS API WebSocket provides real-time streaming of market data with 5-second to real-time updates, depending on the plan. Unlike REST API that requires polling, WebSocket pushes live price updates directly to your application - ideal for trading bots, live dashboards, and financial apps.

How do I connect to the WebSocket API?

Connect to wss://ws-v4.fcsapi.com/ws?access_key=YOUR_KEY with your WebSocket API key. Send a JSON join message: {"type":"join_symbol","symbol":"BINANCE:BTCUSDT","timeframe":"60"}. You will receive real-time price updates for subscribed symbols.

What data is streamed via WebSocket?

Each price message includes the symbol, timeframe and a prices object. In candle mode it holds the candle open time (t), open (o), high (h), low (l), close or current price (c) and volume (v); in askbid mode it holds the update time (update), current price (c), ask price (a), bid price (b) and candle period time (t). Data format is optimized for low bandwidth.

What markets are available via WebSocket?

WebSocket streams data for: Forex (4,500+ forex symbols), Cryptocurrency (15,000+ crypto symbols), Stocks (100,000+ stocks), Indices (S&P 500, NASDAQ, Dow Jones), Commodities (Gold, Silver, Oil), and Funds. Market access depends on your plan level.

Is WebSocket API suitable for trading bots?

Yes, FCS API WebSocket is designed for algorithmic trading with low-latency data delivery. The WebSocket Enterprise plan provides real-time updates with 2,000 concurrent connections - perfect for high-frequency trading applications.

How many symbols can I subscribe to?

One connection can join several symbols, each with its own timeframe. The number of concurrent connections depends on the plan: WebSocket Free (1), WebSocket Basic (15), WebSocket Pro (40), WebSocket Business (250), WebSocket Enterprise (2,000).

What programming languages are supported?

WebSocket is protocol-based and works with any language: JavaScript (browser/Node.js), Python (websocket-client), PHP, Java, C#, Go, Ruby. We provide code examples for all major languages in our documentation.

Is there a free WebSocket plan?

Yes, the WebSocket Free plan uses the demo key fcs_socket_demo for testing, with 1 connection. Paid plans start at $99/month for more connections.

Esc
↑↓ Navigate↵ OpenEsc Close