> ## Documentation Index
> Fetch the complete documentation index at: https://docs.voxfi.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Connection

> Connecting to WebSocket and managing the connection

## WebSocket URL

All WebSocket connections should be made to:

```
wss://data-ws-dev.voxfi.com.br
```

## Establishing Connection

To connect to the WebSocket, establish a standard WebSocket connection to the URL above. No authentication is required for the initial connection, but some channels require authentication when subscribing.

## Ping/Pong

The WebSocket implements an automatic heartbeat system to keep the connection alive and detect disconnections.

### Automatic Heartbeat

The server automatically sends ping messages every **10 seconds**. You must respond with pong within **20 seconds** to avoid disconnection due to timeout.

### Manual Ping

You can also manually send a simple text message to check latency:

**Send:**

```
ping
```

**Receive:**

```
pong
```

### Timeout

If you don't respond to server pings within 20 seconds, the connection will be automatically closed. Make sure your WebSocket implementation automatically responds to server pings.

## Available Channels

The WebSocket offers three types of channels to receive different types of updates:

### User Channel

Receive updates about your own orders and transactions. Requires API key authentication.

[Complete User Channel documentation](/en/websockets/user-channel)

### Market Channel

Receive updates about specific markets (orderbook and trades). Does not require authentication.

[Complete Market Channel documentation](/en/websockets/market-channel)

### Event Channel

Receive updates about specific events (includes all markets in the event). Does not require authentication.

[Complete Event Channel documentation](/en/websockets/event-channel)

## Update Types

You can filter the type of update you want to receive on `market` and `event` channels:

* **`all`** or `""` (default): All updates (orderbook and trades);
* **`orderbook`**: Only orderbook updates;
* **`trades`**: Only trade updates.

## Connection Example

<CodeGroup>
  ```javascript JavaScript theme={null}
  const ws = new WebSocket('wss://data-ws-dev.voxfi.com.br');

  ws.onopen = () => {
    console.log('Connected to WebSocket');
    
    // Send ping to check latency
    ws.send('ping');
  };

  ws.onmessage = (event) => {
    if (event.data === 'pong') {
      console.log('Pong received');
    } else {
      const data = JSON.parse(event.data);
      console.log('Message received:', data);
    }
  };

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

  ws.onclose = (event) => {
    console.log('Connection closed:', event.code, event.reason);
  };
  ```

  ```python Python theme={null}
  import asyncio
  import websockets
  import json

  async def connect_websocket():
      uri = "wss://data-ws-dev.voxfi.com.br"
      
      async with websockets.connect(uri) as websocket:
          # Send ping
          await websocket.send('ping')
          
          # Receive messages
          async for message in websocket:
              if message == 'pong':
                  print('Pong received')
              else:
                  data = json.loads(message)
                  print('Message received:', data)

  asyncio.run(connect_websocket())
  ```
</CodeGroup>

## Best Practices

* **Automatic Reconnection**: Implement automatic reconnection logic in case of disconnection. Use exponential backoff to avoid too frequent reconnections;
* **Automatic Heartbeat**: The server sends pings automatically every 10 seconds. Make sure your implementation automatically responds to server pings;
* **Manual Ping**: You can send `ping` manually to check latency, but it's not necessary due to automatic heartbeat;
* **Error Handling**: Always handle errors and disconnections properly. Check error codes to understand the cause of disconnection;
* **Specific Filters**: Use filters (`orderbook` or `trades`) when you only need one type of update to reduce network traffic;
* **Multiple Subscriptions**: You can subscribe to multiple markets and events on the same WebSocket connection;
* **State Management**: Keep local orderbook state and update as messages arrive;
* **Message Buffer**: In case of reconnection, consider making an HTTP request to get the current state before continuing to receive updates via WebSocket.

## Use Cases

* **Real-Time Price Monitoring**: Use the `market` channel with `orderbook` filter to receive instant price updates and build a real-time visualization;
* **Trade Tracking**: Use the `market` or `event` channel with `trades` filter to monitor trading activity and identify patterns;
* **Order Management**: Use the `user` channel to receive updates about your own orders and transactions, allowing quick reaction to changes;
* **Market Dashboard**: Combine multiple channels to create a complete real-time market dashboard with prices, trades, and your own positions;
* **Price Alerts**: Monitor price changes and automatically execute actions when certain levels are reached;
* **Liquidity Analysis**: Use orderbook updates to analyze market depth and make informed trading decisions;
* **Arbitrage**: Monitor prices across multiple markets simultaneously to identify arbitrage opportunities.
