Skip to main content

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.

Code Examples Repository

How to Subscribe#

Send a subscription message to the WebSocket endpoint:

{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}

Subscription Parameters#

ParameterTypeRequiredDescription
typestringYesMust be "trades"
coinstringYesTrading 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#

FieldTypeDescription
channelstringAlways "trades" for this subscription type
dataarrayArray of trade objects (may contain multiple trades per message)
coinstringTrading pair symbol
sidestring"A" = Ask (sell/taker sold), "B" = Bid (buy/taker bought)
pxstringExecution price
szstringTrade size in base currency
timenumberUnix timestamp in milliseconds
hashstringTransaction hash on Hyperliquid
tidnumberUnique trade ID
usersarrayArray 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#

#!/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())

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?


Stream institutional-grade Hyperliquid trade data with Dwellir's ultra-low latency infrastructure.