@0xmonaco/types 1.0.41 → 1.0.42-develop.791e6f3

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.
@@ -123,6 +123,13 @@ export interface GetCandlesticksParams {
123
123
  endTime?: number;
124
124
  /** Maximum number of bars to return (max: 500, server defaults to 350 if omitted) */
125
125
  limit?: number;
126
+ /**
127
+ * Price series to chart. `"trade"` (default) returns the trade-derived OHLCV
128
+ * series; `"mark"` returns the mark-price series (margin pairs only), where
129
+ * each candle's open/high/low/close are the bucket's closing mark and volume
130
+ * is 0. Omit for the trade series.
131
+ */
132
+ priceType?: "trade" | "mark";
126
133
  }
127
134
  /**
128
135
  * Query parameters for fetching trading pairs
@@ -122,6 +122,28 @@ export interface PortfolioAssetRow {
122
122
  allocationPct?: string;
123
123
  priceAsOf?: string;
124
124
  pricingStatus: "priced" | "unpriced";
125
+ /**
126
+ * Weighted-average cost per unit of the holding, quote-denominated, from the
127
+ * spot cost-basis engine. Present only when a cost-basis checkpoint exists.
128
+ */
129
+ avgCost?: string;
130
+ /**
131
+ * Unrealized PnL for the holding: costBasisQuantity x (markPrice - avgCost),
132
+ * quote-denominated. Uses the cost-basis engine's folded quantity so it agrees
133
+ * with the portfolio summary headline. Present only when both a cost-basis
134
+ * checkpoint and a mark price exist.
135
+ */
136
+ unrealizedPnl?: string;
137
+ /**
138
+ * Unrealized return on the holding's cost basis, as a percentage. Present only
139
+ * when unrealizedPnl is present and the cost basis is non-zero.
140
+ */
141
+ unrealizedRoe?: string;
142
+ /**
143
+ * Cumulative realized PnL booked against this holding over its lifetime, gross
144
+ * of fees, quote-denominated. Present only when a cost-basis checkpoint exists.
145
+ */
146
+ cumRealized?: string;
125
147
  }
