惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
Engineering at Meta
Engineering at Meta
量子位
A
About on SuperTechFans
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
博客园 - 司徒正美
V
Visual Studio Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
腾讯CDC
Jina AI
Jina AI
C
Check Point Blog
H
Help Net Security
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
爱范儿
爱范儿
I
InfoQ

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Route Real-Time Gold and Silver Prices from a Unif...
Emily · 2026-05-29 · via DEV Community

Emily

When I first connected to a precious metals WebSocket API, I expected to get a clean stream of prices. What I actually got was a firehose of mixed ticks—gold, silver, platinum—all arriving through the same callback. If you’ve ever tried to build a trading bot or a custom chart, you know this is a recipe for disaster. In this post, I’ll share how I solved the problem with a few lines of Python and a clear mapping strategy.

The scenario: You have one WebSocket URL that pushes quotes for multiple metals. You need to separate them so you can update different UI components, run independent strategies, or store them in distinct database tables. The data pain point: every message uses the same JSON structure, and the only differentiator is a field like symbol. If you don’t act on it immediately, everything gets mixed up.

Identify Assets via the Symbol Field

Start by checking the API docs for the field that carries the instrument code. Usually it’s symbol, but instrumentId or type are also used. Here’s a typical reference table:

Field Description Example
symbol Asset code XAUUSD, XAGUSD
instrumentId Internal platform ID 1001, 1002
type Asset class gold, silver

I turn this into a dictionary mapping each symbol to a human-readable category:

asset_map = {
    "XAUUSD": "gold",
    "XAGUSD": "silver",
    "XPTUSD": "platinum"
}

Enter fullscreen mode Exit fullscreen mode

Buffer Messages by Type

Because these streams are high-frequency, I avoid processing every tick individually. Instead, the WebSocket callback just updates an in-memory store that is already grouped by asset type:

# Keep the hot path extremely light
def on_message(msg):
    symbol = msg['symbol']
    price = msg['price']
    asset_type = asset_map.get(symbol, "unknown")
    cache[asset_type][symbol] = price

Enter fullscreen mode Exit fullscreen mode

Then, a background timer fetches the latest prices from cache["gold"] and cache["silver"] separately and does the actual work—like computing indicators or rendering charts. The key benefit is complete isolation: your gold logic never touches a silver tick.

Subscribe Selectively

Most APIs allow you to specify which symbols you want. I always trim the list to only what I need. Some providers even support batch subscription by asset_type, which slashes unnecessary traffic even further.

When I tested AllTick’s WebSocket, the symbol field worked exactly as expected for distinguishing metals. Here’s a minimal, runnable snippet:

import websocket
import json

def on_message(ws, message):
    data = json.loads(message)
    symbol = data['symbol']
    print(f"{symbol} real-time price: {data['price']}")

ws = websocket.WebSocketApp("wss://api.alltick.co/ws",
                            on_message=on_message)
ws.run_forever()

Enter fullscreen mode Exit fullscreen mode

With this setup, gold and silver prices flow through the same connection but remain completely independent in your application logic.

Handle Disconnects and Bad Data

I always add reconnection with exponential backoff and a guard clause that checks if symbol exists. If not, the message is skipped. This prevents a single malformed packet from breaking the whole stream.

Wrapping Up

By combining a simple mapping dictionary, type-bucketed caching, and tight subscriptions, you can turn a messy, mixed stream into a set of clean, per-asset data channels. It’s a small engineering effort that pays off every time you add a new metal or a new strategy. If you’re working with WebSocket market data, give this pattern a try—it’s lightweight, scalable, and keeps your codebase sane.