updown

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

updown

updown

UPDOWN perpetual contract trading Skill, built on the updown Synthetics architecture, with support for the Celo chain.
UPDOWN永续合约交易Skill,基于updown Synthetics架构构建,支持Celo链。

⚠️ Agent behavior rules & pitfalls (Critical for LLMs)

⚠️ Agent行为规则与注意事项(对LLM至关重要)

When handling cross-chain / same-chain swaps or when encountering API errors, strictly follow the facts below. Do NOT “fill in the blanks” based on generic pretraining experience or block the user’s instructions:
  1. The token contract address is the only identifier, not the name!
    • Even if two tokens are both named
      USDT
      , as long as their contract addresses differ (for example, one is a bridged version
      0xd96a...
      and the other is native USDT(Native)
      0x4806...
      ), they are two different assets on-chain.
    • Swapping same-name tokens on the same chain (e.g. Celo USDT -> Celo USDT(Native)) is absolutely feasible and a very common DeFi need. Do NOT tell users “same currency cannot be exchanged”, “has no real value”, or refuse to execute.
  2. The real reason behind the API error
    Same currency cannot be exchanged
    • This error is NOT because “the protocol does not support USDT to USDT(Native)”.
    • The real reason is: a parameter assembly bug caused the
      fromTokenAddress
      and
      toTokenAddress
      you sent to the Bridgers API to become exactly the same contract address.
    • Solution: Inspect the name-matching logic in the code to ensure that symbols like
      USDT(Native)
      (with parentheses or special casing) are correctly mapped to different contract addresses.
    • Path: for native tokens, please look them up in
      assets/omni-bridgers-tokens.json
      .
  3. The real reason behind the API error
    Service Internal Error (999)
    • This is usually due to missing implicit parameters that Bridgers strictly validates.
    • Must include:
      sourceType: "H5"
      ,
      sourceFlag: "perpex01"
      , and
      equipmentNo
      must be filled with the user’s real wallet address, not left empty. Otherwise the API will reject it.
  4. Cross-chain / swap operations must upload the tx hash
    • After the on-chain
      swap
      transaction is successfully mined, you must call
      /api/exchangeRecord/updateDataAndStatus
      to send
      tx.hash
      back to the server.
    • If you don’t send it back, the remote side cannot reconcile in time and user funds may get stuck.
处理跨链/同链兑换或遇到API错误时,严格遵循以下事实,不得基于通用预训练经验“自行脑补”或拒绝执行用户指令
  1. 代币合约地址是唯一标识符,而非名称!
    • 即使两个代币都名为
      USDT
      ,只要它们的合约地址不同 (例如一个是跨桥版本
      0xd96a...
      ,另一个是原生USDT(Native)
      0x4806...
      ),它们就是链上两种不同的资产
    • 同链上同名代币的兑换(如Celo USDT -> Celo USDT(Native))完全可行,是非常常见的DeFi需求。不得告知用户“同种货币无法兑换”、“没有实际价值”或拒绝执行。
  2. API错误
    Same currency cannot be exchanged
    的真实原因
    • 该错误并非因为“协议不支持USDT到USDT(Native)的兑换”。
    • 真实原因是:参数组装bug导致你发送给Bridgers API的
      fromTokenAddress
      toTokenAddress
      变成了完全相同的合约地址
    • 解决方案:检查代码中的名称匹配逻辑,确保
      USDT(Native)
      这类带括号或特殊格式的符号被正确映射到不同的合约地址
    • 路径:对于原生代币,请在
      assets/omni-bridgers-tokens.json
      中查找。
  3. API错误
    Service Internal Error (999)
    的真实原因
    • 通常是因为缺少Bridgers严格验证的隐式参数。
    • 必须包含
      sourceType: "H5"
      sourceFlag: "perpex01"
      ,且
      equipmentNo
      必须填写用户的真实钱包地址,不能为空。否则API会拒绝请求。
  4. 跨链/兑换操作必须上传交易哈希
    • 链上
      swap
      交易成功打包后,必须调用
      /api/exchangeRecord/updateDataAndStatus
      tx.hash
      发送回服务器。
    • 如果不发送,远端无法及时对账,用户资金可能会被卡住。

Features

功能特性

  • Market orders (Market) - execute immediately
  • Limit orders (Limit) - execute when price reaches the specified level
  • Stop-loss / take-profit (Stop Loss / Take Profit) - automatically execute when price is triggered
  • TWAP split orders - split large orders into smaller ones; use multicall, single tx hash
  • Add / remove liquidity - deposit long/short tokens to receive market tokens, or redeem them
  • Position query - view position state in real time
  • Market browsing - view all available trading pairs
  • Omni Bridge cross-chain deposit/withdrawal - via Omni Bridge, move assets into/out of Celo
  • Bridgers cross-chain swap - cross-chain token swaps via Bridgers (e.g. Arbitrum USDC → Celo USDT)
  • 市价单(Market) - 立即执行
  • 限价单(Limit) - 价格达到指定水平时执行
  • 止损/止盈(Stop Loss / Take Profit) - 价格触发时自动执行
  • TWAP拆分订单 - 将大额订单拆分为多个小订单;使用multicall,单交易哈希
  • 添加/移除流动性 - 存入多/空代币以获取市场代币,或赎回代币
  • 持仓查询 - 实时查看持仓状态
  • 市场浏览 - 查看所有可用交易对
  • Omni Bridge跨链存提 - 通过Omni Bridge在Celo链间转移资产
  • Bridgers跨链兑换 - 通过Bridgers进行跨链代币兑换(如Arbitrum USDC → Celo USDT)

Quick start

快速开始

Method 1: Trading assistant (recommended)

方法1:交易助手(推荐)

The trading assistant supports natural language input and automatically parses and generates orders:
bash
undefined
交易助手支持自然语言输入,自动解析并生成订单:
bash
undefined

Show help

显示帮助

node scripts/trade-assistant.js
node scripts/trade-assistant.js

Open position with market order

市价单开仓

node scripts/trade-assistant.js "Create a BTC/USDT long market order with 10 USDT margin and 2x leverage"
node scripts/trade-assistant.js "创建BTC/USDT多头市价单,保证金10 USDT,杠杆2倍"

Open position with limit order

限价单开仓

node scripts/trade-assistant.js "Open a short ETH position with a limit price of 3500 and 5 USDT margin"
node scripts/trade-assistant.js "以3500的限价开ETH空头,保证金5 USDT"

Close position

平仓

node scripts/trade-assistant.js "Close my BTC/USDT long position"
node scripts/trade-assistant.js "平仓我的BTC/USDT多头"

Stop-loss / take-profit

止损/止盈

