@0xmonaco/types 1.0.42 → 1.0.43

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.
@@ -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.
@@ -92,7 +92,9 @@ export interface TradingAPI extends BaseAPI {
92
92
  * @param orderId - ID of the order to cancel
93
93
  * @returns Promise resolving to the cancellation result
94
94
  */
95
- cancelOrder(orderId: string): Promise<CancelOrderResponse>;
95
+ cancelOrder(orderId: string, options?: {
96
+ remainingQuantityTarget?: string;
97
+ }): Promise<CancelOrderResponse>;
96
98
  /**
97
99
  * Cancels an active conditional TP/SL order.
98
100
  */
@@ -179,7 +181,35 @@ export interface TradingAPI extends BaseAPI {
179
181
  * @returns Promise resolving to the order details
180
182
  */
181
183
  getOrder(orderId: string): Promise<GetOrderResponse>;
184
+ /**
185
+ * Creates a server-side TWAP (time-weighted average price) parent order.
186
+ * The matching engine executes it as a schedule of market child orders
187
+ * across the window, hard-stopping at the window end.
188
+ * @param tradingPairId - Trading pair UUID
189
+ * @param side - Order side ("BUY" or "SELL")
190
+ * @param quantity - Total quantity to execute across the window (at least 2x the pair's minimum order size)
191
+ * @param options - Window (exactly one of durationSeconds or endTime) plus optional execution parameters
192
+ * @returns Promise resolving to the TWAP creation result
193
+ */
194
+ createTwapOrder(tradingPairId: string, side: OrderSide, quantity: string, options: CreateTwapOrderOptions): Promise<CreateTwapOrderResponse>;
195
+ /**
196
+ * Cancels a TWAP parent order. Child orders are IOC and never rest, so the
197
+ * cancel is atomic and immediate; executed quantity stands.
198
+ * @param twapOrderId - TWAP parent order UUID
199
+ * @returns Promise resolving to the cancellation result
200
+ */
201
+ cancelTwapOrder(twapOrderId: string): Promise<CancelTwapOrderResponse>;
202
+ /**
203
+ * Gets a single TWAP parent order by its UUID. Users can only access their
204
+ * own TWAP orders.
205
+ */
206
+ getTwapOrder(twapOrderId: string): Promise<TwapOrder>;
207
+ /**
208
+ * Lists TWAP parent orders for the authenticated user with pagination and
209
+ * optional state / trading pair filters.
210
+ */
211
+ listTwapOrders(params?: ListTwapOrdersParams): Promise<ListTwapOrdersResponse>;
182
212
  }
183
- export type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderRole, OrderSide, OrderStatus, OrderStatusFilter, OrderTerminalReason, OrderType, PositionSide, TimeInForce, TradingMode, } from "./orders";
213
+ export type { ConditionalOrderConditionType, ConditionalOrderState, ConditionalOrderTriggerSource, Order, OrderRole, OrderSide, OrderStatus, OrderStatusFilter, OrderTerminalReason, OrderType, PositionSide, TimeInForce, TradingMode, TwapOrderState, } from "./orders";
184
214
  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";
