Orderly Sdk React Hooks
by @tarnadas
Reference guide for using Orderly React SDK hooks - useOrderEntry, usePositionStream, useOrderbookStream, useCollateral, and more
clawhub install orderly-sdk-react-hooksπ About This Skill
name: orderly-sdk-react-hooks description: Reference guide for using Orderly React SDK hooks - useOrderEntry, usePositionStream, useOrderbookStream, useCollateral, and more
Orderly Network: SDK React Hooks Reference
Complete reference for all hooks provided by @orderly.network/hooks.
When to Use
Prerequisites
@orderly.network/hooks installedInstallation
npm install @orderly.network/hooks @orderly.network/typesOr with yarn
yarn add @orderly.network/hooks @orderly.network/types
Setup
import { OrderlyAppProvider } from '@orderly.network/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';const queryClient = new QueryClient();
function App() {
return (
);
}
Account Hooks
useAccount
Access account state and actions.
import { useAccount } from '@orderly.network/hooks';const { account, state } = useAccount();
// State
state.status: 'notConnected' | 'connecting' | 'connected' | 'disconnecting'
state.address: string | null
// Account
account.accountId: string
account.address: string
account.connect(): Promise
account.disconnect(): Promise
account.setAddress(address, options): void
// Example
function AccountInfo() {
const { account, state } = useAccount();
if (state.status !== 'connected') {
return ;
}
return (
Account: {account.accountId}
Address: {account.address}
);
}
useWalletConnector
Manage wallet connection.
import { useWalletConnector } from '@orderly.network/hooks';const wallet = useWalletConnector();
// State
wallet.connected: boolean
wallet.connecting: boolean
wallet.connectedChain: { id: string } | null
wallet.address: string | null
// Actions
wallet.connect(): Promise
wallet.disconnect(): Promise
wallet.setChain(options): Promise
// Example
function WalletButton() {
const wallet = useWalletConnector();
if (wallet.connecting) {
return Connecting...;
}
if (wallet.connected) {
return (
{wallet.address?.slice(0, 6)}...{wallet.address?.slice(-4)}
);
} return ;
}
Trading Hooks
useOrderEntry
Create and submit orders.
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;
}
// Methods
setValue(field: string, value: any): void
getValue(field: string): any
helper.validate(): Promise
submit(): Promise
reset(): void
// Example
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 (
);
}
useOrderStream
Stream orders in real-time.
import { useOrderStream, OrderStatus } from '@orderly.network/hooks';const [orders, actions] = useOrderStream(options);
// Options
interface OrderStreamOptions {
status?: OrderStatus | OrderStatus[];
symbol?: string;
side?: OrderSide;
}
// Orders
orders: Order[]
// Order type
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
actions.cancelOrder(orderId: number | string): Promise
actions.cancelAllOrders(options?): Promise
actions.editOrder(orderId, updates): Promise
// Example
function OpenOrders() {
const [orders, { cancelOrder, cancelAllOrders }] = useOrderStream({
status: OrderStatus.INCOMPLETE,
});
return (
{orders.map((order) => (
{order.symbol} {order.side} {order.order_qty} @ {order.price}
))}
);
}
Position Hooks
usePositionStream
Stream positions with real-time PnL.
import { usePositionStream } from '@orderly.network/hooks';const { rows, aggregated, totalUnrealizedROI, isLoading } = usePositionStream();
// Return values
rows: Position[]
aggregated: {
totalUnrealizedPnl: number;
totalNotional: number;
totalCollateral: number;
}
totalUnrealizedROI: number
isLoading: boolean
// Position type
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;
}
// Example
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)}
))}
);
}
useTPSLOrder
Manage Take-Profit and Stop-Loss orders.
import { useTPSLOrder } from '@orderly.network/hooks';const [computed, actions] = useTPSLOrder(position);
// Position with position_qty and average_open_price
interface PositionForTPSL {
symbol: string;
position_qty: number;
average_open_price: number;
}
// Computed values
computed: {
tpTriggerPrice?: string;
slTriggerPrice?: string;
tpOffsetPercentage?: number;
slOffsetPercentage?: number;
}
// Actions
actions.setValue(field: string, value: any): void
actions.validate(): Promise
actions.submit(): Promise
actions.reset(): void
// Example
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 ;
}
Market Data Hooks
useOrderbookStream
Real-time orderbook data.
import { useOrderbookStream } from '@orderly.network/hooks';const { asks, bids, isLoading } = useOrderbookStream(symbol);
// Return values
asks: [string, string][] // [price, quantity] - ascending by price
bids: [string, string][] // [price, quantity] - descending by price
isLoading: boolean
// Example
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}
))}
);
}
useMarkPrice
Current mark price for a symbol.
import { useMarkPrice } from '@orderly.network/hooks';const markPrice = useMarkPrice(symbol);
// Returns: number
// Example
function PriceDisplay({ symbol }: { symbol: string }) {
const markPrice = useMarkPrice(symbol);
return ${markPrice?.toFixed(2)};
}
useTickerStream
24-hour ticker statistics.
import { useTickerStream } from '@orderly.network/hooks';const ticker = useTickerStream(symbol);
// Ticker type
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;
}
useSymbolInfo
Get trading rules for a symbol.
import { useSymbolInfo } from '@orderly.network/hooks';const symbolInfo = useSymbolInfo(symbol);
// Symbol info type
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;
}
Balance Hooks
useCollateral
Account collateral information.
import { useCollateral } from '@orderly.network/hooks';const { totalCollateral, freeCollateral, availableBalance } = useCollateral({ dp: 2 });
// Return values
totalCollateral: number // Total account value
freeCollateral: number // Available for new positions
availableBalance: number // Free balance
// Example
function AccountSummary() {
const { totalCollateral, freeCollateral } = useCollateral({ dp: 2 });
return (
Total: ${totalCollateral}
Available: ${freeCollateral}
);
}
useBalance
Token balance on Orderly.
import { useBalance } from '@orderly.network/hooks';const balance = useBalance();
// Returns: { USDC: string, USDT: string, ... }
// Example
function BalanceDisplay() {
const balance = useBalance();
return USDC: {balance?.USDC || '0'};
}
Chain Hooks
useChains
Get supported chains.
import { useChains } from '@orderly.network/hooks';const [chains, { findByChainId }] = useChains();
// Chain type
interface Chain {
id: number;
name: string;
network: string;
chain_id: string;
explorer: string;
}
// Example
function ChainSelector() {
const [chains] = useChains();
return (
);
}
Deposit/Withdraw Hooks
useDeposit
Handle deposits.
import { useDeposit } from '@orderly.network/hooks';const {
balance,
allowance,
approve,
deposit,
depositFee,
setQuantity,
fetchBalance,
} = useDeposit(options);
// Options
interface DepositOptions {
address: string; // Token contract address
decimals: number; // Token decimals
srcToken: string; // Token symbol
srcChainId: number; // Source chain ID
}
// Example
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 (
);
}
useWithdraw
Handle withdrawals.
import { useWithdraw } from '@orderly.network/hooks';const { withdraw, isLoading, withdrawFee } = useWithdraw();
// Withdraw options
interface WithdrawOptions {
symbol: string;
amount: string;
address: string; // Destination address
chainId: number;
network: string;
}
// Example
const { withdraw, isLoading } = useWithdraw();
await withdraw({
symbol: 'USDC',
amount: '100',
address: '0x...',
chainId: 42161,
network: 'arbitrum',
});
Leverage Hook
useLeverage
Get and set leverage.
import { useLeverage } from '@orderly.network/hooks';const { leverage, maxLeverage, setLeverage, isLoading } = useLeverage(symbol);
// Return values
leverage: number
maxLeverage: number
setLeverage(value: number): Promise
isLoading: boolean
// Example
function LeverageControl({ symbol }: { symbol: string }) {
const { leverage, maxLeverage, setLeverage } = useLeverage(symbol);
return (
setLeverage(parseInt(e.target.value))}
/>
);
}
Common Patterns
Combined Trading Interface
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 (
);
}
Related Skills
β‘ When to Use
βοΈ Configuration
import { OrderlyAppProvider } from '@orderly.network/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';const queryClient = new QueryClient();
function App() {
return (
);
}