node scripts/trade-assistant.js "Set stop-loss for BTC long position, trigger price 60000" node scripts/trade-assistant.js "Set take-profit for ETH short position, trigger price 4000"
node scripts/trade-assistant.js "为BTC多头设置止损,触发价60000" node scripts/trade-assistant.js "为ETH空头设置止盈,触发价4000"

Queries

查询

node scripts/trade-assistant.js "Show my positions" node scripts/trade-assistant.js "Check my balance"
undefined
node scripts/trade-assistant.js "查看我的持仓" node scripts/trade-assistant.js "查询我的余额"
undefined

Add / remove liquidity

添加/移除流动性

bash
undefined
bash
undefined

Add liquidity

添加流动性

node scripts/add-liquidity.js assets/orders/add-liquidity-btc-example.json
node scripts/add-liquidity.js assets/orders/add-liquidity-btc-example.json

Remove liquidity

移除流动性

node scripts/remove-liquidity.js assets/orders/remove-liquidity-btc-example.json

You must configure `DepositVault`, `WithdrawalVault`, and `WNT` in `assets/addresses.json`.
See [references/liquidity-deposit-withdrawal.md](references/liquidity-deposit-withdrawal.md).
node scripts/remove-liquidity.js assets/orders/remove-liquidity-btc-example.json

你必须在`assets/addresses.json`中配置`DepositVault`、`WithdrawalVault`和`WNT`。详情请见[references/liquidity-deposit-withdrawal.md](references/liquidity-deposit-withdrawal.md)。

Method 2: Use the CLI tool

方法2:使用CLI工具

1. View available markets

1. 查看可用市场

bash
node scripts/trade-cli.js markets
Note: The market list is read from config files by default. To update it, run:
bash
undefined
bash
node scripts/trade-cli.js markets
注意:市场列表默认从配置文件读取。如需更新,请运行:
bash
undefined

Try updating the market list from chain

尝试从链上更新市场列表

node scripts/update-markets.js
node scripts/update-markets.js

Or view markets directly on-chain (experimental)

或直接从链上查看市场(实验性)

node scripts/markets-onchain.js
undefined
node scripts/markets-onchain.js
undefined

2. View order types

2. 查看订单类型

bash
node scripts/trade-cli.js order-types
bash
node scripts/trade-cli.js order-types

3. Generate order templates

3. 生成订单模板

bash
undefined
bash
undefined

Market order template (open position)

市价单开仓模板

node scripts/trade-cli.js template MarketIncrease
node scripts/trade-cli.js template MarketIncrease

Limit order template (open position)

限价单开仓模板

node scripts/trade-cli.js template LimitIncrease
node scripts/trade-cli.js template LimitIncrease

Stop-loss template (close position)

止损平仓模板

node scripts/trade-cli.js template StopLossDecrease
node scripts/trade-cli.js template StopLossDecrease

Take-profit template (close position)

止盈平仓模板

node scripts/trade-cli.js template TakeProfitDecrease
undefined
node scripts/trade-cli.js template TakeProfitDecrease
undefined

4. Execute trades

4. 执行交易

bash
undefined
bash
undefined

Open position

开仓

node scripts/open-position.js assets/orders/<config-file>
node scripts/open-position.js assets/orders/<配置文件>

Close position

平仓

node scripts/close-position.js assets/orders/<config-file>

**Note**: Order config files are stored in the `assets/orders/` directory by default.
node scripts/close-position.js assets/orders/<配置文件>

**注意**:订单配置文件默认存储在`assets/orders/`目录下。

5. Query positions

5. 查询持仓

bash
undefined
bash
undefined

Query positions

查询持仓

node scripts/query.js positions
node scripts/query.js positions

Query balance

查询余额

node scripts/query.js balance
undefined
node scripts/query.js balance
undefined

Order types in detail

订单类型详情

Opening orders (Increase Position)

开仓订单(Increase Position)

TypeOrderTypeDescription
MarketIncrease2Market order to open a position; executes at current price
LimitIncrease3Limit order to open; executes when price reaches triggerPrice
TwapMarketIncrease3TWAP market open; splits a large order into multiple parts
StopIncrease8Market stop order
类型OrderType描述
MarketIncrease2市价单开仓;按当前价格执行
LimitIncrease3限价单开仓;价格达到triggerPrice时执行
TwapMarketIncrease3TWAP市价开仓;将大额订单拆分为多个部分
StopIncrease8市价止损开仓

Closing orders (Decrease Position)

平仓订单(Decrease Position)

TypeOrderTypeDescription
MarketDecrease4Market order to close; executes immediately at current price
LimitDecrease5Limit order to close; executes when price reaches triggerPrice
StopLossDecrease6Stop-loss close; automatically executes when price falls to triggerPrice
TakeProfitDecrease5Take-profit close; automatically executes when price rises to triggerPrice
TwapMarketDecrease5TWAP close; splits a large order into multiple parts, multicall, one tx hash
类型OrderType描述
MarketDecrease4市价单平仓;立即按当前价格执行
LimitDecrease5限价单平仓;价格达到triggerPrice时执行
StopLossDecrease6止损平仓;价格跌至triggerPrice时自动执行
TakeProfitDecrease5止盈平仓;价格涨至triggerPrice时自动执行
TwapMarketDecrease5TWAP平仓;将大额订单拆分为多个部分,使用multicall,单交易哈希

Order configuration parameters

订单配置参数

Basic parameters

基础参数

json
{
  "market": "0x...", // Market address (required)
  "indexToken": "0x...", // Index token address (required)
  "initialCollateralToken": "0x...", // Collateral token (required)
  "isLong": true, // Long position or not (required)
  "orderType": 0, // Order type (required)
  "sizeDeltaUsdHuman": 100, // Position size (USD)
  "initialCollateralDeltaAmountHuman": 100 // Collateral amount
}
json
{
  "market": "0x...", // 市场地址(必填)
  "indexToken": "0x...", // 指数代币地址(必填)
  "initialCollateralToken": "0x...", // 保证金代币(必填)
  "isLong": true, // 是否为多头(必填)
  "orderType": 0, // 订单类型(必填)
  "sizeDeltaUsdHuman": 100, // 持仓规模(美元)
  "initialCollateralDeltaAmountHuman": 100 // 保证金金额
}

Limit / stop parameters

限价/止损参数

json
{
  "triggerPriceHuman": 70000, // Trigger price (for limit/stop orders)
  "acceptablePriceHuman": 70500 // Acceptable price (slippage protection)
}
json
{
  "triggerPriceHuman": 70000, // 触发价格(用于限价/止损单)
  "acceptablePriceHuman": 70500 // 可接受价格(滑点保护)
}

