<?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"><channel><title><![CDATA[Greenhaven365 Notes]]></title><description><![CDATA[Practical notes on crypto futures, funding and risk.]]></description><link>https://greenhaven365.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 13:59:40 GMT</lastBuildDate><atom:link href="https://greenhaven365.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Compute realized volatility of a Bitcoin perpetual from public candlesticks (Python)]]></title><description><![CDATA[Pull confirmed OKX klines for BTC-USDT-SWAP, build close-to-close log returns, and annualize sample realized vol on a stated 24/7 convention.]]></description><link>https://greenhaven365.hashnode.dev/compute-realized-volatility-of-a-bitcoin-perpetual-from-public-candlesticks-python</link><guid isPermaLink="true">https://greenhaven365.hashnode.dev/compute-realized-volatility-of-a-bitcoin-perpetual-from-public-candlesticks-python</guid><category><![CDATA[Python]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Bitcoin]]></category><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[volatility]]></category><dc:creator><![CDATA[Greenhaven365]]></dc:creator><pubDate>Sat, 14 Nov 2026 18:15:13 GMT</pubDate><content:encoded><![CDATA[<p>Realized volatility is a <strong>backward-looking statistic</strong>, not a forecast and not a margin requirement. This tutorial pulls confirmed public candlesticks for OKX <code>BTC-USDT-SWAP</code> (no API key), builds close-to-close log returns, and annualizes the sample standard deviation on a stated 24/7 convention: <code>sqrt(365 × 24 / hours_per_bar)</code>. The klines are last-trade bars, not mark-price bars. That choice is labeled in the output because liquidation and unrealized PnL usually watch mark, not last.</p>
<p>The script will not tell you what volatility will be tomorrow, and it will not size a position for you.</p>
<blockquote>
<p><strong>Not financial advice.</strong> This is a programming / market-structure exercise. Derivatives trading can liquidate your margin. Verify candle conventions against the venue you use.</p>
</blockquote>
<h2>What we will compute</h2>
<p>For a series of confirmed bar closes <code>C_0, C_1, …, C_n</code> in a fixed window:</p>
<pre><code class="language-text">r_t        = ln(C_t / C_{t-1})
s_sample   = sample standard deviation of r_t   (denominator n−1)
ann_vol    = s_sample × sqrt(365 × 24 / hours_per_bar)
</code></pre>
<p>Choices the script makes explicit:</p>
<ul>
<li><strong>Price:</strong> the candle <strong>close</strong>, which on this public endpoint is a last-trade close. A mark-based volatility would be a different series.</li>
<li><strong>Timestamp:</strong> the <code>ts</code> field is the <strong>bar open</strong>. A 1H bar with <code>ts</code> equal to 00:00 covers 00:00–01:00; its close is as of 01:00. The code prints both the open timestamp and the implied close clock.</li>
<li><strong>Confirmed bars only:</strong> the payload’s confirm flag must be <code>1</code>. A forming bar is dropped.</li>
<li><strong>Day count:</strong> 365 calendar days, 24 hours, because these contracts trade around the clock. A 252-day “trading year” would be a different convention and needs a different column label.</li>
<li><strong>Estimator:</strong> sample standard deviation. The population (<code>n</code>) figure is printed beside it as a sensitivity, not as a second truth.</li>
</ul>
<p>Annualizing one noisy window is arithmetic. A 24-hour estimate will jump around, especially on a day with a large close-to-close move. If you use a volatility number to think about stop distance or a risk budget, treat it as an input you have to refresh; a sizing walkthrough that starts from a dollar risk and a stop, rather than from a volatility slogan, is at <a href="https://www.greenhaven365.com/calculate-crypto-futures-position-size-fixed-risk-budget/">greenhaven365.com/calculate-crypto-futures-position-size-fixed-risk-budget/</a>. A broader pre-trade risk list for Bitcoin perpetuals is at <a href="https://www.greenhaven365.com/beginner-risk-checklist-bitcoin-perpetual-contracts/">greenhaven365.com/beginner-risk-checklist-bitcoin-perpetual-contracts/</a>.</p>
<h2>Fetch confirmed candles</h2>
<pre><code class="language-python">import json
import math
import statistics
import urllib.request
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

INST = "BTC-USDT-SWAP"
UA = {"User-Agent": "realized-vol-demo/1.0"}
LOCAL_TZ = ZoneInfo("Asia/Shanghai")
YEAR_DAYS = 365.0  # 24/7 calendar convention — not a forecast


def get_payload(url: str) -&gt; list:
    req = urllib.request.Request(url, headers=UA)
    with urllib.request.urlopen(req, timeout=20) as resp:
        payload = json.loads(resp.read().decode())
    if str(payload.get("code")) != "0":
        raise RuntimeError(payload)
    return payload["data"]


def parse_ts(ms: str | int) -&gt; datetime:
    return datetime.fromtimestamp(int(ms) / 1000, tz=timezone.utc).astimezone(LOCAL_TZ)


