Trades Stream
Stream real-time trade executions as they occur on Hyperliquid. Each trade message contains the execution price, size, direction (buy/sell), timestamp, and participant wallet addresses.
Clone our complete examples: github.com/dwellir-public/hyperliquid-orderbook-server-code-examples
How to Subscribe#
Send a subscription message to the WebSocket endpoint:
{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
Subscription Parameters#
| Parameter | Type | Required | Description |
|---|---|---|---|
type | string | Yes | Must be "trades" |
coin | string | Yes | Trading pair symbol (e.g., "BTC", "ETH", "SOL") |
Sample Response#
{
"channel": "trades",
"data": [
{
"coin": "BTC",
"side": "B",
"px": "90058.0",
"sz": "0.00012",
"hash": "0x0a4cc891f222c1cf0bc60432f4991e02013400778d25e0a1ae1573e4b1269bb9",
"time": 1767878803102,
"tid": 907188554740561,
"users": [
"0xb08ed6f6ad7b22138d4db6d0549efcf1f5e51767",
"0x13558be785661958932ceac35ba20de187275a42"
]
}
]
}
Response Field Reference#
| Field | Type | Description |
|---|---|---|
channel | string | Always "trades" for this subscription type |
data | array | Array of trade objects (may contain multiple trades per message) |
coin | string | Trading pair symbol |
side | string | "A" = Ask (sell/taker sold), "B" = Bid (buy/taker bought) |
px | string | Execution price |
sz | string | Trade size in base currency |
time | number | Unix timestamp in milliseconds |
hash | string | Transaction hash on Hyperliquid |
tid | number | Unique trade ID |
users | array | Array of two wallet addresses: [buyer, seller] |
Understanding the side Field#
The side field indicates which side of the order book the trade executed against:
"A"(Ask): The taker sold into the bid. A market sell order matched with a resting buy order."B"(Bid): The taker bought from the ask. A market buy order matched with a resting sell order.
Code Examples#
- Python
- JavaScript
- Go
#!/usr/bin/env python3
"""
Trades Stream Example - Real-time trade executions
"""
import asyncio
import json
import websockets
from datetime import datetime
async def stream_trades():
ws_url = "wss://your-instance.dwellir.com/ws"
async with websockets.connect(ws_url) as websocket:
# Subscribe to BTC trades
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}))
print("Subscribed to BTC trades\n")
async for message in websocket:
data = json.loads(message)
if data.get("channel") == "trades":
for trade in data["data"]:
side = "BUY" if trade["side"] == "B" else "SELL"
timestamp = datetime.fromtimestamp(trade["time"] / 1000)
print(f"[{side}] {trade['coin']}: "
f"{trade['sz']} @ ${trade['px']} | "
f"{timestamp.strftime('%H:%M:%S.%f')[:-3]}")
if __name__ == "__main__":
asyncio.run(stream_trades())
const WebSocket = require('ws');
const wsUrl = 'wss://your-instance.dwellir.com/ws';
const ws = new WebSocket(wsUrl);
ws.on('open', () => {
// Subscribe to BTC trades
ws.send(JSON.stringify({
method: 'subscribe',
subscription: {
type: 'trades',
coin: 'BTC'
}
}));
console.log('Subscribed to BTC trades\n');
});
ws.on('message', (rawData) => {
const data = JSON.parse(rawData);
if (data.channel === 'trades') {
for (const trade of data.data) {
const side = trade.side === 'B' ? 'BUY' : 'SELL';
const time = new Date(trade.time).toISOString();
console.log(`[${side}] ${trade.coin}: ${trade.sz} @ $${trade.px} | ${time}`);
}
}
});
ws.on('error', (error) => console.error('WebSocket error:', error));
package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/gorilla/websocket"
)
type TradeMessage struct {
Channel string `json:"channel"`
Data []Trade `json:"data"`
}
type Trade struct {
Coin string `json:"coin"`
Side string `json:"side"`
Px string `json:"px"`
Sz string `json:"sz"`
Time int64 `json:"time"`
Hash string `json:"hash"`
Tid int64 `json:"tid"`
Users []string `json:"users"`
}
func main() {
wsURL := "wss://your-instance.dwellir.com/ws"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer conn.Close()
// Subscribe to BTC trades
subscription := map[string]interface{}{
"method": "subscribe",
"subscription": map[string]string{
"type": "trades",
"coin": "BTC",
},
}
conn.WriteJSON(subscription)
fmt.Println("Subscribed to BTC trades\n")
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
return
}
var tradeMsg TradeMessage
if err := json.Unmarshal(message, &tradeMsg); err != nil {
continue
}
if tradeMsg.Channel == "trades" {
for _, trade := range tradeMsg.Data {
side := "SELL"
if trade.Side == "B" {
side = "BUY"
}
timestamp := time.UnixMilli(trade.Time).Format("15:04:05.000")
fmt.Printf("[%s] %s: %s @ $%s | %s\n",
side, trade.Coin, trade.Sz, trade.Px, timestamp)
}
}
}
}
VWAP Calculator Example#
Calculate Volume-Weighted Average Price from the trade stream:
from collections import deque
class VWAPCalculator:
def __init__(self, window_size=100):
self.trades = deque(maxlen=window_size)
def add_trade(self, price, size):
self.trades.append({
'price': float(price),
'size': float(size)
})
def get_vwap(self):
if not self.trades:
return 0
total_value = sum(t['price'] * t['size'] for t in self.trades)
total_volume = sum(t['size'] for t in self.trades)
return total_value / total_volume if total_volume > 0 else 0
def get_total_volume(self):
return sum(t['size'] for t in self.trades)
# Usage in your trade handler
vwap = VWAPCalculator(window_size=100)
async def handle_trade(trade):
vwap.add_trade(trade['px'], trade['sz'])
print(f"VWAP: ${vwap.get_vwap():.2f} | Volume: {vwap.get_total_volume():.4f}")
Buy/Sell Pressure Analysis#
Track market direction from trade flow:
class TradePressureAnalyzer:
def __init__(self, window_size=50):
self.buy_volume = 0
self.sell_volume = 0
self.trades = deque(maxlen=window_size)
def add_trade(self, side, size):
size = float(size)
# Remove oldest trade's contribution if at capacity
if len(self.trades) == self.trades.maxlen:
old = self.trades[0]
if old['side'] == 'B':
self.buy_volume -= old['size']
else:
self.sell_volume -= old['size']
# Add new trade
self.trades.append({'side': side, 'size': size})
if side == 'B':
self.buy_volume += size
else:
self.sell_volume += size
def get_buy_sell_ratio(self):
if self.sell_volume == 0:
return float('inf') if self.buy_volume > 0 else 0
return self.buy_volume / self.sell_volume
def get_pressure_signal(self):
ratio = self.get_buy_sell_ratio()
if ratio > 1.5:
return "STRONG BUY PRESSURE"
elif ratio > 1.1:
return "BUY PRESSURE"
elif ratio < 0.67:
return "STRONG SELL PRESSURE"
elif ratio < 0.9:
return "SELL PRESSURE"
return "NEUTRAL"
Use Cases#
Trade Flow Analysis#
Monitor real-time trade executions to understand market momentum:
- Direction detection: Track whether buyers or sellers are dominating
- Large trade alerts: Identify whale activity by filtering on size
- Execution timing: Measure latency between your orders and confirmations
VWAP and TWAP Calculations#
Build execution benchmarks from the trade stream:
- VWAP: Volume-weighted average price for execution quality analysis
- TWAP: Time-weighted average price for order slicing strategies
- Implementation shortfall: Compare your fills against market VWAP
Historical Trade Recording#
Capture trade data for backtesting and research:
- Tick data collection: Store every trade for historical analysis
- Pattern recognition: Train ML models on trade sequences
- Market replay: Reconstruct market conditions for strategy testing
Wallet Tracking#
Use the users field to monitor specific addresses:
- Whale watching: Alert when known large traders execute
- Copy trading signals: Track successful trader activity
- Smart money flow: Analyze institutional wallet behavior
Subscription Management#
Multiple Coin Subscriptions#
Subscribe to multiple trading pairs on a single connection:
coins = ["BTC", "ETH", "SOL", "ARB"]
for coin in coins:
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": coin
}
}))
Unsubscribe#
Stop receiving trades for a specific coin:
{
"method": "unsubscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
Get Access#
Ready to integrate real-time Hyperliquid trade data?
- Volume Calculator - Estimate monthly message volume
- Contact Sales - Get your WebSocket credentials
- Dashboard - Manage your subscription
Stream institutional-grade Hyperliquid trade data with Dwellir's ultra-low latency infrastructure.