@spfunctions/cli 1.7.19 → 1.7.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/101.index.js +1 -0
  2. package/dist/12.index.js +1 -0
  3. package/dist/160.index.js +1 -0
  4. package/dist/174.index.js +1 -0
  5. package/dist/278.index.js +6 -0
  6. package/dist/582.index.js +1 -0
  7. package/dist/641.index.js +324 -0
  8. package/dist/669.index.js +1 -0
  9. package/dist/722.index.js +1 -0
  10. package/dist/788.index.js +1 -0
  11. package/dist/816.index.js +12 -0
  12. package/dist/830.index.js +1 -0
  13. package/dist/921.index.js +1 -0
  14. package/dist/index.js +1 -833
  15. package/package.json +5 -2
  16. package/dist/cache.d.ts +0 -6
  17. package/dist/cache.js +0 -31
  18. package/dist/cache.test.d.ts +0 -1
  19. package/dist/cache.test.js +0 -73
  20. package/dist/client.d.ts +0 -56
  21. package/dist/client.js +0 -205
  22. package/dist/client.test.d.ts +0 -1
  23. package/dist/client.test.js +0 -89
  24. package/dist/commands/agent.d.ts +0 -20
  25. package/dist/commands/agent.js +0 -4119
  26. package/dist/commands/announcements.d.ts +0 -3
  27. package/dist/commands/announcements.js +0 -28
  28. package/dist/commands/augment.d.ts +0 -12
  29. package/dist/commands/augment.js +0 -56
  30. package/dist/commands/balance.d.ts +0 -3
  31. package/dist/commands/balance.js +0 -17
  32. package/dist/commands/book.d.ts +0 -17
  33. package/dist/commands/book.js +0 -220
  34. package/dist/commands/cancel.d.ts +0 -5
  35. package/dist/commands/cancel.js +0 -41
  36. package/dist/commands/context.d.ts +0 -6
  37. package/dist/commands/context.js +0 -208
  38. package/dist/commands/create.d.ts +0 -7
  39. package/dist/commands/create.js +0 -42
  40. package/dist/commands/dashboard.d.ts +0 -14
  41. package/dist/commands/dashboard.js +0 -215
  42. package/dist/commands/delta.d.ts +0 -16
  43. package/dist/commands/delta.js +0 -115
  44. package/dist/commands/edges.d.ts +0 -26
  45. package/dist/commands/edges.js +0 -246
  46. package/dist/commands/evaluate.d.ts +0 -4
  47. package/dist/commands/evaluate.js +0 -30
  48. package/dist/commands/explore.d.ts +0 -14
  49. package/dist/commands/explore.js +0 -116
  50. package/dist/commands/feed.d.ts +0 -13
  51. package/dist/commands/feed.js +0 -73
  52. package/dist/commands/fills.d.ts +0 -4
  53. package/dist/commands/fills.js +0 -29
  54. package/dist/commands/forecast.d.ts +0 -4
  55. package/dist/commands/forecast.js +0 -53
  56. package/dist/commands/get.d.ts +0 -5
  57. package/dist/commands/get.js +0 -98
  58. package/dist/commands/heartbeat.d.ts +0 -20
  59. package/dist/commands/heartbeat.js +0 -73
  60. package/dist/commands/history.d.ts +0 -3
  61. package/dist/commands/history.js +0 -38
  62. package/dist/commands/liquidity.d.ts +0 -14
  63. package/dist/commands/liquidity.js +0 -378
  64. package/dist/commands/list.d.ts +0 -5
  65. package/dist/commands/list.js +0 -38
  66. package/dist/commands/login.d.ts +0 -10
  67. package/dist/commands/login.js +0 -98
  68. package/dist/commands/markets.d.ts +0 -10
  69. package/dist/commands/markets.js +0 -39
  70. package/dist/commands/milestones.d.ts +0 -8
  71. package/dist/commands/milestones.js +0 -56
  72. package/dist/commands/orders.d.ts +0 -4
  73. package/dist/commands/orders.js +0 -28
  74. package/dist/commands/performance.d.ts +0 -11
  75. package/dist/commands/performance.js +0 -250
  76. package/dist/commands/positions.d.ts +0 -19
  77. package/dist/commands/positions.js +0 -294
  78. package/dist/commands/prompt.d.ts +0 -13
  79. package/dist/commands/prompt.js +0 -35
  80. package/dist/commands/publish.d.ts +0 -15
  81. package/dist/commands/publish.js +0 -39
  82. package/dist/commands/query.d.ts +0 -15
  83. package/dist/commands/query.js +0 -132
  84. package/dist/commands/rfq.d.ts +0 -5
  85. package/dist/commands/rfq.js +0 -35
  86. package/dist/commands/scan.d.ts +0 -11
  87. package/dist/commands/scan.js +0 -230
  88. package/dist/commands/schedule.d.ts +0 -3
  89. package/dist/commands/schedule.js +0 -38
  90. package/dist/commands/settlements.d.ts +0 -6
  91. package/dist/commands/settlements.js +0 -50
  92. package/dist/commands/setup.d.ts +0 -24
  93. package/dist/commands/setup.js +0 -700
  94. package/dist/commands/signal.d.ts +0 -6
  95. package/dist/commands/signal.js +0 -32
  96. package/dist/commands/strategies.d.ts +0 -11
  97. package/dist/commands/strategies.js +0 -130
  98. package/dist/commands/telegram.d.ts +0 -15
  99. package/dist/commands/telegram.js +0 -125
  100. package/dist/commands/trade.d.ts +0 -12
  101. package/dist/commands/trade.js +0 -112
  102. package/dist/commands/watch.d.ts +0 -19
  103. package/dist/commands/watch.js +0 -157
  104. package/dist/commands/whatif.d.ts +0 -17
  105. package/dist/commands/whatif.js +0 -209
  106. package/dist/commands/x.d.ts +0 -28
  107. package/dist/commands/x.js +0 -167
  108. package/dist/config.d.ts +0 -55
  109. package/dist/config.js +0 -139
  110. package/dist/config.test.d.ts +0 -1
  111. package/dist/config.test.js +0 -138
  112. package/dist/index.d.ts +0 -20
  113. package/dist/kalshi.d.ts +0 -144
  114. package/dist/kalshi.js +0 -498
  115. package/dist/polymarket.d.ts +0 -237
  116. package/dist/polymarket.js +0 -353
  117. package/dist/polymarket.test.d.ts +0 -1
  118. package/dist/polymarket.test.js +0 -424
  119. package/dist/share.d.ts +0 -4
  120. package/dist/share.js +0 -27
  121. package/dist/skills/loader.d.ts +0 -19
  122. package/dist/skills/loader.js +0 -86
  123. package/dist/telegram/agent-bridge.d.ts +0 -15
  124. package/dist/telegram/agent-bridge.js +0 -573
  125. package/dist/telegram/bot.d.ts +0 -10
  126. package/dist/telegram/bot.js +0 -297
  127. package/dist/telegram/commands.d.ts +0 -11
  128. package/dist/telegram/commands.js +0 -120
  129. package/dist/telegram/format.d.ts +0 -11
  130. package/dist/telegram/format.js +0 -51
  131. package/dist/telegram/format.test.d.ts +0 -1
  132. package/dist/telegram/format.test.js +0 -73
  133. package/dist/telegram/poller.d.ts +0 -6
  134. package/dist/telegram/poller.js +0 -32
  135. package/dist/topics.d.ts +0 -17
  136. package/dist/topics.js +0 -102
  137. package/dist/topics.test.d.ts +0 -1
  138. package/dist/topics.test.js +0 -131
  139. package/dist/tui/border.d.ts +0 -33
  140. package/dist/tui/border.js +0 -87
  141. package/dist/tui/chart.d.ts +0 -19
  142. package/dist/tui/chart.js +0 -117
  143. package/dist/tui/dashboard.d.ts +0 -9
  144. package/dist/tui/dashboard.js +0 -814
  145. package/dist/tui/layout.d.ts +0 -16
  146. package/dist/tui/layout.js +0 -41
  147. package/dist/tui/screen.d.ts +0 -33
  148. package/dist/tui/screen.js +0 -102
  149. package/dist/tui/state.d.ts +0 -40
  150. package/dist/tui/state.js +0 -36
  151. package/dist/tui/widgets/commandbar.d.ts +0 -8
  152. package/dist/tui/widgets/commandbar.js +0 -82
  153. package/dist/tui/widgets/detail.d.ts +0 -9
  154. package/dist/tui/widgets/detail.js +0 -151
  155. package/dist/tui/widgets/edges.d.ts +0 -4
  156. package/dist/tui/widgets/edges.js +0 -34
  157. package/dist/tui/widgets/liquidity.d.ts +0 -9
  158. package/dist/tui/widgets/liquidity.js +0 -142
  159. package/dist/tui/widgets/orders.d.ts +0 -4
  160. package/dist/tui/widgets/orders.js +0 -37
  161. package/dist/tui/widgets/portfolio.d.ts +0 -4
  162. package/dist/tui/widgets/portfolio.js +0 -59
  163. package/dist/tui/widgets/signals.d.ts +0 -4
  164. package/dist/tui/widgets/signals.js +0 -31
  165. package/dist/tui/widgets/statusbar.d.ts +0 -8
  166. package/dist/tui/widgets/statusbar.js +0 -72
  167. package/dist/tui/widgets/thesis.d.ts +0 -4
  168. package/dist/tui/widgets/thesis.js +0 -66
  169. package/dist/tui/widgets/trade.d.ts +0 -9
  170. package/dist/tui/widgets/trade.js +0 -117
  171. package/dist/tui/widgets/upcoming.d.ts +0 -4
  172. package/dist/tui/widgets/upcoming.js +0 -41
  173. package/dist/tui/widgets/whatif.d.ts +0 -7
  174. package/dist/tui/widgets/whatif.js +0 -113
  175. package/dist/types/output.d.ts +0 -412
  176. package/dist/types/output.js +0 -9
  177. package/dist/utils.d.ts +0 -52
  178. package/dist/utils.js +0 -146
  179. package/dist/utils.test.d.ts +0 -1
  180. package/dist/utils.test.js +0 -111