def fetch_confirmed(bar: str, limit: int) -&gt; list:
    rows = get_payload(
        "https://www.okx.com/api/v5/market/candles"
        f"?instId={INST}&amp;bar={bar}&amp;limit={limit}"
    )
    # payload: [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]
    confirmed = [r for r in rows if str(r[8]) == "1"]
    confirmed.sort(key=lambda r: int(r[0]))  # oldest first
    return confirmed
</code></pre>
<p>OKX returns newest candles first. The sort puts them in chronological order before any return is computed. The <code>f</code> prefix on the candles URL is required; without it, <code>{INST}</code> is sent literally.</p>
<h2>Annualize a window and print a small table</h2>
<pre><code class="language-python">BAR_HOURS = {"1H": 1.0, "5m": 5.0 / 60.0, "15m": 0.25}


def realized_vol(rows: list, bar: str, window_hours: float) -&gt; None:
    hours_per_bar = BAR_HOURS[bar]
    n_returns = int(round(window_hours / hours_per_bar))
    if len(rows) &lt; n_returns + 1:
        raise RuntimeError(
            f"not enough confirmed {bar} candles: have {len(rows)}, "
            f"need {n_returns + 1}"
        )
    window = rows[-(n_returns + 1):]
    closes = [float(r[4]) for r in window]
    opens = [parse_ts(r[0]) for r in window]
    close_clocks = [o + timedelta(hours=hours_per_bar) for o in opens]
    rets = [math.log(closes[i] / closes[i - 1]) for i in range(1, len(closes))]
    s_sample = statistics.stdev(rets)
    s_pop = statistics.pstdev(rets)
    periods = (YEAR_DAYS * 24.0) / hours_per_bar
    ann_sample = s_sample * math.sqrt(periods)
    ann_pop = s_pop * math.sqrt(periods)
    simple = closes[-1] / closes[0] - 1.0
    i_min = min(range(len(rets)), key=lambda i: rets[i])
    i_max = max(range(len(rets)), key=lambda i: rets[i])
    print(f"bar={bar}  window={window_hours:.0f}h  n_returns={len(rets)}")
    print(
        f"  first close {closes[0]:.1f}  bar open {opens[0].isoformat()}  "
        f"close as of {close_clocks[0].isoformat()}"
    )
    print(
        f"  last  close {closes[-1]:.1f}  bar open {opens[-1].isoformat()}  "
        f"close as of {close_clocks[-1].isoformat()}"
    )
    print(f"  simple close-to-close {simple * 100:.3f}%")
    print(
        f"  sample stdev {s_sample:.8f}  pop stdev {s_pop:.8f}  "
        f"periods/year {periods:.0f}"
    )
    print(
        f"  ann vol sample {ann_sample * 100:.2f}%  "
        f"ann vol pop {ann_pop * 100:.2f}%  "
        f"(× sqrt({periods:.0f}); not a forecast)"
    )
    print(
        f"  min log ret {rets[i_min] * 100:.4f}%  "
        f"at close as of {close_clocks[i_min + 1].isoformat()}"
    )
    print(
        f"  max log ret {rets[i_max] * 100:.4f}%  "
        f"at close as of {close_clocks[i_max + 1].isoformat()}"
    )


def report() -&gt; None:
    h1 = fetch_confirmed("1H", 200)
    m5 = fetch_confirmed("5m", 300)
    m15 = fetch_confirmed("15m", 120)
    print(
        f"{INST} last-trade candles  convention=ACT/365 × 24h  "
        f"estimator=sample stdev of close-to-close log returns"
    )
    print(
        f"1H confirmed {len(h1)}  "
        f"{parse_ts(h1[0][0]).isoformat()} -&gt; {parse_ts(h1[-1][0]).isoformat()}"
    )
    realized_vol(h1, "1H", 24)
    realized_vol(h1, "1H", 168)
    print(
        f"5m confirmed {len(m5)}  "
        f"{parse_ts(m5[0][0]).isoformat()} -&gt; {parse_ts(m5[-1][0]).isoformat()}"
    )
    realized_vol(m5, "5m", 24)
    print(f"15m confirmed {len(m15)}")
    realized_vol(m15, "15m", 24)


if __name__ == "__main__":
    report()
</code></pre>
<p>On <strong>15 November 2026 at 01:41 (Asia/Shanghai)</strong>, a live run printed the following. Close clocks are the bar open plus the bar length, so the OKX open-timestamp convention is not ambiguous.</p>
<pre><code class="language-text">BTC-USDT-SWAP last-trade candles  convention=ACT/365 × 24h  estimator=sample stdev of close-to-close log returns
1H confirmed 199  2026-11-06T18:00:00+08:00 -&gt; 2026-11-15T00:00:00+08:00
bar=1H  window=24h  n_returns=24
  first close 68668.0  bar open 2026-11-14T00:00:00+08:00  close as of 2026-11-14T01:00:00+08:00
  last  close 65315.0  bar open 2026-11-15T00:00:00+08:00  close as of 2026-11-15T01:00:00+08:00
  simple close-to-close -4.883%
  sample stdev 0.00509909  pop stdev 0.00499173  periods/year 8760
  ann vol sample 47.72%  ann vol pop 46.72%  (× sqrt(8760); not a forecast)
  min log ret -1.3876%  at close as of 2026-11-14T12:00:00+08:00
  max log ret 0.5983%  at close as of 2026-11-14T18:00:00+08:00
