orderly-sdk-trading-workflows
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOrderly Network: SDK Trading Workflows
Orderly Network:SDK交易工作流
A comprehensive guide to implementing complete trading workflows in Orderly Network DEX applications, from wallet connection through order execution and position management.
本指南详细介绍了如何在Orderly Network DEX应用中实现完整的交易工作流,涵盖从钱包连接到订单执行、仓位管理的全流程。
When to Use
适用场景
- Building a complete trading interface
- Implementing deposit → trade → withdraw flow
- Understanding the end-to-end trading lifecycle
- Creating automated trading bots
- 构建完整的交易界面
- 实现充值→交易→提现流程
- 理解端到端的交易生命周期
- 开发自动化交易机器人
Prerequisites
前置条件
- Orderly SDK packages installed
- Wallet connection configured
- Account authenticated
- 已安装Orderly SDK包
- 已配置钱包连接
- 账户已完成认证
Overview
概述
This skill covers end-to-end trading workflows:
- Connect → Wallet connection and authentication
- Deposit → Fund your Orderly account
- Trade → Place and manage orders
- Monitor → Track positions and PnL
- Withdraw → Move funds back to wallet
本技能涵盖以下端到端交易工作流:
- 连接 → 钱包连接与认证
- 充值 → 为Orderly账户充值
- 交易 → 下单与订单管理
- 监控 → 追踪仓位与盈亏(PnL)
- 提现 → 将资金转回钱包
Complete Trading Flow
完整交易流程
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Connect │────▶│ Deposit │────▶│ Trade │
│ Wallet │ │ Funds │ │ (Orders) │
└──────────────┘ └──────────────┘ └──────────────┘
│
▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Withdraw │◀────│ Close │◀────│ Monitor │
│ Funds │ │ Positions │ │ Positions │
└──────────────┘ └──────────────┘ └──────────────┘┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Connect │────▶│ Deposit │────▶│ Trade │
│ Wallet │ │ Funds │ │ (Orders) │
└──────────────┘ └──────────────┘ └──────────────┘
│
▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Withdraw │◀────│ Close │◀────│ Monitor │
│ Funds │ │ Positions │ │ Positions │
└──────────────┘ └──────────────┘ └──────────────┘1. Connect & Authenticate
1. 连接与认证
Check Account State
检查账户状态
tsx
import { useAccount, AccountStatusEnum } from '@orderly.network/hooks';
function TradingGuard({ children }) {
const { state, createAccount, createOrderlyKey } = useAccount();
switch (state.status) {
case AccountStatusEnum.NotConnected:
return <ConnectWalletPrompt />;
case AccountStatusEnum.Connected:
return (
<div>
<p>Create your Orderly account to start trading</p>
<Button onClick={() => createAccount()}>Create Account</Button>
</div>
);
case AccountStatusEnum.NotSignedIn:
return (
<div>
<p>Enable trading by creating your trading key</p>
<Button onClick={() => createOrderlyKey()}>Enable Trading</Button>
</div>
);
case AccountStatusEnum.SignedIn:
return children;
}
}tsx
import { useAccount, AccountStatusEnum } from '@orderly.network/hooks';
function TradingGuard({ children }) {
const { state, createAccount, createOrderlyKey } = useAccount();
switch (state.status) {
case AccountStatusEnum.NotConnected:
return <ConnectWalletPrompt />;
case AccountStatusEnum.Connected:
return (
<div>
<p>创建您的Orderly账户以开始交易</p>
<Button onClick={() => createAccount()}>创建账户</Button>
</div>
);
case AccountStatusEnum.NotSignedIn:
return (
<div>
<p>创建交易密钥以启用交易功能</p>
<Button onClick={() => createOrderlyKey()}>启用交易</Button>
</div>
);
case AccountStatusEnum.SignedIn:
return children;
}
}Using AuthGuard (Simpler)
使用AuthGuard(更简便)
tsx
import { AuthGuard } from '@orderly.network/ui-connector';
function TradingPage() {
return (
<AuthGuard>
<TradingInterface />
</AuthGuard>
);
}tsx
import { AuthGuard } from '@orderly.network/ui-connector';
function TradingPage() {
return (
<AuthGuard>
<TradingInterface />
</AuthGuard>
);
}2. Deposit Funds
2. 充值资金
Using useDeposit Hook
使用useDeposit Hook
tsx
import { useDeposit } from '@orderly.network/hooks';
function DepositForm() {
const { deposit, balance, allowance, approve, isNativeToken, quantity, setQuantity, depositFee } =
useDeposit({
address: '0xUSDC_ADDRESS',
decimals: 6,
srcChainId: 42161,
srcToken: 'USDC',
});
const handleDeposit = async () => {
try {
// Check and approve if needed
if (!isNativeToken && allowance < quantity) {
await approve();
}
// Execute deposit
const result = await deposit();
toast.success('Deposit successful!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input value={quantity} onChange={(e) => setQuantity(e.target.value)} placeholder="Amount" />
<Text>Balance: {balance} USDC</Text>
<Text>Fee: {depositFee} USDC</Text>
<Button onClick={handleDeposit}>Deposit</Button>
</div>
);
}tsx
import { useDeposit } from '@orderly.network/hooks';
function DepositForm() {
const { deposit, balance, allowance, approve, isNativeToken, quantity, setQuantity, depositFee } =
useDeposit({
address: '0xUSDC_ADDRESS',
decimals: 6,
srcChainId: 42161,
srcToken: 'USDC',
});
const handleDeposit = async () => {
try {
// 检查并按需授权
if (!isNativeToken && allowance < quantity) {
await approve();
}
// 执行充值
const result = await deposit();
toast.success('充值成功!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input value={quantity} onChange={(e) => setQuantity(e.target.value)} placeholder="金额" />
<Text>余额: {balance} USDC</Text>
<Text>手续费: {depositFee} USDC</Text>
<Button onClick={handleDeposit}>充值</Button>
</div>
);
}Using DepositForm Component
使用DepositForm组件
tsx
import { DepositForm } from '@orderly.network/ui-transfer';
function DepositPage() {
return (
<DepositForm
onDeposit={(result) => {
toast.success('Deposited successfully!');
}}
/>
);
}tsx
import { DepositForm } from '@orderly.network/ui-transfer';
function DepositPage() {
return (
<DepositForm
onDeposit={(result) => {
toast.success('充值成功!');
}}
/>
);
}3. Check Account Balance
3. 检查账户余额
Using useCollateral
使用useCollateral
tsx
import { useCollateral } from '@orderly.network/hooks';
function AccountBalance() {
const { totalCollateral, freeCollateral, totalValue, availableBalance, unsettledPnL } =
useCollateral({ dp: 2 });
return (
<Card>
<Text>Total Value: ${totalValue}</Text>
<Text>Free Collateral: ${freeCollateral}</Text>
<Text>Unsettled PnL: ${unsettledPnL}</Text>
</Card>
);
}tsx
import { useCollateral } from '@orderly.network/hooks';
function AccountBalance() {
const { totalCollateral, freeCollateral, totalValue, availableBalance, unsettledPnL } =
useCollateral({ dp: 2 });
return (
<Card>
<Text>总资产: ${totalValue}</Text>
<Text>可用保证金: ${freeCollateral}</Text>
<Text>未结算盈亏: ${unsettledPnL}</Text>
</Card>
);
}4. Place Orders
4. 下单
Market Order
市价单
tsx
import { useMutation } from '@orderly.network/hooks';
import { OrderType, OrderSide } from '@orderly.network/types';
function MarketOrderButton({ symbol, side, quantity }) {
const [submitOrder] = useMutation('/v1/order');
const placeMarketOrder = async () => {
const order = {
symbol,
side,
order_type: OrderType.MARKET,
order_quantity: quantity,
};
try {
const result = await submitOrder(order);
if (result.success) {
toast.success(`Order placed: ${result.data.order_id}`);
}
} catch (error) {
toast.error(error.message);
}
};
return (
<Button color={side === OrderSide.BUY ? 'buy' : 'sell'} onClick={placeMarketOrder}>
{side === OrderSide.BUY ? 'Buy' : 'Sell'} Market
</Button>
);
}tsx
import { useMutation } from '@orderly.network/hooks';
import { OrderType, OrderSide } from '@orderly.network/types';
function MarketOrderButton({ symbol, side, quantity }) {
const [submitOrder] = useMutation('/v1/order');
const placeMarketOrder = async () => {
const order = {
symbol,
side,
order_type: OrderType.MARKET,
order_quantity: quantity,
};
try {
const result = await submitOrder(order);
if (result.success) {
toast.success(`订单已下单: ${result.data.order_id}`);
}
} catch (error) {
toast.error(error.message);
}
};
return (
<Button color={side === OrderSide.BUY ? 'buy' : 'sell'} onClick={placeMarketOrder}>
{side === OrderSide.BUY ? '买入' : '卖出'} 市价单
</Button>
);
}Limit Order
限价单
tsx
function LimitOrderForm({ symbol }) {
const [submitOrder] = useMutation('/v1/order');
const [price, setPrice] = useState('');
const [quantity, setQuantity] = useState('');
const [side, setSide] = useState(OrderSide.BUY);
const placeLimitOrder = async () => {
const order = {
symbol,
side,
order_type: OrderType.LIMIT,
order_price: parseFloat(price),
order_quantity: parseFloat(quantity),
};
const result = await submitOrder(order);
if (result.success) {
toast.success('Limit order placed!');
}
};
return (
<div>
<Input label="Price" value={price} onChange={(e) => setPrice(e.target.value)} />
<Input label="Quantity" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
<Button
color="buy"
onClick={() => {
setSide(OrderSide.BUY);
placeLimitOrder();
}}
>
Buy
</Button>
<Button
color="sell"
onClick={() => {
setSide(OrderSide.SELL);
placeLimitOrder();
}}
>
Sell
</Button>
</div>
);
}tsx
function LimitOrderForm({ symbol }) {
const [submitOrder] = useMutation('/v1/order');
const [price, setPrice] = useState('');
const [quantity, setQuantity] = useState('');
const [side, setSide] = useState(OrderSide.BUY);
const placeLimitOrder = async () => {
const order = {
symbol,
side,
order_type: OrderType.LIMIT,
order_price: parseFloat(price),
order_quantity: parseFloat(quantity),
};
const result = await submitOrder(order);
if (result.success) {
toast.success('限价单已下单!');
}
};
return (
<div>
<Input label="价格" value={price} onChange={(e) => setPrice(e.target.value)} />
<Input label="数量" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
<Button
color="buy"
onClick={() => {
setSide(OrderSide.BUY);
placeLimitOrder();
}}
>
买入
</Button>
<Button
color="sell"
onClick={() => {
setSide(OrderSide.SELL);
placeLimitOrder();
}}
>
卖出
</Button>
</div>
);
}Using useOrderEntry (Recommended)
使用useOrderEntry(推荐)
tsx
import { useOrderEntry } from '@orderly.network/hooks';
import { OrderSide, OrderType } from '@orderly.network/types';
function OrderEntryForm({ symbol }) {
const { formattedOrder, submit, maxQty, freeCollateral, errors, setValues } =
useOrderEntry(symbol);
useEffect(() => {
setValues({
side: OrderSide.BUY,
order_type: OrderType.LIMIT,
});
}, []);
const handleSubmit = async () => {
if (Object.keys(errors).length > 0) {
toast.error('Please fix validation errors');
return;
}
try {
await submit();
toast.success('Order submitted!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input
label="Price"
value={formattedOrder.order_price}
onChange={(e) => setValues({ order_price: e.target.value })}
error={errors.order_price}
/>
<Input
label="Quantity"
value={formattedOrder.order_quantity}
onChange={(e) => setValues({ order_quantity: e.target.value })}
error={errors.order_quantity}
/>
<Text>Max: {maxQty}</Text>
<Text>Available: ${freeCollateral}</Text>
<Button onClick={handleSubmit}>Submit Order</Button>
</div>
);
}tsx
import { useOrderEntry } from '@orderly.network/hooks';
import { OrderSide, OrderType } from '@orderly.network/types';
function OrderEntryForm({ symbol }) {
const { formattedOrder, submit, maxQty, freeCollateral, errors, setValues } =
useOrderEntry(symbol);
useEffect(() => {
setValues({
side: OrderSide.BUY,
order_type: OrderType.LIMIT,
});
}, []);
const handleSubmit = async () => {
if (Object.keys(errors).length > 0) {
toast.error('请修复验证错误');
return;
}
try {
await submit();
toast.success('订单已提交!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input
label="价格"
value={formattedOrder.order_price}
onChange={(e) => setValues({ order_price: e.target.value })}
error={errors.order_price}
/>
<Input
label="数量"
value={formattedOrder.order_quantity}
onChange={(e) => setValues({ order_quantity: e.target.value })}
error={errors.order_quantity}
/>
<Text>最大可买: {maxQty}</Text>
<Text>可用保证金: ${freeCollateral}</Text>
<Button onClick={handleSubmit}>提交订单</Button>
</div>
);
}5. Monitor Orders
5. 监控订单
Active Orders
活跃订单
tsx
import { useOrderStream } from '@orderly.network/hooks';
function ActiveOrders({ symbol }) {
const [orders, { refresh }] = useOrderStream({
symbol,
status: 'OPEN',
});
return (
<DataTable
columns={[
{ header: 'Symbol', accessorKey: 'symbol' },
{ header: 'Side', accessorKey: 'side' },
{ header: 'Price', accessorKey: 'price' },
{ header: 'Quantity', accessorKey: 'quantity' },
{ header: 'Status', accessorKey: 'status' },
{
header: 'Actions',
cell: ({ row }) => <Button onClick={() => cancelOrder(row.order_id)}>Cancel</Button>,
},
]}
data={orders}
/>
);
}tsx
import { useOrderStream } from '@orderly.network/hooks';
function ActiveOrders({ symbol }) {
const [orders, { refresh }] = useOrderStream({
symbol,
status: 'OPEN',
});
return (
<DataTable
columns={[
{ header: '交易对', accessorKey: 'symbol' },
{ header: '方向', accessorKey: 'side' },
{ header: '价格', accessorKey: 'price' },
{ header: '数量', accessorKey: 'quantity' },
{ header: '状态', accessorKey: 'status' },
{
header: '操作',
cell: ({ row }) => <Button onClick={() => cancelOrder(row.order_id)}>撤销</Button>,
},
]}
data={orders}
/>
);
}Cancel Order
撤销订单
tsx
import { useMutation } from '@orderly.network/hooks';
function useCancelOrder() {
const [cancel] = useMutation('/v1/order', 'DELETE');
return async (orderId: string, symbol: string) => {
const result = await cancel({
order_id: orderId,
symbol,
});
return result;
};
}tsx
import { useMutation } from '@orderly.network/hooks';
function useCancelOrder() {
const [cancel] = useMutation('/v1/order', 'DELETE');
return async (orderId: string, symbol: string) => {
const result = await cancel({
order_id: orderId,
symbol,
});
return result;
};
}6. Monitor Positions
6. 监控仓位
Real-time Position Stream
实时仓位流
tsx
import { usePositionStream } from '@orderly.network/hooks';
function PositionsTable({ symbol }) {
const [positions, positionInfo, { loading }] = usePositionStream(symbol);
return (
<DataTable
columns={[
{ header: 'Symbol', accessorKey: 'symbol' },
{ header: 'Size', accessorKey: 'position_qty' },
{ header: 'Entry Price', accessorKey: 'average_open_price' },
{ header: 'Mark Price', accessorKey: 'mark_price' },
{
header: 'Unrealized PnL',
accessorKey: 'unrealized_pnl',
cell: ({ getValue }) => (
<Text color={getValue() >= 0 ? 'success' : 'danger'}>${getValue().toFixed(2)}</Text>
),
},
]}
data={positions}
/>
);
}tsx
import { usePositionStream } from '@orderly.network/hooks';
function PositionsTable({ symbol }) {
const [positions, positionInfo, { loading }] = usePositionStream(symbol);
return (
<DataTable
columns={[
{ header: '交易对', accessorKey: 'symbol' },
{ header: '仓位大小', accessorKey: 'position_qty' },
{ header: '开仓均价', accessorKey: 'average_open_price' },
{ header: '标记价格', accessorKey: 'mark_price' },
{
header: '未实现盈亏',
accessorKey: 'unrealized_pnl',
cell: ({ getValue }) => (
<Text color={getValue() >= 0 ? 'success' : 'danger'}>${getValue().toFixed(2)}</Text>
),
},
]}
data={positions}
/>
);
}7. Close Positions
7. 平仓
Close Specific Position
平指定仓位
tsx
import { useMutation } from '@orderly.network/hooks';
import { OrderType, OrderSide } from '@orderly.network/types';
function ClosePositionButton({ position }) {
const [submitOrder] = useMutation('/v1/order');
const closePosition = async () => {
const order = {
symbol: position.symbol,
side: position.position_qty > 0 ? OrderSide.SELL : OrderSide.BUY,
order_type: OrderType.MARKET,
order_quantity: Math.abs(position.position_qty),
reduce_only: true,
};
const result = await submitOrder(order);
if (result.success) {
toast.success('Position closed!');
}
};
return (
<Button color="danger" onClick={closePosition}>
Close Position
</Button>
);
}tsx
import { useMutation } from '@orderly.network/hooks';
import { OrderType, OrderSide } from '@orderly.network/types';
function ClosePositionButton({ position }) {
const [submitOrder] = useMutation('/v1/order');
const closePosition = async () => {
const order = {
symbol: position.symbol,
side: position.position_qty > 0 ? OrderSide.SELL : OrderSide.BUY,
order_type: OrderType.MARKET,
order_quantity: Math.abs(position.position_qty),
reduce_only: true,
};
const result = await submitOrder(order);
if (result.success) {
toast.success('仓位已平仓!');
}
};
return (
<Button color="danger" onClick={closePosition}>
平仓
</Button>
);
}8. Withdraw Funds
8. 提现资金
Using useWithdraw Hook
使用useWithdraw Hook
tsx
import { useWithdraw } from '@orderly.network/hooks';
function WithdrawForm() {
const { withdraw, maxAmount, availableWithdraw, unsettledPnL } = useWithdraw({
srcChainId: 42161,
token: 'USDC',
decimals: 6,
});
const [amount, setAmount] = useState('');
const handleWithdraw = async () => {
try {
await withdraw(parseFloat(amount));
toast.success('Withdrawal initiated!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Amount" />
<Text>Available: {availableWithdraw} USDC</Text>
<Text>Max: {maxAmount} USDC</Text>
<Button onClick={handleWithdraw}>Withdraw</Button>
</div>
);
}tsx
import { useWithdraw } from '@orderly.network/hooks';
function WithdrawForm() {
const { withdraw, maxAmount, availableWithdraw, unsettledPnL } = useWithdraw({
srcChainId: 42161,
token: 'USDC',
decimals: 6,
});
const [amount, setAmount] = useState('');
const handleWithdraw = async () => {
try {
await withdraw(parseFloat(amount));
toast.success('提现已发起!');
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="金额" />
<Text>可提现金额: {availableWithdraw} USDC</Text>
<Text>最大可提现: {maxAmount} USDC</Text>
<Button onClick={handleWithdraw}>提现</Button>
</div>
);
}9. Leverage Management
9. 杠杆管理
Get/Set Leverage
获取/设置杠杆
tsx
import { useLeverage } from '@orderly.network/hooks';
function LeverageControl() {
const { curLeverage, maxLeverage, leverageLevers, update, isLoading } = useLeverage();
const changeLeverage = async (newLeverage: number) => {
try {
await update({ leverage: newLeverage });
toast.success(`Leverage set to ${newLeverage}x`);
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Text>Current: {curLeverage}x</Text>
<Slider
value={[curLeverage]}
onValueChange={([v]) => changeLeverage(v)}
min={1}
max={maxLeverage}
/>
</div>
);
}tsx
import { useLeverage } from '@orderly.network/hooks';
function LeverageControl() {
const { curLeverage, maxLeverage, leverageLevers, update, isLoading } = useLeverage();
const changeLeverage = async (newLeverage: number) => {
try {
await update({ leverage: newLeverage });
toast.success(`杠杆已设置为${newLeverage}倍`);
} catch (error) {
toast.error(error.message);
}
};
return (
<div>
<Text>当前杠杆: {curLeverage}x</Text>
<Slider
value={[curLeverage]}
onValueChange={([v]) => changeLeverage(v)}
min={1}
max={maxLeverage}
/>
</div>
);
}10. Risk Monitoring
10. 风险监控
Margin Ratio
保证金比率
tsx
import { useMarginRatio } from '@orderly.network/hooks';
function RiskIndicator() {
const { marginRatio, mmr, currentLeverage } = useMarginRatio();
const isAtRisk = marginRatio < mmr * 1.5;
return (
<Card>
<Text>Margin Ratio: {(marginRatio * 100).toFixed(2)}%</Text>
<Text>MMR: {(mmr * 100).toFixed(2)}%</Text>
{isAtRisk && <Badge color="warning">Approaching Liquidation</Badge>}
</Card>
);
}tsx
import { useMarginRatio } from '@orderly.network/hooks';
function RiskIndicator() {
const { marginRatio, mmr, currentLeverage } = useMarginRatio();
const isAtRisk = marginRatio < mmr * 1.5;
return (
<Card>
<Text>保证金比率: {(marginRatio * 100).toFixed(2)}%</Text>
<Text>维持保证金率(MMR): {(mmr * 100).toFixed(2)}%</Text>
{isAtRisk && <Badge color="warning">即将触发强平</Badge>}
</Card>
);
}Complete Trading Page Example
完整交易页面示例
tsx
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { TradingPage } from '@orderly.network/trading';
import { AuthGuard } from '@orderly.network/ui-connector';
import { API } from '@orderly.network/types';
export default function Trading() {
const { symbol } = useParams();
const navigate = useNavigate();
const onSymbolChange = (data: API.Symbol) => {
navigate(`/trade/${data.symbol}`);
};
return (
<AuthGuard>
<TradingPage
symbol={symbol!}
onSymbolChange={onSymbolChange}
tradingViewConfig={{
scriptSRC: '/tradingview/charting_library/charting_library.js',
library_path: '/tradingview/charting_library/',
}}
sharePnLConfig={{
backgroundImages: ['/pnl-bg-1.png', '/pnl-bg-2.png'],
}}
/>
</AuthGuard>
);
}tsx
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { TradingPage } from '@orderly.network/trading';
import { AuthGuard } from '@orderly.network/ui-connector';
import { API } from '@orderly.network/types';
export default function Trading() {
const { symbol } = useParams();
const navigate = useNavigate();
const onSymbolChange = (data: API.Symbol) => {
navigate(`/trade/${data.symbol}`);
};
return (
<AuthGuard>
<TradingPage
symbol={symbol!}
onSymbolChange={onSymbolChange}
tradingViewConfig={{
scriptSRC: '/tradingview/charting_library/charting_library.js',
library_path: '/tradingview/charting_library/',
}}
sharePnLConfig={{
backgroundImages: ['/pnl-bg-1.png', '/pnl-bg-2.png'],
}}
/>
</AuthGuard>
);
}Error Handling Patterns
错误处理模式
Order-Specific Errors
订单相关错误
tsx
import { useOrderEntry } from '@orderly.network/hooks';
function OrderForm() {
const { errors, submit } = useOrderEntry('PERP_ETH_USDC');
const handleSubmit = async () => {
if (errors.order_price) {
toast.error(`Price: ${errors.order_price}`);
return;
}
try {
await submit();
} catch (error) {
if (error.code === 'INSUFFICIENT_BALANCE') {
toast.error('Insufficient balance. Please deposit more funds.');
} else if (error.code === 'RISK_TOO_HIGH') {
toast.error('Order rejected: would exceed risk limits.');
} else {
toast.error(error.message);
}
}
};
}tsx
import { useOrderEntry } from '@orderly.network/hooks';
function OrderForm() {
const { errors, submit } = useOrderEntry('PERP_ETH_USDC');
const handleSubmit = async () => {
if (errors.order_price) {
toast.error(`价格错误: ${errors.order_price}`);
return;
}
try {
await submit();
} catch (error) {
if (error.code === 'INSUFFICIENT_BALANCE') {
toast.error('余额不足,请充值更多资金。');
} else if (error.code === 'RISK_TOO_HIGH') {
toast.error('订单被拒绝:超出风险限制。');
} else {
toast.error(error.message);
}
}
};
}Best Practices
最佳实践
1. Always Check Auth Before Trading
1. 交易前务必检查认证状态
tsx
const { state } = useAccount();
if (state.status !== AccountStatusEnum.SignedIn) {
return <AuthGuard>{children}</AuthGuard>;
}tsx
const { state } = useAccount();
if (state.status !== AccountStatusEnum.SignedIn) {
return <AuthGuard>{children}</AuthGuard>;
}2. Validate Orders Before Submission
2. 提交前验证订单
tsx
const { errors, validated } = metaState;
if (!validated || Object.keys(errors).length > 0) {
// Don't submit
}tsx
const { errors, validated } = metaState;
if (!validated || Object.keys(errors).length > 0) {
// 不要提交
}3. Use Real-time Streams for Position Data
3. 使用实时流获取仓位数据
tsx
// Good - real-time updates
const [positions] = usePositionStream();tsx
// 推荐 - 实时更新
const [positions] = usePositionStream();4. Handle Loading States
4. 处理加载状态
tsx
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;tsx
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;5. Show Execution Feedback
5. 显示执行反馈
tsx
toast.loading('Submitting order...');
try {
await submit();
toast.success('Order placed!');
} catch (e) {
toast.error(e.message);
}tsx
toast.loading('提交订单中...');
try {
await submit();
toast.success('订单已下单!');
} catch (e) {
toast.error(e.message);
}Related Skills
相关技能
- orderly-sdk-wallet-connection - Wallet integration
- orderly-sdk-react-hooks - Hook reference
- orderly-trading-orders - Order management details
- orderly-positions-tpsl - Position management
- orderly-deposit-withdraw - Fund management
- orderly-sdk-wallet-connection - 钱包集成
- orderly-sdk-react-hooks - Hook参考
- orderly-trading-orders - 订单管理详情
- orderly-positions-tpsl - 仓位管理
- orderly-deposit-withdraw - 资金管理