Orderly React SDK 钩子使用参考指南,包括 useOrderEntry、usePositionStream、useOrderbookStream、useCollateral 等。
顺序网络: SDK React Hooks Reference. 完成由 @ orderly.network/ hooks. 提供的所有钩的引用. 何时使用. 是一项面向实际任务的技能。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。
执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
@orderly.network/hooks 提供的所有 Hook 的完整参考。
@orderly.network/hooksOrderlyConfigProvider 包裹(注:原文为 OrderlyAppProvider,此处按实际组件名统一为 OrderlyConfigProvider;但根据后续 Setup 示例中实际使用的是 OrderlyAppProvider,此处应保留原文一致性,故修正为:OrderlyAppProvider 包裹您的应用)npm install @orderly.network/hooks @orderly.network/types # 或使用 yarn yarn add @orderly.network/hooks @orderly.network/types
import { OrderlyAppProvider } from '@orderly.network/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return (
);
}
访问账户状态及操作方法。
import { useAccount } from '@orderly.network/hooks';
const { account, state } = useAccount();
// 状态
state.status: 'notConnected' | 'connecting' | 'connected' | 'disconnecting'
state.address: string | null
// 账户对象
account.accountId: string
account.address: string
account.connect(): Promise
account.disconnect(): Promise
account.setAddress(address, options): void
// 示例
function AccountInfo() {
const { account, state } = useAccount();
if (state.status !== 'connected') {
return ;
}
return (
Account: {account.accountId}
Address: {account.address}
);
}
管理钱包连接状态。
import { useWalletConnector } from '@orderly.network/hooks';
const wallet = useWalletConnector();
// 状态
wallet.connected: boolean
wallet.connecting: boolean
wallet.connectedChain: { id: string } | null
wallet.address: string | null
// 操作方法
wallet.connect(): Promise
wallet.disconnect(): Promise
wallet.setChain(options): Promise
// 示例
function WalletButton() {
const wallet = useWalletConnector();
if (wallet.connecting) {
return Connecting...;
}
if (wallet.connected) {
return (
{wallet.address?.slice(0, 6)}...{wallet.address?.slice(-4)}
);
}
return ;
}
创建并提交订单。
import { useOrderEntry, OrderSide, OrderType } from '@orderly.network/hooks';
const {
submit,
setValue,
getValue,
helper,
reset,
isSubmitting,
errors,
} = useOrderEntry(symbol, options);
// Options 类型定义
interface OrderEntryOptions {
initialOrder?: {
side?: OrderSide;
order_type?: OrderType;
price?: string;
order_quantity?: string;
};
onSuccess?: (result) => void;
onError?: (error) => void;
}
// 方法说明
setValue(field: string, value: any): void
getValue(field: string): any
helper.validate(): Promise
submit(): Promise
reset(): void
// 示例
function OrderForm({ symbol }: { symbol: string }) {
const { submit, setValue, getValue, helper, isSubmitting } = useOrderEntry(symbol, {
initialOrder: {
side: OrderSide.BUY,
order_type: OrderType.LIMIT,
},
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const valid = await helper.validate();
if (valid) {
await submit();
}
};
return (
);
}
实时流式获取订单列表。
import { useOrderStream, OrderStatus } from '@orderly.network/hooks';
const [orders, actions] = useOrderStream(options);
// Options 类型定义
interface OrderStreamOptions {
status?: OrderStatus | OrderStatus[];
symbol?: string;
side?: OrderSide;
}
// 订单数组
orders: Order[]
// Order 类型定义
interface Order {
order_id: number;
symbol: string;
side: 'BUY' | 'SELL';
order_type: string;
price: string;
order_qty: string;
filled_qty: string;
status: string;
created_at: number;
updated_at: number;
}
// 操作方法
actions.cancelOrder(orderId: number | string): Promise
actions.cancelAllOrders(options?): Promise
actions.editOrder(orderId, updates): Promise
// 示例
function OpenOrders() {
const [orders, { cancelOrder, cancelAllOrders }] = useOrderStream({
status: OrderStatus.INCOMPLETE,
});
return (
{orders.map((order) => (
{order.symbol} {order.side} {order.order_qty} @ {order.price}
))}
);
}
实时流式获取持仓数据及未实现盈亏(PnL)。
import { usePositionStream } from '@orderly.network/hooks';
const { rows, aggregated, totalUnrealizedROI, isLoading } = usePositionStream();
// 返回值说明
rows: Position[]
aggregated: {
totalUnrealizedPnl: number;
totalNotional: number;
totalCollateral: number;
}
totalUnrealizedROI: number
isLoading: boolean
// Position 类型定义
interface Position {
symbol: string;
position_qty: number;
average_open_price: number;
mark_price: number;
unrealized_pnl: number;
unrealized_pnl_roi: number;
leverage: number;
liq_price: number;
mmr: number;
imr: number;
notional: number;
}
// 示例
function PositionsSummary() {
const { rows, aggregated, totalUnrealizedROI } = usePositionStream();
return (
Total PnL: ${aggregated?.totalUnrealizedPnl?.toFixed(2)}
ROI: {(totalUnrealizedROI * 100).toFixed(2)}%
{rows.map((pos) => (
{pos.symbol}
{pos.position_qty}
${pos.unrealized_pnl.toFixed(2)}
))}
);
}
管理止盈(Take-Profit)与止损(Stop-Loss)订单。
import { useTPSLOrder } from '@orderly.network/hooks';
const [computed, actions] = useTPSLOrder(position);
// PositionForTPSL 类型定义(用于 TP/SL 计算的持仓结构)
interface PositionForTPSL {
symbol: string;
position_qty: number;
average_open_price: number;
}
// 计算所得字段
computed: {
tpTriggerPrice?: string;
slTriggerPrice?: string;
tpOffsetPercentage?: number;
slOffsetPercentage?: number;
}
// 操作方法
actions.setValue(field: string, value: any): void
actions.validate(): Promise
actions.submit(): Promise
actions.reset(): void
// 示例
function TPSSForm({ position }: { position: Position }) {
const [_, { setValue, validate, submit }] = useTPSLOrder(position);
const handleSetTPSL = async () => {
setValue('tp_trigger_price', '3500');
setValue('sl_trigger_price', '2800');
if (await validate()) {
await submit();
}
};
return ;
}
实时订单簿数据。
import { useOrderbookStream } from '@orderly.network/hooks';
const { asks, bids, isLoading } = useOrderbookStream(symbol);
// 返回值说明
asks: [string, string][] // [price, quantity],按价格升序排列
bids: [string, string][] // [price, quantity],按价格降序排列
isLoading: boolean
// 示例
function Orderbook({ symbol }: { symbol: string }) {
const { asks, bids } = useOrderbookStream(symbol);
return (
{asks.slice(0, 10).map(([price, qty], i) => (
{price}
{qty}
))}
{bids.slice(0, 10).map(([price, qty], i) => (
{price}
{qty}
))}
);
}
获取指定交易对当前标记价格(Mark Price)。
import { useMarkPrice } from '@orderly.network/hooks';
const markPrice = useMarkPrice(symbol);
// 返回值类型:number
// 示例
function PriceDisplay({ symbol }: { symbol: string }) {
const markPrice = useMarkPrice(symbol);
return ${markPrice?.toFixed(2)};
}
获取 24 小时行情统计信息(Ticker)。
import { useTickerStream } from '@orderly.network/hooks';
const ticker = useTickerStream(symbol);
// Ticker 类型定义
interface Ticker {
symbol: string;
last_price: string;
high_24h: string;
low_24h: string;
volume_24h: string;
quote_volume_24h: string;
open: string;
price_change_24h: string;
price_change_percent_24h: string;
}
获取指定交易对的交易规则信息。
import { useSymbolInfo } from '@orderly.network/hooks';
const symbolInfo = useSymbolInfo(symbol);
// SymbolInfo 类型定义
interface SymbolInfo {
symbol: string;
base_currency: string;
quote_currency: string;
base_min: number;
base_max: number;
base_tick: number;
quote_min: number;
quote_max: number;
quote_tick: number;
min_notional: number;
price_range: number;
leverage_max: number;
}
获取账户抵押品(Collateral)信息。
import { useCollateral } from '@orderly.network/hooks';
const { totalCollateral, freeCollateral, availableBalance } = useCollateral({ dp: 2 });
// 返回值说明
totalCollateral: number // 账户总资产价值
freeCollateral: number // 可用于新开仓的资金
availableBalance: number // 可用余额(自由余额)
// 示例
function AccountSummary() {
const { totalCollateral, freeCollateral } = useCollateral({ dp: 2 });
return (
Total: ${totalCollateral}
Available: ${freeCollateral}
);
}
获取用户在 Orderly 上各代币的余额。
import { useBalance } from '@orderly.network/hooks';
const balance = useBalance();
// 返回值类型:{ USDC: string, USDT: string, ... }
// 示例
function BalanceDisplay() {
const balance = useBalance();
return USDC: {balance?.USDC || '0'};
}
获取 Orderly 支持的区块链列表。
import { useChains } from '@orderly.network/hooks';
const [chains, { findByChainId }] = useChains();
// Chain 类型定义
interface Chain {
id: number;
name: string;
network: string;
chain_id: string;
explorer: string;
}
// 示例
function ChainSelector() {
const [chains] = useChains();
return (
);
}
处理充值流程。
import { useDeposit } from '@orderly.network/hooks';
const {
balance,
allowance,
approve,
deposit,
depositFee,
setQuantity,
fetchBalance,
} = useDeposit(options);
// Options 类型定义
interface DepositOptions {
address: string; // 代币合约地址
decimals: number; // 代币精度(小数位数)
srcToken: string; // 代币符号(如 USDC)
srcChainId: number; // 源链 ID
}
// 示例
function DepositUSDC() {
const { balance, allowance, approve, deposit, isApproving, isDepositing } = useDeposit({
address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',
decimals: 6,
srcToken: 'USDC',
srcChainId: 42161,
});
const amount = '100';
const handleDeposit = async () => {
if (parseFloat(allowance) < 100) {
await approve();
}
await deposit(amount);
};
return (
);
}
处理提现流程。
import { useWithdraw } from '@orderly.network/hooks';
const { withdraw, isLoading, withdrawFee } = useWithdraw();
// WithdrawOptions 类型定义
interface WithdrawOptions {
symbol: string;
amount: string;
address: string; // 目标地址
chainId: number;
network: string;
}
// 示例
const { withdraw, isLoading } = useWithdraw();
await withdraw({
symbol: 'USDC',
amount: '100',
address: '0x...',
chainId: 42161,
network: 'arbitrum',
});
获取并设置指定交易对的杠杆倍数。
import { useLeverage } from '@orderly.network/hooks';
const { leverage, maxLeverage, setLeverage, isLoading } = useLeverage(symbol);
// 返回值说明
leverage: number
maxLeverage: number
setLeverage(value: number): Promise
isLoading: boolean
// 示例
function LeverageControl({ symbol }: { symbol: string }) {
const { leverage, maxLeverage, setLeverage } = useLeverage(symbol);
return (
setLeverage(parseInt(e.target.value))}
/>
);
}
import {
useAccount,
useOrderEntry,
usePositionStream,
useOrderbookStream,
useCollateral,
OrderSide,
OrderType,
} from '@orderly.network/hooks';
function TradingInterface({ symbol }: { symbol: string }) {
const { state } = useAccount();
const { rows: positions } = usePositionStream();
const { asks, bids } = useOrderbookStream(symbol);
const { freeCollateral } = useCollateral();
const { submit, setValue, getValue, helper } = useOrderEntry(symbol);
if (state.status !== 'connected') {
return ;
}
return (
);
}