TWAP parameters

TWAP参数

json
{
  "twapInterval": 300, // Interval between each part (seconds)
  "twapParts": 5 // Number of parts to split into
}
json
{
  "twapInterval": 300, // 每部分订单的间隔时间(秒)
  "twapParts": 5 // 拆分的份数
}

Close-position-specific parameters

平仓专属参数

json
{
  "closePercent": 100 // Close percentage (1-100)
}
json
{
  "closePercent": 100 // 平仓比例(1-100)
}

Price calculation rules

价格计算规则

  • Open long position: acceptablePrice = oraclePrice × 1.03 (+3%)
  • Open short position: acceptablePrice = oraclePrice × 0.97 (-3%)
  • Close long position: acceptablePrice = oraclePrice × 0.97 (-3%)
  • Close short position: acceptablePrice = oraclePrice × 1.03 (+3%)
  • 开多头:acceptablePrice = oraclePrice × 1.03(+3%)
  • 开空头:acceptablePrice = oraclePrice × 0.97(-3%)
  • 平多头:acceptablePrice = oraclePrice × 0.97(-3%)
  • 平空头:acceptablePrice = oraclePrice × 1.03(+3%)

Execution fee

执行手续费

  • Default executionFee: 0.2 CELO
  • Can be customized via
    executionFeeHuman
    in the order config
  • 默认executionFee:0.2 CELO
  • 可通过订单配置中的
    executionFeeHuman
    自定义

Script list

脚本列表

ScriptPurpose
trade-assistant.js
Trading assistant - natural language orders, auto-generate configs
trade-cli.js
CLI tool (market query, template generation, parameter explanations)
open-position.js
Open position script (supports all order types)
close-position.js
Close position script (supports all close types)
add-liquidity.js
Add liquidity - after approval, multicall to deposit long/short tokens
remove-liquidity.js
Remove liquidity - after approval, multicall to redeem market tokens
query.js
Query tool (positions, balance)
update-markets.js
Update market list config file
markets-onchain.js
Read market list from chain (experimental)
omni-bridge-tx.js
Send Omni Bridge cross-chain tx (generic deposit/withdraw TX sender)
脚本用途
trade-assistant.js
交易助手 - 自然语言指令,自动生成配置文件
trade-cli.js
CLI工具(市场查询、模板生成、参数说明)
open-position.js
开仓脚本(支持所有订单类型)
close-position.js
平仓脚本(支持所有平仓类型)
add-liquidity.js
添加流动性 - 授权后,使用multicall存入多/空代币
remove-liquidity.js
移除流动性 - 授权后,使用multicall赎回市场代币
query.js
查询工具(持仓、余额)
update-markets.js
更新市场列表配置文件
markets-onchain.js
从链上读取市场列表(实验性)
omni-bridge-tx.js
发送Omni Bridge跨链交易(通用存提交易发送器)

Add / remove liquidity

添加/移除流动性

Providing liquidity to a market yields market tokens (LP tokens). Redeeming market tokens returns long/short tokens. The process follows the contracts: first approve tokens to the Router, then use ExchangeRouter.multicall to send
sendTokens
+
createDeposit
or
sendTokens
+
createWithdrawal
in a single transaction.
Pre-configuration: in
assets/addresses.json
, under
celo
, configure:
  • DepositVault
    - deposit contract address
  • WithdrawalVault
    - withdrawal contract address
  • WNT
    - execution-fee token address (usually wrapped native token on Celo)
For full details see references/liquidity-deposit-withdrawal.md.
为市场提供流动性可获得市场代币(LP代币)。赎回市场代币可换回多/空代币。流程遵循合约要求:先授权代币给Router,再使用ExchangeRouter.multicall在单笔交易中发送
sendTokens
+
createDeposit
sendTokens
+
createWithdrawal
预配置:在
assets/addresses.json
celo
节点下配置:
  • DepositVault
    - 存入合约地址
  • WithdrawalVault
    - 取出合约地址
  • WNT
    - 手续费代币地址(通常为Celo上的包装原生代币)
详细说明请见references/liquidity-deposit-withdrawal.md

Add liquidity (add-liquidity)

添加流动性(add-liquidity)

Deposit long tokens and short tokens to receive market tokens (LP tokens). After the keeper executes, market tokens are sent to
receiver
.
bash
node scripts/add-liquidity.js assets/orders/add-liquidity-btc-example.json
FieldDescription
marketSymbol
or
market
Market identifier, e.g.
"BTC"
or market address
initialLongTokenAmountHuman
Long token amount (human-readable)
initialShortTokenAmountHuman
Short token amount (human-readable)
executionFeeHuman
Execution fee (default 0.2)
receiver
Address to receive market tokens (defaults to wallet)
存入多代币和空代币以获取市场代币(LP代币)。在keeper执行后,市场代币会发送至
receiver
地址。
bash
node scripts/add-liquidity.js assets/orders/add-liquidity-btc-example.json
字段描述
marketSymbol
market
市场标识,例如
"BTC"
或市场地址
initialLongTokenAmountHuman
多代币数量(人类可读格式)
initialShortTokenAmountHuman
空代币数量(人类可读格式)
executionFeeHuman
执行手续费(默认0.2)
receiver
接收市场代币的地址(默认钱包地址)

Remove liquidity (remove-liquidity)

移除流动性(remove-liquidity)

Burn market tokens to retrieve long/short tokens. After the keeper executes, long and short tokens are sent to
receiver
.
bash
node scripts/remove-liquidity.js assets/orders/remove-liquidity-btc-example.json
FieldDescription
marketSymbol
or
market
Market identifier
marketTokenAmountHuman
Amount of market tokens to redeem
executionFeeHuman
Execution fee (default 0.2)
receiver
Address to receive long/short tokens (defaults to wallet)
销毁市场代币以取回多/空代币。在keeper执行后,多和空代币会发送至
receiver
地址。
bash
node scripts/remove-liquidity.js assets/orders/remove-liquidity-btc-example.json
字段描述
marketSymbol
market
市场标识
marketTokenAmountHuman
要赎回的市场代币数量
executionFeeHuman
执行手续费(默认0.2)
receiver
接收多/空代币的地址(默认钱包地址)

Liquidity flow

流动性流程

  1. Add: user approves → multicall(sendTokens × 3 + createDeposit) → keeper executes → receive market tokens
  2. Remove: user approves → multicall(sendTokens × 2 + createWithdrawal) → keeper executes → receive long/short tokens
  1. 添加:用户授权 → multicall(sendTokens ×3 + createDeposit) → keeper执行 → 接收市场代币
  2. 移除:用户授权 → multicall(sendTokens ×2 + createWithdrawal) → keeper执行 → 接收多/空代币