126
148
  export interface PortfolioAssets {
127
149
  window: PortfolioSeriesWindow;
@@ -151,6 +151,15 @@ export interface PositionRisk {
151
151
  * as unavailable, never as zero.
152
152
  */
153
153
  liquidationPrice: string;
154
+ /**
155
+ * Account distress ratio: maintenance margin required divided by equity
156
+ * (higher is closer to liquidation, decimal string). Equity that is zero or
157
+ * negative has no meaningful quotient, so an account that still owes a
158
+ * maintenance requirement reports the max-decimal sentinel
159
+ * (`79228162514264337593543950335`, maximal distress) rather than zero or a
160
+ * negative value, and an account with no open maintenance requirement reports
161
+ * `0`. Clamp the sentinel before display.
162
+ */
154
163
  marginRatio: string;
155
164
  /**
156
165
  * Position-scoped requirement at markPrice using the market
@@ -169,7 +178,16 @@ export interface TpSlLeg {
169
178
  orderType: OrderType;
170
179
  limitPrice?: string;
171
180
  quantity?: string;
172
- /** Resolve the full live position size when triggered. */
181
+ /**
182
+ * Resolve the full live position size when triggered.
183
+ *
184
+ * A full-close leg supersedes the position's previously active full-close
185
+ * legs of the same condition type — they are cancelled in the same engine
186
+ * step that creates this one, so moving a take-profit or stop-loss is a
187
+ * single call. Fixed-`quantity` legs never participate (laddered partial
188
+ * exits stack), a superseded leg's OCO sibling stays active, and legs
189
+ * attached to an entry order are excluded on both sides.
190
+ */
173
191
  closePosition?: boolean;
174
192
  timeInForce?: Extract<TimeInForce, "GTC" | "IOC">;
175
193
  slippageToleranceBps?: number;
@@ -199,6 +199,12 @@ export interface AccountBalance {
199
199
  lockedBalanceRaw: string;
200
200
  /** Total balance (available + locked) in raw format (wei) */
201
201
  totalBalanceRaw: string;
202
+ /**
203
+ * True when this asset is the chain's wrapped-native token (e.g. WSEI):
204
+ * vault deposits can be made in native coin via depositNative (the vault
205
+ * wraps on entry) and withdrawals pay out native.
206
+ */
207
+ wrappedNative?: boolean;
202
208
  }
203
209
  /**
204
210
  * A single user trade execution.
@@ -15,7 +15,7 @@ import type { SubAccountsAPI } from "../sub-accounts";
15
15
  import type { SweeperAPI } from "../sweeper";
16
16
  import type { TradingAPI, TradingMode } from "../trading";
17
17
  import type { VaultAPI } from "../vault";
18
- import type { ConditionalOrderEvent, MonacoWebSocketConfig, OHLCVEvent, OrderbookEvent, OrderbookQuotationMode, OrderEvent, TradeEvent, UserBalanceEvent, UserMovementEvent } from "../websocket";
18
+ import type { ConditionalOrderEvent, MonacoWebSocketConfig, OHLCVEvent, OrderbookEvent, OrderbookQuotationMode, OrderEvent, TradeEvent, TwapOrderEvent, UserBalanceEvent, UserMovementEvent } from "../websocket";
19
19
  import type { WhitelistAPI } from "../whitelist";
20
20
  import type { WithdrawalsAPI } from "../withdrawals";
21
21
  import type { Network } from "./network";
@@ -154,6 +154,7 @@ export interface MonacoSDK {
154
154
  userOrders: (handler: (event: OrderEvent) => void) => () => void;
155
155
  balances: (handler: (event: UserBalanceEvent) => void) => () => void;
156
156
  conditionalOrders: (handler: (event: ConditionalOrderEvent) => void, tradingPairId?: string) => () => void;
157
+ twapOrders: (handler: (event: TwapOrderEvent) => void, tradingPairId?: string) => () => void;
157
158
  };
158
159
  /** Wallet client for all blockchain operations (undefined until set) */
159
160
  walletClient: WalletClient | undefined;
@@ -6,7 +6,7 @@
6
6
  import type { BaseAPI } from "../api/index";
7
7
  import type { MarginMode } from "../margin-accounts";
8
8
  import type { Order, OrderSide, PositionSide, TimeInForce, TradingMode } from "./orders";
9
- import type { BatchCancelOrdersResponse, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchReplaceOrderParams, BatchReplaceOrdersResponse, CancelConditionalOrderResponse, CancelOrderResponse, ConditionalOrder, CreateOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, ParentTpSlLegParams, ReplaceOrderResponse } from "./responses";
9
+ import type { BatchCancelOrdersResponse, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchReplaceOrderParams, BatchReplaceOrdersResponse, CancelConditionalOrderResponse, CancelOrderResponse, CancelTwapOrderResponse, ConditionalOrder, CreateOrderResponse, CreateTwapOrderOptions, CreateTwapOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, ListTwapOrdersParams, ListTwapOrdersResponse, ParentTpSlLegParams, ReplaceOrderResponse, TwapOrder } from "./responses";
10
10
  /**
11
11
  * Trading API interface.
12
12
  * Provides methods for placing and managing orders.
@@ -179,7 +179,35 @@ export interface TradingAPI extends BaseAPI {
179
179
  * @returns Promise resolving to the order details
180
180
  */
181
181
  getOrder(orderId: string): Promise<GetOrderResponse>;
182
+ /**
183
+ * Creates a server-side TWAP (time-weighted average price) parent order.
184
+ * The matching engine executes it as a schedule of market child orders
185
+ * across the window, hard-stopping at the window end.
186
+ * @param tradingPairId - Trading pair UUID
187
+ * @param side - Order side ("BUY" or "SELL")
188
+ * @param quantity - Total quantity to execute across the window (at least 2x the pair's minimum order size)
189
+ * @param options - Window (exactly one of durationSeconds or endTime) plus optional execution parameters
190
+ * @returns Promise resolving to the TWAP creation result
191
+ */
192
+ createTwapOrder(tradingPairId: string, side: OrderSide, quantity: string, options: CreateTwapOrderOptions): Promise<CreateTwapOrderResponse>;
193
+ /**
194
+ * Cancels a TWAP parent order. Child orders are IOC and never rest, so the
195
+ * cancel is atomic and immediate; executed quantity stands.
196
+ * @param twapOrderId - TWAP parent order UUID
197
+ * @returns Promise resolving to the cancellation result
198
+ */
199
+ cancelTwapOrder(twapOrderId: string): Promise<CancelTwapOrderResponse>;
200
+ /**
201
+ * Gets a single TWAP parent order by its UUID. Users can only access their
202
+ * own TWAP orders.
203
+ */
204
+ getTwapOrder(twapOrderId: string): Promise<TwapOrder>;
205
+ /**
206
+ * Lists TWAP parent orders for the authenticated user with pagination and
207
+ * optional state / trading pair filters.
208
+ */
209
+ listTwapOrders(params?: ListTwapOrdersParams): Promise<ListTwapOrdersResponse>;
182
210
  }
183
- export type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderRole, OrderSide, OrderStatus, OrderStatusFilter, OrderTerminalReason, OrderType, PositionSide, TimeInForce, TradingMode, } from "./orders";
211
+ export type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderRole, OrderSide, OrderStatus, OrderStatusFilter, OrderTerminalReason, OrderType, PositionSide, TimeInForce, TradingMode, TwapOrderState, } from "./orders";
184
212
  export { ORDER_STATUS_VALUES } from "./orders";
