DEV Community

StockFX
StockFX

Posted on

Step-by-Step Guide to Integrating iTick WebSocket API in Your App

This technical guide details the workflow for integrating iTick’s WebSocket API to deliver real-time, low-latency financial market data within institutional, fintech, and quantitative trading applications. iTick supports multi-protocol access and comprehensive coverage of global markets, including stocks, forex, cryptocurrencies, indices, futures, and funds. The infrastructure sustains over 70 million messages per second, delivers 99.99% uptime, and manages more than 1 trillion rows of tick data. These features empower high-frequency data streaming, market surveillance, and quantitative strategy development for both established financial firms and advanced developers.

This article provides technical information solely for integration purposes. All data and API instructions described here are strictly informational and do not constitute financial, investment, or trading advice. Before production deployment, test your solution thoroughly in a sandbox environment, and confirm regulatory compliance for all integrations. Data provided by iTick cannot be redistributed.

Key reasons to use iTick WebSocket API:

Ultra-low latency streaming for immediate access to global multi-asset tick data
Comprehensive market coverage - US, Hong Kong, A-shares, forex, major crypto, global indices, futures, and funds
Cloud-native endpoints for both free and commercial use, scalable to institutional loads
Access to tick, quote, order book depth, and kline (candlestick) data for diverse trading and risk management systems
A successful integration requires a verified iTick account, an active API Key, and a development environment supporting WebSocket protocols (Node.js/JavaScript, Python, Java, Go, or similar).

Fast Start: iTick API Access, Endpoint Choices, and Key Requirements
Before starting your project, ensure the following:

