|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Loading prices...
WebSocket

WebSocket Connection

Connect to the Polyblock WebSocket server for real-time price updates, orderbook changes, and trade notifications.

Establishing Connection

Connect to the WebSocket server at ws://localhost:8081/ws:

const ws = new WebSocket('ws://localhost:8081/ws')

ws.onopen = () => {
  console.log('Connected to Polyblock WebSocket')
}

ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}

ws.onclose = (event) => {
  console.log('WebSocket closed:', event.code, event.reason)
}
The WebSocket connection itself doesn't require authentication. However, some message types may require credentials.

Health Check

Verify the WebSocket service is running before attempting to connect:

curl http://localhost:8081/health

# Response
{"status":"ok"}

If the health check fails, start the WebSocket service:

cd ws-service && npm run start

Reconnection Strategy

Implement automatic reconnection for robust applications:

class WebSocketClient {
  constructor(url) {
    this.url = url
    this.reconnectDelay = 1000
    this.maxReconnectDelay = 30000
    this.connect()
  }

  connect() {
    this.ws = new WebSocket(this.url)
    
    this.ws.onopen = () => {
      console.log('Connected')
      this.reconnectDelay = 1000 // Reset on success
      this.resubscribe()
    }
    
    this.ws.onclose = () => {
      console.log(`Reconnecting in ${this.reconnectDelay}ms`)
      setTimeout(() => this.connect(), this.reconnectDelay)
      this.reconnectDelay = Math.min(
        this.reconnectDelay * 2,
        this.maxReconnectDelay
      )
    }
  }
  
  resubscribe() {
    // Re-subscribe to previously subscribed channels
  }
}
Double the reconnection delay on each failure (up to a maximum) to avoid overwhelming the server.

Complete Example

const ws = new WebSocket('ws://localhost:8081/ws')

ws.onopen = () => {
  console.log('Connected!')
  
  // Subscribe to market data
  ws.send(JSON.stringify({
    type: 'subscribe',
    channel: 'prices',
    marketId: 'YOUR_MARKET_ID'
  }))
}

ws.onmessage = (event) => {
  const data = JSON.parse(event.data)
  
  switch (data.type) {
    case 'price_update':
      console.log('Price:', data.price)
      break
    case 'orderbook_update':
      console.log('Orderbook:', data.bids, data.asks)
      break
  }
}

ws.onclose = () => {
  console.log('Disconnected')
}