Omni Bridge cross-chain deposit / withdrawal

Omni Bridge跨链存提

This section documents the cross-chain deposit / withdrawal flow based on Omni Bridge. It provides command-line level instructions and a generic TX sending script. The script can run independently and does not depend on any specific frontend project.
本节记录基于Omni Bridge的跨链存提流程,提供命令行级别的操作说明和通用交易发送脚本。该脚本可独立运行,不依赖任何特定前端项目。

1. Concepts and use cases

1. 概念与使用场景

  • Omni Bridge: Cross-chain bridge infrastructure used to transfer representations of the same asset between chains (e.g. from Ethereum to Celo).
  • Role of this Skill:
    • Does not reimplement complex frontend quoting, route selection, or fee estimation logic in this repo;
    • Only provides a TX sender based on transaction data generated by a frontend/backend, so you can perform the same cross-chain action from a pure CLI environment.
Typical scenarios:
  • You obtain the parameters of an Omni Bridge transaction (
    to
    ,
    data
    ,
    value
    , etc.) from any frontend or its backend API and want to execute it directly on a server / terminal;
  • You already have a stable routing service to generate bridge transactions, and only need a reliable “sign and broadcast” script.
  • Omni Bridge:跨链桥基础设施,用于在链间转移同一资产的映射版本(例如从以太坊到Celo)。
  • 本Skill的作用
    • 不会在本仓库中重新实现复杂的前端报价、路径选择或手续费估算逻辑;
    • 仅提供基于前端/后端生成的交易数据的TX发送器,让你可以在纯CLI环境中执行相同的跨链操作。
典型场景:
  • 你从任意前端或其后端API获取了Omni Bridge交易的参数(
    to
    data
    value
    等),希望直接在服务器/终端执行;
  • 你已有稳定的路由服务来生成桥接交易,只需要一个可靠的“签名并广播”脚本。

2. Reference frontend-level flow

2. 参考前端流程

The typical frontend user flow (for understanding only) is:
  1. Select source and destination chains (for example: Ethereum → Celo).
  2. Select deposit/withdraw asset and amount:
    • Choose the token to send from the source chain (
      fromToken
      );
    • Choose the token to receive on the destination chain (
      toToken
      );
    • Enter the amount; the frontend uses
      bridgersFetcher
      or similar APIs to get quotes and min/max amounts.
  3. Check balance and allowance:
    • The frontend checks current token balance;
    • For ERC20 tokens, it checks allowance; if insufficient, it sends an Approve transaction first.
  4. Generate Omni Bridge transaction data:
    • The frontend calls the routing service and obtains the on-chain transaction details:
      • to
        : Omni Bridge or aggregator contract address
      • data
        : call data (ABI-encoded)
      • value
        : value of native asset to send, if any
  5. Send on-chain transaction:
    • The frontend sends the transaction via a wallet (e.g. MetaMask).
  6. Wait for cross-chain completion:
    • Listen for confirmation of the source chain transaction;
    • After bridging completes, check balance or records on the destination chain.
典型的前端用户流程(仅用于理解):
  1. 选择源链和目标链(例如:以太坊 → Celo)。
  2. 选择存提资产和金额
    • 选择从源链发送的代币(
      fromToken
      );
    • 选择在目标链接收的代币(
      toToken
      );
    • 输入金额;前端使用
      bridgersFetcher
      或类似API获取报价和最小/最大金额。
  3. 检查余额和授权
    • 前端检查当前代币余额;
    • 对于ERC20代币,检查授权额度;如果不足,先发送授权交易。
  4. 生成Omni Bridge交易数据
    • 前端调用路由服务,获取链上交易详情:
      • to
        :Omni Bridge或聚合器合约地址
      • data
        :调用数据(ABI编码)
      • value
        :要发送的原生资产金额(如有)
  5. 发送链上交易
    • 前端通过钱包(如MetaMask)发送交易。
  6. 等待跨链完成
    • 监听源链交易的确认;
    • 桥接完成后,检查目标链上的余额或记录。

3. Sending Omni Bridge transactions via script in this Skill

3. 使用本Skill的脚本发送Omni Bridge交易

This repo provides
scripts/omni-bridge-tx.js
to send any Omni Bridge-related transaction from the command line (no matter whether it’s “cross-chain deposit” or “cross-chain withdrawal”, as long as you already have
to
/
data
/
value
).
本仓库提供
scripts/omni-bridge-tx.js
,用于从命令行发送任何Omni Bridge相关交易(无论“跨链存入”还是“跨链取出”,只要你已有
to
/
data
/
value
)。

3.1 Environment configuration

3.1 环境配置

Reuse the existing Celo config file in this repo:
  • In
    assets/celo.env.local
    , configure:
bash
CELO_RPC_URL=your_CELO_RPC_url
CELO_PRIVATE_KEY=your_wallet_private_key
CELO_CHAIN_ID=42220 # or the corresponding Celo chain ID
Note: if you want to send Omni Bridge transactions on another chain, temporarily change the above environment variables to that chain’s RPC/private key/ChainId. The script itself only depends on the RPC and is not tightly bound to Celo.
复用本仓库中已有的Celo配置文件:
  • assets/celo.env.local
    中配置:
bash
CELO_RPC_URL=你的CELO_RPC地址
CELO_PRIVATE_KEY=你的钱包私钥
CELO_CHAIN_ID=42220 # 或对应的Celo链ID
注意:如果你想在其他链上发送Omni Bridge交易,临时将上述环境变量改为对应链的RPC/私钥/ChainId即可。脚本本身仅依赖RPC,与Celo无强绑定。

3.2 Usage: generic TX sender

3.2 使用:通用TX发送器

The CLI format is:
bash
node scripts/omni-bridge-tx.js \
  --to 0xBridgeOrRouterAddress \
  --data 0xYourCalldataHere \
  --value 0 \
  --gasLimit 600000
  • Required parameters
    • --to
      : transaction recipient address (typically the Omni Bridge/router contract)
    • --data
      : ABI-encoded call data
  • Optional parameters
    • --value
      : amount of native token to send (string, in ETH/CELO units, e.g.
      0
      or
      0.1
      )
    • --gasLimit
      : custom gas limit (defaults to
      ethers
      estimate)
Internally, the script:
  1. Reads
    CELO_RPC_URL
    ,
    CELO_PRIVATE_KEY
    ,
    CELO_CHAIN_ID
    from
    assets/celo.env.local
    ;
  2. Creates a Provider and Wallet via
    ethers
    ;
  3. Constructs and sends the transaction using the provided
    to
    ,
    data
    , and
    value
    ;
  4. Prints:
    • The sending wallet address
    • The transaction hash
    • Block number and gas usage once confirmed