215
+ 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
+ }
@@ -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<{
@@ -226,6 +228,7 @@ export declare const PlaceMarketOrderSchema: z.ZodObject<{
226
228
  */
227
229
  export declare const CancelOrderSchema: z.ZodObject<{
228
230
  orderId: z.ZodUUID;
231
+ remainingQuantityTarget: z.ZodOptional<z.ZodString>;
229
232
  }, z.core.$strip>;
230
233
  /**
231
234
  * Replace Order validation schema
@@ -322,6 +325,63 @@ export declare const ListConditionalOrdersSchema: z.ZodObject<{
322
325
  page: z.ZodOptional<z.ZodNumber>;
323
326
  pageSize: z.ZodOptional<z.ZodNumber>;
324
327
  }, z.core.$strip>;
328
+ export declare const TwapOrderStateSchema: z.ZodEnum<{
329
+ CANCELLED: "CANCELLED";
330
+ ACTIVE: "ACTIVE";
331
+ PENDING: "PENDING";
332
+ COMPLETED: "COMPLETED";
333
+ }>;
334
+ /**
335
+ * Create TWAP Order validation schema
336
+ *
337
+ * Validates parameters for creating a TWAP parent order. The execution
338
+ * window is mandatory: exactly one of durationSeconds or endTime.
339
+ */
340
+ export declare const CreateTwapOrderSchema: z.ZodObject<{
341
+ tradingPairId: z.ZodUUID;
342
+ side: z.ZodEnum<{
343
+ BUY: "BUY";
344
+ SELL: "SELL";
345
+ }>;
346
+ quantity: z.ZodString;
347
+ options: z.ZodObject<{
348
+ durationSeconds: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
349
+ startTime: z.ZodOptional<z.ZodISODateTime>;
350
+ endTime: z.ZodOptional<z.ZodISODateTime>;
351
+ limitPrice: z.ZodOptional<z.ZodString>;
352
+ slippageToleranceBps: z.ZodOptional<z.ZodNumber>;
353
+ randomize: z.ZodOptional<z.ZodBoolean>;
354
+ reduceOnly: z.ZodOptional<z.ZodBoolean>;
355
+ tradingMode: z.ZodOptional<z.ZodEnum<{
356
+ SPOT: "SPOT";
357
+ MARGIN: "MARGIN";
358
+ }>>;
359
+ marginAccountId: z.ZodOptional<z.ZodUUID>;
360
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
361
+ marginMode: z.ZodOptional<z.ZodEnum<{
362
+ ISOLATED: "ISOLATED";
363
+ CROSS: "CROSS";
364
+ }>>;
365
+ leverage: z.ZodOptional<z.ZodString>;
366
+ strategyKey: z.ZodOptional<z.ZodString>;
367
+ useMasterBalance: z.ZodOptional<z.ZodBoolean>;
368
+ clientTwapId: z.ZodOptional<z.ZodString>;
369
+ }, z.core.$strip>;
370
+ }, z.core.$strip>;
371
+ export declare const CancelTwapOrderSchema: z.ZodObject<{
372
+ twapOrderId: z.ZodUUID;
373
+ }, z.core.$strip>;
374
+ export declare const ListTwapOrdersSchema: z.ZodObject<{
375
+ state: z.ZodOptional<z.ZodEnum<{
376
+ CANCELLED: "CANCELLED";
377
+ ACTIVE: "ACTIVE";
378
+ PENDING: "PENDING";
379
+ COMPLETED: "COMPLETED";
380
+ }>>;
381
+ tradingPairId: z.ZodOptional<z.ZodUUID>;
382
+ page: z.ZodOptional<z.ZodNumber>;
383
+ pageSize: z.ZodOptional<z.ZodNumber>;
384
+ }, z.core.$strip>;
325
385
  /**
326
386
  * Single batch create order item validation schema
327
387
  *
@@ -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,
@@ -276,6 +282,14 @@ export const PlaceMarketOrderSchema = z
276
282
  */
277
283
  export const CancelOrderSchema = z.object({
278
284
  orderId: UUIDSchema,
285
+ /**
286
+ * Partial cancel: reduce the resting order in place to this remaining
287
+ * quantity, keeping its queue position. A target ("leave this much
288
+ * resting"), not an amount to remove, so a retried request converges. Must
289
+ * be a positive multiple of the market's quantity step, strictly below the
290
+ * order's current remaining quantity. Omit for a full cancel.
291
+ */
292
+ remainingQuantityTarget: PositiveDecimalStringSchema.optional(),
279
293
  });
280
294
  /**
281
295
  * Replace Order validation schema
@@ -352,6 +366,86 @@ export const ListConditionalOrdersSchema = z.object({
352
366
  page: z.number().int().min(1, "Page must be at least 1").optional(),
353
367
  pageSize: z.number().int().min(1, "Page size must be at least 1").max(100, "Page size cannot exceed 100").optional(),
354
368
  });
369
+ export const TwapOrderStateSchema = z.enum(["PENDING", "ACTIVE", "COMPLETED", "CANCELLED"], {
370
+ message: "Invalid TWAP order state",
371
+ });
372
+ /**
373
+ * TWAP window duration in whole seconds. Accepts a number or a numeric
374
+ * string for ergonomics; either way the client serializes it as a JSON
375
+ * number (the server deserializes an int64 and rejects strings). Only
376
+ * positivity and integrality are validated client-side — the min/max window
377
+ * bounds are env-tunable server configuration.
378
+ */
379
+ const TwapDurationSecondsSchema = z.union([
380
+ z.number().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),
381
+ z.string().regex(/^[1-9]\d*$/, "durationSeconds must be a positive integer string (e.g., '3600')"),
382
+ ]);
383
+ /**
384
+ * Create TWAP Order validation schema
385
+ *
386
+ * Validates parameters for creating a TWAP parent order. The execution
387
+ * window is mandatory: exactly one of durationSeconds or endTime.
388
+ */
389
+ export const CreateTwapOrderSchema = z
390
+ .object({
391
+ tradingPairId: UUIDSchema,
392
+ side: OrderSideSchema,
393
+ quantity: PositiveDecimalStringSchema,
394
+ options: z.object({
395
+ durationSeconds: TwapDurationSecondsSchema.optional(),
396
+ startTime: ISO8601DateSchema.optional(),
397
+ endTime: ISO8601DateSchema.optional(),
398
+ limitPrice: PositiveDecimalStringSchema.optional(),
399
+ slippageToleranceBps: TwapSlippageToleranceBpsSchema.optional(),
400
+ randomize: z.boolean().optional(),
401
+ reduceOnly: z.boolean().optional(),
402
+ tradingMode: TradingModeSchema.optional(),
403
+ marginAccountId: UUIDSchema.optional(),
404
+ riskBucketId: UUIDSchema.optional(),
405
+ marginMode: MarginModeSchema.optional(),
406
+ leverage: PositiveDecimalStringSchema.optional(),
407
+ strategyKey: z.string().min(1).max(128).optional(),
408
+ useMasterBalance: z.boolean().optional(),
409
+ clientTwapId: z.string().min(1).max(36, "clientTwapId cannot exceed 36 characters").optional(),
410
+ }),
411
+ })
412
+ .refine((data) => (data.options.durationSeconds !== undefined) !== (data.options.endTime !== undefined), {
413
+ message: "Exactly one of durationSeconds or endTime must be set",
414
+ path: ["options", "durationSeconds"],
415
+ })
416
+ .refine((data) => data.options.startTime === undefined || data.options.endTime !== undefined, {
417
+ message: "startTime is only valid together with endTime",
418
+ path: ["options", "startTime"],
419
+ })
420
+ .refine((data) => data.options.marginMode === undefined || data.options.tradingMode === "MARGIN", {
421
+ message: "marginMode is only supported for MARGIN orders",
422
+ path: ["options", "tradingMode"],
423
+ })
424
+ .refine((data) => data.options.riskBucketId === undefined || data.options.tradingMode === "MARGIN", {
425
+ message: "riskBucketId is only supported for MARGIN orders",
426
+ path: ["options", "tradingMode"],
427
+ })
428
+ .refine((data) => data.options.marginMode !== "CROSS" || data.options.riskBucketId === undefined, {
429
+ message: "marginMode CROSS cannot be combined with riskBucketId",
430
+ path: ["options", "riskBucketId"],
431
+ })
432
+ .refine((data) => data.options.marginMode !== "CROSS" || data.options.strategyKey === undefined, {
433
+ message: "marginMode CROSS cannot be combined with strategyKey",
434
+ path: ["options", "strategyKey"],
435
+ })
436
+ .refine((data) => data.options.tradingMode !== "MARGIN" || data.options.reduceOnly === true || data.options.leverage !== undefined, {
437
+ message: "leverage is required for normal MARGIN TWAP orders",
438
+ path: ["options", "leverage"],
439
+ });
440
+ export const CancelTwapOrderSchema = z.object({
441
+ twapOrderId: UUIDSchema,
442
+ });
443
+ export const ListTwapOrdersSchema = z.object({
444
+ state: TwapOrderStateSchema.optional(),
445
+ tradingPairId: UUIDSchema.optional(),
446
+ page: z.number().int().min(1, "Page must be at least 1").optional(),
447
+ pageSize: z.number().int().min(1, "Page size must be at least 1").max(100, "Page size cannot exceed 100").optional(),
448
+ });
355
449
  /**
356
450
  * Single batch create order item validation schema
357
451
  *
@@ -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) */
@@ -9,3 +9,4 @@ export * from "./orderbook-events";
9
9
  export * from "./orders-events";
10
10
  export * from "./position-events";
11
11
  export * from "./trade-events";
12
+ export * from "./twap-order-events";
@@ -9,3 +9,4 @@ export * from "./orderbook-events";
9
9
  export * from "./orders-events";
10
10
  export * from "./position-events";
11
11
  export * from "./trade-events";
12
+ export * from "./twap-order-events";
@@ -5,6 +5,15 @@
5
5
  */
6
6
  import type { Candlestick, Interval } from "../../market";
7
7
  import type { TradingMode } from "../../trading";
8
+ /**
9
+ * OHLCV price series selector for the optional fifth channel token.
10
+ *
11
+ * - `trade` — the trade-derived candles (the default when the token is omitted).
12
+ * - `mark` — the close-only mark-price series (open = high = low = close = mark,
13
+ * zero volume), published on `1m` for margin pairs.
14
+ * - `*` — both series.
15
+ */
16
+ export type OHLCVPriceType = "trade" | "mark" | "*";
8
17
  /**
9
18
  * OHLCV update event
10
19
  */
@@ -15,6 +24,12 @@ export interface OHLCVEvent {
15
24
  interval: Interval;
16
25
  /** Trading mode */
17
26
  tradingMode: TradingMode;
27
+ /**
28
+ * Price series this candle belongs to. Always a concrete series on the wire
29
+ * (`trade` or `mark`, never the `*` selector); lets a wildcard subscriber
30
+ * tell the two streams apart. Absent only on legacy frames that omit it.
31
+ */
32
+ priceType?: "trade" | "mark";
18
33
  /** OHLCV candlestick data */
19
34
  candlestick: Candlestick;
20
35
  }