@nktkas/hyperliquid
Version:
Hyperliquid API SDK for all major JS runtimes, written in TypeScript.
140 lines (139 loc) • 5.89 kB
JavaScript
import * as v from "valibot";
// ============================================================
// API Schemas
// ============================================================
import { Address, Cloid, Hex, UnsignedDecimal, UnsignedInteger } from "../../_schemas.js";
/**
* Place an order(s).
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
*/ export const OrderRequest = /* @__PURE__ */ (()=>{
return v.object({
/** Action to perform. */ action: v.object({
/** Type of action. */ type: v.literal("order"),
/** Array of order parameters. */ orders: v.array(v.object({
/** Asset ID. */ a: UnsignedInteger,
/** Position side (`true` for long, `false` for short). */ b: v.boolean(),
/** Price. */ p: v.pipe(UnsignedDecimal, v.check((input)=>Number(input) > 0, "Value must be greater than zero")),
/** Size (in base currency units). */ s: UnsignedDecimal,
/** Whether the order is reduce-only. */ r: v.boolean(),
/** Order type (`limit` for limit orders, `trigger` for stop-loss/take-profit orders). */ t: v.union([
v.object({
/** Limit order parameters. */ limit: v.object({
/**
* Time-in-force.
* - `"Gtc"`: Remains active until filled or canceled.
* - `"Ioc"`: Fills immediately or cancels any unfilled portion.
* - `"Alo"`: Adds liquidity only.
* - `"FrontendMarket"`: Similar to Ioc, but add a note that this is market order.
*/ tif: v.picklist([
"Gtc",
"Ioc",
"Alo",
"FrontendMarket"
])
})
}),
v.object({
/** Trigger order parameters. */ trigger: v.object({
/** Whether the order is a market order. */ isMarket: v.boolean(),
/** Trigger price. */ triggerPx: v.pipe(UnsignedDecimal, v.check((input)=>Number(input) > 0, "Value must be greater than zero")),
/** Indicates whether it is take profit or stop loss. */ tpsl: v.picklist([
"tp",
"sl"
])
})
})
]),
/** Client Order ID. */ c: v.optional(Cloid)
})),
/**
* Order grouping strategy:
* - `"na"`: Standard order without grouping.
* - `"normalTpsl"`: TP/SL order with fixed size that doesn't adjust with position changes.
* - `"positionTpsl"`: TP/SL order that adjusts proportionally with the position size.
* - `{ p: number }`: Order priority rate as a fraction `p / 1e8` (max `p = 80000`, i.e. 8 bps).
* Only valid when every order is IOC on a perp asset.
*/ grouping: v.optional(v.union([
v.picklist([
"na",
"normalTpsl",
"positionTpsl"
]),
v.object({
/** Priority rate as a fraction `p / 1e8` (max `80000`, i.e. 8 bps). */ p: v.pipe(UnsignedInteger, v.maxValue(80000))
})
]), "na"),
/** Builder fee. */ builder: v.optional(v.object({
/** Builder address. */ b: Address,
/** Builder fee in 0.1bps (1 = 0.0001%). Max 100 for perps (0.1%), 1000 for spot (1%). */ f: v.pipe(UnsignedInteger, v.maxValue(1000))
}))
}),
/** Nonce (timestamp in ms) used to prevent replay attacks. */ nonce: UnsignedInteger,
/** ECDSA signature components. */ signature: v.object({
/** First 32-byte component. */ r: v.pipe(Hex, v.length(66)),
/** Second 32-byte component. */ s: v.pipe(Hex, v.length(66)),
/** Recovery identifier. */ v: v.picklist([
27,
28
])
}),
/** Vault address (for vault trading). */ vaultAddress: v.optional(Address),
/** Expiration time of the action. */ expiresAfter: v.optional(UnsignedInteger)
});
})();
// ============================================================
// Execution Logic
// ============================================================
import { parse } from "../../../_base.js";
import { canonicalize } from "../../../signing/mod.js";
import { executeL1Action } from "./_base/mod.js";
/** Schema for action fields (excludes request-level system fields). */ const OrderActionSchema = /* @__PURE__ */ (()=>{
return v.object(OrderRequest.entries.action.entries);
})();
/**
* Place an order(s).
*
* Signing: L1 Action.
*
* @param config General configuration for Exchange API requests.
* @param params Parameters specific to the API request.
* @param opts Request execution options.
* @return Successful variant of {@link OrderResponse} without error statuses.
*
* @throws {ValidationError} When the request parameters fail validation (before sending).
* @throws {TransportError} When the transport layer throws an error.
* @throws {ApiRequestError} When the API returns an unsuccessful response.
*
* @example
* ```ts
* import { HttpTransport } from "@nktkas/hyperliquid";
* import { order } from "@nktkas/hyperliquid/api/exchange";
* import { privateKeyToAccount } from "npm:viem/accounts";
*
* const wallet = privateKeyToAccount("0x..."); // viem or ethers
* const transport = new HttpTransport(); // or `WebSocketTransport`
*
* const data = await order({ transport, wallet }, {
* orders: [
* {
* a: 0,
* b: true,
* p: "30000",
* s: "0.1",
* r: false,
* t: { limit: { tif: "Gtc" } },
* },
* ],
* grouping: "na",
* });
* ```
*
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
*/ export function order(config, params, opts) {
const action = canonicalize(OrderActionSchema, parse(OrderActionSchema, {
type: "order",
...params
}));
return executeL1Action(config, action, opts);
}
//# sourceMappingURL=order.js.map