skewtape 0.0.1 → 0.1.4
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.
- package/LICENSE +21 -0
- package/README.md +182 -0
- package/dist/cjs/backtest.d.ts +146 -0
- package/dist/cjs/backtest.js +410 -0
- package/dist/cjs/client.d.ts +255 -0
- package/dist/cjs/client.js +447 -0
- package/dist/cjs/download.d.ts +33 -0
- package/dist/cjs/download.js +160 -0
- package/dist/cjs/errors.d.ts +76 -0
- package/dist/cjs/errors.js +159 -0
- package/dist/cjs/exact.d.ts +36 -0
- package/dist/cjs/exact.js +168 -0
- package/dist/cjs/fees.d.ts +68 -0
- package/dist/cjs/fees.js +196 -0
- package/dist/cjs/geoblock.d.ts +48 -0
- package/dist/cjs/geoblock.js +78 -0
- package/dist/cjs/index.d.ts +31 -0
- package/dist/cjs/index.js +98 -0
- package/dist/cjs/kalshi.d.ts +261 -0
- package/dist/cjs/kalshi.js +416 -0
- package/dist/cjs/keccak.d.ts +10 -0
- package/dist/cjs/keccak.js +84 -0
- package/dist/cjs/msgpack.d.ts +15 -0
- package/dist/cjs/msgpack.js +112 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paginated.d.ts +26 -0
- package/dist/cjs/paginated.js +51 -0
- package/dist/cjs/quote-math.d.ts +146 -0
- package/dist/cjs/quote-math.js +446 -0
- package/dist/cjs/quote.d.ts +108 -0
- package/dist/cjs/quote.js +307 -0
- package/dist/cjs/route-hyperliquid.d.ts +228 -0
- package/dist/cjs/route-hyperliquid.js +387 -0
- package/dist/cjs/route.d.ts +297 -0
- package/dist/cjs/route.js +516 -0
- package/dist/cjs/stream.d.ts +99 -0
- package/dist/cjs/stream.js +529 -0
- package/dist/cjs/version.d.ts +6 -0
- package/dist/cjs/version.js +9 -0
- package/dist/esm/backtest.d.ts +146 -0
- package/dist/esm/backtest.js +403 -0
- package/dist/esm/client.d.ts +255 -0
- package/dist/esm/client.js +441 -0
- package/dist/esm/download.d.ts +33 -0
- package/dist/esm/download.js +155 -0
- package/dist/esm/errors.d.ts +76 -0
- package/dist/esm/errors.js +142 -0
- package/dist/esm/exact.d.ts +36 -0
- package/dist/esm/exact.js +158 -0
- package/dist/esm/fees.d.ts +68 -0
- package/dist/esm/fees.js +185 -0
- package/dist/esm/geoblock.d.ts +48 -0
- package/dist/esm/geoblock.js +74 -0
- package/dist/esm/index.d.ts +31 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/kalshi.d.ts +261 -0
- package/dist/esm/kalshi.js +404 -0
- package/dist/esm/keccak.d.ts +10 -0
- package/dist/esm/keccak.js +80 -0
- package/dist/esm/msgpack.d.ts +15 -0
- package/dist/esm/msgpack.js +109 -0
- package/dist/esm/paginated.d.ts +26 -0
- package/dist/esm/paginated.js +47 -0
- package/dist/esm/quote-math.d.ts +146 -0
- package/dist/esm/quote-math.js +437 -0
- package/dist/esm/quote.d.ts +108 -0
- package/dist/esm/quote.js +297 -0
- package/dist/esm/route-hyperliquid.d.ts +228 -0
- package/dist/esm/route-hyperliquid.js +376 -0
- package/dist/esm/route.d.ts +297 -0
- package/dist/esm/route.js +507 -0
- package/dist/esm/stream.d.ts +99 -0
- package/dist/esm/stream.js +524 -0
- package/dist/esm/version.d.ts +6 -0
- package/dist/esm/version.js +6 -0
- package/package.json +48 -1
- package/src/backtest.ts +490 -0
- package/src/client.ts +595 -0
- package/src/download.ts +161 -0
- package/src/errors.ts +143 -0
- package/src/exact.ts +159 -0
- package/src/fees.ts +189 -0
- package/src/generated/schema.d.ts +2500 -0
- package/src/geoblock.ts +90 -0
- package/src/index.ts +146 -0
- package/src/kalshi.ts +563 -0
- package/src/keccak.ts +82 -0
- package/src/msgpack.ts +83 -0
- package/src/paginated.ts +51 -0
- package/src/quote-math.ts +555 -0
- package/src/quote.ts +324 -0
- package/src/route-hyperliquid.ts +457 -0
- package/src/route.ts +631 -0
- package/src/stream.ts +539 -0
- package/src/version.ts +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Blockbrainers SAS (Skewtape)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# skewtape
|
|
2
|
+
|
|
3
|
+
Prediction-market data from every venue Skewtape serves, in one schema: markets, fills, candles, fees and resolutions, with matched events that link the same question across venues. This is the TypeScript client for the [Skewtape API](https://docs.skewtape.com), for Node 20 and later. It loads by `import { Skewtape } from "skewtape"` or by `const { Skewtape } = require("skewtape")`, each with its own types: npm installs an ESM build and a CommonJS build of the same code. A program that loads both holds two copies, so an error from one is not an `instanceof` the other's classes: load it one way in a program.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install skewtape
|
|
7
|
+
export SKEWTAPE_API_KEY=st_live_... # a key from the dashboard, docs.skewtape.com/keys
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { Skewtape } from "skewtape";
|
|
12
|
+
|
|
13
|
+
const sk = new Skewtape(); // or new Skewtape({ apiKey: "st_live_..." })
|
|
14
|
+
|
|
15
|
+
for (const venue of await sk.venues()) console.log(venue.key, venue.flags);
|
|
16
|
+
|
|
17
|
+
// Matched events: the same question across venues, with a confidence and
|
|
18
|
+
// whether every member resolves the same way.
|
|
19
|
+
for await (const event of sk.events({ minConfidence: 0.9, resolutionEqual: true })) {
|
|
20
|
+
console.log(event.event_id, event.question_canonical, event.members.map((m) => m.venue));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const event = await sk.events.get("st_evt_00412");
|
|
24
|
+
|
|
25
|
+
// Markets of one venue. Iterating a list reads every page, one call each
|
|
26
|
+
// against your plan's monthly calls, so this reads the first page only.
|
|
27
|
+
const first = await sk.markets({ venue: "kalshi" }).pages().next();
|
|
28
|
+
for (const market of first.done ? [] : first.value.items) {
|
|
29
|
+
console.log(market.market_id, market.status, market.fee_category);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Fills of a matched event over a dated window (maker legs by default).
|
|
33
|
+
// Fills are on the Builder and Pro plans: a Free or History key gets a
|
|
34
|
+
// ForbiddenPlanError here.
|
|
35
|
+
const since = new Date("2026-11-02T00:00:00Z");
|
|
36
|
+
const until = new Date("2026-11-03T00:00:00Z");
|
|
37
|
+
for await (const fill of sk.fills({ eventId: "st_evt_00412", since, until })) {
|
|
38
|
+
console.log(fill.venue, fill.ts, fill.price);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Pairs: matched events with exactly two active members.
|
|
42
|
+
const pairs = await sk.pairs({ minConfidence: 0.9 }).toArray();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The quickstart above is run against a mock API by the package's tests, so it stays current.
|
|
46
|
+
|
|
47
|
+
- Every list (`markets`, `events`, `pairs`, `fills`, `candles`, `resolutions`, `fees`) returns a `Paginated`: `for await` for every item across pages, `.pages()` for the pages, `.first()` for the first item, `.toArray()` for all of them. Nothing is fetched until you iterate. `markets({ resolved })` filters on the client, so every page is still fetched: pass a venue or market ids with it.
|
|
48
|
+
- A `429 rate_limited`, or a `429` with no error body as a proxy sends, is retried with the server's `Retry-After` (three times by default, `maxRetries`). A `429 lookup_rate_limited` (too many invalid keys from your address) throws `AuthenticationError` at once: fix the key. A `429 quota_exceeded` throws `QuotaExceededError` at once, with `resetsAt` and `upgradeUrl`. A request past `timeout` (30 seconds by default) throws a `SkewtapeError`. Any other error throws a `SkewtapeError` subclass (`AuthenticationError`, `ForbiddenPlanError` with `.plan`, `BlockedError` with `.blockReasonCode`, `NotFoundError`, `RateLimitError`, `QuotaExceededError`, `ServerError`), carrying the API's `code`, `message`, `docsUrl` and `requestId`.
|
|
49
|
+
- `sk.download.bundles()` lists the History snapshots and monthly deltas your account may download, and `sk.download.bundle(bundleId, folder)` fetches one whole, resuming a partial download, checking each file's sha256 and the folder's `CHECKSUMS.sha256`; `sk.download.file(bundleId, path, dest)` fetches one file. They need a key on the Builder or Pro plan (a History purchase downloads from the dashboard), and the file host never sees the key. `sk.download(url, dest, { sha256 })` fetches a link you already hold; `sk.download.verify(folder)` checks a folder.
|
|
50
|
+
- Withheld fields read `null` with `blocked` true and `block_reason_code` on the row: see [Data rights and geoblocking](https://docs.skewtape.com/rights).
|
|
51
|
+
- The response types are the API's (`Market`, `MatchedEvent`, `Fill`, ...), exported from the package, generated from the public OpenAPI document into `src/generated/schema.d.ts` and never edited by hand. `AGENTS.md` tells a coding agent how to use the package. The version's major and minor follow the API's version.
|
|
52
|
+
- `sk.quote(eventId, { outcome, side, size })` is the best venue, or split across venues, for a size of one outcome of a matched event once each venue's taker fee is counted ([Quotes](https://docs.skewtape.com/quote)). It places nothing. One metered call reads the quote context (`sk.quoteContext(eventId)` alone); the books are read from each venue, from your machine, with a fetch that never carries your key. Amounts are integers in millionths (`net_micros`, `net_avg_price_micros`, ...). A venue that cannot be reached is left out and named in `skipped`, and none reachable throws `VenueUnreachableError`; members that do not resolve alike throw `RuleMismatchError` unless `allowRuleMismatch`; a venue whose fee is unknown (no fee row, or one the data policy withholds) is never compared with one whose fee is known: when a venue whose fee is known can fill some of the size, it is left out of the plan, quoted alone in `venues` before fees, and `warnings` says so (otherwise they are compared before fees, and `warnings` says the fee is not counted). Kalshi's book is Kalshi's public orderbook, read with no key (a `kalshi_dflow` member waits for DFlow access and is left out); any venue's reader can be replaced in `bookReaders`.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// The best venue, or split, for 100 contracts of "yes" once each taker fee is
|
|
56
|
+
// counted: one metered call, then each venue's book. It places nothing.
|
|
57
|
+
const q = await sk.quote("st_evt_00412", { outcome: "yes", side: "buy", size: 100 });
|
|
58
|
+
console.log(q.plan, q.filled_micro, q.net_avg_price_micros, q.legs.map((leg) => [leg.venue, leg.size_micro]));
|
|
59
|
+
for (const skip of q.skipped) console.log("left out:", skip.venue, skip.reason, skip.detail);
|
|
60
|
+
for (const warning of q.warnings) console.log("warning:", warning);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Backtest: fee-aware P&L on the record
|
|
64
|
+
|
|
65
|
+
`sk.backtest(trades)` replays trades you supply over the history Skewtape records and gives their P&L before and after fees. It is arithmetic on history: it forecasts nothing, suggests no trade and optimises nothing.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// Two trades on a real Kalshi market that resolved yes on 3 Nov 2026; the prices are illustrative, not the market's.
|
|
69
|
+
const result = await sk.backtest(
|
|
70
|
+
[
|
|
71
|
+
{ venue: "kalshi", market_id: "KXKBORFI-26NOV030430SAMKTW-Y", token_id: "yes", side: "buy", ts: "2026-11-02T10:00:00Z", size: "100", price: "0.40" },
|
|
72
|
+
{ venue: "kalshi", market_id: "KXKBORFI-26NOV030430SAMKTW-Y", token_id: "yes", side: "sell", ts: "2026-11-02T20:00:00Z", size: "30", price: "0.62" },
|
|
73
|
+
],
|
|
74
|
+
{ asOf: "2026-11-04T00:00:00Z" },
|
|
75
|
+
);
|
|
76
|
+
console.log(result.totals.pnl_raw, result.totals.pnl_before_fees_raw, result.totals.fees_raw, result.totals.decimals);
|
|
77
|
+
for (const position of result.positions) console.log(position.token_id, position.status, position.outcome, position.pnl_raw);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- **Prices.** A trade carries `price` (0 to 1) or an exact `notional_raw`, or neither: then the last fill (`history: "fills"`, the default, Builder and Pro) or candle (`history: "candles"`, `candleRes`, `1h` by default; any size on Builder and Pro, Polymarket `1d` only on Free and History) at or before its time prices it. A candle prices a time only once its bucket has ended. `lookbackSeconds` (a day by default) is how far back it looks, a candle more for candles. An open position at `asOf` is marked the same way. Trades that all carry a price, on markets resolved by `asOf`, read no fills or candles, so they run on every plan.
|
|
81
|
+
- **What it reads.** The fee rows of the trades' venues, their markets and those markets' resolutions (a request per 100 markets), and the history windows above. Pass any of them (`fees`, `markets`, `resolutions`, `fills`, `candles`) to read nothing for it.
|
|
82
|
+
- **Fees.** The schedule row in force for the market's `fee_category` at the trade's time, as on [Fees](https://docs.skewtape.com/fees); `role: "maker"` pays the maker fee where the venue charges one. A trade no row covers is refused, and the error names it. Where the data policy withholds a market's `fee_category` (the market row reads `blocked` true), give it on the trade (`fee_category`), or pass `onMissingFee: "zero"` to count the fee as zero with a warning.
|
|
83
|
+
- **Value.** At `asOf` (now by default), each position is worth what its market resolved to (1 a share for the outcome it resolved to, 0 for the other), or, still open, the last price on record. A market whose current word is a reversal (it resolved, then the venue's word changed) is valued as open, at the last price on record, so it needs the history read on its window. A voided market is valued only with `voidPayout`, since what a venue pays on a void is its rule. Nothing after `asOf` is read.
|
|
84
|
+
- **Exact.** Amounts are bigints in raw units (`totals.decimals`), prices exact fractions as strings; `backtestToJSON(result)` gives plain numbers. `runBacktest(...)` is the same arithmetic over data you pass in, with no request. `conformance/backtest.json` pins it; the Python SDK passes the same vectors, and every fee in them is checked against Skewtape's own fee code. `takerFeeRaw`, `makerFeeRaw` and `selectFeeRow` are exported for fills you price yourself.
|
|
85
|
+
|
|
86
|
+
## Live feed
|
|
87
|
+
|
|
88
|
+
`sk.stream({ topics })` reads the live feed (Builder and Pro) and reconnects by itself: it resumes from the last event it gave you, so nothing is missed or given twice, waits longer after each failed connection, and drops a trade it already gave you, by `(venue, tx_hash, log_index)`. It yields the server's messages: `event`, `snapshot`, `resync`, and the errors that leave the connection running. An error reconnecting cannot fix (a bad key, a plan without the feed or the topic) throws. It uses the platform's WebSocket (browsers, Node 22 and later); on Node 20 pass one, such as the `ws` package's.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { WebSocket } from "ws"; // Node 20 only
|
|
92
|
+
|
|
93
|
+
const stream = sk.stream({ topics: ["trades"], venues: ["kalshi"], WebSocket });
|
|
94
|
+
for await (const msg of stream) {
|
|
95
|
+
if (msg.op === "event" && msg.kind === "trade") {
|
|
96
|
+
const fill = msg.payload as { market_id: string; price: number; size_raw: number };
|
|
97
|
+
console.log(fill.market_id, fill.price, fill.size_raw);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`stream.resumeFrom` is where the stream would resume: keep it, and pass it as `resumeFrom` to go on later from there (`stream.lastSeq` is the last event's seq only, unset before the first event). Before the first event it resumes from where the first connection started, so a quiet stream misses nothing across a deploy either. If the account resumes more often than its plan allows, the feed refuses with `replay_limited`: the stream yields that error, which says how long the wait is, then waits and subscribes again. It pings the server every heartbeat and reconnects when a connection goes silent, and if your loop falls 10,000 messages behind, it reconnects from the last seq it gave you rather than hold more. A topic your plan no longer covers is told once as an error and left out when it reconnects; the other topics go on. The key is a private field: logging the client or the stream does not show it. `stream.close()` ends it, a wait included.
|
|
103
|
+
|
|
104
|
+
## Kalshi, live and optional
|
|
105
|
+
|
|
106
|
+
Skewtape's Kalshi data (markets, fills, candles, resolutions) comes from the calls above, under the Kalshi data licence. `sk.kalshi()` is something else: an optional live client that calls Kalshi's Trade API from your machine, under your own Kalshi membership, for a reading of the live venue beside that history. It is read only, writes nothing to disk, and never talks to a Skewtape host.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const kalshi = sk.kalshi(); // public requests; with your own key: sk.kalshi({ accessKey: keyId, privateKey: pem })
|
|
110
|
+
|
|
111
|
+
// The live Kalshi markets of a matched event, found by the ticker its kalshi
|
|
112
|
+
// and kalshi_dflow members share.
|
|
113
|
+
const event = await sk.events.get("st_evt_00412");
|
|
114
|
+
for (const market of await kalshi.marketsFor(event)) {
|
|
115
|
+
console.log(market.ticker, market.status, market.yes_bid_dollars, market.yes_ask_dollars);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const book = await kalshi.orderbook("KXKBORFI-26NOV030430SAMKTW-Y", { depth: 5 });
|
|
119
|
+
console.log(book.best_yes_bid, book.best_no_bid);
|
|
120
|
+
|
|
121
|
+
for await (const trade of kalshi.trades({ ticker: "KXKBORFI-26NOV030430SAMKTW-Y", since })) {
|
|
122
|
+
console.log(trade.created_time, trade.taker_outcome_side, trade.yes_price_dollars, trade.count_fp);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const sticks = await kalshi.candlesticks("KXKBORFI-26NOV030430SAMKTW-Y", { period: "1h", since });
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
- `kalshi.markets({ status, seriesTicker, eventTicker, tickers })`, `kalshi.market(ticker)`, `kalshi.trades({ ticker, since, until })`, `kalshi.orderbook(ticker, { depth })` and `kalshi.candlesticks(ticker, { period, since, until })` (`1m`, `1h` or `1d`; a Kalshi `1d` stick is a New York day). `kalshi.tickers(event)` and `kalshi.marketsFor(event)` read a matched event's `kalshi` and `kalshi_dflow` members, whose `market_id` is the Kalshi ticker.
|
|
129
|
+
- Prices and counts are Kalshi's own strings; every row keeps the whole JSON object in `raw`.
|
|
130
|
+
- Kalshi serves older trades and settled markets from its `/historical` routes, past a cutoff that moves, and this client does not call them: for that history use `sk.fills` and `sk.markets`.
|
|
131
|
+
- Your key goes in the options, from wherever you keep it; the client reads no environment variable. With one, every request is signed as Kalshi's docs describe (Ed25519 or RSA, through `node:crypto`) and counts against your account's rate-limit tier. Without one the calls are public requests. Kalshi's terms and rate limits apply to them, not your Skewtape plan.
|
|
132
|
+
- A `429` is retried with a backoff (0.5, 1 and 2 seconds); a request past `timeout` (30 seconds by default) and any other error throw `KalshiError`, a `SkewtapeError` with Kalshi's `code`, `message` and `details`.
|
|
133
|
+
|
|
134
|
+
## Routing an order with your own code
|
|
135
|
+
|
|
136
|
+
`route(...)` (also `sk.route`) builds an unsigned order and stops there: it never signs, never sends, never takes a private key, and needs no Skewtape key. The builder code or fee it carries is yours; omit it and the order carries none. The package holds no Skewtape code or account, and a test keeps it that way.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { geoblock, hyperliquidApproveBuilderFee, route } from "skewtape";
|
|
140
|
+
|
|
141
|
+
// Polymarket: a V2 order to sign as EIP-712 typed data. exchange is the book's
|
|
142
|
+
// ("ctf", "neg_risk" or "protocol_v2"); tickSize is the book's tick.
|
|
143
|
+
const order = route({
|
|
144
|
+
venue: "polymarket", exchange: "ctf", tokenId: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
|
|
145
|
+
side: "BUY", price: "0.52", size: "10", tickSize: "0.01", maker: yourAddress,
|
|
146
|
+
builder: yourBuilderCode, // optional: your bytes32 code from your Polymarket profile
|
|
147
|
+
});
|
|
148
|
+
const signature = await walletClient.signTypedData(order.typedData); // viem; ethers v6: signer.signTypedData(domain, types, message)
|
|
149
|
+
const body = order.postBody(signature, yourClobApiKeyId); // POST /order, with your CLOB credentials
|
|
150
|
+
|
|
151
|
+
// DFlow (tokenized Kalshi outcome tokens): the GET /order request that returns
|
|
152
|
+
// the unsigned transaction, with your fee and fee account.
|
|
153
|
+
const request = route({
|
|
154
|
+
venue: "kalshi_dflow", inputMint: usdcMint, outputMint: outcomeMint, amount: 25_000_000,
|
|
155
|
+
userPublicKey: yourUsersWallet, platformFeeScale: 50, feeAccount: yourFeeTokenAccount,
|
|
156
|
+
});
|
|
157
|
+
// fetch(request.fullUrl, { headers: { [request.apiKeyHeader]: yourDflowKey } })
|
|
158
|
+
|
|
159
|
+
// Hyperliquid HIP-4 outcomes: an order on side 0 or 1 of an outcome (coin
|
|
160
|
+
// "#960" is outcome 96, side 0), signed by the key that trades (an API wallet).
|
|
161
|
+
const hl = route({
|
|
162
|
+
venue: "hyperliquid", outcome: 96, side: 0, isBuy: false, price: "0.55", size: "20",
|
|
163
|
+
builder: yourBuilderAddress, builderFee: 10, // optional, yours: 10 is 1 basis point
|
|
164
|
+
});
|
|
165
|
+
const hlSignature = await apiWallet.signTypedData(hl.typedData);
|
|
166
|
+
// fetch(hl.exchangeUrl, { method: "POST", body: JSON.stringify(hl.postBody(hlSignature)) })
|
|
167
|
+
|
|
168
|
+
// Once per builder, the user's main wallet approves your maximum fee.
|
|
169
|
+
const approval = hyperliquidApproveBuilderFee({ builder: yourBuilderAddress, maxFeeRate: "0.01%", signatureChainId: 42161 });
|
|
170
|
+
// A browser wallet signs approval.typedDataJson() (eth_signTypedData_v4); a viem key signs approval.digest.
|
|
171
|
+
|
|
172
|
+
const where = await geoblock.polymarket(); // "allowed", "blocked" or "unknown"
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
- **Polymarket:** the order is the V2 `Order` (salt, maker, signer, tokenId, makerAmount, takerAmount, side, signatureType, timestamp, metadata, builder), on the exchange's EIP-712 domain: "Polymarket CTF Exchange", version "2" for `ctf` and `neg_risk`, "3" for a Protocol V2 book (`protocol_v2`), Polygon. Prices and sizes are decimal strings, never floats, and amounts follow Polymarket's rounding by tick size. A limit order (`GTC`, `GTD` with `expiration` in Unix seconds) and a market SELL (`FOK`, `FAK`) take `size` in shares; a market BUY takes `amount`, the USD to spend, with `price` the most you pay. `signatureType` is `EOA` (the default; `signer` is the maker), `POLY_PROXY` or `POLY_GNOSIS_SAFE` (pass `signer`). A Deposit Wallet order (`POLY_1271`) is signed through an ERC-7739 wrapper this builder does not produce. `typedDataJson()` gives the JSON `eth_signTypedData_v4` takes. Builder fee rates are set on your Polymarket profile, not in the order.
|
|
176
|
+
- **DFlow:** `platformFeeScale` is DFlow's fee for a prediction market swap, 0 to 999 in thousandths; `platformFeeBps` its fixed spot fee. Either needs `feeAccount`, your token account for the fee mint, which must exist before the trade.
|
|
177
|
+
- **Hyperliquid (HIP-4 outcomes):** the order is an L1 action, signed as a "phantom agent" on the EIP-712 domain "Exchange", chain 1337, so it is signed by a key you hold (usually an API wallet your user approved), not a browser wallet on its own chain. `builder` and `builderFee` (tenths of a basis point, at most 1000) are yours, both or neither; your user first approves your maximum fee with their main wallet (`hyperliquidApproveBuilderFee`; viem refuses its type name, so a viem key signs `digest`). Prices have at most 5 significant figures and 8 decimals less `szDecimals` (pass it if you have it: the docs do not give one for outcomes); `tif` is `Gtc`, `Ioc` or `Alo`; `nonce` is now in milliseconds by default. Hyperliquid's HIP-4 page says outcome fees are zero for testing and builders earn on sell orders, its fees page that fees are charged on closing or settling: the order is the same either way.
|
|
178
|
+
- **Your users are your responsibility:** who may trade on which venue, from where, under which terms. `geoblock.polymarket()` asks Polymarket whether it would take orders from this machine's network location, and any failure (network, timeout, an unexpected reply) is `"unknown"`, never `"allowed"`. It is one indication, not a licence.
|
|
179
|
+
|
|
180
|
+
## Licence
|
|
181
|
+
|
|
182
|
+
MIT, copyright 2026 Blockbrainers SAS (Skewtape): see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fee-aware P&L for a list of trades the caller supplies, over the history
|
|
3
|
+
* Skewtape records (story E4).
|
|
4
|
+
*
|
|
5
|
+
* This is arithmetic on history. Each trade is priced at its own price, or at
|
|
6
|
+
* the last recorded fill or candle at or before its time; the fee the schedule
|
|
7
|
+
* in force charges is taken off; every position is then valued at the outcome
|
|
8
|
+
* its market resolved to, or, still open, at the last recorded price at or
|
|
9
|
+
* before asOf. Nothing is read from after asOf. It forecasts nothing, suggests
|
|
10
|
+
* no trade and optimises nothing: the result is what these trades come to on
|
|
11
|
+
* the record, before and after fees.
|
|
12
|
+
*
|
|
13
|
+
* Amounts are exact bigints in raw units (a position's at its fill decimals,
|
|
14
|
+
* totals at the largest decimals among the positions); prices are exact
|
|
15
|
+
* fractions, shown as decimal strings when they end. conformance/backtest.json
|
|
16
|
+
* pins the arithmetic, and the Python and TypeScript SDKs pass the same vectors.
|
|
17
|
+
*
|
|
18
|
+
* import { runBacktest } from "skewtape";
|
|
19
|
+
* const result = runBacktest(trades, { asOf, fees, markets, resolutions, fills });
|
|
20
|
+
* console.log(result.totals.pnl_raw, result.totals.fees_raw);
|
|
21
|
+
*
|
|
22
|
+
* sk.backtest(trades) fetches the fees, markets, resolutions and price history
|
|
23
|
+
* for the trades first, then runs the same function.
|
|
24
|
+
*/
|
|
25
|
+
import { SkewtapeError, type ErrorFields } from "./errors.js";
|
|
26
|
+
import { type FeeRowInput } from "./fees.js";
|
|
27
|
+
export declare const CANDLE_MICROS: Record<string, bigint>;
|
|
28
|
+
/** A backtest that cannot run as asked; code says why: bad_trade, after_as_of, price_missing, fee_row_missing, decimals_mismatch. */
|
|
29
|
+
export declare class BacktestError extends SkewtapeError {
|
|
30
|
+
constructor(message: string, code: string, fields?: ErrorFields);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One trade to replay. side is buy or sell (of token_id), role taker (the
|
|
34
|
+
* default) or maker. The size is size (shares, a decimal) or size_raw (raw
|
|
35
|
+
* units at decimals); the price is price (0 to 1), or notional_raw (raw
|
|
36
|
+
* units, exact), or neither, and then the history prices it. decimals and
|
|
37
|
+
* fee_category default to the history's and the market's.
|
|
38
|
+
*/
|
|
39
|
+
export interface Trade {
|
|
40
|
+
venue: string;
|
|
41
|
+
market_id: string;
|
|
42
|
+
token_id: string;
|
|
43
|
+
side: "buy" | "sell" | string;
|
|
44
|
+
ts: Date | string;
|
|
45
|
+
size?: string | number | bigint;
|
|
46
|
+
size_raw?: number | bigint | string;
|
|
47
|
+
price?: string | number;
|
|
48
|
+
notional_raw?: number | bigint | string;
|
|
49
|
+
role?: "taker" | "maker" | string;
|
|
50
|
+
decimals?: number;
|
|
51
|
+
fee_category?: string;
|
|
52
|
+
}
|
|
53
|
+
type Row = Record<string, unknown>;
|
|
54
|
+
/** One trade as replayed: size, notional and fee in raw units at decimals, the price and its source, the fee row used, the cash it moved. */
|
|
55
|
+
export interface TradeResult {
|
|
56
|
+
index: number;
|
|
57
|
+
venue: string;
|
|
58
|
+
market_id: string;
|
|
59
|
+
token_id: string;
|
|
60
|
+
side: string;
|
|
61
|
+
role: string;
|
|
62
|
+
ts: string;
|
|
63
|
+
decimals: number;
|
|
64
|
+
size_raw: bigint;
|
|
65
|
+
notional_raw: bigint;
|
|
66
|
+
price: string;
|
|
67
|
+
price_source: "given" | "notional" | "fill" | "candle";
|
|
68
|
+
fee_raw: bigint;
|
|
69
|
+
fee_category: string | null;
|
|
70
|
+
fee_row_effective_from: string | null;
|
|
71
|
+
cash_raw: bigint;
|
|
72
|
+
}
|
|
73
|
+
/** One (venue, market, token) position and its value at asOf; value_raw and pnl_raw are null when nothing values it. */
|
|
74
|
+
export interface PositionResult {
|
|
75
|
+
venue: string;
|
|
76
|
+
market_id: string;
|
|
77
|
+
token_id: string;
|
|
78
|
+
decimals: number;
|
|
79
|
+
shares_raw: bigint;
|
|
80
|
+
bought_raw: bigint;
|
|
81
|
+
sold_raw: bigint;
|
|
82
|
+
fees_raw: bigint;
|
|
83
|
+
cash_raw: bigint;
|
|
84
|
+
status: "resolved" | "voided" | "open";
|
|
85
|
+
outcome: string | null;
|
|
86
|
+
payout: string | null;
|
|
87
|
+
mark_price: string | null;
|
|
88
|
+
value_raw: bigint | null;
|
|
89
|
+
value_source: "resolution" | "void_payout" | "mark" | null;
|
|
90
|
+
pnl_raw: bigint | null;
|
|
91
|
+
pnl_before_fees_raw: bigint | null;
|
|
92
|
+
}
|
|
93
|
+
/** Every valued position summed at decimals; fees_raw is their fees (the fee impact), fees_paid_raw every trade's. */
|
|
94
|
+
export interface Totals {
|
|
95
|
+
decimals: number;
|
|
96
|
+
pnl_raw: bigint;
|
|
97
|
+
pnl_before_fees_raw: bigint;
|
|
98
|
+
fees_raw: bigint;
|
|
99
|
+
fees_paid_raw: bigint;
|
|
100
|
+
realized_pnl_raw: bigint;
|
|
101
|
+
unrealized_pnl_raw: bigint;
|
|
102
|
+
complete: boolean;
|
|
103
|
+
}
|
|
104
|
+
/** fee_row_missing, oversold, trade_after_resolution, outcome_unmatched, voided_unsettled or no_mark, with a sentence. */
|
|
105
|
+
export interface BacktestWarning {
|
|
106
|
+
code: string;
|
|
107
|
+
message: string;
|
|
108
|
+
trade: number | null;
|
|
109
|
+
position: [string, string, string] | null;
|
|
110
|
+
}
|
|
111
|
+
export interface BacktestResult {
|
|
112
|
+
as_of: string;
|
|
113
|
+
trades: TradeResult[];
|
|
114
|
+
positions: PositionResult[];
|
|
115
|
+
totals: Totals;
|
|
116
|
+
warnings: BacktestWarning[];
|
|
117
|
+
}
|
|
118
|
+
export interface BacktestOptions {
|
|
119
|
+
asOf: Date | string;
|
|
120
|
+
fees: Iterable<FeeRowInput>;
|
|
121
|
+
markets?: Iterable<Row>;
|
|
122
|
+
resolutions?: Iterable<Row>;
|
|
123
|
+
fills?: Iterable<Row>;
|
|
124
|
+
candles?: Iterable<Row>;
|
|
125
|
+
/** Fills or candles first when both price a time. fills by default. */
|
|
126
|
+
prefer?: "fills" | "candles";
|
|
127
|
+
/** A decimal per share that settles a voided market; without it a voided position stays unvalued. */
|
|
128
|
+
voidPayout?: string | number;
|
|
129
|
+
/** error (the default) refuses a trade no fee row covers; zero counts its fee as zero and warns. */
|
|
130
|
+
onMissingFee?: "error" | "zero";
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Replay trades over the history given and value every position at asOf. See
|
|
134
|
+
* the module comment; the arithmetic is the Python SDK's, vector for vector.
|
|
135
|
+
*/
|
|
136
|
+
export declare function runBacktest(trades: Iterable<Trade | Row>, options: BacktestOptions): BacktestResult;
|
|
137
|
+
/**
|
|
138
|
+
* Whether a market's resolution events settle its positions at asOf, so they
|
|
139
|
+
* need no mark: resolved to an outcome, or voided (valued by voidPayout, or
|
|
140
|
+
* left unvalued with a warning). sk.backtest reads the asOf window only for
|
|
141
|
+
* markets this is false for.
|
|
142
|
+
*/
|
|
143
|
+
export declare function settledAt(rows: Iterable<Row>, asOf: Date | string): boolean;
|
|
144
|
+
/** A result with every bigint as a number, for JSON: the shape of the Python SDK's to_dict(). An amount past 2^53 stays a decimal string. */
|
|
145
|
+
export declare function backtestToJSON(result: BacktestResult): unknown;
|
|
146
|
+
export {};
|