CLI格式:
bash
node scripts/omni-bridge-tx.js \\
  --to 0xBridgeOrRouterAddress \\
  --data 0xYourCalldataHere \\
  --value 0 \\
  --gasLimit 600000
  • 必填参数
    • --to
      :交易接收地址(通常为Omni Bridge或路由合约)
    • --data
      :ABI编码的调用数据
  • 可选参数
    • --value
      :要发送的原生代币数量(字符串,以ETH/CELO为单位,例如
      0
      0.1
    • --gasLimit
      :自定义gas限制(默认由
      ethers
      估算)
脚本内部流程:
  1. assets/celo.env.local
    读取
    CELO_RPC_URL
    CELO_PRIVATE_KEY
    CELO_CHAIN_ID
  2. 通过
    ethers
    创建Provider和Wallet;
  3. 使用提供的
    to
    data
    value
    构造并发送交易;
  4. 打印:
    • 发送钱包地址
    • 交易哈希
    • 交易确认后的区块号和gas使用量

3.3 Using frontend-generated transaction data

3.3 使用前端生成的交易数据

When debugging with any frontend that integrates Omni Bridge routing, you usually obtain tx parameters from:
  • Intercepting wallet calls in the browser devtools;
  • Or using the
    tx
    data returned by the project’s routing/bridge API (e.g.
    { to, data, value }
    ).
Once you have these fields, plug them directly into the script, for example:
bash
node scripts/omni-bridge-tx.js \
  --to 0xYourOmniBridgeAddress \
  --data 0xabcdef1234... \
  --value 0.05
Semantically, this transaction can be:
  • Cross-chain deposit: deposit assets from the current chain into Omni Bridge and wait to receive tokens on the destination chain;
  • Cross-chain withdrawal: withdraw assets from a bridge contract to the current or another chain.
The script itself does not distinguish “deposit” from “withdrawal”; it only reliably signs and broadcasts the bridge transaction you have constructed.
在调试任何集成了Omni Bridge路由的前端时,通常可以通过以下方式获取交易参数:
  • 在浏览器开发者工具中拦截钱包调用;
  • 或使用项目路由/桥接API返回的
    tx
    数据(例如
    { to, data, value }
    )。
获取这些字段后,直接填入脚本即可,例如:
bash
node scripts/omni-bridge-tx.js \\
  --to 0xYourOmniBridgeAddress \\
  --data 0xabcdef1234... \\
  --value 0.05
从语义上,该交易可以是:
  • 跨链存入:将当前链的资产存入Omni Bridge,等待在目标链接收代币;
  • 跨链取出:从桥合约中取出资产到当前链或其他链。
脚本本身不区分“存入”和“取出”;它仅可靠地签名并广播你构造的桥接交易

3.4 End-to-end example using Bridgers REST API

3.4 使用Bridgers REST API的端到端示例

A typical cross-chain call can be executed by an HTTP client (in the style of
bridgersFetcher
) calling
https://api.bridgers.xyz
. The core flow is:
  1. The frontend constructs
    params
    (see
    submitHandle
    in
    DepositView.tsx
    /
    WithdrawalView.tsx
    ):
    • equipmentNo
      /
      fromAddress
      /
      toAddress
      : user address
    • fromTokenAddress
      /
      toTokenAddress
      : source/destination token addresses (use placeholder
      0xeeee...
      for native tokens)
    • fromTokenChain
      /
      toTokenChain
      : chain identifiers (e.g.
      ETH
      ,
      CELO
      , taken from token config
      mainNetwork
      )
    • fromTokenAmount
      : amount on the source chain (on-chain precision or API format)
    • amountOutMin
      : minimum acceptable output
    • fromCoinCode
      /
      toCoinCode
      : token symbols (e.g.
      USDT
      ,
      USDC
      )
  2. The frontend calls
    bridgersFetcher.fetchSwapCall(params)
    :
ts
// Pseudocode example: bridgersFetcher
export class bridgersFetcher {
  fetchSwapCall(params) {
    return fetch(buildUrl('https://api.bridgers.xyz', '/api/sswap/swap'), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params),
    }).then((res) => res.json())
  }
}
  1. On success, the response structure contains
    data.txData
    :
ts
// Typical snippet from DepositView / WithdrawalView
const calldata = await bridgers.fetchSwapCall(params)
if (calldata.resCode === 100) {
  const txData = calldata.data.txData
  // txData structure roughly:
  // {
  //   to:   "0x...", // target bridge/router contract address
  //   data: "0x...", // ABI-encoded calldata
  //   value:"0x..."  // optional, hex string amount
  // }
}
In the browser, the frontend hands
txData
directly to the wallet for signing and sending. In this Skill, you can perform the same operation on the server in two steps:
典型的跨链调用可通过HTTP客户端(如
bridgersFetcher
风格)调用
https://api.bridgers.xyz
执行。核心流程:
  1. 前端构造
    params
    (参考
    DepositView.tsx
    /
    WithdrawalView.tsx
    中的
    submitHandle
    ):
    • equipmentNo
      /
      fromAddress
      /
      toAddress
      :用户地址
    • fromTokenAddress
      /
      toTokenAddress
      :源/目标代币地址(原生代币使用占位符
      0xeeee...
    • fromTokenChain
      /
      toTokenChain
      :链标识(例如
      ETH
      CELO
      ,取自代币配置的
      mainNetwork
    • fromTokenAmount
      :源链上的金额(链上精度或API格式)
    • amountOutMin
      :最小可接受输出
    • fromCoinCode
      /
      toCoinCode
      :代币符号(例如
      USDT
      USDC
  2. 前端调用
    bridgersFetcher.fetchSwapCall(params)
ts
// 伪代码示例:bridgersFetcher
export class bridgersFetcher {
  fetchSwapCall(params) {
    return fetch(buildUrl('https://api.bridgers.xyz', '/api/sswap/swap'), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params),
    }).then((res) => res.json())
  }
}
  1. 成功后,响应结构包含
    data.txData
ts
// DepositView / WithdrawalView中的典型片段
const calldata = await bridgers.fetchSwapCall(params)
if (calldata.resCode === 100) {
  const txData = calldata.data.txData
  // txData结构大致为:
  // {
  //   to:   "0x...", // 目标桥/路由合约地址
  //   data: "0x...", // ABI编码的调用数据
  //   value:"0x..."  // 可选,十六进制金额
  // }
}
在浏览器中,前端会直接将
txData
交给钱包签名并发送。在本Skill中,你可以在服务器上通过两步完成相同操作:
3.4.1 Step one: obtain
txData
via REST API
3.4.1 第一步:通过REST API获取
txData
Option A: use
curl
directly against Bridgers API
bash
curl -X POST "https://api.bridgers.xyz/api/sswap/swap" \
  -H "Content-Type: application/json" \
  -d '{
    "equipmentNo": "0xYourAddress",
    "sourceType": "H5",
    "userNo": "",
    "sessionUuid": "",
    "orderId": "",
    "sourceFlag": "perpex01",
    "utmSource": "",
    "fromTokenAddress": "0xFromTokenAddress",
    "toTokenAddress":   "0xToTokenAddress",
    "fromAddress": "0xYourAddress",
    "toAddress":   "0xYourAddress",
    "fromTokenChain": "ETH",
    "toTokenChain":   "CELO",
    "fromTokenAmount": "1000000",
    "amountOutMin": "990000",
    "fromCoinCode": "USDT",
    "toCoinCode":   "USDT"
  }'