iTick account registration with API Key creation
Supported programming language (JavaScript, Python, Java, Go, etc.)
Reference to official documentation and examples via the iTick API Quick Start Guide
Outbound network access to secure WebSocket endpoints (wss://)
WebSocket Endpoints by Product and Plan
iTick provides separate WebSocket endpoints for each market product and service tier. Select the correct endpoint for your use case, as performance and data depth vary between free and paid plans.

Product Free WebSocket Endpoint Paid WebSocket Endpoint
Crypto wss://api-free.itick.org/crypto wss://api.itick.org/crypto
Forex wss://api-free.itick.org/forex wss://api.itick.org/forex
Indices wss://api-free.itick.org/indices wss://api.itick.org/indices
Stocks wss://api-free.itick.org/stock wss://api.itick.org/stock
Futures wss://api-free.itick.org/future (Check documentation for endpoint)
Funds wss://api-free.itick.org/fund (Check documentation for endpoint)
Core differences:

Reliability: Paid endpoints guarantee 99.99% uptime, higher throughput, and advanced failover. Free endpoints offer limited redundancy.
Market Data Depth: Premium plans allow more data types, higher subscription volume, and advanced order book access.
Rate Limits: Maximum 500 concurrent symbol subscriptions per connection. Paid subscriptions may permit higher overall usage across multiple sockets.
Refer to the iTick pricing plans and endpoint options for up-to-date information on service tiers and features.

Checklist for getting started:

Register an iTick account
Generate and securely store your API Key
Choose appropriate endpoint URLs per asset class and plan
Confirm that your environment can access target URLs and necessary ports
Establishing and Managing WebSocket Connections
WebSocket URL Structure and Product Mapping
Use the appropriate endpoint URL for your product class:

Stocks: wss://api.itick.org/stock (paid) or wss://api-free.itick.org/stock (free)
Forex: wss://api.itick.org/forex (paid) or wss://api-free.itick.org/forex (free)
Crypto, Indices, Futures, and Funds: replace “stock” or “forex” accordingly
Connection Lifecycle: States and Event Handlers
WebSocket connection states:

State Name Code Description
CONNECTING 0 Handshake initiation, not ready for data
OPEN 1 Ready for message exchange
CLOSING 2 Closure handshake underway
CLOSED 3 Fully closed, reconnect required for activity
Recommended event handlers:

onopen: Initiate authentication
onmessage: Parse all incoming server messages (market data, pings, responses)
onerror: Detect connection issues; log and trigger reconnection if required
onclose: Handle planned/unplanned disconnects and launch reconnect strategy
Quick Best Practice: Always begin integration in a sandbox or development environment and consult compliance teams where applicable.

Example: JavaScript Event Handlers
var ws = new WebSocket('wss://api.itick.org/stock');

ws.onopen = function() { // Authenticate here };

ws.onmessage = function(event) { // Parse and route messages };

ws.onerror = function(error) { // Error logging and reconnection logic };

ws.onclose = function(event) { // Reconnect as needed };

Authentication Process
After connection establishment, send an authentication request containing your API Key.

Authentication steps:

Wait for the onopen event.
Send a JSON message: { "ac":"auth", "params":"YOUR_API_KEY" }
Upon success, expect: { "code":1, "resAc":"auth", "msg":"authenticated" }
If authentication fails (e.g., code: -1), the server will typically close the connection.
Checklist:

Send authentication immediately after connection is open
Parse the response and confirm success before any subscription
On failure, validate the API Key and do not attempt frequent retries without correcting the issue
Example:

ws.send(JSON.stringify({ac:"auth", params:"YOUR_API_KEY"}));

On successful authentication:
Proceed to subscription. Authentication must succeed for each new connection.

Subscribing to Market Data Streams
After authenticating, subscribe to desired symbols and data types.

Symbol format: symbol$region (e.g., AAPL$US for Apple in the US market)
Multiple symbols: Comma-separated list (e.g., AAPL$US,GOOG$US)
Subscription types:
tick: Trade-by-trade (tick-by-tick) data
quote: Level 1 snapshot (OHLCV)
depth: Order book, price/volume depth
kline: Candlestick bars, typically 1-min
Subscription message example:

ws.send(JSON.stringify({ac:"subscribe", params:"AAPL$US,tick,quote"}));

For several symbols and types:

ws.send(JSON.stringify({ac:"subscribe", params:"AAPL$US,GOOG$US,tick,quote,depth"}));

Limit: Up to 500 unique symbols per connection. Use separate sockets for larger symbol sets.
To explore regions, symbol conventions, and multi-market coverage, consult Global Market Stock API details.

Always resubscribe after reconnects
Invalid or oversized requests result in errors or refused connections
Key reminders:

Do not exceed subscription cap per connection
Batch your symbol requests efficiently
Ensure downstream systems can process real-time traffic volumes
Handling Incoming Messages and Keep-Alive Mechanism
Message Types and Core Fields
Field Description Example (Tick) Example (Quote)
s Symbol AAPL AAPL
r Region US US
ld Last price 225.215 225.215
v Volume 16742235 16742235
t Timestamp (ms since epoch) 1731689407000 1731689407000
chp Change percent (quote) – -1.17
type Message type (tick, quote, depth) tick quote
d Trade direction 2 –
ts Trading status (SUSP, etc.) – SUSP
tick: Trade-by-trade data, possible trade direction (d: 0 - default, 1 - sell, 2 - buy; supported for major US, HK, and A-share equities).
quote: OHLCV and trade status (ts field indicates suspensions or halts).
depth: Includes order book ladders.
Server Ping/Pong Protocol for Keep-Alive
iTick maintains WebSocket health using regular pings.

Server sends: { "ac":"ping", "params":timestamp }
Client replies: { "ac":"pong", "params":timestamp }
Always match the timestamp exactly
Example:

if (message.ac === "ping") { ws.send(JSON.stringify({ac:"pong", params:message.params})); }

Handle pong responses consistently - missed or delayed replies will cause disconnection.

Preventing Buffer Overflows
Ensure your application processes incoming messages as quickly as they are received
Subscribing to too many symbols or slow downstream processing increases buffer risk
Connections facing backlogs may be closed by the server to protect overall system integrity
Monitor application throughput against your plan’s allocation and system performance goals.

Code Examples: Popular Language Implementations
Always validate in test mode before introducing code into production. Review all error handlers, event lifecycle logic, and ensure compliance with local technical standards.

JavaScript (Browser/Node.js Sample)
var ws = new WebSocket('wss://api.itick.org/stock');

ws.onopen = function() { ws.send(JSON.stringify({ac:"auth", params:"YOUR_API_KEY"})); };

ws.onmessage = function(event) { var msg = JSON.parse(event.data); if (msg.ac === "ping") { ws.send(JSON.stringify({ac:"pong", params:msg.params})); return; } if (msg.resAc === "auth" && msg.code === 1) { ws.send(JSON.stringify({ac:"subscribe", params:"AAPL$US,tick,quote"})); return; } // Handle data messages here };

ws.onerror = function(error) { // Log or handle the error };

ws.onclose = function(event) { setTimeout(function() { // Simple reconnect; use exponential backoff for resilience }, 1000); };

Python (asyncio + websockets)
import asyncio import websockets import json

async def run(): uri = "wss://api.itick.org/stock" async with websockets.connect(uri) as ws: await ws.send(json.dumps({"ac":"auth","params":"YOUR_API_KEY"})) while True: msg = await ws.recv() msg = json.loads(msg) if msg.get("ac") == "ping": await ws.send(json.dumps({"ac":"pong","params":msg["params"]})) elif msg.get("resAc") == "auth" and msg.get("code") == 1: await ws.send(json.dumps({"ac":"subscribe","params":"AAPL$US,tick,quote"})) else:

Process live data here
pass
asyncio.run(run())

Java (org.java_websocket client)
import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI;

WebSocketClient client = new WebSocketClient(new URI("wss://api.itick.org/stock")) { @override public void onOpen(ServerHandshake handshakedata) { send("{\"ac\":\"auth\",\"params\":\"YOUR_API_KEY\"}"); }

@override
public void onMessage(String message) {
JSONObject msg = new JSONObject(message);
if (msg.optString("ac", "").equals("ping")) {
send("{\"ac\":\"pong\",\"params\":" + msg.get("params") + "}");
} else if (msg.optString("resAc", "").equals("auth") && msg.optInt("code", -1) == 1) {
send("{\"ac\":\"subscribe\",\"params\":\"AAPL$US,tick,quote\"}");
} else {
// Process live messages
}
}

@override
public void onClose(int code, String reason, boolean remote) {
// Reconnection logic
}

@override
public void onError(Exception ex) {
// Error handling logic
}
}; client.connect();

Go (gorilla/websocket)
package main

import ( "github.com/gorilla/websocket" "encoding/json" "log" )

func main() { c, _, err := websocket.DefaultDialer.Dial("wss://api.itick.org/stock", nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() authMsg := map[string]interface{}{"ac": "auth", "params": "YOUR_APIKEY"} c.WriteJSON(authMsg) for { , message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } var msg map[string]interface{} json.Unmarshal(message, &msg) if msg["ac"] == "ping" { pong := map[string]interface{}{"ac": "pong", "params": msg["params"]} c.WriteJSON(pong) } else if msg["resAc"] == "auth" && int(msg["code"].(float64)) == 1 { subscribe := map[string]interface{}{"ac": "subscribe", "params": "AAPL$US,tick,quote"} c.WriteJSON(subscribe) } else { // Process data } } }

Best Practices and Troubleshooting
Implementation Tips
Use exponential backoff for connection retries to avoid rate limiting and unnecessary server load
Keep subscription lists lean; subscribe only to assets and data types needed for your workflow
Each connection: maximum 500 symbols; partition across sockets as needed for coverage
Monitor latency and inbound message processing speeds against your operational requirements
Handle authentication, connection, and parsing errors cleanly; trigger support only after verifying your own environment
Troubleshooting Checklist
Verify API Key authentication status and endpoint accuracy
On connection loss, check for causes: expired keys, exceeded quotas, missed pings, or performance bottlenecks
Respond to server pings immediately to maintain connection continuity
Analyze disconnection codes and logs for patterns
Monitor for buffer overflows; optimize code if lag is detected
For ongoing strategies and adaptive integration advice, the iTick Technical Blog for API integration tips provides up-to-date tutorials and use cases.

Optional Advanced Topics
Multi-asset subscriptions: Merge symbols from different regions and asset classes (e.g., AAPL$US and 00700$HK) within a single connection, as long as you do not exceed the 500-symbol cap.
Custom filters: Reduce stream volume by specifying just the types of data (tick, quote, depth, kline) and symbols you need.
Trading status monitoring: The "ts" field in quote messages flags trading suspensions or delistings; automated systems can use this to manage real-time risk.
Tick direction usage: The "d" field (0, 1, 2) in tick messages provides order flow analytics for supported markets.
Subscription Example:
ws.send(JSON.stringify({ ac:"subscribe", params:"AAPL$US,tick,quote,00700$HK,quote,depth" }));

Systematic platforms should build logic accounting for real-time changes in trading status or instrument availability based on inbound metadata fields.

Frequently Asked Questions
What WebSocket endpoints are available for stocks and other products?
Stocks: wss://api.itick.org/stock (paid), wss://api-free.itick.org/stock (free). For Crypto, Forex, Indices, Futures, and Funds, replace "stock" accordingly in the endpoint URL.

How do I authenticate?
After opening the WebSocket, send {ac:"auth", params:"YOUR_API_KEY"}. A successful authentication returns {code:1, resAc:"auth", msg:"authenticated"}.

What symbols and types can I subscribe to?
Use symbol$region (e.g., AAPL$US). Data types: tick, quote, depth, kline. Subscribe by sending {ac:"subscribe", params:"AAPL$US,tick,quote"}.

How do I keep the connection alive?
Respond to every server ping ({ac:"ping", params:timestamp}) with a pong containing the same timestamp ({ac:"pong", params:timestamp}).

What causes disconnections, and how to prevent them?
Disconnections result from failed authentication, exceeding symbol caps, buffer overflows (slow message handling), or not replying to pings.

Which markets are covered by iTick WebSocket API?
It covers global stocks (US, HK, A-shares, and others), forex, major cryptocurrencies, a wide array of indices, futures, and funds.

Can I receive multiple data types per symbol (tick, quote, depth, etc.)?
Yes; specify multiple types in the params string.

What common fields are in messages?
Most include: s (symbol), ld (last price), v (volume), t (timestamp), type (data type).

Is trade direction included?
Yes, in the "d" field of tick data for major equity markets (0: default, 1: sell, 2: buy).

How do I implement WebSocket integration in JavaScript?
Use the WebSocket class, implement onopen/onmessage/onclose/onerror, send proper authentication and subscription messages, and reply to ping events immediately.

Note: Service plans and operational limits may change. Refer to the official documentation for the latest guidelines.

Compliance and Disclaimer
All financial market data provided via the iTick Real-time Market Data API, including through WebSocket and REST protocols, is strictly for informational use and must not be relied upon for trading, investment, or financial decision-making. Data redistribution is strictly prohibited under licensing agreements. Always validate integrations in non-production environments prior to deployment and consult with your technology and legal compliance teams to ensure adherence to all regulatory and internal controls.

For further technical assistance, current best practices, or clarification on integration challenges, Contact iTick Support to engage with a specialist.

Top comments (0)