185
- export type { BatchCancelError, BatchCancelOrdersResponse, BatchCancelResult, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchCreateResult, BatchError, BatchReplaceOrderParams, BatchReplaceOrdersResponse, BatchReplaceResult, CancelConditionalOrderResponse, CancelOrderResponse, ConditionalOrder, CreateOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, MatchResult, ParentTpSlLegParams, ReplaceOrderResponse, UpdatedFields, } from "./responses";
213
+ export type { BatchCancelError, BatchCancelOrdersResponse, BatchCancelResult, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchCreateResult, BatchError, BatchReplaceOrderParams, BatchReplaceOrdersResponse, BatchReplaceResult, CancelConditionalOrderResponse, CancelOrderResponse, CancelTwapOrderResponse, ConditionalOrder, CreateOrderResponse, CreateTwapOrderOptions, CreateTwapOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, ListTwapOrdersParams, ListTwapOrdersResponse, MatchResult, ParentTpSlLegParams, ReplaceOrderResponse, TwapOrder, UpdatedFields, } from "./responses";
@@ -160,3 +160,11 @@ export type ConditionalOrderTriggerSource = "MARK_PRICE";
160
160
  * Conditional TP/SL lifecycle state.
161
161
  */
162
162
  export type ConditionalOrderState = "PENDING_PARENT" | "ACTIVE" | "TRIGGERING" | "TRIGGERED" | "CANCELLED" | "EXPIRED" | "FAILED";
163
+ /**
164
+ * TWAP parent-order lifecycle state.
165
+ * - PENDING: window start is in the future; no child orders yet
166
+ * - ACTIVE: inside the execution window; child slices are firing
167
+ * - COMPLETED: window ended (fully filled or hard-stopped with a shortfall)
168
+ * - CANCELLED: cancelled by the user before the window ended
169
+ */
170
+ export type TwapOrderState = "PENDING" | "ACTIVE" | "COMPLETED" | "CANCELLED";
@@ -4,7 +4,7 @@
4
4
  * Response types for trading operations.
5
5
  */
6
6
  import type { MarginMode } from "../margin-accounts";
