← Back to Articles

WebSocket Alerts: Real-Time Trade Notifications

"In trading, timing is everything. The difference between catching a move and missing it can be measured in seconds."

What if you could receive instant notifications the moment a top trader opens a position? No delays, no refreshing pages, no missing opportunities. That's exactly what PerpsTracker's WebSocket Alerts deliver.

This guide will walk you through everything you need to know about WebSocket alerts—what they are, how to set them up, and how to use them to stay ahead of the market.

What Are WebSocket Alerts?

WebSocket is a communication protocol that enables real-time, two-way communication between your application and our servers. Unlike traditional HTTP requests where you have to keep asking "any new trades?", WebSockets push data to you instantly when something happens.

WebSocket vs Polling: The Difference

  • HTTP Polling: You ask the server every few seconds "any new trades?" - wasteful and slow
  • WebSocket: Server tells YOU immediately when a trade happens - instant and efficient

Result: WebSocket alerts arrive in milliseconds, not seconds. In fast-moving markets, this can be the difference between catching a trade and missing it entirely.

What Triggers an Alert?

You'll receive real-time notifications for trades from wallets on your watchlist:

  • New Positions: When a trader opens a new long or short position
  • Position Increases: When a trader adds to an existing position
  • Position Closes: When a trader closes (fully or partially) a position
  • Liquidations: When a trader's position gets liquidated

Prerequisites: What You Need

Before You Start:

An Elite subscription (WebSocket alerts are an Elite feature)
Your API key from the account settings page
At least one wallet added to your watchlist
Basic programming knowledge (JavaScript, Python, or any WebSocket-capable language)

Don't Have an Elite Subscription Yet?

View our pricing page to learn about Elite features. WebSocket alerts, webhooks, and advanced API access are all included.

Quick Start: Connect in 5 Minutes

Here's the fastest way to get connected and receiving alerts:

Step 1: Get Your API Key

  1. Log in to your PerpsTracker account
  2. Go to Account Settings → API Keys
  3. Click "Generate New Key"
  4. Copy and save your API key securely

Keep Your API Key Secret

Your API key grants access to your account's WebSocket alerts. Never share it publicly, commit it to git repositories, or expose it in client-side code. Treat it like a password.

Step 2: Connect to the WebSocket

Connect to our WebSocket endpoint with your API key:

// WebSocket Connection URL wss://perpstracker.com:5001/ws/alerts?apiKey=YOUR_API_KEY

Step 3: JavaScript Example

Here's a complete, working example you can run in Node.js:

const WebSocket = require('ws'); const API_KEY = 'your_api_key_here'; const WS_URL = `wss://perpstracker.com:5001/ws/alerts?apiKey=${API_KEY}`; const ws = new WebSocket(WS_URL); ws.on('open', () => { console.log('Connected to PerpsTracker WebSocket!'); }); ws.on('message', (data) => { const alert = JSON.parse(data); if (alert.type === 'trade') { console.log(`Trade Alert: ${alert.data.owner}`); console.log(` Market: ${alert.data.marketSymbol}`); console.log(` Side: ${alert.data.side}`); console.log(` Size: $${alert.data.sizeUsd}`); console.log(` Type: ${alert.data.tradeType}`); } }); ws.on('close', () => { console.log('WebSocket connection closed'); }); ws.on('error', (error) => { console.error('WebSocket error:', error.message); });

Step 4: Python Example

Prefer Python? Here's the equivalent code:

import asyncio import websockets import json API_KEY = "your_api_key_here" WS_URL = f"wss://perpstracker.com:5001/ws/alerts?apiKey={API_KEY}" async def listen_alerts(): async with websockets.connect(WS_URL) as ws: print("Connected to PerpsTracker WebSocket!") async for message in ws: alert = json.loads(message) if alert["type"] == "trade": data = alert["data"] print(f"Trade Alert: {data['owner']}") print(f" Market: {data['marketSymbol']}") print(f" Side: {data['side']}") print(f" Size: ${data['sizeUsd']}") asyncio.run(listen_alerts())

Understanding Alert Data

Each trade alert contains comprehensive information about the trade. Here's what you'll receive:

Field Description Example
owner Trader's wallet address DRVRvzf8pS...
marketSymbol Trading pair SOL-PERP
side Long or Short long
sizeUsd Position size in USD 15000.50
leverage Position leverage 5.2
entryPrice Entry price 185.42
tradeType Type of trade action open, increase, close, liquidation
timestamp When the trade occurred 2025-01-15T10:30:00Z

Best Practices for Production Use

1. Implement Automatic Reconnection

WebSocket connections can drop due to network issues. Always implement automatic reconnection:

function connect() { const ws = new WebSocket(WS_URL); ws.on('close', () => { console.log('Connection lost. Reconnecting in 5s...'); setTimeout(connect, 5000); }); ws.on('error', (error) => { console.error('WebSocket error:', error); ws.close(); }); return ws; }

2. Handle Heartbeats

The server sends periodic ping messages. Respond with pong to keep the connection alive:

ws.on('ping', () => { ws.pong(); });

3. Process Alerts Asynchronously

Don't block the WebSocket handler. If you need to perform actions (like placing trades), do them asynchronously:

ws.on('message', async (data) => { const alert = JSON.parse(data); // Don't await here - process in background processAlert(alert).catch(console.error); });

Common Use Cases

What Can You Build With WebSocket Alerts?

  • Copy Trading Bot: Automatically mirror trades from top traders
  • Telegram/Discord Notifications: Push alerts to your phone instantly
  • Trade Dashboard: Real-time display of watchlist activity
  • Analytics Pipeline: Feed trade data into your own analysis system
  • Alert Aggregator: Combine with other data sources for smart alerts

Troubleshooting

Connection Refused

  • Verify your API key is correct and hasn't been revoked
  • Ensure you have an active Elite subscription
  • Check that you're using the correct WebSocket URL (wss:// not ws://)

Not Receiving Alerts

  • Confirm you have wallets added to your watchlist
  • Verify those wallets are actively trading
  • Check your connection is still open (implement heartbeat handling)

Connection Drops Frequently

  • Implement automatic reconnection with exponential backoff
  • Respond to ping messages with pong
  • Check your network stability

Need More Help?

Check our full documentation or join our Discord community for support.

Next Steps

Now that you understand WebSocket alerts, you're ready to build something powerful. Here are some recommended next steps:

Your Action Plan:

Set up your development environment with WebSocket support
Generate your API key and test the connection
Add your target traders to your watchlist
Build your first alert handler
Read the Building a Copy Trader guide for advanced usage
← Back to Articles