Repository navigation
Expand file tree
/
Copy path03_clob_public.cpp
More file actions
257 lines (228 loc) · 11 KB
/
Copy path03_clob_public.cpp
File metadata and controls
257 lines (228 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Example 03: CLOB Public API — Orderbook, prices, batch queries, price history.
//
// The CLOB (Central Limit Order Book) is where trading happens.
// Each binary market has two tokens: Yes and No, identified by token_id.
// token_id comes from the Gamma API's clob_token_ids field.
//
// All endpoints in this example require no authentication.
//
// Run: ./03_clob_public
#include <polymarket/gamma/gamma_client.hpp>
#include <polymarket/clob/clob_client.hpp>
#include <polymarket/types/enums.hpp>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace polymarket;
// Parse Yes and No token IDs from the JSON array '["id1","id2"]'
static std::pair<std::string, std::string> parse_token_ids(std::string_view raw) {
std::pair<std::string, std::string> result;
size_t pos = 0, n = 0;
while (pos < raw.size() && n < 2) {
auto p1 = raw.find('"', pos);
if (p1 == std::string_view::npos) break;
auto p2 = raw.find('"', p1 + 1);
if (p2 == std::string_view::npos) break;
(n == 0 ? result.first : result.second) = std::string(raw.substr(p1 + 1, p2 - p1 - 1));
pos = p2 + 1;
++n;
}
return result;
}
// Print top N levels from one side of an orderbook.
// REST sort order: bids ascending (worst=[0], best=back())
// asks descending (worst=[0], best=back())
static void print_levels(const char* label,
const std::vector<OrderBookLevel>& levels, int n) {
printf(" %-4s (%zu levels):", label, levels.size());
int start = std::max(0, (int)levels.size() - n);
for (int i = (int)levels.size() - 1; i >= start; --i)
printf(" %s @ %s", levels[i].price.c_str(), levels[i].size.c_str());
printf("\n");
}
int main() {
GammaClient gamma;
ClobClient clob;
// ── 1. Health check ───────────────────────────────────────────────────────
printf("=== Health & Time ===\n");
{
auto ok = clob.ok();
if (ok) printf(" status: %s\n", ok->c_str());
auto t = clob.server_time();
if (t) printf(" server time: %s\n", t->c_str());
}
// ── 2. Pick a market from Gamma to get real token IDs ────────────────────
printf("\n=== Market (from Gamma) ===\n");
std::string token_yes, token_no, condition_id;
{
MarketsFilter f;
f.limit = 1; f.active = true; f.closed = false;
f.order = "volume"; f.ascending = false;
auto markets = gamma.get_markets(f);
if (!markets || markets->data.empty()) {
printf("Failed to get market\n");
return 1;
}
auto& m = markets->data[0];
condition_id = m.condition_id;
auto tids = parse_token_ids(m.clob_token_ids);
token_yes = std::move(tids.first);
token_no = std::move(tids.second);
printf(" question: %.*s\n", (int)m.question.size(), m.question.data());
printf(" condition_id: %s\n", condition_id.c_str());
printf(" token_yes: %.20s...\n", token_yes.c_str());
printf(" token_no: %.20s...\n", token_no.c_str());
}
// ── 3. Orderbook ─────────────────────────────────────────────────────────
// REST: bids ascending (worst first) → best bid = bids.back()
// asks descending (worst first) → best ask = asks.back()
printf("\n=== Orderbook (Yes token) ===\n");
{
auto book = clob.book(token_yes);
if (!book) {
printf(" Error: %s\n", book.error().message().c_str());
} else {
printf(" market: %s\n", book->market.c_str());
printf(" timestamp: %s\n", book->timestamp.c_str());
printf(" tick_size: %s\n", book->tick_size.c_str());
printf(" min_order: %s\n", book->min_order_size.c_str());
printf(" neg_risk: %s\n", book->neg_risk ? "yes" : "no");
if (book->last_trade_price)
printf(" last_trade: %s\n", book->last_trade_price->c_str());
print_levels("Bids", book->bids, 3);
print_levels("Asks", book->asks, 3);
if (!book->bids.empty() && !book->asks.empty()) {
double bid = std::stod(book->bids.back().price);
double ask = std::stod(book->asks.back().price);
printf(" spread: %.4f mid: %.4f\n", ask - bid, (bid + ask) / 2.0);
}
}
}
// ── 4. Price endpoints ────────────────────────────────────────────────────
// price(Side::Buy) = best bid, price(Side::Sell) = best ask
printf("\n=== Price Data (Yes token) ===\n");
{
auto mid = clob.midpoint(token_yes);
if (mid) printf(" midpoint: %s\n", mid->mid.c_str());
auto bid = clob.price(token_yes, Side::Buy);
if (bid) printf(" best bid: %s\n", bid->price.c_str());
auto ask = clob.price(token_yes, Side::Sell);
if (ask) printf(" best ask: %s\n", ask->price.c_str());
auto sp = clob.spread(token_yes);
if (sp) printf(" spread: %s\n", sp->spread.c_str());
auto ltp = clob.last_trade_price(token_yes);
if (ltp) printf(" last trade: %s (%s)\n",
ltp->price.c_str(), to_string(ltp->side));
}
// ── 5. Market metadata (results are cached after first call) ──────────────
printf("\n=== Metadata ===\n");
{
auto ts = clob.tick_size(token_yes);
if (ts) printf(" tick_size: %g\n", ts->minimum_tick_size);
auto nr = clob.neg_risk(token_yes);
if (nr) printf(" neg_risk: %s\n", nr->neg_risk ? "yes" : "no");
auto fr = clob.fee_rate(token_yes);
if (fr) printf(" fee_rate: %d bps\n", fr->base_fee);
}
// ── 6. Batch queries — one request for both Yes and No tokens ─────────────
printf("\n=== Batch Queries (Yes + No tokens) ===\n");
{
std::vector<std::string> tokens = {token_yes, token_no};
auto mids = clob.midpoints(tokens);
if (mids) {
printf(" midpoints:\n");
for (auto& [id, v] : *mids)
printf(" %.20s... mid=%s\n", id.c_str(), v.c_str());
}
auto spreads = clob.spreads(tokens);
if (spreads) {
printf(" spreads:\n");
for (auto& [id, v] : *spreads)
printf(" %.20s... spread=%s\n", id.c_str(), v.c_str());
}
auto ltps = clob.last_trades_prices(tokens);
if (ltps) {
printf(" last trades:\n");
for (auto& r : *ltps)
printf(" price=%-6s side=%s\n", r.price.c_str(), to_string(r.side));
}
auto books = clob.books(tokens);
if (books) printf(" books: fetched %zu orderbooks\n", books->size());
}
// ── 7. Batch prices by side ───────────────────────────────────────────────
// POST /prices — ask for specific token+side combinations in one call
printf("\n=== Batch Prices (by side) ===\n");
{
auto raw = clob.prices({{token_yes, Side::Buy}, {token_yes, Side::Sell},
{token_no, Side::Buy}, {token_no, Side::Sell}});
if (raw) printf(" %s\n", raw->c_str());
}
// ── 8. Price history ──────────────────────────────────────────────────────
// Available intervals: OneMinute, OneHour, SixHours, OneDay, OneWeek, Max
printf("\n=== Price History (1h, last 5 points) ===\n");
{
auto hist = clob.price_history(token_yes, PriceHistoryInterval::OneHour);
if (!hist) {
printf(" Error: %s\n", hist.error().message().c_str());
} else {
printf(" Total points: %zu\n", hist->history.size());
int start = std::max(0, (int)hist->history.size() - 5);
for (int i = start; i < (int)hist->history.size(); ++i)
printf(" t=%-13lld p=%.4f\n",
(long long)hist->history[i].t, hist->history[i].p);
}
}
// ── 9. Browse CLOB markets (cursor-based pagination) ─────────────────────
// get_markets() returns up to 100 markets per page and a next_cursor.
// Pass next_cursor back to advance. Empty cursor = no more pages.
printf("\n=== CLOB Markets (2 pages) ===\n");
{
std::string cursor;
for (int page = 0; page < 2; ++page) {
auto r = clob.get_markets(cursor);
if (!r) { printf(" Error: %s\n", r.error().message().c_str()); break; }
printf(" Page %d: %zu markets next_cursor=%s\n",
page + 1, r->data.size(), r->next_cursor.c_str());
if (page == 0 && !r->data.empty()) {
auto& cm = r->data[0];
printf(" sample: %s\n", cm.question.c_str());
printf(" tick=%.4f maker_fee=%.4f taker_fee=%.4f\n",
cm.minimum_tick_size, cm.maker_base_fee, cm.taker_base_fee);
if (cm.tokens && !cm.tokens->empty()) {
printf(" outcomes:");
for (auto& tok : *cm.tokens)
printf(" %s(%.4f)", tok.outcome.c_str(), tok.price);
printf("\n");
}
}
cursor = r->next_cursor;
if (cursor.empty()) break;
}
}
// ── 10. Fetch single market by condition_id ──────────────────────────────
printf("\n=== Single Market by condition_id ===\n");
{
auto r = clob.get_market(condition_id);
if (!r) {
printf(" Error: %s\n", r.error().message().c_str());
} else {
printf(" question: %s\n", r->question.c_str());
printf(" active: %s\n", r->active ? "yes" : "no");
printf(" closed: %s\n", r->closed ? "yes" : "no");
printf(" neg_risk: %s\n", r->neg_risk ? "yes" : "no");
printf(" tick_size: %.4f\n", r->minimum_tick_size);
printf(" maker_fee: %.0f bps\n", r->maker_base_fee);
printf(" taker_fee: %.0f bps\n", r->taker_base_fee);
if (r->end_date_iso)
printf(" end_date: %s\n", r->end_date_iso->c_str());
if (r->tokens) {
printf(" tokens (%zu):\n", r->tokens->size());
for (auto& t : *r->tokens)
printf(" %-5s price=%.4f winner=%s\n",
t.outcome.c_str(), t.price, t.winner ? "yes" : "no");
}
}
}
printf("\nDone.\n");
return 0;
}