7
- import type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderSide, OrderStatus, OrderStatusFilter, OrderType, PositionSide, TimeInForce, TradingMode } from "./orders";
7
+ import type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderSide, OrderStatus, OrderStatusFilter, OrderType, PositionSide, TimeInForce, TradingMode, TwapOrderState } from "./orders";
8
8
  /**
9
9
  * Match result information for order execution.
10
10
  * Contains detailed information about trades, fills, and execution quality.
@@ -455,3 +455,193 @@ export interface ListConditionalOrdersResponse {
455
455
  page: number;
456
456
  pageSize: number;
457
457
  }
458
+ /**
459
+ * Options for creating a server-side TWAP parent order.
460
+ *
461
+ * The execution window is mandatory: exactly one of `durationSeconds` or
462
+ * `endTime` must be set. `startTime` is only valid together with `endTime`
463
+ * and defaults to now.
464
+ */
465
+ export interface CreateTwapOrderOptions {
466
+ /**
467
+ * Execution window length in seconds from launch. Exactly one of
468
+ * `durationSeconds` or `endTime` must be set. Bounds (env-tunable server
469
+ * defaults): 300 to 86400 (5 minutes to 24 hours).
470
+ */
471
+ durationSeconds?: number | string;
472
+ /** Window start (ISO 8601). Only valid together with `endTime`; defaults to now. */
473
+ startTime?: string;
474
+ /**
475
+ * Window end (ISO 8601). Exactly one of `durationSeconds` or `endTime` must
476
+ * be set. Execution stops hard at this time; any unfilled remainder is
477
+ * reported as shortfall.
478
+ */
479
+ endTime?: string;
480
+ /**
481
+ * Optional parent-level limit price as decimal string. BUY child orders
482
+ * never execute above it, SELL children never below it. Omitted: slippage
483
+ * band protection only.
484
+ */
485
+ limitPrice?: string;
486
+ /** Per-slice protective price band in basis points around the reference price (default 100 = 1%). */
487
+ slippageToleranceBps?: number;
488
+ /**
489
+ * Apply seeded randomization to slice sizes (±30%) and timing (±30%);
490
+ * default true. The seed is recorded for audit, so the schedule is
491
+ * reproducible to compliance but unpredictable to the market.
492
+ */
493
+ randomize?: boolean;
494
+ /** Whether the TWAP parent is reduce-only (margin only). Child orders inherit it and clamp to the live position. */
495
+ reduceOnly?: boolean;
496
+ /** Trading mode: "SPOT" or "MARGIN" (default: "SPOT"). */
497
+ tradingMode?: TradingMode;
498
+ /** Margin account UUID for margin TWAP orders. Resolved once at creation and reused by every child order. */
499
+ marginAccountId?: string;
500
+ /** Existing isolated risk bucket UUID for risk-bucket-scoped margin TWAP orders. Snapshot at creation. */
501
+ riskBucketId?: string;
502
+ /** Risk bucket mode for margin TWAP orders. Defaults to ISOLATED. */
503
+ marginMode?: MarginMode;
504
+ /** Leverage multiplier as a decimal string. Required for normal margin TWAP orders; optional and ignored for reduce-only. */
505
+ leverage?: string;
506
+ /** Strategy key used to group risk buckets for margin orders. */
507
+ strategyKey?: string;
508
+ /** Use master account balance for sub-account orders. */
509
+ useMasterBalance?: boolean;
510
+ /** Client-assigned idempotency key (max 36 chars), unique per user and application. A duplicate is rejected with 409. */
511
+ clientTwapId?: string;
512
+ }
513
+ /**
514
+ * Response from creating a TWAP parent order.
515
+ */
516
+ export interface CreateTwapOrderResponse {
517
+ /** Created TWAP parent order UUID */
518
+ twapOrderId: string;
519
+ /**
520
+ * Result status: SUCCESS or FAILED. SUCCESS means the parent is durably
521
+ * recorded; execution itself is best-effort within the window.
522
+ */
523
+ status: "SUCCESS" | "FAILED";
524
+ /** Human-readable status message */
525
+ message: string;
526
+ /** Initial parent state: always PENDING at create; the parent activates on its first attempted slice */
527
+ state: TwapOrderState;
528
+ /** Resolved margin account UUID for margin TWAP orders */
529
+ marginAccountId?: string;
530
+ /** Resolved isolated risk bucket UUID for risk-bucket-scoped margin TWAP orders */
531
+ riskBucketId?: string;
532
+ /** Number of slices in the planned schedule */
533
+ plannedSlices: number;
534
+ /** Planned time of the first slice (ISO 8601) */
535
+ firstSliceAt?: string;
536
+ /** Resolved window end (ISO 8601). Execution never continues past it. */
537
+ endTime: string;
538
+ }
539
+ /**
540
+ * Response from cancelling a TWAP parent order.
541
+ */
542
+ export interface CancelTwapOrderResponse {
543
+ /** Cancelled TWAP parent order UUID */
544
+ twapOrderId: string;
545
+ /** Result status: SUCCESS or FAILED */
546
+ status: "SUCCESS" | "FAILED";
547
+ /** Human-readable status message */
548
+ message: string;
549
+ }
550
+ /**
551
+ * A TWAP parent order read model.
552
+ */
553
+ export interface TwapOrder {
554
+ /** TWAP parent order UUID */
555
+ twapOrderId: string;
556
+ /** Trading pair UUID */
557
+ tradingPairId: string;
558
+ /** Order side: "BUY" or "SELL" */
559
+ side: OrderSide;
560
+ /** Trading mode: "SPOT" or "MARGIN" */
561
+ tradingMode: TradingMode;
562
+ /** Total quantity requested */
563
+ totalQuantity: string;
564
+ /** Quantity executed so far across all child orders */
565
+ executedQuantity: string;
566
+ /** Notional (quote) value executed so far */
567
+ executedNotional: string;
568
+ /** Volume-weighted average fill price (executedNotional / executedQuantity); absent until the first fill */
569
+ averageFillPrice?: string;
570
+ /** Execution progress as a decimal fraction (executedQuantity / totalQuantity, 0 to 1) */
571
+ progress: string;
572
+ /** Parent-level limit price; absent when only the slippage band protects child orders */
573
+ limitPrice?: string;
574
+ /** Per-slice protective price band in basis points */
575
+ slippageToleranceBps: number;
576
+ /** Whether the parent is reduce-only */
577
+ reduceOnly: boolean;
578
+ /** Margin account UUID for margin TWAP orders */
579
+ marginAccountId?: string;
580
+ /** Isolated risk bucket UUID for risk-bucket-scoped margin TWAP orders */
581
+ riskBucketId?: string;
582
+ /** Leverage for margin TWAP orders */
583
+ leverage?: string;
584
+ /** Whether child orders use the master account balance */
585
+ useMasterBalance?: boolean;
586
+ /** Strategy key used to group risk buckets */
587
+ strategyKey?: string;
588
+ /** Client-assigned idempotency key */
589
+ clientTwapId?: string;
590
+ /** Whether seeded size/timing randomization is applied to the schedule */
591
+ randomize: boolean;
592
+ /** Window start (ISO 8601) */
593
+ startTime: string;
594
+ /** Window end (ISO 8601). Execution stops hard at this time. */
595
+ endTime: string;
596
+ /** Derived base slice interval in milliseconds (int64 serialized as a JSON number; stored for audit) */
597
+ intervalMs: number;
598
+ /** Number of slices in the planned schedule */
599
+ plannedSlices: number;
600
+ /** Number of child orders placed so far */
601
+ slicesPlaced: number;
602
+ /**
603
+ * Number of slices skipped or failed so far (limit price through the
604
+ * market, self-trade prevention, halted market, failed admission). Skips
605
+ * never terminate the parent; the deficit flows into catch-up.
606
+ */
607
+ slicesSkipped: number;
608
+ /** Planned time of the next slice (ISO 8601); absent once the parent is terminal */
609
+ nextSliceAt?: string;
610
+ /** Parent state: PENDING, ACTIVE, COMPLETED, or CANCELLED */
611
+ state: TwapOrderState;
612
+ /** Terminal cause detail, e.g. an end-of-window shortfall ('ended with shortfall <qty>'); absent for non-terminal parents */
613
+ terminalReason?: string;
614
+ /** Creation timestamp (ISO 8601) */
615
+ createdAt: string;
616
+ /** Last update timestamp (ISO 8601) */
617
+ updatedAt: string;
618
+ /** Cancellation timestamp (ISO 8601) */
619
+ cancelledAt?: string;
620
+ /** Completion timestamp (ISO 8601) */
621
+ completedAt?: string;
622
+ }
623
+ /**
624
+ * Query parameters for listing TWAP parent orders.
625
+ */
626
+ export interface ListTwapOrdersParams {
627
+ /** Filter by parent state */
628
+ state?: TwapOrderState;
629
+ /** Filter by trading pair UUID */
630
+ tradingPairId?: string;
631
+ /** Page number (1-indexed) */
632
+ page?: number;
633
+ /** Items per page (max 100) */
634
+ pageSize?: number;
635
+ }
636
+ /**
637
+ * Response from listing TWAP parent orders.
638
+ */
639
+ export interface ListTwapOrdersResponse {
640
+ orders: TwapOrder[];
641
+ /** Total number of TWAP orders matching the filter */
642
+ total: number;
643
+ /** Current page number */
644
+ page: number;
645
+ /** Items per page */
646
+ pageSize: number;
647
+ }
@@ -171,6 +171,10 @@ export declare const GetCandlesticksByPairIdSchema: z.ZodObject<{
171
171
  startTime: z.ZodOptional<z.ZodNumber>;
172
172
  endTime: z.ZodOptional<z.ZodNumber>;
173
173
  limit: z.ZodOptional<z.ZodNumber>;
174
+ priceType: z.ZodOptional<z.ZodEnum<{
175
+ trade: "trade";
176
+ mark: "mark";
177
+ }>>;
174
178
  }, z.core.$strip>;