The important fields in the JSON response are:
json
{
  "resCode": 100,
  "data": {
    "txData": {
      "to": "0xBridgeOrRouterAddress",
      "data": "0xabcdef...",
      "value": "0x0"
    },
    "orderId": "xxx",
    "operation": "deposit" // or "withdrawal"
  }
}
You can save
txData
to a local file, for example:
bash
curl ... > bridgers-tx.json
Option B: reuse
bridgersFetcher
logic in Node.js
If you want to call it directly from a backend script, you can use the same request structure in a standalone Node script (e.g.
scripts/fetch-bridgers-tx.js
):
js
const fetch = require('node-fetch')
async function main() {
  const params = {
    equipmentNo: '0xYourAddress',
    sourceType: 'H5',
    userNo: '',
    sessionUuid: '',
    orderId: '',
    sourceFlag: 'perpex01',
    utmSource: '',
    fromTokenAddress: '0xFromTokenAddress',
    toTokenAddress: '0xToTokenAddress',
    fromAddress: '0xYourAddress',
    toAddress: '0xYourAddress',
    fromTokenChain: 'ETH',
    toTokenChain: 'CELO',
    fromTokenAmount: '1000000',
    amountOutMin: '990000',
    fromCoinCode: 'USDT',
    toCoinCode: 'USDT',
  }

  const res = await fetch('https://api.bridgers.xyz/api/sswap/swap', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  })

  const json = await res.json()
  if (json.resCode !== 100) {
    throw new Error(`bridgers error: ${json.resCode} ${json.resMsg || ''}`)
  }

  const txData = json.data.txData
  console.log('to:', txData.to)
  console.log('data:', txData.data)
  console.log('value:', txData.value)
}

main().catch(console.error)
选项A:直接使用
curl
调用Bridgers API
bash
curl -X POST "https://api.bridgers.xyz/api/sswap/swap" \\
  -H "Content-Type: application/json" \\
  -d '{
    "equipmentNo": "0x你的地址",
    "sourceType": "H5",
    "userNo": "",
    "sessionUuid": "",
    "orderId": "",
    "sourceFlag": "perpex01",
    "utmSource": "",
    "fromTokenAddress": "0x源代币地址",
    "toTokenAddress":   "0x目标代币地址",
    "fromAddress": "0x你的地址",
    "toAddress":   "0x你的地址",
    "fromTokenChain": "ETH",
    "toTokenChain":   "CELO",
    "fromTokenAmount": "1000000",
    "amountOutMin": "990000",
    "fromCoinCode": "USDT",
    "toCoinCode":   "USDT"
  }'
JSON响应中的关键字段:
json
{
  "resCode": 100,
  "data": {
    "txData": {
      "to": "0x桥或路由合约地址",
      "data": "0xabcdef...",
      "value": "0x0"
    },
    "orderId": "xxx",
    "operation": "deposit" // 或 "withdrawal"
  }
}
你可以将
txData
保存到本地文件,例如:
bash
curl ... > bridgers-tx.json
选项B:在Node.js中复用
bridgersFetcher
逻辑
如果你想直接从后端脚本调用,可以在独立Node脚本中使用相同的请求结构(例如
scripts/fetch-bridgers-tx.js
):
js
const fetch = require('node-fetch')
async function main() {
  const params = {
    equipmentNo: '0x你的地址',
    sourceType: 'H5',
    userNo: '',
    sessionUuid: '',
    orderId: '',
    sourceFlag: 'perpex01',
    utmSource: '',
    fromTokenAddress: '0x源代币地址',
    toTokenAddress: '0x目标代币地址',
    fromAddress: '0x你的地址',
    toAddress: '0x你的地址',
    fromTokenChain: 'ETH',
    toTokenChain: 'CELO',
    fromTokenAmount: '1000000',
    amountOutMin: '990000',
    fromCoinCode: 'USDT',
    toCoinCode: 'USDT',
  }

  const res = await fetch('https://api.bridgers.xyz/api/sswap/swap', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  })

  const json = await res.json()
  if (json.resCode !== 100) {
    throw new Error(`bridgers错误: ${json.resCode} ${json.resMsg || ''}`)
  }

  const txData = json.data.txData
  console.log('to:', txData.to)
  console.log('data:', txData.data)
  console.log('value:', txData.value)
}

main().catch(console.error)
3.4.2 Step two: pass
txData
to
omni-bridge-tx.js
3.4.2 第二步:将
txData
传入
omni-bridge-tx.js
After obtaining
txData
, call the TX sending script provided by this Skill:
bash
node scripts/omni-bridge-tx.js \
  --to   "$(jq -r '.data.txData.to'   bridgers-tx.json)" \
  --data "$(jq -r '.data.txData.data' bridgers-tx.json)" \
  --value "0"  # If txData.value is non-zero, put the corresponding ETH/CELO amount here
Notes:
  • txData.value
    is usually a hex string (Wei). The
    --value
    parameter of
    omni-bridge-tx.js
    uses human-readable units and parses them with
    parseEther
    . If you need to match
    txData.value
    exactly, you can:
    • Modify
      omni-bridge-tx.js
      to support hex strings directly; or
    • Convert hex Wei to ETH/CELO in an external script, then pass the result to
      --value
      .
This gives you a fully frontend-independent end-to-end flow:
  1. Use the Bridgers REST API to generate a cross-chain bridge transaction (
    /api/sswap/swap
    txData
    );
  2. Use this repo’s
    omni-bridge-tx.js
    to sign and send the Omni Bridge deposit/withdrawal transaction from the CLI;
  3. Optionally integrate
    bridgers.updateDataAndStatus
    or
    fetchTransData
    APIs on the server to sync order status.