@@ -1,237 +0,0 @@
1
- /**
2
- * Polymarket Public API Client (CLI-side)
3
- *
4
- * Three APIs:
5
- * Gamma (gamma-api.polymarket.com) — market discovery, events, search, tags
6
- * CLOB (clob.polymarket.com) — orderbook, prices, OHLC, spreads
7
- * Data (data-api.polymarket.com) — positions, trades, activity (public, address-based)
8
- *
9
- * All endpoints here are public (no auth required).
10
- * Trading endpoints (order placement) are NOT included — see P2 roadmap.
11
- */
12
- export interface PolymarketEvent {
13
- id: string;
14
- slug: string;
15
- title: string;
16
- description: string;
17
- startDate: string;
18
- endDate: string;
19
- active: boolean;
20
- closed: boolean;
21
- volume: number;
22
- liquidity: number;
23
- markets: PolymarketMarket[];
24
- negRisk: boolean;
25
- }
26
- export interface PolymarketMarket {
27
- id: string;
28
- question: string;
29
- conditionId: string;
30
- slug: string;
31
- outcomes: string;
32
- outcomePrices: string;
33
- volume: string;
34
- volume24hr: number;
35
- volumeNum: number;
36
- liquidityNum: number;
37
- active: boolean;
38
- closed: boolean;
39
- endDateIso: string;
40
- clobTokenIds: string;
41
- bestBid: number;
42
- bestAsk: number;
43
- spread: number;
44
- lastTradePrice: number;
45
- oneDayPriceChange: number;
46
- negRisk: boolean;
47
- negRiskMarketID: string;
48
- enableOrderBook: boolean;
49
- orderPriceMinTickSize: number;
50
- groupItemTitle: string;
51
- acceptingOrders: boolean;
52
- }
53
- export interface OrderbookLevel {
54
- price: string;
55
- size: string;
56
- }
57
- export interface RawOrderbook {
58
- market: string;
59
- asset_id: string;
60
- timestamp: string;
61
- bids: OrderbookLevel[];
62
- asks: OrderbookLevel[];
63
- hash: string;
64
- }
65
- export interface OrderbookDepth {
66
- bestBid: number;
67
- bestAsk: number;
68
- spread: number;
69
- bidDepthTop3: number;
70
- askDepthTop3: number;
71
- totalBidDepth: number;
72
- totalAskDepth: number;
73
- liquidityScore: 'high' | 'medium' | 'low';
74
- levels: {
75
- bids: OrderbookLevel[];
76
- asks: OrderbookLevel[];
77
- };
78
- }
79
- export interface OHLCCandle {
80
- t: number;
81
- o: number;
82
- h: number;
83
- l: number;
84
- c: number;
85
- v: number;
86
- }
87
- export interface PolymarketPosition {
88
- asset: string;
89
- conditionId: string;
90
- size: number;
91
- avgPrice: number;
92
- currentPrice: number;
93
- initialValue: number;
94
- currentValue: number;
95
- percentPnl: number;
96
- cashPnl: number;
97
- outcome: string;
98
- outcomeIndex: number;
99
- title: string;
100
- slug: string;
101
- eventSlug: string;
102
- curPrice: number;
103
- endDate: string;
104
- icon: string;
105
- }
106
- /**
107
- * Search markets and events by keyword.
108
- * Returns events with their markets (reduces API calls).
109
- */
110
- export declare function polymarketSearch(query: string, limit?: number): Promise<PolymarketEvent[]>;
111
- /**
112
- * List active events with pagination.
113
- * Supports sorting by volume_24hr, volume, liquidity, etc.
114
- */
115
- export declare function polymarketListEvents(params?: {
116
- limit?: number;
117
- offset?: number;
118
- order?: string;
119
- ascending?: boolean;
120
- tag_id?: string;
121
- }): Promise<PolymarketEvent[]>;
122
- /**
123
- * Get a single event by ID (includes full markets array).
124
- */
125
- export declare function polymarketGetEvent(id: string): Promise<PolymarketEvent>;
126
- /**
127
- * Get a single market by ID or slug.
128
- */
129
- export declare function polymarketGetMarket(idOrSlug: string): Promise<PolymarketMarket>;
130
- /**
131
- * List available tags for topic-based filtering.
132
- */
133
- export declare function polymarketListTags(): Promise<Array<{
134
- id: string;
135
- label: string;
136
- slug: string;
137
- }>>;
138
- /**
139
- * Fetch raw orderbook for a token ID.
140
- * Returns bids and asks arrays with price/size at each level.
141
- */
142
- export declare function polymarketGetOrderbook(tokenId: string): Promise<RawOrderbook | null>;
143
- /**
144
- * Compute orderbook depth metrics from raw orderbook.
145
- * Converts Polymarket prices (0-1 dollars) to cents (0-100) for consistency with Kalshi.
146
- */
147
- export declare function computeOrderbookDepth(raw: RawOrderbook): OrderbookDepth;
148
- /**
149
- * Fetch orderbook with computed depth metrics.
150
- * Convenience wrapper: fetch + compute in one call.
151
- */
152
- export declare function polymarketGetOrderbookWithDepth(tokenId: string): Promise<OrderbookDepth | null>;
153
- /**
154
- * Fetch midpoint price for a token.
155
- */
156
- export declare function polymarketGetMidpoint(tokenId: string): Promise<number | null>;
157
- /**
158
- * Fetch spread for a token.
159
- */
160
- export declare function polymarketGetSpread(tokenId: string): Promise<number | null>;
161
- /**
162
- * Batch midpoint query (up to 500 tokens).
163
- */
164
- export declare function polymarketGetMidpoints(tokenIds: string[]): Promise<Record<string, number>>;
165
- /**
166
- * Fetch OHLC candlestick data.
167
- *
168
- * @param tokenId - CLOB token ID (asset_id)
169
- * @param fidelity - Candle interval: '1m','5m','15m','30m','1h','4h','1d','1w'
170
- * @param startTs - Start Unix timestamp (seconds)
171
- * @param endTs - End Unix timestamp (seconds, optional)
172
- * @param limit - Max candles (up to 1000)
173
- */
174
- export declare function polymarketGetOHLC(params: {
175
- tokenId: string;
176
- fidelity?: string;
177
- startTs: number;
178
- endTs?: number;
179
- limit?: number;
180
- }): Promise<OHLCCandle[]>;
181
- /**
182
- * Fetch price history (simple time series, no OHLC).
183
- * Supports relative intervals or absolute timestamp ranges.
184
- *
185
- * @param tokenId - CLOB token ID
186
- * @param interval - Relative: 'max','1w','1d','6h','1h'
187
- * @param startTs - Absolute start (mutually exclusive with interval)
188
- * @param endTs - Absolute end
189
- * @param fidelity - Data point frequency in minutes (default: 60)
190
- */
191
- export declare function polymarketGetPriceHistory(params: {
192
- tokenId: string;
193
- interval?: string;
194
- startTs?: number;
195
- endTs?: number;
196
- fidelity?: number;
197
- }): Promise<Array<{
198
- t: number;
199
- p: number;
200
- }>>;
201
- /**
202
- * Fetch current open positions for a wallet address.
203
- * No auth required — positions are public on-chain data.
204
- */
205
- export declare function polymarketGetPositions(walletAddress: string): Promise<PolymarketPosition[]>;
206
- /**
207
- * Fetch closed positions for a wallet address.
208
- */
209
- export declare function polymarketGetClosedPositions(walletAddress: string): Promise<PolymarketPosition[]>;
210
- /**
211
- * Score liquidity based on spread and depth.
212
- * Matches Kalshi's scoring for consistency:
213
- * high: spread ≤ 2¢ AND depth ≥ 500
214
- * medium: spread ≤ 5¢ AND depth ≥ 100
215
- * low: everything else
216
- */
217
- export declare function scoreLiquidity(spreadCents: number, totalDepth: number): 'high' | 'medium' | 'low';
218
- /**
219
- * Parse clobTokenIds JSON string into [yesTokenId, noTokenId].
220
- */
221
- export declare function parseClobTokenIds(clobTokenIds: string): [string, string] | null;
222
- /**
223
- * Parse outcomes JSON string.
224
- */
225
- export declare function parseOutcomes(outcomes: string): string[];
226
- /**
227
- * Parse outcomePrices JSON string into numbers.
228
- */
229
- export declare function parseOutcomePrices(outcomePrices: string): number[];
230
- /**
231
- * Convert Polymarket price (0-1 dollars) to cents (0-100).
232
- */
233
- export declare function toCents(price: number): number;
234
- /**
235
- * Build a Polymarket URL for a market.
236
- */
237
- export declare function polymarketUrl(eventSlug: string): string;
@@ -1,353 +0,0 @@
1
- "use strict";
2
- /**
3
- * Polymarket Public API Client (CLI-side)
4
- *
5
- * Three APIs:
6
- * Gamma (gamma-api.polymarket.com) — market discovery, events, search, tags
7
- * CLOB (clob.polymarket.com) — orderbook, prices, OHLC, spreads
8
- * Data (data-api.polymarket.com) — positions, trades, activity (public, address-based)
9
- *
10
- * All endpoints here are public (no auth required).
11
- * Trading endpoints (order placement) are NOT included — see P2 roadmap.
12
- */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.polymarketSearch = polymarketSearch;
15
- exports.polymarketListEvents = polymarketListEvents;
16
- exports.polymarketGetEvent = polymarketGetEvent;
17
- exports.polymarketGetMarket = polymarketGetMarket;
18
- exports.polymarketListTags = polymarketListTags;
19
- exports.polymarketGetOrderbook = polymarketGetOrderbook;
20
- exports.computeOrderbookDepth = computeOrderbookDepth;
21
- exports.polymarketGetOrderbookWithDepth = polymarketGetOrderbookWithDepth;
22
- exports.polymarketGetMidpoint = polymarketGetMidpoint;
23
- exports.polymarketGetSpread = polymarketGetSpread;
24
- exports.polymarketGetMidpoints = polymarketGetMidpoints;
25
- exports.polymarketGetOHLC = polymarketGetOHLC;
26
- exports.polymarketGetPriceHistory = polymarketGetPriceHistory;
27
- exports.polymarketGetPositions = polymarketGetPositions;
28
- exports.polymarketGetClosedPositions = polymarketGetClosedPositions;
29
- exports.scoreLiquidity = scoreLiquidity;
30
- exports.parseClobTokenIds = parseClobTokenIds;
31
- exports.parseOutcomes = parseOutcomes;
32
- exports.parseOutcomePrices = parseOutcomePrices;
33
- exports.toCents = toCents;
34
- exports.polymarketUrl = polymarketUrl;
35
- const GAMMA = 'https://gamma-api.polymarket.com';
36
- const CLOB = 'https://clob.polymarket.com';
37
- const DATA = 'https://data-api.polymarket.com';
38
- // ============================================================================
39
- // GAMMA API — Market Discovery
40
- // ============================================================================
41
- /**
42
- * Search markets and events by keyword.
43
- * Returns events with their markets (reduces API calls).
44
- */
45
- async function polymarketSearch(query, limit = 20) {
46
- const params = new URLSearchParams({
47
- q: query,
48
- limit_per_type: limit.toString(),
49
- });
50
- const res = await fetch(`${GAMMA}/public-search?${params}`);
51
- if (!res.ok)
52
- throw new Error(`Polymarket search error: ${res.status}`);
53
- const data = await res.json();
54
- return data.events || [];
55
- }
56
- /**
57
- * List active events with pagination.
58
- * Supports sorting by volume_24hr, volume, liquidity, etc.
59
- */
60
- async function polymarketListEvents(params) {
61
- const sp = new URLSearchParams({
62
- active: 'true',
63
- closed: 'false',
64
- limit: (params?.limit || 50).toString(),
65
- offset: (params?.offset || 0).toString(),
66
- });
67
- if (params?.order)
68
- sp.set('order', params.order);
69
- if (params?.ascending !== undefined)
70
- sp.set('ascending', String(params.ascending));
71
- if (params?.tag_id)
72
- sp.set('tag_id', params.tag_id);
73
- const res = await fetch(`${GAMMA}/events?${sp}`);
74
- if (!res.ok)
75
- throw new Error(`Polymarket events error: ${res.status}`);
76
- return res.json();
77
- }
78
- /**
79
- * Get a single event by ID (includes full markets array).
80
- */
81
- async function polymarketGetEvent(id) {
82
- const res = await fetch(`${GAMMA}/events/${id}`);
83
- if (!res.ok)
84
- throw new Error(`Polymarket event error: ${res.status}`);
85
- return res.json();
86
- }
87
- /**
88
- * Get a single market by ID or slug.
89
- */
90
- async function polymarketGetMarket(idOrSlug) {
91
- const res = await fetch(`${GAMMA}/markets/${idOrSlug}`);
92
- if (!res.ok)
93
- throw new Error(`Polymarket market error: ${res.status}`);
94
- return res.json();
95
- }
96
- /**
97
- * List available tags for topic-based filtering.
98
- */
99
- async function polymarketListTags() {
100
- const res = await fetch(`${GAMMA}/tags`);
101
- if (!res.ok)
102
- throw new Error(`Polymarket tags error: ${res.status}`);
103
- return res.json();
104
- }
105
- // ============================================================================
106
- // CLOB API — Orderbook & Pricing
107
- // ============================================================================
108
- /**
109
- * Fetch raw orderbook for a token ID.
110
- * Returns bids and asks arrays with price/size at each level.
111
- */
112
- async function polymarketGetOrderbook(tokenId) {
113
- try {
114
- const res = await fetch(`${CLOB}/book?token_id=${tokenId}`);
115
- if (!res.ok)
116
- return null;
117
- const data = await res.json();
118
- if (data.error)
119
- return null;
120
- return data;
121
- }
122
- catch {
123
- return null;
124
- }
125
- }
126
- /**
127
- * Compute orderbook depth metrics from raw orderbook.
128
- * Converts Polymarket prices (0-1 dollars) to cents (0-100) for consistency with Kalshi.
129
- */
130
- function computeOrderbookDepth(raw) {
131
- const bids = (raw.bids || [])
132
- .map(l => ({ price: parseFloat(l.price), size: parseFloat(l.size) }))
133
- .sort((a, b) => b.price - a.price); // highest bid first
134
- const asks = (raw.asks || [])
135
- .map(l => ({ price: parseFloat(l.price), size: parseFloat(l.size) }))
136
- .sort((a, b) => a.price - b.price); // lowest ask first
137
- const bestBid = bids.length > 0 ? Math.round(bids[0].price * 100) : 0;
138
- const bestAsk = asks.length > 0 ? Math.round(asks[0].price * 100) : 100;
139
- const spread = bestAsk - bestBid;
140
- const bidDepthTop3 = bids.slice(0, 3).reduce((sum, l) => sum + l.size, 0);
141
- const askDepthTop3 = asks.slice(0, 3).reduce((sum, l) => sum + l.size, 0);
142
- const totalBidDepth = bids.reduce((sum, l) => sum + l.size, 0);
143
- const totalAskDepth = asks.reduce((sum, l) => sum + l.size, 0);
144
- const liquidityScore = scoreLiquidity(spread, bidDepthTop3 + askDepthTop3);
145
- return {
146
- bestBid,
147
- bestAsk,
148
- spread,
149
- bidDepthTop3: Math.round(bidDepthTop3),
150
- askDepthTop3: Math.round(askDepthTop3),
151
- totalBidDepth: Math.round(totalBidDepth),
152
- totalAskDepth: Math.round(totalAskDepth),
153
- liquidityScore,
154
- levels: { bids: raw.bids, asks: raw.asks },
155
- };
156
- }
157
- /**
158
- * Fetch orderbook with computed depth metrics.
159
- * Convenience wrapper: fetch + compute in one call.
160
- */
161
- async function polymarketGetOrderbookWithDepth(tokenId) {
162
- const raw = await polymarketGetOrderbook(tokenId);
163
- if (!raw)
164
- return null;
165
- return computeOrderbookDepth(raw);
166
- }
167
- /**
168
- * Fetch midpoint price for a token.
169
- */
170
- async function polymarketGetMidpoint(tokenId) {
171
- try {
172
- const res = await fetch(`${CLOB}/midpoint?token_id=${tokenId}`);
173
- if (!res.ok)
174
- return null;
175
- const data = await res.json();
176
- return data.mid ? parseFloat(data.mid) : null;
177
- }
178
- catch {
179
- return null;
180
- }
181
- }
182
- /**
183
- * Fetch spread for a token.
184
- */
185
- async function polymarketGetSpread(tokenId) {
186
- try {
187
- const res = await fetch(`${CLOB}/spread?token_id=${tokenId}`);
188
- if (!res.ok)
189
- return null;
190
- const data = await res.json();
191
- return data.spread ? parseFloat(data.spread) : null;
192
- }
193
- catch {
194
- return null;
195
- }
196
- }
197
- /**
198
- * Batch midpoint query (up to 500 tokens).
199
- */
200
- async function polymarketGetMidpoints(tokenIds) {
201
- if (tokenIds.length === 0)
202
- return {};
203
- const res = await fetch(`${CLOB}/midpoints`, {
204
- method: 'POST',
205
- headers: { 'Content-Type': 'application/json' },
206
- body: JSON.stringify(tokenIds),
207
- });
208
- if (!res.ok)
209
- throw new Error(`Polymarket midpoints error: ${res.status}`);
210
- return res.json();
211
- }
212
- /**
213
- * Fetch OHLC candlestick data.
214
- *
215
- * @param tokenId - CLOB token ID (asset_id)
216
- * @param fidelity - Candle interval: '1m','5m','15m','30m','1h','4h','1d','1w'
217
- * @param startTs - Start Unix timestamp (seconds)
218
- * @param endTs - End Unix timestamp (seconds, optional)
219
- * @param limit - Max candles (up to 1000)
220
- */
221
- async function polymarketGetOHLC(params) {
222
- const sp = new URLSearchParams({
223
- asset_id: params.tokenId,
224
- startTs: params.startTs.toString(),
225
- fidelity: params.fidelity || '1h',
226
- });
227
- if (params.endTs)
228
- sp.set('endTs', params.endTs.toString());
229
- if (params.limit)
230
- sp.set('limit', params.limit.toString());
231
- const res = await fetch(`${CLOB}/ohlc?${sp}`);
232
- if (!res.ok) {
233
- // OHLC endpoint may not exist on all deployments — fall back gracefully
234
- return [];
235
- }
236
- const data = await res.json();
237
- return Array.isArray(data) ? data : (data.candles || data.data || []);
238
- }
239
- /**
240
- * Fetch price history (simple time series, no OHLC).
241
- * Supports relative intervals or absolute timestamp ranges.
242
- *
243
- * @param tokenId - CLOB token ID
244
- * @param interval - Relative: 'max','1w','1d','6h','1h'
245
- * @param startTs - Absolute start (mutually exclusive with interval)
246
- * @param endTs - Absolute end
247
- * @param fidelity - Data point frequency in minutes (default: 60)
248
- */
249
- async function polymarketGetPriceHistory(params) {
250
- const sp = new URLSearchParams({ market: params.tokenId });
251
- if (params.interval)
252
- sp.set('interval', params.interval);
253
- if (params.startTs)
254
- sp.set('startTs', params.startTs.toString());
255
- if (params.endTs)
256
- sp.set('endTs', params.endTs.toString());
257
- if (params.fidelity)
258
- sp.set('fidelity', params.fidelity.toString());
259
- const res = await fetch(`${CLOB}/prices-history?${sp}`);
260
- if (!res.ok)
261
- return [];
262
- const data = await res.json();
263
- return data.history || [];
264
- }
265
- // ============================================================================
266
- // DATA API — Positions & Activity (public, address-based)
267
- // ============================================================================
268
- /**
269
- * Fetch current open positions for a wallet address.
270
- * No auth required — positions are public on-chain data.
271
- */
272
- async function polymarketGetPositions(walletAddress) {
273
- const res = await fetch(`${DATA}/positions?user=${walletAddress}`);
274
- if (!res.ok)
275
- return [];
276
- const data = await res.json();
277
- return Array.isArray(data) ? data : [];
278
- }
279
- /**
280
- * Fetch closed positions for a wallet address.
281
- */
282
- async function polymarketGetClosedPositions(walletAddress) {
283
- const res = await fetch(`${DATA}/closed-positions?user=${walletAddress}`);
284
- if (!res.ok)
285
- return [];
286
- const data = await res.json();
287
- return Array.isArray(data) ? data : [];
288
- }
289
- // ============================================================================
290
- // HELPERS
291
- // ============================================================================
292
- /**
293
- * Score liquidity based on spread and depth.
294
- * Matches Kalshi's scoring for consistency:
295
- * high: spread ≤ 2¢ AND depth ≥ 500
296
- * medium: spread ≤ 5¢ AND depth ≥ 100
297
- * low: everything else
298
- */
299
- function scoreLiquidity(spreadCents, totalDepth) {
300
- if (spreadCents <= 2 && totalDepth >= 500)
301
- return 'high';
302
- if (spreadCents <= 5 && totalDepth >= 100)
303
- return 'medium';
304
- return 'low';
305
- }
306
- /**
307
- * Parse clobTokenIds JSON string into [yesTokenId, noTokenId].
308
- */
309
- function parseClobTokenIds(clobTokenIds) {
310
- try {
311
- const ids = JSON.parse(clobTokenIds);
312
- if (Array.isArray(ids) && ids.length >= 2)
313
- return [ids[0], ids[1]];
314
- return null;
315
- }
316
- catch {
317
- return null;
318
- }
319
- }
320
- /**
321
- * Parse outcomes JSON string.
322
- */
323
- function parseOutcomes(outcomes) {
324
- try {
325
- return JSON.parse(outcomes);
326
- }
327
- catch {
328
- return [];
329
- }
330
- }
331
- /**
332
- * Parse outcomePrices JSON string into numbers.
333
- */
334
- function parseOutcomePrices(outcomePrices) {
335
- try {
336
- return JSON.parse(outcomePrices);
337
- }
338
- catch {
339
- return [];
340
- }
341
- }
342
- /**
343
- * Convert Polymarket price (0-1 dollars) to cents (0-100).
344
- */
345
- function toCents(price) {
346
- return Math.round(price * 100);
347
- }
348
- /**
349
- * Build a Polymarket URL for a market.
350
- */
351
- function polymarketUrl(eventSlug) {
352
- return `https://polymarket.com/event/${eventSlug}`;
353
- }
@@ -1 +0,0 @@
1
- export {};