Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions ts-sdk/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ts-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pod-network/trade-sdk",
"version": "0.12.0",
"version": "0.13.0",
"description": "Read/stream TypeScript SDK for the pod trading indexer: cacheable REST seeds + one multiplexed WebSocket, kept in memory. Framework-agnostic.",
"type": "module",
"sideEffects": false,
Expand Down
3 changes: 3 additions & 0 deletions ts-sdk/src/codec/fixed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { WAD } from "./units.js";

const absB = (x: bigint) => (x < 0n ? -x : x);

/** `Math.min` for bigints, which it rejects. */
export const min = (a: bigint, b: bigint) => (a < b ? a : b);

/** Decimal `*`: (a*b)/1e18 truncated toward zero. */
export function mul(a: bigint, b: bigint): bigint {
const n = a * b;
Expand Down
1 change: 1 addition & 0 deletions ts-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export {
closePreview, type ClosePreview,
priceForReturn, type ReturnPriceInput,
closestTriggers,
estimateFill, type FillEstimate,
} from "./sync/order-preview.js";
export type { SeriesResource } from "./sync/candles.js";
export { CandleSeries } from "./sync/candles.js";
Expand Down
54 changes: 53 additions & 1 deletion ts-sdk/src/sync/order-preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import type { Market, PerpPosition, PositionsSnapshot } from "../types/public.js";
import { div, imRate, mul } from "../codec/fixed.js";
import { WAD } from "../codec/units.js";
import { previewOrder } from "./order-preview.js";
import { estimateFill, previewOrder } from "./order-preview.js";

const LOT = 10n ** 12n; // 1e-6 base units — every staging/canary perp
const PRICE = 100n * WAD;
Expand Down Expand Up @@ -176,3 +176,55 @@ describe("previewOrder liquidationPrice", () => {
expect(p.liquidationPrice).toBeUndefined();
});
});

describe("estimateFill", () => {
const lvl = (price: number, volume: number) => ({ price: BigInt(price) * WAD, volume: BigInt(volume) * WAD, total: 0n, depth: 0 });
const book = {
asks: [lvl(100, 1), lvl(101, 2), lvl(103, 5)],
bids: [lvl(99, 1), lvl(98, 2)],
};

it("clears at a part-taken best level with no slippage", () => {
const f = estimateFill(book, "long", WAD / 2n);
expect(f).toEqual({ filled: WAD / 2n, price: 100n * WAD, slippagePct: 0, exhausted: false });
});

it("taking a level whole clears midway to the next one", () => {
expect(estimateFill(book, "long", WAD).price).toBe(100n * WAD + WAD / 2n);
});

it("charges the whole fill the last level's price, not the average across levels", () => {
const f = estimateFill(book, "long", 2n * WAD);
expect(f.price).toBe(101n * WAD); // 101 still holds 1 after this fill
expect(f.slippagePct).toBeCloseTo(1, 6);
});

it("stops at the limit, and the clearing price never passes it", () => {
// 100 and 101 taken whole: the midpoint to 103 would be 102.5, over the limit.
const f = estimateFill(book, "long", 5n * WAD, 102n * WAD);
expect(f.filled).toBe(3n * WAD);
expect(f.price).toBe(102n * WAD);
expect(f.exhausted).toBe(false);
});

it("fills nothing when the best level is already past the limit", () => {
expect(estimateFill(book, "long", WAD, 99n * WAD)).toEqual({ filled: 0n, exhausted: false });
});

it("walks the bids for a short, slippage still counted as worse", () => {
const f = estimateFill(book, "short", 2n * WAD);
expect(f.price).toBe(98n * WAD);
expect(f.slippagePct).toBeCloseTo((1 / 99) * 100, 6);
});

it("flags running off the levels given, clearing at the last one with nothing past it", () => {
const f = estimateFill(book, "short", 10n * WAD, 90n * WAD);
expect(f.filled).toBe(3n * WAD);
expect(f.price).toBe(98n * WAD);
expect(f.exhausted).toBe(true);
});

it("an empty side fills nothing and is exhausted", () => {
expect(estimateFill({ asks: [], bids: [] }, "long", WAD)).toEqual({ filled: 0n, exhausted: true });
});
});
58 changes: 56 additions & 2 deletions ts-sdk/src/sync/order-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
// implied_leverage = (Σ current perp notional + notional) / perps_equity
// liquidation = mark where equity falls to Σ maintenance margin (im/2)

import type { Market, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
import { div, imRate, mul } from "../codec/fixed.js";
import type { Market, Orderbook, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
import { div, imRate, min, mul } from "../codec/fixed.js";
import { alignSize, parseAmount, toNumber, WAD } from "../codec/units.js";

export interface ReturnPriceInput {
Expand Down Expand Up @@ -220,3 +220,57 @@ export function closePreview(
fee: mul(notional, input.feeRate ?? 0n),
};
}

export interface FillEstimate {
/** Base size the book fills within `limit` (≤ `size`). */
filled: bigint;
/** The price the whole fill clears at were this the batch's only order;
* undefined when nothing fills. A batch clears every match at one price and
* a market order never sets it, so this is at least the last level reached —
* not an average across the levels. */
price?: bigint;
/** How much worse `price` is than the best level, in percent — the cost of
* the size alone, spread excluded. */
slippagePct?: number;
/** The walk ran off the last level given while still inside `limit`. On a
* depth-truncated book `filled` is then a floor, not an estimate. */
exhausted: boolean;
}

/**
* What a taker order of `size` (base, magnitude) would fill against `book`:
* walks the opposite side best-first — asks for a long, bids for a short — and
* stops at `limit`, a market order's protective price. Grouped levels make the
* prices approximate to the grouping.
*/
export function estimateFill(
book: Pick<Orderbook, "bids" | "asks">,
side: "long" | "short",
size: bigint,
limit?: bigint,
): FillEstimate {
const levels = side === "long" ? book.asks : book.bids;
const within = (p: bigint) => limit === undefined || (side === "long" ? p <= limit : p >= limit);
let filled = 0n;
let left = 0n; // volume the last level reached still holds
let i = 0;
for (; i < levels.length && filled < size; i++) {
const l = levels[i]!;
if (!within(l.price)) break;
const take = min(l.volume, size - filled);
filled += take;
left = l.volume - take;
}
const exhausted = filled < size && i === levels.length;
if (filled === 0n) return { filled, exhausted };
// The clearing range runs from the last level matched to the first level left
// unmatched — that same level when only part of it was taken — and settles at
// its midpoint, never past the order's own limit (doc/protocol/orderbook.md, Clearing).
const last = levels[i - 1]!.price;
const unmatched = left > 0n ? last : levels[i]?.price;
let price = unmatched === undefined ? last : (last + unmatched) / 2n;
if (limit !== undefined && !within(price)) price = limit;
const best = levels[0]!.price;
const worse = side === "long" ? price - best : best - price;
return { filled, price, slippagePct: (Number(worse) / Number(best)) * 100, exhausted };
}
Loading