<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by San Si wu on Medium]]></title>
        <description><![CDATA[Stories by San Si wu on Medium]]></description>
        <link>https://medium.com/@wutainfofu?source=rss-6591263924c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4UtZ0h6uQ9kVXwAQ</url>
            <title>Stories by San Si wu on Medium</title>
            <link>https://medium.com/@wutainfofu?source=rss-6591263924c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wutainfofu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python Forex Real-Time Market Data API: Migrating from REST Polling to WebSocket Push, Pitfalls…]]></title>
            <link>https://medium.com/@wutainfofu/python-forex-real-time-market-data-api-migrating-from-rest-polling-to-websocket-push-pitfalls-c365701436f7?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c365701436f7</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[forex]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 12:10:46 GMT</pubDate>
            <atom:updated>2026-10-26T12:10:46.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Forex Real-Time Market Data API: Migrating from REST Polling to WebSocket Push, Pitfalls Included</h3><p>I have a small forex rate dashboard project that mainly tracks the major currency pairs — EURUSD, GBPUSD, USDJPY. The first version was lazy: I used the REST endpoint to poll quotes every three seconds, and it worked fine for a while. Then I started doing volatility monitoring and realized that polling data can’t reconstruct a continuous price curve — the jumps between ticks were being erased by the three-second interval. That’s when I decided to migrate the real-time layer from REST polling to WebSocket push. This article documents the whole migration: the problems with the v1 polling approach, every pitfall I hit along the way, and how REST and WebSocket now work together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPAnS7JjWFl2fGI7D3oJIA.jpeg" /><figcaption>Forex Real-Time Market Data API</figcaption></figure><h3>v1: REST Polling — Simple, but with Real Problems</h3><p>The first version was dead simple — a loop calling the quote endpoint and updating the page with the latest price:</p><pre>import time<br>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: &quot;your_token_here&quot;}<br>def get_forex_quote(code=&quot;EURUSD&quot;, region=&quot;GB&quot;):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/forex/quote&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: region, &quot;code&quot;: code}<br>    )<br>    return resp.json()[&quot;data&quot;]<br>while True:<br>    q = get_forex_quote(&quot;EURUSD&quot;)<br>    # fields: ld last price o open h high l low t timestamp(ms) v volume tu turnover ch change chp change% ts trading status<br>    print(q[&quot;ld&quot;], q[&quot;t&quot;])<br>    time.sleep(3)</pre><p>The /forex/quote endpoint returns a single quote object with fields s/ld/o/h/l/t/v/tu/ch/chp/ts, clearly documented. The polling approach worked, but problems surfaced as I used it:</p><ul><li><strong>Latency is a function of the polling interval</strong>: with a three-second poll, the gap between when the market moved and when you see it can be up to three seconds. For intraday monitoring, that makes signals half a beat late</li><li><strong>Price jumps get lost</strong>: between two requests the price can move several ticks, and you never see the intermediate steps — the curve renders as stairs, not a curve</li><li><strong>Most requests are wasted</strong>: forex trades 24 hours a day, but with a three-second poll, most responses are identical to the last one — bandwidth and rate limits go to meaningless calls</li></ul><p>Polling is small in code but has a hard ceiling. Once you need volatility monitoring and tick-level data, there’s no way around switching.</p><h3>The Migration Decision: When You Know WebSocket Is Required</h3><p>My own signals — hit any one of them and it’s worth doing:</p><ol><li><strong>You need to monitor price movements, not just final states</strong> — curves, volatility, tick characteristics are impossible with polling</li><li><strong>You’re tracking multiple pairs at once</strong> — five pairs means five requests per cycle, and you’d need to double the frequency; the rate limits buckle first</li><li><strong>Latency starts affecting decisions</strong> — for example, quote-triggered alerts that are a few seconds late may miss the entry point</li></ol><p>Once I was clear on that, I started the migration. For the real-time layer I switched from REST to WebSocket push — the data source I used is iTick, and you can get a token from its website <a href="http://itick.org/">itick.org</a>. REST and WebSocket share the same token, so the switching cost turned out lower than expected.</p><h3>WebSocket Integration: Auth, Subscribe, Heartbeat — None Can Be Skipped</h3><p>The forex WebSocket flow is fixed: <strong>connect → wait for auth success → subscribe → receive messages → heartbeat every 30 seconds</strong>. The most overlooked sentence in the docs: connection established ≠ ready to subscribe — you must receive the auth success message (resAc:&quot;auth&quot;) before sending a subscribe request. I tripped on this the first time: subscribing inside on_open got a subscribe failure — too early.</p><p>Correct implementation:</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/forex&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>heartbeat_alive = True<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    # key: wait for auth success before subscribing<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;EURUSD$GB,GBPUSD$GB,USDJPY$GB&quot;,  # comma-separated, format symbol$region<br>            &quot;types&quot;: &quot;quote&quot;                              # quote/tick/depth/kline@1<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        # pushed quote fields are identical to REST: s/ld/o/h/l/t/v/tu<br>        print(data[&quot;s&quot;], data[&quot;ld&quot;], data[&quot;t&quot;])<br>def heartbeat(ws):<br>    while heartbeat_alive:<br>        time.sleep(30)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;ping&quot;,<br>            &quot;params&quot;: str(int(time.time() * 1000))<br>        }))<br>ws = websocket.WebSocketApp(<br>    WS_URL,<br>    header=[f&quot;token: {TOKEN}&quot;],<br>    on_message=on_message<br>)<br>ws.run_forever()</pre><p>The subscribe format is EURUSD$GB — &quot;symbol$region&quot; — with multiple instruments separated by commas. A single connection can subscribe up to 500 instruments, so all the major pairs fit on one connection. The type field in messages distinguishes data types: quote is quote updates, tick is trade-by-trade, depth is order book, kline@1 is 1-minute K-line increments.</p><h3>Pitfalls Hit During Migration, One by One</h3><h3>Pitfall 1: Subscribing Immediately on Connect</h3><p>Covered above — subscribing in on_open is wrong. You must wait for resAc:&quot;auth&quot;. The rule is simple: treat authenticated as the real &quot;ready to subscribe&quot; state.</p><h3>Pitfall 2: Heartbeat Thread Leak</h3><p>My first version started the heartbeat inside on_open. Every reconnect spawned another heartbeat thread, while old threads kept sending pings and pongs piled up unhandled. I later tied the heartbeat thread&#39;s liveness flag to the connection lifecycle — set it False on disconnect, start a fresh thread on reconnect.</p><h3>Pitfall 3: State Not Reset on Reconnect</h3><p>authenticated stayed True after a reconnect, so the code skipped the subscribe step even though the server had re-authenticated — and I received zero market data. After reconnect you must reset authenticated to False and let the flow go through &quot;auth → subscribe&quot; again.</p><h3>Pitfall 4: Messages Too Fast, Cache Explodes</h3><p>After subscribing to tick (trade-by-trade), message volume at peak can be huge. If your message handler does heavy work (like writing to a database), consumption can&#39;t keep up, the server buffer piles up, and the connection gets dropped. The fix: keep the message handler minimal (update prices in memory), and push persistence to a separate queue.</p><h3>The Right REST + WebSocket Combo: Snapshot + Increment</h3><p>After the migration I realized REST isn’t obsolete — its role just changed: <strong>REST handles snapshots, WebSocket handles increments</strong>. On startup, pull a full snapshot via the REST batch endpoint to initialize the current state of every pair, then let WebSocket push incremental updates and only touch what changed:</p><pre>def get_forex_quotes_batch():<br>    # /forex/quotes batch quotes, codes comma-separated<br>    # returns a dict keyed by product code<br>    resp = requests.get(<br>        f&quot;{API_BASE}/forex/quotes&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: &quot;GB&quot;, &quot;codes&quot;: &quot;EURUSD,GBPUSD,USDJPY,GBPUSD,USDCNH&quot;}<br>    )<br>    return resp.json()[&quot;data&quot;]<br>snapshot = get_forex_quotes_batch()<br>for symbol, quote in snapshot.items():<br>    print(symbol, quote[&quot;ld&quot;], quote[&quot;t&quot;])</pre><p>The batch endpoint /forex/quotes takes codes (plural), and the max number per call depends on your plan: 10 basic, 20 pro, 50 advanced. The response is a dict keyed by product code — iterate and update your local state table. This &quot;REST snapshot + WS increment&quot; combo cut invalid requests by 90% compared to pure polling, with more continuous data.</p><h3>Pitfall Checklist</h3><ul><li><strong>Wait for auth success before subscribing</strong> — authenticated True is the only &quot;ready&quot; state</li><li><strong>Heartbeat every 30 seconds</strong>; no heartbeat for over 1 minute and the server disconnects you; reset all state after reconnect</li><li><strong>Heartbeat threads must be stoppable</strong> — don’t stack them on reconnect</li><li><strong>Multiple instruments are comma-separated</strong> in symbol$region format, up to 500 per connection</li><li><strong>REST for snapshots, WS for increments</strong> — and don’t do heavy work inside the WS message handler</li><li><strong>Timestamps are milliseconds</strong> — unify units before comparing with local time</li><li><strong>The batch parameter is </strong><strong>codes</strong>, not code, and the response is a dict keyed by code</li></ul><h3>Wrap-Up</h3><p>Migrating from REST polling to WebSocket push isn’t really about swapping protocols — it’s about <strong>changing from “scheduled pulling” to “event-driven”</strong>: process quotes when they arrive, do nothing when there’s no activity. With this structure, latency went from “up to three seconds” to “milliseconds”, and request volume dropped by an order of magnitude. If you’re building forex real-time quote monitoring, alerting, or data collection, this migration path is directly reusable. For endpoint parameters and subscription details, checking the <a href="https://docs.itick.org/">official API docs</a> while coding saves the most time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c365701436f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Render Global Index K-Line Data: A Practical Chart Library Selection Guide After Fetching…]]></title>
            <link>https://medium.com/@wutainfofu/how-to-render-global-index-k-line-data-a-practical-chart-library-selection-guide-after-fetching-5cb1edc5f119?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb1edc5f119</guid>
            <category><![CDATA[kline]]></category>
            <category><![CDATA[index-funds]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 10:57:16 GMT</pubDate>
            <atom:updated>2026-10-20T10:57:16.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Render Global Index K-Line Data: A Practical Chart Library Selection Guide After Fetching Data with Python</h3><p>Anyone building market monitoring dashboards or index analysis tools eventually hits the final hurdle: the data API works, K-line data arrives, and then you get stuck on chart rendering — either the library docs are confusing, the charts lag, or there are no technical indicators. Data is only the first half; getting from data to pixels is a separate challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlrGFdvVAsMzYTLN-zmkAg.jpeg" /><figcaption>Global Index K-Line Data</figcaption></figure><p>I recently built a global index quotes page — for the data source I used iTick’s index API, and you can grab a token from their website <a href="http://itick.org/">itick.org</a>. This article records the trade-offs I made along the way: how to pin down the data structure, how the mainstream K-line chart libraries differ, and how it all fits together.</p><h3>Step 1: Pin Down the Data Structure and Fields</h3><p>Before choosing a chart library, you need to know exactly what data you hold. Fetching global index K-lines with Python — confirm the endpoint parameters and response fields first.</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br>def get_index_kline(code=&quot;SPX&quot;, region=&quot;GB&quot;, ktype=8, limit=200):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/indices/kline&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: region,   # index market code, GB = US market<br>            &quot;code&quot;: code,       # index code, e.g. SPX S&amp;P 500, NDX Nasdaq 100<br>            &quot;kType&quot;: ktype,     # period: 1=1min 2=5min 5=1hour 8=daily 9=weekly 10=monthly<br>            &quot;limit&quot;: limit      # number of bars, max 500<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br>bars = get_index_kline()<br>print(bars[0])</pre><p>Each returned bar has the fields t/o/h/l/c/v/tu: t timestamp (ms), o open, h high, l low, c close, v volume, tu turnover. This OHLCV structure is industry standard and recognized by almost every chart library — but <strong>each library has its own requirements for time format and data shape</strong>, and that&#39;s the root of most downstream pitfalls.</p><h3>Step 2: Before Choosing a Library, Understand the Data Format Differences</h3><p>There are many K-line chart libraries, but their data requirements fall into two categories:</p><p><strong>Array-of-rows format</strong>: [timestamp, open, high, low, close], timestamp first. TradingView&#39;s lightweight-charts uses this, with a type called UTCTimestamp (seconds).</p><p><strong>List-of-objects format</strong>: [{time: ..., open: ..., high: ..., low: ..., close: ...}, ...]. Both KLineChart and ECharts consume this; the time field can be milliseconds or a date string.</p><p>So no matter which library you pick, “convert the API response to the target shape” is unavoidable. Best to normalize on the Python side instead of wrestling in JS:</p><pre>def to_chart_format(bars):<br>    # lightweight-charts uses second-level timestamps<br>    return [[b[&quot;t&quot;] // 1000, b[&quot;o&quot;], b[&quot;h&quot;], b[&quot;l&quot;], b[&quot;c&quot;]] for b in bars]<br>def to_object_format(bars):<br>    # KLineChart / ECharts use object lists; time can stay in ms<br>    return [{&quot;time&quot;: b[&quot;t&quot;], &quot;open&quot;: b[&quot;o&quot;], &quot;high&quot;: b[&quot;h&quot;],<br>             &quot;low&quot;: b[&quot;l&quot;], &quot;close&quot;: b[&quot;c&quot;], &quot;volume&quot;: b[&quot;v&quot;]} for b in bars]</pre><p>Once the data is ready, chart library selection becomes a real comparison.</p><h3>Step 3: The Mainstream K-Line Chart Libraries, One by One</h3><h3>lightweight-charts</h3><p>TradingView’s official open-source lightweight charting library, built specifically for candlesticks. The pros are real: great performance (tens of thousands of bars without lag), a look close to TradingView’s own charts, a clean API, and solid docs. The cons: no built-in technical indicators (MACD, KDJ etc. must be computed and drawn yourself), and no trading features (drawing tools, order entry) — it’s positioned as data visualization, not a trading terminal.</p><p>If your goal is market display and research panels without heavy rendering work, this is the first choice. It’s open source and easy to find.</p><h3>KLineChart</h3><p>A K-line library from China with friendly Chinese docs, plenty of built-in technical indicators and drawing tools, and an active community. For developers in Chinese-speaking teams it has the lowest learning curve and suits <strong>tools with full technical analysis features</strong>. Cons: larger bundle size than lightweight-charts, and less style-customization freedom (you work within its component system).</p><h3>ECharts</h3><p>A general-purpose charting library, not designed specifically for candlesticks — but it wins on ecosystem, docs, and customization flexibility. K-line with ECharts is “serviceable”: the candlestick series supports basic candles, dataZoom handles zooming, but complex scenarios (volume linkage, order books, indicator overlays) require manual assembly, and performance at high data volumes isn&#39;t its strength.</p><h3>TradingView Charting Library</h3><p>The most feature-complete: professional-grade K-lines, indicators, drawing tools, and multi-timeframe switching. Best experience for commercial products. The cost is complexity and licensing — integration and maintenance cost far more than the first three, and it rarely makes sense for personal projects or small tools.</p><p>Side by side:</p><p>LibraryLearning curveTechnical indicatorsPerformanceCustomizationBest forlightweight-chartsLowDIY requiredHighHighQuote display, research panelsKLineChartLowRich built-insMediumMediumCharting tools, indicator analysisEChartsMediumBasicMediumHighGeneral charts, mixed dashboardsTradingViewHighCompleteHighMediumCommercial terminals, pro products</p><h3>Step 4: Full Example — A Global Index K-Line Panel</h3><p>With the format-conversion functions ready, selection becomes light. I ended up using lightweight-charts for the main panel: Python fetches and converts, the frontend renders.</p><p>Python side outputs the converted data to the frontend:</p><pre>import json<br>chart_data = to_chart_format(get_index_kline(code=&quot;SPX&quot;, ktype=8, limit=300))<br>print(json.dumps(chart_data))</pre><p>Frontend rendering with lightweight-charts (CDN example):</p><pre>&lt;script src=&quot;https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js&quot;&gt;&lt;/script&gt;<br>&lt;div id=&quot;chart&quot; style=&quot;width: 100%; height: 480px;&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;<br>  const chart = LightweightCharts.createChart(<br>    document.getElementById(&#39;chart&#39;),<br>    { layout: { textColor: &#39;#333&#39; }, grid: { vertLines: { color: &#39;#eee&#39; } } }<br>  );<br>  const series = chart.addCandlestickSeries();<br>  // data comes from the Python side as [[time, o, h, l, c], ...]<br>  series.setData(data);<br>&lt;/script&gt;</pre><p>300 daily bars of the S&amp;P 500 — lightweight-charts renders smoothly, zoom and pan feel natural, and the style is clean. The whole pipeline: <strong>REST fetch → Python normalization → frontend rendering</strong>, with no manual steps in between.</p><h3>Selection Advice: Match the Library to Your Use Case</h3><ul><li><strong>Market monitoring / data display pages</strong>: lightweight-charts — light, fast, looks good</li><li><strong>Charting tools with technical indicators</strong>: KLineChart — built-in indicators, friendly docs</li><li><strong>Mixed dashboards (K-line is just one widget)</strong>: ECharts — big ecosystem, consistent with other charts</li><li><strong>Commercial-grade trading terminals</strong>: TradingView charting library — but think through the licensing cost first</li></ul><h3>Pitfalls to Watch</h3><p><strong>Inconsistent timestamp units.</strong> The API returns milliseconds; lightweight-charts wants second-level UTCTimestamp. Feeding it raw milliseconds renders K-lines from 1970. Handle conversions in one place, don&#39;t divide inline at render time.</p><p><strong>Timezone.</strong> Global indices span multiple timezones; K-line timestamps are UTC. Watch out during localized frontend rendering so chart time stays aligned with quote time.</p><p><strong>Adjustment.</strong> Indices have no adjustment concept, but if this pipeline gets reused for individual stocks later (forward/backward adjusted prices), you must pick the right data caliber — adjustment conventions differ across data sources and are a classic trap.</p><p><strong>Incremental updates, not full redraws.</strong> In real-time push scenarios, resetting all data on every new bar makes the chart flicker; lightweight-charts’ update() touches only the last bar, which is far better for performance.</p><h3>Wrap-Up</h3><p>Along the data-to-rendering pipeline, what really decides the experience isn’t any single component — it’s <strong>data format normalization</strong>. Understand the API fields, write the conversion functions once, and picking any library just becomes a matter of swapping a render interface. For the data side, I keep the <a href="https://docs.itick.org/">official API docs</a> open while writing code to check fields, rather than guessing parameters from memory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb1edc5f119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Real-Time US Stock Data: Measure REST Polling vs WebSocket Push Latency Yourself]]></title>
            <link>https://medium.com/@wutainfofu/python-real-time-us-stock-data-measure-rest-polling-vs-websocket-push-latency-yourself-a7923b4d6570?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7923b4d6570</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[us-stock-market]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 03:36:12 GMT</pubDate>
            <atom:updated>2026-10-19T03:36:12.507Z</atom:updated>
            <content:encoded><![CDATA[<p>If you build US stock market tools or quantitative strategies, you’ll eventually face the same question: for real-time quotes, should you use HTTP polling or WebSocket push? Opinions online are all over the place — some say polling is amateur hour, others insist WebSocket is the only proper solution. Instead of listening to people argue, write code and measure it yourself: connect both approaches to the same data source, quantify latency, request volume, and resource usage with a consistent methodology, and the answer becomes obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fTiXCt-OdsU25865p5L9A.jpeg" /><figcaption>Real-Time US Stock Data</figcaption></figure><p>This article is a complete record of that measurement process: how to design the test, how to measure the REST side, how to measure the WebSocket side, how to compare the results, and finally which approach fits which scenario.</p><h3>Why Latency Deserves Serious Measurement</h3><p>Many people building US stock tools start with “a one or two second delay doesn’t matter.” That depends entirely on your strategy:</p><ul><li>Daily stock selection: grab data after the close, latency is irrelevant</li><li>Minute-level monitoring: one or two seconds is acceptable, but it must be stable</li><li>Order flow, event-driven, or spread strategies: latency determines whether the strategy works at all</li></ul><p>Also, latency isn’t only about “how fast” — it’s about <strong>jitter</strong>. An interface averaging 100 ms but occasionally jumping to 5 seconds hurts a strategy more than a steady 200 ms. So when measuring, don’t just record averages; capture the maximum and the distribution too.</p><h3>Test Design: Define the Metric Before You Write Code</h3><p>The most common failure in latency testing is <strong>inconsistent measurement definitions</strong>. If you define “latency” differently for REST and WebSocket, the comparison is meaningless.</p><p>I recommend one unified definition:</p><p>latency = time data arrives locally — the quote’s own generation timestamp</p><p>Compare this same difference for both approaches. The REST response includes the latest trade timestamp t (in milliseconds); the WebSocket quote message also carries t. When data arrives locally, record time.time() * 1000 and subtract t — that&#39;s the end-to-end latency for this data point.</p><p>Collect at least a few hundred samples and record three numbers: minimum, average, and P95. Averages hide jitter; P95 reveals how bad the worst case really is.</p><p>One fairness rule: <strong>subscribe to the same instruments on both sides, measured in the same session.</strong> US pre-market, regular, and after-hours push frequencies are completely different — comparing numbers across sessions is meaningless.</p><h3>Measuring REST Polling</h3><p>On the REST side, the approach is simple: loop over the quote endpoint, compute latency on every response, run N rounds, and store the sequence.</p><pre>import time<br>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br>def measure_rest_polling(symbol=&quot;AAPL&quot;, region=&quot;US&quot;, rounds=200):<br>    latencies = []<br>    for _ in range(rounds):<br>        # record time before sending the request (ms)<br>        t0 = time.time() * 1000<br>        resp = requests.get(<br>            f&quot;{API_BASE}/stock/quote&quot;,<br>            headers=headers,<br>            params={&quot;region&quot;: region, &quot;code&quot;: symbol}<br>        )<br>        data = resp.json()[&quot;data&quot;]<br>        # quote timestamp t is in milliseconds<br>        latency = t0 - data[&quot;t&quot;]<br>        latencies.append(latency)<br>        time.sleep(1)  # simulate a real polling interval<br>    return latencies<br>lats = measure_rest_polling()<br>lats.sort()<br>n = len(lats)<br>print(f&quot;samples: {n}&quot;)<br>print(f&quot;min: {lats[0]:.0f}ms, avg: {sum(lats)/n:.0f}ms, P95: {lats[int(n*0.95)]:.0f}ms&quot;)</pre><p>One detail worth noting: t0 is recorded <em>before</em> the request is sent, but the request has a full network round trip before the response returns. Strictly speaking, the price REST returns is the <strong>last trade at the time of the response</strong> — by the time you process it, the market may have moved on. So REST&#39;s &quot;effective latency&quot; is inherently larger than WebSocket&#39;s: it includes an entire request-response cycle, even at one request per second.</p><p>Polling frequency also has a ceiling. One request per second means 3,600 requests per hour; leave it running all day and the volume becomes very significant. For individual developers, this is both a cost problem and a rate-limit problem.</p><h3>Measuring WebSocket Push</h3><p>On the WebSocket side, data is pushed by the server, so the measurement logic flips: for every quote message received, compute latency from the message’s t and the local receive time.</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>latencies = []<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;AAPL$US&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        now = time.time() * 1000<br>        latency = now - data[&quot;t&quot;]<br>        latencies.append(latency)<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br>ws = websocket.WebSocketApp(<br>    WS_URL,<br>    header=[f&quot;token: {TOKEN}&quot;],<br>    on_message=on_message<br>)<br>ws.run_forever()</pre><p>Let it run until a few hundred messages arrive, then analyze latencies offline:</p><pre>lats = sorted(latencies)<br>n = len(lats)<br>print(f&quot;samples: {n}&quot;)<br>print(f&quot;min: {lats[0]:.0f}ms, avg: {sum(lats)/n:.0f}ms, P95: {lats[int(n*0.95)]:.0f}ms&quot;)</pre><p>WebSocket latency has two characteristics. First, <strong>push frequency follows the market</strong> — more messages when order flow is active, fewer when it’s quiet, unlike polling’s fixed rhythm. Second, <strong>after connection, it occupies only one long-lived socket</strong>, and request volume stays constant no matter how many instruments you subscribe to. That’s the most fundamental difference from polling.</p><h3>Comparison Dimensions: Latency Is Not the Only One</h3><p>Once both sides are measured, you’ll have two datasets. But choosing an approach can’t be based on latency alone. I recommend comparing across four dimensions:</p><p>DimensionREST PollingWebSocket PushLatencyExtra request-response cycle, higher end-to-endServer-pushed, lower and steadierRequest volumeScales with polling frequency, costly over long runsConstant after connect, independent of instrument countResource usageNew connection per request, HTTP overheadOne long-lived connection, needs heartbeat maintenanceComplexitySimple, one requests loopAuth, heartbeat, reconnect handling required</p><p>The conclusion is clear: <strong>low-frequency, short-lived, script-style scenarios use REST; high-frequency, long-running, multi-instrument scenarios use WebSocket.</strong> Daily tasks, one-off snapshots, and test scripts are fine with REST; intraday monitoring, event-driven logic, and cross-instrument real-time dashboards should go through WebSocket.</p><h3>Pitfalls Confirmed Along the Way</h3><p>While running the measurements, I re-confirmed a few classic traps. Writing them down so you don’t have to rediscover them:</p><p><strong>Auth sequencing.</strong> A WebSocket connection being established doesn’t mean you can subscribe. Wait for resAc:&quot;auth&quot; with code:1 before sending subscribe. I&#39;ve seen code that subscribes immediately after connect — zero data received, and the program reports no error.</p><p><strong>Heartbeat is mandatory.</strong> The docs require a heartbeat every 30 seconds; without it the server drops the long connection. When your measurement script runs for hours, a missed heartbeat silently kills the second half of your dataset.</p><p><strong>Timestamp units.</strong> Quote and K-line timestamps are in milliseconds. Subtracting time.time() (seconds) gives a huge negative number. Standardize on milliseconds, or write a conversion utility — don&#39;t divide inline in business code.</p><p><strong>Check trading status.</strong> US pre-market, regular, and after-hours quote characteristics differ greatly; the ts field marks trading status. Run latency tests during normal trading hours, otherwise your distribution is meaningless.</p><h3>Wrap-Up</h3><p>“Is polling or push better?” The answer isn’t online — it’s in your measurement script. Define the metric, run both sides, compare across four dimensions, and the right choice for your scenario becomes obvious. For most individual developers building US stock tools, the final setup usually is: REST for snapshots and historical data, WebSocket for intraday real-time monitoring — each doing its own job.</p><p>For specific parameters and response field details, I keep the <a href="https://docs.itick.org/">official API docs</a> open while writing code — way more reliable than guessing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7923b4d6570" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Code Review of a Gold Futures Quote Script: The Traps That Silently Kill Your WebSocket]]></title>
            <link>https://medium.com/@wutainfofu/a-code-review-of-a-gold-futures-quote-script-the-traps-that-silently-kill-your-websocket-476cff114c50?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/476cff114c50</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[gold]]></category>
            <category><![CDATA[future]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 11:35:32 GMT</pubDate>
            <atom:updated>2026-10-15T11:35:32.487Z</atom:updated>
            <content:encoded><![CDATA[<p>If you build precious metals market monitoring or gold futures quantitative strategies, you’ll eventually walk the same path: writing Python data collectors that connect to a real-time market data API and pull international gold prices and COMEX gold futures data into your own system. The direction itself has no real barrier — the barrier lives in the integration details. A single WebSocket connection’s auth sequencing, heartbeat mechanism, and timestamp handling can silently kill your data stream at 3 AM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_3SkRWaql3AY1H5GsS2Uw.jpeg" /><figcaption>Gold Futures Quote Script</figcaption></figure><p>A friend recently sent me a gold futures quote-collection script he’d written, saying “sometimes the data just stops updating, with no error at all.” I went through the code line by line — there’s more than one problem. This article isn’t a tutorial; it’s a real code review. Here’s the original code, the issues I found, and the fixes written against the official docs. If you’re writing futures market-data collectors, real-time quote pipelines, or precious metals data infrastructure, you’ll probably recognize some of these.</p><h3>The Original Code</h3><pre>import json<br>import time<br>import requests<br>import websocket<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br>def get_quote():<br>    resp = requests.get(<br>        f&quot;{API_BASE}/future/quote&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: &quot;US&quot;, &quot;code&quot;: &quot;GC&quot;}<br>    )<br>    return resp.json()[&quot;data&quot;]<br>def on_message(ws, message):<br>    payload = json.loads(message)<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        ts = data[&quot;t&quot;] // 1000<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;last&#39;]} ({data[&#39;chp&#39;]}%) time={ts}&quot;)<br>def on_open(ws):<br>    # Subscribe immediately after connection<br>    ws.send(json.dumps({<br>        &quot;ac&quot;: &quot;subscribe&quot;,<br>        &quot;params&quot;: &quot;GC$US&quot;,<br>        &quot;types&quot;: &quot;quote&quot;<br>    }))<br>ws = websocket.WebSocketApp(<br>    &quot;wss://api.itick.org/future&quot;,<br>    header=[f&quot;token: {TOKEN}&quot;],<br>    on_message=on_message,<br>    on_open=on_open<br>)<br>ws.run_forever()</pre><p>This code runs. At first glance nothing looks wrong. But going through it carefully, I found six issues — three of which explain the “silently disappearing data.”</p><h3>Review Findings: Six Issues</h3><h3>Issue 1: Subscribing Before Authentication Completes</h3><p>on_open firing only means the TCP and WebSocket handshake succeeded — <strong>it does not mean the server has authenticated your token</strong>. The docs state clearly: wait for a resAc:&quot;auth&quot; message with code:1 before sending subscribe. This code subscribes immediately, when the server may still be validating the token. The subscription gets rejected without an error — a classic &quot;no data but the program keeps running&quot; cause.</p><p>This trap is extremely common with real-time WebSocket streaming APIs. REST is request-response: when something is wrong, you get an error code back. WebSocket is a long-lived connection — many integration problems surface no error at all, and you can only detect them by watching message types. When integrating a real-time quote API, <strong>treat “authenticated” as an explicit state transition</strong>, never assume a successful connect means you’re ready to use.</p><p>Fix: add an authenticated state flag; only subscribe after auth succeeds.</p><pre>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;GC$US&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return</pre><h3>Issue 2: No Heartbeat, Connection Killed by the Server</h3><p>The futures WebSocket requires a <strong>heartbeat every 30 seconds</strong> ({&quot;ac&quot;:&quot;ping&quot;,&quot;params&quot;:&quot;timestamp&quot;}). If you don&#39;t consume messages or send heartbeats, the server will drop the connection. This code has zero heartbeat logic — after a few hours the server reaps the connection, and the program neither exits nor reconnects. It just looks like &quot;the data vanished.&quot;</p><p>Gold futures differ from stocks mainly in trading hours: roughly 23 hours a day, with only about a one-hour maintenance break. In this scenario, long-lived connections are the norm, so heartbeat isn’t optional — it’s mandatory. Many people building precious metals monitoring systems skip the heartbeat initially and don’t realize the data stopped until an hour or two later.</p><p>Fix: start a heartbeat thread after auth succeeds.</p><pre>import threading<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;ping&quot;,<br>            &quot;params&quot;: str(int(time.time() * 1000))<br>        }))<br># Start inside the auth-success branch<br>threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()</pre><h3>Issue 3: Timestamp Treated as Seconds</h3><p>data[&quot;t&quot;] is a <strong>millisecond timestamp</strong>. The code does // 1000 to convert to seconds, then prints it raw without timezone conversion. The US gold session maps to Beijing evening hours; showing raw UTC timestamps makes every &quot;what time did the alert fire&quot; answer wrong, and breaks trading-session checks entirely.</p><p>Timestamp issues get worse when you handle cross-market, cross-instrument data. Gold, silver, platinum, and palladium trade across the Asian, European, and US sessions; a monitoring system often processes several markets at once. Time baselines must be unified and conversions explicit. <strong>Milliseconds-to-seconds, UTC-to-local, and DST handling</strong> should be isolated into utility functions, not scattered as inline divisions in business code.</p><p>Fix: convert explicitly to local time.</p><pre>from datetime import datetime<br>ts = data[&quot;t&quot;] / 1000<br>local_time = datetime.fromtimestamp(ts).strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({data[&#39;chp&#39;]}%) time={local_time}&quot;)</pre><h3>Issue 4: Wrong Field Name</h3><p>The code reads data[&#39;last&#39;], but the actual quote field is ld (latest price). The result: the program runs, the connection is alive, data keeps flowing — but you never get the correct price. This is the most dangerous kind of bug because nothing reports it.</p><p>Field naming varies wildly across data sources. Some APIs use last, others price or close; &quot;percent change&quot; might be chp, change_pct, or percent_change. <strong>The first step of integrating any financial data API is reading the response field docs cover to cover</strong> and writing a field-mapping table before touching code. For futures quote APIs, the quote fields are s/ld/chp/o/h/l/v/tu/ts; K-line fields are t/o/h/l/c/v/tu. Memorizing these saves hours of debugging.</p><p>Fix: check field names against the docs — quote fields are s/ld/chp/o/h/l/v/tu/ts; K-line fields are t/o/h/l/c/v/tu.</p><h3>Issue 5: No Reconnect Logic</h3><p>When run_forever() exits after a connection error, the program just ends. Gold futures trade 23 hours a day; a disconnect at 3 AM with nobody watching means the data pipeline is dead until someone restarts it. Production code needs automatic reconnection.</p><p>One subtle point in reconnect logic: <strong>reset </strong><strong>authenticated after reconnecting</strong>. A new connection requires fresh authentication; if the flag stays True from the previous session, subscribe will fire before auth completes — exactly Issue 1 again. That&#39;s why well-built real-time market data clients place this flag outside the connection loop and reset it on every connect.</p><p>Fix: wrap in a loop; on disconnect, reset authenticated (a new connection needs fresh auth) and retry.</p><pre>while True:<br>    authenticated = False<br>    ws = websocket.WebSocketApp(<br>        &quot;wss://api.itick.org/future&quot;,<br>        header=[f&quot;token: {TOKEN}&quot;],<br>        on_message=on_message<br>    )<br>    try:<br>        ws.run_forever()<br>    except Exception:<br>        pass<br>    print(&quot;Connection lost, reconnecting in 5s...&quot;)<br>    time.sleep(5)</pre><h3>Issue 6: Treating Market Closure as an API Outage</h3><p>COMEX gold closes for about one hour daily, and there’s no trade data in that window. Without any trading-status check, the first instinct when data goes quiet is “the API is broken.” Quotes actually include a ts field for trading status — check the status before trusting the data.</p><p>Precious metals trading rules differ from stocks: stocks have fixed sessions with long closures and everyone expects them; near-24-hour products like gold have short closure windows that get overlooked. Add the ts trading-status check to your monitor, and distinguish &quot;maintenance window&quot; from &quot;real outage&quot; — that alone prevents many 3 AM false alarms.</p><p>Fix:</p><pre>if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>    if data.get(&quot;ts&quot;) == 0:<br>        print(&quot;Market closed, skipping&quot;)<br>        return<br>    # process quote normally</pre><h3>Review Checklist at a Glance</h3><p>Here’s the six issues condensed into a self-check table to run after writing your code:</p><p>#Check itemFailure symptomCorrect approach1Auth sequencingNo data but program runsWait for resAc:&quot;auth&quot; + code:1 before subscribe2HeartbeatConnection reaped after hoursSend {&quot;ac&quot;:&quot;ping&quot;,&quot;params&quot;:&quot;timestamp&quot;} every 30s3Timestamp unitWrong times, broken session checksms-to-seconds + explicit local timezone4Field namesWrong prices, zero errorsCheck docs: quote ld, K-line c5ReconnectProgram silently ends after 3 AM dropLoop + reset auth flag6Trading statusClosures mistaken for outagesCheck ts before processing</p><p>This table applies to real-time quote integration for other products too — stocks, forex, indices, futures share the same integration framework; the differences are only in code formats and trading sessions.</p><h3>The Fixed, Complete Code</h3><pre>import json<br>import threading<br>import time<br>from datetime import datetime<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/future&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br><br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;GC$US&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        if data.get(&quot;ts&quot;) == 0:<br>            return  # market closed<br>        ts = datetime.fromtimestamp(data[&quot;t&quot;] / 1000).strftime(&quot;%H:%M:%S&quot;)<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({data[&#39;chp&#39;]}%) {ts}&quot;)<br><br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br><br>while True:<br>    authenticated = False<br>    ws = websocket.WebSocketApp(<br>        WS_URL,<br>        header=[f&quot;token: {TOKEN}&quot;],<br>        on_message=on_message<br>    )<br>    try:<br>        ws.run_forever()<br>    except Exception:<br>        pass<br>    print(&quot;Connection lost, reconnecting in 5s...&quot;)<br>    time.sleep(5)</pre><h3>Where to Take This Code Next</h3><p>Reviewing is only the first step. Dropping this code into a real gold market monitoring system usually means adding three more pieces:</p><p><strong>Multi-instrument expansion.</strong> Watching only GC is rarely enough — silver, platinum, and palladium usually need to be tracked together. The WebSocket subscription supports comma-separated instruments (GC$US,SI$US), so one connection covers your whole precious metals portfolio without opening multiple sockets. On the REST side, the batch quote endpoint /future/quotes takes codes (plural) with comma-separated product codes — one request returns snapshots for many instruments, far more efficient than looping over single-quote calls.</p><p><strong>Historical K-line coverage.</strong> Monitoring needs real-time quotes; backtesting and moving-average math need historical data. The REST /future/kline endpoint uses kType for period (1=1min, 2=5min, 5=1hour, 8=daily, 9=weekly, 10=monthly) and limit for bar count. Pull daily candles into a local database, incrementally update after close, and monitoring and backtesting share one data source.</p><p><strong>Alert triggering.</strong> Once real-time quotes arrive, whatever logic you attach is easy: moving-average breakouts, price-range monitoring, relative-strength calculations. With the data layer solved, you can finally focus on strategy.</p><h3>Review Takeaways</h3><p>These problems are very representative: <strong>most “data mysteriously disappeared” incidents aren’t API outages — they’re small integration issues.</strong> Auth sequencing, heartbeat, field names, timezone, reconnection. Each issue looks trivial on its own, but stacked together you get “program running, data dropping, you hunting for the cause.”</p><p>When writing market-data collectors, I now run a five-point self-check when I finish: did I wait for auth? Is the heartbeat running? Do field names match the docs? Are timestamps converted? Will it reconnect? Once those five are done, most integration traps are avoided.</p><p>For field and parameter details, I keep the <a href="https://docs.itick.org/">official API docs</a> open while writing code — way more reliable than trying to remember.</p><p>GitHub：<a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=476cff114c50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global Stock Market API Comparison: Which Real-Time Data Feed Should Individual Quants Choose?]]></title>
            <link>https://medium.com/@wutainfofu/global-stock-market-api-comparison-which-real-time-data-feed-should-individual-quants-choose-0c7234d30fa5?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c7234d30fa5</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 12:02:06 GMT</pubDate>
            <atom:updated>2026-10-14T12:02:06.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Halfway through building a cross-market quant strategy, you realize you’re using one API for US stocks, another for A-shares, and yet another for HK stocks. Free interfaces that worked yesterday change their fields today. So-called “real-time” quotes arrive with a 15-second delay. <strong>When building global stock strategies, individual developers often underestimate how much the data infrastructure limits what your strategy can actually do.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMDXTMMK3IvAGiRfNOfeHQ.jpeg" /><figcaption>Stock Market API</figcaption></figure><p>This article doesn’t just list APIs. It answers three questions: what to use for historical backtesting, what to use for intraday quotes, and how to build a unified data layer across markets.</p><h3>Start with the conclusion: don’t rely on one data source to do everything</h3><p>For individual developers working on global stocks, the most reliable approach isn’t finding one magic API. It’s building a layered data architecture:</p><p>Data layerPrimary useWhat to useHistorical researchDaily bars, fundamentals, index constituents, factor researchLocal database + free historical interfacesIntraday market dataReal-time snapshots, K-lines, cross-market comparisonUnified-format real-time quote APITrade verificationPositions, orders, fillsBroker trading API</p><p><strong>Historical data needs completeness and reproducibility. Real-time data needs low latency and stability. Trade data must come from your broker.</strong></p><p>If you’re only doing daily stock selection, there’s no point paying for millisecond data. But if your strategy depends on cross-market price spreads or order flow, scraping free web data might break your strategy.</p><h3>Comparing common global stock data feeds</h3><p>Data sourceMarkets coveredReal-time capabilityAPI stabilityCostBest forYahoo FinanceGlobal major marketsWeak (noticeable delay)Web-based, occasional rate limitsFreeLearning, prototyping, low-frequency analysisAlpha VantageUS-focusedModerateWell-documented, but rate-limitedFree tier limitedUS daily research, beginner projectsTushare ProA-share focusedModerateWell-structuredCredit-based permissionsA-share factor research, fundamentalsAKShareA-share + some overseasModerateWeb-scraping dependentFreeMulti-market exploration, data scraping<a href="https://itick.org/">iTick</a>US / CN / HK / JP / INStrongProper REST + WebSocketToken-basedCross-market strategies, real-time monitoring, multi-market parallel</p><p>There’s no universal ranking. Whether a data source works depends on your strategy frequency, market coverage, budget, and fault tolerance.</p><p><strong>Arguing about the “best” data source when you’re doing daily stock picks vs. cross-market real-time arbitrage is like comparing bike tires to race car tires — different scenarios entirely.</strong></p><h3>Free data sources: great for research, not for production</h3><p>Yahoo Finance and AKShare’s biggest advantage is broad coverage and easy onboarding. Stocks, funds, and indices are all accessible from one Python package — great for validating ideas quickly.</p><p>Their downside is equally obvious: many interfaces wrap public web pages. If the upstream page structure, parameters, or anti-scraping policy changes, the interface breaks. Yahoo Finance’s free tier frequently rate-limits you under high call volume; AKShare’s fields depend on HTML parsing, so a page redesign breaks everything.</p><p>Good use cases for free sources:</p><ul><li>Quickly validating whether a factor has research value</li><li>Scraping low-frequency public data for one-off analysis</li><li>Learning different markets’ code formats and trading rules</li></ul><p>Don’t put a single free interface into an unattended production pipeline. If you must use one, add local caching, field validation, alerting, and a backup source.</p><p><strong>Free data isn’t actually free. Spending three days fixing a broken field often costs more than a year of a paid interface.</strong></p><h3>Unified real-time APIs: the engineering solution for cross-market strategies</h3><p>The hardest part of cross-market strategies isn’t getting data from any single market — it’s maintaining five different APIs, five different code formats, and five different authentication tokens. US stocks use one SDK, A-shares another, HK stocks require yet another token. Timestamp formats differ, field names differ, and when something breaks you don’t know which side to debug.</p><p>Unified real-time APIs solve this with one consistent interface format and one authentication token across multiple markets. Here’s what that looks like in practice:</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Same function, different regions = different markets<br>def get_quote(region, code):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: region, &quot;code&quot;: code}<br>    )<br>    return resp.json()[&quot;data&quot;]<br><br># US Apple<br>us = get_quote(&quot;US&quot;, &quot;AAPL&quot;)<br># A-share Kweichow Moutai<br>cn = get_quote(&quot;CN&quot;, &quot;600519&quot;)<br># HK Tencent<br>hk = get_quote(&quot;HK&quot;, &quot;00700&quot;)<br># Japan Toyota<br>jp = get_quote(&quot;JP&quot;, &quot;7203&quot;)<br># India Reliance<br>in_ = get_quote(&quot;IN&quot;, &quot;RELIANCE&quot;)<br>print(f&quot;US AAPL: {us[&#39;ld&#39;]} ({us[&#39;chp&#39;]}%)&quot;)<br>print(f&quot;CN 600519: {cn[&#39;ld&#39;]} ({cn[&#39;chp&#39;]}%)&quot;)<br>print(f&quot;HK 00700: {hk[&#39;ld&#39;]} ({hk[&#39;chp&#39;]}%)&quot;)</pre><p>The same get_quote function works across five markets by changing one region parameter. For cross-market strategy development, this engineering value is massive — you don&#39;t maintain five codebases, and when something breaks you debug one interface.</p><p>WebSocket real-time push follows the same unified pattern:</p><pre>import json<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    <br>    # Wait for auth success before subscribing<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # Subscribe to US and HK stocks on the same connection<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;AAPL$US,00700$HK&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return<br>    <br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({data[&#39;chp&#39;]}%)&quot;)<br>ws = websocket.WebSocketApp(WS_URL, header=[f&quot;token: {TOKEN}&quot;], on_message=on_message)<br>ws.run_forever()</pre><p>One WebSocket connection subscribes to both US and HK stocks simultaneously — no need to maintain two connections. This unified design is a huge time-saver for cross-market real-time monitoring.</p><p><strong>A few pitfalls to watch out for:</strong></p><ul><li>Code formats differ by market: AAPL (US), 600519 (CN), 00700 (HK), 7203 (JP)</li><li>India uses a three-parameter subscription format: RELIANCE$NSE$IN</li><li>All timestamps are in milliseconds — don’t treat them as seconds</li><li>Trading hours differ across markets; US markets open at night in Asia time, so watch the overlap window when building cross-market monitors</li></ul><h3>Which strategy should use which data source?</h3><h3>Single-market daily stock selection and backtesting</h3><p>Use free historical interfaces plus a local database (DuckDB, Parquet, or PostgreSQL). Incrementally update after market close — no need to poll real-time interfaces throughout the day.</p><p>If budget is tight, build your main library on free sources and supplement with real-time API data for intraday.</p><h3>Multi-market comparison and cross-market monitoring</h3><p>This is where a unified real-time API earns its keep. Use free sources for historical data, but use one stable, consistently formatted interface for intraday monitoring. Otherwise, you’re spending more time maintaining US vs. A-share vs. HK SDKs than actually building strategies.</p><h3>Cross-market spread strategies (AH premium, US-China arbitrage, etc.)</h3><p>These strategies need real-time prices from both markets simultaneously. Timestamp consistency matters — if you’re using two different APIs, the timestamps won’t align and your spread calculation is unreliable. Using one unified service means both data points come from the same infrastructure, so timestamp consistency is much better.</p><h3>Preparing for live trading</h3><p>Production environments should never rely on a single data source. The primary source drives real-time decisions, the backup source monitors for failures, and broker fills calibrate your actual positions. If all three disagree, stop trading — don’t guess which number is right.</p><h3>Summary of recommendations</h3><p>Near-zero budget, still learning: use free sources, build your research pipeline and local data warehouse first.</p><p>Single-market daily factors and fundamentals: use a dedicated historical interface for your research database, supplement with free sources.</p><p>Cross-market comparison, AH premium, multi-market real-time monitoring: test a unified-format real-time API, supplement long samples with historical data.</p><p><strong>The ultimate data source choice for individual quants isn’t the most expensive or the one with the most endpoints. It’s the one that matches your strategy frequency, can be verified, and gives you an exit when something fails.</strong></p><p>Data determines whether your backtest is trustworthy. Risk management determines whether you survive in live trading. The strategy code is often the easiest part.</p><p><em>For specific parameters and response field details, I keep the </em><a href="https://docs.itick.org/"><em>official API docs</em></a><em> open while writing code — saves a lot of trial and error.</em></p><p>GitHub：<a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c7234d30fa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Hong Kong Stock API Guide: Hang Seng Market Data and AH Premium Monitoring]]></title>
            <link>https://medium.com/@wutainfofu/python-hong-kong-stock-api-guide-hang-seng-market-data-and-ah-premium-monitoring-349919496f97?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/349919496f97</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 11:37:10 GMT</pubDate>
            <atom:updated>2026-10-13T11:37:10.886Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a cross-market quantitative trading system or monitoring Stock Connect strategies, connecting to Hong Kong stock data is essential. HK stocks have a unique relationship with A-shares — the same company often lists in both markets, and the prices can diverge significantly. This is the AH-share premium, a classic arbitrage opportunity and a great technical use case for cross-market data APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWuUdngo4aP4auZYQKswTg.jpeg" /><figcaption>Hong Kong Stock API Guide</figcaption></figure><p>This guide walks through connecting to HK stock real-time quotes with Python, using the AH premium monitoring scenario as a practical example.</p><h3>Why HK Stock Data Matters</h3><p>When I first started building A-share quant strategies, domestic data APIs were enough. But when I wanted to build an AH-share arbitrage strategy, I realized I needed real-time prices from both markets. The problem: using two different APIs for each market meant mismatched timestamps and inconsistent latency — the calculated spread was unreliable.</p><p>After trying a few options, I settled on a unified data source that covers both A-shares and HK stocks in one API — no need to maintain two separate codebases, and the timestamps from both markets are consistent enough for spread monitoring. When building cross-market monitors, having <a href="https://itick.org/">one key that works across multiple markets</a> makes a real difference.</p><h3>HK Market Basics</h3><p>Let’s get the fundamentals straight first, so you know what each field means in the API response.</p><p><strong>Trading hours</strong>: 9:30 AM — 12:00 PM and 1:00 PM — 4:00 PM HKT. Half an hour longer than A-shares, with a 1-hour lunch break.</p><p><strong>Code format</strong>: HK stock codes are 5-digit numbers, e.g., 00700 for Tencent, 09988 for Alibaba, 03690 for Meituan. Different from A-shares’ 6-digit codes.</p><p><strong>Trading currency</strong>: Hong Kong Dollars (HKD). When calculating AH premium, you need to convert to CNY.</p><p><strong>Region code</strong>: Pass region=HK for HK stocks, region=CN for A-shares.</p><h3>REST API for HK Stock Quotes</h3><p>Start with REST to confirm the data format.</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Get HK stock real-time quote<br>def get_hk_stock_quote(code):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;HK&quot;,<br>            &quot;code&quot;: code<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br><br># Fetch a few HK blue chips<br>stocks = [&quot;00700&quot;, &quot;09988&quot;, &quot;03690&quot;]<br>for code in stocks:<br>    q = get_hk_stock_quote(code)<br>    sign = &quot;+&quot; if q[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;{code}: {q[&#39;ld&#39;]} ({sign}{q[&#39;chp&#39;]}%)&quot;)</pre><p>Response fields are consistent across markets: ld latest price, chp percent change, o/h/l open/high/low, v volume. That&#39;s enough for a dashboard.</p><p><strong>Note</strong>: HK codes are 5-digit numbers with leading zeros. Pass them as strings (e.g., &quot;00700&quot;). I once passed &quot;700&quot; and got an empty response — HK codes must be exactly 5 digits.</p><h3>WebSocket for Real-Time HK Push</h3><p>For intraday monitoring, polling REST is wasteful. WebSocket real-time push is the way to go.</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    # Wait for auth success before subscribing<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # HK subscription format: code$region<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;00700$HK,09988$HK&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)</pre><p>HK subscriptions use two parameters (00700$HK), same as US stocks and A-shares — not the three-parameter format used for Indian markets.</p><h3>AH Premium Monitoring: The Practical Use Case</h3><p>This is the most technically interesting application of HK stock data — the same company lists in both A-share and HK markets, and the prices often differ.</p><p>Take China Merchants Bank: A-share code 600036, HK code 03968. The prices should theoretically be similar, but in practice the premium can range from 5% to 30%. This spread is what quantitative traders watch for arbitrage opportunities.</p><pre># AH premium monitoring<br># CMB: A-share 600036, HK 03968<br># Ping An: A-share 601318, HK 02318<br>def get_ah_premium(a_code, h_code, hkd_cny_rate=0.92):<br>    &quot;&quot;&quot;<br>    Calculate AH-share premium<br>    a_code: A-share code<br>    h_code: HK stock code<br>    hkd_cny_rate: HKD to CNY exchange rate<br>    &quot;&quot;&quot;<br>    # Get A-share price<br>    a_resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: &quot;CN&quot;, &quot;code&quot;: a_code}<br>    ).json()[&quot;data&quot;]<br>    <br>    # Get HK stock price<br>    h_resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={&quot;region&quot;: &quot;HK&quot;, &quot;code&quot;: h_code}<br>    ).json()[&quot;data&quot;]<br>    <br>    # Convert HK price to CNY<br>    h_price_cny = h_resp[&quot;ld&quot;] * hkd_cny_rate<br>    <br>    # Calculate premium<br>    premium = (a_resp[&quot;ld&quot;] - h_price_cny) / h_price_cny * 100<br>    <br>    return {<br>        &quot;a_code&quot;: a_code,<br>        &quot;a_price&quot;: a_resp[&quot;ld&quot;],<br>        &quot;h_code&quot;: h_code,<br>        &quot;h_price_hkd&quot;: h_resp[&quot;ld&quot;],<br>        &quot;h_price_cny&quot;: round(h_price_cny, 2),<br>        &quot;premium_pct&quot;: round(premium, 2)<br>    }<br><br># Monitor a few AH pairs<br>ah_pairs = [<br>    (&quot;600036&quot;, &quot;03968&quot;),  # China Merchants Bank<br>    (&quot;601318&quot;, &quot;02318&quot;),  # Ping An Insurance<br>    (&quot;600900&quot;, &quot;00900&quot;),  # China Yangtze Power<br>]<br>for a_code, h_code in ah_pairs:<br>    result = get_ah_premium(a_code, h_code)<br>    print(f&quot;{result[&#39;a_code&#39;]} / {result[&#39;h_code&#39;]}: &quot;<br>          f&quot;A-share {result[&#39;a_price&#39;]} CNY, HK {result[&#39;h_price_hkd&#39;]} HKD &quot;<br>          f&quot;(≈{result[&#39;h_price_cny&#39;]} CNY), &quot;<br>          f&quot;Premium {result[&#39;premium_pct&#39;]}%&quot;)</pre><p>This script shows you the AH premium for each pair. When the premium is unusually high or low, that’s the arbitrage signal.</p><p><strong>Note</strong>: The exchange rate fluctuates, so update it periodically in production — don’t hardcode it.</p><h3>K-Line Data</h3><p>For technical analysis or backtesting, K-line data works the same way as other markets, just with region=HK.</p><pre>def get_hk_kline(code, k_type=8, limit=100):<br>    &quot;&quot;&quot;<br>    k_type: 1=1min, 2=5min, 5=1hour, 8=daily, 9=weekly, 10=monthly<br>    &quot;&quot;&quot;<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/kline&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;HK&quot;,<br>            &quot;code&quot;: code,<br>            &quot;kType&quot;: k_type,<br>            &quot;limit&quot;: limit<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br># Pull the last 100 daily candles for Tencent<br>daily = get_hk_kline(&quot;00700&quot;, k_type=8, limit=100)<br>closes = [bar[&quot;c&quot;] for bar in daily]<br># 20-day moving average<br>ma20 = sum(closes[-20:]) / 20<br>print(f&quot;00700 latest close: {closes[-1]}, 20-day MA: {ma20:.2f}&quot;)<br></pre><p>K-line responses use standard OHLCV: t timestamp, o/h/l/c open/high/low/close, v volume.</p><h3>HK-Specific Pitfalls</h3><p><strong>5-digit codes with leading zeros.</strong> HK codes are 5 digits (00700, 09988), different from A-shares’ 6 digits (600519). I once passed “700” and got nothing — HK codes need leading zeros to make 5 digits.</p><p><strong>Trading hours are 30 minutes longer than A-shares.</strong> HK trades 9:30–12:00 and 13:00–16:00. When building cross-market monitors, be aware of the overlapping time window.</p><p><strong>HKD currency.</strong> HK prices are in Hong Kong Dollars. For AH premium calculations, convert to CNY. The exchange rate is dynamic — don’t hardcode it.</p><p><strong>Stock Connect coverage is limited.</strong> Not all HK stocks are available through Stock Connect. When building strategies, check the eligible universe.</p><p><strong>Timestamps are in milliseconds.</strong> All timestamps are in milliseconds. Treating them as seconds gives you a date far in the future — remember to divide by 1000.</p><h3>Complete Script: HK Market + AH Premium Monitor</h3><p>Putting it all together:</p><pre>import json, time, threading, requests, websocket<br>API_BASE = &quot;https://api.itick.org&quot;<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># HK watchlist<br>watchlist = [&quot;00700&quot;, &quot;09988&quot;, &quot;03690&quot;]<br># Initial snapshot<br>print(&quot;=== HK Snapshot ===&quot;)<br>for code in watchlist:<br>    r = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;HK&quot;, &quot;code&quot;: code}).json()[&quot;data&quot;]<br>    sign = &quot;+&quot; if r[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;  {code}: {r[&#39;ld&#39;]} ({sign}{r[&#39;chp&#39;]}%)&quot;)<br># AH premium snapshot<br>print(&quot;\n=== AH Premium ===&quot;)<br>ah_pairs = [(&quot;600036&quot;, &quot;03968&quot;), (&quot;601318&quot;, &quot;02318&quot;)]<br>for a_code, h_code in ah_pairs:<br>    a = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;CN&quot;, &quot;code&quot;: a_code}).json()[&quot;data&quot;]<br>    h = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;HK&quot;, &quot;code&quot;: h_code}).json()[&quot;data&quot;]<br>    h_cny = h[&quot;ld&quot;] * 0.92<br>    premium = (a[&quot;ld&quot;] - h_cny) / h_cny * 100<br>    print(f&quot;  {a_code}/{h_code}: A-share {a[&#39;ld&#39;]} CNY, HK {h[&#39;ld&#39;]} HKD &quot;<br>          f&quot;(≈{h_cny:.2f} CNY), Premium {premium:.1f}%&quot;)<br># WebSocket real-time HK push<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        params = &quot;,&quot;.join(f&quot;{c}$HK&quot; for c in watchlist)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: params,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;[live] {data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br>ws = websocket.WebSocketApp(WS_URL, header=[f&quot;token: {TOKEN}&quot;], on_message=on_message)<br>ws.run_forever()</pre><p>This script gives you an opening snapshot of HK stocks and AH premium ratios, plus live HK price updates through the trading day.</p><h3>Wrap-Up</h3><p>The technical architecture for HK stock data is the same as A-shares or US stocks — REST for snapshots and historical data, WebSocket for real-time push. The main differences are the code format (5 digits with leading zeros), the trading currency (HKD), and the longer trading hours. The most technically interesting use case is AH premium monitoring — pulling prices from both markets and calculating the cross-market spread.</p><p>For HK quant strategies or AH-share arbitrage, this workflow is ready to go. I usually keep the <a href="https://docs.itick.org/">official API docs</a> open while writing code to double-check parameter names and response fields — saves a lot of trial and error.</p><p>GitHub：<a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349919496f97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python A-Share Real-Time Market Data API: Shanghai/Shenzhen Stock Data and WebSocket Push Guide]]></title>
            <link>https://medium.com/@wutainfofu/python-a-share-real-time-market-data-api-shanghai-shenzhen-stock-data-and-websocket-push-guide-ea9ab4ca73ef?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9ab4ca73ef</guid>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 12:27:05 GMT</pubDate>
            <atom:updated>2026-10-12T12:27:05.887Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a quantitative trading system or market data dashboard for the Chinese A-share market, you’ll quickly realize that A-share trading rules are quite different from US or Hong Kong markets — daily price limits, T+1 settlement, call auctions, and the lunch break all shape how the data looks. This guide walks through connecting to A-share real-time quotes with Python, and how those special rules map to the API response fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qP_fjJMLC8j-3P575EhjA.jpeg" /><figcaption>A-Share Real-Time Market Data API</figcaption></figure><h3>Why You Need a Proper A-Share Data API</h3><p>When I first started building market tools, I tried scraping financial websites for stock data. It worked for about a week before the page structure changed and everything broke. The latency was also terrible — not usable for real-time monitoring. That’s when I switched to a proper financial data API.</p><p>When evaluating a stock data API, I look for three things: broad coverage across Shanghai and Shenzhen exchanges, low latency for real-time use cases, and sufficient historical K-line data for backtesting. After trying a few options, I’ve been using <a href="https://itick.org/">itick</a> — the API design is clean, documentation is clear, and the Python integration took about an hour from sign-up to pulling live quotes.</p><h3>A-Share Trading Rules and How They Map to Data Fields</h3><p>Let’s get the trading rules straight first, so you know what each field means when you see it in the API response.</p><p><strong>Trading hours</strong>: 9:30–11:30 AM and 1:00–3:00 PM Beijing time. There’s a 1.5-hour lunch break.</p><p><strong>Price limits</strong>: Main board stocks move ±10%, ChiNext and STAR Market move ±20%, ST stocks move ±5%. At the limit-up price, buy orders pile up and sell orders dry up; the reverse happens at limit-down.</p><p><strong>T+1 settlement</strong>: Shares bought today can’t be sold until tomorrow, but the API returns real-time volume and turnover.</p><p><strong>Call auction</strong>: 9:15–9:25 AM is the opening call auction period — trades do happen during this window.</p><p>How do these show up in the API response? Key fields:</p><ul><li>ts: Trading status — 0 = normal trading, 1 = suspended, 2 = delisted, 3 = circuit breaker. No trades when suspended.</li><li>ld: Latest price. At limit-up, this is the ceiling price.</li><li>chp: Percent change. ±10% means limit-up or limit-down.</li><li>v: Cumulative daily volume.</li><li>tu: Cumulative daily turnover.</li></ul><h3>REST API for A-Share Quotes</h3><p>Start with REST to confirm the data format. For market dashboards or batch snapshots, the REST quote endpoint is the easiest entry point.</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Get A-share real-time quote<br>def get_a_share_quote(code):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;CN&quot;,<br>            &quot;code&quot;: code<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br><br># Fetch a few blue chips<br>stocks = [&quot;600519&quot;, &quot;000001&quot;, &quot;300750&quot;]<br>for code in stocks:<br>    q = get_a_share_quote(code)<br>    sign = &quot;+&quot; if q[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;{code}: {q[&#39;ld&#39;]} ({sign}{q[&#39;chp&#39;]}%)&quot;)</pre><p>The response fields are consistent across markets: ld latest price, chp percent change, o/h/l open/high/low, v volume. That&#39;s enough for a dashboard or basic technical analysis.</p><p><strong>Note</strong>: A-share codes are 6-digit numbers. Pass them as strings (e.g., &quot;600519&quot;), not integers. I wasted half a day passing them as numeric types before realizing the API rejected the request.</p><h3>WebSocket for Real-Time A-Share Push</h3><p>For intraday monitoring or price alerts, polling REST every few seconds is wasteful. That’s where WebSocket real-time push comes in.</p><p>The subscription format is the same as US stocks — two parameters: code$region.</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    # Wait for auth success before subscribing<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # A-share subscription format: code$region<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;600519$CN,000001$CN&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)</pre><p>A-share subscriptions use two parameters (600519$CN), same as US stocks — not the three-parameter format used for Indian markets. For real-time market data, WebSocket push is far more efficient than polling.</p><h3>K-Line (Candlestick) Data</h3><p>For technical analysis or backtesting, you’ll need historical K-line data. The endpoint works the same way as other markets, just with region=CN.</p><pre>def get_a_share_kline(code, k_type=8, limit=100):<br>    &quot;&quot;&quot;<br>    k_type: 1=1min, 2=5min, 5=1hour, 8=daily, 9=weekly, 10=monthly<br>    &quot;&quot;&quot;<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/kline&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;CN&quot;,<br>            &quot;code&quot;: code,<br>            &quot;kType&quot;: k_type,<br>            &quot;limit&quot;: limit<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br># Pull the last 100 daily candles for Kweichow Moutai<br>daily = get_a_share_kline(&quot;600519&quot;, k_type=8, limit=100)<br>closes = [bar[&quot;c&quot;] for bar in daily]<br># 20-day moving average<br>ma20 = sum(closes[-20:]) / 20<br>print(f&quot;600519 latest close: {closes[-1]}, 20-day MA: {ma20:.2f}&quot;)</pre><p>K-line responses use the standard OHLCV format: t timestamp, o/h/l/c open/high/low/close, v volume. Ready for technical analysis out of the box.</p><h3>A-Share-Specific Pitfalls</h3><p><strong>Lunch break means no data.</strong> From 11:30 AM to 1:00 PM Beijing time, there are no trades. When I first set up price alerts, I thought the API had gone down during lunch — turns out the market was just closed. Don’t treat the lunch break as a liquidity event.</p><p><strong>Detecting limit-up/limit-down.</strong> Main board stocks hit the daily limit at ±10%, ChiNext/STAR at ±20%. Your strategy should check whether a stock is at limit before trying to buy — at limit-up you can’t get filled. The chp field tells you how close you are.</p><p><strong>6-digit codes.</strong> A-share codes are 6-digit numbers (600519, 000001), different from Hong Kong’s 5 digits (00700) or Japan’s 4 digits (7203). I once passed “700” and got an empty response — that’s Tencent’s HK code, not an A-share.</p><p><strong>Region is CN.</strong> Pass region=CN for A-shares, not SH or SZ.</p><p><strong>Call auction volume.</strong> During 9:15–9:25 AM, trades happen but prices swing wildly. Don’t mistake call-auction volume for continuous-auction volume in your strategy.</p><h3>Complete Script: A-Share Market Monitor</h3><p>Putting it all together:</p><pre>import json, time, threading, requests, websocket<br>API_BASE = &quot;https://api.itick.org&quot;<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Watchlist<br>watchlist = [&quot;600519&quot;, &quot;000001&quot;, &quot;300750&quot;]<br># Initial snapshot<br>print(&quot;=== A-Share Snapshot ===&quot;)<br>for code in watchlist:<br>    r = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;CN&quot;, &quot;code&quot;: code}).json()[&quot;data&quot;]<br>    sign = &quot;+&quot; if r[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;  {code}: {r[&#39;ld&#39;]} ({sign}{r[&#39;chp&#39;]}%)&quot;)<br># WebSocket real-time push<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        params = &quot;,&quot;.join(f&quot;{c}$CN&quot; for c in watchlist)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: params,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;[live] {data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br>ws = websocket.WebSocketApp(WS_URL, header=[f&quot;token: {TOKEN}&quot;], on_message=on_message)<br>ws.run_forever()</pre><p>This script gives you an opening snapshot and live price updates through the trading day. From here you can extend it into a dashboard or alert system.</p><h3>Wrap-Up</h3><p>The technical architecture for A-share data is the same as other markets — REST for snapshots and historical data, WebSocket for real-time push. The main differences are in the trading rules (price limits, T+1, lunch break) and the code format (6 digits). These are the details that trip you up if you don’t know about them going in.</p><p>The full API documentation is available <a href="https://docs.itick.org/">here</a>.<br>GitHub：<a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9ab4ca73ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Japan Stock API Integration: TSE Market Data and Real-Time Subscriptions]]></title>
            <link>https://medium.com/@wutainfofu/python-japan-stock-api-integration-tse-market-data-and-real-time-subscriptions-b4306c596908?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4306c596908</guid>
            <category><![CDATA[japan]]></category>
            <category><![CDATA[japan-stock-market]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 12:13:30 GMT</pubDate>
            <atom:updated>2026-10-11T12:13:30.268Z</atom:updated>
            <content:encoded><![CDATA[<p>More and more friends are doing Asia-market quant work these days, and Japan is one you can’t ignore — the TSE Prime (formerly the First Section) has over 2,000 listed companies and ranks in the global top three for average daily turnover. Compared with the US and Hong Kong markets, Japan’s code system and trading rules are quite different, and it’s easy to trip up when connecting to the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1annZsUMia0uTqRtpL_hZw.jpeg" /><figcaption>Japan Stock API</figcaption></figure><p>This post documents the full process of connecting to Japanese stock market data, focusing on Japan’s code system and how it differs from other markets.</p><h3>Basics of the Japanese Market</h3><p>Japan’s main exchange is the Tokyo Stock Exchange (TSE), which now has three segments: Prime (main board), Standard, and Growth. The Nikkei 225 index and the TOPIX (Tokyo Stock Price Index) you commonly hear about are both selected from the Prime segment.</p><p>Compared with other markets, the Japanese market has a few characteristics:</p><p><strong>First, codes are 4-digit numbers.</strong> Unlike the US market’s alphabetic codes (AAPL) or Hong Kong’s 5-digit numeric codes (00700), Japanese stock codes are 4 digits. For example, 7203 is Toyota, 9984 is SoftBank, and 6758 is Sony.</p><p><strong>Second, trading hours follow Japan Standard Time (JST).</strong> JST is 1 hour ahead of Beijing time. The exchange opens at Tokyo time 9:00–11:30 (before noon) and 12:30–15:00 (after noon). Watch out for timezone conversion when doing real-time monitoring.</p><p><strong>Third, the region code is </strong><strong>JP.</strong> It&#39;s not like US or HK — for the Japanese market you pass JP.</p><h3>Quick Reference: Japanese Stock Codes</h3><p>Here are the codes of common Japanese large-cap stocks, ready to use when connecting to data:</p><p>CodeCompanyIndustry7203Toyota MotorAutomobile9984SoftBank GroupConglomerate6758Sony GroupElectronics8306Mitsubishi UFJ Financial GroupBanking6861KeyenceIndustrial automation6098Recruit HoldingsHuman resources7974NintendoGaming4063Shin-Etsu ChemicalChemicals</p><p>These are all Nikkei 225 constituents — highly liquid with stable data.</p><h3>Fetching Japanese Stock Quotes via REST</h3><p>Let’s start with REST to confirm the data format.</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Fetch real-time quotes for Japanese stocks<br>def get_jp_stock_quote(code):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;JP&quot;,<br>            &quot;code&quot;: code<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br><br># Fetch a few Japanese large-cap stocks<br>stocks = [&quot;7203&quot;, &quot;9984&quot;, &quot;6758&quot;]<br>for code in stocks:<br>    q = get_jp_stock_quote(code)<br>    sign = &quot;+&quot; if q[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;{code}: {q[&#39;ld&#39;]} ({sign}{q[&#39;chp&#39;]}%)&quot;)</pre><p>The returned fields are basically the same as other markets: ld latest price, chp change percentage, o/h/l open/high/low, v volume. These are enough for building a market dashboard.</p><p><strong>Note</strong>: Japanese stock codes are 4-digit numbers, so pass them as strings (“7203”), not as numbers.</p><h3>Subscribing to Japanese Stocks via WebSocket</h3><p>The WebSocket subscription format is the same as the US market: two parameters, code$market.</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    # First wait for authentication to succeed<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # Japanese stock subscription format: code$market<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;7203$JP,9984$JP&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)</pre><p>Unlike the Indian market — Japan uses two parameters (7203$JP), not three. Because Japan&#39;s primary exchange is just the TSE, there&#39;s no need to specify NSE/BSE like in India.</p><h3>Fetching K-Line Data</h3><p>The K-line endpoint is the same as other markets, except you pass JP as the region.</p><pre>def get_jp_kline(code, k_type=8, limit=100):<br>    &quot;&quot;&quot;<br>    k_type: 1=1min 2=5min 5=1hour 8=daily 9=weekly 10=monthly<br>    &quot;&quot;&quot;<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/kline&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;JP&quot;,<br>            &quot;code&quot;: code,<br>            &quot;kType&quot;: k_type,<br>            &quot;limit&quot;: limit<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br># Fetch the last 100 daily K-lines for Toyota<br>daily = get_jp_kline(&quot;7203&quot;, k_type=8, limit=100)<br>closes = [bar[&quot;c&quot;] for bar in daily]<br># Calculate the 20-day moving average<br>ma20 = sum(closes[-20:]) / 20<br>print(f&quot;7203 latest close: {closes[-1]}, 20-day MA: {ma20:.2f}&quot;)<br></pre><p>The K-line returns standard OHLCV: t timestamp, o/h/l/c open/high/low/close, v volume. You can use these fields directly for technical analysis.</p><h3>Notes on Japanese Market Integration</h3><p><strong>Codes are 4-digit numbers.</strong> Japanese stock codes are 4 digits (7203, 9984), which differs from both Hong Kong’s 5-digit codes (00700) and the US’s alphabetic codes (AAPL). At first I passed “07203” (with a leading zero) and got back empty data.</p><p><strong>Trading hours are 1 hour ahead of China.</strong> Japan Standard Time (JST) is 1 hour ahead of Beijing time. The TSE opens at Tokyo time 9:00–11:30 and 12:30–15:00, which corresponds to Beijing time 8:00–10:30 and 11:30–14:00. Watch the timezone when doing real-time monitoring.</p><p><strong>There’s a midday break.</strong> The Japanese market has a 1-hour lunch break (Tokyo time 11:30–12:30) with no trade data during that period. Be careful when backtesting strategies — don’t mistake the lunch break for a liquidity drought.</p><p><strong>The subscription format uses two parameters.</strong> Japan, like the US, uses two parameters (7203$JP), not India&#39;s three-parameter format. Because Japan&#39;s primary exchange is just the TSE.</p><p><strong>Timestamps are in milliseconds.</strong> All returned timestamps are in milliseconds. Treating them as seconds will give you a far-future time, so remember to divide by 1000.</p><h3>Complete Script: Japanese Stock Market Monitor</h3><p>Putting the earlier sections together, here’s the final complete script:</p><pre>import json, time, threading, requests, websocket<br>API_BASE = &quot;https://api.itick.org&quot;<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Japanese stock watchlist<br>watchlist = [&quot;7203&quot;, &quot;9984&quot;, &quot;6758&quot;]<br># Fetch snapshot on startup<br>print(&quot;=== Japanese Stock Snapshot ===&quot;)<br>for code in watchlist:<br>    r = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;JP&quot;, &quot;code&quot;: code}).json()[&quot;data&quot;]<br>    sign = &quot;+&quot; if r[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;  {code}: {r[&#39;ld&#39;]} ({sign}{r[&#39;chp&#39;]}%)&quot;)<br># Real-time WebSocket push<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        params = &quot;,&quot;.join(f&quot;{c}$JP&quot; for c in watchlist)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: params,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;[LIVE] {data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br>ws = websocket.WebSocketApp(WS_URL, header=[f&quot;token: {TOKEN}&quot;], on_message=on_message)<br>ws.run_forever()</pre><p>Once this script runs, you’ll first see a snapshot of Japanese stocks before the market opens, then real-time price and change updates throughout the session.</p><h3>Summary</h3><p>The technical framework for connecting to Japanese stock data is similar to the US market — REST for snapshots and historical data, WebSocket for real-time push. The main differences are the code system (4-digit numbers), trading hours (1 hour ahead of China), and the midday break. These details are easy to overlook unless you actually step on each pitfall.</p><p>Reference docs: <a href="https://docs.itick.org/websocket/stocks">https://docs.itick.org/websocket/stocks</a><br>GitHub: <a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4306c596908" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python India Stock API Integration: NSE/BSE Market Data and Real-Time Subscriptions]]></title>
            <link>https://medium.com/@wutainfofu/python-india-stock-api-integration-nse-bse-market-data-and-real-time-subscriptions-eaaebdfc1662?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaaebdfc1662</guid>
            <category><![CDATA[india]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[nse]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 11:44:24 GMT</pubDate>
            <atom:updated>2026-10-10T11:44:24.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately a lot of my friends have been building quantitative strategies for emerging markets, and India is one you can’t ignore. The combined market cap of NSE (National Stock Exchange of India) and BSE (Bombay Stock Exchange) ranks among the top globally, and growth is fast — many strategies perform completely differently in the Indian market than they do in the US.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R00tcgHDidniVZMPp3BUTw.jpeg" /><figcaption>India Stock API</figcaption></figure><p>But when it comes to connecting to Indian stock data, there are a few things that differ from the US and Hong Kong markets — especially the subscription format and exchange specification. This post documents the full process of connecting to Indian stock market data.</p><h3>How the Indian Market Differs from Others</h3><p>When I first started, I assumed it was just like the US market — pass a code and a region and you’re done. Turns out that’s not the case at all.</p><p><strong>First, India has two main exchanges: NSE and BSE.</strong> The same stock can be listed on both exchanges, with the same code but on different exchanges. So when connecting to Indian stocks, you must specify the exchange, or the data returned might not be the one you want.</p><p><strong>Second, the WebSocket subscription format is different.</strong> The US market uses two parameters: AAPL$US (codemarket).Indiausesthreeparameters:‘RELIANCE<em>market</em>).<em>Indiausesthreeparameters</em>:‘<em>RELIANCE</em>NSEIN‘(code<em>IN</em>‘(<em>code</em>exchange$market). At first I passed it in the US format and the subscription kept failing.</p><p><strong>Third, the region code is </strong><strong>IN.</strong> It&#39;s not like US or HK — for the Indian market you pass IN.</p><h3>Fetching Indian Stock Quotes via REST</h3><p>Let’s start with REST to confirm the data format is right.</p><pre>import requests<br>API_BASE = &quot;https://api.itick.org&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Fetch real-time quotes for Indian stocks<br>def get_india_stock_quote(code, exchange=&quot;NSE&quot;):<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/quote&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;IN&quot;,<br>            &quot;code&quot;: code,<br>            &quot;exchange&quot;: exchange<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br><br># Fetch a few Indian large-cap stocks<br>stocks = [<br>    (&quot;RELIANCE&quot;, &quot;NSE&quot;),   # Reliance Industries<br>    (&quot;TCS&quot;, &quot;NSE&quot;),        # Tata Consultancy Services<br>    (&quot;INFY&quot;, &quot;NSE&quot;),       # Infosys<br>]<br>for code, exchange in stocks:<br>    q = get_india_stock_quote(code, exchange)<br>    sign = &quot;+&quot; if q[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;{code}({exchange}): {q[&#39;ld&#39;]} ({sign}{q[&#39;chp&#39;]}%)&quot;)</pre><p>The returned fields are basically the same as other markets: ld latest price, chp change percentage, o/h/l open/high/low, v volume. These are enough for building a market dashboard.</p><p><strong>Note</strong>: Indian stock codes are alphabetic (RELIANCE, TCS), not numeric. This is different from Hong Kong’s numeric codes (700).</p><h3>Subscribing to Indian Stocks via WebSocket (Key Section)</h3><p>This is where the Indian market trips people up most — the subscription format is different from other markets.</p><p>Other markets (US, Hong Kong, forex) all use two parameters: code$market, e.g. AAPL$US.</p><p>The Indian market uses three parameters: code$exchange$market, e.g. RELIANCE$NSE$IN.</p><pre>import json<br>import threading<br>import time<br>import websocket<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    # First wait for authentication to succeed<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # Indian stock subscription format: code$exchange$market<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: &quot;RELIANCE$NSE$IN,TCS$NSE$IN&quot;,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;{data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)</pre><p><strong>Why does India need an extra exchange parameter?</strong> Because the same stock can be listed on both NSE and BSE, and the prices may differ. Specifying the exchange ensures you get the data from the exchange you actually want.</p><h3>Fetching K-Line Data</h3><p>The K-line endpoint is the same as other markets, except it has an extra exchange parameter.</p><pre>def get_india_kline(code, exchange=&quot;NSE&quot;, k_type=8, limit=100):<br>    &quot;&quot;&quot;<br>    k_type: 1=1min 2=5min 5=1hour 8=daily 9=weekly 10=monthly<br>    &quot;&quot;&quot;<br>    resp = requests.get(<br>        f&quot;{API_BASE}/stock/kline&quot;,<br>        headers=headers,<br>        params={<br>            &quot;region&quot;: &quot;IN&quot;,<br>            &quot;code&quot;: code,<br>            &quot;exchange&quot;: exchange,<br>            &quot;kType&quot;: k_type,<br>            &quot;limit&quot;: limit<br>        }<br>    )<br>    return resp.json()[&quot;data&quot;]<br># Fetch the last 100 daily K-lines for RELIANCE<br>daily = get_india_kline(&quot;RELIANCE&quot;, &quot;NSE&quot;, k_type=8, limit=100)<br>closes = [bar[&quot;c&quot;] for bar in daily]<br># Calculate the 20-day moving average<br>ma20 = sum(closes[-20:]) / 20<br>print(f&quot;RELIANCE latest close: {closes[-1]}, 20-day MA: {ma20:.2f}&quot;)<br></pre><p>The K-line returns standard OHLCV: t timestamp, o/h/l/c open/high/low/close, v volume. You can use these fields directly for technical analysis.</p><h3>Special Notes on Indian Market Integration</h3><p><strong>Don’t get the subscription format wrong.</strong> This is the most common pitfall. India uses three parameters: RELIANCE$NSE$IN, not two. At first I passed RELIANCE$IN in the US format, and the subscription kept failing.</p><p><strong>Always specify the exchange.</strong> India has two exchanges, NSE and BSE, and the same stock can be listed on both. The REST endpoint requires exchange=NSE or exchange=BSE, and WebSocket subscriptions must include the exchange code in the params.</p><p><strong>Trading hours differ from China.</strong> Indian market hours follow India Standard Time (IST), which is 2.5 hours behind Beijing time. Watch out for timezone conversion when doing real-time monitoring.</p><p><strong>Stock codes are alphabetic.</strong> Indian stock codes are alphabetic (RELIANCE, TCS, INFY), not numeric. This differs from Hong Kong’s numeric codes (700).</p><p><strong>Timestamps are in milliseconds.</strong> All returned timestamps are in milliseconds. Treating them as seconds will give you a far-future time, so remember to divide by 1000.</p><h3>Complete Script: Indian Stock Market Monitor</h3><p>Putting the earlier sections together, here’s the final complete script:</p><pre>import json, time, threading, requests, websocket<br>API_BASE = &quot;https://api.itick.org&quot;<br>WS_URL = &quot;wss://api.itick.org/stock&quot;<br>TOKEN = &quot;your_token_here&quot;<br>headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;token&quot;: TOKEN}<br># Indian stock watchlist<br>watchlist = [<br>    (&quot;RELIANCE&quot;, &quot;NSE&quot;),<br>    (&quot;TCS&quot;, &quot;NSE&quot;),<br>    (&quot;INFY&quot;, &quot;NSE&quot;),<br>]<br># Fetch snapshot on startup<br>print(&quot;=== Indian Stock Snapshot ===&quot;)<br>for code, exchange in watchlist:<br>    r = requests.get(f&quot;{API_BASE}/stock/quote&quot;,<br>                     headers=headers,<br>                     params={&quot;region&quot;: &quot;IN&quot;, &quot;code&quot;: code, &quot;exchange&quot;: exchange}).json()[&quot;data&quot;]<br>    sign = &quot;+&quot; if r[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>    print(f&quot;  {code}({exchange}): {r[&#39;ld&#39;]} ({sign}{r[&#39;chp&#39;]}%)&quot;)<br># Real-time WebSocket push<br>authenticated = False<br>def on_message(ws, message):<br>    global authenticated<br>    payload = json.loads(message)<br>    if payload.get(&quot;resAc&quot;) == &quot;auth&quot; and payload.get(&quot;code&quot;) == 1 and not authenticated:<br>        authenticated = True<br>        # Indian stock subscription format: code$exchange$market<br>        params = &quot;,&quot;.join(f&quot;{c}${e}$IN&quot; for c, e in watchlist)<br>        ws.send(json.dumps({<br>            &quot;ac&quot;: &quot;subscribe&quot;,<br>            &quot;params&quot;: params,<br>            &quot;types&quot;: &quot;quote&quot;<br>        }))<br>        threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()<br>        return<br>    if payload.get(&quot;resAc&quot;) == &quot;pong&quot;:<br>        return<br>    data = payload.get(&quot;data&quot;) or {}<br>    if data.get(&quot;type&quot;) == &quot;quote&quot;:<br>        sign = &quot;+&quot; if data[&quot;chp&quot;] &gt;= 0 else &quot;&quot;<br>        print(f&quot;[LIVE] {data[&#39;s&#39;]}: {data[&#39;ld&#39;]} ({sign}{data[&#39;chp&#39;]}%)&quot;)<br>def heartbeat(ws):<br>    while True:<br>        time.sleep(30)<br>        ws.send(json.dumps({&quot;ac&quot;: &quot;ping&quot;, &quot;params&quot;: str(int(time.time() * 1000))}))<br>ws = websocket.WebSocketApp(WS_URL, header=[f&quot;token: {TOKEN}&quot;], on_message=on_message)<br>ws.run_forever()</pre><p>Once this script runs, you’ll first see a snapshot of Indian stocks before the market opens, then real-time price and change updates throughout the session.</p><h3>Summary</h3><p>The technical framework for connecting to Indian stock data is similar to the US and Hong Kong markets — REST for snapshots and historical data, WebSocket for real-time push. But there are a few special points: the subscription format uses three parameters (codeexchange<em>exchange</em>market), you must specify the NSE or BSE exchange, and trading hours differ from China. These details are easy to overlook unless you actually step on each pitfall.</p><p>Reference docs: <a href="https://docs.itick.org/websocket/stocks">https://docs.itick.org/websocket/stocks</a><br>GitHub: <a href="https://github.com/itick-org">https://github.com/itick-org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaaebdfc1662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What to Look for in a Forex Data API (When You’ve Already Tried Three)]]></title>
            <link>https://medium.com/@wutainfofu/what-to-look-for-in-a-forex-data-api-when-youve-already-tried-three-90741c94658e?source=rss-6591263924c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/90741c94658e</guid>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[San Si wu]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 11:57:25 GMT</pubDate>
            <atom:updated>2026-09-20T11:57:25.795Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve built anything that touches the forex market — a price alert bot, a currency strength dashboard, a backtesting rig, even a simple widget on your personal site — you’ve probably gone through the same cycle I did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96mr208DlLKZSAcppQRiLA.jpeg" /><figcaption>Forex Data API</figcaption></figure><p>You start with whatever your trading platform gives you for free. Then you realize the quotes are delayed, the historical data has gaps, and when you try to pull data programmatically, you hit a paywall or a rate limit faster than you expected. So you switch providers. Then you switch again.</p><p>After going through that cycle myself, I ended up writing down the things I actually care about when evaluating a forex data API. This is that list.</p><h3>Coverage: How Many Pairs Do You Actually Need?</h3><p>Most providers advertise “100+ currency pairs.” That sounds impressive until you realize 80 of them are exotic crosses nobody trades. What matters is the coverage of the pairs you actually use.</p><p>If you’re a major-pairs trader (EUR/USD, GBP/USD, USD/JPY, USD/CHF, AUD/USD), almost any provider will cover you. The problem starts when you expand: CAD crosses, JPY crosses, EM currencies like USD/ZAR or USD/TRY, even things like EUR/CZK or USD/HKD.</p><p>I learned this the hard way when I built a currency strength meter. I needed consistent quotes across 28 pairs covering G10 currencies against each other. My first provider had solid majors but spotty coverage on the exotics, which meant the strength index had blind spots. The whole point of the tool was to see where money was flowing, and if a pair was missing, the picture was incomplete.</p><p>When you’re evaluating a provider, don’t look at the total number. Look at whether they cover the exact pairs on your watchlist.</p><h3>Real-Time vs. Delayed: The Fine Print</h3><p>“Real-time” is one of the most abused terms in market data.</p><p>Some providers advertise real-time quotes but actually give you 15-minute delayed data unless you pay a premium tier. Others stream what looks like real-time data but have a gap during the Asian session when liquidity thins out. A few will give you real-time prices but no tick-level history — meaning you can see the current price but you can’t reconstruct what happened 20 minutes ago.</p><p>The way to test this: open the provider’s quote on a pairs that moves fast (GBP/USD during the London session is a good test). Compare it to at least two independent sources — your trading terminal, another data provider, even a simple web search. If the prices consistently match, you’re getting real data. If they don’t, you’re either delayed or the data is being consolidated from a different liquidity source.</p><h3>Historical Data: Gaps Kill Backtests</h3><p>This is where most providers fall apart.</p><p>Live streaming works fine. The interface is clean. The documentation is decent. But when you pull historical K-line data for backtesting, you start noticing the gaps. Missing hours during low-liquidity periods. Candles that have open=high=low=close because there were no trades. Data that starts and stops arbitrarily.</p><p>For discretionary traders, gaps in historical data are annoying. For systematic traders, they’re catastrophic. If your backtest data has holes, your strategy looks better or worse than it actually is, and you can’t trust the results.</p><p>When you’re evaluating a provider, specifically ask: how far back does the minute-level data go? Are there gaps during the weekend? Do they adjust for rollovers and DST changes? These aren’t edge cases — they’re the difference between a usable dataset and a nice-looking chart.</p><h3>WebSocket Reliability: Connections Need to Stay Up</h3><p>If you’re building anything that runs continuously — a monitoring tool, a real-time dashboard, an automated strategy — you need a WebSocket feed that doesn’t drop every hour.</p><p>Most providers support WebSocket connections. The difference is what happens when your connection gets interrupted:</p><ul><li>Do they buffer missed messages, or do you have to re-sync manually?</li><li>Is there a heartbeat mechanism, or does the connection silently die after a minute of inactivity?</li><li>Can you resume from where you left off, or do you have to restart the whole stream?</li></ul><p>The worst case I’ve seen: a provider that advertised WebSocket streaming but would silently disconnect after exactly 60 seconds unless you sent a heartbeat. If you didn’t read the documentation carefully (or if you forgot to implement it), you’d wake up the next morning to a dead stream and no alerts.</p><h3>Rate Limits and Pricing: Read the Fine Print</h3><p>“Free tier” is great until you hit a rate limit at 9 AM when the market opens and you need data the most.</p><p>Some providers have per-second limits that sound generous until you realize you’re polling 20 pairs and that’s 20 requests per second just for snapshots. Others have monthly limits that sound infinite until you’re backtesting and pulling thousands of historical candles.</p><p>Look for: what happens when you exceed the limit? Does the API throttle you, reject requests, or just slow down? Is the limit documented, or do you discover it by getting 429 errors at the worst possible moment?</p><h3>What I Actually Use Now</h3><p>After going through a few providers, I ended up settling on <a href="https://itick.org/">iTick</a> for my forex data needs. A few things worked for me:</p><ul><li>The pair coverage included the exotics I needed for the currency strength meter, not just the majors</li><li>The WebSocket feed has proper auth flow and heartbeat, so it stays connected through the quiet Asian hours</li><li>Historical K-line data is consistent enough for backtesting — no random gaps in the data</li><li>The REST API is simple: you pass the pair and the region, you get OHLC data back. No complicated SDK to install, no bizarre parameter names</li></ul><p>I’m not saying it’s the right choice for everyone. If you only trade majors and need a simple quote for a personal project, almost any free provider will work. But if you’re building something that needs reliable real-time data across multiple pairs, clean historical data for backtesting, and a stream that stays up — it’s worth adding to your shortlist.</p><p>You can sign up and check the coverage for your specific pairs <a href="https://itick.org/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90741c94658e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>