Websockets

circle-info

Hedgers do not need to provide a uPnL service.

Websocket Endpoints

Detailed documentation about websockets queries and returned data can be found here. It's recommended that solvers follow the same structure in their websockets to integrate with frontends more easily.

/upnl-ws

Streams unrealized profit/loss (uPnL) data for a given user sub-account address. The client sends an address (string) to subscribe. The server should validates this address (whitelisting check) and then, in a loop, retrieves and sends the user’s uPnL every 2 seconds.

  async def send_upnl_data(websocket: WebSocket, address: str, q: asyncio.Queue):
        """
        Fetch user's uPnL and send it to the client.
        If there's new data in the queue (new address?), switch to that on next iteration.
        """
        if q.empty():
            content = UpnlCalculator.get_party_a_upnl(address) if address else {}
            await safe_send_data(websocket, content)
            await asyncio.sleep(2) 
            return address
        else:
            return await q.get()

The uPnL Calculator is designed to compute and store unrealized profit/loss (uPnL) for PartyA and PartyB accounts. It ensures that the system maintains a real-time view of user account health by leveraging database computations and caching these results in Redis for efficient access. Prices are retrieved using an external price-fetcher utility (e.g., Binance or other sources) and uPnL is calculated for each account.

/upnl-a

The /upnl-a route retrieves the precomputed uPnL value for a given PartyA account from Redis. The route queries Redis for the key corresponding to the given account: If the key exists, it returns the cached uPnL data as a JSON object.

uPnL Calculation Flow

  • The system iterates through all PartyA accounts stored in the database. Each account is identified using a SingleAccountIdentifier.

  • Current market prices for each symbol are fetched using the PriceFetcher utility

  • Open positions for each account are grouped by symbol. For each position, Quantities and prices are aggregated. Signed and total quantities are calculated based on position types (LONG/SHORT).

For each account:

  • Unrealized profit/loss is computed based on the difference between current market prices and position opening prices.

  • Notional values are calculated as the total exposure per account.

  • Liquidation checks are performed to determine account solvency.

Calculation Snippet

/position-state-ws

This WebSocket allows clients (e.g., frontends or user dashboards) to subscribe to updates for specific addresses and stream real-time position states for those addresses as well as notify users about changes to their positions.

Core Functions

initialize_listeners()

  • Purpose: Listens for incoming data from clients and validates addresses.

  • Flow:

    • Parse the address list sent by the client.

    • Validate addresses against a whitelist (CounterPartyWhiteList).

    • Register channels for listening to position state updates.

send_position_data()

  • Purpose: Fetch position updates from the database or message queue and send them to the client.

  • Flow:

    • Retrieve notifications from PsycopgManager.

    • Parse the notification payload for position state updates.

    • Send the parsed data back to the client.

get_data_and_send()

  • Purpose: Combines the above functions into a continuous data retrieval and sending loop.

  • Flow:

    • Call initialize_listeners() to set up subscriptions.

    • Continuously fetch and send position state data to clients.

/funding-rate-ws

This WebSocket enables real-time funding rate updates to clients. Below is the structure and key features of the WebSocket implementation.

Fetching Symbol Funding Details

The funding rate details are fetched from Binance or another external source.

Calculating Funding Details

This method prepares the funding rate details required for applying funding rates to positions. The query groups positions by party_a_address and calculates funding rates:

Applying Funding Rates

Applies calculated rates to positions and update the system. You can read about charging funding rates here.

Last updated