bar=1H  window=168h  n_returns=168
  first close 75711.3  bar open 2026-11-08T00:00:00+08:00  close as of 2026-11-08T01:00:00+08:00
  last  close 65315.0  bar open 2026-11-15T00:00:00+08:00  close as of 2026-11-15T01:00:00+08:00
  simple close-to-close -13.732%
  sample stdev 0.00467114  pop stdev 0.00465721  periods/year 8760
  ann vol sample 43.72%  ann vol pop 43.59%  (× sqrt(8760); not a forecast)
  min log ret -2.1691%  at close as of 2026-11-09T06:00:00+08:00
  max log ret 1.3567%  at close as of 2026-11-13T15:00:00+08:00
5m confirmed 299  2026-11-14T00:45:00+08:00 -&gt; 2026-11-15T01:35:00+08:00
bar=5m  window=24h  n_returns=288
  first close 68870.5  bar open 2026-11-14T01:35:00+08:00  close as of 2026-11-14T01:40:00+08:00
  last  close 66005.8  bar open 2026-11-15T01:35:00+08:00  close as of 2026-11-15T01:40:00+08:00
  simple close-to-close -4.160%
  sample stdev 0.00173147  pop stdev 0.00172847  periods/year 105120
  ann vol sample 56.14%  ann vol pop 56.04%  (× sqrt(105120); not a forecast)
  min log ret -0.9462%  at close as of 2026-11-14T11:35:00+08:00
  max log ret 0.7334%  at close as of 2026-11-14T23:45:00+08:00
15m confirmed 119
bar=15m  window=24h  n_returns=96
  first close 68695.2  bar open 2026-11-14T01:15:00+08:00  close as of 2026-11-14T01:30:00+08:00
  last  close 65584.1  bar open 2026-11-15T01:15:00+08:00  close as of 2026-11-15T01:30:00+08:00
  simple close-to-close -4.529%
  sample stdev 0.00296383  pop stdev 0.00294835  periods/year 35040
  ann vol sample 55.48%  ann vol pop 55.19%  (× sqrt(35040); not a forecast)
  min log ret -1.3281%  at close as of 2026-11-14T10:30:00+08:00
  max log ret 0.7887%  at close as of 2026-11-14T23:45:00+08:00
</code></pre>
<p>A few readings of <em>this</em> window, none of them a forecast:</p>
<ul>
<li>The 1H close-to-close move over those 24 hours was <strong>−4.883%</strong>. Annualized sample realized vol on that same 24-hour, 1H series was <strong>47.72%</strong>. The seven-day, 1H figure was <strong>43.72%</strong>, with a −13.732% simple move. A one-day annualization on a large down day is noisy; the two windows are not a regime call.</li>
<li>Finer bars produced a higher 24-hour annualized figure in this snapshot (<strong>56.14%</strong> on 5-minute closes, <strong>55.48%</strong> on 15-minute closes). That can happen when a sharp move is resolved more clearly at higher frequency. It is not evidence that a finer bar is “the correct” volatility.</li>
<li>The 1H and 5-minute 24-hour windows are not identical clocks (the 1H window ends at the 00:00–01:00 bar; the 5-minute window ends at 01:40). Do not treat the difference between 47.72% and 56.14% as a pure bar-size effect.</li>
<li>Population standard deviation sat slightly below the sample figure, as expected with <code>n</code> of 24 and almost no difference at <code>n</code> of 168 or 288. The headline number in this tutorial is the <strong>sample</strong> column.</li>
</ul>
<h2>What this script does not cover</h2>
<p>Do not treat annualized realized vol as implied volatility, as a margin parameter, or as a guaranteed stop distance. The series is last-trade, not mark. Overnight gaps in the usual equity-market sense are not the main issue here; 24/7 trading is, and the convention already counts 24 hours.</p>
<p>Parkinson, Garman–Klass, or Yang–Zhang estimators would use the high/low fields this endpoint also returns. They are different statistics and need their own labels. If you change the day count, change the label at the same time.</p>
<p>Useful follow-ups: store each window’s <code>ann_vol</code> with its start and end close clocks and refuse to compare two figures that do not share a convention; or pull mark-price history, if you have a documented source, and compare it to this last-trade series without averaging them.</p>
<p><strong>Sources:</strong> OKX public API <code>market/candles</code> for <code>BTC-USDT-SWAP</code>, retrieved 2026-11-15 01:41 (Asia/Shanghai). Day-count and estimator choices are this tutorial’s, not a venue “official volatility.”</p>
<p><strong>AI disclosure:</strong> This article was created with AI assistance (drafting/editing). The numeric snapshot was checked against a live public API response on the date above. Re-run the script and verify the venue’s current candle conventions before relying on any figure.</p>
<p><strong>Disclaimer:</strong> Not financial advice. Educational / developer content only.</p>
]]></content:encoded></item></channel></rss>