获取
txData
后,调用本Skill提供的TX发送脚本:
bash
node scripts/omni-bridge-tx.js \\
  --to   "$(jq -r '.data.txData.to'   bridgers-tx.json)" \\
  --data "$(jq -r '.data.txData.data' bridgers-tx.json)" \\
  --value "0"  # 如果txData.value非零,在此处填入对应的ETH/CELO金额
注意:
  • txData.value
    通常是十六进制字符串(Wei单位)。
    omni-bridge-tx.js
    --value
    参数使用人类可读单位,并通过
    parseEther
    解析。如果你需要完全匹配
    txData.value
    ,可以:
    • 修改
      omni-bridge-tx.js
      以直接支持十六进制字符串;或
    • 在外部脚本中将十六进制Wei转换为ETH/CELO单位,再传入
      --value
这样你就拥有了完全独立于前端的端到端流程
  1. 使用Bridgers REST API生成跨链桥接交易(
    /api/sswap/swap
    txData
    );
  2. 使用本仓库的
    omni-bridge-tx.js
    从CLI签名并发送Omni Bridge存提交易;
  3. 可选地在服务器上集成
    bridgers.updateDataAndStatus
    fetchTransData
    API以同步订单状态。

3.5 Security and caveats

3.5 安全与注意事项

  • When storing a private key in
    assets/celo.env.local
    , ensure the file is never committed to version control and has restricted read permissions on the server.
  • Before execution, always verify:
    • --to
      address is correct;
    • --data
      comes from a trusted frontend/backend service;
    • --value
      is within an acceptable risk amount.
  • If unsure, test with a very small amount (e.g. 0.001).
  • assets/celo.env.local
    中存储私钥时,确保该文件永远不会提交到版本控制,并在服务器上设置严格的读取权限。
  • 执行前,始终验证:
    • --to
      地址正确;
    • --data
      来自可信的前端/后端服务;
    • --value
      在可接受的风险范围内。
  • 如有疑问,先用极小金额测试(例如0.001)。

3.6 Omni Bridgers related config files (chains & tokens & API)

3.6 Omni Bridgers相关配置文件(链、代币、API)

See references/omni-bridgers.md.
详情请见references/omni-bridgers.md

Trade output example

交易输出示例

After a successful open-position transaction:
=== Transaction submitted ===
createOrder txHash: 0x...
Transaction link: https://celoscan.io/tx/0x...

=== Transaction confirmed ===
status: ✅ success
blockNumber: 61500000
gasUsed: 850000

=== OrderCreated event ===
orderKey: 0x...
orderType: 0
account: 0x...

Note: the order has been created and is waiting for the keeper to execute...
After execution is complete, you can query positions to view the position status
开仓交易成功后:
=== 交易已提交 ===
createOrder txHash: 0x...
交易链接: https://celoscan.io/tx/0x...

=== 交易已确认 ===
status: ✅ 成功
blockNumber: 61500000
gasUsed: 850000

=== OrderCreated事件 ===
orderKey: 0x...
orderType: 0
account: 0x...

注意:订单已创建,等待keeper执行...
执行完成后,可查询持仓以查看状态

Examples

示例

Open BTC long with market order

市价单开BTC多头

json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "initialCollateralToken": "0xd96a1ac57a180a3819633bCE3dC602Bd8972f595",
  "isLong": true,
  "orderType": 0,
  "sizeDeltaUsdHuman": 100,
  "initialCollateralDeltaAmountHuman": 100
}
json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "initialCollateralToken": "0xd96a1ac57a180a3819633bCE3dC602Bd8972f595",
  "isLong": true,
  "orderType": 0,
  "sizeDeltaUsdHuman": 100,
  "initialCollateralDeltaAmountHuman": 100
}

Open BTC long with limit order (executes when price reaches $70,000)

限价单开BTC多头(价格达到70,000美元时执行)

json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "initialCollateralToken": "0xd96a1ac57a180a3819633bCE3dC602Bd8972f595",
  "isLong": true,
  "orderType": 1,
  "sizeDeltaUsdHuman": 100,
  "initialCollateralDeltaAmountHuman": 100,
  "triggerPriceHuman": 70000,
  "acceptablePriceHuman": 70500
}
json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "initialCollateralToken": "0xd96a1ac57a180a3819633bCE3dC602Bd8972f595",
  "isLong": true,
  "orderType": 1,
  "sizeDeltaUsdHuman": 100,
  "initialCollateralDeltaAmountHuman": 100,
  "triggerPriceHuman": 70000,
  "acceptablePriceHuman": 70500
}

Set stop-loss (auto-close BTC when price drops to $65,000)

设置止损(价格跌至65,000美元时自动平仓BTC多头)

json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "isLong": true,
  "orderType": 5,
  "closePercent": 100,
  "triggerPriceHuman": 65000,
  "acceptablePriceHuman": 64500
}
json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "isLong": true,
  "orderType": 5,
  "closePercent": 100,
  "triggerPriceHuman": 65000,
  "acceptablePriceHuman": 64500
}

Set take-profit (auto-close BTC when price rises to $80,000)

设置止盈(价格涨至80,000美元时自动平仓BTC多头)

json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "isLong": true,
  "orderType": 6,
  "closePercent": 100,
  "triggerPriceHuman": 80000,
  "acceptablePriceHuman": 79500
}
json
{
  "market": "0xDbBe49A7165F40C79D00bCD3B456AaE887c3d771",
  "indexToken": "0x57433eD8eC1FAD60b8E1dcFdD1fBD56aBA19C04C",
  "isLong": true,
  "orderType": 6,
  "closePercent": 100,
  "triggerPriceHuman": 80000,
  "acceptablePriceHuman": 79500
}

Trading flow

交易流程

  1. User creates order → call
    createOrder
    to submit the order
  2. Keeper listens → off-chain keeper listens for order events
  3. Keeper executes → provides prices and executes the order
  4. Order completes → position is updated and funds change
  1. 用户创建订单 → 调用
    createOrder
    提交订单
  2. Keeper监听 → 链下keeper监听订单事件
  3. Keeper执行 → 提供价格并执行订单
  4. 订单完成 → 持仓更新,资金变动

Notes

注意事项

  • Ensure the wallet has enough CELO to pay gas and executionFee
  • Ensure sufficient collateral token balance
  • Limit/stop orders may need to wait for keeper execution
  • TWAP orders are executed as multiple transactions
  • 确保钱包有足够的CELO支付gas和executionFee
  • 确保有足够的保证金代币余额
  • 限价/止损单可能需要等待keeper执行
  • TWAP订单会拆分为多笔交易执行

Resource navigation