175
179
  /**
176
180
  * @deprecated Use GetCandlesticksByPairIdSchema instead. Symbol-based lookups are no longer supported.
@@ -191,6 +195,10 @@ export declare const GetCandlesticksBySymbolSchema: z.ZodObject<{
191
195
  startTime: z.ZodOptional<z.ZodNumber>;
192
196
  endTime: z.ZodOptional<z.ZodNumber>;
193
197
  limit: z.ZodOptional<z.ZodNumber>;
198
+ priceType: z.ZodOptional<z.ZodEnum<{
199
+ trade: "trade";
200
+ mark: "mark";
201
+ }>>;
194
202
  }, z.core.$strip>;
195
203
  /**
196
204
  * Get Trading Pair validation schema
@@ -188,6 +188,7 @@ export const GetCandlesticksByPairIdSchema = z
188
188
  startTime: TimestampSchema.optional(),
189
189
  endTime: TimestampSchema.optional(),
190
190
  limit: CandlestickLimitSchema,
191
+ priceType: z.enum(["trade", "mark"]).optional(),
191
192
  })
192
193
  .refine((data) => {
193
194
  // Only validate startTime < endTime if both are provided
@@ -67,6 +67,8 @@ export declare const ISO8601DateSchema: z.ZodISODateTime;
67
67
  */
