关于 orderly-positions-tpsl
orderly-positions-tpsl 是用于管理 Orderly Network 永续合约持仓和风险设置的技能,涵盖持仓与盈亏数据、杠杆以及止盈止损单,并介绍 REST API 和 React hooks。
主要功能
- 01读取持仓及历史记录
- 02实时获取持仓并更新盈亏
- 03全部或部分平仓
- 04查询和设置杠杆
- 05配置及取消止盈止损单
- 06查看保证金与清算风险
适用场景
- 01构建持仓管理界面
- 02跟踪未实现盈亏与杠杆
- 03设置或取消持仓止盈止损单
- 04监控保证金和清算风险
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ orderlynetwork/ skills --skill orderly-positions-tpsl安装后在 Claude Code 中输入/orderly-positions-tpsl确认已加载。
详细介绍
Orderly Network:持仓与 TP/SL
本技能涵盖持仓管理、PnL 跟踪、杠杆设置,以及配置止盈(TP)和止损(SL)订单以进行风险管理。
适用场景
- 构建持仓管理界面
- 实施带有 TP/SL 的风险管理
- 跟踪未实现 PnL
- 调整杠杆设置
前提条件
- 在 Orderly 上有未平仓持仓
- 了解永续期货
- 具有
read和trading权限范围的 API 密钥
持仓数据结构
interface Position {
symbol: string; // e.g., "PERP_ETH_USDC"
position_qty: number; // Positive = long, Negative = short
average_open_price: number; // Entry price
mark_price: number; // Current mark price
unrealized_pnl: number; // Unrealized profit/loss
unrealized_pnl_roi: number; // ROI percentage
mmr: number; // Maintenance margin ratio
imr: number; // Initial margin ratio
notional: number; // Position value
leverage: number; // Current leverage
est_liq_price: number; // Estimated liquidation price
cost_position: number; // Position cost
settle_price: number; // Settlement price
unsettled_pnl: number; // Unsettled PnL
}
获取持仓(REST API)
// Get all positions
GET /v1/positions
// Get position for specific symbol
GET /v1/position/{symbol}
// Example response
{
"success": true,
"data": {
"rows": [
{
"symbol": "PERP_ETH_USDC",
"position_qty": 0.5,
"average_open_price": 3000,
"mark_price": 3100,
"unrealized_pnl": 50,
"unrealized_pnl_roi": 0.0333,
"mmr": 0.01,
"imr": 0.02,
"notional": 1550,
"leverage": 10,
"est_liq_price": 2700
}
]
}
}
React SDK:usePositionStream
通过实时流式传输持仓并自动更新 PnL:
import { usePositionStream } from '@orderly.network/hooks';
function PositionsTable() {
const {
rows,
aggregated,
totalUnrealizedROI,
isLoading
} = usePositionStream();
if (isLoading) return <div>Loading positions...</div>;
return (
<div>
<div className="summary">
<h3>Total Unrealized PnL: {aggregated?.totalUnrealizedPnl?.toFixed(2)} USDC</h3>
<p>ROI: {(totalUnrealizedROI * 100).toFixed(2)}%</p>
</div>
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Size</th>
<th>Entry Price</th>
<th>Mark Price</th>
<th>Unrealized PnL</th>
<th>Leverage</th>
<th>Liq. Price</th>
</tr>
</thead>
<tbody>
{rows.map((position) => (
<tr key={position.symbol}>
<td>{position.symbol}</td>
<td className={position.position_qty > 0 ? 'long' : 'short'}>
{position.position_qty > 0 ? '+' : ''}{position.position_qty}
</td>
<td>{position.average_open_price.toFixed(2)}</td>
<td>{position.mark_price.toFixed(2)}</td>
<td className={position.unrealized_pnl >= 0 ? 'profit' : 'loss'}>
{position.unrealized_pnl.toFixed(2)} USDC
</td>
<td>{position.leverage}x</td>
<td>{position.liq_price.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
平仓
部分平仓
import { usePositionClose } from '@orderly.network/hooks';
function ClosePositionButton({ symbol, positionQty }: { symbol: string; positionQty: number }) {
const { closePosition, isClosing } = usePositionClose();
const handleClose = async (percentage: number) => {
const quantity = Math.abs(positionQty) * (percentage / 100);
await closePosition({
symbol,
qty: quantity,
side: positionQty > 0 ? 'SELL' : 'BUY',
});
};
return (
<div>
<button onClick={() => handleClose(25)} disabled={isClosing}>Close 25%</button>
<button onClick={() => handleClose(50)} disabled={isClosing}>Close 50%</button>
<button onClick={() => handleClose(100)} disabled={isClosing}>Close 100%</button>
</div>
);
}
市价平仓(REST API)
// Close entire position at market price
POST /v1/order
Body: {
symbol: 'PERP_ETH_USDC',
side: positionQty > 0 ? 'SELL' : 'BUY',
order_type: 'MARKET',
order_quantity: Math.abs(positionQty).toString(),
reduce_only: true,
}
杠杆管理
获取当前杠杆
GET /v1/client/leverage?symbol={symbol}
// Response
{
"success": true,
"data": {
"leverage": 10,
"max_leverage": 25
}
}
设置杠杆
POST /v1/client/leverage
Body: {
symbol: 'PERP_ETH_USDC',
leverage: 15, // New leverage value
}
// React SDK
import { useLeverage } from '@orderly.network/hooks';
function LeverageSlider({ symbol }: { symbol: string }) {
const { leverage, maxLeverage, setLeverage, isLoading } = useLeverage(symbol);
const handleChange = async (newLeverage: number) => {
try {
await setLeverage(newLeverage);
} catch (error) {
console.error('Failed to set leverage:', error);
}
};
return (
<div>
<label>Leverage: {leverage}x</label>
<input
type="range"
min="1"
max={maxLeverage}
value={leverage}
onChange={(e) => handleChange(parseInt(e.target.value))}
disabled={isLoading}
/>
</div>
);
}
止盈 / 止损订单
TP/SL 订单类型
| 类型 | 描述 |
|---|---|
TAKE_PROFIT | 价格达到目标时触发(获利) |
STOP_LOSS | 价格跌破阈值时触发 |
TRAILING_STOP | 随价格变动的动态止损 |
使用 useTPSLOrder Hook
import { useTPSLOrder } from '@orderly.network/hooks';
function TPSSettings({ position }: { position: Position }) {
const [computed, { setValue, submit, validate, reset }] = useTPSLOrder(position);
const handleSubmit = async () => {
try {
await validate();
await submit();
console.log('TP/SL order placed');
} catch (error) {
console.error('TP/SL failed:', error);
}
};
return (
<div className="tpsl-form">
<h4>Take Profit</h4>
<div>
<label>Trigger Price</label>
<input
type="number"
placeholder="TP Price"
onChange={(e) => setValue('tp_trigger_price', e.target.value)}
/>
</div>
<div>
<label>Or Offset %</label>
<input
type="number"
placeholder="e.g., 5 for 5%"
onChange={(e) => setValue('tp_offset_percentage', parseFloat(e.target.value))}
/>
</div>
<h4>Stop Loss</h4>
<div>
<label>Trigger Price</label>
<input
type="number"
placeholder="SL Price"
onChange={(e) => setValue('sl_trigger_price', e.target.value)}
/>
</div>
<div>
<label>Or Offset %</label>
<input
type="number"
placeholder="e.g., -5 for -5%"
onChange={(e) => setValue('sl_offset_percentage', parseFloat(e.target.value))}
/>
</div>
<button onClick={handleSubmit}>Set TP/SL</button>
</div>
);
}
REST API:用于 TP/SL 的 Algo 订单
// Place TP/SL order (creates both TP and SL as child orders)
POST /v1/algo/order
Body: {
symbol: 'PERP_ETH_USDC',
algo_type: 'TP_SL',
quantity: 5.5,
trigger_price_type: 'MARK_PRICE',
child_orders: [
{
symbol: 'PERP_ETH_USDC',
algo_type: 'TAKE_PROFIT',
side: 'SELL',
type: 'MARKET',
trigger_price: 3500,
reduce_only: true
},
{
symbol: 'PERP_ETH_USDC',
algo_type: 'STOP_LOSS',
side: 'SELL',
type: 'MARKET',
trigger_price: 2800,
reduce_only: true
}
]
}
// Positional TP/SL (attached to entire position)
POST /v1/algo/order
Body: {
symbol: 'PERP_ETH_USDC',
algo_type: 'POSITIONAL_TP_SL',
trigger_price_type: 'MARK_PRICE',
child_orders: [
{
symbol: 'PERP_ETH_USDC',
algo_type: 'TAKE_PROFIT',
side: 'SELL',
type: 'CLOSE_POSITION',
trigger_price: 3500,
reduce_only: true
},
{
symbol: 'PERP_ETH_USDC',
algo_type: 'STOP_LOSS',
side: 'SELL',
type: 'CLOSE_POSITION',
trigger_price: 2800,
reduce_only: true
}
]
}
STOP 订单(止损市价单)
POST /v1/algo/order
Body: {
symbol: 'PERP_ETH_USDC',
algo_type: 'STOP',
quantity: 5.5,
side: 'BUY',
type: 'LIMIT',
trigger_price_type: 'MARK_PRICE',
trigger_price: 4.203,
price: 3.5 // Limit price for the triggered order
}
取消 TP/SL 订单
// Cancel single algo order
DELETE /v1/algo/order?order_id={order_id}&symbol={symbol}
// Cancel all algo orders for symbol
DELETE /v1/algo/orders?symbol={symbol}
// React SDK
const [algoOrders, { cancelAlgoOrder }] = useAlgoOrderStream();
await cancelAlgoOrder(orderId);
持仓历史
GET /v1/position_history?symbol={symbol}&start={timestamp}&end={timestamp}
// Response includes closed positions with realized PnL
PnL 计算
未实现 PnL
// For LONG positions
unrealizedPnL = (markPrice - averageOpenPrice) * positionQty;
// For SHORT positions
unrealizedPnL = (averageOpenPrice - markPrice) * Math.abs(positionQty);
ROI
// Return on Investment
roi = unrealizedPnL / ((averageOpenPrice * Math.abs(positionQty)) / leverage);
强平价格
// For LONG positions
liqPrice = averageOpenPrice * (1 - mmr - 1 / leverage);
// For SHORT positions
liqPrice = averageOpenPrice * (1 + mmr + 1 / leverage);
风险指标
// Available fields from GET /v1/positions response:
{
"current_margin_ratio_with_orders": 1.2385,
"free_collateral": 450315.09,
"initial_margin_ratio": 0.1,
"initial_margin_ratio_with_orders": 0.1,
"maintenance_margin_ratio": 0.05,
"maintenance_margin_ratio_with_orders": 0.05,
"margin_ratio": 1.2385,
"open_margin_ratio": 1.2102,
"total_collateral_value": 489865.71,
"total_pnl_24_h": 0
}
保证金与抵押品:了解层级结构
Orderly 使用多层风险系统。以下说明各部分如何配合:
Your Deposit
↓
[Collateral Factor] → Determines effective collateral value
↓
Effective Collateral (what you can actually use)
↓
[IMR/MMR] → Required margin per position
↓
Used Collateral (locked in positions)
↓
Free Collateral (available for new trades)
三个层级说明
1. 抵押品系数(代币层级)
- 由 Orderly 风险团队按代币设定
- 示例:USDC = 1.0,USDT = 0.95
- 存入时应用:$1000 USDT × 0.95 = $950 有效抵押品
- 查询位置:
GET /v1/public/token
2. IMR/MMR(持仓层级)
- IMR(初始保证金率):开立持仓所需的最低抵押品
- MMR(维持保证金率):保持持仓开放所需的最低抵押品
- 由杠杆决定:10 倍杠杆 = 10% IMR、约 5% MMR
- 应用于持仓名义价值:$10,000 持仓 × 10% IMR = 所需 $1,000
- 查询位置:持仓对象或交易对信息
3. 账户保证金率(账户层级)
margin_ratio = total_collateral / total_notional- 如果该值降至接近 MMR,表示你正接近强平
- 查询位置:
GET /v1/client/holding
计算示例
Deposit: $10,000 USDC (collateral_factor = 1.0)
Effective Collateral: $10,000
Open Position: $50,000 ETH-PERP at 10x leverage
IMR Required: $50,000 × 10% = $5,000
MMR Required: $50,000 × 5% = $2,500
After opening:
- Used Collateral: $5,000
- Free Collateral: $5,000
- Margin Ratio: $10,000 / $50,000 = 20%
Liquidation happens when:
- Margin Ratio drops to MMR (5%)
- That means your collateral drops to $2,500
- Or position grows to $200,000 notional
要点:你需要足够的有效抵押品(应用抵押品系数后)以满足 IMR 要求(由杠杆决定)。margin_ratio 可显示你距离强平有多近(由 MMR 决定)。
常见问题
“Position would exceed max leverage”错误
- 当前名义价值加上新杠杆后超出限额
- 减少持仓规模或增加抵押品
“Insufficient margin for TP/SL”错误
- TP/SL 订单需要可用保证金
- 平掉部分持仓或增加抵押品
TP/SL 未触发
- 检查 trigger_price 是否有效
- 确认订单状态为 NEW
- 市场价格可能已跳空越过触发价
强平风险
- 密切关注 margin_ratio
- 尽早设置止损
- 留意持仓时间较长时的资金费率
相关技能
- orderly-trading-orders - 下单
- orderly-websocket-streaming - 实时持仓更新
- orderly-sdk-react-hooks - 完整 SDK 参考
- orderly-api-authentication - 签名请求
评论
支持 Markdown