> For the complete documentation index, see [llms.txt](https://docs.nexus.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nexus.xyz/api-reference/zh-cn/guides/get-started.md).

# 入门

从零开始到在 Nexus Exchange 上开出一个仓位的八步演练。您将用钱包登录、创建 HMAC API 密钥、对请求签名、为账户充值、浏览市场、下单、撤单或修改订单，并监控仓位。

每一步都以五种客户端展示：cURL、Rust、Python、TypeScript 和 Exchange CLI。每一步选择一个标签页即可。

本页最初是交易所应用曾在 `/api-docs` 提供的交互式 API 文档中的 **Getting Started** 标签页。该路由已无法访问，因此现在由本页作为指南。

## 开始之前

* **您需要一个以太坊钱包**来对登录消息签名。开始时不需要其他任何东西。
* **基础 URL**。下面的示例使用公共测试网主机。不带前缀的路径位于 `/v1` 传输基础路径 `https://api.testnet.nexus.xyz/v1` 之下，`/api/v1` 路径则位于主机根地址之下，因此完整 URL 形如 `https://api.testnet.nexus.xyz/api/v1/…`。在本地运行时，基础 URL 为 `http://localhost:9090`。请替换为您所调用部署的基础 URL。在存在带版本路由的地方，路径以 `/api/v1` 前缀展示。`/v1` 基础 URL 上不带前缀的形式可访问同一操作，也是官方客户端正在迁移到的形式。关于契约声明的其他基础 URL，以及 `/api/v1` 路径上的 `servers` 覆盖如何解析，请参见[基础 URL](/api-reference/zh-cn/readme.md#base-urls)。
* **身份验证**。有两种方案：仅用于创建和管理 API 密钥的**会话令牌**（Bearer），以及用于其他一切（包括所有交易）的 **HMAC-SHA256** API 密钥签名。
* **两个部署**。交易所应用基于同一代码库部署了两次。**测试网**部署已上线，通过合成额度水龙头为账户注资。**主网**真实资金部署将通过把 USDX 从以太坊主网跨链转入来注资。它尚未上线：其主机 `api.nexus.xyz` 目前无法解析。下面的第4步在两者之间有所不同，两种情况都有说明。
* **占位符**。`0xSIGNATURE_HEX`、`nx_7f3a1b...`、`sess_abc123...` 和 `0x<wallet-private-key>` 等值都是占位符。请替换为您自己的值；切勿将任何密钥提交到代码仓库。

### 语言覆盖情况

cURL 是基线，每一步都有 cURL 示例。四种 SDK/CLI 客户端尚未覆盖每一步。当某个客户端在某一步没有示例时，标签页会注明，您可以改为参照 cURL 示例。交互式文档的做法相同，会附注说明并回退到 cURL。

### 机器可读的入口

代理无需阅读本页，即可从以下入口开始：

* `llms.txt`，位于 <https://exchange.nexus.xyz/llms.txt>
* `openapi.json`，即 OpenAPI 契约，位于 `https://api.testnet.nexus.xyz/openapi.json`
* `/metadata`，交易所应用的机器可读元数据路由
* **MCP 服务器**，已发布到 npm，因此只需一行即可添加。它通过 stdio 在本地运行，因此您的 API 密钥保留在您的机器上：

```bash
claude mcp add nexus-exchange -- npx -y @nexus-xyz/exchange-mcp
```

其公开的市场数据和演示工具无需凭证，因此在您拥有密钥之前该命令就已可用。托管的 MCP 端点已在计划中；其 DNS 尚未生效，因此目前没有可添加的远程 URL。

OpenAPI 规范和变更日志在 [nexus-xyz/nexus-exchange-api](https://github.com/nexus-xyz/nexus-exchange-api) 中进行版本管理，版本发布记录在 [GitHub Releases](https://github.com/nexus-xyz/nexus-exchange-api/releases)。

***

## 身份验证

第1–3步带您从钱包走到一个已签名的请求。

## 1. 登录

`POST /auth/login`。无需身份验证。

使用 EIP-191 个人签名进行身份验证。要签名的消息始终是固定字符串“Sign in to Nexus Exchange”。服务器会从签名中恢复出您的钱包地址。

**说明**

* 会话令牌在24小时后过期。
* 您只在创建和管理 API 密钥时需要会话，交易时不需要。

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST 'https://api.testnet.nexus.xyz/v1/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{
    "message": "Sign in to Nexus Exchange",
    "signature": "0xSIGNATURE_HEX"
  }'
```

{% endtab %}

{% tab title="Rust" %}

```rust
use nexus_exchange::{Client, Config, EthSigner, Network};

// EIP-191 personal_sign of the fixed login message. The signer
// holds your key only to sign — nothing is written to disk.
let signer = EthSigner::from_hex("0x<wallet-private-key>")?;
let client = Client::new(Config::new(Network::Testnet));

let session = client.sign_in(&signer).await?;
println!("signed in as {}", session.address);
// session.token is a SecretString — hand it to
// Config::session_token to authenticate the /keys endpoints.
```

{% endtab %}

{% tab title="Python" %}

```python
from nexus_exchange import Client, EthSigner

signer = EthSigner.from_hex("0x<wallet-private-key>")

with Client() as client:
    session = client.sign_in(signer)  # EIP-191 personal_sign
    print(session.address, session.token)
```

{% endtab %}

{% tab title="TypeScript" %}
TypeScript 暂不支持。请使用 cURL 示例。
{% endtab %}

{% tab title="CLI" %}

```bash
export NEXUS_PRIVATE_KEY=0x<your-evm-key>
nexus auth login   # signs EIP-191, stores the session token (mode 0600)
```

{% endtab %}
{% endtabs %}

**请求体**

```json
{
  "message": "Sign in to Nexus Exchange",
  "signature": "0xSIGNATURE_HEX"
}
```

**响应**

```json
{
  "token": "sess_abc123...",
  "address": "0xYOUR_WALLET_ADDRESS"
}
```

## 2. 创建 API 密钥

`POST /keys`。**需要会话令牌。**

使用会话令牌创建一个 HMAC 密钥对。secret 只显示一次，请立即保存。

**说明**

* 此响应之后，您将无法再取回 secret。
* 密钥继承您账户的等级。`X-RateLimit-*` 响应头会报告各等级的速率限制。

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST 'https://api.testnet.nexus.xyz/v1/keys' \
  -H 'Authorization: Bearer sess_abc123...' \
  -H 'Content-Type: application/json' \
  -d '{"label": "my-bot"}'
```

{% endtab %}

{% tab title="Rust" %}

```rust
use nexus_exchange::{Client, Config, Network};

// /keys endpoints authenticate with the session token from step 1.
let client =
    Client::new(Config::new(Network::Testnet).session_token("sess_..."));

let key = client.create_api_key().await?;
// key.secret is returned once — persist it immediately.
println!("key_id: {}", key.key_id);
```

{% endtab %}

{% tab title="Python" %}
Python 暂不支持。请使用 cURL 示例。
{% endtab %}

{% tab title="TypeScript" %}
TypeScript 暂不支持。请使用 cURL 示例。
{% endtab %}

{% tab title="CLI" %}

```bash
nexus keys create   # secret is shown ONCE — store it now
```

{% endtab %}
{% endtabs %}

**请求体**

```json
{
  "label": "my-bot"
}
```

**响应**

```json
{
  "key_id": "nx_7f3a1b...",
  "secret": "e4d2c8f1...long_hex..."
}
```

## 3. 对请求签名

`GET /markets`。**需要 HMAC API 密钥。**

每个需要身份验证的请求都需要三个请求头。构造一个规范字符串，用您的 secret 对其做 HMAC-SHA256，然后附上结果。

**必需的请求头**

| 请求头           | 必填 | 说明                       |
| ------------- | -- | ------------------------ |
| `X-API-Key`   | 是  | 您的密钥 ID（`nx_...`）        |
| `X-Timestamp` | 是  | 当前时间，自 epoch 起的毫秒数       |
| `X-Signature` | 是  | 规范字符串的 HMAC-SHA256 十六进制值 |

**说明**

* 规范格式：`timestamp\nMETHOD\npath\nquery\nsha256(body)`
* `path` 是**契约中写明的**路径。路由带有 `/api/v1` 前缀时请包含该前缀，但**不要**包含 `/v1` 传输前缀，它会在验证签名之前被去除。调用 `…/v1/markets` 意味着签名 `/markets`；调用 `…/api/v1/tickers` 意味着签名 `/api/v1/tickers`。
* 时间戳必须与服务器时间相差在 ±30秒以内（自 epoch 起的毫秒数）。
* 对于没有请求体的 GET 请求，对空字符串做哈希。

{% tabs %}
{% tab title="cURL" %}

```bash
# Build the HMAC signature
TIMESTAMP=$(python3 -c 'import time; print(int(time.time()*1000))')
BODY_HASH=$(echo -n "" | shasum -a 256 | cut -d' ' -f1)
CANONICAL="$TIMESTAMP\nGET\n/markets\n\n$BODY_HASH"
SIGNATURE=$(echo -ne "$CANONICAL" | \
  openssl dgst -sha256 -mac HMAC -macopt "hexkey:$NEXUS_API_SECRET" -hex | awk '{print $NF}')

curl 'https://api.testnet.nexus.xyz/v1/markets' \
  -H "X-API-Key: nx_7f3a1b..." \
  -H "X-Timestamp: $TIMESTAMP" \
  -H "X-Signature: $SIGNATURE"
```

{% endtab %}

{% tab title="Rust" %}

```rust
use nexus_exchange::{Client, Config, Network};

// The SDK builds the canonical string and HMAC-signs every request.
let client = Client::new(Config::new(Network::Testnet).api_key(
    std::env::var("NEXUS_API_KEY")?,
    std::env::var("NEXUS_API_SECRET")?,
));

let markets = client.fetch_markets().await?;
println!("{} markets", markets.len());
```

{% endtab %}

{% tab title="Python" %}

```python
import os
from nexus_exchange import Client

# The SDK builds the canonical string and HMAC-signs every request.
client = Client(
    api_key=os.environ["NEXUS_API_KEY"],
    api_secret=os.environ["NEXUS_API_SECRET"],
)

print(len(client.fetch_markets()), "markets")
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { Client, Network } from "@nexus-xyz/exchange-ts";

// The SDK builds the canonical string and HMAC-signs every request.
const client = new Client({
  network: Network.Testnet,
  apiKey: process.env.NEXUS_API_KEY,
  apiSecret: process.env.NEXUS_API_SECRET,
});

console.log((await client.fetchMarketSummaries()).length, "markets");
```

{% endtab %}

{% tab title="CLI" %}

```bash
nexus setup            # interactive; stores credentials (mode 0600)
# ...or per shell:
export NEXUS_API_KEY=nx_...
export NEXUS_API_SECRET=...
nexus balance          # every request is HMAC-signed for you
```

{% endtab %}
{% endtabs %}

**响应**

```json
[
  { "id": "BTC-USDX-PERP", "base": "BTC", "quote": "USDX", "status": "active" },
  { "id": "ETH-USDX-PERP", "base": "ETH", "quote": "USDX", "status": "active" }
]
```

{% hint style="info" %}
在交互式文档中，这一步有一个针对 `GET /markets` 的实时“Try it”按钮。
{% endhint %}

***

## 交易

第4–8步为账户注资、建立仓位并对其进行监控。

## 4. 为账户充值

`POST /account/credit`。**需要 HMAC API 密钥**。仅限测试网。

领取合成 USDX 额度以开始交易。每个 API 密钥每天最多可领取500 USDX。省略 `"amount"` 即可领取当日剩余的全部额度。

{% hint style="warning" %}
额度水龙头仅存在于**测试网**。在主网真实资金部署上，此端点返回 `403`，只能通过跨链桥注资。请参见下文的主网情况。
{% endhint %}

**说明**

* 金额是十进制字符串，与 API 中的所有货币值一样。
* 当日额度用完后返回429。额度在下一个 UTC 日重置。

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST 'https://api.testnet.nexus.xyz/api/v1/account/credit' \
  -H 'X-API-Key: nx_7f3a1b...' \
  -H 'X-Timestamp: UNIX_MS' \
  -H 'X-Signature: HMAC_HEX' \
  -H 'Content-Type: application/json' \
  -d '{"amount": "500"}'
```

{% endtab %}

{% tab title="Rust" %}

```rust
use nexus_exchange::types::Decimal;

// `client` is the HMAC-credentialed client from step 3.
// Pass None to claim the full remaining daily allowance.
let credit = client
    .claim_credit(Some("500".parse::<Decimal>()?))
    .await?;
println!("credited {} (today: {})", credit.amount, credit.credited_today);
```

{% endtab %}

{% tab title="Python" %}

```python
# `client` is the HMAC-credentialed client from step 3.
credit = client.claim_credit("500")  # omit the amount for the daily max
print(credit.amount, credit.credited_today)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
// `client` is the HMAC-credentialed client from step 3.
const credit = await client.claimCredit({ amount: "500" }); // {} = daily max
console.log(credit.amount, credit.credited_today);
```

{% endtab %}

{% tab title="CLI" %}

```bash
nexus account credit --amount 500   # omit --amount for the daily max
```

{% endtab %}
{% endtabs %}

**请求体**

```json
{
  "amount": "500"
}
```

**响应**

```json
{
  "amount": "500",
  "credited_today": "500",
  "daily_limit": "500"
}
```

### 主网上的第4步：使用真实抵押品注资

在主网真实资金部署上（已计划，尚未上线），真实充值将取代第4步。测试网的试玩部署有合成额度水龙头，主网真实资金部署则没有。您不必自己为此做分支判断。有一个端点会回答“该部署如何接受抵押品”，响应中会给出注资模式。

[`GET /account/deposit-target`](https://docs.nexus.xyz/api-reference/account/fetch-deposit-address)。**需要 HMAC API 密钥。**

主网上没有合成额度。向交易所询问应将抵押品发送到哪里，发送后轮询，直到余额体现这笔资金。

**不要硬编码注资方式**。响应是一个以 `mode` 区分的联合类型。您得到的模式是部署的属性，而不是您请求的属性，也没有任何参数可以选择模式。配置了真实充值合约的部署返回 `onchain`。其他所有部署返回 `testnet-faucet`，并指向其合成额度端点。根据 `mode` 做分支，同一段客户端代码即可在任一部署上完成注资。

**说明**

* 仅用于发现。`GET /account/deposit-target` 不会转移任何资金，也不会创建充值。按返回的指引操作是一个单独、明确的步骤。
* 在 `onchain` 模式下，`onchain.address` 是充值合约地址，`onchain.chain` 是其所在的链。两者都是部署配置，请读取它们，不要硬编码。
* **`403 EARLY_ACCESS_REQUIRED` 表示您的账户目前还不能在此注资**。当部署将注资限定于抢先体验参与者时，它会拒绝未加入的账户，并且该拒绝**在账户加入之前是永久性的。请勿重试**。这一限制有意与 `POST /account/credit` 和 `POST /faucet` 保持一致，这样无法注资的账户就不会被告知如何注资。
* 该端点绝不会为填充 `onchain` 结构而捏造地址。如果配置为链上充值的部署地址格式错误，它会返回 `503 DEPOSIT_TARGET_MISCONFIGURED`，而不是公布该地址，因为向错误地址充值会导致资金销毁。这是运营方的配置错误，而不是暂时性故障，重试无法解决。
* `min_amount` 是**建议值，不强制执行**。它是让首笔交易可行的下限；较小的链上充值不会被拒绝。
* `confirm` 在两种模式下完全相同，因此在任一部署上都可用。交易前请轮询 `GET /account`，直到 `balance` 体现这笔资金。
* `POST /account/credit` 是一个**仅限测试网**的水龙头，入账的 USDX 是合成的。契约自身的指引是：不要构建假定该操作在每个网络上都存在的注资流程。主网完全没有合成额度。
* [`GET /api/v1/bridge/assets`](https://docs.nexus.xyz/api-reference/bridge/fetch-bridge-assets) 列出支持的链，以及每条链上可充值的资产及其精度、最小金额和所需确认数。
* 使用 [`GET /api/v1/bridge/deposits`](https://docs.nexus.xyz/api-reference/bridge/fetch-bridge-deposits) 跟踪跨链充值，或通过 [`GET /api/v1/bridge/deposits/{id}`](https://docs.nexus.xyz/api-reference/bridge/fetch-bridge-deposit) 按其 `{tx_hash}:{log_index}` id 跟踪单笔充值。该读取模型由 watcher 写入，这些端点只负责读取。
* 链上转账不可撤销。请只从您控制的钱包发送指引中指定的资产。
* 完整流程是：在此注资，交易（后续步骤），然后提现。`GET /withdrawals` 列出您的记录，[`POST /withdrawals`](https://docs.nexus.xyz/api-reference/account/withdraw) 发起一笔提现。它通过以钱包自身密钥签名的 EIP-712 `WithdrawIntent` 进行身份验证，**而不是** API 密钥，因此不会复用上面的 HMAC 凭证。跨链桥提现是一个单独的操作，即 [`POST /api/v1/bridge/withdrawals`](https://docs.nexus.xyz/api-reference/bridge/create-bridge-withdrawal)。

{% tabs %}
{% tab title="cURL" %}

```bash
# 1) Ask the venue how this deployment accepts collateral.
#    Branch on .mode — "onchain" or "testnet-faucet". Do not assume either shape.
curl 'https://api.testnet.nexus.xyz/v1/account/deposit-target' \
  -H 'X-API-Key: nx_7f3a1b...' \
  -H 'X-Timestamp: UNIX_MS' \
  -H 'X-Signature: HMAC_HEX'

# onchain mode answers with the deposit contract to send to:
#   { "mode": "onchain", "account": "0x742d...", "asset": "USDX", "min_amount": "10",
#     "onchain": { "chain": "nexus-mainnet", "asset": "USDX",
#                  "address": "0x1f98...", "min_amount": "10" },
#     "confirm": { "method": "GET", "path": "/account", "poll_field": "balance" } }

# 2) Send the named asset to onchain.address on onchain.chain from your own wallet.

# 3) Confirm with the instruction's own confirm block — poll until balance moves.
curl 'https://api.testnet.nexus.xyz/v1/account' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'

# Optional: the cross-chain deposit record, once the watcher has seen it.
curl 'https://api.testnet.nexus.xyz/api/v1/bridge/deposits' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'
```

{% endtab %}

{% tab title="Rust" %}
Rust 暂不支持。请使用 cURL 示例。跨链桥步骤的高层客户端封装仍在开发中。
{% endtab %}

{% tab title="Python" %}
Python 暂不支持。请使用 cURL 示例。
{% endtab %}

{% tab title="TypeScript" %}
TypeScript 暂不支持。请使用 cURL 示例。
{% endtab %}

{% tab title="CLI" %}
CLI 暂不支持。请使用 cURL 示例。
{% endtab %}
{% endtabs %}

**请求体**

无。`GET /account/deposit-target` 不接受参数，也没有请求体。

**响应**（`onchain` 模式，契约中 `DepositTarget` 的示例）

```json
{
  "mode": "onchain",
  "account": "0x742d35cc6634c0532925a3b844bc9e7595f0beb0",
  "asset": "USDX",
  "min_amount": "10",
  "onchain": {
    "chain": "nexus-mainnet",
    "asset": "USDX",
    "address": "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984",
    "token_address": "0xf92b58d2225a73b45ded3bc2290ac1a2077c1cf2",
    "min_amount": "10",
    "instructions": "Approve USDX spend for the deposit contract, then call depositTo(token, amount, beneficiary) with token set to `onchain.token_address`, amount in USDX base units, and beneficiary set to `account`. Only USDX is accepted; other tokens are rejected on-chain. Funds credit to the exchange account within 30s of on-chain confirmation."
  },
  "confirm": {
    "method": "GET",
    "path": "/account",
    "poll_field": "balance",
    "note": "Poll until balance reflects the deposit (SPEC target: within 30s of on-chain confirmation)."
  }
}
```

## 5. 浏览市场

`GET /markets/{market_id}/ticker`。**需要 HMAC API 密钥。**

列出可用的永续合约市场并查看当前价格。

{% tabs %}
{% tab title="cURL" %}

```bash
# List markets (4 trading on testnet today; 32 configured)
curl 'https://api.testnet.nexus.xyz/v1/markets' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'

# Get a single ticker
curl 'https://api.testnet.nexus.xyz/api/v1/markets/BTC-USDX-PERP/ticker' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'
```

{% endtab %}

{% tab title="Rust" %}

```rust
let markets = client.fetch_markets().await?;
println!("{} markets", markets.len());

let ticker = client.fetch_ticker("BTC-USDX-PERP").await?;
println!(
    "{}: last={:?} mark={:?}",
    ticker.symbol, ticker.last, ticker.mark_price
);
```

{% endtab %}

{% tab title="Python" %}

```python
for market in client.fetch_markets():
    print(market.market_id)

ticker = client.fetch_ticker("BTC-USDX-PERP")
print(ticker.last, ticker.mark_price)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
for (const market of await client.fetchMarketSummaries()) {
  console.log(market.market_id);
}

const ticker = await client.fetchTicker("BTC-USDX-PERP");
console.log(ticker.last, ticker.markPrice);
```

{% endtab %}

{% tab title="CLI" %}

```bash
nexus markets                 # tradable markets and their rules
nexus ticker BTC-USDX-PERP    # ticker for one market
```

{% endtab %}
{% endtabs %}

**响应**

```json
{
  "symbol": "BTC-USDX-PERP",
  "last": 84250.5,
  "bid": 84249.0,
  "ask": 84252.0,
  "volume": 1523.4,
  "change": 2.1
}
```

{% hint style="info" %}
这一步的源码注释写的是 `# List markets (all 32)`。这是已配置的市场数量，而不是正在交易的数量。测试网目前正在交易**4**个市场，因此上面的注释已作更正。当前的市场集合请参见 [Exchange Testnet](https://docs.nexus.xyz/exchange/exchange-testnet)。

主网部署的市场集合有所不同。主网上线时有3个市场（`BTC-USDX-PERP`、`ETH-USDX-PERP`、`SOL-USDX-PERP`），之后扩展到32个以上。那里的 cURL 注释写的是 `# List markets (3 at internal launch: BTC, ETH, SOL — expanding to 32+)`。

在交互式文档中，这一步有一个针对 `GET /markets/BTC-USDX-PERP/ticker` 的实时“Try it”按钮。
{% endhint %}

### 价格和数量精度

提交前请先取整。每个市场都声明了三条量化规则，不符合规则的订单会被交易所拒绝，而不是替您取整。

| `GET /markets` 上的字段 | 规则            |
| ------------------- | ------------- |
| `tick_size`         | 限价必须是它的整数倍。   |
| `lot_size`          | 订单数量必须是它的整数倍。 |
| `min_order_size`    | 订单数量不得低于此值。   |

对于 `BTC-USDX-PERP`，这三个值分别为 `0.5`、`0.001` 和 `0.001`。因此价格 `83000.25` 无效，因为它不是 `0.5` 的整数倍；数量 `0.0005` 也无效，因为它同时低于最小交易单位和最小下单数量。`83000.00` 和 `0.001` 是有效的。

请按市场读取这些值，而不要硬编码。它们因市场而异（`ETH-USDX-PERP` 为 `0.10` 和 `0.01`，`SOL-USDX-PERP` 为 `0.01` 和 `0.1`），并且属于上线时的配置。[市场规格（英文）](https://docs.nexus.xyz/exchange/trading/perpetuals/market-specifications) 发布了每个已上线市场的当前表格。

**向安全的一侧取整**。将买入价格按最小价格变动*向下*取整，卖出价格*向上*取整，数量则按最小交易单位向下取整。将数量向上取整可能使订单超出您的权益所能支撑的保证金，订单随后会因其他原因被拒绝。

## 6. 下单

`POST /orders`。**需要 HMAC API 密钥。**

提交限价单或市价单。响应会确认订单已被接受。

**说明**

* 使用 `"type": "market"` 以当前最优价格立即成交。
* 可在一次 `POST /orders/batch` 调用中批量提交多个订单。交易所按顺序处理它们，结果保持请求中的顺序。

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST 'https://api.testnet.nexus.xyz/api/v1/orders' \
  -H 'X-API-Key: nx_7f3a1b...' \
  -H 'X-Timestamp: UNIX_MS' \
  -H 'X-Signature: HMAC_HEX' \
  -H 'Content-Type: application/json' \
  -d '{
    "market_id": "BTC-USDX-PERP",
    "side": "buy",
    "type": "limit",
    "size": 0.01,
    "price": 83000.00
  }'
```

{% endtab %}

{% tab title="Rust" %}

```rust
use nexus_exchange::types::{OrderRequest, Side, TimeInForce};

let order = OrderRequest::limit(
    "BTC-USDX-PERP",
    Side::Buy,
    "83000".parse()?,
    "0.01".parse()?,
    TimeInForce::Gtc,
);
let placed = client.create_order(&order).await?;
println!("placed {} — {}", placed.order.id, placed.order.status);
```

{% endtab %}

{% tab title="Python" %}

```python
from decimal import Decimal
from nexus_exchange import OrderRequest

order = OrderRequest.limit(
    "BTC-USDX-PERP", "Buy", Decimal("83000"), Decimal("0.01")
)
placed = client.create_order(order)
print(placed.order.id, placed.order.status)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const { order } = await client.placeOrder({
  market_id: "BTC-USDX-PERP",
  side: "Buy",
  order_type: "Limit",
  price: "83000",
  quantity: "0.01",
  time_in_force: "GTC",
});
console.log(order.id, order.status);
```

{% endtab %}

{% tab title="CLI" %}

```bash
# Prompts for confirmation; pass --yes to skip
nexus order place --market BTC-USDX-PERP --side buy --type limit \
  --price 83000 --quantity 0.01 --tif GTC
```

{% endtab %}
{% endtabs %}

**请求体**

```json
{
  "market_id": "BTC-USDX-PERP",
  "side": "buy",
  "type": "limit",
  "size": 0.01,
  "price": 83000.0
}
```

**响应**

```json
{
  "id": "ord_f82a...",
  "status": "open",
  "filled": 0.0,
  "market_id": "BTC-USDX-PERP",
  "side": "buy",
  "type": "limit",
  "size": 0.01,
  "price": 83000.0
}
```

## 7. 撤单或修改

`DELETE /orders/{order_id}` · `DELETE /orders` · `PATCH /orders/{order_id}`。**需要 HMAC API 密钥。**

这是三个独立的操作：

| 操作                          | 效果                                     |
| --------------------------- | -------------------------------------- |
| `DELETE /orders/{order_id}` | 撤销一个挂单。                                |
| `DELETE /orders`            | 撤销所有挂单，或通过 `?market_id=` 撤销某一市场上的所有订单。 |
| `PATCH /orders/{order_id}`  | **原子性撤单并替换**：在一次调用中修改价格和/或数量。          |

**说明**

* **修改订单会返回一个带有新 id 的替换订单**。`200` 响应体是新订单；您修改的那个 id 已不复存在。请跟踪返回给您的 id，而不是您发送的 id。
* 修改订单时必须至少提供 `price` 或 `size` 之一。
* 修改订单的交易前保证金检查**不计入被替换订单仍占用的保证金**，因此按替换订单新增的保证金来计算。以相同数量重新定价不需要额外保证金，缩小数量则会释放保证金，而不是需要更多保证金。
* 强平订单不可修改。
* 修改订单时返回 `409` 表示订单在您读取之后发生了变化。它在您读取和写入之间已成交或已被撤销。
* **撤单与提交订单使用各自独立的速率限制额度**。用完订单额度绝不会阻止撤单。只有带 `bucket: cancel` 的 `429` 才表示您的撤单通道本身已饱和。参见[速率限制](/api-reference/zh-cn/guides/rate-limits.md)。

{% tabs %}
{% tab title="cURL" %}

```bash
# Amend a resting order's price — note the response carries a NEW order id
curl -X PATCH 'https://api.testnet.nexus.xyz/api/v1/orders/ORDER_ID?market_id=BTC-USDX-PERP' \
  -H 'X-API-Key: nx_7f3a1b...' \
  -H 'X-Timestamp: UNIX_MS' \
  -H 'X-Signature: HMAC_HEX' \
  -H 'Content-Type: application/json' \
  -d '{"price": 82500.00}'

# Cancel everything on one market
curl -X DELETE 'https://api.testnet.nexus.xyz/api/v1/orders?market_id=BTC-USDX-PERP' \
  -H 'X-API-Key: nx_7f3a1b...' -H 'X-Timestamp: UNIX_MS' -H 'X-Signature: HMAC_HEX'
```

{% endtab %}
{% endtabs %}

## 8. 监控仓位

`GET /positions`。**需要 HMAC API 密钥。**

查看持有的仓位、未实现盈亏和账户健康状况。

{% tabs %}
{% tab title="cURL" %}

```bash
# Open positions
curl 'https://api.testnet.nexus.xyz/api/v1/positions' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'

# Account summary
curl 'https://api.testnet.nexus.xyz/api/v1/account' \
  -H 'X-API-Key: ...' -H 'X-Timestamp: ...' -H 'X-Signature: ...'
```

{% endtab %}

{% tab title="Rust" %}

```rust
let account = client.fetch_balance().await?;
println!("equity {}", account.equity);

for p in client.fetch_positions().await? {
    println!(
        "{} {} size {} | uPnL {}",
        p.market_id, p.side, p.size, p.unrealized_pnl
    );
}
```

{% endtab %}

{% tab title="Python" %}

```python
account = client.fetch_balance()
print(account.equity)

for p in client.fetch_positions():
    print(p.market_id, p.side, p.size, p.unrealized_pnl)
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
const account = await client.getAccount();
console.log(account.equity);

for (const p of await client.getPositions()) {
  console.log(p.market_id, p.side, p.size, p.unrealized_pnl);
}
```

{% endtab %}

{% tab title="CLI" %}

```bash
nexus positions   # open positions with PnL
nexus balance     # balance, collateral, equity, margin
```

{% endtab %}
{% endtabs %}

**响应**

```json
{
  "balance": 10000.0,
  "equity": 10012.5,
  "margin_used": 83.0,
  "margin_ratio": 0.008,
  "positions": 1
}
```

{% hint style="info" %}
在交互式文档中，这一步有一个针对 `GET /account` 的实时“Try it”按钮。
{% endhint %}

***

## WebSocket

入门时使用轮询即可。实时订单簿或成交推送应使用数据流。

有两个 socket，它们不能互换：

* [`GET /stream`](https://docs.nexus.xyz/api-reference/websocket/connect-stream) 提供公开的市场数据，**无需令牌**。发送一条 `{"subscribe": [...]}` 消息即可。订单簿帧是完整的前20档快照，因此重连后无需重放任何内容。
* [`GET /ws`](https://docs.nexus.xyz/api-reference/websocket/connect-web-socket) 需要来自 [`POST /ws/token`](https://docs.nexus.xyz/api-reference/websocket/create-ws-token) 的令牌，除公开频道外还承载各账户的频道，带有 `op` 封装结构、序列号和重连游标。

每个页面都有频道列表、消息结构和重连规则。

在基于它进行开发之前：

* **断线撤单需要主动开启，按账户设置，默认关闭**。使用 `PUT /account/cancel-on-disconnect` 设置，使用对应的 `GET` 读取。它是一个失联保护开关。当您最后一个已认证的连接断开且未在宽限期内重连时，交易所会撤销您的挂单。没有它，断开的连接会让您的订单继续有效。
* **检查 `active`，而不仅仅是 `enabled`**。`enabled` 是您自己的开启设置。`active` 还要求交易所端的功能开关已打开，因此 `active` 才能告诉您断线撤单是否会触发。账户可能读回 `enabled: true`，却仍未受到保护。
* **数据流不是仓位状态的权威来源**。任何重连之后，请以 `GET /positions` 和 `GET /account` 为准进行对账，而不是从上次中断处重放。

## 客户端

上面的代码片段使用以下包：

| 客户端        | 包 / crate                |
| ---------- | ------------------------ |
| Rust       | `nexus_exchange`         |
| Python     | `nexus_exchange`         |
| TypeScript | `@nexus-xyz/exchange-ts` |
| CLI        | `nexus` 命令               |

CLI 和各语言 SDK 在交易所 monorepo 之外分发。引导式演练没有说明它们的仓库，因此这里不提供安装说明。

## 后续步骤

* [概览](/api-reference/zh-cn/readme.md)：交易所 API 涵盖哪些内容以及如何组织
* [身份验证](/api-reference/zh-cn/guides/authentication.md)：会话令牌、HMAC 规范化以及 API 密钥管理的完整说明
* [订单类型](/api-reference/zh-cn/guides/order-types.md)：全部八种订单类型的要求矩阵，以及参考侧边栏中的 Trading 页面
* [`GET /stream`](https://docs.nexus.xyz/api-reference/websocket/connect-stream)（公开，无需令牌）和 [`GET /ws`](https://docs.nexus.xyz/api-reference/websocket/connect-web-socket)（令牌来自 `POST /ws/token`）：频道、消息结构和重连


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.nexus.xyz/api-reference/zh-cn/guides/get-started.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
