astrnvk's picture
витрина: справочный набор с метками — бесплатно
8f1e168 verified
Raw
History Blame Contribute Delete
72.7 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Polymarket order book data</title>
<meta name="description" content="Tick-level quotes, trades and L2 order book depth from Polymarket up/down markets. BTC, ETH, SOL, XRP. Parquet with sha256 manifests. Priced per day from $3.">
<!-- Machine-readable copy of what this page says, for agents and crawlers.
Kept in sync by hand with the copy below; numbers that change daily
(date range, day count) are deliberately absent rather than stale. -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Dataset",
"name": "Polymarket up/down market microstructure",
"description": "Tick-level best bid/ask, trades with taker side, L2 order book depth and spot candles from Polymarket 5-minute up/down markets on BTC, ETH, SOL and XRP. One Parquet file per asset, table and UTC day, each with a sha256 manifest.",
"license": "https://spdx.org/licenses/CC-BY-NC-4.0.html",
"creator": { "@type": "Organization", "name": "astrnvk" },
"temporalCoverage": "2026-06-30/..",
"variableMeasured": [
"best bid", "best ask", "spread", "order book depth", "trade price",
"trade size", "taker side", "spot open/high/low/close"
],
"distribution": [{
"@type": "DataDownload",
"encodingFormat": "application/vnd.apache.parquet",
"contentUrl": "https://huggingface.co/datasets/astrnvk/polymarket-orderbook-data-preview"
}],
"offers": {
"@type": "Offer",
"priceCurrency": "USD",
"priceSpecification": [
{ "@type": "UnitPriceSpecification", "price": "5", "referenceQuantity": { "@type": "QuantitativeValue", "unitCode": "DAY", "minValue": 1, "maxValue": 6 } },
{ "@type": "UnitPriceSpecification", "price": "4", "referenceQuantity": { "@type": "QuantitativeValue", "unitCode": "DAY", "minValue": 7, "maxValue": 29 } },
{ "@type": "UnitPriceSpecification", "price": "3", "referenceQuantity": { "@type": "QuantitativeValue", "unitCode": "DAY", "minValue": 30 } }
],
"acceptedPaymentMethod": "https://purl.org/goodrelations/v1#ByBankTransferInAdvance"
}
}
</script>
<style>
/* Instrument panel, not a document. The whole page is set in one monospace
voice: this is market data, and the type should say so before the words do.
Hierarchy comes from size, weight and tracking instead of a second family,
which also sidesteps loading a webfont the CSP would block. */
:root {
--ground: #f7f6f3;
--panel: #edebe6;
--ink: #14161a;
--dim: #6a6e77;
--line: #dcd8d1;
--signal: #0a6f63;
--warn: #94670f;
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas,
"Liberation Mono", "Courier New", monospace;
--page: 940px;
}
@media (prefers-color-scheme: dark) {
:root {
--ground: #0e0f12;
--panel: #16181d;
--ink: #e8e6e1;
--dim: #888d96;
--line: #262a31;
--signal: #3ad4bd;
--warn: #d9a94e;
}
}
/* The viewer's own toggle has to beat the system preference both ways. */
:root[data-theme="dark"] {
--ground:#0e0f12; --panel:#16181d; --ink:#e8e6e1;
--dim:#888d96; --line:#262a31; --signal:#3ad4bd; --warn:#d9a94e;
}
:root[data-theme="light"] {
--ground:#f7f6f3; --panel:#edebe6; --ink:#14161a;
--dim:#6a6e77; --line:#dcd8d1; --signal:#0a6f63; --warn:#94670f;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--ground);
color: var(--ink);
font-family: var(--mono);
font-size: 15px;
line-height: 1.65;
-webkit-font-smoothing: antialiased;
}
.wrap { max-width: var(--page); margin: 0 auto; padding: 0 24px; }
/* Alternating bands give the page its rhythm. No hairline rails, no
left-hand index column: this reads as a panel, not a broadsheet. */
.band { padding: 56px 0; }
.band.sunk { background: var(--panel); }
.band + .band { border-top: 1px solid var(--line); }
p { margin: 0 0 14px; max-width: 68ch; }
p:last-child { margin-bottom: 0; }
a { color: var(--signal); text-underline-offset: 3px; }
h1, h2, h3 { font-weight: 600; margin: 0; letter-spacing: -0.02em; }
h1 { font-size: clamp(30px, 5vw, 46px); line-height: 1.08; text-wrap: balance; }
h2 { font-size: clamp(21px, 3vw, 27px); line-height: 1.2; margin-bottom: 18px; }
h3 { font-size: 15px; letter-spacing: 0; margin-bottom: 6px; }
.eyebrow {
font-size: 10.5px;
letter-spacing: 0.15em;
text-transform: uppercase;
color: var(--dim);
margin-bottom: 12px;
}
.dim { color: var(--dim); }
.num { font-variant-numeric: tabular-nums; }
/* ------------------------------------------------------------------ head */
.top {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
flex-wrap: wrap;
padding: 16px 0;
border-bottom: 1px solid var(--line);
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.top nav { display: flex; gap: 20px; }
.top a { color: var(--dim); text-decoration: none; }
.top a:hover { color: var(--ink); }
/* Two products, two tabs. Rendered only when the script runs: without it the
page stays what it always was, one document with everything on it, and a
pair of buttons that switch nothing would be worse than no buttons. */
.tabs { display: flex; }
/* An author `display` beats the UA rule behind [hidden], so both of these
would stay on screen without it — the tab strip visible and inert on a page
whose script never ran, which is the one state this must not produce. */
.tabs[hidden], .top nav[hidden] { display: none; }
.tab {
font: inherit; font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase;
padding: 9px 16px; cursor: pointer;
background: none; color: var(--dim);
border: 1px solid var(--line);
margin-left: -1px; /* shared edge, one rule between them */
transition: color 0.12s ease;
}
.tab:first-child { margin-left: 0; }
.tab:hover { color: var(--ink); }
.tab[aria-selected="true"] {
color: var(--ink);
border-color: var(--ink);
position: relative; z-index: 1; /* its border wins over the neighbour's */
}
.tab:focus-visible { outline: 2px solid var(--signal); outline-offset: 2px; }
.hero { padding: 60px 0 44px; }
.hero p.lede { font-size: 17px; color: var(--dim); max-width: 60ch; margin-top: 18px; }
/* Spec strip: four facts, aligned, no card chrome. */
.specs {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1px;
margin-top: 36px;
background: var(--line);
border: 1px solid var(--line);
}
.specs div { background: var(--ground); padding: 14px 16px; }
.specs dt { font-size: 10.5px; letter-spacing: 0.15em; text-transform: uppercase; color: var(--dim); }
.specs dd { margin: 4px 0 0; font-size: 15px; font-variant-numeric: tabular-nums; }
/* ---------------------------------------------------------------- tables */
.scroll { overflow-x: auto; margin-top: 18px; }
table { border-collapse: collapse; width: 100%; font-size: 13.5px; min-width: 560px; }
th {
text-align: left;
font-weight: 600;
font-size: 10.5px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--dim);
padding: 0 16px 8px 0;
border-bottom: 1px solid var(--ink);
}
td { padding: 10px 16px 10px 0; border-bottom: 1px solid var(--line); vertical-align: top; }
tr:last-child td { border-bottom: 0; }
td:last-child, th:last-child { padding-right: 0; }
/* Rate card: no min-width floor, it is three short columns. */
.rates { min-width: 0; margin-top: 20px; }
.rates td { font-variant-numeric: tabular-nums; }
.rates td:nth-child(2) { color: var(--signal); font-weight: 600; }
/* ------------------------------------------------------------- key facts */
.facts { display: grid; gap: 1px; background: var(--line); border: 1px solid var(--line); margin-top: 8px; }
.fact { background: var(--ground); padding: 16px 18px; }
.band.sunk .fact { background: var(--panel); }
.fact p { margin: 0; color: var(--dim); font-size: 13.5px; }
/* ------------------------------------------------------------------ stats */
.stats {
display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 1px; margin-top: 24px; background: var(--line); border: 1px solid var(--line);
}
.stat { background: var(--ground); padding: 18px 20px; }
.band.sunk .stat { background: var(--panel); }
/* Число — главное, ради чего блок существует: масштаб архива не читается из
слова «35 дней». Поэтому оно крупнее заголовка секции. */
.stat-n {
font-size: clamp(24px, 4vw, 34px); font-weight: 600;
font-variant-numeric: tabular-nums; letter-spacing: -0.02em; line-height: 1.1;
}
.stat-l { font-size: 11px; letter-spacing: 0.13em; text-transform: uppercase; color: var(--dim); margin-top: 6px; }
/* ------------------------------------------------------------- form fields */
.field { margin: 0 0 14px; }
.field:first-of-type { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--line); }
.field label { display: block; margin-bottom: 5px; }
.field .req { color: var(--warn); }
.field input {
width: 100%;
padding: 9px 11px;
font: inherit;
font-size: 14px;
color: var(--ink);
background: var(--ground);
border: 1px solid var(--line);
box-sizing: border-box;
}
.band.sunk .field input { background: var(--panel); }
.field input:focus { outline: none; border-color: var(--ink); }
.field input::placeholder { color: var(--dim); }
/* Состояние поля показывается рамкой, а не только текстом: подпись под полем
легко пропустить, а цветную границу видно боковым зрением. */
.field input.bad { border-color: var(--warn); }
.field input.good { border-color: var(--signal); }
.field .hint { display: block; font-size: 12px; margin-top: 5px; color: var(--dim); }
.field .hint.bad { color: var(--warn); }
.field .hint.good { color: var(--signal); }
#rp-voucher { text-transform: uppercase; letter-spacing: 0.06em; }
/* -------------------------------------------------------- price breakdown */
/* Разбор цены прячется под <details>: покупателю обычно хватает суммы, но
когда в диапазоне неполные дни, «почему столько» — первый же вопрос. */
.rp-calc { margin-top: 6px; font-size: 12.5px; }
.rp-calc summary { cursor: pointer; color: var(--dim); }
.rp-calc summary:hover { color: var(--ink); }
.rp-calc table { min-width: 0; margin-top: 10px; font-size: 12.5px; }
.rp-calc td { padding: 5px 12px 5px 0; border-bottom: 1px solid var(--line); }
.rp-calc td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
.rp-calc tr.sum td { border-bottom: 0; border-top: 1px solid var(--ink); font-weight: 600; }
.rp-calc .note { color: var(--dim); margin-top: 10px; }
/* --------------------------------------------------------- range picker */
.picker { margin-top: 8px; }
.rp-state { font-size: 13.5px; color: var(--dim); }
.rp-state.err { color: var(--warn); }
.rp-nav { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.rp-month { font-size: 14px; letter-spacing: 0.04em; }
.rp-nav-btn {
font-family: inherit; font-size: 12px;
background: none; border: 1px solid var(--line); color: var(--ink);
padding: 6px 12px; cursor: pointer;
}
.rp-nav-btn:hover:not(:disabled) { border-color: var(--ink); }
.rp-nav-btn:disabled { color: var(--dim); cursor: not-allowed; }
.rp-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; max-width: 420px; }
.rp-dow { font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); text-align: center; padding-bottom: 4px; }
.rp-cell {
position: relative;
aspect-ratio: 1;
display: flex; align-items: center; justify-content: center;
font-family: inherit; font-size: 13px; font-variant-numeric: tabular-nums;
background: none; border: 1px solid transparent; color: var(--ink);
cursor: pointer; padding: 0;
}
.rp-cell.empty { visibility: hidden; cursor: default; }
.rp-cell.unavailable { color: var(--dim); opacity: 0.45; cursor: not-allowed; }
.rp-cell.available:hover:not(.selected-edge) { border-color: var(--dim); }
.rp-cell.in-range { background: var(--line); }
.rp-cell.selected-edge { background: var(--signal); border-color: var(--signal); color: var(--ground); }
/* Completeness stripe. Length is the share of streams present, colour flags
a collection gap. Shape carries the main quantity so the cell still reads
without colour vision. */
.rp-mark {
position: absolute; left: 50%; transform: translateX(-50%);
bottom: 3px; width: 62%; height: 2px; background: var(--line);
}
.rp-mark > i { display: block; height: 100%; background: var(--ink); }
.rp-mark.gap > i { background: var(--warn); }
.rp-cell.selected-edge .rp-mark { background: rgba(255,255,255,0.35); }
.rp-cell.selected-edge .rp-mark > i { background: var(--ground); }
.rp-cell.selected-edge .rp-mark.gap > i { background: var(--warn); }
.rp-legend { display: flex; flex-wrap: wrap; gap: 8px 20px; margin: 16px 0 0; font-size: 12px; color: var(--dim); }
.rp-legend-item { display: flex; align-items: center; gap: 8px; }
.rp-legend-bar { display: block; width: 24px; height: 2px; background: var(--line); flex: none; }
.rp-legend-bar > i { display: block; height: 100%; background: var(--ink); }
.rp-legend-bar.gap > i { background: var(--warn); }
.rp-summary {
display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between;
gap: 8px 24px; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line);
}
/* Оба столбца тянутся по содержимому, а не по высоте соседа: цена с тремя
строками пояснения не должна отталкивать «Selection» вниз, оставляя над ним
дыру в половину экрана. */
.rp-summary > * { margin: 0; }
.rp-selection { font-size: 13.5px; }
.rp-price { text-align: right; }
.amount { font-size: 30px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; }
.rp-price .dim { display: block; font-size: 12px; margin-top: 2px; max-width: 46ch; margin-left: auto; }
.rp-status { margin-top: 10px; font-size: 13px; color: var(--warn); }
/* The one filled element on the page. Everything else is type and rules, so
a solid block reads as "this is the action" without a second accent. */
.buy {
display: inline-block; margin-top: 20px;
font-family: inherit; font-size: 13px; font-weight: 600;
letter-spacing: 0.06em; text-transform: uppercase;
padding: 14px 28px;
background: var(--signal); border: 1px solid var(--signal); color: var(--ground);
cursor: pointer; transition: transform 0.12s ease;
}
.buy:hover:not(:disabled) { transform: translateY(-2px); }
.buy:active:not(:disabled) { transform: none; }
.buy:disabled { background: none; color: var(--dim); border-color: var(--line); cursor: not-allowed; }
/* -------------------------------------------------------------- products */
.product {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px 24px;
padding: 22px 0;
border-top: 1px solid var(--line);
}
.product:last-of-type { border-bottom: 1px solid var(--line); }
.product h3 { font-size: 17px; letter-spacing: -0.01em; margin-bottom: 2px; }
.product .price { font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; white-space: nowrap; }
.product .price small { display: block; font-size: 10.5px; font-weight: 400; letter-spacing: 0.14em; text-transform: uppercase; color: var(--dim); margin-top: 2px; }
.product ul { margin: 10px 0 0; padding-left: 18px; color: var(--dim); font-size: 13.5px; }
.product li { margin-bottom: 3px; }
.product .meta { grid-column: 1 / -1; font-size: 12px; color: var(--dim); }
/* Checkout for the two code products. One set of fields, two buttons: the
buyer fills the email once and then picks an edition, rather than meeting
the same two inputs twice on one page. */
.editions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 20px; }
.editions .buy { margin-top: 0; flex: 1 1 240px; text-align: center; }
.editions .buy small {
display: block; font-size: 10px; font-weight: 400; letter-spacing: 0.1em;
opacity: 0.75; margin-top: 3px;
}
/* The second edition is the same action, not a lesser one — outlined so the
pair does not read as "recommended" and "other". */
.editions .buy.alt { background: none; color: var(--signal); }
.editions .buy.alt:hover:not(:disabled) { transform: translateY(-2px); }
/* Inline identifiers only (column and command names in the prose). The block
<pre> rules went with the API section that used them. */
code { font-size: 0.94em; }
footer { padding: 40px 0 64px; border-top: 1px solid var(--line); color: var(--dim); font-size: 12.5px; }
footer p { max-width: 76ch; }
:focus-visible { outline: 2px solid var(--signal); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
@media (max-width: 600px) {
.band { padding: 40px 0; }
.rp-price { text-align: left; }
.buy { display: block; width: 100%; text-align: center; }
}
</style>
</head>
<body>
<div class="wrap">
<header class="top">
<span>Polymarket microstructure</span>
<nav>
<a href="#pricing">Pricing</a>
<a href="#files">Files</a>
<a href="#code">Code</a>
</nav>
<div class="tabs" id="tabs" role="tablist" aria-label="What is on sale" hidden>
<button type="button" class="tab" id="tab-data" role="tab"
aria-controls="panel-data" aria-selected="true">Datasets</button>
<button type="button" class="tab" id="tab-bots" role="tab"
aria-controls="panel-bots" aria-selected="false">Trading bots</button>
</div>
</header>
</div>
<div id="panel-data" role="tabpanel" aria-labelledby="tab-data">
<div class="wrap hero">
<h1>Polymarket order book data</h1>
<p class="lede">Tick-level quotes, trades and L2 depth from the 5-minute up/down markets on BTC, ETH, SOL and XRP. Parquet, one file per asset per UTC day, every manifest carrying a sha256.</p>
<dl class="specs">
<div><dt>Assets</dt><dd>BTC ETH SOL XRP</dd></div>
<div><dt>From</dt><dd class="num">30 Jun 2026</dd></div>
<div><dt>Format</dt><dd>Parquet, zstd-6</dd></div>
<div><dt>Price</dt><dd class="num">$3&ndash;5 / day</dd></div>
</dl>
</div>
<section class="band" id="scale">
<div class="wrap">
<div class="eyebrow">Archive size</div>
<h2>What has been recorded so far</h2>
<p class="dim" style="font-size:14px">Counted across the whole collection period, not just the days on sale. Refreshed once a day.</p>
<div class="stats" id="stats" hidden>
<div class="stat"><div class="stat-n" id="st-markets">&mdash;</div><div class="stat-l">markets recorded</div></div>
<div class="stat"><div class="stat-n" id="st-rows">&mdash;</div><div class="stat-l">rows across six streams</div></div>
<div class="stat"><div class="stat-n" id="st-span">&mdash;</div><div class="stat-l">days of collection</div></div>
</div>
<div class="scroll" id="stats-tables" hidden>
<table class="rates" style="min-width:420px">
<thead><tr><th>Asset</th><th>5-minute</th><th>15-minute</th><th>Total</th></tr></thead>
<tbody id="st-assets"></tbody>
</table>
</div>
<p class="dim" id="st-note" style="font-size:12px;margin-top:12px"></p>
</div>
</section>
<section class="band sunk" id="limits">
<div class="wrap">
<div class="eyebrow">Read first</div>
<h2>Read this part first</h2>
<p class="dim">Four caveats, up here rather than in a footnote. If any one of them matters to your use case, nothing else on this page will help.</p>
<div class="facts">
<div class="fact">
<h3>The snapshots are top-of-book</h3>
<p>Best bid, best ask, and that is the whole of it. There are <code>level</code> and <code>size</code> columns, but they exist to keep the schema stable across tables, and every row has them at 0. A reconstructed ladder is a different table — and it does not reach all the way back.</p>
</div>
<div class="fact">
<h3>Depth starts 20 July 2026</h3>
<p>Fifteen days of the thirty-five have it. Everything before is quotes, trades and spot candles: still fine for flow and spread work, useless if you came to model the book. That gap is exactly why those days bill at 55% of a full one.</p>
</div>
<div class="fact">
<h3>The clock changes partway through</h3>
<p>Up to 20 July the timestamp is <code>ts</code> — our receipt time, rounded to the second. Ordering inside a second is gone and cannot be recovered. If your model cares about sequence at that resolution, buy from 21 July on, where <code>ts_ms</code> is exchange time in milliseconds.</p>
</div>
<div class="fact">
<h3>Uptime is measured, not claimed</h3>
<p>It runs from 95.8% to 100%, depending on the day. Each day carries its own figure rather than an average across the archive; the calendar shows it, and the price is computed from it.</p>
</div>
</div>
</div>
</section>
<section class="band" id="pricing">
<div class="wrap">
<div class="eyebrow">Pricing</div>
<h2>Pick a range, pay by the day</h2>
<p class="dim">Every purchase covers all four assets, and whatever streams existed on the dates you pick. Longer ranges are cheaper per day.</p>
<div class="scroll">
<table class="rates">
<thead><tr><th>Range</th><th>Rate</th><th>Example</th></tr></thead>
<tbody>
<tr><td>1&ndash;6 days</td><td>$5 / day</td><td class="num">3 days, $15</td></tr>
<tr><td>7&ndash;29 days</td><td>$4 / day</td><td class="num">10 days, $40</td></tr>
<tr><td>30+ days</td><td>$3 / day</td><td class="num">30 days, $90</td></tr>
</tbody>
</table>
</div>
<p class="dim" style="font-size:13px;margin-top:14px">Two rules keep the arithmetic honest. Days holding no data are not counted at all, so a range that straddles a gap costs less than its calendar length suggests. And a longer range never costs less than a shorter one — which is why the total flattens at $90 anywhere between 23 and 30 days.</p>
<div class="picker" id="range-picker">
<p class="rp-state" id="rp-state">Loading available dates.</p>
<div id="rp-calendar" hidden>
<div class="rp-nav">
<button type="button" class="rp-nav-btn" id="rp-prev" aria-label="Previous month">Prev</button>
<span class="rp-month num" id="rp-month-label"></span>
<button type="button" class="rp-nav-btn" id="rp-next" aria-label="Next month">Next</button>
</div>
<div class="rp-grid" id="rp-grid"></div>
<div class="rp-legend">
<span class="rp-legend-item"><span class="rp-legend-bar"><i style="width:100%"></i></span> All six streams</span>
<span class="rp-legend-item"><span class="rp-legend-bar"><i style="width:55%"></i></span> No depth, charged at 55%</span>
<span class="rp-legend-item"><span class="rp-legend-bar gap"><i style="width:100%"></i></span> Collection gap</span>
</div>
<p class="dim" style="font-size:12px;margin-top:8px;max-width:none">The stripe under each date is that day's completeness: length is the share of streams present, amber means the collector lost time. You pay for the full-day equivalent, so a patchy stretch costs proportionally less. If the total surprises you, open the breakdown under the price — it shows every step of the sum.</p>
<div class="rp-summary">
<div>
<div class="eyebrow" style="margin-bottom:4px">Selection</div>
<div class="rp-selection" id="rp-selection-text">No dates selected</div>
</div>
<div class="rp-price" id="rp-price"></div>
</div>
<details class="rp-calc" id="rp-calc" hidden>
<summary>How this price is worked out</summary>
<div id="rp-calc-body"></div>
</details>
<div class="field">
<label for="rp-email" class="eyebrow">Email <span class="req">(required)</span></label>
<input id="rp-email" type="email" autocomplete="email" required placeholder="you@example.com">
<span class="hint" id="rp-email-hint">Your download link is emailed here. It is the only way back to your files if you switch device or clear your browser.</span>
</div>
<div class="field">
<label for="rp-voucher" class="eyebrow">Voucher code <span class="dim">(optional)</span></label>
<input id="rp-voucher" type="text" autocomplete="off" spellcheck="false" placeholder="CODE" maxlength="32">
<span class="hint" id="rp-voucher-hint">Checked at checkout. Leave empty if you have none.</span>
</div>
<button class="buy" id="rp-buy" disabled>Select dates</button>
<p class="rp-status" id="rp-status"></p>
</div>
</div>
</div>
</section>
<section class="band sunk" id="files">
<div class="wrap">
<div class="eyebrow">Files</div>
<h2>What ships</h2>
<p class="dim">One Parquet file per asset, per table, per day. Each ships with a manifest carrying its sha256, row count and interval bounds, so a download can be verified without taking our word for it.</p>
<div class="scroll">
<table>
<thead><tr><th>Table</th><th>Time column</th><th>Contents</th><th>Available</th></tr></thead>
<tbody>
<tr><td>book_snaps</td><td>ts, ts_ms</td><td>Best bid and ask</td><td>All days</td></tr>
<tr><td>book_depth</td><td>ts_ms</td><td>Ladder levels: price, size, side. Around 88 per event.</td><td>From 20 Jul</td></tr>
<tr><td>clob_trades</td><td>ts</td><td>Trades with taker side</td><td>All days</td></tr>
<tr><td>clob_trades_ws</td><td>ts_ms</td><td>Trade stream with tx hash and fee, for VPIN</td><td>From 21 Jul</td></tr>
<tr><td>spot_klines</td><td>ts</td><td>Spot candles for the underlying</td><td>All days</td></tr>
<tr><td>book_meta</td><td>ts_ms</td><td>Market parameters. In practice only book_hash is populated.</td><td>From 21 Jul</td></tr>
</tbody>
</table>
</div>
<p style="margin-top:20px">Four days — 26 to 29 June — are up for free. Read the schema and the file layout before you spend anything. <a href="https://huggingface.co/datasets/astrnvk/polymarket-orderbook-data-preview">Preview on Hugging Face</a></p>
<p style="margin-top:14px"><strong>Labels are a separate, free download.</strong> The day files are microstructure only. The market metadata, the settled outcomes and the collector's own record of where it lost time live in three small files — <span class="m">markets.parquet</span>, <span class="m">resolutions.parquet</span>, <span class="m">gaps.parquet</span> — in the <a href="https://huggingface.co/datasets/astrnvk/polymarket-orderbook-data-preview/tree/main/refs">refs/ folder of the preview repository</a>. If you plan to train anything supervised you need them: the outcome is the answer your model is learning to predict. They cover the whole archive, so one download covers any range you buy.</p>
</div>
</section>
<section class="band" id="delivery">
<div class="wrap">
<div class="eyebrow">Delivery</div>
<h2>Getting the files</h2>
<p>Payment goes through Plisio, in crypto. Once it confirms you get a download list good for thirty days, with a request budget sized to your order. The bytes come straight from storage and never pass through our server.</p>
<p>A month is several hundred files. Clicking through them by hand is nobody's idea of a good evening, so the order page hands over the whole list as one text file, with a ready-made command under it for Linux, macOS and PowerShell.</p>
<p>If the data disagrees with what this page says, you get your money back. That is the whole reason the caveats sit at the top and not down here in the small print.</p>
</div>
</section>
</div><!-- /panel-data -->
<div id="panel-bots" role="tabpanel" aria-labelledby="tab-bots">
<div class="wrap hero">
<h1>The code that trades on it</h1>
<p class="lede">The collector, the feature and model pipeline, the decision loop with its risk limits, and a Telegram bot you run all of it from. Two editions: one that simulates every fill, one that places the orders.</p>
<dl class="specs">
<div><dt>Editions</dt><dd>Paper · Live</dd></div>
<div><dt>Price</dt><dd class="num">$149 · $399</dd></div>
<div><dt>Licence</dt><dd>One buyer, source included</dd></div>
<div><dt>Models</dt><dd>Not included</dd></div>
</dl>
</div>
<section class="band" id="code">
<div class="wrap">
<div class="eyebrow">What this is</div>
<h2>Working infrastructure, not a strategy</h2>
<p class="dim">The same stack that collects this dataset also trades on it. One payment, no subscription, no seats: source, an installer that takes a bare Ubuntu server to a running bot in about half an hour, and the pipeline that trains the models. The models themselves are not included — you train those on your own data, and they are yours.</p>
<div class="product">
<div>
<h3>Paper simulator</h3>
<p class="dim" style="font-size:13.5px;margin:0">Runs the whole loop against live market data without ever placing an order. What you are buying is the plumbing: already built, already running, not sketched.</p>
<ul>
<li>Collector: Polymarket websocket and REST into PostgreSQL, with gap detection</li>
<li>Fill simulation with maker/taker fees, spread and settlement against resolutions</li>
<li>Feature builder, LightGBM training pipeline and walk-forward validation gates</li>
<li>Trade ledger in Parquet, Telegram control bot, web dashboard</li>
<li>Gate A, B and C: what may be trained, what may be deployed, and when it has decayed</li>
</ul>
</div>
<div class="price">$149<small>one-time</small></div>
</div>
<div class="product">
<div>
<h3>Live trader</h3>
<p class="dim" style="font-size:13.5px;margin:0">Everything above, except it actually places the orders on the Polymarket CLOB.</p>
<ul>
<li>Signed CLOB order placement, position tracking and reconciliation</li>
<li>Wallet credentials connected from Telegram and stored encrypted — never in a config file</li>
<li>Risk limits: bet size, open positions, daily loss cap, entry price ceiling</li>
<li>Regime router: twelve models across four assets and three market phases</li>
<li>Kill switch and paper/live toggle from Telegram</li>
</ul>
</div>
<div class="price">$399<small>one-time</small></div>
</div>
<div class="product">
<div class="meta">
<strong>On performance.</strong> The strategy this code implements was net negative over the author's own measured sample: about −$277 across 4 280 paper trades, −$371 across 4 722 in the live configuration, at a 47% hit rate against a break-even near 49%. No real order has ever been placed by the author — the execution path is written and exercised against the API, but every one of those trades was simulated. And since no models ship with it, a fresh install has no view of its own at all until you train one, which needs a fortnight of collected data before the gates will allow it. This is sold as working infrastructure, not as a profitable strategy. If you want a bot that makes money out of the box, do not buy this.
</div>
</div>
<div class="facts" style="margin-top:22px">
<div class="fact">
<h3>Configured from Telegram</h3>
<p>Position size, how many trades at once, the daily loss cap, the entry price ceiling — all set from chat, applied to the running bot, no restart. The live edition takes your wallet the same way: a guided prompt that deletes the message with the key in it and stores the key encrypted.</p>
</div>
<div class="fact">
<h3>You bring the models</h3>
<p><code>artifacts/</code> arrives empty. Gate A will not let you train on less than two weeks of collected data, and until there is a model the bot runs, reports and holds. Buying a month of recorded history from the <a href="#pricing">datasets</a> is the only way to shorten that wait. A first Gate B verdict of <code>FAIL</code> is the ordinary outcome, not a defect.</p>
</div>
<div class="fact">
<h3>You need a server and disk</h3>
<p>Two cores and 4 GB of RAM are enough, but recording the full book is 25–40 GB a day. The docs cover keeping a window instead, or trimming what you record — and training is hours of CPU you should not run on the box that is collecting.</p>
</div>
<div class="fact">
<h3>What arrives</h3>
<p>A tarball with the source, an idempotent <code>install.sh</code>, systemd units, the database schema in one file, and documentation written for someone who has not seen the code before. A manifest carries a sha256 for every file in it.</p>
</div>
<div class="fact">
<h3>Licence and support</h3>
<p>One buyer, any number of your own machines, source included and yours to modify. No redistribution and no running it as a service for other people. Support covers installation and defects — not strategy design.</p>
</div>
</div>
<div class="picker" id="bot-checkout">
<div class="field">
<label for="bot-email" class="eyebrow">Email <span class="req">(required)</span></label>
<input id="bot-email" type="email" autocomplete="email" required placeholder="you@example.com">
<span class="hint" id="bot-email-hint">The download link is emailed here. It is the only way back to the archive if you switch device or clear your browser.</span>
</div>
<div class="field">
<label for="bot-voucher" class="eyebrow">Voucher</label>
<input id="bot-voucher" type="text" autocomplete="off" spellcheck="false" placeholder="CODE" maxlength="32">
<span class="hint">Checked at checkout. Leave empty if you have none.</span>
</div>
<div class="editions">
<button class="buy" id="buy-paper" data-sku="bot-paper" disabled>Buy paper simulator<small>$149 one-time</small></button>
<button class="buy alt" id="buy-live" data-sku="bot-live" disabled>Buy live trader<small>$399 one-time</small></button>
</div>
<p class="rp-status" id="bot-status"></p>
<p class="dim" style="font-size:12px;margin-top:12px">Payment goes through Plisio, in crypto, same as the datasets. The archive is a single download from the same storage, and the link is good for thirty days — keep a copy of what you download.</p>
</div>
<p style="margin-top:22px">Questions before buying? Message <a href="https://t.me/Datasets_support_bot">@Datasets_support_bot</a>.</p>
</div>
</section>
</div><!-- /panel-bots -->
<footer>
<div class="wrap">
<p>Collected from the public Polymarket API. Not affiliated with Polymarket. Sold as-is, for research. Nothing here is trading advice.</p>
<p style="margin-top:10px">Questions, or paid and got nothing? Message <a href="https://t.me/Datasets_support_bot">@Datasets_support_bot</a> with your order id.</p>
</div>
</footer>
<script>
const FUNCTIONS_URL = "https://otaolntxdltbyojbbyhg.supabase.co/functions/v1";
// Public anon key. Safe to ship in client code: it only grants what the
// Supabase gateway allows anonymous callers, and the gateway requires it on
// every PostgREST call.
const ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im90YW9sbnR4ZGx0YnlvamJieWhnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODQ2NjMxNTIsImV4cCI6MjEwMDIzOTE1Mn0.8Axxbhd2vIRaQzXqOcKf-L6lTzrbuUybZlOHC9a6TaM";
// ------------------------------------------------------------------- tabs
//
// Two products on one static page. Splitting them is a display decision and
// nothing more: both panels are in the document either way, so a reader
// without JavaScript gets the page as it always was — everything, in order —
// rather than half a shop and two dead buttons. That is also why the tab strip
// itself is `hidden` in the markup and revealed here.
//
// The hash is the state: /#bots is shareable, survives a reload, and the old
// section anchors (#pricing, #files, #code) keep working by resolving to
// whichever panel contains them.
(function tabs() {
const strip = document.getElementById("tabs");
const panels = {
data: document.getElementById("panel-data"),
bots: document.getElementById("panel-bots"),
};
const buttons = {
data: document.getElementById("tab-data"),
bots: document.getElementById("tab-bots"),
};
if (!strip || !panels.data || !panels.bots) return;
const names = ["data", "bots"];
function show(name, opts) {
const options = opts || {};
names.forEach((n) => {
panels[n].hidden = n !== name;
buttons[n].setAttribute("aria-selected", String(n === name));
});
if (options.focus) buttons[name].focus();
// Replace rather than push: the tabs are a view switch, and a back button
// that walks through every tab you glanced at is not what anyone wants.
if (options.hash !== false) {
history.replaceState(null, "",
name === "data" ? location.pathname + location.search : "#" + name);
}
}
// Which panel owns a given element — used to resolve an anchor like #code
// into the tab that has to be open before scrolling to it.
function panelOf(el) {
for (const n of names) if (panels[n].contains(el)) return n;
return null;
}
function fromHash() {
const raw = (location.hash || "").replace(/^#/, "");
if (!raw) return { tab: "data", target: null };
if (raw === "bots" || raw === "code") return { tab: "bots", target: null };
if (raw === "data" || raw === "datasets") return { tab: "data", target: null };
const target = document.getElementById(raw);
const owner = target && panelOf(target);
return { tab: owner || "data", target: owner ? target : null };
}
names.forEach((name) => {
buttons[name].addEventListener("click", () => {
show(name);
window.scrollTo({ top: 0, behavior: "smooth" });
});
});
// Left/right arrows move between tabs, which is what a tablist is expected
// to do once it announces itself as one.
strip.addEventListener("keydown", (e) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
const current = buttons.data.getAttribute("aria-selected") === "true" ? 0 : 1;
const next = names[(current + (e.key === "ArrowRight" ? 1 : names.length - 1)) % names.length];
e.preventDefault();
show(next, { focus: true });
});
// Any in-page link that points into the other panel switches to it first.
// Without this the browser scrolls to a hidden element and nothing happens,
// which is exactly how the footer and the cross-sell links would break.
document.addEventListener("click", (e) => {
const link = e.target.closest && e.target.closest('a[href^="#"]');
if (!link) return;
const id = link.getAttribute("href").slice(1);
if (!id) return;
const target = document.getElementById(id);
if (!target) return;
const owner = panelOf(target);
if (owner && panels[owner].hidden) {
e.preventDefault();
show(owner, { hash: false });
target.scrollIntoView({ behavior: "smooth", block: "start" });
history.replaceState(null, "", "#" + id);
}
});
window.addEventListener("hashchange", () => {
const { tab, target } = fromHash();
show(tab, { hash: false });
if (target) target.scrollIntoView({ block: "start" });
});
const initial = fromHash();
show(initial.tab, { hash: false });
strip.hidden = false;
// The old anchor nav duplicated what the tabs now do, across panels where
// half its links would jump into hidden content.
const nav = document.querySelector(".top nav");
if (nav) nav.hidden = true;
if (initial.target) initial.target.scrollIntoView({ block: "start" });
})();
// ------------------------------------------------------------ range picker
//
// The buyer picks a start and end date. The price is estimated client-side
// over however many days inside that range actually hold data, weighted by
// how complete each one is. The server recomputes and owns the real price at
// create-invoice time; this is display only.
// Размер архива. Отдельный запрос к shop.dataset_stats — снимок, который раз
// в сутки обновляет automation/sync_dataset_stats.py. Живого счётчика тут быть
// не может: витрина статическая, а считать миллиарды строк на каждый заход
// никто не станет.
//
// Блок скрыт, пока цифры не пришли: пустая рамка с прочерками выглядит хуже,
// чем её отсутствие, а страница без него остаётся связной.
(async function archiveStats() {
const REST = FUNCTIONS_URL.replace(/\/functions\/v1$/, "") + "/rest/v1";
let row;
try {
const res = await fetch(REST + "/dataset_stats?select=*&limit=1", {
headers: { apikey: ANON, authorization: "Bearer " + ANON, "accept-profile": "shop" },
});
if (!res.ok) return;
row = (await res.json())[0];
} catch (e) {
return;
}
if (!row) return;
// Миллиарды прописью: «5 688 275 391» не читается, «5.69 billion» читается.
const big = (n) =>
n >= 1e9 ? (n / 1e9).toFixed(2) + " billion"
: n >= 1e6 ? (n / 1e6).toFixed(1) + " million"
: n.toLocaleString("en-US");
const grouped = (n) => n.toLocaleString("en-US");
document.getElementById("st-markets").textContent = grouped(row.markets_total);
document.getElementById("st-rows").textContent = big(row.rows_total);
const days = row.first_day && row.last_day
? Math.round((Date.parse(row.last_day) - Date.parse(row.first_day)) / 864e5) + 1
: null;
document.getElementById("st-span").textContent = days === null ? "—" : String(days);
document.getElementById("stats").hidden = false;
// Разбивка по активам: 5-минутные и 15-минутные окна — разные рынки, и
// покупателю важно, что есть оба горизонта.
const byAsset = row.by_asset || [];
const assets = [...new Set(byAsset.map((x) => x.asset))].sort();
if (assets.length) {
const pick = (a, iv) => {
const hit = byAsset.find((x) => x.asset === a && x.interval_sec === iv);
return hit ? hit.markets : 0;
};
document.getElementById("st-assets").innerHTML = assets.map((a) => {
const m5 = pick(a, 300), m15 = pick(a, 900);
return "<tr><td>" + a.toUpperCase() + "</td><td>" + grouped(m5) +
"</td><td>" + grouped(m15) + "</td><td>" + grouped(m5 + m15) + "</td></tr>";
}).join("");
document.getElementById("stats-tables").hidden = false;
}
const when = row.captured_at ? new Date(row.captured_at) : null;
const rowsNote = (row.by_table || [])
.map((t) => t.table + " " + big(t.rows))
.join(", ");
document.getElementById("st-note").textContent =
"Covers " + (row.first_day || "?") + " to " + (row.last_day || "?") +
", the entire collection period — the archive on sale starts later. " +
"Row counts are planner estimates, accurate to within a percent or so" +
(rowsNote ? ": " + rowsNote : "") + "." +
(when ? " Updated " + when.toISOString().slice(0, 16).replace("T", " ") + " UTC." : "");
})();
(function rangePicker() {
const root = document.getElementById("range-picker");
if (!root) return;
const stateEl = document.getElementById("rp-state");
const calendarEl = document.getElementById("rp-calendar");
const prevBtn = document.getElementById("rp-prev");
const nextBtn = document.getElementById("rp-next");
const monthLabel = document.getElementById("rp-month-label");
const gridEl = document.getElementById("rp-grid");
const selectionText = document.getElementById("rp-selection-text");
const priceEl = document.getElementById("rp-price");
const buyBtn = document.getElementById("rp-buy");
const statusEl = document.getElementById("rp-status");
const DOW = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
const MONTH_NAMES = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
function pad2(n) { return String(n).padStart(2, "0"); }
function ymd(y, m, d) { return y + "-" + pad2(m + 1) + "-" + pad2(d); } // m is 0-based
// Tiered per-day pricing, mirroring supabase/functions/_shared/pricing.ts
// exactly: 1-6 days $5/day, 7-29 $4/day, 30+ $3/day, then clamped so a
// longer range is never cheaper than a shorter one.
//
// The clamp is not cosmetic. Without it 6 days ($30) would cost more than
// 7 ($28), and 29 ($116) more than 30 ($90), so the total would visibly
// drop as the buyer dragged the range wider.
const MAX_RANGE_DAYS = 366;
const PRICE = (function buildPriceTable() {
const rate = (n) => (n <= 6 ? 5 : n <= 29 ? 4 : 3);
const table = new Array(MAX_RANGE_DAYS + 1);
table[0] = 0;
let best = Infinity;
for (let n = MAX_RANGE_DAYS; n >= 1; n--) {
best = Math.min(best, rate(n) * n);
table[n] = best;
}
return table;
})();
function priceForDays(n) {
if (!Number.isInteger(n) || n < 1 || n > MAX_RANGE_DAYS) return null;
return PRICE[n];
}
// Зеркало priceForEquivalent из pricing.ts: тарифная таблица дискретна,
// между целыми интерполируем. Округление до целого числа дней съедало всю
// скидку на коротких диапазонах — день с 54% потоков стоил как полный.
// $28, но $2.75 — хвост .00 у круглой суммы только шумит.
function money(x) {
return x.toFixed(2).replace(/\.00$/, "");
}
function priceForEquivalent(x) {
if (!isFinite(x)) return null;
if (x <= 0) return 0.01;
if (x >= MAX_RANGE_DAYS) return PRICE[MAX_RANGE_DAYS];
const w = Math.floor(x), f = x - w;
return Math.max(Math.round((PRICE[w] + (PRICE[w + 1] - PRICE[w]) * f) * 100) / 100, 0.01);
}
function perDayRate(n) {
const p = priceForDays(n);
return p === null ? null : p / n;
}
// Server test vectors (see pricing.test.ts):
// 1=5 5=25 6=28 7=28 8=32 13=52 22=88 29=90 30=90 31=93 366=1098
// Stream weights, an exact mirror of STREAM_WEIGHTS in pricing.ts. They sum
// to 1.0: a day carrying all six streams weighs one full day. Edit both
// files together or the estimate here drifts from the invoice.
const STREAM_WEIGHTS = {
book_snaps: 0.30,
book_depth: 0.30,
clob_trades: 0.15,
clob_trades_ws: 0.10,
spot_klines: 0.10,
book_meta: 0.05,
};
// Below this uptime a day is flagged as having a collection gap. 0.995 is
// about 7 minutes out of 1440; anything smaller is measurement noise, not
// something worth warning a buyer about.
const GAP_THRESHOLD = 0.995;
function dayWeight(info) {
if (!info) return 0;
let streams = 0;
for (const t of (info.tables || [])) streams += STREAM_WEIGHTS[t] || 0;
if (streams > 1) streams = 1;
const cov = info.coverage == null ? 1 : Number(info.coverage);
const uptime = isFinite(cov) ? Math.min(Math.max(cov, 0), 1) : 1;
return streams * uptime;
}
// Mirror of chargeableDays: sum of weights, rounded, floored at one day so
// a range of nothing but incomplete days is never free.
function chargeableDays(dates) {
let sum = 0;
for (const d of dates) sum += dayWeight(dayInfo.get(d));
// Округление до 4 знаков: веса вроде 0.55 неточны в плавающей точке, и
// неделя полных дней иначе складывается в 6.999999999999999.
return Math.round(sum * 10000) / 10000;
}
let availableDays = []; // sorted "YYYY-MM-DD" strings, from the API
let availableSet = new Set();
let dayInfo = new Map(); // "YYYY-MM-DD" -> {tables, coverage}
let minY, minM, maxY, maxM; // calendar bounds, from min/max available day
let cursorY, cursorM; // month on screen (0-based month)
let rangeStart = null;
let rangeEnd = null; // null while only one date is picked
// availableDays is sorted (the API is called with order=day), so a linear
// scan with an early break is enough at this size.
function availableDatesInRange(start, end) {
const out = [];
for (const d of availableDays) {
if (d < start) continue;
if (d > end) break;
out.push(d);
}
return out;
}
function countAvailableInRange(start, end) {
return availableDatesInRange(start, end).length;
}
function effectiveRange() {
if (!rangeStart) return null;
const s = rangeStart;
const e = rangeEnd || rangeStart; // one date picked so far, treat as 1 day
return s <= e ? [s, e] : [e, s];
}
function showState(kind, msg) {
stateEl.hidden = false;
stateEl.className = "rp-state" + (kind === "err" ? " err" : "");
stateEl.textContent = msg;
calendarEl.hidden = true;
}
function formatRangeLabel(s, e) {
return s === e ? s : s + " to " + e;
}
function renderMonth() {
monthLabel.textContent = MONTH_NAMES[cursorM] + " " + cursorY;
prevBtn.disabled = cursorY === minY && cursorM === minM;
nextBtn.disabled = cursorY === maxY && cursorM === maxM;
gridEl.innerHTML = "";
const frag = document.createDocumentFragment();
DOW.forEach((label) => {
const el = document.createElement("div");
el.className = "rp-dow";
el.textContent = label;
frag.appendChild(el);
});
const firstDow = new Date(Date.UTC(cursorY, cursorM, 1)).getUTCDay();
const daysInMonth = new Date(Date.UTC(cursorY, cursorM + 1, 0)).getUTCDate();
const range = effectiveRange();
for (let i = 0; i < firstDow; i++) {
const el = document.createElement("button");
el.type = "button";
el.className = "rp-cell empty";
el.disabled = true;
el.tabIndex = -1;
frag.appendChild(el);
}
for (let d = 1; d <= daysInMonth; d++) {
const dateStr = ymd(cursorY, cursorM, d);
const isAvailable = availableSet.has(dateStr);
const el = document.createElement("button");
el.type = "button";
el.textContent = String(d);
let cls = "rp-cell " + (isAvailable ? "available" : "unavailable");
if (range) {
const [s, e] = range;
if (dateStr === s || dateStr === e) cls += " selected-edge";
else if (dateStr > s && dateStr < e) cls += " in-range";
}
el.className = cls;
if (isAvailable) {
const info = dayInfo.get(dateStr) || {};
const streams = (info.tables || []).length;
const cov = info.coverage == null ? 1 : Number(info.coverage);
const hasGap = cov < GAP_THRESHOLD;
// Stripe length is the share of streams, ignoring uptime: uptime is
// carried by colour, so one mark never encodes the same figure twice.
let streamShare = 0;
for (const t of (info.tables || [])) streamShare += STREAM_WEIGHTS[t] || 0;
const mark = document.createElement("span");
mark.className = "rp-mark" + (hasGap ? " gap" : "");
const fill = document.createElement("i");
fill.style.width = Math.round(Math.min(streamShare, 1) * 100) + "%";
mark.appendChild(fill);
el.appendChild(mark);
el.title = dateStr + ": " + streams + " of 6 streams" +
(streams < 6 ? " (no order book depth)" : "") +
(hasGap ? ", collection gap of " + (100 - cov * 100).toFixed(1) + "% of the day" : "");
el.addEventListener("click", () => selectDate(dateStr));
} else {
el.disabled = true;
el.title = "No data for " + dateStr;
}
frag.appendChild(el);
}
gridEl.appendChild(frag);
}
// Цена последнего корректного выбора. null — даты не выбраны или диапазон
// непригоден; тогда текстом кнопки распоряжается renderSummary.
let priceReady = null;
function emailOk() {
const el = document.getElementById("rp-email");
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(el ? el.value.trim() : "");
}
// Почта обязательна, потому что письмо — единственная копия ключа доступа
// вне localStorage. Покупатель без адреса теряет файлы при смене устройства,
// и восстановить их не можем даже мы: в БД лежит только хэш.
function applyBuyGate() {
const el = document.getElementById("rp-email");
const hint = document.getElementById("rp-email-hint");
const ok = emailOk();
if (el) {
const typed = el.value.trim() !== "";
el.classList.toggle("bad", typed && !ok);
el.classList.toggle("good", ok);
}
if (hint) hint.classList.toggle("bad", !ok && el && el.value.trim() !== "");
if (priceReady === null) return;
if (!ok) {
buyBtn.disabled = true;
buyBtn.textContent = "Enter your email";
} else {
buyBtn.disabled = false;
buyBtn.textContent = "Buy for $" + money(priceReady);
}
}
// Разбор цены. Показывается только когда есть что объяснять, но написан так,
// чтобы объяснять и простой случай: покупатель, увидевший неожиданную сумму,
// должен найти ответ здесь, а не писать в поддержку.
function renderCalc(dates, n, sumW, billed, price, full) {
const box = document.getElementById("rp-calc");
const body = document.getElementById("rp-calc-body");
if (!box || !body) return;
const rows = [];
const add = (k, v) => rows.push("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
add("Days with data in your range", n);
// Группируем дни по полноте: список из тридцати строк никто не читает.
const buckets = new Map();
for (const d of dates) {
const w = dayWeight(dayInfo.get(d));
const key = Math.round(w * 100);
buckets.set(key, (buckets.get(key) || 0) + 1);
}
const keys = [...buckets.keys()].sort((a, b) => b - a);
for (const k of keys) {
const cnt = buckets.get(k);
const noun = cnt === 1 ? "day" : "days";
const label = k === 100
? "complete " + noun
: noun + " at " + k + "% (missing streams or uptime)";
add("&nbsp;&nbsp;" + cnt + " " + label, (k / 100).toFixed(2) + " each");
}
add("Full-day equivalent", sumW.toFixed(2));
add("Billed as", billed.toFixed(2) + " full-day equivalents");
add("Rate at that length", "$" + (price / billed).toFixed(2) + " / full day");
rows.push('<tr class="sum"><td>Total</td><td>$' + money(price) + "</td></tr>");
let note = "";
if (billed < n) {
const off = full ? Math.round(100 * (1 - price / full)) : 0;
const short = Math.round(100 * (1 - sumW / n));
note = "Days without order book depth, or with a collection gap, count as " +
"less than a full day. " + n + " calendar days here are worth " +
sumW.toFixed(2) + " complete ones, and that is exactly what you pay for. " +
"That is " + off + "% off the " + n + "-day price of $" + full + ".";
if (off < short) {
note += " Note the discount (" + off + "%) is smaller than the shortfall (" +
short + "%): fewer billed days move you up the rate card, where a day costs more.";
}
} else {
note = "Every day in this range carries all six streams with no collection gap, " +
"so nothing is discounted.";
}
body.innerHTML = '<table><tbody>' + rows.join("") +
"</tbody></table><p class=\"note\">" + note + "</p>";
box.hidden = false;
}
function renderSummary() {
const range = effectiveRange();
if (!range) {
selectionText.textContent = "No dates selected";
priceEl.innerHTML = "";
priceReady = null;
const cb = document.getElementById("rp-calc"); if (cb) cb.hidden = true;
buyBtn.disabled = true;
buyBtn.textContent = "Select dates";
return;
}
const [s, e] = range;
const dates = availableDatesInRange(s, e);
const n = dates.length;
selectionText.textContent = formatRangeLabel(s, e) +
(rangeEnd ? "" : " (click an end date, or buy this one day)");
if (n === 0) {
priceEl.innerHTML = '<span class="dim">No data in this range. Pick dates that are highlighted.</span>';
priceReady = null;
const cb2 = document.getElementById("rp-calc"); if (cb2) cb2.hidden = true;
buyBtn.disabled = true;
buyBtn.textContent = "Select dates";
return;
}
// Priced on chargeable days: incomplete dates weigh less than full ones.
// full is what the range would cost were every day complete, so the gap
// between the two is the discount the buyer sees.
const billed = chargeableDays(dates);
const price = priceForEquivalent(billed);
const full = priceForDays(n);
if (price === null) {
priceEl.innerHTML = '<span class="dim">Longer than ' + MAX_RANGE_DAYS + ' days. Pick a shorter range.</span>';
priceReady = null;
const cb3 = document.getElementById("rp-calc"); if (cb3) cb3.hidden = true;
buyBtn.disabled = true;
buyBtn.textContent = "Range too long";
return;
}
const rate = price / n;
let detail;
if (billed < n) {
const off = full ? Math.round(100 * (1 - price / full)) : 0;
detail = n + " day" + (n === 1 ? "" : "s") + ", " +
billed.toFixed(2) + " full-day equivalent" +
(off > 0 ? ", <strong>" + off + "% off</strong> for incomplete days" : "");
} else {
// Every selected day is complete, so a tier hint is meaningful. Only
// ever suggest a tier the archive can actually reach: the longest
// possible selection is the whole archive.
let nudge = "";
const nextTierStart = n < 7 ? 7 : n < 30 ? 30 : null;
if (nextTierStart !== null && availableDays.length >= nextTierStart) {
const nextRate = perDayRate(nextTierStart);
if (nextRate < rate) {
nudge = ", " + (nextTierStart - n) + " more day" +
(nextTierStart - n === 1 ? "" : "s") + " drops to $" +
nextRate.toFixed(2) + "/day";
}
}
detail = n + " day" + (n === 1 ? "" : "s") + ", $" + rate.toFixed(2) + "/day" + nudge;
}
priceEl.innerHTML =
'<span class="amount">$' + money(price) + "</span>" +
'<span class="dim">' + detail +
"<br>Estimate. The server sets the final price at checkout.</span>";
let sumW = 0;
for (const d of dates) sumW += dayWeight(dayInfo.get(d));
renderCalc(dates, n, sumW, billed, price, full);
priceReady = price;
applyBuyGate();
}
function render() {
renderMonth();
renderSummary();
}
function selectDate(dateStr) {
// First click sets the start and doubles as a one-day selection so the
// price and Buy button work immediately. Second click sets the end,
// swapping if it lands before the start. Third click starts over.
if (rangeStart === null || rangeEnd !== null) {
rangeStart = dateStr;
rangeEnd = null;
} else if (dateStr === rangeStart) {
rangeEnd = dateStr;
} else if (dateStr < rangeStart) {
rangeEnd = rangeStart;
rangeStart = dateStr;
} else {
rangeEnd = dateStr;
}
render();
}
prevBtn.addEventListener("click", () => {
if (cursorM === 0) { cursorY -= 1; cursorM = 11; } else { cursorM -= 1; }
renderMonth();
});
nextBtn.addEventListener("click", () => {
if (cursorM === 11) { cursorY += 1; cursorM = 0; } else { cursorM += 1; }
renderMonth();
});
// Тело запроса к create-invoice. Код ваучера уходит как есть — сумму по нему
// считает сервер (redeem_voucher), витрина действующих кодов не знает и
// знать не должна: иначе их список утёк бы в исходник страницы.
function buildOrderBody(start_day, end_day, emailVal, voucherVal) {
const body = { start_day: start_day, end_day: end_day };
if (emailVal) body.email = emailVal;
if (voucherVal) body.voucher = voucherVal;
return body;
}
buyBtn.addEventListener("click", async () => {
const range = effectiveRange();
if (!range) return;
const [start_day, end_day] = range;
if (countAvailableInRange(start_day, end_day) < 1) return;
const emailEl = document.getElementById("rp-email");
const emailVal = emailEl && emailEl.value.trim();
const voucherEl = document.getElementById("rp-voucher");
const voucherVal = voucherEl && voucherEl.value.trim().toUpperCase();
if (!emailOk()) {
statusEl.textContent = "Enter a valid email — your download link is sent there.";
const em = document.getElementById("rp-email");
if (em) em.focus();
return;
}
const original = buyBtn.textContent;
buyBtn.disabled = true;
buyBtn.textContent = "Opening invoice";
statusEl.textContent = "";
try {
const res = await fetch(FUNCTIONS_URL + "/create-invoice", {
method: "POST",
// verify_jwt is off on these functions, so the anon apikey and
// Authorization headers are neither required nor wanted: sending
// them trips the CORS preflight, which only allow-lists content-type.
headers: { "content-type": "application/json" },
// The email is ours, collected here. The one Plisio asks for on its
// own checkout page never comes back to us — plisio-callback does not
// carry it — so without this field we have no way to reach a buyer.
// create-invoice has always accepted it as optional; nothing sent it.
body: JSON.stringify(buildOrderBody(start_day, end_day, emailVal, voucherVal)),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const reason = data && data.error === "no_available_days"
? "No data in that range. Pick a different one."
: data && data.error === "invalid_voucher"
? "That voucher code is not valid, or it has been used up."
: (data && data.error) || ("request failed (" + res.status + ")");
throw new Error(reason);
}
// Handed out once. Without it the buyer returns from checkout unable to
// claim the download.
localStorage.setItem("claim:" + data.order_id, data.claim_secret);
location.href = data.invoice_url;
} catch (err) {
buyBtn.disabled = false;
buyBtn.textContent = original;
statusEl.textContent = err.message || "Something went wrong. Try again.";
if (/voucher/i.test(err.message || "")) {
const vc = document.getElementById("rp-voucher");
const vh = document.getElementById("rp-voucher-hint");
if (vc) { vc.classList.add("bad"); vc.classList.remove("good"); vc.focus(); }
if (vh) { vh.classList.add("bad"); vh.textContent = "This code was rejected. Check it, or clear the field to pay full price."; }
}
console.error(err);
}
});
// Поля реагируют на ввод сразу: узнать, что почта не подходит, в момент
// клика по «купить» — худший момент из возможных.
(function wireFields() {
const em = document.getElementById("rp-email");
if (em) {
em.addEventListener("input", applyBuyGate);
em.addEventListener("blur", applyBuyGate);
}
const vc = document.getElementById("rp-voucher");
const vh = document.getElementById("rp-voucher-hint");
if (vc) {
vc.addEventListener("input", () => {
// Приводим к тому же виду, в каком код лежит в БД: верхний регистр,
// без пробелов. Иначе «testrun » с хвостовым пробелом выглядел бы
// опечаткой покупателя, хотя сервер его принимает.
const norm = vc.value.toUpperCase().replace(/\s+/g, "");
if (norm !== vc.value) {
const pos = vc.selectionStart;
vc.value = norm;
try { vc.setSelectionRange(pos, pos); } catch (e) { /* не критично */ }
}
// Формат проверяем на месте, существование кода — только сервер:
// список действующих кодов витрине отдавать нельзя, иначе он утечёт
// в исходник страницы.
const looksOk = /^[A-Z0-9-]{3,32}$/.test(norm);
vc.classList.toggle("bad", norm !== "" && !looksOk);
vc.classList.toggle("good", looksOk);
if (vh) {
vh.classList.toggle("bad", norm !== "" && !looksOk);
vh.textContent = norm === ""
? "Checked at checkout. Leave empty if you have none."
: looksOk
? "Looks like a code — we check it when you click Buy."
: "Codes are 3-32 characters: letters, digits and dashes.";
}
});
}
})();
async function init() {
const restBase = FUNCTIONS_URL.replace(/\/functions\/v1$/, "");
let rows;
try {
// Accept-Profile: shop is required. The table lives in the shop schema
// and PostgREST defaults to public, answering 404 PGRST205. The header
// makes this a preflighted request; Supabase answers OPTIONS 200 with
// access-control-allow-headers: apikey,accept-profile.
const res = await fetch(
restBase + "/rest/v1/available_days?select=day,tables,coverage&order=day",
{ headers: { apikey: ANON, "Accept-Profile": "shop" } },
);
if (!res.ok) throw new Error("failed to load available days (" + res.status + ")");
rows = await res.json();
} catch (err) {
console.error(err);
showState("err", "Could not load available dates. Refresh to try again.");
return;
}
dayInfo = new Map(
(rows || []).map((r) => [r.day, { tables: r.tables, coverage: r.coverage }]),
);
availableDays = (rows || []).map((r) => r.day).sort();
if (availableDays.length === 0) {
showState("info", "No data on sale yet. Check back soon.");
return;
}
availableSet = new Set(availableDays);
const first = availableDays[0].split("-").map(Number);
const last = availableDays[availableDays.length - 1].split("-").map(Number);
minY = first[0]; minM = first[1] - 1;
maxY = last[0]; maxM = last[1] - 1;
// Open on the current month rather than the earliest: the archive grows,
// and buyers care about the fresh edge.
//
// Clamping to the archive bounds is required. The export runs a day
// behind, and on the first of a month there is nothing fresh at all, so
// without the clamp the calendar would open on an empty month past the
// navigation limit (Next is already disabled there, and it would read as
// "no data"). Computed in UTC because catalogue days are cut in UTC.
const monthIx = (y, m) => y * 12 + m;
const nowUtc = new Date();
const ix = Math.min(
Math.max(
monthIx(nowUtc.getUTCFullYear(), nowUtc.getUTCMonth()),
monthIx(minY, minM),
),
monthIx(maxY, maxM),
);
cursorY = Math.floor(ix / 12);
cursorM = ix % 12;
stateEl.hidden = true;
calendarEl.hidden = false;
render();
}
init();
})();
// --------------------------------------------------------- code checkout
//
// The two bot editions are fixed-price products, so this goes down the older
// and simpler of create-invoice's two paths: {sku, email} rather than a date
// range. The price is not sent and never could be — the function reads it from
// shop.products, which is why a tampered request buys nothing for a cent.
//
// The sku is deliberately unversioned. shop.products holds one row per edition
// and publish_release.py repoints its hf_paths at the newest archive, so this
// page never needs editing when a release goes out — which is also why no
// version number appears anywhere above: a hand-maintained one would be wrong
// within a release or two, and the buyer sees the real one in the file name.
(function botCheckout() {
const emailEl = document.getElementById("bot-email");
const emailHint = document.getElementById("bot-email-hint");
const voucherEl = document.getElementById("bot-voucher");
const statusEl = document.getElementById("bot-status");
const buttons = Array.from(document.querySelectorAll(".editions .buy"));
if (!emailEl || !buttons.length) return;
const emailOk = () => /^[^@\s]+@[^@\s.]+\.[^@\s]+$/.test(emailEl.value.trim());
function applyGate() {
const ok = emailOk();
buttons.forEach((b) => { b.disabled = !ok; });
if (!emailEl.value.trim()) {
emailEl.classList.remove("bad", "good");
emailHint.classList.remove("bad");
return;
}
emailEl.classList.toggle("good", ok);
emailEl.classList.toggle("bad", !ok);
emailHint.classList.toggle("bad", !ok);
}
emailEl.addEventListener("input", applyGate);
emailEl.addEventListener("blur", applyGate);
voucherEl.addEventListener("input", () => {
const norm = voucherEl.value.toUpperCase().replace(/\s+/g, "");
if (norm !== voucherEl.value) {
const pos = voucherEl.selectionStart;
voucherEl.value = norm;
try { voucherEl.setSelectionRange(pos, pos); } catch (e) { /* не критично */ }
}
});
applyGate();
buttons.forEach((button) => {
button.addEventListener("click", async () => {
if (!emailOk()) { emailEl.focus(); return; }
const body = { sku: button.dataset.sku, email: emailEl.value.trim() };
const voucher = voucherEl.value.trim().toUpperCase();
if (voucher) body.voucher = voucher;
const label = button.innerHTML;
buttons.forEach((b) => { b.disabled = true; });
button.textContent = "Opening invoice";
statusEl.textContent = "";
try {
const res = await fetch(FUNCTIONS_URL + "/create-invoice", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(
data && data.error === "unknown_sku"
? "That edition is not on sale right now. Message support and I will sort it out."
: data && data.error === "invalid_voucher"
? "That voucher code is not valid, or it has been used up."
: (data && data.error) || ("request failed (" + res.status + ")")
);
}
// Same contract as the dataset purchase: the claim secret is handed
// over exactly once, and without it the buyer returns from checkout
// unable to download what they paid for.
localStorage.setItem("claim:" + data.order_id, data.claim_secret);
location.href = data.invoice_url;
} catch (err) {
button.innerHTML = label;
applyGate();
statusEl.textContent = err.message || "Something went wrong. Try again.";
console.error(err);
}
});
});
})();
</script>
</body>
</html>