68
68
  export declare const SlippageToleranceSchema: z.ZodOptional<z.ZodNumber>;
69
69
  export declare const SlippageToleranceBpsSchema: z.ZodNumber;
70
+ /** TWAP slices cap at 500 bps (5%) — tighter than standalone market orders. */
71
+ export declare const TwapSlippageToleranceBpsSchema: z.ZodNumber;
70
72
  export declare const ParentTpSlLegSchema: z.ZodObject<{
71
73
  triggerPrice: z.ZodString;
72
74
  orderType: z.ZodEnum<{
@@ -322,6 +324,63 @@ export declare const ListConditionalOrdersSchema: z.ZodObject<{
322
324
  page: z.ZodOptional<z.ZodNumber>;
323
325
  pageSize: z.ZodOptional<z.ZodNumber>;
324
326
  }, z.core.$strip>;
327
+ export declare const TwapOrderStateSchema: z.ZodEnum<{
328
+ CANCELLED: "CANCELLED";
329
+ ACTIVE: "ACTIVE";
330
+ PENDING: "PENDING";
331
+ COMPLETED: "COMPLETED";
332
+ }>;
333
+ /**
334
+ * Create TWAP Order validation schema
335
+ *
336
+ * Validates parameters for creating a TWAP parent order. The execution
337
+ * window is mandatory: exactly one of durationSeconds or endTime.
338
+ */
339
+ export declare const CreateTwapOrderSchema: z.ZodObject<{
340
+ tradingPairId: z.ZodUUID;
341
+ side: z.ZodEnum<{
342
+ BUY: "BUY";
343
+ SELL: "SELL";
344
+ }>;
345
+ quantity: z.ZodString;
346
+ options: z.ZodObject<{
347
+ durationSeconds: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
348
+ startTime: z.ZodOptional<z.ZodISODateTime>;
349
+ endTime: z.ZodOptional<z.ZodISODateTime>;
350
+ limitPrice: z.ZodOptional<z.ZodString>;
351
+ slippageToleranceBps: z.ZodOptional<z.ZodNumber>;
352
+ randomize: z.ZodOptional<z.ZodBoolean>;
353
+ reduceOnly: z.ZodOptional<z.ZodBoolean>;
354
+ tradingMode: z.ZodOptional<z.ZodEnum<{
355
+ SPOT: "SPOT";
356
+ MARGIN: "MARGIN";
357
+ }>>;
358
+ marginAccountId: z.ZodOptional<z.ZodUUID>;
359
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
360
+ marginMode: z.ZodOptional<z.ZodEnum<{
361
+ ISOLATED: "ISOLATED";
362
+ CROSS: "CROSS";
363
+ }>>;
364
+ leverage: z.ZodOptional<z.ZodString>;
365
+ strategyKey: z.ZodOptional<z.ZodString>;
366
+ useMasterBalance: z.ZodOptional<z.ZodBoolean>;
367
+ clientTwapId: z.ZodOptional<z.ZodString>;
368
+ }, z.core.$strip>;
369
+ }, z.core.$strip>;
370
+ export declare const CancelTwapOrderSchema: z.ZodObject<{
371
+ twapOrderId: z.ZodUUID;
372
+ }, z.core.$strip>;
373
+ export declare const ListTwapOrdersSchema: z.ZodObject<{
374
+ state: z.ZodOptional<z.ZodEnum<{
375
+ CANCELLED: "CANCELLED";
376
+ ACTIVE: "ACTIVE";
377
+ PENDING: "PENDING";
378
+ COMPLETED: "COMPLETED";
379
+ }>>;
380
+ tradingPairId: z.ZodOptional<z.ZodUUID>;
381
+ page: z.ZodOptional<z.ZodNumber>;
382
+ pageSize: z.ZodOptional<z.ZodNumber>;
383
+ }, z.core.$strip>;
325
384
  /**
326
385
  * Single batch create order item validation schema
327
386
  *
@@ -78,6 +78,12 @@ export const SlippageToleranceBpsSchema = z
78
78
  .int()
79
79
  .min(0, "Slippage tolerance must be at least 0 bps")
80
80
  .max(10000, "Slippage tolerance cannot exceed 10000 bps");
81
+ /** TWAP slices cap at 500 bps (5%) — tighter than standalone market orders. */
82
+ export const TwapSlippageToleranceBpsSchema = z
83
+ .number()
84
+ .int()
85
+ .min(0, "Slippage tolerance must be at least 0 bps")
86
+ .max(500, "TWAP slippage tolerance cannot exceed 500 bps (5%)");
81
87
  export const ParentTpSlLegSchema = z
82
88
  .object({
83
89
  triggerPrice: PositiveDecimalStringSchema,
@@ -352,6 +358,86 @@ export const ListConditionalOrdersSchema = z.object({
352
358
  page: z.number().int().min(1, "Page must be at least 1").optional(),
353
359
  pageSize: z.number().int().min(1, "Page size must be at least 1").max(100, "Page size cannot exceed 100").optional(),
354
360
  });
361
+ export const TwapOrderStateSchema = z.enum(["PENDING", "ACTIVE", "COMPLETED", "CANCELLED"], {
362
+ message: "Invalid TWAP order state",
363
+ });
364
+ /**
365
+ * TWAP window duration in whole seconds. Accepts a number or a numeric
366
+ * string for ergonomics; either way the client serializes it as a JSON
367
+ * number (the server deserializes an int64 and rejects strings). Only
368
+ * positivity and integrality are validated client-side — the min/max window
369
+ * bounds are env-tunable server configuration.
370
+ */
371
+ const TwapDurationSecondsSchema = z.union([
372
+ z.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),
373
+ z.string().regex(/^[1-9]\d*$/, "durationSeconds must be a positive integer string (e.g., '3600')"),
374
+ ]);
375
+ /**
376
+ * Create TWAP Order validation schema
377
+ *
378
+ * Validates parameters for creating a TWAP parent order. The execution
379
+ * window is mandatory: exactly one of durationSeconds or endTime.
380
+ */
381
+ export const CreateTwapOrderSchema = z
382
+ .object({
383
+ tradingPairId: UUIDSchema,
384
+ side: OrderSideSchema,
385
+ quantity: PositiveDecimalStringSchema,
386
+ options: z.object({
387
+ durationSeconds: TwapDurationSecondsSchema.optional(),
388
+ startTime: ISO8601DateSchema.optional(),
389
+ endTime: ISO8601DateSchema.optional(),
390
+ limitPrice: PositiveDecimalStringSchema.optional(),
391
+ slippageToleranceBps: TwapSlippageToleranceBpsSchema.optional(),
392
+ randomize: z.boolean().optional(),
393
+ reduceOnly: z.boolean().optional(),
394
+ tradingMode: TradingModeSchema.optional(),
395
+ marginAccountId: UUIDSchema.optional(),
396
+ riskBucketId: UUIDSchema.optional(),
397
+ marginMode: MarginModeSchema.optional(),
398
+ leverage: PositiveDecimalStringSchema.optional(),
399
+ strategyKey: z.string().min(1).max(128).optional(),
400
+ useMasterBalance: z.boolean().optional(),
401
+ clientTwapId: z.string().min(1).max(36, "clientTwapId cannot exceed 36 characters").optional(),
402
+ }),
403
+ })
404
+ .refine((data) => (data.options.durationSeconds !== undefined) !== (data.options.endTime !== undefined), {
405
+ message: "Exactly one of durationSeconds or endTime must be set",
406
+ path: ["options", "durationSeconds"],
407
+ })
408
+ .refine((data) => data.options.startTime === undefined || data.options.endTime !== undefined, {
409
+ message: "startTime is only valid together with endTime",
410
+ path: ["options", "startTime"],
411
+ })
412
+ .refine((data) => data.options.marginMode === undefined || data.options.tradingMode === "MARGIN", {
413
+ message: "marginMode is only supported for MARGIN orders",
414
+ path: ["options", "tradingMode"],
415
+ })
416
+ .refine((data) => data.options.riskBucketId === undefined || data.options.tradingMode === "MARGIN", {
417
+ message: "riskBucketId is only supported for MARGIN orders",
418
+ path: ["options", "tradingMode"],
419
+ })
420
+ .refine((data) => data.options.marginMode !== "CROSS" || data.options.riskBucketId === undefined, {
421
+ message: "marginMode CROSS cannot be combined with riskBucketId",
422
+ path: ["options", "riskBucketId"],
423
+ })
424
+ .refine((data) => data.options.marginMode !== "CROSS" || data.options.strategyKey === undefined, {
425
+ message: "marginMode CROSS cannot be combined with strategyKey",
426
+ path: ["options", "strategyKey"],
427
+ })
428
+ .refine((data) => data.options.tradingMode !== "MARGIN" || data.options.reduceOnly === true || data.options.leverage !== undefined, {
429
+ message: "leverage is required for normal MARGIN TWAP orders",
430
+ path: ["options", "leverage"],
431
+ });
432
+ export const CancelTwapOrderSchema = z.object({
433
+ twapOrderId: UUIDSchema,
434
+ });
435
+ export const ListTwapOrdersSchema = z.object({
436
+ state: TwapOrderStateSchema.optional(),
437
+ tradingPairId: UUIDSchema.optional(),
438
+ page: z.number().int().min(1, "Page must be at least 1").optional(),
439
+ pageSize: z.number().int().min(1, "Page size must be at least 1").max(100, "Page size cannot exceed 100").optional(),
440
+ });
355
441
  /**
356
442
  * Single batch create order item validation schema
357
443
  *
@@ -23,8 +23,12 @@ export interface AccountEventData {
23
23
  /** Collateral available for new margin allocation (decimal string) */
24
24
  freeCollateral: string;
25
25
  /**
26
- * Maintenance margin required divided by equity; `0` when equity is zero
27
- * (decimal string).
26
+ * Account distress ratio: maintenance margin required over equity (higher is
27
+ * closer to liquidation, decimal string). When equity is non-positive the
28
+ * quotient is undefined, so an account that still owes a maintenance
29
+ * requirement saturates to the max-decimal sentinel
30
+ * (`79228162514264337593543950335`, maximal distress) and an empty account
31
+ * with no requirement is `0`. Clamp the sentinel before display.
28
32
  */
29
33
  marginRatio: string;
30
34
  /** Maintenance margin required to keep the account solvent (decimal string) */
@@ -2,9 +2,11 @@ export * from "./account-events";
2
2
  export * from "./balance-events";
3
3
  export * from "./conditional-order-events";
4
4
  export * from "./liquidation-events";
5
+ export * from "./market-stats-events";
5
6
  export * from "./movement-events";
6
7
  export * from "./ohlcv-events";
7
8
  export * from "./orderbook-events";
8
9
  export * from "./orders-events";
9
10
  export * from "./position-events";
10
11
  export * from "./trade-events";
12
+ export * from "./twap-order-events";
@@ -2,9 +2,11 @@ export * from "./account-events";
2
2
  export * from "./balance-events";
3
3
  export * from "./conditional-order-events";
4
4
  export * from "./liquidation-events";
5
+ export * from "./market-stats-events";
5
6
  export * from "./movement-events";
6
7
  export * from "./ohlcv-events";
7
8
  export * from "./orderbook-events";
8
9
  export * from "./orders-events";
9
10
  export * from "./position-events";
10
11
  export * from "./trade-events";
12
+ export * from "./twap-order-events";