JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 183
  • Score
    100M100P100Q100071F
  • License MIT

WebSocket streaming SDK for real-time WioEX market data

Package Exports

  • @wioex/stream-sdk
  • @wioex/stream-sdk/dist/index.esm.js
  • @wioex/stream-sdk/dist/index.js
  • @wioex/stream-sdk/dist/wioex-stream.min.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@wioex/stream-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@wioex/stream-sdk

npm version TypeScript License: MIT

WebSocket streaming SDK for real-time WioEX market data. Receive live stock ticker updates with a simple, event-driven API.

Features

  • 🚀 Real-time streaming - WebSocket-based live market data
  • 📊 Multiple stocks - Track up to 8 stocks simultaneously
  • 🔄 Auto-reconnection - Automatic reconnection with exponential backoff
  • 🎯 Type-safe - Written in TypeScript with full type definitions
  • 🌐 Universal - Works in Node.js and browsers
  • 📦 Lightweight - Minimal dependencies
  • 🔌 Event-driven - Simple EventEmitter-based API
  • 💪 Production-ready - Robust error handling and heartbeat mechanism

Installation

npm install @wioex/stream-sdk

Quick Start

Node.js

import { WioexStreamClient } from '@wioex/stream-sdk';

const client = new WioexStreamClient({
  apiKey: 'your-api-key',
  maxSymbols: 8
});

// Listen for ticker updates
client.on('ticker', (data) => {
  console.log(`${data.ticket}: $${data.last} (${data.changePercent}%)`);
});

// Connect and subscribe
client.connect();
client.subscribe(['AAPL', 'TSLA', 'GOOGL']);

Browser

<script src="https://unpkg.com/@wioex/stream-sdk/dist/wioex-stream.min.js"></script>
<script>
  const client = new WioexStream({
    apiKey: 'your-api-key',
    maxSymbols: 8
  });

  client.on('ticker', (data) => {
    console.log(`${data.ticket}: $${data.last}`);
  });

  client.connect();
  client.subscribe(['AAPL', 'TSLA']);
</script>

API Reference

Constructor

new WioexStreamClient(config: WioexStreamConfig)

Configuration Options

Option Type Default Description
apiKey string required Your WioEX API key
maxSymbols number 8 Maximum symbols to track (1-8)
autoReconnect boolean true Enable auto-reconnection
reconnectDelay number 3000 Reconnection delay (ms)
maxReconnectAttempts number 0 Max reconnect attempts (0 = infinite)
heartbeatInterval number 30000 Heartbeat interval (ms)
streamUrl string Auto WebSocket URL (auto-generated)

Methods

connect(): void

Connect to WioEX WebSocket stream.

client.connect();

disconnect(): void

Disconnect from WebSocket stream.

client.disconnect();

subscribe(stocks: string | string[]): void

Subscribe to stock ticker updates.

client.subscribe('AAPL');
client.subscribe(['AAPL', 'TSLA', 'GOOGL']);

Throws: Error if attempting to subscribe to more than maxSymbols.

unsubscribe(stocks: string | string[]): void

Unsubscribe from stock ticker updates.

client.unsubscribe('AAPL');
client.unsubscribe(['AAPL', 'TSLA']);

getState(): ConnectionState

Get current connection state.

const state = client.getState();
// Returns: 'disconnected' | 'connecting' | 'connected' | 'registered' | 'reconnecting' | 'failed'

getSubscribedStocks(): string[]

Get list of currently subscribed stocks.

const stocks = client.getSubscribedStocks();
console.log(stocks); // ['AAPL', 'TSLA', 'GOOGL']

getStats(): ClientStats

Get client statistics.

const stats = client.getStats();
console.log(stats);
// {
//   connectedAt: 1704067200000,
//   reconnectAttempts: 0,
//   messagesReceived: 152,
//   messagesSent: 3,
//   tickersReceived: 148,
//   subscribedStocks: ['AAPL', 'TSLA'],
//   state: 'registered'
// }

isConnected(): boolean

Check if client is connected.

if (client.isConnected()) {
  console.log('Connected!');
}

Events

The client extends EventEmitter and emits the following events:

connected

Emitted when WebSocket connection is established.

client.on('connected', () => {
  console.log('Connected to WioEX stream');
});

registered

Emitted when client is registered with API key.

client.on('registered', (data) => {
  console.log('Registered:', data.message);
});

subscribed

Emitted when subscribed to stocks.

client.on('subscribed', (stocks: string[]) => {
  console.log('Subscribed to:', stocks);
});

unsubscribed

Emitted when unsubscribed from stocks.

client.on('unsubscribed', (stocks: string[]) => {
  console.log('Unsubscribed from:', stocks);
});

ticker

Emitted when ticker data is received.

client.on('ticker', (data: TickerData) => {
  console.log(`${data.ticket}: $${data.last}`);
});

TickerData Structure:

interface TickerData {
  ticket: string;        // Stock symbol
  last: string;          // Last price
  open: string;          // Opening price
  high: string;          // High price
  low: string;           // Low price
  volume: string;        // Trading volume
  bid: string;           // Bid price
  ask: string;           // Ask price
  change: string;        // Price change
  changePercent: string; // Change percentage
  timestamp: number;     // Unix timestamp
}

error