资源导航

  • Scripts:
    scripts/
    • trade-assistant.js
      - trading assistant (natural language orders)
    • trade-cli.js
      - CLI tool
    • open-position.js
      - open position script
    • close-position.js
      - close position script
    • add-liquidity.js
      - add liquidity
    • remove-liquidity.js
      - remove liquidity
    • query.js
      - query tool
    • update-markets.js
      - update market list
  • Reference docs:
    references/
    • liquidity-deposit-withdrawal.md - add/remove liquidity details
    • setup.md - environment and dependencies
    • createOrder-updateOrder-cancleOrder.md - order contract reference
  • Config:
    assets/
    • addresses.json
      - contract addresses (ExchangeRouter, DepositVault, WithdrawalVault, WNT)
    • markets.json
      - market config
    • celo-tokens.json
      - token decimals
    • celo.env.local
      - environment variables (RPC, private key)
    • abis/
      - contract ABIs
    • orders/
      - order and liquidity config directory
  • 脚本
    scripts/
    • trade-assistant.js
      - 交易助手(自然语言指令)
    • trade-cli.js
      - CLI工具
    • open-position.js
      - 开仓脚本
    • close-position.js
      - 平仓脚本
    • add-liquidity.js
      - 添加流动性
    • remove-liquidity.js
      - 移除流动性
    • query.js
      - 查询工具
    • update-markets.js
      - 更新市场列表
  • 参考文档
    references/
    • liquidity-deposit-withdrawal.md - 添加/移除流动性详情
    • setup.md - 环境与依赖配置
    • createOrder-updateOrder-cancleOrder.md - 订单合约参考
  • 配置文件
    assets/
    • addresses.json
      - 合约地址(ExchangeRouter、DepositVault、WithdrawalVault、WNT)
    • markets.json
      - 市场配置
    • celo-tokens.json
      - 代币小数位数
    • celo.env.local
      - 环境变量(RPC、私钥)
    • abis/
      - 合约ABI
    • orders/
      - 订单与流动性配置目录

Trading assistant (trade-assistant.js)

交易助手(trade-assistant.js)

The trading assistant is the UPDOWN Skill’s intelligent order-placement tool. It supports natural language parsing to simplify trading.
交易助手是UPDOWN Skill的智能下单工具,支持自然语言解析以简化交易操作。

Usage

使用方法

bash
node scripts/trade-assistant.js "your trading instruction"
bash
node scripts/trade-assistant.js "你的交易指令"

Supported command formats

支持的命令格式

Open-position orders

开仓订单

Command exampleDescription
Create a BTC/USDT long market order with 10 USDT margin, 2x
Market long BTC
Market short ETH/USDT with 5 USDT margin
Market short ETH
Open BTC long with limit, trigger 65000, 10 USDT margin
Limit long
Open ETH short with limit, trigger 3500, 5 USDT margin
Limit short
命令示例描述
Create a BTC/USDT long market order with 10 USDT margin, 2x
市价单开BTC多头
Market short ETH/USDT with 5 USDT margin
市价单开ETH空头
Open BTC long with limit, trigger 65000, 10 USDT margin
限价单开BTC多头
Open ETH short with limit, trigger 3500, 5 USDT margin
限价单开ETH空头

Close-position orders

平仓订单

Command exampleDescription
Close BTC/USDT long
Market close
Market close ETH short
Market close
Close 50% of BTC long
Partial close
命令示例描述
Close BTC/USDT long
市价单平仓
Market close ETH short
市价单平仓
Close 50% of BTC long
部分平仓

Stop-loss / take-profit

止损/止盈

Command exampleDescription
Set stop-loss for BTC long, trigger 60000
Stop-loss
Set take-profit for ETH short, trigger 4000
Take-profit
命令示例描述
Set stop-loss for BTC long, trigger 60000
设置止损
Set take-profit for ETH short, trigger 4000
设置止盈

Query

查询

Command exampleDescription
Show my positions
Query all positions
Check my balance
Query wallet balance
命令示例描述
Show my positions
查询所有持仓
Check my balance
查询钱包余额

Parameter parsing

参数解析

The trading assistant automatically parses the following parameters:
  • Market pair: BTC, ETH, CELO, EURm, JPYm, NGNm, AUDm, GBPm
  • Order type: market / limit
  • Direction: long / short (open long/open short/long/short)
  • Margin: any amount (denominated in USDT/USD/U)
  • Leverage: default 1x, can be specified (e.g. 2x, 5x, 10x)
  • Trigger price: required for limit and stop orders
交易助手自动解析以下参数:
  • 交易对:BTC、ETH、CELO、EURm、JPYm、NGNm、AUDm、GBPm
  • 订单类型:市价单/限价单
  • 方向:多头/空头(开多/开空/多/空)
  • 保证金:任意金额(以USDT/USD/U为单位)
  • 杠杆:默认1倍,可指定(如2x、5x、10x)
  • 触发价格:限价单和止损单必填

Workflow

工作流程

  1. User inputs a natural-language instruction
  2. Assistant parses and validates parameters
  3. Automatically generates an order config file
  4. Prints the execution command
  5. User copies and runs the command to execute the trade
  1. 用户输入自然语言指令
  2. 助手解析并验证参数
  3. 自动生成订单配置文件
  4. 打印执行命令
  5. 用户复制并运行命令以执行交易

Sample output

示例输出

=== User input ===
Create a BTC/USDT long market order with 10 USDT margin, 2x leverage

=== Parsed result ===
{
  "action": "open",
  "market": "BTC",
  "orderType": "market",
  "isLong": true,
  "collateralUsd": 10,
  "leverage": 2
}

=== Generated order config ===
{
  "market": "0x...",
  "indexToken": "0x...",
  "isLong": true,
  "orderType": 0,
  "sizeDeltaUsdHuman": 20,
  "initialCollateralDeltaAmountHuman": 10,
  ...
}

✅ Order config saved: assets/orders/order-open-btc-long.json

Run:
  node scripts/open-position.js assets/orders/order-open-btc-long.json
=== 用户输入 ===
Create a BTC/USDT long market order with 10 USDT margin, 2x leverage

=== 解析结果 ===
{
  "action": "open",
  "market": "BTC",
  "orderType": "market",
  "isLong": true,
  "collateralUsd": 10,
  "leverage": 2
}

=== 生成的订单配置 ===
{
  "market": "ox...",
  "indexToken": "0x...",
  "isLong": true,
  "orderType": 0,
  "sizeDeltaUsdHuman": 20,
  "initialCollateralDeltaAmountHuman": 10,
  ...
}

✅ 订单配置已保存: assets/orders/order-open-btc-long.json

运行:
  node scripts/open-position.js assets/orders/order-open-btc-long.json

References

参考