Emitted when an error occurs.

client.on('error', (error: Error) => {
  console.error('Error:', error.message);
});

disconnected

Emitted when connection is closed.

client.on('disconnected', (code: number, reason: string) => {
  console.log(`Disconnected (${code}): ${reason}`);
});

reconnecting

Emitted when attempting to reconnect.

client.on('reconnecting', (attempt: number) => {
  console.log(`Reconnecting... (attempt ${attempt})`);
});

stateChange

Emitted when connection state changes.

client.on('stateChange', (state: ConnectionState) => {
  console.log(`State: ${state}`);
});

Examples

Basic Usage

import { WioexStreamClient } from '@wioex/stream-sdk';

const client = new WioexStreamClient({
  apiKey: process.env.WIOEX_API_KEY!,
  maxSymbols: 5
});

client.on('ticker', (data) => {
  const change = parseFloat(data.changePercent);
  const arrow = change >= 0 ? '↑' : '↓';
  console.log(`${arrow} ${data.ticket}: $${data.last} (${change.toFixed(2)}%)`);
});

client.connect();
client.subscribe(['AAPL', 'TSLA', 'GOOGL', 'MSFT', 'AMZN']);

Dynamic Subscription Management

const client = new WioexStreamClient({
  apiKey: 'your-api-key',
  maxSymbols: 3
});

client.on('registered', () => {
  // Subscribe to initial stocks
  client.subscribe(['AAPL', 'TSLA', 'GOOGL']);
});

// After 30 seconds, switch to different stocks
setTimeout(() => {
  client.unsubscribe(['GOOGL']);
  client.subscribe(['MSFT']);
}, 30000);

client.connect();

Error Handling

const client = new WioexStreamClient({
  apiKey: 'your-api-key',
  autoReconnect: true,
  maxReconnectAttempts: 5
});

client.on('error', (error) => {
  console.error('Error:', error.message);
});

client.on('disconnected', (code, reason) => {
  console.log(`Disconnected: ${reason}`);
  if (code !== 1000) {
    console.log('Unexpected disconnection');
  }
});

client.on('reconnecting', (attempt) => {
  console.log(`Reconnecting... attempt ${attempt}`);
});

client.connect();

Statistics Monitoring

const client = new WioexStreamClient({
  apiKey: 'your-api-key'
});

client.connect();
client.subscribe(['AAPL', 'TSLA']);

// Log statistics every minute
setInterval(() => {
  const stats = client.getStats();
  console.log('Statistics:', {
    uptime: Date.now() - stats.connectedAt!,
    messagesReceived: stats.messagesReceived,
    tickersReceived: stats.tickersReceived,
    subscribedStocks: stats.subscribedStocks
  });
}, 60000);

WebSocket Protocol

The SDK communicates with WioEX WebSocket API using JSON messages:

Connection

wss://stream.wioex.com/rs/i/{max_symbols}/websocket

Registration

{
  "action": "register",
  "apiKey": "your-api-key"
}

Response:

{
  "status": "success",
  "type": "registered",
  "message": "Client registered successfully"
}

Subscribe

{
  "action": "subscribe",
  "stocks": ["AAPL", "TSLA", "GOOGL"]
}

Response:

{
  "status": "success",
  "type": "subscribed",
  "message": "Subscribed to stocks",
  "stocks": ["AAPL", "TSLA", "GOOGL"]
}

Ticker Update

{
  "sarex": {
    "_p": { "e": "d" },
    "ticker": {
      "ticket": "AAPL",
      "last": "185.25",
      "open": "183.50",
      "high": "186.00",
      "low": "183.00",
      "volume": "52478963",
      "bid": "185.20",
      "ask": "185.30",
      "change": "1.75",
      "changePercent": "0.95",
      "timestamp": 1704067200000
    }
  }
}

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import {
  WioexStreamClient,
  WioexStreamConfig,
  TickerData,
  ConnectionState,
  ClientStats
} from '@wioex/stream-sdk';

const config: WioexStreamConfig = {
  apiKey: 'your-api-key',
  maxSymbols: 8
};

const client = new WioexStreamClient(config);

client.on('ticker', (data: TickerData) => {
  // TypeScript knows the exact structure of data
  console.log(data.ticket, data.last, data.changePercent);
});

Browser Support

The SDK works in all modern browsers that support WebSocket:

  • Chrome 16+
  • Firefox 11+
  • Safari 7+
  • Edge 12+
  • Opera 12.1+

Node.js Support

Requires Node.js 16 or higher.

Development

# Install dependencies
npm install

# Build the package
npm run build

# Run linter
npm run lint

# Run tests
npm test

# Development mode (watch)
npm run dev

Examples

See the examples/ directory for complete examples:

  • Node.js Example: examples/node-example.js
  • Browser Example: examples/browser-example.html

To run the Node.js example:

cd examples
WIOEX_API_KEY=your-api-key node node-example.js

To run the browser example:

  1. Build the package: npm run build
  2. Open examples/browser-example.html in a browser
  3. Enter your API key and click Connect

License

MIT License - see LICENSE file for details.

Support

Publishing to NPM

To publish this package to NPM:

# Login to NPM
npm login

# Build the package
npm run build

# Publish to NPM
npm publish --access public

Made with ❤️ by WioEX