mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-09 16:28:06 +00:00
Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73d34434b0 | ||
|
|
d0154e5721 | ||
|
|
52b6a8a076 | ||
|
|
db6a9cfc68 | ||
|
|
03b8e53d30 | ||
|
|
8d79ace8b3 | ||
|
|
1fb6d3d62d | ||
|
|
c4559cb0d7 | ||
|
|
1d88ddefb5 | ||
|
|
683352f737 | ||
|
|
a629bc940c | ||
|
|
fe7b8eb6f3 | ||
|
|
24339929dc | ||
|
|
ed855f6859 | ||
|
|
e144c1822f | ||
|
|
69271d33ca | ||
|
|
f1140f106a | ||
|
|
3b935b7979 | ||
|
|
00388f9166 | ||
|
|
a32efa2ba0 | ||
|
|
76704b6bdd | ||
|
|
168d8cbb08 | ||
|
|
9629c22496 | ||
|
|
a34d06f9b4 | ||
|
|
2ba3e80ad9 | ||
|
|
12e8e3e064 | ||
|
|
aa24995d28 | ||
|
|
d493642935 | ||
|
|
86670486a6 | ||
|
|
6496011d8f | ||
|
|
792351ab8a | ||
|
|
4915dc574e | ||
|
|
9866e8068f | ||
|
|
099af3ce01 | ||
|
|
445e634aa1 | ||
|
|
4bb1fee995 | ||
|
|
aad14395e0 | ||
|
|
598f2a0eb6 | ||
|
|
cb1cef6f1b | ||
|
|
fd034d493f | ||
|
|
2551670874 | ||
|
|
3ec7e9b8d6 | ||
|
|
499ee692da | ||
|
|
de13142950 | ||
|
|
597e41f053 | ||
|
|
b0a33a58d1 | ||
|
|
65b9f21981 | ||
|
|
33b5407245 | ||
|
|
7aafc3b69d | ||
|
|
9a093459bc | ||
|
|
aa36b0cfdc | ||
|
|
93c6409688 |
+25
-1
@@ -2,16 +2,35 @@
|
||||
LANG=zh
|
||||
|
||||
# Exchange selection
|
||||
EXCHANGE=aster # Pick aster (default) or grvt/lighter/backpack/paradex/nado
|
||||
EXCHANGE=aster # Pick aster (default) or standx/grvt/lighter/backpack/paradex/nado
|
||||
|
||||
# Aster API credentials
|
||||
ASTER_API_KEY=
|
||||
ASTER_API_SECRET=
|
||||
|
||||
# StandX authentication (set when EXCHANGE=standx)
|
||||
STANDX_TOKEN=
|
||||
STANDX_SYMBOL=BTC-USD
|
||||
# STANDX_BASE_URL=https://perps.standx.com
|
||||
# STANDX_WS_URL=wss://perps.standx.com/ws-stream/v1
|
||||
# STANDX_SESSION_ID=
|
||||
# Optional: request signing key (ed25519 private key, supports hex or base58 format)
|
||||
# STANDX_REQUEST_PRIVATE_KEY=
|
||||
# Token expiry configuration (recommended method: creation date + validity days)
|
||||
# Get these values when generating API token at https://standx.com/user/session
|
||||
# STANDX_TOKEN_CREATE_DATE=2026-01-15 # Token creation date (YYYY-MM-DD format)
|
||||
# STANDX_TOKEN_VALIDITY_DAYS=30 # Token validity period in days
|
||||
# Legacy method: direct expiry timestamp (Unix seconds)
|
||||
# STANDX_TOKEN_EXPIRY=1737092800
|
||||
|
||||
# Core trading symbol and sizing
|
||||
TRADE_SYMBOL=BTCUSDT # Trading pair symbol
|
||||
TRADE_AMOUNT=0.001 # Base order quantity (base asset, e.g. BTC)
|
||||
|
||||
# Swing Trading
|
||||
SWING_DIRECTION=short # short | long | both
|
||||
SWING_STOP_LOSS_PCT=0.05 # 0.05 = 5%
|
||||
|
||||
# Risk management (USD amounts unless noted)
|
||||
LOSS_LIMIT=0.04 # Max loss per trade in USDT before forced close
|
||||
TRAILING_PROFIT=0.2 # Trailing stop activation profit (USDT)
|
||||
@@ -145,3 +164,8 @@ NADO_MIN_SIZE_POLICY=adjust
|
||||
# NADO_ARCHIVE_URL=https://archive.prod.nado.xyz/v1
|
||||
# NADO_TRIGGER_URL=https://trigger.prod.nado.xyz/v1
|
||||
# NADO_DEBUG=false
|
||||
|
||||
# Telegram notification configuration
|
||||
# TELEGRAM_BOT_TOKEN= # Telegram bot token from @BotFather
|
||||
# TELEGRAM_CHAT_ID= # Chat ID to receive notifications
|
||||
# TELEGRAM_ACCOUNT_LABEL= # Account label to distinguish multiple bot instances (e.g., "Account-A")
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# RitMEX Bot - Claude Instructions
|
||||
|
||||
## Package Manager
|
||||
|
||||
**必须使用 Bun** - 这个项目使用 Bun 作为包管理器和运行时。所有能用 bun 执行的命令都必须使用 bun:
|
||||
|
||||
- 安装依赖: `bun install`
|
||||
- 运行脚本: `bun run <script>`
|
||||
- 执行测试: `bun test`
|
||||
- 类型检查: `bun run typecheck`
|
||||
|
||||
**不要使用 npm、yarn 或 npx**
|
||||
@@ -12,6 +12,7 @@ A Bun-powered multi-exchange perpetuals workstation that ships an SMA30 trend en
|
||||
|
||||
* [Lighter 手续费优惠注册链接](https://app.lighter.xyz/?referral=111909FA)
|
||||
* [Aster 手续费优惠注册链接](https://www.asterdex.com/zh-CN/referral/4665f3)
|
||||
* [StandX 手续费优惠注册链接](https://standx.com/referral?code=xingxingjun)
|
||||
* [Binance 手续费优惠注册链接](https://www.binance.com/join?ref=KNKCA9XC)
|
||||
* [GRVT 手续费优惠注册链接](https://grvt.io/exchange/sign-up?ref=sea)
|
||||
* [Nado 手续费优惠注册链接](https://app.nado.xyz?join=LKbIUs5)
|
||||
@@ -35,10 +36,12 @@ A Bun-powered multi-exchange perpetuals workstation that ships an SMA30 trend en
|
||||
| 交易所 | 合约类型 | 必填环境变量 | 备注 |
|
||||
| --- | --- | --- | --- |
|
||||
| Aster | USDT 永续 | `ASTER_API_KEY`, `ASTER_API_SECRET` | 默认交易所;兼容脚本引导
|
||||
| StandX | USD 永续 | `STANDX_TOKEN` | 使用 JWT Token 登录,优先走 WebSocket 推送
|
||||
| GRVT | USDT 永续 | `GRVT_API_KEY`, `GRVT_API_SECRET`, `GRVT_SUB_ACCOUNT_ID` | `GRVT_ENV` 可切换 `prod`/`testnet`
|
||||
| Lighter | zkLighter 永续 | `LIGHTER_ACCOUNT_INDEX`, `LIGHTER_API_PRIVATE_KEY` | 默认 `LIGHTER_ENV=testnet`
|
||||
| Backpack | USDC 永续 | `BACKPACK_API_KEY`, `BACKPACK_API_SECRET`, `BACKPACK_PASSWORD` | `BACKPACK_SANDBOX=true` 启用沙盒
|
||||
| Paradex | StarkEx 永续 | `PARADEX_PRIVATE_KEY`, `PARADEX_WALLET_ADDRESS` | `PARADEX_SANDBOX=true` 使用测试网
|
||||
| Nado | USDC 永续 | `NADO_SIGNER_PRIVATE_KEY`, `NADO_SUBACCOUNT_OWNER` | `NADO_ENV` 可切换 `inkMainnet`/`inkTestnet`
|
||||
|
||||
## 系统要求
|
||||
- Bun ≥ 1.2(需同时包含 `bun`、`bunx` 命令)
|
||||
@@ -83,7 +86,7 @@ curl -fsSL https://github.com/discountry/ritmex-bot/raw/refs/heads/main/setup.sh
|
||||
|
||||
| 变量 | 说明 |
|
||||
| --- | --- |
|
||||
| `EXCHANGE` | 选择交易所(`aster`/`grvt`/`lighter`/`backpack`/`paradex`/`nado`) |
|
||||
| `EXCHANGE` | 选择交易所(`aster`/`standx`/`grvt`/`lighter`/`backpack`/`paradex`/`nado`) |
|
||||
| `TRADE_SYMBOL` | 交易对(默认 `BTCUSDT`) |
|
||||
| `TRADE_AMOUNT` | 单笔下单数量(标的资产计) |
|
||||
| `LOSS_LIMIT` | 单笔最大亏损触发的强平额度(USDT) |
|
||||
@@ -108,6 +111,36 @@ curl -fsSL https://github.com/discountry/ritmex-bot/raw/refs/heads/main/setup.sh
|
||||
3. 根据交易对调整 `TRADE_SYMBOL`、`PRICE_TICK`、`QTY_STEP` 等精度参数。
|
||||
4. 一键脚本会自动写入这些变量,手动部署时需自行维护。
|
||||
|
||||
### StandX
|
||||
|
||||
* [StandX 做市策略教程](docs/standx/maker-points-guide.md)
|
||||
|
||||
策略需要 StandX 的 API Token 和签名私钥才能下单。
|
||||
|
||||
**获取方式(使用 StandX 官方 API 生成功能):**
|
||||
1. 打开 StandX 官方 API 创建页面:https://standx.com/user/session
|
||||
2. 连接钱包并登录
|
||||
3. 点击 **"Generate API Token"** 按钮
|
||||
4. 页面会显示以下信息:
|
||||
- **Token**(以 `eyJ` 开头的 JWT 字符串)→ 填入 `STANDX_TOKEN`
|
||||
- **Ed25519 Private Key**(Base58 格式私钥,类似 `HdsyJD7oWgT...`)→ 填入 `STANDX_REQUEST_PRIVATE_KEY`
|
||||
- **创建日期** 和 **有效期天数** → 用于配置 Token 过期提醒
|
||||
|
||||
> Ed25519 Private Key 是系统自动生成的签名私钥,仅用于交易请求签名,你的资产仍在主钱包中,非常安全。
|
||||
|
||||
请妥善保存这些凭证,不要分享给他人。
|
||||
|
||||
**配置步骤:**
|
||||
1. 设置 `EXCHANGE=standx`。
|
||||
2. 填写 `STANDX_TOKEN`(Perps API 的 JWT Token)。
|
||||
3. 填写 `STANDX_REQUEST_PRIVATE_KEY`(Ed25519 签名私钥,Base58 格式)。
|
||||
4. 设置 `STANDX_SYMBOL`(默认 `BTC-USD`),并校准 `PRICE_TICK` / `QTY_STEP`。
|
||||
5. 推荐配置 Token 过期时间:
|
||||
- `STANDX_TOKEN_CREATE_DATE`(创建日期,格式 `YYYY-MM-DD`)
|
||||
- `STANDX_TOKEN_VALIDITY_DAYS`(有效期天数)
|
||||
6. 可选:`STANDX_BASE_URL`、`STANDX_WS_URL`、`STANDX_SESSION_ID` 用于自定义环境。
|
||||
|
||||
|
||||
### GRVT
|
||||
1. 在 `.env` 中设置 `EXCHANGE=grvt`。
|
||||
2. 填写 `GRVT_API_KEY`、`GRVT_API_SECRET`、`GRVT_SUB_ACCOUNT_ID`。
|
||||
|
||||
+46
-9
@@ -1,20 +1,25 @@
|
||||
# ritmex-bot
|
||||
|
||||
**Language Setting**: Set `LANG=en` in your `.env` file to display the CLI interface in English.
|
||||
|
||||
A Bun-powered multi-exchange perpetuals workstation that ships an SMA30 trend engine, a Guardian stop sentinel, and two market-making modes. It offers instant restarts, realtime market data, structured logging, and an Ink-based CLI dashboard.
|
||||
|
||||
If you'd like to support this project and get fee discounts, please consider using these referral links:
|
||||
|
||||
* [Lighter referral link](https://app.lighter.xyz/?referral=111909FA)
|
||||
* [Aster referral link](https://www.asterdex.com/en/referral/4665f3)
|
||||
* [StandX referral link](https://standx.com/referral?code=xingxingjun)
|
||||
* [Binance referral link](https://www.binance.com/join?ref=KNKCA9XC)
|
||||
* [GRVT referral link](https://grvt.io/exchange/sign-up?ref=sea)
|
||||
* [Nado referral link](https://app.nado.xyz?join=LKbIUs5)
|
||||
* [Backpack referral link](https://backpack.exchange/join/ritmex)
|
||||
* [edgex referral link](https://pro.edgex.exchange/referral/BULL)
|
||||
* [Paradex referral link](https://paradex.io/ref/xingxingjun)
|
||||
* [Apex referral link](https://join.omni.apex.exchange/RITHMEX)
|
||||
* [Apex referral link](https://join.omni.apex.exchange/SEA)
|
||||
|
||||
## Documentation Map
|
||||
- [中文 README](README.md)
|
||||
- [Beginner-friendly Quick Start](simple-readme.md)
|
||||
- [Grid Trading Strategy Guide](grid-trading.md)
|
||||
|
||||
## Highlights
|
||||
- **Live data & risk sync** via websockets with REST fallbacks and full reconciliation on restart.
|
||||
@@ -27,13 +32,15 @@ A Bun-powered multi-exchange perpetuals workstation that ships an SMA30 trend en
|
||||
| Exchange | Contract Type | Required Environment Variables | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Aster | USDT perpetuals | `ASTER_API_KEY`, `ASTER_API_SECRET` | Default venue; works with the bootstrap script |
|
||||
| StandX | USD perpetuals | `STANDX_TOKEN` | Uses JWT token auth; prefer websocket streams |
|
||||
| GRVT | USDT perpetuals | `GRVT_API_KEY`, `GRVT_API_SECRET`, `GRVT_SUB_ACCOUNT_ID` | Switch `GRVT_ENV` between `prod` and `testnet` |
|
||||
| Lighter | zkLighter perpetuals | `LIGHTER_ACCOUNT_INDEX`, `LIGHTER_API_PRIVATE_KEY` | Defaults to `LIGHTER_ENV=testnet` |
|
||||
| Backpack | USDC perpetuals | `BACKPACK_API_KEY`, `BACKPACK_API_SECRET`, `BACKPACK_PASSWORD` | Set `BACKPACK_SANDBOX=true` for the sandbox |
|
||||
| Paradex | StarkEx perpetuals | `PARADEX_PRIVATE_KEY`, `PARADEX_WALLET_ADDRESS` | Toggle `PARADEX_SANDBOX=true` for the testnet |
|
||||
| Nado | USDC perpetuals | `NADO_SIGNER_PRIVATE_KEY`, `NADO_SUBACCOUNT_OWNER` | Switch `NADO_ENV` between `inkMainnet` and `inkTestnet` |
|
||||
|
||||
## Requirements
|
||||
- Bun ≥ 1.2 (both `bun` and `bunx` on PATH)
|
||||
- Bun >= 1.2 (both `bun` and `bunx` on PATH)
|
||||
- macOS, Linux, or Windows via WSL (native Windows works but WSL is recommended)
|
||||
- Node.js is optional unless your tooling requires it
|
||||
|
||||
@@ -75,7 +82,7 @@ The script installs Bun, project dependencies, collects Aster API credentials, g
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `EXCHANGE` | Choose the venue (`aster` / `grvt` / `lighter` / `backpack` / `paradex` / `nado`) |
|
||||
| `EXCHANGE` | Choose the venue (`aster` / `standx` / `grvt` / `lighter` / `backpack` / `paradex` / `nado`) |
|
||||
| `TRADE_SYMBOL` | Contract symbol (defaults to `BTCUSDT`) |
|
||||
| `TRADE_AMOUNT` | Order size in base asset units |
|
||||
| `LOSS_LIMIT` | Max per-trade loss in USDT before forced close |
|
||||
@@ -94,12 +101,42 @@ The script installs Bun, project dependencies, collects Aster API credentials, g
|
||||
> ```
|
||||
|
||||
## Exchange Setup Guides
|
||||
|
||||
### Aster
|
||||
1. Keep `EXCHANGE=aster` (default value).
|
||||
2. Supply `ASTER_API_KEY` and `ASTER_API_SECRET`.
|
||||
3. Adjust `TRADE_SYMBOL`, `PRICE_TICK`, and `QTY_STEP` to match the requested market.
|
||||
4. The bootstrap script auto-populates these variables; manual installs must maintain them.
|
||||
|
||||
### StandX
|
||||
|
||||
* [StandX Maker Points Strategy Guide](docs/standx/maker-points-guide.md)
|
||||
|
||||
The strategy requires a StandX API Token and signing private key to place orders.
|
||||
|
||||
**How to obtain (using StandX's official API generation feature):**
|
||||
1. Open the StandX official API creation page: https://standx.com/user/session
|
||||
2. Connect your wallet and log in
|
||||
3. Click the **"Generate API Token"** button
|
||||
4. The page will display the following information:
|
||||
- **Token** (JWT string starting with `eyJ`) → Fill in `STANDX_TOKEN`
|
||||
- **Ed25519 Private Key** (Base58 format, like `HdsyJD7oWgT...`) → Fill in `STANDX_REQUEST_PRIVATE_KEY`
|
||||
- **Creation date** and **Validity days** → Used to configure token expiry reminders
|
||||
|
||||
> The Ed25519 Private Key is an auto-generated signing key used only for trade request signatures. Your assets remain in your main wallet and are completely safe.
|
||||
|
||||
Please keep these credentials safe and do not share them with anyone.
|
||||
|
||||
**Configuration steps:**
|
||||
1. Set `EXCHANGE=standx`.
|
||||
2. Provide `STANDX_TOKEN` (JWT token for perps API).
|
||||
3. Provide `STANDX_REQUEST_PRIVATE_KEY` (Ed25519 signing private key, Base58 format).
|
||||
4. Set `STANDX_SYMBOL` (defaults to `BTC-USD`) and align `PRICE_TICK` / `QTY_STEP`.
|
||||
5. Recommended: configure token expiry settings:
|
||||
- `STANDX_TOKEN_CREATE_DATE` (creation date, format `YYYY-MM-DD`)
|
||||
- `STANDX_TOKEN_VALIDITY_DAYS` (validity days)
|
||||
6. Optional: `STANDX_BASE_URL`, `STANDX_WS_URL`, or `STANDX_SESSION_ID` for custom endpoints.
|
||||
|
||||
### GRVT
|
||||
1. Set `EXCHANGE=grvt` inside `.env`.
|
||||
2. Fill `GRVT_API_KEY`, `GRVT_API_SECRET`, and `GRVT_SUB_ACCOUNT_ID`.
|
||||
@@ -108,25 +145,25 @@ The script installs Bun, project dependencies, collects Aster API credentials, g
|
||||
|
||||
### Lighter
|
||||
1. Set `EXCHANGE=lighter`.
|
||||
2. Provide `LIGHTER_ACCOUNT_INDEX` and `LIGHTER_API_PRIVATE_KEY` (40-byte hex private key).
|
||||
2. Provide `LIGHTER_ACCOUNT_INDEX` and `LIGHTER_API_PRIVATE_KEY` (40-byte hex private key). `LIGHTER_ACCOUNT_INDEX` is your account index, which you can find by opening DevTools (F12) on the official website and observing API requests. `LIGHTER_API_PRIVATE_KEY` is your API private key.
|
||||
3. Switch `LIGHTER_ENV` to `mainnet`, `staging`, or `dev` when necessary; override `LIGHTER_BASE_URL` if endpoints differ.
|
||||
4. `LIGHTER_SYMBOL` defaults to `BTCUSDT`; override price/size decimals when markets differ.
|
||||
|
||||
### Backpack
|
||||
1. Set `EXCHANGE=backpack`.
|
||||
2. Populate `BACKPACK_API_KEY`, `BACKPACK_API_SECRET`, and `BACKPACK_PASSWORD`; add `BACKPACK_SUBACCOUNT` if you trade from a subaccount.
|
||||
2. Populate `BACKPACK_API_KEY`, `BACKPACK_API_SECRET`, and `BACKPACK_PASSWORD`; add `BACKPACK_SUBACCOUNT` if you trade from a subaccount (defaults to main account ID).
|
||||
3. Toggle `BACKPACK_SANDBOX=true` for the sandbox environment and verify `BACKPACK_SYMBOL` matches the contract (defaults to `BTC_USD_PERP`).
|
||||
4. Enable `BACKPACK_DEBUG=true` for verbose adapter logging.
|
||||
|
||||
### Paradex
|
||||
1. Set `EXCHANGE=paradex`.
|
||||
2. Provide `PARADEX_PRIVATE_KEY` (EVM private key) and `PARADEX_WALLET_ADDRESS`.
|
||||
2. Provide `PARADEX_PRIVATE_KEY` (EVM private key) and `PARADEX_WALLET_ADDRESS`. Note: These are your EVM wallet address and private key. It is recommended to create a brand new wallet and avoid storing unrelated assets in it.
|
||||
3. The adapter connects to mainnet by default; enable `PARADEX_SANDBOX=true` and adjust `PARADEX_SYMBOL` for testnet usage.
|
||||
4. Advanced tuning: use `PARADEX_USE_PRO`, `PARADEX_RECONNECT_DELAY_MS`, or debug flags as needed.
|
||||
|
||||
### Nado
|
||||
1. Set `EXCHANGE=nado`.
|
||||
2. On the Nado web app, open DevTools → switch to the `Application` tab → `Local Storage`, locate `nado.userSettings`, then grab the `privateKey` field from its JSON value and paste it into `.env` as `NADO_SIGNER_PRIVATE_KEY`.
|
||||
2. On the Nado web app (trading interface), open DevTools (F12) -> switch to the `Application` tab -> `Local Storage`, locate `nado.userSettings`, then grab the `privateKey` field from its JSON value and paste it into `.env` as `NADO_SIGNER_PRIVATE_KEY`.
|
||||
3. Provide `NADO_SUBACCOUNT_OWNER` (or `NADO_EVM_ADDRESS`).
|
||||
4. Select network via `NADO_ENV=inkMainnet` (mainnet) or `inkTestnet` (testnet).
|
||||
5. Set `NADO_SYMBOL` using Nado product symbols like `BTC-PERP` (it also accepts `BTCUSDT0` and maps it to `BTC-PERP`).
|
||||
@@ -178,7 +215,7 @@ bun x vitest --watch
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
- Keep at least 50–100 USDT in the account before deploying a live strategy.
|
||||
- Keep at least 50-100 USDT in the account before deploying a live strategy.
|
||||
- Configure leverage on the exchange manually (~50x is recommended); the bot will not change it.
|
||||
- Ensure your server or workstation clock is in sync to avoid signature errors.
|
||||
- Accounts must run in one-way position mode.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 0,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "ritmex-bot",
|
||||
@@ -14,6 +15,7 @@
|
||||
"ethereum-cryptography": "^2.1.3",
|
||||
"ink": "^6.3.1",
|
||||
"react": "^19.1.1",
|
||||
"trading-signals": "^7.4.3",
|
||||
"viem": "^2.43.1",
|
||||
"ws": "^8.18.3",
|
||||
},
|
||||
@@ -29,7 +31,7 @@
|
||||
"packages": {
|
||||
"@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.1", "", {}, "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ=="],
|
||||
|
||||
"@alcalzone/ansi-tokenize": ["@alcalzone/ansi-tokenize@0.2.0", "", { "dependencies": { "ansi-styles": "^6.2.1", "is-fullwidth-code-point": "^5.0.0" } }, "sha512-qI/5TaaaCZE4yeSZ83lu0+xi1r88JSxUjnH4OP/iZF7+KKZ75u3ee5isd0LxX+6N8U0npL61YrpbthILHB6BnA=="],
|
||||
"@alcalzone/ansi-tokenize": ["@alcalzone/ansi-tokenize@0.2.4", "", { "dependencies": { "ansi-styles": "^6.2.1", "is-fullwidth-code-point": "^5.0.0" } }, "sha512-HTgrrTgZ9Jgeo6Z3oqbQ7lifOVvRR14vaDuBGPPUxk9Thm+vObaO4QfYYYWw4Zo5CWQDBEfsinFA6Gre+AqwNQ=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.10", "", { "os": "aix", "cpu": "ppc64" }, "sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw=="],
|
||||
|
||||
@@ -83,19 +85,19 @@
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.10", "", { "os": "win32", "cpu": "x64" }, "sha512-9KpxSVFCu0iK1owoez6aC/s/EdUQLDN3adTxGCqxMVhrPDj6bt5dbrHDXUuq+Bs2vATFBBrQS5vdQ/Ed2P+nbw=="],
|
||||
|
||||
"@grvt/client": ["@grvt/client@1.6.4", "", { "dependencies": { "axios": "^1.12.2" } }, "sha512-yZfEvsC/BtkcdMjoB7Eh6gshBraz/9810qCllvNXDx6OmdxR+NfxPO+ucNlPbyjEt1HfSVzHBWB1yGnVl1usNA=="],
|
||||
"@grvt/client": ["@grvt/client@1.6.25", "", { "dependencies": { "axios": "^1.13.2" } }, "sha512-LG3oZSJDq1Qz6mLiHDmg+v/Hp+Nd+yOp8GIvkBVyIdOcPVzuzC8UQD7IxvS+g5EfQQKLiKzXSjKLc39a11Uj1A=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
|
||||
|
||||
"@nadohq/client": ["@nadohq/client@0.1.0-alpha.41", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.41", "@nadohq/indexer-client": "^0.1.0-alpha.41", "@nadohq/shared": "^0.1.0-alpha.41", "@nadohq/trigger-client": "^0.1.0-alpha.41", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-BbJjG32AsaBJtFA9VPH+3/sfR/pUCXVJ0spgairReb+FaZY2rYsasWGPi07y7OROXL7ZS9/LewntC6iu2NVzQg=="],
|
||||
"@nadohq/client": ["@nadohq/client@0.1.0-alpha.45", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.45", "@nadohq/indexer-client": "^0.1.0-alpha.45", "@nadohq/shared": "^0.1.0-alpha.45", "@nadohq/trigger-client": "^0.1.0-alpha.45", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-63S7eT5xSk3hxEXRLGDI94mPeu/zd1Nu4oUOZrY8wzhaT7Gl7PVP2snb8JH/PduVQzgs7+qblr4aTBI/j6QvLQ=="],
|
||||
|
||||
"@nadohq/engine-client": ["@nadohq/engine-client@0.1.0-alpha.41", "", { "dependencies": { "@nadohq/shared": "^0.1.0-alpha.41", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-PR2/MaZ2rprd42572UL26B6zBzUFLUVbvAwPFGf6N733RysUxMRixEJmUfSrPVKgZkA4gxqqEhLB0iZA08DBjw=="],
|
||||
"@nadohq/engine-client": ["@nadohq/engine-client@0.1.0-alpha.45", "", { "dependencies": { "@nadohq/shared": "^0.1.0-alpha.45", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-GqaRrsB0Z2EgNY6wu4nG5OTc5hF+buNRMc0+jPLlOQonlPJAC4OiMCgCigm4nJecYwsdiQD05W3Z4YUqggxbyw=="],
|
||||
|
||||
"@nadohq/indexer-client": ["@nadohq/indexer-client@0.1.0-alpha.41", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.41", "@nadohq/shared": "^0.1.0-alpha.41", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-5oXM+r3xQmbAHx00MlZmZj64VfcVNNWCtZgJu1Hx+A6F7zZtt0zBmDR6WnY1qWQBM/yZc/xa/Rr3ypXN5VSyQg=="],
|
||||
"@nadohq/indexer-client": ["@nadohq/indexer-client@0.1.0-alpha.45", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.45", "@nadohq/shared": "^0.1.0-alpha.45", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-8PzG9taYh380lsKT8i4UvGfhZiPpt+zPisx+ErVqMifyhcJAhgMeYNcfijwMQFNJdgTaBvtI0R5JK98l4Y0YQw=="],
|
||||
|
||||
"@nadohq/shared": ["@nadohq/shared@0.1.0-alpha.41", "", { "peerDependencies": { "bignumber.js": "^9.3.0", "viem": "*" } }, "sha512-c6rRU/9RjIRV0RSHwmliNOE3i3xi65zKGqW9O0M4Oc8a0SQXB5SpskQeSFOaZ1b9BHGi0TYg1xaLBjtYzbysJQ=="],
|
||||
"@nadohq/shared": ["@nadohq/shared@0.1.0-alpha.45", "", { "peerDependencies": { "bignumber.js": "^9.3.0", "viem": "*" } }, "sha512-4Ml8dO9mkwnIidflpunwVMLX2KJA79b53T9xTBkH1Yzy0iOnbEE27r25wvgJgyszU0aznbPBv2++FZ0d0B5Zhg=="],
|
||||
|
||||
"@nadohq/trigger-client": ["@nadohq/trigger-client@0.1.0-alpha.41", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.41", "@nadohq/shared": "^0.1.0-alpha.41", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-PxHeqi+aGUHs6S2jHRz2GC9OQD3Mb25sqqwgvDz3EoXWAfv+tYAaSDsLL8FmYEPsbTswjfXm0PoThPDyImyU9A=="],
|
||||
"@nadohq/trigger-client": ["@nadohq/trigger-client@0.1.0-alpha.45", "", { "dependencies": { "@nadohq/engine-client": "^0.1.0-alpha.45", "@nadohq/shared": "^0.1.0-alpha.45", "axios": "*", "ts-mixer": "*" }, "peerDependencies": { "viem": "*" } }, "sha512-Xt8W9zxOZhMvoXSRnx9kUR26wWuHc3EgTVTBbUXt7SlI9v3IP9I3idS6SU3j2f08flcvNqRmC2EbXyYDC2XeyQ=="],
|
||||
|
||||
"@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="],
|
||||
|
||||
@@ -155,7 +157,7 @@
|
||||
|
||||
"@scure/bip39": ["@scure/bip39@1.3.0", "", { "dependencies": { "@noble/hashes": "~1.4.0", "@scure/base": "~1.1.6" } }, "sha512-disdg7gHuTDZtY+ZdkmLpPCk7fxZSu3gBiEGuoC1XYxv9cGx3Z6cpTggCgW6odSOOIXCiDjuGejW+aJKCY/pIQ=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.2.22", "", { "dependencies": { "bun-types": "1.2.22" } }, "sha512-5A/KrKos2ZcN0c6ljRSOa1fYIyCKhZfIVYeuyb4snnvomnpFqC0tTsEkdqNxbAgExV384OETQ//WAjl3XbYqQA=="],
|
||||
"@types/bun": ["@types/bun@1.3.8", "", { "dependencies": { "bun-types": "1.3.8" } }, "sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA=="],
|
||||
|
||||
"@types/chai": ["@types/chai@5.2.2", "", { "dependencies": { "@types/deep-eql": "*" } }, "sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg=="],
|
||||
|
||||
@@ -169,8 +171,6 @@
|
||||
|
||||
"@types/node": ["@types/node@24.5.2", "", { "dependencies": { "undici-types": "~7.12.0" } }, "sha512-FYxk1I7wPv3K2XBaoyH2cTnocQEu8AOZ60hPbsyukMPLv5/5qr7V1i8PLHdl6Zf87I+xZXFvPCXYjiTFq+YSDQ=="],
|
||||
|
||||
"@types/react": ["@types/react@19.1.13", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-hHkbU/eoO3EG5/MZkuFSKmYqPbSVk5byPFa3e7y/8TybHiLMACgI8seVYlicwk7H5K/rI2px9xrQp/C+AUDTiQ=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="],
|
||||
|
||||
"@vitest/mocker": ["@vitest/mocker@3.2.4", "", { "dependencies": { "@vitest/spy": "3.2.4", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ=="],
|
||||
@@ -187,7 +187,7 @@
|
||||
|
||||
"abitype": ["abitype@1.2.3", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3.22.0 || ^4.0.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg=="],
|
||||
|
||||
"ansi-escapes": ["ansi-escapes@7.1.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-YdhtCd19sKRKfAAUsrcC1wzm4JuzJoiX4pOJqIoW2qmKj5WzG/dL8uUJ0361zaXtHqK7gEhOwtAtz7t3Yq3X5g=="],
|
||||
"ansi-escapes": ["ansi-escapes@7.2.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-g6LhBsl+GBPRWGWsBtutpzBYuIIdBkLEvad5C/va/74Db018+5TZiyA26cZJAr3Rft5lprVqOIPxf5Vid6tqAw=="],
|
||||
|
||||
"ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
|
||||
|
||||
@@ -199,17 +199,17 @@
|
||||
|
||||
"auto-bind": ["auto-bind@5.0.1", "", {}, "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg=="],
|
||||
|
||||
"axios": ["axios@1.12.2", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw=="],
|
||||
"axios": ["axios@1.13.4", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, "sha512-1wVkUaAO6WyaYtCkcYCOx12ZgpGf9Zif+qXa4n+oYzK558YryKqiL6UWwd5DqiH3VRW0GYhTZQ/vlgJrCoNQlg=="],
|
||||
|
||||
"bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
|
||||
|
||||
"bun-types": ["bun-types@1.2.22", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-hwaAu8tct/Zn6Zft4U9BsZcXkYomzpHJX28ofvx7k0Zz2HNz54n1n+tDgxoWFGB4PcFvJXJQloPhaV2eP3Q6EA=="],
|
||||
"bun-types": ["bun-types@1.3.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-fL99nxdOWvV4LqjmC+8Q9kW3M4QTtTR1eePs94v5ctGqU8OeceWrSUaRw3JYb7tU3FkMIAjkueehrHPPPGKi5Q=="],
|
||||
|
||||
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
|
||||
|
||||
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
|
||||
|
||||
"ccxt": ["ccxt@4.5.12", "", { "dependencies": { "ws": "^8.8.1" } }, "sha512-2lfL2TKjq4vBkQUQWJfDqFywhvYCZmk9r0SWC8GqA4AHZ6qozKVUJowxQTvdRsLX9jBwYSE0nc7JVurBrQ6SHg=="],
|
||||
"ccxt": ["ccxt@4.5.35", "", { "dependencies": { "ws": "^8.8.1" } }, "sha512-aFn1jq/vR9wD3Vxu/2UFoS8snqlvfYn/iYrNhyZZfzB3N+kAHhP5+sAgO6ZwNHkHiUT9IPPahC1ZSFdPtjpIYA=="],
|
||||
|
||||
"chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="],
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
|
||||
"cli-cursor": ["cli-cursor@4.0.0", "", { "dependencies": { "restore-cursor": "^4.0.0" } }, "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg=="],
|
||||
|
||||
"cli-truncate": ["cli-truncate@4.0.0", "", { "dependencies": { "slice-ansi": "^5.0.0", "string-width": "^7.0.0" } }, "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA=="],
|
||||
"cli-truncate": ["cli-truncate@5.1.1", "", { "dependencies": { "slice-ansi": "^7.1.0", "string-width": "^8.0.0" } }, "sha512-SroPvNHxUnk+vIW/dOSfNqdy1sPEFkrTk6TUtqLCnBlo3N7TNYYkzzN7uSD6+jVjrdO4+p8nH7JzH6cIvUem6A=="],
|
||||
|
||||
"code-excerpt": ["code-excerpt@4.0.0", "", { "dependencies": { "convert-to-spaces": "^2.0.1" } }, "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA=="],
|
||||
|
||||
@@ -229,15 +229,13 @@
|
||||
|
||||
"convert-to-spaces": ["convert-to-spaces@2.0.1", "", {}, "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ=="],
|
||||
|
||||
"csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="],
|
||||
|
||||
"delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
|
||||
|
||||
"dotenv": ["dotenv@17.2.2", "", {}, "sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q=="],
|
||||
"dotenv": ["dotenv@17.2.3", "", {}, "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w=="],
|
||||
|
||||
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
@@ -295,7 +293,7 @@
|
||||
|
||||
"indent-string": ["indent-string@5.0.0", "", {}, "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg=="],
|
||||
|
||||
"ink": ["ink@6.3.1", "", { "dependencies": { "@alcalzone/ansi-tokenize": "^0.2.0", "ansi-escapes": "^7.0.0", "ansi-styles": "^6.2.1", "auto-bind": "^5.0.1", "chalk": "^5.6.0", "cli-boxes": "^3.0.0", "cli-cursor": "^4.0.0", "cli-truncate": "^4.0.0", "code-excerpt": "^4.0.0", "es-toolkit": "^1.39.10", "indent-string": "^5.0.0", "is-in-ci": "^2.0.0", "patch-console": "^2.0.0", "react-reconciler": "^0.32.0", "signal-exit": "^3.0.7", "slice-ansi": "^7.1.0", "stack-utils": "^2.0.6", "string-width": "^7.2.0", "type-fest": "^4.27.0", "widest-line": "^5.0.0", "wrap-ansi": "^9.0.0", "ws": "^8.18.0", "yoga-layout": "~3.2.1" }, "peerDependencies": { "@types/react": ">=19.0.0", "react": ">=19.0.0", "react-devtools-core": "^6.1.2" }, "optionalPeers": ["@types/react", "react-devtools-core"] }, "sha512-3wGwITGrzL6rkWsi2gEKzgwdafGn4ZYd3u4oRp+sOPvfoxEHlnoB5Vnk9Uy5dMRUhDOqF3hqr4rLQ4lEzBc2sQ=="],
|
||||
"ink": ["ink@6.6.0", "", { "dependencies": { "@alcalzone/ansi-tokenize": "^0.2.1", "ansi-escapes": "^7.2.0", "ansi-styles": "^6.2.1", "auto-bind": "^5.0.1", "chalk": "^5.6.0", "cli-boxes": "^3.0.0", "cli-cursor": "^4.0.0", "cli-truncate": "^5.1.1", "code-excerpt": "^4.0.0", "es-toolkit": "^1.39.10", "indent-string": "^5.0.0", "is-in-ci": "^2.0.0", "patch-console": "^2.0.0", "react-reconciler": "^0.33.0", "signal-exit": "^3.0.7", "slice-ansi": "^7.1.0", "stack-utils": "^2.0.6", "string-width": "^8.1.0", "type-fest": "^4.27.0", "widest-line": "^5.0.0", "wrap-ansi": "^9.0.0", "ws": "^8.18.0", "yoga-layout": "~3.2.1" }, "peerDependencies": { "@types/react": ">=19.0.0", "react": ">=19.0.0", "react-devtools-core": "^6.1.2" }, "optionalPeers": ["@types/react", "react-devtools-core"] }, "sha512-QDt6FgJxgmSxAelcOvOHUvFxbIUjVpCH5bx+Slvc5m7IEcpGt3dYwbz/L+oRnqEGeRvwy1tineKK4ect3nW1vQ=="],
|
||||
|
||||
"is-fullwidth-code-point": ["is-fullwidth-code-point@5.1.0", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="],
|
||||
|
||||
@@ -323,7 +321,7 @@
|
||||
|
||||
"onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
|
||||
|
||||
"ox": ["ox@0.10.5", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.2.3", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-mXJRiZswmX46abrzNkJpTN9sPJ/Rhevsp5Dfg0z80D55aoLNmEV4oN+/+feSNW593c2CnHavMqSVBanpJ0lUkQ=="],
|
||||
"ox": ["ox@0.11.3", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.2.3", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-1bWYGk/xZel3xro3l8WGg6eq4YEKlaqvyMtVhfMFpbJzK2F6rj4EDRtqDCWVEJMkzcmEi9uW2QxsqELokOlarw=="],
|
||||
|
||||
"patch-console": ["patch-console@2.0.0", "", {}, "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA=="],
|
||||
|
||||
@@ -339,15 +337,15 @@
|
||||
|
||||
"proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
|
||||
|
||||
"react": ["react@19.1.1", "", {}, "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ=="],
|
||||
"react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
|
||||
"react-reconciler": ["react-reconciler@0.32.0", "", { "dependencies": { "scheduler": "^0.26.0" }, "peerDependencies": { "react": "^19.1.0" } }, "sha512-2NPMOzgTlG0ZWdIf3qG+dcbLSoAc/uLfOwckc3ofy5sSK0pLJqnQLpUFxvGcN2rlXSjnVtGeeFLNimCQEj5gOQ=="],
|
||||
"react-reconciler": ["react-reconciler@0.33.0", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }, "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA=="],
|
||||
|
||||
"restore-cursor": ["restore-cursor@4.0.0", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg=="],
|
||||
|
||||
"rollup": ["rollup@4.52.0", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.52.0", "@rollup/rollup-android-arm64": "4.52.0", "@rollup/rollup-darwin-arm64": "4.52.0", "@rollup/rollup-darwin-x64": "4.52.0", "@rollup/rollup-freebsd-arm64": "4.52.0", "@rollup/rollup-freebsd-x64": "4.52.0", "@rollup/rollup-linux-arm-gnueabihf": "4.52.0", "@rollup/rollup-linux-arm-musleabihf": "4.52.0", "@rollup/rollup-linux-arm64-gnu": "4.52.0", "@rollup/rollup-linux-arm64-musl": "4.52.0", "@rollup/rollup-linux-loong64-gnu": "4.52.0", "@rollup/rollup-linux-ppc64-gnu": "4.52.0", "@rollup/rollup-linux-riscv64-gnu": "4.52.0", "@rollup/rollup-linux-riscv64-musl": "4.52.0", "@rollup/rollup-linux-s390x-gnu": "4.52.0", "@rollup/rollup-linux-x64-gnu": "4.52.0", "@rollup/rollup-linux-x64-musl": "4.52.0", "@rollup/rollup-openharmony-arm64": "4.52.0", "@rollup/rollup-win32-arm64-msvc": "4.52.0", "@rollup/rollup-win32-ia32-msvc": "4.52.0", "@rollup/rollup-win32-x64-gnu": "4.52.0", "@rollup/rollup-win32-x64-msvc": "4.52.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-+IuescNkTJQgX7AkIDtITipZdIGcWF0pnVvZTWStiazUmcGA2ag8dfg0urest2XlXUi9kuhfQ+qmdc5Stc3z7g=="],
|
||||
|
||||
"scheduler": ["scheduler@0.26.0", "", {}, "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA=="],
|
||||
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||
|
||||
@@ -363,7 +361,7 @@
|
||||
|
||||
"std-env": ["std-env@3.9.0", "", {}, "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw=="],
|
||||
|
||||
"string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
|
||||
"string-width": ["string-width@8.1.1", "", { "dependencies": { "get-east-asian-width": "^1.3.0", "strip-ansi": "^7.1.0" } }, "sha512-KpqHIdDL9KwYk22wEOg/VIqYbrnLeSApsKT/bSj6Ez7pn3CftUiLAv2Lccpq1ALcpLV9UX1Ppn92npZWu2w/aw=="],
|
||||
|
||||
"strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="],
|
||||
|
||||
@@ -381,6 +379,8 @@
|
||||
|
||||
"tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="],
|
||||
|
||||
"trading-signals": ["trading-signals@7.4.3", "", {}, "sha512-kOyzd85qhuhU7yGkB5z74MVP6j30xBCfZy5+bgBnvfxY1ZdvaQsdD+C5j+CoIRtCAgSOuxB7jmPpBrqO6h17sQ=="],
|
||||
|
||||
"ts-mixer": ["ts-mixer@6.0.4", "", {}, "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="],
|
||||
|
||||
"type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
|
||||
@@ -389,7 +389,7 @@
|
||||
|
||||
"undici-types": ["undici-types@7.12.0", "", {}, "sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ=="],
|
||||
|
||||
"viem": ["viem@2.43.1", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.10.5", "ws": "8.18.3" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-S33pBNlRvOlVv4+L94Z8ydCMDB1j0cuHFUvaC28i6OTxw3uY1P4M3h1YDFK8YC1H9/lIbeBTTvCRhi0FqU/2iw=="],
|
||||
"viem": ["viem@2.45.1", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.11.3", "ws": "8.18.3" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-LN6Pp7vSfv50LgwhkfSbIXftAM5J89lP9x8TeDa8QM7o41IxlHrDh0F9X+FfnCWtsz11pEVV5sn+yBUoOHNqYA=="],
|
||||
|
||||
"vite": ["vite@7.1.7", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-VbA8ScMvAISJNJVbRDTJdCwqQoAareR/wutevKanhR2/1EkoXVZVkkORaYm/tNVCjP/UDTKtcw3bAkwOUdedmA=="],
|
||||
|
||||
@@ -403,12 +403,10 @@
|
||||
|
||||
"wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="],
|
||||
|
||||
"ws": ["ws@8.18.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
|
||||
"ws": ["ws@8.19.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
|
||||
|
||||
"yoga-layout": ["yoga-layout@3.2.1", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="],
|
||||
|
||||
"cli-truncate/slice-ansi": ["slice-ansi@5.0.0", "", { "dependencies": { "ansi-styles": "^6.0.0", "is-fullwidth-code-point": "^4.0.0" } }, "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ=="],
|
||||
|
||||
"ox/@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="],
|
||||
|
||||
"ox/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
|
||||
@@ -425,7 +423,11 @@
|
||||
|
||||
"viem/@scure/bip39": ["@scure/bip39@1.6.0", "", { "dependencies": { "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A=="],
|
||||
|
||||
"cli-truncate/slice-ansi/is-fullwidth-code-point": ["is-fullwidth-code-point@4.0.0", "", {}, "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ=="],
|
||||
"viem/ws": ["ws@8.18.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
|
||||
|
||||
"widest-line/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
|
||||
|
||||
"wrap-ansi/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
|
||||
|
||||
"ox/@scure/bip32/@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="],
|
||||
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
# Nado 交易机器人完全新手教程
|
||||
|
||||
> 本教程面向零基础用户,手把手教你如何在 Nado 交易所使用 ritmex-bot 进行自动化交易。
|
||||
|
||||
## 目录
|
||||
|
||||
1. [什么是 Nado 和 ritmex-bot](#什么是-nado-和-ritmex-bot)
|
||||
2. [准备工作](#准备工作)
|
||||
3. [安装 Bun 运行环境](#安装-bun-运行环境)
|
||||
4. [下载并安装 ritmex-bot](#下载并安装-ritmex-bot)
|
||||
5. [在 Nado 创建账户并入金](#在-nado-创建账户并入金)
|
||||
6. [获取 Nado 鉴权信息(重要)](#获取-nado-鉴权信息重要)
|
||||
7. [配置 .env 文件](#配置-env-文件)
|
||||
8. [启动交易机器人](#启动交易机器人)
|
||||
9. [策略说明与选择](#策略说明与选择)
|
||||
10. [常见问题与排查](#常见问题与排查)
|
||||
|
||||
---
|
||||
|
||||
## 什么是 Nado 和 ritmex-bot
|
||||
|
||||
### Nado 交易所
|
||||
|
||||
Nado 是一个运行在 **Ink L2 网络**(基于 Optimism Superchain)的去中心化永续合约交易所。它支持 BTC、ETH 等主流加密货币的永续合约交易,具有以下特点:
|
||||
|
||||
- **去中心化**:资产由用户钱包控制,无需信任中心化机构
|
||||
- **低延迟**:使用 L2 网络,交易确认快速
|
||||
- **统一保证金**:支持多种资产作为抵押品
|
||||
|
||||
注册使用 Nado 目前需要邀请码:
|
||||
|
||||
* [https://app.nado.xyz?join=eGp9qPD](https://app.nado.xyz?join=eGp9qPD)
|
||||
* [https://app.nado.xyz?join=LKbIUs5](https://app.nado.xyz?join=LKbIUs5)
|
||||
|
||||
### ritmex-bot 交易机器人
|
||||
|
||||
ritmex-bot 是一个多交易所量化交易终端,支持多种自动化交易策略:
|
||||
|
||||
- **趋势跟随策略**:基于 SMA30 均线的趋势交易
|
||||
- **做市策略**:双边挂单赚取买卖价差
|
||||
- **Guardian 防守策略**:自动监控仓位,补挂止损止盈
|
||||
- **网格策略**:区间震荡行情的网格交易
|
||||
|
||||
---
|
||||
|
||||
## 准备工作
|
||||
|
||||
在开始之前,请确保你具备以下条件:
|
||||
|
||||
### 硬件要求
|
||||
|
||||
- 一台可以联网的电脑(macOS、Linux 或 Windows)
|
||||
- 稳定的网络连接
|
||||
|
||||
### 软件要求
|
||||
|
||||
- **终端/命令行工具**
|
||||
- macOS:使用自带的"终端"应用
|
||||
- Windows:推荐使用 WSL(Windows Subsystem for Linux)或 PowerShell
|
||||
- Linux:使用自带的终端
|
||||
|
||||
### 资金要求
|
||||
|
||||
- 至少 **50-100 USDT** 等值的资金用于交易
|
||||
- 少量 **ETH**(约 0.01-0.05 ETH)用于支付 Gas 费用
|
||||
|
||||
### 钱包要求
|
||||
|
||||
- 一个支持 EVM 的钱包,推荐:
|
||||
- **MetaMask**(浏览器插件)
|
||||
- **Rabby Wallet**(更专业的交易钱包)
|
||||
|
||||
---
|
||||
|
||||
## 安装 Bun 运行环境
|
||||
|
||||
ritmex-bot 使用 **Bun** 作为运行环境。Bun 是一个快速的 JavaScript 运行时。
|
||||
|
||||
### macOS / Linux 安装
|
||||
|
||||
打开终端,输入以下命令:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
```
|
||||
|
||||
安装完成后,**关闭并重新打开终端**,然后验证安装:
|
||||
|
||||
```bash
|
||||
bun -v
|
||||
```
|
||||
|
||||
如果显示版本号(如 `1.2.x`),说明安装成功。
|
||||
|
||||
### Windows 安装
|
||||
|
||||
**方法一:使用 PowerShell(推荐)**
|
||||
|
||||
以管理员身份打开 PowerShell,输入:
|
||||
|
||||
```powershell
|
||||
powershell -c "irm bun.sh/install.ps1 | iex"
|
||||
```
|
||||
|
||||
**方法二:使用 WSL(更稳定)**
|
||||
|
||||
1. 先安装 WSL:在 PowerShell 中运行 `wsl --install`
|
||||
2. 重启电脑
|
||||
3. 打开 WSL 终端,按照 Linux 方式安装 Bun
|
||||
|
||||
---
|
||||
|
||||
## 下载并安装 ritmex-bot
|
||||
|
||||
### 方法一:使用 Git(推荐)
|
||||
|
||||
```bash
|
||||
# 克隆代码仓库
|
||||
git clone https://github.com/discountry/ritmex-bot.git
|
||||
|
||||
# 进入项目目录
|
||||
cd ritmex-bot
|
||||
|
||||
# 安装依赖
|
||||
bun install
|
||||
```
|
||||
|
||||
### 方法二:直接下载 ZIP
|
||||
|
||||
1. 访问 https://github.com/discountry/ritmex-bot
|
||||
2. 点击绿色的 "Code" 按钮
|
||||
3. 选择 "Download ZIP"
|
||||
4. 解压下载的文件
|
||||
5. 在终端中进入解压后的目录
|
||||
6. 运行 `bun install`
|
||||
|
||||
---
|
||||
|
||||
## 在 Nado 创建账户并入金
|
||||
|
||||
### 步骤 1:连接钱包
|
||||
|
||||
1. 访问 Nado 官网:https://app.nado.xyz
|
||||
2. 点击右上角的 **"Connect Wallet"**
|
||||
3. 选择你的钱包(如 MetaMask)
|
||||
4. 在钱包中确认连接
|
||||
|
||||
### 步骤 2:添加 Ink 网络到钱包
|
||||
|
||||
Nado 运行在 Ink L2 网络上,你需要先添加这个网络:
|
||||
|
||||
**自动添加方式:**
|
||||
1. 访问 https://chainlist.org/
|
||||
2. 搜索 "Ink"
|
||||
3. 点击 "Add to MetaMask"
|
||||
|
||||
**手动添加方式:**
|
||||
|
||||
在钱包设置中添加自定义网络,填写以下信息:
|
||||
|
||||
| 参数 | 值 |
|
||||
|------|-----|
|
||||
| 网络名称 | INK |
|
||||
| RPC URL | https://rpc-gel.inkonchain.com |
|
||||
| Chain ID | 57073 |
|
||||
| 货币符号 | ETH |
|
||||
| 区块浏览器 | https://explorer.inkonchain.com |
|
||||
|
||||
### 步骤 3:获取 Gas 费用(ETH)
|
||||
|
||||
在 Ink 网络上进行任何操作都需要少量 ETH 作为 Gas 费用。
|
||||
|
||||
**获取方式:**
|
||||
|
||||
- **从 CEX 直接提现**:Kraken 支持零手续费提现到 Ink 网络
|
||||
- **跨链桥接**:使用 [Superbridge](https://superbridge.app/)、[Bungee](https://bungee.exchange/) 或 [Relay](https://relay.link/) 从其他链桥接 ETH 到 Ink
|
||||
|
||||
> 建议至少准备 0.01-0.05 ETH 用于支付 Gas 费用
|
||||
|
||||
### 步骤 4:存入交易资金
|
||||
|
||||
1. 在 Nado 网站导航到 **Portfolio** 页面
|
||||
2. 点击 **Deposit**
|
||||
3. 选择要存入的资产(支持 USDT0、wETH、USDC、kBTC、wBTC)
|
||||
4. 输入金额并确认交易
|
||||
|
||||
---
|
||||
|
||||
## 获取 Nado 鉴权信息(重要)
|
||||
|
||||
这是配置机器人最关键的一步。Nado 使用基于 EVM 的签名认证方式,你需要获取以下两个关键信息:
|
||||
|
||||
- **NADO_SIGNER_PRIVATE_KEY**:签名私钥
|
||||
- **NADO_SUBACCOUNT_OWNER**:子账户所有者地址
|
||||
|
||||
### 获取方式:从浏览器开发者工具提取
|
||||
|
||||
#### 步骤 1:登录 Nado 交易界面
|
||||
|
||||
1. 访问 https://app.nado.xyz
|
||||
2. 连接你的钱包并完成登录
|
||||
3. 确保你已经在 Nado 启用了一键交易功能并能正常下单
|
||||
|
||||
#### 步骤 2:打开浏览器开发者工具
|
||||
|
||||
- **Chrome / Edge**:按 `F12` 或 `Ctrl+Shift+I`(Mac 上是 `Cmd+Option+I`)
|
||||
- **Firefox**:按 `F12` 或 `Ctrl+Shift+I`
|
||||
- **Safari**:先在偏好设置中启用开发者菜单,然后按 `Cmd+Option+I`
|
||||
|
||||
#### 步骤 3:找到 Local Storage 中的私钥
|
||||
|
||||
1. 在开发者工具中,切换到 **Application** 标签(Chrome/Edge)或 **Storage** 标签(Firefox)
|
||||
2. 在左侧菜单找到 **Local Storage**
|
||||
3. 点击展开,找到 `https://app.nado.xyz`
|
||||
4. 在右侧列表中找到 **`nado.userSettings`** 这一项
|
||||
5. 点击这一项,查看其 Value(值)
|
||||
|
||||
#### 步骤 4:提取私钥
|
||||
|
||||
`nado.userSettings` 的值是一个 JSON 对象,大致结构如下:
|
||||
|
||||
```json
|
||||
"signingPreferenceBySubaccountKey": {
|
||||
"inkMainnet_default": {
|
||||
{
|
||||
"privateKey": "0x1234567890abcdef...",
|
||||
...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**你需要的是 `privateKey` 字段的值**,它是一个以 `0x` 开头的 64 位十六进制字符串。
|
||||
|
||||
将这个值复制下来,这就是你的 `NADO_SIGNER_PRIVATE_KEY`。
|
||||
|
||||
#### 步骤 5:获取子账户所有者地址
|
||||
|
||||
`NADO_SUBACCOUNT_OWNER` 就是你连接到 Nado 的钱包地址。
|
||||
|
||||
获取方式:
|
||||
1. 打开你的钱包(如 MetaMask)
|
||||
2. 复制你的钱包地址(以 `0x` 开头的 42 位地址)
|
||||
|
||||
这就是你的 `NADO_SUBACCOUNT_OWNER`。
|
||||
|
||||
### 关于 Linked Signer(进阶)
|
||||
|
||||
Nado 支持 "Linked Signer" 功能,允许你使用一个专门的签名密钥来代表你的主账户进行交易。这提供了额外的安全层:
|
||||
|
||||
- 主钱包私钥保持离线安全
|
||||
- Linked Signer 只有交易权限,无法提取资金
|
||||
- 可以随时撤销 Linked Signer
|
||||
|
||||
当你在 Nado 网站首次连接钱包时,系统会自动为你创建一个 Linked Signer,这个签名密钥就存储在浏览器的 Local Storage 中。
|
||||
|
||||
> **重要安全提示**:
|
||||
> - `NADO_SIGNER_PRIVATE_KEY` 是 Linked Signer 的私钥,不是你主钱包的私钥
|
||||
> - 这个私钥只能用于在 Nado 上签署交易,无法直接转移你的链上资产
|
||||
> - 但仍需妥善保管,不要分享给他人
|
||||
|
||||
---
|
||||
|
||||
## 配置 .env 文件
|
||||
|
||||
### 步骤 1:创建 .env 文件
|
||||
|
||||
在项目根目录下,复制示例配置文件:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
### 步骤 2:编辑 .env 文件
|
||||
|
||||
使用任意文本编辑器打开 `.env` 文件:
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
open -e .env
|
||||
|
||||
# Linux
|
||||
nano .env
|
||||
|
||||
# Windows
|
||||
notepad .env
|
||||
```
|
||||
|
||||
### 步骤 3:填写 Nado 配置
|
||||
|
||||
在 `.env` 文件中找到并修改以下配置项:
|
||||
|
||||
```bash
|
||||
# ============================================
|
||||
# 交易所选择
|
||||
# ============================================
|
||||
EXCHANGE=nado
|
||||
|
||||
# ============================================
|
||||
# Nado 交易所配置(必填)
|
||||
# ============================================
|
||||
|
||||
# 签名私钥 - 从浏览器 Local Storage 获取
|
||||
# 格式:以 0x 开头的 64 位十六进制字符串
|
||||
NADO_SIGNER_PRIVATE_KEY=0x你的私钥
|
||||
|
||||
# 子账户所有者地址 - 你的钱包地址
|
||||
# 格式:以 0x 开头的 42 位地址
|
||||
NADO_SUBACCOUNT_OWNER=0x你的钱包地址
|
||||
|
||||
# 子账户名称(可选,默认为 default)
|
||||
NADO_SUBACCOUNT_NAME=default
|
||||
|
||||
# 网络环境(可选)
|
||||
# inkMainnet = 主网(真实交易)
|
||||
# inkTestnet = 测试网(模拟交易)
|
||||
NADO_ENV=inkMainnet
|
||||
|
||||
# 交易品种(可选,默认 BTC-PERP)
|
||||
NADO_SYMBOL=BTC-PERP
|
||||
|
||||
# ============================================
|
||||
# 交易参数配置
|
||||
# ============================================
|
||||
|
||||
# 单笔交易数量(以 BTC 计)
|
||||
TRADE_AMOUNT=0.001
|
||||
|
||||
# 止损金额(USD)- 亏损超过此金额触发平仓
|
||||
LOSS_LIMIT=10
|
||||
|
||||
# 移动止盈触发金额(USD)
|
||||
TRAILING_PROFIT=5
|
||||
|
||||
# 移动止盈回撤比例(0.2 = 20%)
|
||||
TRAILING_CALLBACK_RATE=0.2
|
||||
```
|
||||
|
||||
### 完整的 Nado 配置示例
|
||||
|
||||
```bash
|
||||
# 交易所选择
|
||||
EXCHANGE=nado
|
||||
|
||||
# Nado 凭证
|
||||
NADO_SIGNER_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
|
||||
NADO_SUBACCOUNT_OWNER=0xAbCdEf1234567890AbCdEf1234567890AbCdEf12
|
||||
NADO_SUBACCOUNT_NAME=default
|
||||
NADO_ENV=inkMainnet
|
||||
NADO_SYMBOL=BTC-PERP
|
||||
|
||||
# 交易参数
|
||||
TRADE_AMOUNT=0.001
|
||||
|
||||
# 趋势策略
|
||||
LOSS_LIMIT=10
|
||||
TRAILING_PROFIT=5
|
||||
TRAILING_CALLBACK_RATE=0.2
|
||||
|
||||
# 波段策略
|
||||
SWING_DIRECTION=short
|
||||
SWING_STOP_LOSS_PCT=0.05 # 价格反向运动 5% 止损
|
||||
|
||||
# 做市策略参数(如果使用做市策略)
|
||||
LOSS_LIMIT=0.08
|
||||
MAKER_LOSS_LIMIT=0.08
|
||||
LIQUIDITY_MAKER_LOSS_LIMIT=0.08
|
||||
LIQUIDITY_MAKER_CLOSE_TICK_OFFSET=5
|
||||
MAKER_ENTRY_DEPTH_LEVEL=1
|
||||
```
|
||||
|
||||
## 启动交易机器人
|
||||
|
||||
### 方法一:交互式启动(推荐新手)
|
||||
|
||||
```bash
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
启动后会显示一个交互式菜单,使用方向键选择策略,按回车确认。
|
||||
|
||||
### 方法二:命令行直接启动
|
||||
|
||||
```bash
|
||||
# 启动趋势策略
|
||||
bun run index.ts --strategy trend --silent
|
||||
|
||||
# 启动做市策略
|
||||
bun run index.ts --strategy maker --silent
|
||||
```
|
||||
|
||||
### 方法三:使用 PM2 后台运行(推荐生产环境)
|
||||
|
||||
```bash
|
||||
# 安装 PM2
|
||||
bun add -d pm2
|
||||
|
||||
# 后台启动趋势策略
|
||||
bunx pm2 start bun --name ritmex-trend --cwd . --restart-delay 5000 -- run index.ts --strategy trend --silent
|
||||
|
||||
# 查看运行状态
|
||||
bunx pm2 list
|
||||
|
||||
# 查看日志
|
||||
bunx pm2 logs ritmex-trend
|
||||
|
||||
# 停止运行
|
||||
bunx pm2 stop ritmex-trend
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 策略说明与选择
|
||||
|
||||
### 趋势策略(Trend)
|
||||
|
||||
**适用场景**:单边行情,趋势明显的市场
|
||||
|
||||
**工作原理**:
|
||||
- 使用 SMA30(30 周期简单移动平均线)判断趋势
|
||||
- 价格突破均线时开仓
|
||||
- 内置止损和移动止盈
|
||||
|
||||
**配置参数**:
|
||||
```bash
|
||||
TRADE_AMOUNT=0.001 # 单笔交易量
|
||||
LOSS_LIMIT=10 # 止损金额(USD)
|
||||
TRAILING_PROFIT=5 # 移动止盈触发金额
|
||||
TRAILING_CALLBACK_RATE=0.2 # 回撤比例
|
||||
```
|
||||
|
||||
### 做市策略(Maker)
|
||||
|
||||
**适用场景**:震荡行情,低波动市场
|
||||
|
||||
**工作原理**:
|
||||
- 在买卖盘口双边挂单
|
||||
- 赚取买卖价差
|
||||
- 根据持仓自动调整挂单方向
|
||||
|
||||
**配置参数**:
|
||||
```bash
|
||||
MAKER_BID_OFFSET=0 # 买单价格偏移
|
||||
MAKER_ASK_OFFSET=0 # 卖单价格偏移
|
||||
MAKER_REFRESH_INTERVAL_MS=500 # 刷新间隔
|
||||
```
|
||||
|
||||
## 常见问题与排查
|
||||
|
||||
### 问题 1:启动时提示 "Missing NADO_SIGNER_PRIVATE_KEY"
|
||||
|
||||
**原因**:未正确配置签名私钥
|
||||
|
||||
**解决方案**:
|
||||
1. 确认 `.env` 文件存在于项目根目录
|
||||
2. 检查 `NADO_SIGNER_PRIVATE_KEY` 是否正确填写
|
||||
3. 确保私钥以 `0x` 开头
|
||||
|
||||
### 问题 2:启动时提示 "Missing NADO_SUBACCOUNT_OWNER"
|
||||
|
||||
**原因**:未配置子账户所有者地址
|
||||
|
||||
**解决方案**:
|
||||
1. 在 `.env` 中填写 `NADO_SUBACCOUNT_OWNER` 为你的钱包地址
|
||||
2. 也可以使用 `NADO_EVM_ADDRESS` 作为替代
|
||||
|
||||
### 问题 3:连接失败,无法获取账户信息
|
||||
|
||||
**可能原因及解决方案**:
|
||||
|
||||
1. **网络问题**:检查网络连接,确保能访问 Nado API
|
||||
2. **私钥错误**:重新从浏览器 Local Storage 获取正确的私钥
|
||||
3. **账户未激活**:确保在 Nado 网站上至少存入过资金
|
||||
4. **Linked Signer 未启用**:账户需要至少有 5 USDT 价值的资产才能使用 Linked Signer
|
||||
|
||||
### 问题 4:下单失败,提示精度错误
|
||||
|
||||
**原因**:价格或数量精度不符合交易所要求
|
||||
|
||||
**解决方案**:
|
||||
```bash
|
||||
# BTC-PERP 的标准精度
|
||||
PRICE_TICK=0.1 # 价格精度 0.1 USD
|
||||
QTY_STEP=0.001 # 数量精度 0.001 BTC
|
||||
```
|
||||
|
||||
### 问题 5:时间同步错误
|
||||
|
||||
**原因**:本地时间与服务器时间相差太大
|
||||
|
||||
**解决方案**:
|
||||
- macOS/Linux:`sudo ntpdate -u time.apple.com`
|
||||
- Windows:设置 → 时间和语言 → 同步时间
|
||||
|
||||
### 问题 6:Gas 费用不足
|
||||
|
||||
**原因**:Ink 网络上的 ETH 余额不足
|
||||
|
||||
**解决方案**:
|
||||
1. 通过跨链桥向 Ink 网络转入少量 ETH(0.01-0.05 ETH)
|
||||
2. 推荐使用 Superbridge 或 Relay 进行跨链
|
||||
|
||||
### 问题 7:找不到 Local Storage 中的私钥
|
||||
|
||||
**可能原因**:
|
||||
1. 尚未在 Nado 完成首次连接/操作
|
||||
2. 浏览器清除了缓存
|
||||
|
||||
**解决方案**:
|
||||
1. 重新访问 https://app.nado.xyz
|
||||
2. 连接钱包并进行一次操作(如查看账户)
|
||||
3. 再次检查 Local Storage
|
||||
|
||||
---
|
||||
|
||||
## 安全提示
|
||||
|
||||
1. **永远不要分享你的私钥**:`NADO_SIGNER_PRIVATE_KEY` 虽然不是主钱包私钥,但仍可用于在 Nado 上进行交易
|
||||
|
||||
2. **使用专用交易账户**:建议创建一个专门用于交易的新钱包,不要放置大量资产
|
||||
|
||||
3. **定期检查授权**:在钱包中定期检查并撤销不需要的 DApp 授权
|
||||
|
||||
4. **小额测试**:首次运行时使用小额资金测试,确认一切正常后再增加资金
|
||||
|
||||
5. **保护 .env 文件**:
|
||||
- 不要将 `.env` 文件提交到 Git
|
||||
- 不要分享给他人
|
||||
- 定期更换凭证
|
||||
|
||||
---
|
||||
|
||||
## 社区与支持
|
||||
|
||||
- **Telegram 交流群**:https://t.me/+4fdo0quY87o4Mjhh
|
||||
- **GitHub Issues**:https://github.com/discountry/ritmex-bot/issues
|
||||
- **Nado 官方文档**:https://docs.nado.xyz
|
||||
|
||||
---
|
||||
|
||||
## 风险提示
|
||||
|
||||
量化交易具备风险。请注意:
|
||||
|
||||
- 市场波动可能导致亏损
|
||||
- 技术故障可能导致订单执行异常
|
||||
- 请勿投入无法承受损失的资金
|
||||
- 建议先在测试网或小额账户中验证策略
|
||||
|
||||
祝交易顺利!
|
||||
@@ -0,0 +1,717 @@
|
||||
## StandX Perps Authentication
|
||||
|
||||
官网创建的 API 提供了
|
||||
|
||||
API Token 以及 Ed25519 Private Key,用于签名交易。
|
||||
|
||||
⚠️ This document is under construction.
|
||||
|
||||
This document explains how to obtain JWT access tokens for the StandX Perps API through wallet signatures.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Valid wallet address and corresponding private key
|
||||
- Development environment with `ed25519` algorithm support
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
### 1\. Prepare Wallet and Temporary ed25519 Key Pair
|
||||
|
||||
1. **Prepare Wallet**: Ensure you have a blockchain wallet with its address and private key.
|
||||
2. **Generate Temporary ed25519 Key Pair and `requestId`**
|
||||
|
||||
### 2\. Get Signature Data
|
||||
|
||||
Request signature data from the server:
|
||||
|
||||
> **Note**: Code examples provided below are for reference purposes only and demonstrate the general implementation approach. Adapt them to your specific production environment.
|
||||
|
||||
#### Using curl
|
||||
|
||||
```
|
||||
curl 'https://api.standx.com/v1/offchain/prepare-signin?chain=<chain>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-raw '{
|
||||
"address": "<your_wallet_address>",
|
||||
"requestId": "<base58_encoded_public_key>"
|
||||
}'
|
||||
```
|
||||
|
||||
#### TypeScript/ES6 Implementation Reference
|
||||
|
||||
#### Request Parameters
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| chain | string | Yes | Blockchain network: `bsc` or `solana` |
|
||||
| address | string | Yes | Wallet address |
|
||||
| requestId | string | Yes | Base58-encoded ed25519 public key from step 1 |
|
||||
|
||||
#### Success Response
|
||||
|
||||
```
|
||||
{
|
||||
"success": true,
|
||||
"signedData": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
}
|
||||
```
|
||||
|
||||
### 3\. Parse and Verify Signature Data
|
||||
|
||||
`signedData` is a JWT string that must be verified using StandX’s public key.
|
||||
|
||||
#### Get Verification Public Key
|
||||
|
||||
```
|
||||
# Using curl
|
||||
curl 'https://api.standx.com/v1/offchain/certs'
|
||||
```
|
||||
|
||||
#### Example signedData Payload
|
||||
|
||||
### 4\. Sign the Message
|
||||
|
||||
Sign `payload.message` with your wallet private key to generate the `signature`.
|
||||
|
||||
#### BSC (EVM) Implementation Reference
|
||||
|
||||
```
|
||||
import { ethers } from "ethers";
|
||||
|
||||
const provider = new ethers.JsonRpcProvider(
|
||||
"https://bsc-dataseed.binance.org/"
|
||||
);
|
||||
const privateKey = "<your_wallet_private_key>"; // Keep secure; use environment variables
|
||||
const wallet = new ethers.Wallet(privateKey, provider);
|
||||
|
||||
// Sign using the message from the parsed payload
|
||||
const signature = await wallet.signMessage(payload.message);
|
||||
```
|
||||
|
||||
#### Solana Implementation Reference
|
||||
|
||||
```
|
||||
import bs58 from "bs58";
|
||||
import { ed25519 } from "@noble/curves/ed25519";
|
||||
import { Keypair } from "@solana/web3.js";
|
||||
|
||||
const privateKey = "<your_base58_encoded_private_key>"; // Keep secure; use environment variables
|
||||
const walletKeypair = Keypair.fromSecretKey(bs58.decode(privateKey));
|
||||
|
||||
// Sign using the message from the parsed payload
|
||||
const messageBytes = new TextEncoder().encode(payload.message);
|
||||
const signatureBytes = ed25519.sign(
|
||||
messageBytes,
|
||||
walletKeypair.secretKey.slice(0, 32) // First 32 bytes are the private key
|
||||
);
|
||||
|
||||
// Solana requires a specific signature format
|
||||
const signature = Buffer.from(
|
||||
JSON.stringify({
|
||||
input: payload,
|
||||
output: {
|
||||
signedMessage: Array.from(messageBytes),
|
||||
signature: Array.from(signatureBytes),
|
||||
account: {
|
||||
publicKey: Array.from(walletKeypair.publicKey.toBytes()),
|
||||
},
|
||||
},
|
||||
})
|
||||
).toString("base64");
|
||||
```
|
||||
|
||||
### 5\. Get Access Token
|
||||
|
||||
Submit the `signature` and original `signedData` to the login endpoint.
|
||||
|
||||
**Optional Parameter:**
|
||||
|
||||
- `expiresSeconds` (number): Token expiration time in seconds. Defaults to `604800` (7 days) if not specified. This controls how long the JWT access token remains valid before requiring re-authentication.
|
||||
|
||||
> **Security Note**: For security best practices, avoid setting excessively long expiration times. Shorter token lifetimes reduce the risk of unauthorized access if a token is compromised. Consider your security requirements when configuring this value.
|
||||
|
||||
#### Using curl
|
||||
|
||||
#### TypeScript/ES6 Implementation Reference
|
||||
|
||||
#### Success Response
|
||||
|
||||
```
|
||||
{
|
||||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"address": "0x...",
|
||||
"alias": "user123",
|
||||
"chain": "bsc",
|
||||
"perpsAlpha": true
|
||||
}
|
||||
```
|
||||
|
||||
### 6\. Use Access Token
|
||||
|
||||
Use the obtained `token` for subsequent API requests by adding `Authorization: Bearer <token>` to the request headers.
|
||||
|
||||
## Body Signature Flow
|
||||
|
||||
### Basic Flow
|
||||
|
||||
1. Prepare a key pair
|
||||
2. Build message: `{version},{id},{timestamp},{payload}`
|
||||
3. Sign with private key
|
||||
4. Base64 encode signature
|
||||
5. Attach signature to request headers
|
||||
|
||||
```
|
||||
{
|
||||
...
|
||||
"authorization": "Bearer <token>",
|
||||
"x-request-sign-version": "v1",
|
||||
"x-request-id": "uuid",
|
||||
"x-request-timestamp": "timestamp",
|
||||
"x-request-signature": "signature",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Code example (only for reference):
|
||||
|
||||
```
|
||||
import { ed25519 } from "@noble/curves/ed25519";
|
||||
import { base58 } from "@scure/base";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
/**
|
||||
* Sign request and return Base64-encoded signature.
|
||||
*/
|
||||
function encodeRequestSignature(
|
||||
xRequestVersion: string,
|
||||
xRequestId: string,
|
||||
xRequestTimestamp: number,
|
||||
payload: string,
|
||||
signingKey: Uint8Array
|
||||
): string {
|
||||
// Build message to sign: "{version},{id},{timestamp},{payload}"
|
||||
const signMsg = \`${xRequestVersion},${xRequestId},${xRequestTimestamp},${payload}\`;
|
||||
|
||||
// Sign message with Ed25519 private key
|
||||
const messageBytes = Buffer.from(signMsg, "utf-8");
|
||||
const signature = ed25519.sign(messageBytes, signingKey);
|
||||
|
||||
// Base64 encode the signature
|
||||
return Buffer.from(signature).toString("base64");
|
||||
}
|
||||
|
||||
// --- Example Usage ---
|
||||
|
||||
// Generate Ed25519 key pair
|
||||
const privateKey = ed25519.utils.randomSecretKey();
|
||||
const publicKey = ed25519.getPublicKey(privateKey);
|
||||
|
||||
// Generate requestId (base58-encoded public key)
|
||||
const requestId = base58.encode(publicKey);
|
||||
|
||||
// Prepare request parameters
|
||||
const xRequestVersion = "v1";
|
||||
const xRequestId = uuidv4();
|
||||
const xRequestTimestamp = Date.now();
|
||||
|
||||
const payloadDict = {
|
||||
user_id: 12345,
|
||||
data: "some important information",
|
||||
};
|
||||
const payloadStr = JSON.stringify(payloadDict);
|
||||
|
||||
// Generate signature
|
||||
const signature = encodeRequestSignature(
|
||||
xRequestVersion,
|
||||
xRequestId,
|
||||
xRequestTimestamp,
|
||||
payloadStr,
|
||||
privateKey
|
||||
);
|
||||
|
||||
// Verify signature (optional)
|
||||
try {
|
||||
const verifyMsg = \`v1,${xRequestId},${xRequestTimestamp},${payloadStr}\`;
|
||||
const signatureBytes = Buffer.from(signature, "base64");
|
||||
const messageBytes = Buffer.from(verifyMsg, "utf-8");
|
||||
|
||||
const isValid = ed25519.verify(signatureBytes, messageBytes, publicKey);
|
||||
if (!isValid) throw new Error("Verification failed");
|
||||
} catch (error) {
|
||||
console.error("Signature verification error:", error.message);
|
||||
}
|
||||
|
||||
// Send Request with Body Signature
|
||||
fetch("/api/request_need_body_signature", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
authorization: \`Bearer ${token}\`,
|
||||
"x-request-sign-version": "v1",
|
||||
"x-request-id": xRequestId,
|
||||
"x-request-timestamp": xRequestTimestamp.toString(),
|
||||
"x-request-signature": signature,
|
||||
},
|
||||
body: payloadStr,
|
||||
});
|
||||
```
|
||||
|
||||
### Complete Authentication Examples
|
||||
|
||||
For complete, runnable implementations, see the chain-specific examples:
|
||||
|
||||
- [EVM (BSC) Example](https://docs.standx.com/standx-api/perps-auth-evm-example) - Authentication using ethers.js for BSC and other EVM-compatible chains
|
||||
- [Solana (SVM) Example](https://docs.standx.com/standx-api/perps-auth-svm-example) - Authentication using @solana/web3.js for Solana
|
||||
|
||||
Last updated on
|
||||
|
||||
[About StandX API](https://docs.standx.com/standx-api/standx-api "About StandX API") [Perps Auth EVM Example](https://docs.standx.com/standx-api/perps-auth-evm-example "Perps Auth EVM Example")
|
||||
|
||||
## StandX Perps Authentication - EVM Example
|
||||
|
||||
This example demonstrates how to authenticate with the StandX Perps API using an EVM-compatible wallet (e.g., BSC).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js environment with TypeScript support
|
||||
- EVM wallet with private key
|
||||
- Required packages:
|
||||
```
|
||||
npm install @noble/curves @scure/base ethers
|
||||
```
|
||||
|
||||
## Complete Implementation
|
||||
|
||||
```
|
||||
import { ed25519 } from "@noble/curves/ed25519";
|
||||
import { base58 } from "@scure/base";
|
||||
import { ethers } from "ethers";
|
||||
|
||||
// Types
|
||||
export type Chain = "bsc" | "solana";
|
||||
|
||||
export interface SignedData {
|
||||
domain: string;
|
||||
uri: string;
|
||||
statement: string;
|
||||
version: string;
|
||||
chainId: number;
|
||||
nonce: string;
|
||||
address: string;
|
||||
requestId: string;
|
||||
issuedAt: string;
|
||||
message: string;
|
||||
exp: number;
|
||||
iat: number;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
address: string;
|
||||
alias: string;
|
||||
chain: string;
|
||||
perpsAlpha: boolean;
|
||||
}
|
||||
|
||||
export interface RequestSignatureHeaders {
|
||||
"x-request-sign-version": string;
|
||||
"x-request-id": string;
|
||||
"x-request-timestamp": string;
|
||||
"x-request-signature": string;
|
||||
}
|
||||
|
||||
// Authentication Class
|
||||
export class StandXAuth {
|
||||
private ed25519PrivateKey: Uint8Array;
|
||||
private ed25519PublicKey: Uint8Array;
|
||||
private requestId: string;
|
||||
private baseUrl = "https://api.standx.com";
|
||||
|
||||
constructor() {
|
||||
const privateKey = ed25519.utils.randomSecretKey();
|
||||
this.ed25519PrivateKey = privateKey;
|
||||
this.ed25519PublicKey = ed25519.getPublicKey(privateKey);
|
||||
this.requestId = base58.encode(this.ed25519PublicKey);
|
||||
}
|
||||
|
||||
async authenticate(
|
||||
chain: Chain,
|
||||
walletAddress: string,
|
||||
signMessage: (msg: string) => Promise<string>
|
||||
): Promise<LoginResponse> {
|
||||
const signedDataJwt = await this.prepareSignIn(chain, walletAddress);
|
||||
const payload = this.parseJwt<SignedData>(signedDataJwt);
|
||||
const signature = await signMessage(payload.message);
|
||||
return this.login(chain, signature, signedDataJwt);
|
||||
}
|
||||
|
||||
private async prepareSignIn(chain: Chain, address: string): Promise<string> {
|
||||
const res = await fetch(
|
||||
\`${this.baseUrl}/v1/offchain/prepare-signin?chain=${chain}\`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ address, requestId: this.requestId }),
|
||||
}
|
||||
);
|
||||
const data = await res.json();
|
||||
if (!data.success) throw new Error("Failed to prepare sign-in");
|
||||
return data.signedData;
|
||||
}
|
||||
|
||||
private async login(
|
||||
chain: Chain,
|
||||
signature: string,
|
||||
signedData: string,
|
||||
expiresSeconds: number = 604800 // default: 7 days
|
||||
): Promise<LoginResponse> {
|
||||
const res = await fetch(
|
||||
\`${this.baseUrl}/v1/offchain/login?chain=${chain}\`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ signature, signedData, expiresSeconds }),
|
||||
}
|
||||
);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
signRequest(
|
||||
payload: string,
|
||||
requestId: string,
|
||||
timestamp: number
|
||||
): RequestSignatureHeaders {
|
||||
const version = "v1";
|
||||
const message = \`${version},${requestId},${timestamp},${payload}\`;
|
||||
const signature = ed25519.sign(
|
||||
Buffer.from(message, "utf-8"),
|
||||
this.ed25519PrivateKey
|
||||
);
|
||||
|
||||
return {
|
||||
"x-request-sign-version": version,
|
||||
"x-request-id": requestId,
|
||||
"x-request-timestamp": timestamp.toString(),
|
||||
"x-request-signature": Buffer.from(signature).toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
private parseJwt<T>(token: string): T {
|
||||
const base64Url = token.split(".")[1];
|
||||
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
||||
return JSON.parse(Buffer.from(base64, "base64").toString("utf-8"));
|
||||
}
|
||||
}
|
||||
|
||||
// Usage Example
|
||||
async function main() {
|
||||
// Initialize auth
|
||||
const auth = new StandXAuth();
|
||||
|
||||
// Setup wallet
|
||||
const provider = new ethers.JsonRpcProvider(
|
||||
"https://bsc-dataseed.binance.org/"
|
||||
);
|
||||
const privateKey = process.env.WALLET_PRIVATE_KEY!;
|
||||
const wallet = new ethers.Wallet(privateKey, provider);
|
||||
|
||||
// Authenticate
|
||||
const loginResponse = await auth.authenticate(
|
||||
"bsc",
|
||||
wallet.address,
|
||||
async (message) => wallet.signMessage(message)
|
||||
);
|
||||
|
||||
console.log("Access Token:", loginResponse.token);
|
||||
|
||||
// Sign a request
|
||||
const payload = JSON.stringify({
|
||||
symbol: "BTC-USD",
|
||||
side: "buy",
|
||||
order_type: "limit",
|
||||
qty: "0.1",
|
||||
price: "50000",
|
||||
time_in_force: "gtc",
|
||||
reduce_only: false,
|
||||
});
|
||||
|
||||
const headers = auth.signRequest(payload, crypto.randomUUID(), Date.now());
|
||||
|
||||
// Make authenticated request
|
||||
await fetch("https://perps.standx.com/api/new_order", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: \`Bearer ${loginResponse.token}\`,
|
||||
...headers,
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. **Wallet Setup**: Uses `ethers.js` to create a wallet from a private key
|
||||
2. **Message Signing**: EVM wallets sign the message directly using `wallet.signMessage()`
|
||||
3. **Signature Format**: The signature is returned as-is from the wallet (hex string)
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create a `.env` file with:
|
||||
|
||||
```
|
||||
WALLET_PRIVATE_KEY=your_private_key_here
|
||||
```
|
||||
|
||||
> **Security Note**: Never commit private keys to version control. Use environment variables or secure key management solutions.
|
||||
|
||||
[Perps Auth](https://docs.standx.com/standx-api/perps-auth "Perps Auth") [Perps Auth SVM Example](https://docs.standx.com/standx-api/perps-auth-svm-example "Perps Auth SVM Example")
|
||||
|
||||
## StandX Perps Authentication - Solana (SVM) Example
|
||||
|
||||
This example demonstrates how to authenticate with the StandX Perps API using a Solana wallet.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js environment with TypeScript support
|
||||
- Solana wallet with private key (base58-encoded)
|
||||
- Required packages:
|
||||
```
|
||||
npm install @noble/curves @scure/base @solana/web3.js bs58
|
||||
```
|
||||
|
||||
## Complete Implementation
|
||||
|
||||
```
|
||||
import { ed25519 } from "@noble/curves/ed25519";
|
||||
import { base58 } from "@scure/base";
|
||||
import bs58 from "bs58";
|
||||
import { Keypair } from "@solana/web3.js";
|
||||
|
||||
// Types
|
||||
export type Chain = "bsc" | "solana";
|
||||
|
||||
export interface SignedData {
|
||||
domain: string;
|
||||
uri: string;
|
||||
statement: string;
|
||||
version: string;
|
||||
chainId: number;
|
||||
nonce: string;
|
||||
address: string;
|
||||
requestId: string;
|
||||
issuedAt: string;
|
||||
message: string;
|
||||
exp: number;
|
||||
iat: number;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
address: string;
|
||||
alias: string;
|
||||
chain: string;
|
||||
perpsAlpha: boolean;
|
||||
}
|
||||
|
||||
export interface RequestSignatureHeaders {
|
||||
"x-request-sign-version": string;
|
||||
"x-request-id": string;
|
||||
"x-request-timestamp": string;
|
||||
"x-request-signature": string;
|
||||
}
|
||||
|
||||
// Authentication Class
|
||||
export class StandXAuth {
|
||||
private ed25519PrivateKey: Uint8Array;
|
||||
private ed25519PublicKey: Uint8Array;
|
||||
private requestId: string;
|
||||
private baseUrl = "https://api.standx.com";
|
||||
|
||||
constructor() {
|
||||
const privateKey = ed25519.utils.randomSecretKey();
|
||||
this.ed25519PrivateKey = privateKey;
|
||||
this.ed25519PublicKey = ed25519.getPublicKey(privateKey);
|
||||
this.requestId = base58.encode(this.ed25519PublicKey);
|
||||
}
|
||||
|
||||
async authenticate(
|
||||
chain: Chain,
|
||||
walletAddress: string,
|
||||
signMessage: (msg: string, payload: SignedData) => Promise<string>
|
||||
): Promise<LoginResponse> {
|
||||
const signedDataJwt = await this.prepareSignIn(chain, walletAddress);
|
||||
const payload = this.parseJwt<SignedData>(signedDataJwt);
|
||||
const signature = await signMessage(payload.message, payload);
|
||||
return this.login(chain, signature, signedDataJwt);
|
||||
}
|
||||
|
||||
private async prepareSignIn(chain: Chain, address: string): Promise<string> {
|
||||
const res = await fetch(
|
||||
\`${this.baseUrl}/v1/offchain/prepare-signin?chain=${chain}\`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ address, requestId: this.requestId }),
|
||||
}
|
||||
);
|
||||
const data = await res.json();
|
||||
if (!data.success) throw new Error("Failed to prepare sign-in");
|
||||
return data.signedData;
|
||||
}
|
||||
|
||||
private async login(
|
||||
chain: Chain,
|
||||
signature: string,
|
||||
signedData: string,
|
||||
expiresSeconds: number = 604800 // default: 7 days
|
||||
): Promise<LoginResponse> {
|
||||
const res = await fetch(
|
||||
\`${this.baseUrl}/v1/offchain/login?chain=${chain}\`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ signature, signedData, expiresSeconds }),
|
||||
}
|
||||
);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
signRequest(
|
||||
payload: string,
|
||||
requestId: string,
|
||||
timestamp: number
|
||||
): RequestSignatureHeaders {
|
||||
const version = "v1";
|
||||
const message = \`${version},${requestId},${timestamp},${payload}\`;
|
||||
const signature = ed25519.sign(
|
||||
Buffer.from(message, "utf-8"),
|
||||
this.ed25519PrivateKey
|
||||
);
|
||||
|
||||
return {
|
||||
"x-request-sign-version": version,
|
||||
"x-request-id": requestId,
|
||||
"x-request-timestamp": timestamp.toString(),
|
||||
"x-request-signature": Buffer.from(signature).toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
private parseJwt<T>(token: string): T {
|
||||
const base64Url = token.split(".")[1];
|
||||
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
||||
return JSON.parse(Buffer.from(base64, "base64").toString("utf-8"));
|
||||
}
|
||||
}
|
||||
|
||||
// Usage Example
|
||||
async function main() {
|
||||
// Initialize auth
|
||||
const auth = new StandXAuth();
|
||||
|
||||
// Setup wallet from base58-encoded private key
|
||||
const privateKey = process.env.SOLANA_PRIVATE_KEY!;
|
||||
const walletKeypair = Keypair.fromSecretKey(bs58.decode(privateKey));
|
||||
const walletAddress = walletKeypair.publicKey.toBase58();
|
||||
|
||||
// Authenticate
|
||||
const loginResponse = await auth.authenticate(
|
||||
"solana",
|
||||
walletAddress,
|
||||
async (message, payload) => {
|
||||
const messageBytes = new TextEncoder().encode(message);
|
||||
const signatureBytes = ed25519.sign(
|
||||
messageBytes,
|
||||
walletKeypair.secretKey.slice(0, 32) // First 32 bytes are the private key
|
||||
);
|
||||
|
||||
// Solana requires a specific signature format
|
||||
return Buffer.from(
|
||||
JSON.stringify({
|
||||
input: payload,
|
||||
output: {
|
||||
signedMessage: Array.from(messageBytes),
|
||||
signature: Array.from(signatureBytes),
|
||||
account: {
|
||||
publicKey: Array.from(walletKeypair.publicKey.toBytes()),
|
||||
},
|
||||
},
|
||||
})
|
||||
).toString("base64");
|
||||
}
|
||||
);
|
||||
|
||||
console.log("Access Token:", loginResponse.token);
|
||||
|
||||
// Sign a request
|
||||
const payload = JSON.stringify({
|
||||
symbol: "BTC-USD",
|
||||
side: "buy",
|
||||
order_type: "limit",
|
||||
qty: "0.1",
|
||||
price: "50000",
|
||||
time_in_force: "gtc",
|
||||
reduce_only: false,
|
||||
});
|
||||
|
||||
const headers = auth.signRequest(payload, crypto.randomUUID(), Date.now());
|
||||
|
||||
// Make authenticated request
|
||||
await fetch("https://perps.standx.com/api/new_order", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: \`Bearer ${loginResponse.token}\`,
|
||||
...headers,
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. **Wallet Setup**: Uses `@solana/web3.js` Keypair with a base58-encoded private key
|
||||
2. **Message Signing**: Uses `@noble/curves/ed25519` for Ed25519 signing with `walletKeypair.secretKey.slice(0, 32)` (first 32 bytes are the private key)
|
||||
3. **Signature Format**: Solana requires a specific JSON structure containing:
|
||||
- `input`: The original payload from the server
|
||||
- `output.signedMessage`: The message bytes as an array
|
||||
- `output.signature`: The signature bytes as an array
|
||||
- `output.account.publicKey`: The wallet’s public key bytes as an array
|
||||
This JSON is then base64-encoded before being sent to the server.
|
||||
|
||||
## Signature Format Explanation
|
||||
|
||||
Unlike EVM wallets that return a simple hex signature, Solana authentication requires a structured response:
|
||||
|
||||
```
|
||||
{
|
||||
input: payload, // Original SignedData from server
|
||||
output: {
|
||||
signedMessage: [...], // Message bytes as number array
|
||||
signature: [...], // Ed25519 signature bytes as number array
|
||||
account: {
|
||||
publicKey: [...] // Wallet public key bytes as number array
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This format allows the server to verify both the signature and the signing account.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Create a `.env` file with:
|
||||
|
||||
```
|
||||
SOLANA_PRIVATE_KEY=your_base58_encoded_private_key_here
|
||||
```
|
||||
|
||||
> **Security Note**: Never commit private keys to version control. Use environment variables or secure key management solutions.
|
||||
|
||||
[Perps Auth EVM Example](https://docs.standx.com/standx-api/perps-auth-evm-example "Perps Auth EVM Example") [Perps HTTP API](https://docs.standx.com/standx-api/perps-http "Perps HTTP API")
|
||||
@@ -0,0 +1,845 @@
|
||||
## StandX Perps HTTP API List
|
||||
|
||||
⚠️ This document is under construction.
|
||||
|
||||
## API Overview
|
||||
|
||||
### Base URL
|
||||
|
||||
```
|
||||
https://perps.standx.com
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
All endpoints except **public endpoints** require JWT authentication. Include the JWT token in the `Authorization` header:
|
||||
|
||||
```
|
||||
Authorization: Bearer <your_jwt_token>
|
||||
```
|
||||
|
||||
**Token Validity**: 7 days
|
||||
|
||||
#### Body Signature
|
||||
|
||||
Some endpoints require body signature. Add the following headers to signed requests:
|
||||
|
||||
```
|
||||
x-request-sign-version: v1
|
||||
x-request-id: <random_string>
|
||||
x-request-timestamp: <timestamp_in_milliseconds>
|
||||
x-request-signature: <your_body_signature>
|
||||
```
|
||||
|
||||
See [Authentication Guide](https://docs.standx.com/standx-api/perps-auth) for implementation details.
|
||||
|
||||
#### Session ID
|
||||
|
||||
For `new_order` and `cancel_order` requests, you will want to know the results of these requests after actual matching. To obtain these results, you need to add the following information to the header in these interface requests:
|
||||
|
||||
```
|
||||
x-session-id: <your_custom_session_id>
|
||||
```
|
||||
|
||||
Note that this session\_id needs to be consistent with the session\_id used in your ws-client.
|
||||
|
||||
### Request Format
|
||||
|
||||
- **`int` parameters** (e.g., timestamp) are expected as JSON integers, not strings
|
||||
- **`decimal` parameters** (e.g., price) are expected as JSON strings, not floats
|
||||
|
||||
## Trade Endpoints
|
||||
|
||||
### Create New Order
|
||||
|
||||
`POST /api/new_order`
|
||||
|
||||
**Note**: A successful response indicates the order was submitted, not necessarily executed. Some orders (e.g., ALO) may be rejected during matching if conditions are not met. Subscribe to [Order Response Stream](https://docs.standx.com/standx-api/perps-ws#order-response-stream) for real-time execution status.
|
||||
|
||||
To receive order updates via [Order Response Stream](https://docs.standx.com/standx-api/perps-ws#order-response-stream), add the `x-session-id` header to your request. This session\_id must be consistent with the session\_id used in your ws-client.
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| side | enum | Order side (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| order\_type | enum | Order type (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| qty | decimal | Order quantity |
|
||||
| time\_in\_force | enum | Time in force (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| reduce\_only | boolean | Only reduce position if `true` |
|
||||
|
||||
**Optional Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| price | decimal | Order price (required for limit orders) |
|
||||
| cl\_ord\_id | string | Client order ID (auto-generated if omitted) |
|
||||
| margin\_mode | enum | Margin mode (see [Reference](https://docs.standx.com/standx-api/perps-reference)). Must match position |
|
||||
| leverage | int | Leverage value. Must match position |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"symbol": "BTC-USD",
|
||||
"side": "buy",
|
||||
"order_type": "limit",
|
||||
"qty": "0.1",
|
||||
"price": "50000",
|
||||
"time_in_force": "gtc",
|
||||
"reduce_only": false
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "xxx-xxx-xxx"
|
||||
}
|
||||
```
|
||||
|
||||
### Cancel Order
|
||||
|
||||
`POST /api/cancel_order`
|
||||
|
||||
To receive order updates via [Order Response Stream](https://docs.standx.com/standx-api/perps-ws#order-response-stream), add the `x-session-id` header to your request. This session\_id must be consistent with the session\_id used in your ws-client.
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Parameters**
|
||||
|
||||
> At least one of `order_id` or `cl_ord_id` is required.
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order\_id | int | Order ID to cancel |
|
||||
| cl\_ord\_id | string | Client order ID to cancel |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"order_id": 2424844
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "xxx-xxx-xxx"
|
||||
}
|
||||
```
|
||||
|
||||
### Cancel Multiple Orders
|
||||
|
||||
`POST /api/cancel_orders`
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Parameters**
|
||||
|
||||
> At least one of `order_id_list` or `cl_ord_id_list` is required.
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order\_id\_list | int\[\] | Order IDs to cancel |
|
||||
| cl\_ord\_id\_list | string\[\] | Client order IDs to cancel |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"order_id_list": [2424844]
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
[]
|
||||
```
|
||||
|
||||
### Change Leverage
|
||||
|
||||
`POST /api/change_leverage`
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| leverage | int | New leverage value |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"symbol": "BTC-USD",
|
||||
"leverage": 10
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "xxx-xxx-xxx"
|
||||
}
|
||||
```
|
||||
|
||||
### Change Margin Mode
|
||||
|
||||
`POST /api/change_margin_mode`
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| margin\_mode | enum | Margin mode (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"symbol": "BTC-USD",
|
||||
"margin_mode": "cross"
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "xxx-xxx-xxx"
|
||||
}
|
||||
```
|
||||
|
||||
## User Endpoints
|
||||
|
||||
### Transfer Margin
|
||||
|
||||
`POST /api/transfer_margin`
|
||||
|
||||
**Authentication Required** • **Body Signature Required**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| amount\_in | decimal | Amount to transfer |
|
||||
|
||||
**Request Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"symbol": "BTC-USD",
|
||||
"amount_in": "1000.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "xxx-xxx-xxx"
|
||||
}
|
||||
```
|
||||
|
||||
### Query Order
|
||||
|
||||
`GET /api/query_order`
|
||||
|
||||
**⚠️ NOTE**: Orders may be rejected due mis-qualification due async matching network structure. To receive the order updates in real-time, please check [Order Response Stream](https://docs.standx.com/standx-api/perps-ws#order-response-stream).
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Query Parameters**
|
||||
|
||||
> At least one of `order_id` or `cl_ord_id` is required.
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| order\_id | int | Order ID to query |
|
||||
| cl\_ord\_id | string | Client order ID to query |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"avail_locked": "3.071880000",
|
||||
"cl_ord_id": "01K2BK4ZKQE0C308SRD39P8N9Z",
|
||||
"closed_block": -1,
|
||||
"created_at": "2025-08-11T03:35:25.559151Z",
|
||||
"created_block": -1,
|
||||
"fill_avg_price": "0",
|
||||
"fill_qty": "0",
|
||||
"id": 1820682,
|
||||
"leverage": "10",
|
||||
"liq_id": 0,
|
||||
"margin": "0",
|
||||
"order_type": "limit",
|
||||
"payload": null,
|
||||
"position_id": 15,
|
||||
"price": "121900.00",
|
||||
"qty": "0.060",
|
||||
"reduce_only": false,
|
||||
"remark": "",
|
||||
"side": "sell",
|
||||
"source": "user",
|
||||
"status": "open",
|
||||
"symbol": "BTC-USD",
|
||||
"time_in_force": "gtc",
|
||||
"updated_at": "2025-08-11T03:35:25.559151Z",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
```
|
||||
|
||||
### Query User Orders
|
||||
|
||||
`GET /api/query_orders`
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Query Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| status | enum | Order status (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| order\_type | enum | Order type (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| start | string | Start time in ISO 8601 format |
|
||||
| end | string | End time in ISO 8601 format |
|
||||
| last\_id | number | Last order ID for pagination |
|
||||
| limit | number | Results limit (default: 100, max: 500) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"page_size": 1,
|
||||
"result": [
|
||||
{
|
||||
"avail_locked": "3.071880000",
|
||||
"cl_ord_id": "01K2BK4ZKQE0C308SRD39P8N9Z",
|
||||
"closed_block": -1,
|
||||
"created_at": "2025-08-11T03:35:25.559151Z",
|
||||
"created_block": -1,
|
||||
"fill_avg_price": "0",
|
||||
"fill_qty": "0",
|
||||
"id": 1820682,
|
||||
"leverage": "10",
|
||||
"liq_id": 0,
|
||||
"margin": "0",
|
||||
"order_type": "limit",
|
||||
"payload": null,
|
||||
"position_id": 15,
|
||||
"price": "121900.00",
|
||||
"qty": "0.060",
|
||||
"reduce_only": false,
|
||||
"remark": "",
|
||||
"side": "sell",
|
||||
"source": "user",
|
||||
"status": "new",
|
||||
"symbol": "BTC-USD",
|
||||
"time_in_force": "gtc",
|
||||
"updated_at": "2025-08-11T03:35:25.559151Z",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
],
|
||||
"total": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Query User All Open Orders
|
||||
|
||||
`GET /api/query_open_orders`
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Query Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| limit | number | Results limit (default: 500, max: 1200) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"page_size": 1,
|
||||
"result": [
|
||||
{
|
||||
"avail_locked": "3.071880000",
|
||||
"cl_ord_id": "01K2BK4ZKQE0C308SRD39P8N9Z",
|
||||
"closed_block": -1,
|
||||
"created_at": "2025-08-11T03:35:25.559151Z",
|
||||
"created_block": -1,
|
||||
"fill_avg_price": "0",
|
||||
"fill_qty": "0",
|
||||
"id": 1820682,
|
||||
"leverage": "10",
|
||||
"liq_id": 0,
|
||||
"margin": "0",
|
||||
"order_type": "limit",
|
||||
"payload": null,
|
||||
"position_id": 15,
|
||||
"price": "121900.00",
|
||||
"qty": "0.060",
|
||||
"reduce_only": false,
|
||||
"remark": "",
|
||||
"side": "sell",
|
||||
"source": "user",
|
||||
"status": "new",
|
||||
"symbol": "BTC-USD",
|
||||
"time_in_force": "gtc",
|
||||
"updated_at": "2025-08-11T03:35:25.559151Z",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
],
|
||||
"total": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Query User Trades
|
||||
|
||||
`GET /api/query_trades`
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Query Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| last\_id | number | Last trade ID for pagination |
|
||||
| side | string | Order side (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| start | string | Start time in ISO 8601 format |
|
||||
| end | string | End time in ISO 8601 format |
|
||||
| limit | number | Results limit (default: 100, max: 500) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"page_size": 1,
|
||||
"result": [
|
||||
{
|
||||
"created_at": "2025-08-11T03:36:19.352620Z",
|
||||
"fee_asset": "DUSD",
|
||||
"fee_qty": "0.121900",
|
||||
"id": 409870,
|
||||
"order_id": 1820682,
|
||||
"pnl": "1.62040",
|
||||
"price": "121900",
|
||||
"qty": "0.01",
|
||||
"side": "sell",
|
||||
"symbol": "BTC-USD",
|
||||
"updated_at": "2025-08-11T03:36:19.352620Z",
|
||||
"user": "bsc_0x...",
|
||||
"value": "1219.00"
|
||||
}
|
||||
],
|
||||
"total": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Query Position Config
|
||||
|
||||
`GET /api/query_position_config`
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"symbol": "BTC-USD",
|
||||
"leverage": 10,
|
||||
"margin_mode": "cross"
|
||||
}
|
||||
```
|
||||
|
||||
### Query User Positions
|
||||
|
||||
`GET /api/query_positions`
|
||||
|
||||
**Authentication Required**
|
||||
|
||||
**Query Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"bankruptcy_price": "109608.01",
|
||||
"created_at": "2025-08-10T09:05:50.265265Z",
|
||||
"entry_price": "121737.96",
|
||||
"entry_value": "114433.68240",
|
||||
"holding_margin": "11443.3682400",
|
||||
"id": 15,
|
||||
"initial_margin": "11443.36824",
|
||||
"leverage": "10",
|
||||
"liq_price": "112373.50",
|
||||
"maint_margin": "2860.30367500",
|
||||
"margin_asset": "DUSD",
|
||||
"margin_mode": "isolated",
|
||||
"mark_price": "121715.05",
|
||||
"mmr": "3.993223845366698695025800014",
|
||||
"position_value": "114412.14700",
|
||||
"qty": "0.940",
|
||||
"realized_pnl": "31.61532",
|
||||
"status": "open",
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T03:41:40.922818Z",
|
||||
"updated_at": "2025-08-10T09:05:50.265265Z",
|
||||
"upnl": "-21.53540",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Query User Balances
|
||||
|
||||
- **Endpoint**: `/api/query_balance`
|
||||
- **Method**: `GET`
|
||||
- **Authentication**: Required
|
||||
- **Description**: Unified balance snapshot.
|
||||
- **Response Fields**:
|
||||
| Name | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| isolated\_balance | decimal | Isolated wallet total |
|
||||
| isolated\_upnl | decimal | Isolated unrealized PnL |
|
||||
| cross\_balance | decimal | Cross wallet free balance |
|
||||
| cross\_margin | decimal | Cross margin used (executed positions only) |
|
||||
| cross\_upnl | decimal | Cross unrealized PnL |
|
||||
| locked | decimal | Order lock (margin + fee), already includes safety factor b |
|
||||
| cross\_available | decimal | cross\_balance - cross\_margin - locked + cross\_upnl |
|
||||
| balance | decimal | Total account assets = cross\_balance + isolated\_balance |
|
||||
| upnl | decimal | Total unrealized PnL = cross\_upnl + isolated\_upnl |
|
||||
| equity | decimal | Account equity = balance + upnl |
|
||||
| pnl\_freeze | decimal | 24h realized PnL (for display) |
|
||||
- **Response Example**:
|
||||
```
|
||||
{
|
||||
"isolated_balance": "11443.3682400",
|
||||
"isolated_upnl": "-21.53540",
|
||||
"cross_balance": "1088575.259316737",
|
||||
"cross_margin": "2860.30367500",
|
||||
"cross_upnl": "31.61532",
|
||||
"locked": "0.000000000",
|
||||
"cross_available": "1085746.571",
|
||||
"balance": "1100018.627556737",
|
||||
"upnl": "10.07992",
|
||||
"equity": "1100028.707476657",
|
||||
"pnl_freeze": "31.61532"
|
||||
}
|
||||
```
|
||||
|
||||
> Notes:
|
||||
>
|
||||
> - `cross_available` may be negative depending on PnL and locks;
|
||||
|
||||
## Public Endpoints
|
||||
|
||||
### Query Symbol Info
|
||||
|
||||
`GET /api/query_symbol_info`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"base_asset": "BTC",
|
||||
"base_decimals": 9,
|
||||
"created_at": "2025-07-10T05:15:32.089568Z",
|
||||
"def_leverage": "10",
|
||||
"depth_ticks": "0.01,0.1,1",
|
||||
"enabled": true,
|
||||
"maker_fee": "0.0001",
|
||||
"max_leverage": "20",
|
||||
"max_open_orders": "100",
|
||||
"max_order_qty": "100",
|
||||
"max_position_size": "1000",
|
||||
"min_order_qty": "0.001",
|
||||
"price_cap_ratio": "0.3",
|
||||
"price_floor_ratio": "0.3",
|
||||
"price_tick_decimals": 2,
|
||||
"qty_tick_decimals": 3,
|
||||
"quote_asset": "DUSD",
|
||||
"quote_decimals": 9,
|
||||
"symbol": "BTC-USD",
|
||||
"taker_fee": "0.0004",
|
||||
"updated_at": "2025-07-10T05:15:32.089568Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Query Symbol Market
|
||||
|
||||
`GET /api/query_symbol_market`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"base": "BTC",
|
||||
"funding_rate": "0.00010000",
|
||||
"high_price_24h": "122164.08",
|
||||
"index_price": "121601.158461",
|
||||
"last_price": "121599.94",
|
||||
"low_price_24h": "114098.44",
|
||||
"mark_price": "121602.43",
|
||||
"mid_price": "121599.99",
|
||||
"next_funding_time": "2025-08-11T08:00:00Z",
|
||||
"open_interest": "15.948",
|
||||
"quote": "DUSD",
|
||||
"spread": ["121599.94", "121600.04"],
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T03:44:40.922233Z",
|
||||
"volume_24h": "9030.51800000000002509"
|
||||
}
|
||||
```
|
||||
|
||||
### Query Symbol Price
|
||||
|
||||
`GET /api/query_symbol_price`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"base": "BTC",
|
||||
"index_price": "121601.158461",
|
||||
"last_price": "121599.94",
|
||||
"mark_price": "121602.43",
|
||||
"mid_price": "121599.99",
|
||||
"quote": "DUSD",
|
||||
"spread_ask": "121600.04",
|
||||
"spread_bid": "121599.94",
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T03:44:40.922233Z"
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: `last_price`, `mid_price`, `spread_ask`, `spread_bid` may be null if no recent trades.
|
||||
|
||||
### Query Depth Book
|
||||
|
||||
`GET /api/query_depth_book`
|
||||
|
||||
**⚠️ Note: The sequence of price levels in the asks and bids arrays is not guaranteed. Please implement local sorting on the client side based on your specific requirements.**
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"asks": [
|
||||
["121895.81", "0.843"],
|
||||
["121896.11", "0.96"]
|
||||
],
|
||||
"bids": [
|
||||
["121884.01", "0.001"],
|
||||
["121884.31", "0.001"]
|
||||
],
|
||||
"symbol": "BTC-USD"
|
||||
}
|
||||
```
|
||||
|
||||
`GET /api/query_recent_trades`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"is_buyer_taker": true,
|
||||
"price": "121720.18",
|
||||
"qty": "0.01",
|
||||
"quote_qty": "1217.2018",
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T03:48:47.086505Z"
|
||||
},
|
||||
{
|
||||
"is_buyer_taker": true,
|
||||
"price": "121720.18",
|
||||
"qty": "0.01",
|
||||
"quote_qty": "1217.2018",
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T03:48:46.850415Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Query Funding Rates
|
||||
|
||||
`GET /api/query_funding_rates`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| start\_time | int | Start time in milliseconds |
|
||||
| end\_time | int | End time in milliseconds |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"symbol": "BTC-USD",
|
||||
"funding_rate": "0.0001",
|
||||
"index_price": "121601.158461",
|
||||
"mark_price": "121602.43",
|
||||
"premium": "0.0001",
|
||||
"time": "2025-08-11T03:48:47.086505Z",
|
||||
"created_at": "2025-08-11T03:48:47.086505Z",
|
||||
"updated_at": "2025-08-11T03:48:47.086505Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## Kline Endpoints
|
||||
|
||||
### Get Server Time
|
||||
|
||||
`GET /api/kline/time`
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
1620000000
|
||||
```
|
||||
|
||||
### Get Kline History
|
||||
|
||||
`GET /api/kline/history`
|
||||
|
||||
**Required Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| symbol | string | Trading pair (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
| from | u64 | Unix timestamp in seconds |
|
||||
| to | u64 | Unix timestamp in seconds |
|
||||
| resolution | enum | Resolution (see [Reference](https://docs.standx.com/standx-api/perps-reference)) |
|
||||
|
||||
**Optional Parameters**
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| countback | u64 | The required amount of bars to load |
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"s": "ok",
|
||||
"t": [1754897028, 1754897031],
|
||||
"c": [121897.95, 121903.04],
|
||||
"o": [121896.02, 121898.05],
|
||||
"h": [121897.95, 121903.15],
|
||||
"l": [121895.92, 121898.05],
|
||||
"v": [0.09, 10.542]
|
||||
}
|
||||
```
|
||||
|
||||
## Health Check
|
||||
|
||||
### Health
|
||||
|
||||
`GET /api/health`
|
||||
|
||||
**Response**:
|
||||
|
||||
```
|
||||
OK
|
||||
```
|
||||
|
||||
## Misc
|
||||
|
||||
### Region and Server Time
|
||||
|
||||
`GET https://geo.standx.com/v1/region`
|
||||
|
||||
**Response Example**:
|
||||
|
||||
```
|
||||
{
|
||||
"systemTime": 1761970177865,
|
||||
"region": "jp"
|
||||
}
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
For enums, constants, and error codes, see [API Reference](https://docs.standx.com/standx-api/perps-reference).
|
||||
|
||||
Last updated on
|
||||
|
||||
[Perps Auth SVM Example](https://docs.standx.com/standx-api/perps-auth-svm-example "Perps Auth SVM Example") [Perps WebSocket API](https://docs.standx.com/standx-api/perps-ws "Perps WebSocket API")
|
||||
@@ -0,0 +1,18 @@
|
||||
## About StandX API
|
||||
|
||||
StandX provides REST and WebSocket APIs for perpetual futures trading. Access real-time market data, manage positions, execute trades, and monitor your portfolio programmatically.
|
||||
|
||||
## Documentation
|
||||
|
||||
- **[Authentication](https://docs.standx.com/standx-api/perps-auth)** - JWT authentication and request signing guide
|
||||
- **[HTTP API](https://docs.standx.com/standx-api/perps-http)** - Complete REST endpoint reference for trading, user data, and market information
|
||||
- **[WebSocket API](https://docs.standx.com/standx-api/perps-ws)** - Real-time data streams and event subscriptions
|
||||
- **[API Reference](https://docs.standx.com/standx-api/perps-reference)** - Enums, constants, and error codes
|
||||
|
||||
Base URL: `https://perps.standx.com`
|
||||
|
||||
Get started by obtaining your JWT token through wallet signature authentication.
|
||||
|
||||
Last updated on
|
||||
|
||||
[Perps Auth](https://docs.standx.com/standx-api/perps-auth "Perps Auth")
|
||||
@@ -0,0 +1,357 @@
|
||||
# StandX 做市积分策略使用教程(超详细新手版)
|
||||
|
||||
本教程会 **手把手** 教你如何运行 StandX 做市积分策略。每一步都有详细说明,按顺序操作即可。
|
||||
|
||||
---
|
||||
|
||||
## 第一步:安装 Bun(运行环境)
|
||||
|
||||
本项目需要 Bun 才能运行。
|
||||
|
||||
### macOS / Linux 用户:
|
||||
打开终端,复制粘贴以下命令后按回车:
|
||||
```bash
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
```
|
||||
|
||||
### Windows 用户:
|
||||
打开 PowerShell,复制粘贴以下命令后按回车:
|
||||
```powershell
|
||||
powershell -c "irm bun.sh/install.ps1 | iex"
|
||||
```
|
||||
|
||||
安装完成后,**关闭终端,重新打开一个新的终端窗口**,然后输入:
|
||||
```bash
|
||||
bun -v
|
||||
```
|
||||
如果显示版本号(如 `1.2.x`),说明安装成功。
|
||||
|
||||
---
|
||||
|
||||
## 第二步:下载项目并安装依赖
|
||||
|
||||
```bash
|
||||
git clone https://github.com/discountry/ritmex-bot.git
|
||||
cd ritmex-bot
|
||||
bun install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 第三步:获取 StandX API Token(最重要的一步)
|
||||
|
||||
> ⚠️ **这一步是 90% 新手卡住的地方,请仔细阅读!**
|
||||
>
|
||||
> ⚠️ **这一步是 90% 新手卡住的地方,请仔细阅读!**
|
||||
>
|
||||
> ⚠️ **这一步是 90% 新手卡住的地方,请仔细阅读!**
|
||||
|
||||
策略需要两样东西才能帮你下单:
|
||||
1. **TOKEN**(API 令牌)
|
||||
2. **代理钱包私钥**(用于签名交易)
|
||||
|
||||
### 获取步骤(图文说明):
|
||||
|
||||
#### 3.1 打开 StandX 官方 API 创建页面
|
||||
|
||||
在浏览器打开这个网址:
|
||||
```
|
||||
https://standx.com/user/session
|
||||
```
|
||||
|
||||
> **现在可以直接在 StandX 官网创建 API Token 了!**
|
||||
|
||||
#### 3.2 连接你的钱包并登录
|
||||
|
||||
如果还没登录,先连接钱包并登录你的 StandX 账户。
|
||||
|
||||
#### 3.3 生成 API Token
|
||||
|
||||
点击页面上的 **"Generate API Token"** 按钮。
|
||||
|
||||
你会看到类似这样的信息:
|
||||
- **Token**(很长一串以 eyJ 开头的字符串)
|
||||
- **Ed25519 Private Key**(Base58 格式的私钥,类似 `HdsyJD7oWgT756124j3taSPGv...`)
|
||||
- **创建日期**(例如:2026-01-15)
|
||||
- **有效期天数**(例如:30 天)
|
||||
|
||||
> 🔴 **请把这些值复制保存下来!**
|
||||
>
|
||||
> 🔴 **请把这些值复制保存下来!**
|
||||
>
|
||||
> 🔴 **请把这些值复制保存下来!**
|
||||
|
||||
### 什么是 Ed25519 Private Key?
|
||||
|
||||
- 这是系统 **自动为你生成** 的一个 Ed25519 签名私钥
|
||||
- 它 **只用于签名交易请求**,不存放你的资金
|
||||
- 你的资产仍然在你自己的钱包里,非常安全
|
||||
- **你不需要手动创建**,生成 API Token 时系统会自动创建
|
||||
- 格式为 Base58 编码(类似 `HdsyJD7oWgT756124j3taSPGv17vo5u7FafDq3vrun4f`)
|
||||
|
||||
---
|
||||
|
||||
## 第四步:配置环境变量
|
||||
|
||||
在项目根目录创建一个 `.env` 文件(如果已存在就修改它)。
|
||||
|
||||
### 4.1 创建/编辑 .env 文件
|
||||
|
||||
**macOS / Linux:**
|
||||
```bash
|
||||
nano .env
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
用记事本打开项目文件夹,新建一个文本文件,命名为 `.env`(注意前面有个点)
|
||||
|
||||
### 4.2 填入以下内容
|
||||
|
||||
> ⚠️ **请务必把下面的示例值替换成你自己的!**
|
||||
>
|
||||
> ⚠️ **请务必把下面的示例值替换成你自己的!**
|
||||
>
|
||||
> ⚠️ **请务必把下面的示例值替换成你自己的!**
|
||||
|
||||
```bash
|
||||
# ===== 交易所设置 =====
|
||||
EXCHANGE=standx
|
||||
|
||||
# ===== 你的 API 凭证(第三步获取的) =====
|
||||
# 把下面的 "你的TOKEN" 替换成你生成的 Token(很长一串以 eyJ 开头的)
|
||||
STANDX_TOKEN=你的TOKEN
|
||||
|
||||
# 把下面的 "你的私钥" 替换成页面中显示的代理钱包私钥(按页面原样粘贴即可)
|
||||
STANDX_REQUEST_PRIVATE_KEY=你的代理钱包私钥
|
||||
|
||||
# ===== 交易品种 =====
|
||||
STANDX_SYMBOL=BTC-USD
|
||||
|
||||
# ===== 策略参数(新手直接用默认值就行) =====
|
||||
MAKER_POINTS_ORDER_AMOUNT=0.01
|
||||
MAKER_POINTS_CLOSE_THRESHOLD=0.1
|
||||
MAKER_POINTS_STOP_LOSS_USD=0
|
||||
MAKER_POINTS_MIN_REPRICE_BPS=3
|
||||
|
||||
# ===== 挂单档位开关 =====
|
||||
MAKER_POINTS_BAND_0_10=true
|
||||
MAKER_POINTS_BAND_10_30=true
|
||||
MAKER_POINTS_BAND_30_100=true
|
||||
|
||||
# ===== Token 过期时间配置(推荐配置) =====
|
||||
# 填写你创建 API Token 时显示的创建日期和有效期天数
|
||||
# 创建日期格式:YYYY-MM-DD(例如:2026-01-15)
|
||||
STANDX_TOKEN_CREATE_DATE=2026-01-15
|
||||
# 有效期天数(例如:30)
|
||||
STANDX_TOKEN_VALIDITY_DAYS=30
|
||||
|
||||
# ===== Telegram 通知配置(可选) =====
|
||||
# 配置后,策略会通过 Telegram 发送重要通知(订单成交、开仓、平仓、止损、Token过期等)
|
||||
# 如何获取 Bot Token:在 Telegram 搜索 @BotFather,发送 /newbot 创建机器人,获取 Token
|
||||
# 如何获取 Chat ID:在 Telegram 搜索 @userinfobot,发送任意消息即可看到你的 Chat ID
|
||||
# TELEGRAM_BOT_TOKEN=你的BotToken
|
||||
# TELEGRAM_CHAT_ID=你的ChatID
|
||||
# TELEGRAM_ACCOUNT_LABEL=我的账户(可选,用于区分多个账户的通知)
|
||||
```
|
||||
|
||||
### 正确填写示例
|
||||
|
||||
假设你生成的 API Token 信息是:
|
||||
- Token: `eyJhbGciOiJFUzI1NiIsImtpZCI6IlhnaEJQSVNuN0RQVHlMcWJtLUVHVkVhOU1lMFpwdU9iMk1Qc2gtbUFlencifQ...`
|
||||
- Ed25519 Private Key: `HdsyJD7oWgT756124j3taSPGv17vo5u7FafDq3vrun4f`
|
||||
- 创建日期: `2026-01-15`
|
||||
- 有效期: `30` 天
|
||||
|
||||
那么你的 `.env` 应该这样写:
|
||||
|
||||
```bash
|
||||
EXCHANGE=standx
|
||||
STANDX_TOKEN=eyJhbGciOiJFUzI1NiIsImtpZCI6IlhnaEJQSVNuN0RQVHlMcWJtLUVHVkVhOU1lMFpwdU9iMk1Qc2gtbUFlencifQ...
|
||||
STANDX_REQUEST_PRIVATE_KEY=HdsyJD7oWgT756124j3taSPGv17vo5u7FafDq3vrun4f
|
||||
STANDX_SYMBOL=BTC-USD
|
||||
MAKER_POINTS_ORDER_AMOUNT=0.01
|
||||
MAKER_POINTS_CLOSE_THRESHOLD=0.1
|
||||
MAKER_POINTS_STOP_LOSS_USD=0
|
||||
MAKER_POINTS_MIN_REPRICE_BPS=3
|
||||
MAKER_POINTS_BAND_0_10=true
|
||||
MAKER_POINTS_BAND_10_30=true
|
||||
MAKER_POINTS_BAND_30_100=true
|
||||
STANDX_TOKEN_CREATE_DATE=2026-01-15
|
||||
STANDX_TOKEN_VALIDITY_DAYS=30
|
||||
# TELEGRAM_BOT_TOKEN=你的BotToken
|
||||
# TELEGRAM_CHAT_ID=你的ChatID
|
||||
```
|
||||
|
||||
> 🔴 **不要加引号!不要加空格!直接粘贴值!**
|
||||
>
|
||||
> 🔴 **不要加引号!不要加空格!直接粘贴值!**
|
||||
>
|
||||
> 🔴 **不要加引号!不要加空格!直接粘贴值!**
|
||||
|
||||
---
|
||||
|
||||
## 第五步:启动策略
|
||||
|
||||
### 普通启动(看实时仪表盘)
|
||||
```bash
|
||||
bun run index.ts --strategy maker-points --exchange standx
|
||||
```
|
||||
|
||||
### 后台运行(推荐长期挂机)
|
||||
```bash
|
||||
bun run pm2:start:maker-points
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置参数说明
|
||||
|
||||
| 参数 | 含义 | 新手建议 |
|
||||
|------|------|----------|
|
||||
| `STANDX_TOKEN` | API 令牌 | 必填,从第三步获取 |
|
||||
| `STANDX_REQUEST_PRIVATE_KEY` | 代理钱包私钥 | 必填,从第三步获取 |
|
||||
| `STANDX_SYMBOL` | 交易品种 | 默认 `BTC-USD` |
|
||||
| `MAKER_POINTS_ORDER_AMOUNT` | 每笔挂单数量 | 建议 `0.01` 起步 |
|
||||
| `MAKER_POINTS_CLOSE_THRESHOLD` | 持仓达到多少开始平仓 | 设为 `0` 表示不自动平仓 |
|
||||
| `MAKER_POINTS_STOP_LOSS_USD` | 亏损多少美元强制平仓 | 设为 `0` 表示关闭止损 |
|
||||
| `MAKER_POINTS_BAND_*` | 三个挂单档位的开关 | 全部 `true` 即可 |
|
||||
| `STANDX_TOKEN_CREATE_DATE` | Token 创建日期 | 推荐配置,格式 YYYY-MM-DD |
|
||||
| `STANDX_TOKEN_VALIDITY_DAYS` | Token 有效期天数 | 推荐配置,与创建日期配合使用 |
|
||||
| `TELEGRAM_BOT_TOKEN` | Telegram 机器人 Token | 可选,用于接收通知 |
|
||||
| `TELEGRAM_CHAT_ID` | Telegram 聊天 ID | 可选,配合 Bot Token 使用 |
|
||||
| `TELEGRAM_ACCOUNT_LABEL` | Telegram 通知账户标签 | 可选,用于区分多个账户 |
|
||||
|
||||
### Token 过期时间配置详解
|
||||
|
||||
`STANDX_TOKEN_CREATE_DATE` 和 `STANDX_TOKEN_VALIDITY_DAYS` 用于设置 Token 的过期时间。配置后,策略会:
|
||||
|
||||
1. **Token 过期前 1 小时**:在日志中提醒你 Token 即将过期
|
||||
2. **Token 过期后**:
|
||||
- 如果有持仓:进入**平仓模式**,只允许平仓和止损,不再开新仓
|
||||
- 如果无持仓但有挂单:**自动取消所有挂单**
|
||||
- 如果无持仓无挂单:进入**静默模式**,只接收数据,不下单
|
||||
|
||||
**推荐配置方式(创建日期 + 有效期天数):**
|
||||
|
||||
在 StandX 官网生成 API Token 时,页面会显示创建日期和有效期天数,直接填入即可:
|
||||
|
||||
```bash
|
||||
# 创建日期(格式:YYYY-MM-DD)
|
||||
STANDX_TOKEN_CREATE_DATE=2026-01-15
|
||||
# 有效期天数
|
||||
STANDX_TOKEN_VALIDITY_DAYS=30
|
||||
```
|
||||
|
||||
**示例计算:**
|
||||
- 创建日期:2026-01-15
|
||||
- 有效期:30 天
|
||||
- 过期时间:2025-02-14 00:00:00 UTC
|
||||
|
||||
**兼容旧版配置(直接指定过期时间戳):**
|
||||
|
||||
如果你之前使用的是 `STANDX_TOKEN_EXPIRY`,仍然可以继续使用:
|
||||
|
||||
```bash
|
||||
# 方式1:使用时间戳(秒)
|
||||
STANDX_TOKEN_EXPIRY=1735689600
|
||||
|
||||
# 方式2:使用 ISO 日期字符串
|
||||
STANDX_TOKEN_EXPIRY=2025-01-01T00:00:00Z
|
||||
```
|
||||
|
||||
> 💡 **提示**:推荐使用新的创建日期 + 有效期天数方式,更直观易懂。
|
||||
|
||||
### Telegram 通知配置详解
|
||||
|
||||
配置 Telegram 通知后,策略会在以下情况发送通知:
|
||||
|
||||
- 📝 **订单成交**:挂单被成交时
|
||||
- 📈 **开仓**:持仓从 0 变为非 0 时
|
||||
- 📉 **平仓**:持仓从非 0 变为 0 时
|
||||
- 🛑 **止损触发**:触发止损平仓时
|
||||
- ⏰ **Token 过期**:Token 过期时
|
||||
|
||||
**配置步骤:**
|
||||
|
||||
1. **创建 Telegram 机器人**:
|
||||
- 在 Telegram 搜索 `@BotFather`
|
||||
- 发送 `/newbot` 命令
|
||||
- 按提示设置机器人名称和用户名
|
||||
- 获取 Bot Token(格式类似:`123456789:ABCdefGHIjklMNOpqrsTUVwxyz`)
|
||||
|
||||
2. **获取你的 Chat ID**:
|
||||
- 在 Telegram 搜索 `@userinfobot`
|
||||
- 发送任意消息
|
||||
- 机器人会返回你的 Chat ID(一串数字,例如:`123456789`)
|
||||
|
||||
3. **配置环境变量**:
|
||||
```bash
|
||||
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz
|
||||
TELEGRAM_CHAT_ID=123456789
|
||||
TELEGRAM_ACCOUNT_LABEL=我的账户(可选)
|
||||
```
|
||||
|
||||
4. **测试通知**:
|
||||
- 启动策略后,如果配置正确,会在 Token 过期或重要事件时收到通知
|
||||
- 如果收不到通知,检查 Bot Token 和 Chat ID 是否正确
|
||||
|
||||
> 💡 **提示**:`TELEGRAM_ACCOUNT_LABEL` 是可选的,如果你有多个账户在运行策略,可以用这个标签区分不同账户的通知。
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q:报错说 Token 无效怎么办?
|
||||
|
||||
重新去 https://standx.com/user/session 生成新的 API Token。Token 可能过期了。
|
||||
|
||||
### Q:Ed25519 Private Key 从哪来的?
|
||||
|
||||
在 StandX 官网(https://standx.com/user/session)点击 "Generate API Token" 按钮时会显示。
|
||||
私钥格式为 Base58 编码(类似 `HdsyJD7oWgT756124j3taSPGv17vo5u7FafDq3vrun4f`)。
|
||||
**你不需要自己创建,系统会自动生成!**
|
||||
**你不需要自己创建,系统会自动生成!**
|
||||
**你不需要自己创建,系统会自动生成!**
|
||||
|
||||
### Q:.env 文件放在哪?
|
||||
|
||||
放在项目根目录,就是 `ritmex-bot` 文件夹里,和 `package.json` 同一个目录。
|
||||
|
||||
### Q:为什么策略没有下单?
|
||||
|
||||
1. 检查账户里有没有足够的保证金
|
||||
2. 检查 TOKEN 和私钥是否正确填写
|
||||
3. 检查 .env 文件是否保存成功
|
||||
|
||||
### Q:担心平掉我手动开的仓位?
|
||||
|
||||
把 `MAKER_POINTS_CLOSE_THRESHOLD` 设为 `0` 或者设置成一个比你持仓大的数字。
|
||||
|
||||
### Q:如何知道 Token 什么时候过期?
|
||||
|
||||
配置 `STANDX_TOKEN_CREATE_DATE`(创建日期)和 `STANDX_TOKEN_VALIDITY_DAYS`(有效期天数),策略会在 Token 过期前 1 小时提醒你。这两个值在生成 API Token 时会显示。Token 过期后,如果有持仓会进入平仓模式,只允许平仓和止损。
|
||||
|
||||
### Q:Telegram 通知收不到怎么办?
|
||||
|
||||
1. 检查 `TELEGRAM_BOT_TOKEN` 和 `TELEGRAM_CHAT_ID` 是否正确填写
|
||||
2. 确保没有在 Bot Token 和 Chat ID 前后加引号或空格
|
||||
3. 在 Telegram 中先给机器人发送一条消息(任意内容),然后再启动策略
|
||||
4. 检查网络连接是否正常
|
||||
|
||||
---
|
||||
|
||||
## 安全提示
|
||||
|
||||
1. **绝对不要把 TOKEN 和私钥分享给任何人!**
|
||||
2. **绝对不要把 TOKEN 和私钥分享给任何人!**
|
||||
3. **绝对不要把 TOKEN 和私钥分享给任何人!**
|
||||
|
||||
代理钱包只用于签名,你的资产始终在你自己的主钱包里。但如果泄露了 TOKEN,别人可以用你的账户交易。
|
||||
|
||||
---
|
||||
|
||||
## 还是不会?
|
||||
|
||||
把你的报错信息截图发到 Telegram 群里,会有人帮你:
|
||||
|
||||
Telegram 群:https://t.me/+4fdo0quY87o4Mjhh
|
||||
@@ -0,0 +1,81 @@
|
||||
[API](https://docs.standx.com/standx-api/standx-api "API") Perps Reference
|
||||
|
||||
## StandX Perps API Reference
|
||||
|
||||
⚠️ This document is under construction.
|
||||
|
||||
## Enums
|
||||
|
||||
### Symbol
|
||||
|
||||
Available symbols (Trading pairs):
|
||||
|
||||
- `BTC-USD`
|
||||
|
||||
### Margin Mode
|
||||
|
||||
- `cross`
|
||||
- `isolated`
|
||||
|
||||
### Token
|
||||
|
||||
Available tokens:
|
||||
|
||||
- `DUSD`
|
||||
|
||||
### Order Side (side)
|
||||
|
||||
- `buy`
|
||||
- `sell`
|
||||
|
||||
### Order Type (order\_type)
|
||||
|
||||
- `limit`
|
||||
- `market`
|
||||
|
||||
### Order Status (status)
|
||||
|
||||
- `open`
|
||||
- `canceled`
|
||||
- `filled`
|
||||
- `rejected`
|
||||
- `untriggered`
|
||||
|
||||
### Time In Force (time\_in\_force)
|
||||
|
||||
| Value | Description |
|
||||
| --- | --- |
|
||||
| `gtc` | Good Til Canceled - Order remains active until canceled |
|
||||
| `ioc` | Immediate Or Cancel - Fill as much as possible immediately, cancel the rest |
|
||||
| `alo` | Add Liquidity Only - Order added to book without immediate execution; only executes as resting order |
|
||||
|
||||
### Resolution
|
||||
|
||||
Kline resolutions:
|
||||
|
||||
- `1T` - 1 tick
|
||||
- `3S` - 3 seconds
|
||||
- `1` - 1 minute
|
||||
- `5` - 5 minutes
|
||||
- `15` - 15 minutes
|
||||
- `60` - 60 minutes (1 hour)
|
||||
- `1D` - 1 day
|
||||
- `1W` - 1 week
|
||||
- `1M` - 1 month
|
||||
|
||||
## Error Responses
|
||||
|
||||
### Common Error Codes
|
||||
|
||||
| Code | Description |
|
||||
| --- | --- |
|
||||
| 400 | Bad Request - Invalid request parameters |
|
||||
| 401 | Unauthorized - Authentication required or invalid token |
|
||||
| 403 | Forbidden - Insufficient permissions |
|
||||
| 404 | Not Found - Resource not found |
|
||||
| 429 | Too Many Requests - Rate limit exceeded |
|
||||
| 500 | Internal Server Error - Server error |
|
||||
|
||||
Last updated on
|
||||
|
||||
[Perps WebSocket API](https://docs.standx.com/standx-api/perps-ws "Perps WebSocket API")
|
||||
@@ -0,0 +1,292 @@
|
||||
## StandX Perps WebSocket API List
|
||||
|
||||
The WebSocket API provides two streams: **Market Stream** for market data and user account updates, and **Order Response Stream** for asynchronous order creation responses.
|
||||
|
||||
⚠️ This document is under construction.
|
||||
|
||||
## Connection Management
|
||||
|
||||
Both WebSocket streams implement the following connection management behavior:
|
||||
|
||||
### Connection Duration Limit
|
||||
|
||||
- **Maximum Duration**: A single WebSocket connection can be maintained for a maximum of **24 hours**
|
||||
- After 24 hours, the connection will be automatically terminated
|
||||
- Clients should implement reconnection logic to handle this gracefully
|
||||
|
||||
### Ping/Pong Mechanism
|
||||
|
||||
- **Server Ping Interval**: The server sends a WebSocket Ping frame every 10 seconds
|
||||
- **Client Response**: Clients must respond with a Pong frame when receiving a Ping
|
||||
- **Timeout**: If the server does not receive a Ping/Pong response within 5 minutes, the connection will be terminated with error:
|
||||
```
|
||||
{
|
||||
"code": 408,
|
||||
"message": "disconnecting due to not receive Pong within 5 minute period"
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: Most modern browsers and WebSocket libraries automatically handle ping/pong frames, so you might not need to implement this manually. However, if your environment doesn’t support automatic ping/pong handling, you can proactively send ping frames to the server. Example using the npm `ws` library:
|
||||
|
||||
```
|
||||
import WebSocket from "ws";
|
||||
// ...
|
||||
private ws: WebSocket;
|
||||
//...
|
||||
ping(): void {
|
||||
this.lastPingTime = Date.now();
|
||||
this.ws.ping();
|
||||
console.log(\`[${new Date().toISOString()}] Ping server\`);
|
||||
}
|
||||
```
|
||||
|
||||
## Market Stream
|
||||
|
||||
Base Endpoint: `wss://perps.standx.com/ws-stream/v1`
|
||||
|
||||
### Available Channels
|
||||
|
||||
```
|
||||
[
|
||||
// public channels
|
||||
{ channel: "price", symbol: "<symbol>" },
|
||||
{ channel: "depth_book", symbol: "<symbol>" },
|
||||
{ channel: "public_trade", symbol: "<symbol>" },
|
||||
// user-level authenticated channels
|
||||
{ channel: "order" },
|
||||
{ channel: "position" },
|
||||
{ channel: "balance" },
|
||||
{ channel: "trade" },
|
||||
]
|
||||
```
|
||||
|
||||
### Subscribe to Depth Book
|
||||
|
||||
**⚠️ Note: The sequence of price levels in the asks and bids arrays is not guaranteed. Please implement local sorting on the client side based on your specific requirements.**
|
||||
|
||||
- Request:
|
||||
- Response:
|
||||
```
|
||||
{
|
||||
"seq": 3,
|
||||
"channel": "depth_book",
|
||||
"symbol": "BTC-USD",
|
||||
"data": {
|
||||
"asks": [
|
||||
["121896.02", "0.839"],
|
||||
["121896.32", "1.051"]
|
||||
],
|
||||
"bids": [
|
||||
["121884.22", "0.001"],
|
||||
["121884.52", "0.001"]
|
||||
],
|
||||
"symbol": "BTC-USD"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Subscribe to Symbol Price
|
||||
|
||||
- Request:
|
||||
- Response:
|
||||
```
|
||||
{
|
||||
"seq": 13,
|
||||
"channel": "price",
|
||||
"symbol": "BTC-USD",
|
||||
"data": {
|
||||
"base": "BTC",
|
||||
"index_price": "121890.651250",
|
||||
"last_price": "121897.95",
|
||||
"mark_price": "121897.56",
|
||||
"mid_price": "121898.00",
|
||||
"quote": "DUSD",
|
||||
"spread": ["121897.95", "121898.05"],
|
||||
"symbol": "BTC-USD",
|
||||
"time": "2025-08-11T07:23:50.923602474Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Authentication Request
|
||||
|
||||
#### Log in with JWT
|
||||
|
||||
- Request:
|
||||
```
|
||||
{
|
||||
"auth": {
|
||||
"token": "<your_jwt_token>",
|
||||
"streams": [{ "channel": "order" }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> `auth.streams` is **Optional**, which enables the user to subscribe to specific channels right after authentication.
|
||||
|
||||
- Response:
|
||||
```
|
||||
{ "seq": 1, "channel": "auth", "data": { "code": 200, "msg": "success" } }
|
||||
```
|
||||
|
||||
#### User Orders Subscription
|
||||
|
||||
- Request:
|
||||
- Response:
|
||||
```
|
||||
{
|
||||
"seq": 35,
|
||||
"channel": "order",
|
||||
"data": {
|
||||
"avail_locked": "0",
|
||||
"cl_ord_id": "01K2C9H93Y42RW8KD6RSVWVDVV",
|
||||
"closed_block": -1,
|
||||
"created_at": "2025-08-11T10:06:37.182464902Z",
|
||||
"created_block": -1,
|
||||
"fill_avg_price": "121245.21",
|
||||
"fill_qty": "1.000",
|
||||
"id": 2547027,
|
||||
"leverage": "15",
|
||||
"liq_id": 0,
|
||||
"margin": "8083.013333334",
|
||||
"order_type": "market",
|
||||
"payload": null,
|
||||
"position_id": 15,
|
||||
"price": "121245.20",
|
||||
"qty": "1.000",
|
||||
"reduce_only": false,
|
||||
"remark": "",
|
||||
"side": "buy",
|
||||
"source": "user",
|
||||
"status": "filled",
|
||||
"symbol": "BTC-USD",
|
||||
"time_in_force": "ioc",
|
||||
"updated_at": "2025-08-11T10:06:37.182465022Z",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### User Position Subscription
|
||||
|
||||
- Request:
|
||||
- Response:
|
||||
```
|
||||
{
|
||||
"seq": 36,
|
||||
"channel": "position",
|
||||
"data": {
|
||||
"created_at": "2025-08-10T09:05:50.265265Z",
|
||||
"entry_price": "121677.65",
|
||||
"entry_value": "2879988.1154631481396099405228",
|
||||
"id": 15,
|
||||
"initial_margin": "191999.219856667",
|
||||
"leverage": "15",
|
||||
"margin_asset": "DUSD",
|
||||
"margin_mode": "isolated",
|
||||
"qty": "23.669",
|
||||
"realized_pnl": "158.197103148",
|
||||
"status": "open",
|
||||
"symbol": "BTC-USD",
|
||||
"updated_at": "2025-08-10T09:05:50.265265Z",
|
||||
"user": "bsc_0x..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### User Balance Subscription
|
||||
|
||||
- Request:
|
||||
- Response:
|
||||
```
|
||||
{
|
||||
"seq": 37,
|
||||
"channel": "balance",
|
||||
"data": {
|
||||
"account_type": "perps",
|
||||
"created_at": "2025-08-09T09:36:54.504639Z",
|
||||
"free": "906946.976225666",
|
||||
"id": "bsc_0x...",
|
||||
"inbound": "0",
|
||||
"is_enabled": true,
|
||||
"kind": "user",
|
||||
"last_tx": "",
|
||||
"last_tx_updated_at": 0,
|
||||
"locked": "0.000000000",
|
||||
"occupied": "0",
|
||||
"outbound": "0",
|
||||
"ref_id": 0,
|
||||
"token": "DUSD",
|
||||
"total": "923207.752500717",
|
||||
"updated_at": "2025-08-09T09:36:54.504639Z",
|
||||
"version": 0,
|
||||
"wallet_id": "bsc_0x..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Order Response Stream
|
||||
|
||||
This WebSocket channel provides real-time order status updates for the `new order` API. Since order creation is asynchronous, this channel notifies clients about order responses, including ALO order rejections.
|
||||
|
||||
**Base Endpoint:**`wss://perps.standx.com/ws-api/v1`
|
||||
|
||||
### Request Structure
|
||||
|
||||
All WebSocket requests follow this structure:
|
||||
|
||||
**Fields:**
|
||||
|
||||
- `session_id`: UUID that remains consistent throughout the session
|
||||
- `request_id`: Unique UUID for each request
|
||||
- `method`: Operation to perform (`auth:login`, `order:new`, `order:cancel`)
|
||||
- `header`: Required for `order:new` and `order:cancel` methods (authentication headers)
|
||||
- `params`: JSON-stringified parameters specific to the method
|
||||
|
||||
### Methods
|
||||
|
||||
#### auth:login
|
||||
|
||||
Authenticate using JWT token.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
```
|
||||
{ "token": "<jwt>" }
|
||||
```
|
||||
|
||||
**Example Request:**
|
||||
|
||||
#### order:new
|
||||
|
||||
Create a new order. Parameters are the same as the HTTP API `new_order` payload.
|
||||
|
||||
#### order:cancel
|
||||
|
||||
Cancel an existing order. Parameters are the same as the HTTP API `cancel_order` payload.
|
||||
|
||||
### Order Response Format
|
||||
|
||||
**Success Response:**
|
||||
|
||||
```
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"request_id": "bccc2b23-03dc-4c2b-912f-4315ebbbb7e0"
|
||||
}
|
||||
```
|
||||
|
||||
**Rejection Response:**
|
||||
|
||||
```
|
||||
{
|
||||
"code": 400,
|
||||
"message": "alo order rejected",
|
||||
"request_id": "1187e114-1914-4111-8da1-2aaaa86bb1b9"
|
||||
}
|
||||
```
|
||||
|
||||
Last updated on
|
||||
|
||||
[Perps HTTP API](https://docs.standx.com/standx-api/perps-http "Perps HTTP API") [Perps Reference](https://docs.standx.com/standx-api/perps-reference "Perps Reference")
|
||||
@@ -0,0 +1,369 @@
|
||||
- The following base endpoints are available. Please use whichever works best for your setup:
|
||||
- **[https://api.binance.com](https://api.binance.com/)**
|
||||
- **[https://api-gcp.binance.com](https://api-gcp.binance.com/)**
|
||||
- **[https://api1.binance.com](https://api1.binance.com/)**
|
||||
- **[https://api2.binance.com](https://api2.binance.com/)**
|
||||
- **[https://api3.binance.com](https://api3.binance.com/)**
|
||||
- **[https://api4.binance.com](https://api4.binance.com/)**
|
||||
- The last 4 endpoints in the point above (`api1` - `api4`) should give better performance but have less stability.
|
||||
- Responses are in JSON by default. To receive responses in SBE, refer to the [SBE FAQ](https://developers.binance.com/docs/binance-spot-api-docs/faqs/sbe_faq) page.
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
|
||||
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
|
||||
- Data is returned in **chronological order**, unless noted otherwise.
|
||||
- Without `startTime` or `endTime`, returns the most recent items up to the limit.
|
||||
- With `startTime`, returns oldest items from `startTime` up to the limit.
|
||||
- With `endTime`, returns most recent items up to `endTime` and the limit.
|
||||
- With both, behaves like `startTime` but does not exceed `endTime`.
|
||||
- All time and timestamp related fields in the JSON responses are in **milliseconds by default.** To receive the information in microseconds, please add the header `X-MBX-TIME-UNIT:MICROSECOND` or `X-MBX-TIME-UNIT:microsecond`.
|
||||
- We support HMAC, RSA, and Ed25519 keys. For more information, please see [API Key types](https://developers.binance.com/docs/binance-spot-api-docs/faqs/api_key_types).
|
||||
- Timestamp parameters (e.g. `startTime`, `endTime`, `timestamp`) can be passed in milliseconds or microseconds.
|
||||
- For APIs that only send public market data, please use the base endpoint **[https://data-api.binance.vision](https://data-api.binance.vision/)**. Please refer to [Market Data Only](https://developers.binance.com/docs/binance-spot-api-docs/faqs/market_data_only) page.
|
||||
- If there are enums or terms you want clarification on, please see the [SPOT Glossary](https://developers.binance.com/docs/binance-spot-api-docs/faqs/spot_glossary) for more information.
|
||||
- APIs have a timeout of 10 seconds when processing a request. If a response from the Matching Engine takes longer than this, the API responds with "Timeout waiting for response from backend server. Send status unknown; execution status unknown." [(-1007 TIMEOUT)](https://developers.binance.com/docs/binance-spot-api-docs/errors#-1007-timeout)
|
||||
- This does not always mean that the request failed in the Matching Engine.
|
||||
- If the status of the request has not appeared in [User Data Stream](https://developers.binance.com/docs/binance-spot-api-docs/user-data-stream), please perform an API query for its status.
|
||||
- **Please avoid SQL keywords in requests** as they may trigger a security block by a WAF (Web Application Firewall) rule. See [https://www.binance.com/en/support/faq/detail/360004492232](https://www.binance.com/en/support/faq/detail/360004492232) for more details.
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
|
||||
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
|
||||
|
||||
Kline/Candlestick data
|
||||
GET /api/v3/klines
|
||||
|
||||
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
|
||||
|
||||
Weight: 2
|
||||
|
||||
Parameters:
|
||||
|
||||
Name Type Mandatory Description
|
||||
symbol STRING YES
|
||||
interval ENUM YES
|
||||
startTime LONG NO
|
||||
endTime LONG NO
|
||||
timeZone STRING NO Default: 0 (UTC)
|
||||
limit INT NO Default: 500; Maximum: 1000.
|
||||
Supported kline intervals (case-sensitive):
|
||||
|
||||
Interval interval value
|
||||
seconds 1s
|
||||
minutes 1m, 3m, 5m, 15m, 30m
|
||||
hours 1h, 2h, 4h, 6h, 8h, 12h
|
||||
days 1d, 3d
|
||||
weeks 1w
|
||||
months 1M
|
||||
Notes:
|
||||
|
||||
If startTime and endTime are not sent, the most recent klines are returned.
|
||||
Supported values for timeZone:
|
||||
Hours and minutes (e.g. -1:00, 05:45)
|
||||
Only hours (e.g. 0, 8, 4)
|
||||
Accepted range is strictly [-12:00 to +14:00] inclusive
|
||||
If timeZone provided, kline intervals are interpreted in that timezone instead of UTC.
|
||||
Note that startTime and endTime are always interpreted in UTC, regardless of timeZone.
|
||||
Data Source: Database
|
||||
|
||||
Response:
|
||||
|
||||
[
|
||||
[
|
||||
1499040000000, // Kline open time
|
||||
"0.01634790", // Open price
|
||||
"0.80000000", // High price
|
||||
"0.01575800", // Low price
|
||||
"0.01577100", // Close price
|
||||
"148976.11427815", // Volume
|
||||
1499644799999, // Kline Close time
|
||||
"2434.19055334", // Quote asset volume
|
||||
308, // Number of trades
|
||||
"1756.87402397", // Taker buy base asset volume
|
||||
"28.46694368", // Taker buy quote asset volume
|
||||
"0" // Unused field, ignore.
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
## WebSocket Streams for Binance
|
||||
|
||||
## General WSS information
|
||||
|
||||
- The base endpoint is: **wss://stream.binance.com:9443** or **wss://stream.binance.com:443**.
|
||||
- Streams can be accessed either in a single raw stream or in a combined stream.
|
||||
- Raw streams are accessed at **/ws/<streamName>**
|
||||
- Combined streams are accessed at **/stream?streams=<streamName1>/<streamName2>/<streamName3>**
|
||||
- Combined stream events are wrapped as follows: **{"stream":"<streamName>","data":<rawPayload>}**
|
||||
- All symbols for streams are **lowercase**
|
||||
- A single connection to **stream.binance.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark
|
||||
- The WebSocket server will send a `ping frame` every 20 seconds.
|
||||
- If the WebSocket server does not receive a `pong frame` back from the connection within a minute the connection will be disconnected.
|
||||
- When you receive a ping, you must send a pong with a copy of ping's payload as soon as possible.
|
||||
- Unsolicited `pong frames` are allowed, but will not prevent disconnection. **It is recommended that the payload for these pong frames are empty.**
|
||||
- The base endpoint **wss://data-stream.binance.vision** can be subscribed to receive **only** market data messages.
|
||||
User data stream is **NOT** available from this URL.
|
||||
- All time and timestamp related fields are **milliseconds by default**. To receive the information in microseconds, please add the parameter `timeUnit=MICROSECOND or timeUnit=microsecond` in the URL.
|
||||
- For example: `/stream?streams=btcusdt@trade&timeUnit=MICROSECOND`
|
||||
- If your request contains a symbol name containing non-ASCII characters, then the stream events may contain non-ASCII characters encoded in UTF-8.
|
||||
- \[All Market Mini Tickers Stream\](#all-market-mini-tickers-stream and [All Market Rolling Window Statistics Streams](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams) events may contain non-ASCII characters encoded in UTF-8.
|
||||
|
||||
## WebSocket Limits
|
||||
|
||||
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
|
||||
- A PING frame
|
||||
- A PONG frame
|
||||
- A JSON controlled message (e.g. subscribe, unsubscribe)
|
||||
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
|
||||
- A single connection can listen to a maximum of 1024 streams.
|
||||
- There is a limit of **300 connections per attempt every 5 minutes per IP**.
|
||||
|
||||
## Live Subscribing/Unsubscribing to streams
|
||||
|
||||
- The following data can be sent through the WebSocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
|
||||
- The `id` is used as an identifier to uniquely identify the messages going back and forth. The following formats are accepted:
|
||||
- 64-bit signed integer
|
||||
- alphanumeric strings; max length 36
|
||||
- `null`
|
||||
- In the response, if the `result` received is `null` this means the request sent was a success for non-query requests (e.g. Subscribing/Unsubscribing).
|
||||
|
||||
### Subscribe to a stream
|
||||
|
||||
- Request
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Unsubscribe to a stream
|
||||
|
||||
- Request
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 312
|
||||
}
|
||||
```
|
||||
|
||||
### Listing Subscriptions
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "LIST_SUBSCRIPTIONS",
|
||||
"id": 3
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": ["btcusdt@aggTrade"],
|
||||
"id": 3
|
||||
}
|
||||
```
|
||||
|
||||
### Setting Properties
|
||||
|
||||
Currently, the only property that can be set is whether `combined` stream payloads are enabled or not. The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`.
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "SET_PROPERTY",
|
||||
"params": ["combined", true],
|
||||
"id": 5
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": null,
|
||||
"id": 5
|
||||
}
|
||||
```
|
||||
|
||||
### Retrieving Properties
|
||||
|
||||
- Request
|
||||
```javascript
|
||||
{
|
||||
"method": "GET_PROPERTY",
|
||||
"params": ["combined"],
|
||||
"id": 2
|
||||
}
|
||||
```
|
||||
- Response
|
||||
```javascript
|
||||
{
|
||||
"result": true, // Indicates that combined is set to true.
|
||||
"id": 2
|
||||
}
|
||||
```
|
||||
|
||||
| Error Message | Description |
|
||||
| --- | --- |
|
||||
| {"code": 0, "msg": "Unknown property","id": %s} | Parameter used in the `SET_PROPERTY` or `GET_PROPERTY` was invalid |
|
||||
| {"code": 1, "msg": "Invalid value type: expected Boolean"} | Value should only be `true` or `false` |
|
||||
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name provided was invalid |
|
||||
| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter `id` had to be provided or the value provided in the `id` parameter is an unsupported type |
|
||||
| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values |
|
||||
| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters provided in the data |
|
||||
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided |
|
||||
| {"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | `method` was not provided in the data |
|
||||
| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. |
|
||||
|
||||
## Detailed Stream information
|
||||
|
||||
## Aggregate Trade Streams
|
||||
|
||||
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
|
||||
|
||||
**Stream Name:** <symbol>@aggTrade
|
||||
|
||||
**Update Speed:** Real-time
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "aggTrade", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"a": 12345, // Aggregate trade ID
|
||||
"p": "0.001", // Price
|
||||
"q": "100", // Quantity
|
||||
"f": 100, // First trade ID
|
||||
"l": 105, // Last trade ID
|
||||
"T": 1672515782136, // Trade time
|
||||
"m": true, // Is the buyer the market maker?
|
||||
"M": true // Ignore
|
||||
}
|
||||
```
|
||||
|
||||
## Trade Streams
|
||||
|
||||
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
|
||||
|
||||
**Stream Name:** <symbol>@trade
|
||||
|
||||
**Update Speed:** Real-time
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "trade", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"t": 12345, // Trade ID
|
||||
"p": "0.001", // Price
|
||||
"q": "100", // Quantity
|
||||
"T": 1672515782136, // Trade time
|
||||
"m": true, // Is the buyer the market maker?
|
||||
"M": true // Ignore
|
||||
}
|
||||
```
|
||||
|
||||
## Kline/Candlestick Streams for UTC
|
||||
|
||||
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+0` timezone
|
||||
|
||||
**Kline/Candlestick chart intervals:**
|
||||
|
||||
s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
|
||||
|
||||
- 1s
|
||||
- 1m
|
||||
- 3m
|
||||
- 5m
|
||||
- 15m
|
||||
- 30m
|
||||
- 1h
|
||||
- 2h
|
||||
- 4h
|
||||
- 6h
|
||||
- 8h
|
||||
- 12h
|
||||
- 1d
|
||||
- 3d
|
||||
- 1w
|
||||
- 1M
|
||||
|
||||
**Stream Name:** <symbol>@kline\_<interval>
|
||||
|
||||
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "kline", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"k": {
|
||||
"t": 1672515780000, // Kline start time
|
||||
"T": 1672515839999, // Kline close time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"i": "1m", // Interval
|
||||
"f": 100, // First trade ID
|
||||
"L": 200, // Last trade ID
|
||||
"o": "0.0010", // Open price
|
||||
"c": "0.0020", // Close price
|
||||
"h": "0.0025", // High price
|
||||
"l": "0.0015", // Low price
|
||||
"v": "1000", // Base asset volume
|
||||
"n": 100, // Number of trades
|
||||
"x": false, // Is this kline closed?
|
||||
"q": "1.0000", // Quote asset volume
|
||||
"V": "500", // Taker buy base asset volume
|
||||
"Q": "0.500", // Taker buy quote asset volume
|
||||
"B": "123456" // Ignore
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Kline/Candlestick Streams with timezone offset
|
||||
|
||||
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+8` timezone
|
||||
|
||||
**Kline/Candlestick chart intervals:**
|
||||
|
||||
Supported intervals: See [`Kline/Candlestick chart intervals`](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#kline-intervals)
|
||||
|
||||
**UTC+8 timezone offset:**
|
||||
|
||||
- Kline intervals open and close in the `UTC+8` timezone. For example the `1d` klines will open at the beginning of the `UTC+8` day, and close at the end of the `UTC+8` day.
|
||||
- Note that `E` (event time), `t` (start time) and `T` (close time) in the payload are Unix timestamps, which are always interpreted in UTC.
|
||||
|
||||
**Stream Name:** <symbol>@kline\_<interval>@+08:00
|
||||
|
||||
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
|
||||
|
||||
**Payload:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"e": "kline", // Event type
|
||||
"E": 1672515782136, // Event time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"k": {
|
||||
"t": 1672515780000, // Kline start time
|
||||
"T": 1672515839999, // Kline close time
|
||||
"s": "BNBBTC", // Symbol
|
||||
"i": "1m", // Interval
|
||||
"f": 100, // First trade ID
|
||||
"L": 200, // Last trade ID
|
||||
"o": "0.0010", // Open price
|
||||
"c": "0.0020", // Close price
|
||||
"h": "0.0025", // High price
|
||||
"l": "0.0015", // Low price
|
||||
"v": "1000", // Base asset volume
|
||||
"n": 100, // Number of trades
|
||||
"x": false, // Is this kline closed?
|
||||
"q": "1.0000", // Quote asset volume
|
||||
"V": "500", // Taker buy base asset volume
|
||||
"Q": "0.500", // Taker buy quote asset volume
|
||||
"B": "123456" // Ignore
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,287 @@
|
||||
# Trading Signals
|
||||
|
||||
   
|
||||
|
||||
Technical indicators and overlays to run [technical analysis](https://en.wikipedia.org/wiki/Technical_analysis) with JavaScript / TypeScript.
|
||||
|
||||
## Motivation
|
||||
|
||||
The "trading-signals" library provides a TypeScript implementation for common technical indicators. It is well-suited for algorithmic trading, allowing developers to perform signal computations for automated trading strategies.
|
||||
|
||||
All indicators can be updated over time by streaming data (prices or [candles](https://en.wikipedia.org/wiki/Candlestick_chart)) to the `add` method. Some indicators also provide `static` batch methods for further performance improvements when providing data up-front during a backtest or historical data import. You can try it out streaming input data by running the provided [demo script](./src/start/demo.ts) with `npm start`, which uses a keyboard input stream.
|
||||
|
||||
## Features
|
||||
|
||||
- **Streaming Updates:** No need to reprocess historical data
|
||||
- **Replace Mode:** Efficient live chart updates
|
||||
- **Lazy Evaluation:** Indicators only calculate when stable
|
||||
- **Memory Efficiency:** Rolling windows, not full history storage
|
||||
- **Excellent Test Coverage:** 100% across all metrics
|
||||
- **Zero Runtime Dependencies:** Minimal bundle size
|
||||
- **Type Safety:** Full TypeScript with strict mode
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install trading-signals
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
**CommonJS:**
|
||||
|
||||
```ts
|
||||
const {SMA} = require('trading-signals');
|
||||
```
|
||||
|
||||
**ESM:**
|
||||
|
||||
```ts
|
||||
import {SMA} from 'trading-signals';
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```typescript
|
||||
import {SMA} from 'trading-signals';
|
||||
|
||||
const sma = new SMA(3);
|
||||
|
||||
// You can add values individually:
|
||||
sma.add(40);
|
||||
sma.add(30);
|
||||
sma.add(20);
|
||||
|
||||
// You can add multiple values at once:
|
||||
sma.updates([20, 40, 80]);
|
||||
|
||||
// You can replace a previous value (useful for live charting):
|
||||
sma.replace(40);
|
||||
|
||||
// You can check if an indicator is stable:
|
||||
console.log(sma.isStable); // true
|
||||
|
||||
// If an indicator is stable, you can get its result:
|
||||
console.log(sma.getResult()); // 50.0003
|
||||
|
||||
// You can also get the result without optional chaining:
|
||||
console.log(sma.getResultOrThrow()); // 50.0003
|
||||
|
||||
// Various precisions are available too:
|
||||
console.log(sma.getResultOrThrow().toFixed(2)); // "50.00"
|
||||
console.log(sma.getResultOrThrow().toFixed(4)); // "50.0003"
|
||||
|
||||
// Each indicator also includes convenient features such as "lowest" and "highest" lifetime values:
|
||||
console.log(sma.lowest?.toFixed(2)); // "23.33"
|
||||
console.log(sma.highest?.toFixed(2)); // "53.33"
|
||||
```
|
||||
|
||||
### When to use `add(...)`?
|
||||
|
||||
To input data, you need to call the indicator's `add` method. Depending on whether the minimum required input data for the interval has been reached, the `add` method may or may not return a result from the indicator.
|
||||
|
||||
### When to use `getResultOrThrow()`?
|
||||
|
||||
You can call `getResultOrThrow()` at any point in time, but it throws errors unless an indicator has received the minimum amount of data. If you call `getResultOrThrow()` before an indicator has received the required amount of input values, a `NotEnoughDataError` will be thrown.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {SMA} from 'trading-signals';
|
||||
|
||||
// Our interval is 3, so we need 3 input values
|
||||
const sma = new SMA(3);
|
||||
|
||||
// We supply 2 input values
|
||||
sma.add(10);
|
||||
sma.add(40);
|
||||
|
||||
try {
|
||||
// We will get an error, because the minimum amount of inputs is 3
|
||||
sma.getResultOrThrow();
|
||||
} catch (error) {
|
||||
console.log(error.constructor.name); // "NotEnoughDataError"
|
||||
}
|
||||
|
||||
// We will supply the 3rd input value
|
||||
sma.add(70);
|
||||
|
||||
// Now, we will receive a proper result
|
||||
console.log(sma.getResultOrThrow()); // 40
|
||||
```
|
||||
|
||||
Most of the time, the minimum amount of data depends on the interval / time period used. If you're not sure, take a look at the test files for the indicator to see examples of correct usage.
|
||||
|
||||
### When to use `getRequiredInputs()`?
|
||||
|
||||
Every indicator provides a `getRequiredInputs()` method that returns the minimum number of input values needed before the indicator becomes stable and can produce results. This is useful for validation and understanding when an indicator will start producing return values.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {SMA, EMA, RSI} from 'trading-signals';
|
||||
|
||||
const sma = new SMA(5);
|
||||
console.log(sma.getRequiredInputs()); // 5
|
||||
```
|
||||
|
||||
The required inputs often depend on the indicator's configuration (like interval/period) and its internal calculation requirements. Some indicators like **MACD** or **Stochastic Oscillator** may require more inputs than their primary period because they use multiple moving averages or lookback periods internally.
|
||||
|
||||
### When to use `getSignal()`?
|
||||
|
||||
Many momentum and trend indicators provide a `getSignal()` method that returns the current trading signal state along with change detection. This is useful for identifying potential trading opportunities.
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
import {RSI} from 'trading-signals';
|
||||
|
||||
const rsi = new RSI(14);
|
||||
|
||||
// Add price data
|
||||
// ...
|
||||
|
||||
// Get the trading signal
|
||||
const signal = rsi.getSignal();
|
||||
console.log(signal.state); // "BEARISH", "BULLISH", "SIDEWAYS", or "UNKNOWN"
|
||||
console.log(signal.hasChanged); // true if the signal state changed from the previous value
|
||||
```
|
||||
|
||||
## Technical Indicator Types
|
||||
|
||||
### Indicator Function
|
||||
|
||||
- Momentum indicators: Measure the speed and strength (intensity) of price movements in a particular direction (overbought/oversold)
|
||||
- Trend indicators: Measure the direction of a trend (bullish/bearish)
|
||||
- Volatility indicators: Measure the degree of variation in prices over time, regardless of direction
|
||||
- Volume indicators: Measure the strength of a trend based on volume
|
||||
|
||||
**Key readings:**
|
||||
|
||||
- Bullish sentiment: expect prices to rise
|
||||
- Bearish sentiment: expect prices to fall
|
||||
- Overbought condition: price may have risen too much too fast, meaning it’s trending up, but traders expect a short-term dip before continuing higher
|
||||
- Oversold condition: price may have dropped too much too fast, meaning it’s trending down, but traders expect a short-term bounce before continuing lower or reversing upward
|
||||
|
||||
### Indicator Timing
|
||||
|
||||
- Leading Indicators: Predictive tools that try to signal future price movements before they happen (i.e. RSI, Stochastic Oscillator, Volume spikes)
|
||||
- Lagging Indicators: Confirmative tools that signal after a trend or move has already started (i.e. Moving Averages, MACD, ADX)
|
||||
|
||||
### Indicator Scale
|
||||
|
||||
- Indicators: Have no upper or lower limits
|
||||
- Oscillators: Move within a fixed range (e.g. 0-100, –1 to +1)
|
||||
|
||||
## Supported Technical Indicators
|
||||
|
||||
1. Acceleration Bands (ABANDS)
|
||||
1. Accelerator Oscillator (AC)
|
||||
1. Average Directional Index (ADX)
|
||||
1. Average True Range (ATR)
|
||||
1. Awesome Oscillator (AO)
|
||||
1. Bollinger Bands (BBANDS)
|
||||
1. Bollinger Bands Width (BBW)
|
||||
1. Center of Gravity (CG)
|
||||
1. Commodity Channel Index (CCI)
|
||||
1. Directional Movement Index (DMI / DX)
|
||||
1. Double Exponential Moving Average (DEMA)
|
||||
1. Dual Moving Average (DMA)
|
||||
1. Exponential Moving Average (EMA)
|
||||
1. Interquartile Range (IQR)
|
||||
1. Linear Regression (LINREG)
|
||||
1. Mean Absolute Deviation (MAD)
|
||||
1. Momentum (MOM / MTM)
|
||||
1. Moving Average Convergence Divergence (MACD)
|
||||
1. On-Balance Volume (OBV)
|
||||
1. Parabolic SAR (PSAR)
|
||||
1. Range Expansion Index (REI)
|
||||
1. Rate-of-Change (ROC)
|
||||
1. Relative Moving Average (RMA)
|
||||
1. Relative Strength Index (RSI)
|
||||
1. Simple Moving Average (SMA)
|
||||
1. Spencer's 15-Point Moving Average (SMA15)
|
||||
1. Stochastic Oscillator (STOCH)
|
||||
1. Stochastic RSI (STOCHRSI)
|
||||
1. Tom Demark's Sequential Indicator (TDS)
|
||||
1. True Range (TR)
|
||||
1. Volume-Weighted Average Price (VWAP)
|
||||
1. Weighted Moving Average (WMA)
|
||||
1. Wilder's Smoothed Moving Average (WSMA / WWS / SMMA / MEMA)
|
||||
1. Williams %R (WILLR)
|
||||
1. Zig Zag Indicator (ZigZag)
|
||||
|
||||
Utility Methods:
|
||||
|
||||
1. Average / Mean
|
||||
1. Grid Sizing (for [grid trading bots](https://b2broker.com/news/understanding-grid-trading-purpose-pros-cons/))
|
||||
1. Maximum
|
||||
1. Median
|
||||
1. Minimum
|
||||
1. Quartile
|
||||
1. Standard Deviation
|
||||
1. Streaks
|
||||
1. Weekday
|
||||
|
||||
## Performance
|
||||
|
||||
### Floating-point arithmetic caveats
|
||||
|
||||
JavaScript uses double-precision floating-point arithmetic. For example, `0.1 + 0.2` yields `0.30000000000000004` due to binary floating-point representation.
|
||||
|
||||

|
||||
|
||||
While this isn’t perfectly accurate, it usually doesn’t matter in practice since indicators often work with averages, which already smooth out precision. In test cases, you can control precision by using Vitest’s [toBeCloseTo](https://vitest.dev/api/expect.html#tobecloseto) assertion.
|
||||
|
||||
Earlier versions of this library (up to version 6) used [big.js][1] for arbitrary-precision arithmetic, but that made calculations about 100x slower on average. For this reason, support for [big.js][1] was removed starting with version 7.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
The information and publications of [trading-signals](https://github.com/bennycode/trading-signals) do not constitute financial advice, investment advice, trading advice or any other form of advice. All results from [trading-signals](https://github.com/bennycode/trading-signals) are intended for information purposes only.
|
||||
|
||||
It is very important to do your own analysis before making any investment based on your own personal circumstances. If you need financial advice or further advice in general, it is recommended that you identify a relevantly qualified individual in your jurisdiction who can advise you accordingly.
|
||||
|
||||
## Alternatives
|
||||
|
||||
- [Cloud9Trader Indicators (JavaScript)](https://github.com/Cloud9Trader/TechnicalIndicators)
|
||||
- [Crypto Trading Hub Indicators (TypeScript)](https://github.com/anandanand84/technicalindicators)
|
||||
- [Highcharts Indicators (TypeScript)](https://github.com/highcharts/highcharts/tree/v12.3.0/ts/Stock/Indicators)
|
||||
- [Indicator TS (TypeScript)](https://github.com/cinar/indicatorts)
|
||||
- [Jesse Trading Bot Indicators (Python)](https://docs.jesse.trade/docs/indicators/reference.html)
|
||||
- [LEAN Indicators (C#)](https://github.com/QuantConnect/Lean/tree/master/Indicators)
|
||||
- [libindicators (C#)](https://github.com/mgfx/libindicators)
|
||||
- [Pandas TA (Python)](https://github.com/twopirllc/pandas-ta)
|
||||
- [Stock Indicators for .NET (C#)](https://github.com/DaveSkender/Stock.Indicators)
|
||||
- [StockSharp (C#)](https://github.com/StockSharp/StockSharp)
|
||||
- [ta-lib (C)](https://github.com/TA-Lib/ta-lib/tree/main/src/ta_func)
|
||||
- [ta-math (TypeScript)](https://github.com/munrocket/ta-math)
|
||||
- [ta4j (Java)](https://github.com/ta4j/ta4j)
|
||||
- [Technical Analysis for Rust (Rust)](https://github.com/greyblake/ta-rs)
|
||||
- [Technical Analysis Library using Pandas and Numpy (Python)](https://github.com/bukosabino/ta)
|
||||
- [Tulip Indicators (ANSI C)](https://github.com/TulipCharts/tulipindicators)
|
||||
|
||||
## Documentation
|
||||
|
||||
Build and run the documentation:
|
||||
|
||||
```bash
|
||||
npm run docs
|
||||
```
|
||||
|
||||
## Maintainers
|
||||
|
||||
[![Benny Neugebauer on Stack Exchange][stack_exchange_bennycode_badge]][stack_exchange_bennycode_url]
|
||||
|
||||
## ⭐️ Become a TypeScript rockstar! ⭐️
|
||||
|
||||
This package was built by Benny Neugebauer. Checkout my [**TypeScript course**](https://typescript.tv/) to become a coding rockstar!
|
||||
|
||||
[<img src="https://raw.githubusercontent.com/bennycode/trading-signals/main/packages/trading-signals/tstv.png">](https://typescript.tv/)
|
||||
|
||||
[1]: http://mikemcl.github.io/big.js/
|
||||
[stack_exchange_bennycode_badge]: https://stackexchange.com/users/flair/203782.png?theme=default
|
||||
[stack_exchange_bennycode_url]: https://stackexchange.com/users/203782/benny-neugebauer?tab=accounts
|
||||
|
||||
## License
|
||||
|
||||
This project is [MIT](./LICENSE) licensed.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Swing strategy (RSI on Binance ETHBTC)
|
||||
|
||||
This repo’s `swing` strategy **trades the exchange symbol you run the bot with** (e.g. `TRADE_SYMBOL`), but **uses Binance spot `ETHBTC` 4h RSI(14)** as the global signal source (per `docs/swingtrading/strategy.md`).
|
||||
|
||||
## Key behavior
|
||||
|
||||
- **Signal source**: Binance spot `ETHBTC`, `4h` klines, RSI period `14`.
|
||||
- **Trade target**: your selected exchange’s `TRADE_SYMBOL` / `*_SYMBOL` (same as other strategies).
|
||||
- **Default mode**: short-only (configurable to long / short / both).
|
||||
- **Stop-loss**:
|
||||
- Tries to place a stop-loss order when supported by the venue.
|
||||
- Always runs a real-time “kill-switch”: if price crosses the stop threshold, it market-closes.
|
||||
- **Spot accounts**: if the connected account is `marketType=spot` and you configure `SWING_DIRECTION=short` (or `both`), the strategy will refuse to trade.
|
||||
|
||||
## Environment variables
|
||||
|
||||
- **Core**
|
||||
- `SWING_DIRECTION`: `short` (default) | `long` | `both`
|
||||
- `SWING_TRADE_AMOUNT`: position size (falls back to `TRADE_AMOUNT`)
|
||||
- `SWING_POLL_INTERVAL_MS`: loop interval (default `500`)
|
||||
- **RSI / signal**
|
||||
- `SWING_RSI_PERIOD`: default `14`
|
||||
- `SWING_RSI_HIGH`: default `70`
|
||||
- `SWING_RSI_LOW`: default `30`
|
||||
- `SWING_SIGNAL_SYMBOL`: default `ETHBTC`
|
||||
- `SWING_SIGNAL_INTERVAL`: default `4h`
|
||||
- **Risk / precision**
|
||||
- `SWING_STOP_LOSS_PCT`: default `0.05` (5%)
|
||||
- `SWING_MAX_CLOSE_SLIPPAGE_PCT`: default `0.05`
|
||||
- `SWING_PRICE_TICK`, `SWING_QTY_STEP`: optional overrides (otherwise synced from exchange when supported)
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
bun run index.ts --strategy swing
|
||||
```
|
||||
|
||||
Silent mode:
|
||||
|
||||
```bash
|
||||
bun run index.ts --strategy swing --silent
|
||||
```
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
无论在任何交易所或者平台运行,都遵循以下逻辑:
|
||||
|
||||
无论交易任何交易对,都参照 ETHBTC 数据进行交易
|
||||
|
||||
从binance现货接口获取 ETHBTC 交易对 4 小时k线数据,rest 接口获取历史数据,获取500条即可
|
||||
|
||||
订阅ws获取最新一根K线的数据
|
||||
|
||||
参考 trading-signals 库,计算 RSI 指标,RSI 参数为 14
|
||||
|
||||
我们的策略仅单边做空,但需要预留配置,可以支持单边做多,单边做空,双向交易
|
||||
|
||||
下面针对单边做空的情况进行说明
|
||||
|
||||
RSI 指标上穿 70 时,进入等待做空状态,后续当 RSI 指标下穿 70 时,执行做空开仓操作
|
||||
|
||||
如果对应的平台支持挂止损 stop loss,则在开仓的同时需要挂一个开仓成本价上涨 5% 的止损单,止损百分比可以设置参数调整,同时也需要有实时监控的止损逻辑,如果在持仓状态下,当前交易对比开仓价格上涨超过 5% ,则执行主动的市价止损操作
|
||||
|
||||
策略需要实时监控当前的交易对ticker数据、orderbook数据,open orders、position,支持ws的全都使用ws数据实时更新
|
||||
|
||||
在有仓位的情况下,如果发现 ETHBTC 的 RSI 指标下穿 30,则进入等待平空状态,如果后续 RSI 指标上穿 30,并且确认仓位有盈利,则执行平空操作
|
||||
|
||||
如此循环往复
|
||||
|
||||
+14
-12
@@ -13,27 +13,29 @@
|
||||
"start:offset:silent": "bun run index.ts --strategy offset-maker --silent",
|
||||
"pm2:start:trend": "pm2 start bun --name ritmex-trend --cwd . --restart-delay 5000 -- run index.ts --strategy trend --silent",
|
||||
"pm2:start:maker": "pm2 start bun --name ritmex-maker --cwd . --restart-delay 5000 -- run index.ts --strategy maker --silent",
|
||||
"pm2:start:offset": "pm2 start bun --name ritmex-offset --cwd . --restart-delay 5000 -- run index.ts --strategy offset-maker --silent"
|
||||
"pm2:start:offset": "pm2 start bun --name ritmex-offset --cwd . --restart-delay 5000 -- run index.ts --strategy offset-maker --silent",
|
||||
"pm2:start:maker-points": "pm2 start bun --name ritmex-maker-points --cwd . --restart-delay 5000 -- run index.ts --strategy maker-points --exchange standx --silent"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
"typescript": "^5.9.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@grvt/client": "^1.6.4",
|
||||
"@nadohq/client": "^0.1.0-alpha.41",
|
||||
"@grvt/client": "^1.6.25",
|
||||
"@nadohq/client": "^0.1.0-alpha.45",
|
||||
"@noble/ed25519": "^3.0.0",
|
||||
"axios": "^1.12.2",
|
||||
"axios": "^1.13.4",
|
||||
"bignumber.js": "^9.3.1",
|
||||
"ccxt": "^4.5.12",
|
||||
"dotenv": "^17.2.2",
|
||||
"ethereum-cryptography": "^2.1.3",
|
||||
"ink": "^6.3.1",
|
||||
"react": "^19.1.1",
|
||||
"viem": "^2.43.1",
|
||||
"ws": "^8.18.3"
|
||||
"ccxt": "^4.5.35",
|
||||
"dotenv": "^17.2.3",
|
||||
"ethereum-cryptography": "^2.2.1",
|
||||
"ink": "^6.6.0",
|
||||
"react": "^19.2.4",
|
||||
"trading-signals": "^7.4.3",
|
||||
"viem": "^2.45.1",
|
||||
"ws": "^8.19.0"
|
||||
}
|
||||
}
|
||||
|
||||
+13
-4
@@ -1,17 +1,20 @@
|
||||
export type StrategyId = "trend" | "guardian" | "maker" | "offset-maker" | "basis" | "grid";
|
||||
export type StrategyId = "trend" | "swing" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid";
|
||||
|
||||
export interface CliOptions {
|
||||
strategy?: StrategyId;
|
||||
silent: boolean;
|
||||
help: boolean;
|
||||
exchange?: "aster" | "grvt" | "lighter" | "backpack" | "paradex" | "nado";
|
||||
exchange?: "aster" | "grvt" | "lighter" | "backpack" | "paradex" | "nado" | "standx";
|
||||
}
|
||||
|
||||
const STRATEGY_VALUES = new Set<StrategyId>([
|
||||
"trend",
|
||||
"swing",
|
||||
"guardian",
|
||||
"maker",
|
||||
"maker-points",
|
||||
"offset-maker",
|
||||
"liquidity-maker",
|
||||
"basis",
|
||||
"grid",
|
||||
]);
|
||||
@@ -69,6 +72,10 @@ function assignStrategy(options: CliOptions, raw: string): void {
|
||||
options.strategy = normalized as StrategyId;
|
||||
} else if (normalized === "offset" || normalized === "offsetmaker" || normalized === "offset-maker") {
|
||||
options.strategy = "offset-maker";
|
||||
} else if (normalized === "makerpoints" || normalized === "maker-points" || normalized === "maker_points") {
|
||||
options.strategy = "maker-points";
|
||||
} else if (normalized === "liquidity" || normalized === "liquiditymaker" || normalized === "liquidity-maker" || normalized === "liquidity_maker") {
|
||||
options.strategy = "liquidity-maker";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +88,8 @@ function assignExchange(options: CliOptions, raw: string): void {
|
||||
normalized === "lighter" ||
|
||||
normalized === "backpack" ||
|
||||
normalized === "paradex" ||
|
||||
normalized === "nado"
|
||||
normalized === "nado" ||
|
||||
normalized === "standx"
|
||||
) {
|
||||
options.exchange = normalized as CliOptions["exchange"];
|
||||
} else if (normalized === "gravity" || normalized === "grav" || normalized === "grv") {
|
||||
@@ -91,10 +99,11 @@ function assignExchange(options: CliOptions, raw: string): void {
|
||||
|
||||
export function printCliHelp(): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Usage: bun run index.ts [--strategy <trend|guardian|maker|offset-maker|basis|grid>] [--exchange <aster|grvt|lighter|backpack|paradex|nado>] [--silent]\n\n` +
|
||||
console.log(`Usage: bun run index.ts [--strategy <trend|swing|guardian|maker|maker-points|offset-maker|liquidity-maker|basis|grid>] [--exchange <aster|grvt|lighter|backpack|paradex|nado|standx>] [--silent]\n\n` +
|
||||
`Options:\n` +
|
||||
` --strategy, -s Automatically start the specified strategy without the interactive menu.\n` +
|
||||
` Aliases: offset, offset-maker for the offset maker engine.\n` +
|
||||
` Aliases: liquidity, liquidity-maker for the liquidity maker engine.\n` +
|
||||
` --exchange, -e Choose exchange. Overrides EXCHANGE/TRADE_EXCHANGE environment variables.\n` +
|
||||
` --silent, -q Reduce console output. When used with --strategy, runs in silent daemon mode.\n` +
|
||||
` --help, -h Show this help message.\n`);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { basisConfig, gridConfig, isBasisStrategyEnabled, makerConfig, tradingConfig } from "../config";
|
||||
import { basisConfig, gridConfig, isBasisStrategyEnabled, liquidityMakerConfig, makerConfig, makerPointsConfig, swingConfig, tradingConfig } from "../config";
|
||||
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import type { ExchangeAdapter } from "../exchanges/adapter";
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { MakerEngine, type MakerEngineSnapshot } from "../strategy/maker-engine";
|
||||
import { OffsetMakerEngine, type OffsetMakerEngineSnapshot } from "../strategy/offset-maker-engine";
|
||||
import { LiquidityMakerEngine, type LiquidityMakerEngineSnapshot } from "../strategy/liquidity-maker-engine";
|
||||
import { MakerPointsEngine, type MakerPointsSnapshot } from "../strategy/maker-points-engine";
|
||||
import { TrendEngine, type TrendEngineSnapshot } from "../strategy/trend-engine";
|
||||
import { SwingEngine, type SwingEngineSnapshot } from "../strategy/swing-engine";
|
||||
import { GuardianEngine, type GuardianEngineSnapshot } from "../strategy/guardian-engine";
|
||||
import { BasisArbEngine, type BasisArbSnapshot } from "../strategy/basis-arb-engine";
|
||||
import { GridEngine, type GridEngineSnapshot } from "../strategy/grid-engine";
|
||||
@@ -19,9 +22,12 @@ type StrategyRunner = (options: RunnerOptions) => Promise<void>;
|
||||
|
||||
export const STRATEGY_LABELS: Record<StrategyId, string> = {
|
||||
trend: "Trend Following",
|
||||
swing: "Swing",
|
||||
guardian: "Guardian",
|
||||
maker: "Maker",
|
||||
"maker-points": "Maker Points",
|
||||
"offset-maker": "Offset Maker",
|
||||
"liquidity-maker": "Liquidity Maker",
|
||||
basis: "Basis Arbitrage",
|
||||
grid: "Grid",
|
||||
};
|
||||
@@ -48,6 +54,19 @@ const STRATEGY_FACTORIES: Record<StrategyId, StrategyRunner> = {
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
swing: async (opts) => {
|
||||
const config = swingConfig;
|
||||
const adapter = createAdapterOrThrow(config.symbol);
|
||||
const engine = new SwingEngine(config, adapter);
|
||||
await runEngine({
|
||||
engine,
|
||||
strategy: "swing",
|
||||
silent: opts.silent,
|
||||
getSnapshot: () => engine.getSnapshot(),
|
||||
onUpdate: (emitter) => engine.on("update", emitter),
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
guardian: async (opts) => {
|
||||
const config = tradingConfig;
|
||||
const adapter = createAdapterOrThrow(config.symbol);
|
||||
@@ -74,6 +93,23 @@ const STRATEGY_FACTORIES: Record<StrategyId, StrategyRunner> = {
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
"maker-points": async (opts) => {
|
||||
const exchangeId = resolveExchangeId();
|
||||
if (exchangeId !== "standx") {
|
||||
throw new Error("Maker Points strategy only supports the StandX exchange.");
|
||||
}
|
||||
const config = makerPointsConfig;
|
||||
const adapter = createAdapterOrThrow(config.symbol);
|
||||
const engine = new MakerPointsEngine(config, adapter);
|
||||
await runEngine({
|
||||
engine,
|
||||
strategy: "maker-points",
|
||||
silent: opts.silent,
|
||||
getSnapshot: () => engine.getSnapshot(),
|
||||
onUpdate: (emitter) => engine.on("update", emitter),
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
"offset-maker": async (opts) => {
|
||||
const config = makerConfig;
|
||||
const adapter = createAdapterOrThrow(config.symbol);
|
||||
@@ -87,13 +123,26 @@ const STRATEGY_FACTORIES: Record<StrategyId, StrategyRunner> = {
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
"liquidity-maker": async (opts) => {
|
||||
const config = liquidityMakerConfig;
|
||||
const adapter = createAdapterOrThrow(config.symbol);
|
||||
const engine = new LiquidityMakerEngine(config, adapter);
|
||||
await runEngine({
|
||||
engine,
|
||||
strategy: "liquidity-maker",
|
||||
silent: opts.silent,
|
||||
getSnapshot: () => engine.getSnapshot(),
|
||||
onUpdate: (emitter) => engine.on("update", emitter),
|
||||
offUpdate: (emitter) => engine.off("update", emitter),
|
||||
});
|
||||
},
|
||||
basis: async (opts) => {
|
||||
if (!isBasisStrategyEnabled()) {
|
||||
throw new Error("Basis arbitrage strategy is disabled. Set ENABLE_BASIS_STRATEGY=true to enable it.");
|
||||
}
|
||||
const exchangeId = resolveExchangeId();
|
||||
if (exchangeId !== "aster" && exchangeId !== "nado") {
|
||||
throw new Error("Basis arbitrage strategy currently only supports the Aster and Nado exchanges");
|
||||
if (exchangeId !== "aster" && exchangeId !== "nado" && exchangeId !== "standx") {
|
||||
throw new Error("Basis arbitrage strategy currently only supports the Aster, Nado, and StandX exchanges");
|
||||
}
|
||||
const adapter = createAdapterOrThrow(basisConfig.futuresSymbol);
|
||||
const engine = new BasisArbEngine(basisConfig, adapter);
|
||||
@@ -133,9 +182,12 @@ interface EngineHarness<TSnapshot> {
|
||||
async function runEngine<
|
||||
TSnapshot extends
|
||||
| TrendEngineSnapshot
|
||||
| SwingEngineSnapshot
|
||||
| GuardianEngineSnapshot
|
||||
| MakerEngineSnapshot
|
||||
| MakerPointsSnapshot
|
||||
| OffsetMakerEngineSnapshot
|
||||
| LiquidityMakerEngineSnapshot
|
||||
| BasisArbSnapshot
|
||||
| GridEngineSnapshot
|
||||
>(
|
||||
|
||||
+251
-9
@@ -6,6 +6,70 @@
|
||||
import { resolveExchangeId, type SupportedExchangeId } from "./exchanges/create-adapter";
|
||||
import { language, type Language } from "./i18n";
|
||||
|
||||
export interface StandxTokenConfig {
|
||||
expiryTimestamp: number | null;
|
||||
}
|
||||
|
||||
function parseTokenExpiry(): number | null {
|
||||
// Method 1: Use creation date + validity days (recommended for official API tokens)
|
||||
const createDate = process.env.STANDX_TOKEN_CREATE_DATE?.trim();
|
||||
const validityDays = process.env.STANDX_TOKEN_VALIDITY_DAYS?.trim();
|
||||
|
||||
if (createDate && validityDays) {
|
||||
// Parse date in YYYY-MM-DD format
|
||||
const dateMatch = createDate.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
if (dateMatch) {
|
||||
const [, year, month, day] = dateMatch;
|
||||
const createTimestamp = Date.UTC(
|
||||
Number(year),
|
||||
Number(month) - 1, // Month is 0-indexed
|
||||
Number(day),
|
||||
0, 0, 0, 0
|
||||
);
|
||||
const days = Number(validityDays);
|
||||
if (Number.isFinite(createTimestamp) && Number.isFinite(days) && days > 0) {
|
||||
return createTimestamp + days * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method 2: Use legacy STANDX_TOKEN_EXPIRY (timestamp or ISO date string)
|
||||
const legacyExpiry = process.env.STANDX_TOKEN_EXPIRY?.trim();
|
||||
if (legacyExpiry) {
|
||||
const asNumber = Number(legacyExpiry);
|
||||
if (Number.isFinite(asNumber) && asNumber > 0) {
|
||||
return asNumber < 1e12 ? asNumber * 1000 : asNumber;
|
||||
}
|
||||
const asDate = Date.parse(legacyExpiry);
|
||||
if (Number.isFinite(asDate) && asDate > 0) {
|
||||
return asDate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const standxTokenConfig: StandxTokenConfig = {
|
||||
expiryTimestamp: parseTokenExpiry(),
|
||||
};
|
||||
|
||||
export function isStandxTokenExpired(): boolean {
|
||||
const expiry = standxTokenConfig.expiryTimestamp;
|
||||
if (expiry == null) return false;
|
||||
return Date.now() >= expiry;
|
||||
}
|
||||
|
||||
export function getStandxTokenExpiryInfo(): { expired: boolean; expiryTimestamp: number | null; remainingMs: number | null } {
|
||||
const expiry = standxTokenConfig.expiryTimestamp;
|
||||
if (expiry == null) {
|
||||
return { expired: false, expiryTimestamp: null, remainingMs: null };
|
||||
}
|
||||
const now = Date.now();
|
||||
const expired = now >= expiry;
|
||||
const remainingMs = expired ? 0 : expiry - now;
|
||||
return { expired, expiryTimestamp: expiry, remainingMs };
|
||||
}
|
||||
|
||||
export interface TradingConfig {
|
||||
symbol: string;
|
||||
tradeAmount: number;
|
||||
@@ -32,6 +96,7 @@ const SYMBOL_PRIORITY_BY_EXCHANGE: Record<SupportedExchangeId, { envKeys: string
|
||||
backpack: { envKeys: ["BACKPACK_SYMBOL", "TRADE_SYMBOL"], fallback: "BTCUSDC" },
|
||||
paradex: { envKeys: ["PARADEX_SYMBOL", "TRADE_SYMBOL"], fallback: "BTC/USDC" },
|
||||
nado: { envKeys: ["NADO_SYMBOL", "TRADE_SYMBOL"], fallback: "BTC-PERP" },
|
||||
standx: { envKeys: ["STANDX_SYMBOL", "TRADE_SYMBOL"], fallback: "BTC-USD" },
|
||||
};
|
||||
|
||||
export function resolveSymbolFromEnv(explicitExchangeId?: SupportedExchangeId | string | null): string {
|
||||
@@ -40,23 +105,51 @@ export function resolveSymbolFromEnv(explicitExchangeId?: SupportedExchangeId |
|
||||
: resolveExchangeId();
|
||||
const { envKeys, fallback } = SYMBOL_PRIORITY_BY_EXCHANGE[exchangeId];
|
||||
for (const key of envKeys) {
|
||||
const value = process.env[key];
|
||||
if (value && value.trim()) {
|
||||
return value.trim();
|
||||
const value = normalizeEnvValue(process.env[key]);
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeEnvValue(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return undefined;
|
||||
|
||||
const quote = trimmed[0];
|
||||
if ((quote === "'" || quote === "\"") && trimmed.endsWith(quote)) {
|
||||
const unquoted = trimmed.slice(1, -1).trim();
|
||||
return unquoted ? unquoted : undefined;
|
||||
}
|
||||
|
||||
// Allow shell-style inline comments: KEY=value # comment
|
||||
const commentIndexHash = trimmed.search(/\s#/);
|
||||
const commentIndexSemi = trimmed.search(/\s;/);
|
||||
const commentIndex =
|
||||
commentIndexHash === -1
|
||||
? commentIndexSemi
|
||||
: commentIndexSemi === -1
|
||||
? commentIndexHash
|
||||
: Math.min(commentIndexHash, commentIndexSemi);
|
||||
if (commentIndex !== -1) {
|
||||
const withoutComment = trimmed.slice(0, commentIndex).trim();
|
||||
return withoutComment ? withoutComment : undefined;
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function parseNumber(value: string | undefined, fallback: number): number {
|
||||
if (!value) return fallback;
|
||||
const next = Number(value);
|
||||
const normalized = normalizeEnvValue(value);
|
||||
if (!normalized) return fallback;
|
||||
const next = Number(normalized);
|
||||
return Number.isFinite(next) ? next : fallback;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
|
||||
if (!value) return fallback;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
const normalized = normalizeEnvValue(value)?.toLowerCase();
|
||||
if (!normalized) return fallback;
|
||||
if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") return true;
|
||||
if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off") return false;
|
||||
@@ -92,6 +185,8 @@ export interface MakerConfig {
|
||||
maxLogEntries: number;
|
||||
maxCloseSlippagePct: number;
|
||||
priceTick: number;
|
||||
/** 开仓挂单档位:1=买1/卖1,2=买2/卖2,以此类推。仅影响无仓位时的开仓挂单,平仓逻辑不受影响。默认1 */
|
||||
entryDepthLevel: number;
|
||||
}
|
||||
|
||||
export const makerConfig: MakerConfig = {
|
||||
@@ -107,6 +202,59 @@ export const makerConfig: MakerConfig = {
|
||||
0.05
|
||||
),
|
||||
priceTick: parseNumber(process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
|
||||
entryDepthLevel: Math.max(1, Math.floor(parseNumber(process.env.MAKER_ENTRY_DEPTH_LEVEL, 1))),
|
||||
};
|
||||
|
||||
export interface MakerPointsConfig {
|
||||
symbol: string;
|
||||
perOrderAmount: number;
|
||||
closeThreshold: number;
|
||||
stopLossUsd: number;
|
||||
refreshIntervalMs: number;
|
||||
maxLogEntries: number;
|
||||
maxCloseSlippagePct: number;
|
||||
priceTick: number;
|
||||
qtyStep: number;
|
||||
enableBand0To10: boolean;
|
||||
enableBand10To30: boolean;
|
||||
enableBand30To100: boolean;
|
||||
/** 0-10 bps 档位挂单数量,未配置时使用 perOrderAmount */
|
||||
band0To10Amount: number;
|
||||
/** 10-30 bps 档位挂单数量,未配置时使用 perOrderAmount */
|
||||
band10To30Amount: number;
|
||||
/** 30-100 bps 档位挂单数量,未配置时使用 perOrderAmount */
|
||||
band30To100Amount: number;
|
||||
minRepriceBps: number;
|
||||
/** 是否根据 Binance 盘口深度失衡自动取消单边挂单,默认 true */
|
||||
enableBinanceDepthCancel: boolean;
|
||||
/** 各档位最小深度阈值 (BTC),盘口到目标价之间的挂单量低于此值则跳过该档位,默认 50 */
|
||||
filterMinDepth: number;
|
||||
}
|
||||
|
||||
const defaultMakerPointsAmount = parseNumber(process.env.MAKER_POINTS_ORDER_AMOUNT, parseNumber(process.env.TRADE_AMOUNT, 0.001));
|
||||
|
||||
export const makerPointsConfig: MakerPointsConfig = {
|
||||
symbol: resolveSymbolFromEnv("standx"),
|
||||
perOrderAmount: defaultMakerPointsAmount,
|
||||
closeThreshold: parseNumber(process.env.MAKER_POINTS_CLOSE_THRESHOLD, 0),
|
||||
stopLossUsd: parseNumber(process.env.MAKER_POINTS_STOP_LOSS_USD, 0),
|
||||
refreshIntervalMs: parseNumber(process.env.MAKER_POINTS_REFRESH_INTERVAL_MS, 500),
|
||||
maxLogEntries: parseNumber(process.env.MAKER_POINTS_MAX_LOG_ENTRIES, 200),
|
||||
maxCloseSlippagePct: parseNumber(
|
||||
process.env.MAKER_POINTS_MAX_CLOSE_SLIPPAGE_PCT ?? process.env.MAX_CLOSE_SLIPPAGE_PCT,
|
||||
0.05
|
||||
),
|
||||
priceTick: parseNumber(process.env.MAKER_POINTS_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
|
||||
qtyStep: parseNumber(process.env.MAKER_POINTS_QTY_STEP ?? process.env.QTY_STEP, 0.001),
|
||||
enableBand0To10: parseBoolean(process.env.MAKER_POINTS_BAND_0_10, true),
|
||||
enableBand10To30: parseBoolean(process.env.MAKER_POINTS_BAND_10_30, true),
|
||||
enableBand30To100: parseBoolean(process.env.MAKER_POINTS_BAND_30_100, true),
|
||||
band0To10Amount: parseNumber(process.env.MAKER_POINTS_BAND_0_10_AMOUNT, defaultMakerPointsAmount),
|
||||
band10To30Amount: parseNumber(process.env.MAKER_POINTS_BAND_10_30_AMOUNT, defaultMakerPointsAmount),
|
||||
band30To100Amount: parseNumber(process.env.MAKER_POINTS_BAND_30_100_AMOUNT, defaultMakerPointsAmount),
|
||||
minRepriceBps: parseNumber(process.env.MAKER_POINTS_MIN_REPRICE_BPS, 3),
|
||||
enableBinanceDepthCancel: parseBoolean(process.env.MAKER_POINTS_BINANCE_DEPTH_CANCEL, true),
|
||||
filterMinDepth: parseNumber(process.env.MAKER_POINTS_FILTER_MIN_DEPTH, 50),
|
||||
};
|
||||
|
||||
export interface BasisArbConfig {
|
||||
@@ -154,11 +302,21 @@ export const basisConfig: BasisArbConfig = {
|
||||
// Users can always override via BASIS_* env vars.
|
||||
futuresSymbol: resolveBasisSymbol(
|
||||
["BASIS_FUTURES_SYMBOL", "ASTER_FUTURES_SYMBOL", "ASTER_SYMBOL", "TRADE_SYMBOL"],
|
||||
(process.env.EXCHANGE ?? "").trim().toLowerCase() === "nado" ? "BTC-PERP" : "ASTERUSDT"
|
||||
(() => {
|
||||
const exchange = (process.env.EXCHANGE ?? "").trim().toLowerCase();
|
||||
if (exchange === "nado") return "BTC-PERP";
|
||||
if (exchange === "standx") return "BTC-USD";
|
||||
return "ASTERUSDT";
|
||||
})()
|
||||
),
|
||||
spotSymbol: resolveBasisSymbol(
|
||||
["BASIS_SPOT_SYMBOL", "ASTER_SPOT_SYMBOL", "ASTER_SYMBOL", "TRADE_SYMBOL"],
|
||||
(process.env.EXCHANGE ?? "").trim().toLowerCase() === "nado" ? "KBTC" : "ASTERUSDT"
|
||||
(() => {
|
||||
const exchange = (process.env.EXCHANGE ?? "").trim().toLowerCase();
|
||||
if (exchange === "nado") return "KBTC";
|
||||
if (exchange === "standx") return "BTC-USD";
|
||||
return "ASTERUSDT";
|
||||
})()
|
||||
),
|
||||
refreshIntervalMs: parseNumber(process.env.BASIS_REFRESH_INTERVAL_MS, 1000),
|
||||
maxLogEntries: parseNumber(process.env.BASIS_MAX_LOG_ENTRIES, 200),
|
||||
@@ -209,6 +367,90 @@ export const gridConfig: GridConfig = {
|
||||
|
||||
gridConfig.maxPositionSize = resolveGridMaxPosition(gridConfig.orderSize, gridConfig.gridLevels);
|
||||
|
||||
export interface LiquidityMakerConfig {
|
||||
symbol: string;
|
||||
tradeAmount: number;
|
||||
lossLimit: number;
|
||||
bidOffset: number;
|
||||
askOffset: number;
|
||||
refreshIntervalMs: number;
|
||||
maxLogEntries: number;
|
||||
maxCloseSlippagePct: number;
|
||||
priceTick: number;
|
||||
/** 平仓挂单距成交价的档位数,默认1档 */
|
||||
closeTickOffset: number;
|
||||
/** 偏移判断阈值倍数,当一侧深度超出另一侧此倍数时取消薄端订单,默认2 */
|
||||
depthImbalanceRatio: number;
|
||||
/** 开仓挂单档位:1=买1/卖1,2=买2/卖2,以此类推。仅影响无仓位时的开仓挂单,平仓逻辑不受影响。默认1 */
|
||||
entryDepthLevel: number;
|
||||
}
|
||||
|
||||
export const liquidityMakerConfig: LiquidityMakerConfig = {
|
||||
symbol: resolveSymbolFromEnv(),
|
||||
tradeAmount: parseNumber(process.env.TRADE_AMOUNT, 0.001),
|
||||
lossLimit: parseNumber(process.env.LIQUIDITY_MAKER_LOSS_LIMIT, parseNumber(process.env.MAKER_LOSS_LIMIT, parseNumber(process.env.LOSS_LIMIT, 0.03))),
|
||||
bidOffset: parseNumber(process.env.LIQUIDITY_MAKER_BID_OFFSET, parseNumber(process.env.MAKER_BID_OFFSET, 0)),
|
||||
askOffset: parseNumber(process.env.LIQUIDITY_MAKER_ASK_OFFSET, parseNumber(process.env.MAKER_ASK_OFFSET, 0)),
|
||||
refreshIntervalMs: parseNumber(process.env.LIQUIDITY_MAKER_REFRESH_INTERVAL_MS, parseNumber(process.env.MAKER_REFRESH_INTERVAL_MS, 500)),
|
||||
maxLogEntries: parseNumber(process.env.LIQUIDITY_MAKER_MAX_LOG_ENTRIES, parseNumber(process.env.MAKER_MAX_LOG_ENTRIES, 200)),
|
||||
maxCloseSlippagePct: parseNumber(
|
||||
process.env.LIQUIDITY_MAKER_MAX_CLOSE_SLIPPAGE_PCT ?? process.env.MAKER_MAX_CLOSE_SLIPPAGE_PCT ?? process.env.MAX_CLOSE_SLIPPAGE_PCT,
|
||||
0.05
|
||||
),
|
||||
priceTick: parseNumber(process.env.LIQUIDITY_MAKER_PRICE_TICK ?? process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
|
||||
closeTickOffset: Math.max(1, Math.floor(parseNumber(process.env.LIQUIDITY_MAKER_CLOSE_TICK_OFFSET, 1))),
|
||||
depthImbalanceRatio: Math.max(1.1, parseNumber(process.env.LIQUIDITY_MAKER_DEPTH_IMBALANCE_RATIO, 2)),
|
||||
entryDepthLevel: Math.max(1, Math.floor(parseNumber(process.env.MAKER_ENTRY_DEPTH_LEVEL, 1))),
|
||||
};
|
||||
|
||||
export type SwingDirection = "both" | "long" | "short";
|
||||
|
||||
export interface SwingConfig {
|
||||
symbol: string;
|
||||
tradeAmount: number;
|
||||
pollIntervalMs: number;
|
||||
maxLogEntries: number;
|
||||
maxCloseSlippagePct: number;
|
||||
priceTick: number;
|
||||
qtyStep: number;
|
||||
direction: SwingDirection;
|
||||
rsiPeriod: number;
|
||||
rsiHigh: number;
|
||||
rsiLow: number;
|
||||
stopLossPct: number;
|
||||
signalSymbol: string;
|
||||
signalInterval: string;
|
||||
}
|
||||
|
||||
const resolveSwingDirection = (raw: string | undefined, fallback: SwingDirection): SwingDirection => {
|
||||
if (!raw) return fallback;
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === "long" || normalized === "long-only") return "long";
|
||||
if (normalized === "short" || normalized === "short-only") return "short";
|
||||
if (normalized === "both" || normalized === "dual" || normalized === "bi" || normalized === "two-way") return "both";
|
||||
return fallback;
|
||||
};
|
||||
|
||||
export const swingConfig: SwingConfig = {
|
||||
symbol: resolveSymbolFromEnv(),
|
||||
tradeAmount: parseNumber(process.env.SWING_TRADE_AMOUNT ?? process.env.TRADE_AMOUNT, 0.001),
|
||||
pollIntervalMs: parseNumber(process.env.SWING_POLL_INTERVAL_MS, parseNumber(process.env.POLL_INTERVAL_MS, 500)),
|
||||
maxLogEntries: parseNumber(process.env.SWING_MAX_LOG_ENTRIES, parseNumber(process.env.MAX_LOG_ENTRIES, 200)),
|
||||
maxCloseSlippagePct: parseNumber(
|
||||
process.env.SWING_MAX_CLOSE_SLIPPAGE_PCT ?? process.env.MAX_CLOSE_SLIPPAGE_PCT,
|
||||
0.05
|
||||
),
|
||||
priceTick: parseNumber(process.env.SWING_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
|
||||
qtyStep: parseNumber(process.env.SWING_QTY_STEP ?? process.env.QTY_STEP, 0.001),
|
||||
direction: resolveSwingDirection(process.env.SWING_DIRECTION, "short"),
|
||||
rsiPeriod: Math.max(1, Math.floor(parseNumber(process.env.SWING_RSI_PERIOD, 14))),
|
||||
rsiHigh: parseNumber(process.env.SWING_RSI_HIGH, 70),
|
||||
rsiLow: parseNumber(process.env.SWING_RSI_LOW, 30),
|
||||
stopLossPct: Math.max(0, parseNumber(process.env.SWING_STOP_LOSS_PCT, 0.05)),
|
||||
signalSymbol: (process.env.SWING_SIGNAL_SYMBOL ?? "ETHBTC").trim().toUpperCase(),
|
||||
signalInterval: (process.env.SWING_SIGNAL_INTERVAL ?? "4h").trim(),
|
||||
};
|
||||
|
||||
export function isBasisStrategyEnabled(): boolean {
|
||||
const raw = process.env.ENABLE_BASIS_STRATEGY;
|
||||
if (!raw) return false;
|
||||
|
||||
@@ -132,6 +132,8 @@ type PlaceOrderOptions = {
|
||||
priceTick: number;
|
||||
qtyStep: number;
|
||||
skipDedupe?: boolean;
|
||||
slPrice?: number;
|
||||
tpPrice?: number;
|
||||
};
|
||||
|
||||
export async function placeOrder(
|
||||
@@ -176,9 +178,11 @@ export async function placeOrder(
|
||||
timeInForce: reduceOnly ? "GTC" : "GTX",
|
||||
reduceOnly: reduceOnly ? true : undefined,
|
||||
closePosition,
|
||||
slPrice: opts?.slPrice,
|
||||
tpPrice: opts?.tpPrice,
|
||||
});
|
||||
pendings[type] = String(order.orderId);
|
||||
log("order", `挂限价单: ${side} @ ${priceNum} 数量 ${quantity} reduceOnly=${reduceOnly}`);
|
||||
log("order", `挂限价单: ${side} @ ${priceNum} 数量 ${quantity} reduceOnly=${reduceOnly}${opts?.slPrice ? ` sl=${opts.slPrice}` : ""}`);
|
||||
return order;
|
||||
} catch (err) {
|
||||
unlockOperating(locks, timers, pendings, type);
|
||||
@@ -292,7 +296,7 @@ export async function placeStopLossOrder(
|
||||
timeInForce: "GTC",
|
||||
reduceOnly: true,
|
||||
closePosition: true,
|
||||
triggerType: side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS",
|
||||
triggerType: "STOP_LOSS",
|
||||
});
|
||||
pendings[type] = String(order.orderId);
|
||||
log("stop", `挂止损单: ${side} STOP_MARKET @ ${normalizedStop}`);
|
||||
|
||||
@@ -37,6 +37,17 @@ export interface FundingRateListener {
|
||||
(snapshot: FundingRateSnapshot): void;
|
||||
}
|
||||
|
||||
export type RestHealthState = "healthy" | "unhealthy";
|
||||
export interface RestHealthInfo {
|
||||
consecutiveErrors: number;
|
||||
method?: string;
|
||||
path?: string;
|
||||
error?: string;
|
||||
}
|
||||
export interface RestHealthListener {
|
||||
(state: RestHealthState, info: RestHealthInfo): void;
|
||||
}
|
||||
|
||||
export interface ExchangePrecision {
|
||||
priceTick: number;
|
||||
qtyStep: number;
|
||||
@@ -47,6 +58,11 @@ export interface ExchangePrecision {
|
||||
minQuoteAmount?: number;
|
||||
}
|
||||
|
||||
export type ConnectionEventType = "disconnected" | "reconnected";
|
||||
export interface ConnectionEventListener {
|
||||
(event: ConnectionEventType, symbol: string): void;
|
||||
}
|
||||
|
||||
export interface ExchangeAdapter {
|
||||
readonly id: string;
|
||||
supportsTrailingStops(): boolean;
|
||||
@@ -61,4 +77,13 @@ export interface ExchangeAdapter {
|
||||
cancelOrders(params: { symbol: string; orderIdList: Array<number | string> }): Promise<void>;
|
||||
cancelAllOrders(params: { symbol: string }): Promise<void>;
|
||||
getPrecision?(): Promise<ExchangePrecision | null>;
|
||||
// 连接保护相关方法(可选,仅 StandX 支持)
|
||||
onConnectionEvent?(listener: ConnectionEventListener): void;
|
||||
offConnectionEvent?(listener: ConnectionEventListener): void;
|
||||
onRestHealthEvent?(listener: RestHealthListener): void;
|
||||
offRestHealthEvent?(listener: RestHealthListener): void;
|
||||
queryOpenOrders?(): Promise<AsterOrder[]>;
|
||||
queryAccountSnapshot?(): Promise<AsterAccountSnapshot | null>;
|
||||
changeMarginMode?(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void>;
|
||||
forceCancelAllOrders?(): Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { LighterExchangeAdapter, type LighterCredentials } from "./lighter/adapt
|
||||
import { BackpackExchangeAdapter, type BackpackCredentials } from "./backpack/adapter";
|
||||
import { ParadexExchangeAdapter, type ParadexCredentials } from "./paradex/adapter";
|
||||
import { NadoExchangeAdapter, type NadoCredentials } from "./nado/adapter";
|
||||
import { StandxExchangeAdapter, type StandxCredentials } from "./standx/adapter";
|
||||
|
||||
export interface ExchangeFactoryOptions {
|
||||
symbol: string;
|
||||
@@ -15,9 +16,17 @@ export interface ExchangeFactoryOptions {
|
||||
backpack?: BackpackCredentials;
|
||||
paradex?: ParadexCredentials;
|
||||
nado?: NadoCredentials;
|
||||
standx?: StandxCredentials;
|
||||
}
|
||||
|
||||
export type SupportedExchangeId = "aster" | "grvt" | "lighter" | "backpack" | "paradex" | "nado";
|
||||
export type SupportedExchangeId =
|
||||
| "aster"
|
||||
| "grvt"
|
||||
| "lighter"
|
||||
| "backpack"
|
||||
| "paradex"
|
||||
| "nado"
|
||||
| "standx";
|
||||
|
||||
export function resolveExchangeId(value?: string | null): SupportedExchangeId {
|
||||
const fallback = (value ?? process.env.EXCHANGE ?? process.env.TRADE_EXCHANGE ?? "aster")
|
||||
@@ -29,6 +38,7 @@ export function resolveExchangeId(value?: string | null): SupportedExchangeId {
|
||||
if (fallback === "backpack") return "backpack";
|
||||
if (fallback === "paradex") return "paradex";
|
||||
if (fallback === "nado") return "nado";
|
||||
if (fallback === "standx") return "standx";
|
||||
return "aster";
|
||||
}
|
||||
|
||||
@@ -38,6 +48,7 @@ export function getExchangeDisplayName(id: SupportedExchangeId): string {
|
||||
if (id === "backpack") return "Backpack";
|
||||
if (id === "paradex") return "Paradex";
|
||||
if (id === "nado") return "Nado";
|
||||
if (id === "standx") return "StandX";
|
||||
return "AsterDex";
|
||||
}
|
||||
|
||||
@@ -58,5 +69,8 @@ export function createExchangeAdapter(options: ExchangeFactoryOptions): Exchange
|
||||
if (id === "nado") {
|
||||
return new NadoExchangeAdapter({ ...options.nado, symbol: options.symbol });
|
||||
}
|
||||
if (id === "standx") {
|
||||
return new StandxExchangeAdapter({ ...options.standx, symbol: options.symbol });
|
||||
}
|
||||
return new AsterExchangeAdapter({ ...options.aster, symbol: options.symbol });
|
||||
}
|
||||
|
||||
@@ -1337,7 +1337,7 @@ function buildUnsignedOrder(params: {
|
||||
|
||||
function buildTriggerMetadata(params: CreateOrderParams): GrvtUnsignedOrder["metadata"]["trigger"] | undefined {
|
||||
if (params.type === "STOP_MARKET") {
|
||||
const triggerType = params.triggerType ?? (params.side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS");
|
||||
const triggerType = params.triggerType ?? "STOP_LOSS";
|
||||
const stopPrice = params.stopPrice ?? params.activationPrice;
|
||||
if (!stopPrice) {
|
||||
throw new Error("GRVT stop orders require a stopPrice or activationPrice");
|
||||
|
||||
@@ -62,7 +62,7 @@ export async function createStopOrder(intent: StopOrderIntent): Promise<AsterOrd
|
||||
quantity: intent.quantity,
|
||||
stopPrice: intent.stopPrice,
|
||||
timeInForce: intent.timeInForce ?? "GTC",
|
||||
triggerType: intent.triggerType ?? (intent.side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS"),
|
||||
triggerType: intent.triggerType ?? "STOP_LOSS",
|
||||
closePosition: toStringBoolean(intent.closePosition ?? true),
|
||||
reduceOnly: toStringBoolean(intent.reduceOnly ?? true),
|
||||
},
|
||||
|
||||
@@ -14,8 +14,9 @@ import * as grvtOrders from "./grvt/order";
|
||||
import * as lighterOrders from "./lighter/order";
|
||||
import * as paradexOrders from "./paradex/order";
|
||||
import * as nadoOrders from "./nado/order";
|
||||
import * as standxOrders from "./standx/order";
|
||||
|
||||
type ExchangeKey = "aster" | "backpack" | "grvt" | "lighter" | "paradex" | "nado";
|
||||
type ExchangeKey = "aster" | "backpack" | "grvt" | "lighter" | "paradex" | "nado" | "standx";
|
||||
|
||||
interface ExchangeOrderHandlers {
|
||||
limit(intent: LimitOrderIntent): Promise<AsterOrder>;
|
||||
@@ -68,9 +69,24 @@ const handlerMap: Record<ExchangeKey, ExchangeOrderHandlers> = {
|
||||
trailingStop: nadoOrders.createTrailingStopOrder,
|
||||
close: nadoOrders.createClosePositionOrder,
|
||||
},
|
||||
standx: {
|
||||
limit: standxOrders.createLimitOrder,
|
||||
market: standxOrders.createMarketOrder,
|
||||
stop: standxOrders.createStopOrder,
|
||||
trailingStop: standxOrders.createTrailingStopOrder,
|
||||
close: standxOrders.createClosePositionOrder,
|
||||
},
|
||||
};
|
||||
|
||||
const knownExchanges: ExchangeKey[] = ["aster", "backpack", "grvt", "lighter", "paradex", "nado"];
|
||||
const knownExchanges: ExchangeKey[] = [
|
||||
"aster",
|
||||
"backpack",
|
||||
"grvt",
|
||||
"lighter",
|
||||
"paradex",
|
||||
"nado",
|
||||
"standx",
|
||||
];
|
||||
|
||||
function normalizeExchangeId(value: string | undefined | null): string | undefined {
|
||||
if (!value) return undefined;
|
||||
|
||||
@@ -13,6 +13,9 @@ export interface BaseOrderIntent {
|
||||
|
||||
export interface LimitOrderIntent extends BaseOrderIntent {
|
||||
price: number;
|
||||
// StandX TPSL 参数
|
||||
slPrice?: number; // 止损价格
|
||||
tpPrice?: number; // 止盈价格
|
||||
}
|
||||
|
||||
export interface MarketOrderIntent extends BaseOrderIntent {
|
||||
|
||||
@@ -602,7 +602,10 @@ export class ParadexGateway {
|
||||
// Only omit amount for MARKET close-position orders; STOP requires explicit size
|
||||
const shouldOmitAmount = isClosePosition && type === "market";
|
||||
const amountArg: any = shouldOmitAmount ? undefined : amount;
|
||||
if (!shouldOmitAmount && amountArg != null && extraParams.size === undefined) {
|
||||
// Paradex/ccxt may require `size` even when amount is omitted for closePosition MARKET orders.
|
||||
if (shouldOmitAmount && amount != null && extraParams.size === undefined) {
|
||||
extraParams.size = amount.toString();
|
||||
} else if (!shouldOmitAmount && amountArg != null && extraParams.size === undefined) {
|
||||
extraParams.size = amountArg.toString();
|
||||
}
|
||||
const order = (await this.exchange.createOrder(
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { LighterCredentials } from "./lighter/adapter";
|
||||
import type { BackpackCredentials } from "./backpack/adapter";
|
||||
import type { ParadexCredentials } from "./paradex/adapter";
|
||||
import type { NadoCredentials } from "./nado/adapter";
|
||||
import type { StandxCredentials } from "./standx/adapter";
|
||||
import { t } from "../i18n";
|
||||
import type { Address } from "viem";
|
||||
|
||||
@@ -42,6 +43,11 @@ export function buildAdapterFromEnv(options: BuildAdapterOptions): ExchangeAdapt
|
||||
return createExchangeAdapter({ exchange: id, symbol, nado: credentials });
|
||||
}
|
||||
|
||||
if (id === "standx") {
|
||||
const credentials = resolveStandxCredentials(symbol);
|
||||
return createExchangeAdapter({ exchange: id, symbol, standx: credentials });
|
||||
}
|
||||
|
||||
return createExchangeAdapter({ exchange: id, symbol, grvt: { symbol } });
|
||||
}
|
||||
|
||||
@@ -153,6 +159,21 @@ function resolveNadoCredentials(symbol: string): NadoCredentials {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
function resolveStandxCredentials(symbol: string): StandxCredentials {
|
||||
const token = process.env.STANDX_TOKEN;
|
||||
if (!token) {
|
||||
throw new Error(t("env.missingStandx"));
|
||||
}
|
||||
return {
|
||||
token,
|
||||
symbol: process.env.STANDX_SYMBOL ?? symbol,
|
||||
baseUrl: process.env.STANDX_BASE_URL ?? undefined,
|
||||
wsUrl: process.env.STANDX_WS_URL ?? undefined,
|
||||
sessionId: process.env.STANDX_SESSION_ID ?? undefined,
|
||||
signingKey: process.env.STANDX_REQUEST_PRIVATE_KEY ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function isHex32(value: string): boolean {
|
||||
return /^0x[0-9a-fA-F]{64}$/.test(value.trim());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { setTimeout, clearTimeout } from "timers";
|
||||
import type {
|
||||
AccountListener,
|
||||
DepthListener,
|
||||
ExchangeAdapter,
|
||||
ExchangePrecision,
|
||||
FundingRateListener,
|
||||
KlineListener,
|
||||
OrderListener,
|
||||
RestHealthListener,
|
||||
TickerListener,
|
||||
} from "../adapter";
|
||||
import type { AsterOrder, CreateOrderParams } from "../types";
|
||||
import { extractMessage } from "../../utils/errors";
|
||||
import { StandxGateway, type StandxGatewayOptions, type ConnectionEventListener, type ConnectionEventType } from "./gateway";
|
||||
|
||||
export type { ConnectionEventListener, ConnectionEventType };
|
||||
|
||||
export interface StandxCredentials {
|
||||
token?: string;
|
||||
symbol?: string;
|
||||
baseUrl?: string;
|
||||
wsUrl?: string;
|
||||
sessionId?: string;
|
||||
signingKey?: string;
|
||||
logger?: StandxGatewayOptions["logger"];
|
||||
}
|
||||
|
||||
export class StandxExchangeAdapter implements ExchangeAdapter {
|
||||
readonly id = "standx";
|
||||
|
||||
private readonly gateway: StandxGateway;
|
||||
private readonly symbol: string;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
private readonly initContexts = new Set<string>();
|
||||
private retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private retryDelayMs = 3000;
|
||||
private lastInitErrorAt = 0;
|
||||
|
||||
constructor(credentials: StandxCredentials = {}) {
|
||||
const token = credentials.token ?? process.env.STANDX_TOKEN;
|
||||
if (!token) {
|
||||
throw new Error("Missing STANDX_TOKEN environment variable");
|
||||
}
|
||||
this.symbol = credentials.symbol ?? process.env.STANDX_SYMBOL ?? process.env.TRADE_SYMBOL ?? "BTC-USD";
|
||||
this.gateway = new StandxGateway({
|
||||
token,
|
||||
symbol: this.symbol,
|
||||
baseUrl: credentials.baseUrl,
|
||||
wsUrl: credentials.wsUrl,
|
||||
sessionId: credentials.sessionId,
|
||||
signingKey: credentials.signingKey,
|
||||
logger: credentials.logger,
|
||||
});
|
||||
}
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(cb: AccountListener): void {
|
||||
void this.ensureInitialized("watchAccount");
|
||||
this.gateway.onAccount(this.safeInvoke("watchAccount", cb));
|
||||
}
|
||||
|
||||
watchOrders(cb: OrderListener): void {
|
||||
void this.ensureInitialized("watchOrders");
|
||||
this.gateway.onOrders(this.safeInvoke("watchOrders", cb));
|
||||
}
|
||||
|
||||
watchDepth(symbol: string, cb: DepthListener): void {
|
||||
void this.ensureInitialized("watchDepth");
|
||||
this.gateway.onDepth(symbol, this.safeInvoke("watchDepth", cb));
|
||||
}
|
||||
|
||||
watchTicker(symbol: string, cb: TickerListener): void {
|
||||
void this.ensureInitialized("watchTicker");
|
||||
this.gateway.onTicker(symbol, this.safeInvoke("watchTicker", cb));
|
||||
}
|
||||
|
||||
watchKlines(symbol: string, interval: string, cb: KlineListener): void {
|
||||
void this.ensureInitialized("watchKlines");
|
||||
this.gateway.onKlines(symbol, interval, this.safeInvoke("watchKlines", cb));
|
||||
}
|
||||
|
||||
watchFundingRate(symbol: string, cb: FundingRateListener): void {
|
||||
void this.ensureInitialized("watchFundingRate");
|
||||
this.gateway.onFundingRate(symbol, this.safeInvoke("watchFundingRate", cb));
|
||||
}
|
||||
|
||||
async createOrder(params: CreateOrderParams): Promise<AsterOrder> {
|
||||
await this.ensureInitialized("createOrder");
|
||||
return this.gateway.createOrder(params);
|
||||
}
|
||||
|
||||
async cancelOrder(params: { symbol: string; orderId: number | string }): Promise<void> {
|
||||
await this.ensureInitialized("cancelOrder");
|
||||
await this.gateway.cancelOrder(params);
|
||||
}
|
||||
|
||||
async cancelOrders(params: { symbol: string; orderIdList: Array<number | string> }): Promise<void> {
|
||||
await this.ensureInitialized("cancelOrders");
|
||||
await this.gateway.cancelOrders(params);
|
||||
}
|
||||
|
||||
async cancelAllOrders(params: { symbol: string }): Promise<void> {
|
||||
await this.ensureInitialized("cancelAllOrders");
|
||||
await this.gateway.cancelAllOrders(params);
|
||||
}
|
||||
|
||||
async getPrecision(): Promise<ExchangePrecision | null> {
|
||||
try {
|
||||
const precision = await this.gateway.getPrecision(this.symbol);
|
||||
if (!precision) return null;
|
||||
return {
|
||||
priceTick: precision.priceTick,
|
||||
qtyStep: precision.qtyStep,
|
||||
priceDecimals: precision.priceDecimals,
|
||||
sizeDecimals: precision.sizeDecimals,
|
||||
minBaseAmount: precision.minBaseAmount,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[StandxExchangeAdapter] getPrecision failed", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听连接事件(断连/重连)
|
||||
*/
|
||||
onConnectionEvent(listener: ConnectionEventListener): void {
|
||||
this.gateway.onConnectionEvent(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消连接事件监听
|
||||
*/
|
||||
offConnectionEvent(listener: ConnectionEventListener): void {
|
||||
this.gateway.offConnectionEvent(listener);
|
||||
}
|
||||
|
||||
onRestHealthEvent(listener: RestHealthListener): void {
|
||||
this.gateway.onRestHealthEvent(listener);
|
||||
}
|
||||
|
||||
offRestHealthEvent(listener: RestHealthListener): void {
|
||||
this.gateway.offRestHealthEvent(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前真实的挂单状态(通过 HTTP API)
|
||||
* 用于验证实际挂单情况,防止取消请求丢失
|
||||
*/
|
||||
async queryOpenOrders(): Promise<AsterOrder[]> {
|
||||
await this.ensureInitialized("queryOpenOrders");
|
||||
return this.gateway.queryOpenOrders(this.symbol);
|
||||
}
|
||||
|
||||
async queryAccountSnapshot() {
|
||||
await this.ensureInitialized("queryAccountSnapshot");
|
||||
return this.gateway.queryAccountSnapshot();
|
||||
}
|
||||
|
||||
async changeMarginMode(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void> {
|
||||
await this.ensureInitialized("changeMarginMode");
|
||||
await this.gateway.changeMarginMode(params.symbol, params.marginMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制取消所有挂单
|
||||
* 会查询当前挂单然后取消,并验证取消成功
|
||||
*/
|
||||
async forceCancelAllOrders(): Promise<boolean> {
|
||||
await this.ensureInitialized("forceCancelAllOrders");
|
||||
return this.gateway.forceCancelAllOrders(this.symbol);
|
||||
}
|
||||
|
||||
private safeInvoke<T extends (...args: any[]) => void>(context: string, cb: T): T {
|
||||
const wrapped = ((...args: any[]) => {
|
||||
try {
|
||||
cb(...args);
|
||||
} catch (error) {
|
||||
console.error(`[StandxExchangeAdapter] ${context} handler failed: ${extractMessage(error)}`);
|
||||
}
|
||||
}) as T;
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
private ensureInitialized(context?: string): Promise<void> {
|
||||
if (!this.initPromise) {
|
||||
this.initContexts.clear();
|
||||
this.initPromise = this.gateway
|
||||
.ensureInitialized(this.symbol)
|
||||
.then((value) => {
|
||||
this.clearRetry();
|
||||
return value;
|
||||
})
|
||||
.catch((error) => {
|
||||
this.handleInitError("initialize", error);
|
||||
this.initPromise = null;
|
||||
this.scheduleRetry();
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
if (context && !this.initContexts.has(context)) {
|
||||
this.initContexts.add(context);
|
||||
this.initPromise.catch((error) => {
|
||||
this.handleInitError(context, error);
|
||||
this.scheduleRetry();
|
||||
});
|
||||
}
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
private scheduleRetry(): void {
|
||||
if (this.retryTimer) return;
|
||||
this.retryTimer = setTimeout(() => {
|
||||
this.retryTimer = null;
|
||||
if (this.initPromise) return;
|
||||
this.retryDelayMs = Math.min(this.retryDelayMs * 2, 60_000);
|
||||
void this.ensureInitialized("retry");
|
||||
}, this.retryDelayMs);
|
||||
}
|
||||
|
||||
private clearRetry(): void {
|
||||
if (this.retryTimer) {
|
||||
clearTimeout(this.retryTimer);
|
||||
this.retryTimer = null;
|
||||
}
|
||||
this.retryDelayMs = 3000;
|
||||
}
|
||||
|
||||
private handleInitError(context: string, error: unknown): void {
|
||||
const now = Date.now();
|
||||
if (now - this.lastInitErrorAt < 5000) return;
|
||||
this.lastInitErrorAt = now;
|
||||
console.error(`[StandxExchangeAdapter] ${context} failed`, error);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,94 @@
|
||||
import type { AsterOrder, CreateOrderParams } from "../types";
|
||||
import type {
|
||||
BaseOrderIntent,
|
||||
ClosePositionIntent,
|
||||
LimitOrderIntent,
|
||||
MarketOrderIntent,
|
||||
StopOrderIntent,
|
||||
TrailingStopOrderIntent,
|
||||
} from "../order-schema";
|
||||
import { toStringBoolean } from "../order-schema";
|
||||
|
||||
function applyCommonFields(params: CreateOrderParams, intent: BaseOrderIntent): CreateOrderParams {
|
||||
if (params.quantity === undefined) {
|
||||
params.quantity = intent.quantity;
|
||||
}
|
||||
if (params.timeInForce === undefined && intent.timeInForce) {
|
||||
params.timeInForce = intent.timeInForce;
|
||||
}
|
||||
if (intent.reduceOnly !== undefined) {
|
||||
params.reduceOnly = toStringBoolean(intent.reduceOnly);
|
||||
}
|
||||
if (intent.closePosition !== undefined) {
|
||||
params.closePosition = toStringBoolean(intent.closePosition);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function createLimitOrder(intent: LimitOrderIntent): Promise<AsterOrder> {
|
||||
const params: CreateOrderParams = applyCommonFields(
|
||||
{
|
||||
symbol: intent.symbol,
|
||||
side: intent.side,
|
||||
type: "LIMIT",
|
||||
quantity: intent.quantity,
|
||||
price: intent.price,
|
||||
timeInForce: intent.timeInForce ?? "GTX",
|
||||
slPrice: intent.slPrice,
|
||||
tpPrice: intent.tpPrice,
|
||||
},
|
||||
intent
|
||||
);
|
||||
return intent.adapter.createOrder(params);
|
||||
}
|
||||
|
||||
export async function createMarketOrder(intent: MarketOrderIntent): Promise<AsterOrder> {
|
||||
const params: CreateOrderParams = applyCommonFields(
|
||||
{
|
||||
symbol: intent.symbol,
|
||||
side: intent.side,
|
||||
type: "MARKET",
|
||||
quantity: intent.quantity,
|
||||
timeInForce: intent.timeInForce ?? "IOC",
|
||||
},
|
||||
intent
|
||||
);
|
||||
return intent.adapter.createOrder(params);
|
||||
}
|
||||
|
||||
export async function createStopOrder(intent: StopOrderIntent): Promise<AsterOrder> {
|
||||
const params: CreateOrderParams = applyCommonFields(
|
||||
{
|
||||
symbol: intent.symbol,
|
||||
side: intent.side,
|
||||
type: "STOP_MARKET",
|
||||
quantity: intent.quantity,
|
||||
stopPrice: intent.stopPrice,
|
||||
timeInForce: intent.timeInForce ?? "GTC",
|
||||
reduceOnly: toStringBoolean(intent.reduceOnly ?? true),
|
||||
closePosition: toStringBoolean(intent.closePosition ?? true),
|
||||
},
|
||||
intent
|
||||
);
|
||||
return intent.adapter.createOrder(params);
|
||||
}
|
||||
|
||||
export async function createTrailingStopOrder(_intent: TrailingStopOrderIntent): Promise<AsterOrder> {
|
||||
throw new Error("StandX exchange does not support trailing stop orders");
|
||||
}
|
||||
|
||||
export async function createClosePositionOrder(intent: ClosePositionIntent): Promise<AsterOrder> {
|
||||
const params: CreateOrderParams = applyCommonFields(
|
||||
{
|
||||
symbol: intent.symbol,
|
||||
side: intent.side,
|
||||
type: "MARKET",
|
||||
quantity: intent.quantity,
|
||||
reduceOnly: "true",
|
||||
closePosition: toStringBoolean(intent.closePosition ?? true),
|
||||
timeInForce: intent.timeInForce ?? "IOC",
|
||||
},
|
||||
intent
|
||||
);
|
||||
return intent.adapter.createOrder(params);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
export interface StandxOrder {
|
||||
id?: number;
|
||||
cl_ord_id?: string;
|
||||
symbol: string;
|
||||
side: string;
|
||||
order_type: string;
|
||||
qty: string;
|
||||
price?: string;
|
||||
fill_qty?: string;
|
||||
fill_avg_price?: string;
|
||||
reduce_only?: boolean;
|
||||
time_in_force?: string;
|
||||
status?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface StandxPosition {
|
||||
symbol: string;
|
||||
qty: string;
|
||||
entry_price?: string;
|
||||
mark_price?: string;
|
||||
upnl?: string;
|
||||
leverage?: string;
|
||||
liq_price?: string;
|
||||
margin_mode?: string;
|
||||
time?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface StandxBalance {
|
||||
token: string;
|
||||
free?: string;
|
||||
locked?: string;
|
||||
total?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface StandxDepthBook {
|
||||
symbol: string;
|
||||
bids: [string, string][];
|
||||
asks: [string, string][];
|
||||
}
|
||||
|
||||
export interface StandxPrice {
|
||||
symbol: string;
|
||||
last_price?: string;
|
||||
mark_price?: string;
|
||||
index_price?: string;
|
||||
mid_price?: string;
|
||||
spread_bid?: string;
|
||||
spread_ask?: string;
|
||||
spread?: [string, string];
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export interface StandxSymbolInfo {
|
||||
symbol: string;
|
||||
price_tick_decimals?: number;
|
||||
qty_tick_decimals?: number;
|
||||
min_order_qty?: string;
|
||||
max_order_qty?: string;
|
||||
depth_ticks?: string;
|
||||
}
|
||||
|
||||
export interface StandxSymbolMarket {
|
||||
symbol: string;
|
||||
funding_rate?: string;
|
||||
next_funding_time?: string;
|
||||
}
|
||||
|
||||
export interface StandxBalanceSnapshot {
|
||||
balance?: string;
|
||||
upnl?: string;
|
||||
cross_available?: string;
|
||||
cross_balance?: string;
|
||||
isolated_balance?: string;
|
||||
cross_upnl?: string;
|
||||
isolated_upnl?: string;
|
||||
locked?: string;
|
||||
}
|
||||
|
||||
export interface StandxKlineHistory {
|
||||
s?: string;
|
||||
t?: number[];
|
||||
o?: number[];
|
||||
h?: number[];
|
||||
l?: number[];
|
||||
c?: number[];
|
||||
v?: number[];
|
||||
}
|
||||
@@ -25,6 +25,9 @@ export interface CreateOrderParams {
|
||||
reduceOnly?: StringBoolean;
|
||||
closePosition?: StringBoolean;
|
||||
triggerType?: "UNSPECIFIED" | "TAKE_PROFIT" | "STOP_LOSS";
|
||||
// StandX TPSL 参数
|
||||
slPrice?: number; // 止损价格
|
||||
tpPrice?: number; // 止盈价格
|
||||
}
|
||||
|
||||
export interface AsterAccountPosition {
|
||||
|
||||
+90
-2
@@ -25,6 +25,11 @@ const translations: Record<string, TranslationEntry> = {
|
||||
zh: "监控均线信号,自动进出场并维护止损/止盈",
|
||||
en: "Monitors SMA signals, automates entries/exits, maintains stops.",
|
||||
},
|
||||
"app.strategy.swing.label": { zh: "Swing 策略 (RSI14/4h)", en: "Swing (RSI14/4h)" },
|
||||
"app.strategy.swing.desc": {
|
||||
zh: "使用 Binance ETHBTC 4h RSI 信号,主动开平仓并维护止损",
|
||||
en: "Uses Binance ETHBTC 4h RSI signals to actively trade and maintain stops.",
|
||||
},
|
||||
"app.strategy.guardian.label": { zh: "Guardian 防守策略", en: "Guardian Protection" },
|
||||
"app.strategy.guardian.desc": {
|
||||
zh: "不主动开仓,只为现有仓位补挂/移动止损,防止裸奔",
|
||||
@@ -35,6 +40,11 @@ const translations: Record<string, TranslationEntry> = {
|
||||
zh: "双边挂单提供流动性,自动追价与风控止损",
|
||||
en: "Places two-sided quotes, auto-chases and risk-manages stops.",
|
||||
},
|
||||
"app.strategy.makerPoints.label": { zh: "StandX 积分做市策略", en: "StandX Maker Points" },
|
||||
"app.strategy.makerPoints.desc": {
|
||||
zh: "基于标记价/盘口挂单赚取 StandX Maker Points",
|
||||
en: "Quotes by mark-price bands to farm StandX maker points.",
|
||||
},
|
||||
"app.strategy.grid.label": { zh: "基础网格策略", en: "Grid Strategy" },
|
||||
"app.strategy.grid.desc": {
|
||||
zh: "在上下边界之间布设等比网格,自动加仓与减仓",
|
||||
@@ -50,6 +60,15 @@ const translations: Record<string, TranslationEntry> = {
|
||||
zh: "监控期货与现货盘口差价,辅助发现套利机会",
|
||||
en: "Monitors futures/spot spread to surface arbitrage windows.",
|
||||
},
|
||||
"app.strategy.liquidityMaker.label": { zh: "流动性做市商", en: "Liquidity Maker" },
|
||||
"app.strategy.liquidityMaker.desc": {
|
||||
zh: "成交后在更优价位挂单平仓,更敏感的深度偏移判断",
|
||||
en: "Places close orders at better prices after fills, with sensitive depth imbalance detection.",
|
||||
},
|
||||
"liquidityMaker.title": { zh: "流动性做市商 (Liquidity Maker)", en: "Liquidity Maker" },
|
||||
"liquidityMaker.initializing": { zh: "流动性做市商初始化中...", en: "Initializing Liquidity Maker..." },
|
||||
"liquidityMaker.lastFill": { zh: "最近成交: {info}", en: "Last fill: {info}" },
|
||||
"liquidityMaker.noFill": { zh: "无", en: "None" },
|
||||
"app.integrity.warning": {
|
||||
zh: "警告: 版权校验失败,当前版本可能被篡改。",
|
||||
en: "Warning: Copyright integrity check failed; build may be tampered.",
|
||||
@@ -118,6 +137,50 @@ const translations: Record<string, TranslationEntry> = {
|
||||
"trend.label.long": { zh: "做多", en: "Long" },
|
||||
"trend.label.short": { zh: "做空", en: "Short" },
|
||||
"trend.label.none": { zh: "无信号", en: "No signal" },
|
||||
"swing.name": { zh: "Swing 策略", en: "swing strategy" },
|
||||
"swing.title": { zh: "Swing 策略仪表盘", en: "Swing Strategy Dashboard" },
|
||||
"swing.readyMessage": { zh: "正在等待交易所/RSI 信号…", en: "Waiting for exchange feeds / RSI signal..." },
|
||||
"swing.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 方向: {direction} | 最近价格: {lastPrice} | 状态: {phase}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Mode: {direction} | Last: {lastPrice} | Phase: {phase}",
|
||||
},
|
||||
"swing.signalLine": {
|
||||
zh: "信号源: Binance {binanceSymbol} | 价格: {binancePrice} | RSI: {rsi} ({zone}) | 连接: {connection}",
|
||||
en: "Signal: Binance {binanceSymbol} | Price: {binancePrice} | RSI: {rsi} ({zone}) | Conn: {connection}",
|
||||
},
|
||||
"swing.statusLine": {
|
||||
zh: "状态: {status} | 按 Esc 返回策略选择",
|
||||
en: "Status: {status} | Press Esc to return to menu.",
|
||||
},
|
||||
"swing.zone.overbought": { zh: "超买", en: "Overbought" },
|
||||
"swing.zone.oversold": { zh: "超卖", en: "Oversold" },
|
||||
"swing.zone.neutral": { zh: "正常区间", en: "Neutral" },
|
||||
"swing.zone.unknown": { zh: "未知", en: "Unknown" },
|
||||
"swing.phase.disabled": { zh: "已禁用", en: "Disabled" },
|
||||
"swing.phase.initializing": { zh: "初始化/同步中", en: "Initializing" },
|
||||
"swing.phase.observing": { zh: "观察", en: "Observing" },
|
||||
"swing.phase.waitingOpenShort": { zh: "等待开空", en: "Waiting to open short" },
|
||||
"swing.phase.waitingCloseShort": { zh: "等待平空", en: "Waiting to close short" },
|
||||
"swing.phase.waitingOpenLong": { zh: "等待开多", en: "Waiting to open long" },
|
||||
"swing.phase.waitingCloseLong": { zh: "等待平多", en: "Waiting to close long" },
|
||||
"swing.positionLine": {
|
||||
zh: "方向: {direction} | 数量: {qty} | 开仓价: {entry}",
|
||||
en: "Direction: {direction} | Size: {qty} | Entry: {entry}",
|
||||
},
|
||||
"swing.pnlLine": {
|
||||
zh: "浮动盈亏: {pnl} USDT | 账户未实现盈亏: {unrealized} USDT",
|
||||
en: "Floating PnL: {pnl} USDT | Account Unrealized: {unrealized} USDT",
|
||||
},
|
||||
"swing.stopLine": {
|
||||
zh: "止损目标价: {stop}",
|
||||
en: "Stop target: {stop}",
|
||||
},
|
||||
"swing.stateTitle": { zh: "策略状态", en: "Strategy State" },
|
||||
"swing.armedLine": {
|
||||
zh: "Armed: SE={se} SX={sx} | LE={le} LX={lx}",
|
||||
en: "Armed: SE={se} SX={sx} | LE={le} LX={lx}",
|
||||
},
|
||||
"swing.volumeLine": { zh: "累计成交量: {volume} USDT", en: "Total volume: {volume} USDT" },
|
||||
"guardian.name": { zh: "Guardian 策略", en: "Guardian strategy" },
|
||||
"guardian.title": { zh: "Guardian 策略仪表盘", en: "Guardian Strategy Dashboard" },
|
||||
"guardian.readyMessage": { zh: "正在等待行情/账户推送…", en: "Waiting for market/account feeds..." },
|
||||
@@ -174,6 +237,27 @@ const translations: Record<string, TranslationEntry> = {
|
||||
},
|
||||
"maker.targetOrders": { zh: "目标挂单", en: "Target Orders" },
|
||||
"maker.noTargetOrders": { zh: "暂无目标挂单", en: "No target orders" },
|
||||
"makerPoints.title": { zh: "Maker Points 策略仪表盘", en: "Maker Points Dashboard" },
|
||||
"makerPoints.initializing": { zh: "正在初始化 Maker Points 策略…", en: "Initializing Maker Points strategy..." },
|
||||
"makerPoints.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 买一价: {bid} | 卖一价: {ask} | 点差: {spread}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Best Bid: {bid} | Best Ask: {ask} | Spread: {spread}",
|
||||
},
|
||||
"makerPoints.quoteLine": {
|
||||
zh: "挂单模式: {mode} | BUY {buy} | SELL {sell}",
|
||||
en: "Quote mode: {mode} | BUY {buy} | SELL {sell}",
|
||||
},
|
||||
"makerPoints.binanceLine": {
|
||||
zh: "Binance 深度: 买10 {buy} | 卖10 {sell} | 状态: {status}",
|
||||
en: "Binance depth: bid10 {buy} | ask10 {sell} | Status: {status}",
|
||||
},
|
||||
"makerPoints.bandDepthLine": {
|
||||
zh: "StandX 档位 {band}bps 深度: 买 {buy} | 卖 {sell}",
|
||||
en: "StandX band {band}bps depth: buy {buy} | sell {sell}",
|
||||
},
|
||||
"makerPoints.mode.closeOnly": { zh: "平仓", en: "Close only" },
|
||||
"makerPoints.mode.normal": { zh: "正常", en: "Normal" },
|
||||
"makerPoints.feed.binance": { zh: "Binance", en: "Binance" },
|
||||
"offset.name": { zh: "偏移做市策略", en: "offset maker strategy" },
|
||||
"offset.title": { zh: "偏移做市策略仪表盘", en: "Offset Maker Strategy Dashboard" },
|
||||
"offset.initializing": { zh: "正在初始化偏移做市策略…", en: "Initializing offset maker strategy..." },
|
||||
@@ -229,8 +313,8 @@ const translations: Record<string, TranslationEntry> = {
|
||||
"grid.direction.long": { zh: "多", en: "Long" },
|
||||
"grid.direction.short": { zh: "空", en: "Short" },
|
||||
"basis.onlyAster": {
|
||||
zh: "期现套利策略目前仅支持 Aster / Nado 交易所。请设置 EXCHANGE=aster 或 EXCHANGE=nado 后重试。",
|
||||
en: "Basis arbitrage currently supports only Aster and Nado. Set EXCHANGE=aster or EXCHANGE=nado and retry.",
|
||||
zh: "期现套利策略目前仅支持 Aster / Nado / StandX 交易所。请设置 EXCHANGE=aster 或 EXCHANGE=nado 或 EXCHANGE=standx 后重试。",
|
||||
en: "Basis arbitrage currently supports only Aster, Nado, and StandX. Set EXCHANGE=aster, EXCHANGE=nado, or EXCHANGE=standx and retry.",
|
||||
},
|
||||
"basis.startFailed": {
|
||||
zh: "无法启动期现套利策略: {message}",
|
||||
@@ -338,6 +422,10 @@ const translations: Record<string, TranslationEntry> = {
|
||||
zh: "NADO_SUBACCOUNT_OWNER / NADO_EVM_ADDRESS 必须是有效的 0x 开头 40 字节十六进制地址",
|
||||
en: "NADO_SUBACCOUNT_OWNER / NADO_EVM_ADDRESS must be a valid 0x-prefixed 40-byte hex address",
|
||||
},
|
||||
"env.missingStandx": {
|
||||
zh: "StandX 需要配置 STANDX_TOKEN",
|
||||
en: "StandX requires STANDX_TOKEN",
|
||||
},
|
||||
"log.subscribe.accountFail": {
|
||||
zh: "订阅账户失败: {error}",
|
||||
en: "Failed to subscribe account: {error}",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
export type {
|
||||
NotificationLevel,
|
||||
TradeNotification,
|
||||
NotificationSender,
|
||||
NotificationConfig,
|
||||
} from "./types";
|
||||
|
||||
export {
|
||||
TelegramNotifier,
|
||||
createTelegramNotifier,
|
||||
type TelegramConfig,
|
||||
} from "./telegram";
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { NotificationSender, TradeNotification, NotificationConfig } from "./types";
|
||||
|
||||
export interface TelegramConfig extends NotificationConfig {
|
||||
botToken: string;
|
||||
chatId: string;
|
||||
}
|
||||
|
||||
const LEVEL_EMOJI: Record<string, string> = {
|
||||
info: "ℹ️",
|
||||
warn: "⚠️",
|
||||
error: "🚨",
|
||||
success: "✅",
|
||||
};
|
||||
|
||||
const TYPE_EMOJI: Record<string, string> = {
|
||||
order_filled: "📝",
|
||||
position_opened: "📈",
|
||||
position_closed: "📉",
|
||||
stop_loss: "🛑",
|
||||
token_expired: "⏰",
|
||||
custom: "📢",
|
||||
};
|
||||
|
||||
const LOG_PREFIX = "[Telegram]";
|
||||
|
||||
function formatNotificationMessage(notification: TradeNotification, accountLabel?: string): string {
|
||||
const levelEmoji = LEVEL_EMOJI[notification.level] ?? "";
|
||||
const typeEmoji = TYPE_EMOJI[notification.type] ?? "";
|
||||
const timestamp = notification.timestamp ?? Date.now();
|
||||
const time = new Date(timestamp).toISOString().replace("T", " ").substring(0, 19);
|
||||
|
||||
const label = notification.accountLabel ?? accountLabel ?? notification.symbol;
|
||||
|
||||
const lines: string[] = [
|
||||
`${typeEmoji}${levelEmoji} [${label}] ${notification.title}`,
|
||||
``,
|
||||
`${notification.message}`,
|
||||
];
|
||||
|
||||
if (notification.details && Object.keys(notification.details).length > 0) {
|
||||
lines.push(``);
|
||||
for (const [key, value] of Object.entries(notification.details)) {
|
||||
if (value != null) {
|
||||
if (Array.isArray(value)) {
|
||||
lines.push(`• ${key}: ${value.join(", ") || "[]"}`);
|
||||
} else {
|
||||
lines.push(`• ${key}: ${value}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(``);
|
||||
lines.push(`🕐 ${time} UTC`);
|
||||
lines.push(`📊 ${notification.symbol}`);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export class TelegramNotifier implements NotificationSender {
|
||||
private readonly config: TelegramConfig;
|
||||
private readonly baseUrl: string;
|
||||
private sendQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(config: Partial<TelegramConfig> = {}) {
|
||||
this.config = {
|
||||
enabled: Boolean(config.botToken && config.chatId),
|
||||
botToken: config.botToken ?? "",
|
||||
chatId: config.chatId ?? "",
|
||||
accountLabel: config.accountLabel,
|
||||
};
|
||||
this.baseUrl = `https://api.telegram.org/bot${this.config.botToken}`;
|
||||
}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return this.config.enabled;
|
||||
}
|
||||
|
||||
async send(notification: TradeNotification): Promise<void> {
|
||||
if (!this.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.sendQueue = this.sendQueue
|
||||
.then(() => this.doSend(notification))
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
private async doSend(notification: TradeNotification): Promise<void> {
|
||||
const text = formatNotificationMessage(notification, this.config.accountLabel);
|
||||
const url = `${this.baseUrl}/sendMessage`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
chat_id: this.config.chatId,
|
||||
text,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
console.info(`${LOG_PREFIX} Notification sent (status ${response.status}).`);
|
||||
return;
|
||||
}
|
||||
const errorText = await response.text().catch(() => "unknown error");
|
||||
console.error(`${LOG_PREFIX} Failed to send notification: ${response.status} ${errorText}`);
|
||||
} catch (error) {
|
||||
console.error(`${LOG_PREFIX} Failed to send notification: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createTelegramNotifier(): TelegramNotifier {
|
||||
return new TelegramNotifier({
|
||||
botToken: process.env.TELEGRAM_BOT_TOKEN,
|
||||
chatId: process.env.TELEGRAM_CHAT_ID,
|
||||
accountLabel: process.env.TELEGRAM_ACCOUNT_LABEL,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export type NotificationLevel = "info" | "warn" | "error" | "success";
|
||||
|
||||
export interface TradeNotification {
|
||||
type: "order_filled" | "position_opened" | "position_closed" | "stop_loss" | "token_expired" | "custom";
|
||||
level: NotificationLevel;
|
||||
symbol: string;
|
||||
title: string;
|
||||
message: string;
|
||||
accountLabel?: string;
|
||||
details?: Record<string, string | number | boolean | null | string[]>;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface NotificationSender {
|
||||
send(notification: TradeNotification): Promise<void>;
|
||||
isEnabled(): boolean;
|
||||
}
|
||||
|
||||
export interface NotificationConfig {
|
||||
enabled: boolean;
|
||||
accountLabel?: string;
|
||||
}
|
||||
@@ -167,7 +167,7 @@ export class BasisArbEngine {
|
||||
}
|
||||
);
|
||||
|
||||
if (this.exchange.id === "nado") {
|
||||
if (this.exchange.id === "nado" || this.exchange.id === "standx") {
|
||||
safeSubscribe<AsterDepth>(
|
||||
this.exchange.watchDepth.bind(this.exchange, this.config.spotSymbol),
|
||||
(depth) => {
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
import NodeWebSocket from "ws";
|
||||
import { computeDepthStats, type DepthImbalance } from "../../utils/depth";
|
||||
|
||||
const WebSocketCtor: typeof globalThis.WebSocket =
|
||||
typeof globalThis.WebSocket !== "undefined"
|
||||
? globalThis.WebSocket
|
||||
: ((NodeWebSocket as unknown) as typeof globalThis.WebSocket);
|
||||
|
||||
const DEFAULT_BASE_URL = "wss://stream.binance.com:9443/ws";
|
||||
|
||||
// ========== Binance WebSocket 连接管理常量 ==========
|
||||
// Binance 会发送 ping,若长时间无消息则认为连接异常
|
||||
// 我们设置 5 分钟作为心跳超时阈值(保守值)
|
||||
const HEARTBEAT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
// 心跳检查间隔(每 30 秒检查一次)
|
||||
const HEARTBEAT_CHECK_INTERVAL_MS = 30_000;
|
||||
// Binance 连接最长有效期 24 小时,我们设置 23 小时主动重连
|
||||
const MAX_CONNECTION_DURATION_MS = 23 * 60 * 60 * 1000;
|
||||
// 数据过时阈值(毫秒)- 超过此时间未收到数据,标记为不可用
|
||||
const DATA_STALE_THRESHOLD_MS = 5_000;
|
||||
// 基础重连延迟
|
||||
const RECONNECT_DELAY_BASE_MS = 3000;
|
||||
// 最大重连延迟
|
||||
const RECONNECT_DELAY_MAX_MS = 60_000;
|
||||
|
||||
export type BinanceConnectionState = "connected" | "disconnected" | "stale";
|
||||
|
||||
export interface BinanceDepthSnapshot {
|
||||
symbol: string;
|
||||
buySum: number;
|
||||
sellSum: number;
|
||||
skipBuySide: boolean;
|
||||
skipSellSide: boolean;
|
||||
imbalance: DepthImbalance;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export type BinanceConnectionListener = (state: BinanceConnectionState) => void;
|
||||
|
||||
export class BinanceDepthTracker {
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
private stopped = false;
|
||||
private snapshot: BinanceDepthSnapshot | null = null;
|
||||
private listeners = new Set<(snapshot: BinanceDepthSnapshot) => void>();
|
||||
private connectionListeners = new Set<BinanceConnectionListener>();
|
||||
|
||||
// ========== 心跳与连接管理 ==========
|
||||
// 上次收到消息的时间戳
|
||||
private lastMessageTime = 0;
|
||||
// 心跳检查定时器
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
// 连接建立时间(用于日志记录)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
private connectionStartTime = 0;
|
||||
// 24 小时重连定时器
|
||||
private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
// 当前连接状态
|
||||
private connectionState: BinanceConnectionState = "disconnected";
|
||||
|
||||
constructor(
|
||||
private readonly symbol: string,
|
||||
private readonly options?: {
|
||||
baseUrl?: string;
|
||||
levels?: number;
|
||||
ratio?: number;
|
||||
speedMs?: number;
|
||||
logger?: (context: string, error: unknown) => void;
|
||||
}
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
onUpdate(handler: (snapshot: BinanceDepthSnapshot) => void): void {
|
||||
this.listeners.add(handler);
|
||||
}
|
||||
|
||||
offUpdate(handler: (snapshot: BinanceDepthSnapshot) => void): void {
|
||||
this.listeners.delete(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听连接状态变化
|
||||
*/
|
||||
onConnectionChange(handler: BinanceConnectionListener): void {
|
||||
this.connectionListeners.add(handler);
|
||||
}
|
||||
|
||||
offConnectionChange(handler: BinanceConnectionListener): void {
|
||||
this.connectionListeners.delete(handler);
|
||||
}
|
||||
|
||||
getSnapshot(): BinanceDepthSnapshot | null {
|
||||
return this.snapshot ? { ...this.snapshot } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前连接状态
|
||||
*/
|
||||
getConnectionState(): BinanceConnectionState {
|
||||
return this.connectionState;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查数据是否过时
|
||||
*/
|
||||
isDataStale(): boolean {
|
||||
if (!this.snapshot) return true;
|
||||
return Date.now() - this.snapshot.updatedAt > DATA_STALE_THRESHOLD_MS;
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
// 停止心跳监控
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
// 停止 24 小时重连定时器
|
||||
if (this.maxDurationTimer) {
|
||||
clearTimeout(this.maxDurationTimer);
|
||||
this.maxDurationTimer = null;
|
||||
}
|
||||
// 停止重连定时器
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
// 关闭 WebSocket
|
||||
if (this.ws) {
|
||||
try {
|
||||
this.ws.close();
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.ws || this.stopped) return;
|
||||
const url = this.buildUrl();
|
||||
this.ws = new WebSocketCtor(url);
|
||||
|
||||
const handleOpen = () => {
|
||||
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
this.connectionStartTime = Date.now();
|
||||
this.lastMessageTime = Date.now();
|
||||
this.updateConnectionState("connected");
|
||||
|
||||
// 启动心跳监控
|
||||
this.startHeartbeatMonitor();
|
||||
// 启动 24 小时自动重连定时器
|
||||
this.startMaxDurationTimer();
|
||||
|
||||
this.options?.logger?.("binanceDepth", "WebSocket connected");
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
this.ws = null;
|
||||
this.stopHeartbeatMonitor();
|
||||
this.stopMaxDurationTimer();
|
||||
this.updateConnectionState("disconnected");
|
||||
|
||||
if (!this.stopped) {
|
||||
this.options?.logger?.("binanceDepth", "WebSocket closed, scheduling reconnect");
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
this.options?.logger?.("binanceDepth", error);
|
||||
// 如果连接从未成功建立,需要清理并重连
|
||||
if (this.ws && this.connectionState === "disconnected") {
|
||||
this.ws = null;
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const handleMessage = (event: { data: unknown }) => {
|
||||
this.lastMessageTime = Date.now();
|
||||
// 如果之前是 stale 状态,恢复为 connected
|
||||
if (this.connectionState === "stale") {
|
||||
this.updateConnectionState("connected");
|
||||
}
|
||||
this.handlePayload(event.data);
|
||||
};
|
||||
|
||||
// 处理 Binance 服务器的 ping 帧
|
||||
// 根据文档:必须尽快回复 pong,payload 为 ping 的 payload 副本
|
||||
const handlePing = (data: unknown) => {
|
||||
this.lastMessageTime = Date.now();
|
||||
if (this.ws && "pong" in this.ws && typeof this.ws.pong === "function") {
|
||||
try {
|
||||
this.ws.pong(data as any);
|
||||
} catch (error) {
|
||||
this.options?.logger?.("binanceDepth pong", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if ("addEventListener" in this.ws && typeof this.ws.addEventListener === "function") {
|
||||
this.ws.addEventListener("open", handleOpen);
|
||||
this.ws.addEventListener("message", handleMessage as any);
|
||||
this.ws.addEventListener("close", handleClose);
|
||||
this.ws.addEventListener("error", handleError as any);
|
||||
this.ws.addEventListener("ping", handlePing as any);
|
||||
} else if ("on" in this.ws && typeof (this.ws as any).on === "function") {
|
||||
const nodeSocket = this.ws as any;
|
||||
nodeSocket.on("open", handleOpen);
|
||||
nodeSocket.on("message", (data: unknown) => handleMessage({ data }));
|
||||
nodeSocket.on("close", handleClose);
|
||||
nodeSocket.on("error", handleError);
|
||||
nodeSocket.on("ping", handlePing);
|
||||
} else {
|
||||
(this.ws as any).onopen = handleOpen;
|
||||
(this.ws as any).onmessage = handleMessage;
|
||||
(this.ws as any).onclose = handleClose;
|
||||
(this.ws as any).onerror = handleError;
|
||||
}
|
||||
}
|
||||
|
||||
private buildUrl(): string {
|
||||
const base = this.options?.baseUrl ?? DEFAULT_BASE_URL;
|
||||
const levels = this.options?.levels ?? 10;
|
||||
const speed = this.options?.speedMs ?? 100;
|
||||
const stream = `${this.symbol.toLowerCase()}@depth${levels}@${speed}ms`;
|
||||
return `${base}/${stream}`;
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer || this.stopped) return;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, RECONNECT_DELAY_MAX_MS);
|
||||
this.connect();
|
||||
}, this.reconnectDelayMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动心跳监控
|
||||
* 根据 Binance 文档:长时间无 pong 会断连
|
||||
* 我们设置 5 分钟作为心跳超时阈值
|
||||
*/
|
||||
private startHeartbeatMonitor(): void {
|
||||
this.stopHeartbeatMonitor();
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
const elapsed = now - this.lastMessageTime;
|
||||
|
||||
// 检查数据是否过时(5 秒无数据)
|
||||
if (elapsed > DATA_STALE_THRESHOLD_MS && this.connectionState === "connected") {
|
||||
this.updateConnectionState("stale");
|
||||
this.options?.logger?.("binanceDepth", `Data stale: ${elapsed}ms since last message`);
|
||||
}
|
||||
|
||||
// 检查心跳超时(5 分钟无消息)
|
||||
if (elapsed > HEARTBEAT_TIMEOUT_MS) {
|
||||
this.options?.logger?.("binanceDepth", `Heartbeat timeout: ${elapsed}ms, forcing reconnect`);
|
||||
this.forceReconnect("heartbeat_timeout");
|
||||
}
|
||||
}, HEARTBEAT_CHECK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private stopHeartbeatMonitor(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动 24 小时自动重连定时器
|
||||
* 根据 Binance 文档:连接最长有效期 24 小时
|
||||
* 我们设置 23 小时主动重连,避免被服务器断开
|
||||
*/
|
||||
private startMaxDurationTimer(): void {
|
||||
this.stopMaxDurationTimer();
|
||||
this.maxDurationTimer = setTimeout(() => {
|
||||
this.options?.logger?.("binanceDepth", "Max connection duration reached (23h), reconnecting");
|
||||
this.forceReconnect("max_duration");
|
||||
}, MAX_CONNECTION_DURATION_MS);
|
||||
}
|
||||
|
||||
private stopMaxDurationTimer(): void {
|
||||
if (this.maxDurationTimer) {
|
||||
clearTimeout(this.maxDurationTimer);
|
||||
this.maxDurationTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重连
|
||||
*/
|
||||
private forceReconnect(reason: string): void {
|
||||
this.options?.logger?.("binanceDepth", `Force reconnect: ${reason}`);
|
||||
this.stopHeartbeatMonitor();
|
||||
this.stopMaxDurationTimer();
|
||||
|
||||
if (this.ws) {
|
||||
try {
|
||||
this.ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
this.updateConnectionState("disconnected");
|
||||
// 立即重连(不使用指数退避)
|
||||
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新连接状态并通知监听器
|
||||
*/
|
||||
private updateConnectionState(state: BinanceConnectionState): void {
|
||||
if (this.connectionState === state) return;
|
||||
this.connectionState = state;
|
||||
for (const listener of this.connectionListeners) {
|
||||
try {
|
||||
listener(state);
|
||||
} catch (error) {
|
||||
this.options?.logger?.("binanceDepth connectionListener", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handlePayload(data: unknown): void {
|
||||
const payload = this.parsePayload(data);
|
||||
if (!payload) return;
|
||||
const bids = Array.isArray(payload.b) ? payload.b : Array.isArray(payload.bids) ? payload.bids : [];
|
||||
const asks = Array.isArray(payload.a) ? payload.a : Array.isArray(payload.asks) ? payload.asks : [];
|
||||
const depth = {
|
||||
lastUpdateId: Number(payload.lastUpdateId ?? payload.u ?? Date.now()),
|
||||
bids,
|
||||
asks,
|
||||
};
|
||||
const levels = this.options?.levels ?? 10;
|
||||
const ratio = this.options?.ratio ?? 3;
|
||||
const stats = computeDepthStats(depth, levels, ratio);
|
||||
this.snapshot = {
|
||||
symbol: this.symbol,
|
||||
buySum: stats.buySum,
|
||||
sellSum: stats.sellSum,
|
||||
skipBuySide: stats.skipBuySide,
|
||||
skipSellSide: stats.skipSellSide,
|
||||
imbalance: stats.imbalance,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
listener({ ...this.snapshot });
|
||||
} catch (error) {
|
||||
this.options?.logger?.("binanceDepth listener", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private parsePayload(
|
||||
data: unknown
|
||||
): { b?: [string, string][]; a?: [string, string][]; bids?: [string, string][]; asks?: [string, string][]; u?: number; lastUpdateId?: number } | null {
|
||||
try {
|
||||
const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf-8") : null;
|
||||
if (!text) return null;
|
||||
const parsed = JSON.parse(text);
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return parsed as {
|
||||
b?: [string, string][];
|
||||
a?: [string, string][];
|
||||
bids?: [string, string][];
|
||||
asks?: [string, string][];
|
||||
u?: number;
|
||||
lastUpdateId?: number;
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
import NodeWebSocket from "ws";
|
||||
import { RSI } from "trading-signals";
|
||||
|
||||
const WebSocketCtor: typeof globalThis.WebSocket =
|
||||
typeof globalThis.WebSocket !== "undefined"
|
||||
? globalThis.WebSocket
|
||||
: ((NodeWebSocket as unknown) as typeof globalThis.WebSocket);
|
||||
|
||||
const DEFAULT_REST_BASE_URL = "https://api.binance.com";
|
||||
const DEFAULT_WS_BASE_URL = "wss://stream.binance.com:9443/ws";
|
||||
|
||||
// Binance sends frequent kline updates (typically 2s). We treat longer silence as stale.
|
||||
const DATA_STALE_THRESHOLD_MS = 10_000;
|
||||
const HEARTBEAT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
const HEARTBEAT_CHECK_INTERVAL_MS = 30_000;
|
||||
const MAX_CONNECTION_DURATION_MS = 23 * 60 * 60 * 1000;
|
||||
|
||||
const RECONNECT_DELAY_BASE_MS = 2000;
|
||||
const RECONNECT_DELAY_MAX_MS = 60_000;
|
||||
|
||||
export type BinanceConnectionState = "connected" | "disconnected" | "stale";
|
||||
|
||||
export interface BinanceRsiSnapshot {
|
||||
symbol: string;
|
||||
interval: string;
|
||||
rsiPeriod: number;
|
||||
rsi: number | null;
|
||||
isStable: boolean;
|
||||
lastClose: number | null;
|
||||
candleOpenTime: number | null;
|
||||
candleClosed: boolean | null;
|
||||
updatedAt: number | null;
|
||||
connectionState: BinanceConnectionState;
|
||||
}
|
||||
|
||||
type BinanceRsiListener = (snapshot: BinanceRsiSnapshot) => void;
|
||||
|
||||
export class BinanceRsiTracker {
|
||||
private ws: WebSocket | null = null;
|
||||
private stopped = false;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastMessageTime = 0;
|
||||
private connectionState: BinanceConnectionState = "disconnected";
|
||||
|
||||
private rsi: RSI;
|
||||
private candleOpenTime: number | null = null;
|
||||
private candleClosed: boolean | null = null;
|
||||
private lastClose: number | null = null;
|
||||
private updatedAt: number | null = null;
|
||||
|
||||
private listeners = new Set<BinanceRsiListener>();
|
||||
|
||||
constructor(
|
||||
private readonly symbol: string,
|
||||
private readonly interval: string,
|
||||
private readonly rsiPeriod: number,
|
||||
private readonly options?: {
|
||||
restBaseUrl?: string;
|
||||
wsBaseUrl?: string;
|
||||
limit?: number;
|
||||
logger?: (context: string, error: unknown) => void;
|
||||
}
|
||||
) {
|
||||
this.rsi = new RSI(this.rsiPeriod);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
void this.seedAndConnect("startup");
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
onUpdate(handler: BinanceRsiListener): void {
|
||||
this.listeners.add(handler);
|
||||
}
|
||||
|
||||
offUpdate(handler: BinanceRsiListener): void {
|
||||
this.listeners.delete(handler);
|
||||
}
|
||||
|
||||
getSnapshot(): BinanceRsiSnapshot {
|
||||
return this.buildSnapshot();
|
||||
}
|
||||
|
||||
private buildSnapshot(): BinanceRsiSnapshot {
|
||||
const rsiValue = this.rsi.getResult();
|
||||
const rsi = typeof rsiValue === "number" && Number.isFinite(rsiValue) ? rsiValue : null;
|
||||
return {
|
||||
symbol: this.symbol,
|
||||
interval: this.interval,
|
||||
rsiPeriod: this.rsiPeriod,
|
||||
rsi,
|
||||
isStable: this.rsi.isStable === true,
|
||||
lastClose: this.lastClose,
|
||||
candleOpenTime: this.candleOpenTime,
|
||||
candleClosed: this.candleClosed,
|
||||
updatedAt: this.updatedAt,
|
||||
connectionState: this.connectionState,
|
||||
};
|
||||
}
|
||||
|
||||
private emitUpdate(): void {
|
||||
const snapshot = this.buildSnapshot();
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
listener(snapshot);
|
||||
} catch (error) {
|
||||
this.options?.logger?.("binanceRsi listener", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
if (this.maxDurationTimer) {
|
||||
clearTimeout(this.maxDurationTimer);
|
||||
this.maxDurationTimer = null;
|
||||
}
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.ws) {
|
||||
try {
|
||||
this.ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.ws = null;
|
||||
}
|
||||
this.updateConnectionState("disconnected");
|
||||
}
|
||||
|
||||
private updateConnectionState(next: BinanceConnectionState): void {
|
||||
if (this.connectionState === next) return;
|
||||
this.connectionState = next;
|
||||
this.emitUpdate();
|
||||
}
|
||||
|
||||
private scheduleReconnect(reason: string): void {
|
||||
if (this.reconnectTimer || this.stopped) return;
|
||||
this.options?.logger?.("binanceRsi", `Scheduling reconnect: ${reason}`);
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, RECONNECT_DELAY_MAX_MS);
|
||||
void this.seedAndConnect(`reconnect:${reason}`);
|
||||
}, this.reconnectDelayMs);
|
||||
}
|
||||
|
||||
private forceReconnect(reason: string): void {
|
||||
if (this.stopped) return;
|
||||
this.options?.logger?.("binanceRsi", `Force reconnect: ${reason}`);
|
||||
// Stop timers and close WS; keep RSI state (we will reseed on reconnect).
|
||||
this.stopHeartbeatMonitor();
|
||||
this.stopMaxDurationTimer();
|
||||
if (this.ws) {
|
||||
try {
|
||||
this.ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.ws = null;
|
||||
}
|
||||
this.updateConnectionState("disconnected");
|
||||
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
this.scheduleReconnect(reason);
|
||||
}
|
||||
|
||||
private startHeartbeatMonitor(): void {
|
||||
if (this.heartbeatTimer) return;
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
const elapsed = Date.now() - this.lastMessageTime;
|
||||
if (elapsed > DATA_STALE_THRESHOLD_MS && this.connectionState === "connected") {
|
||||
this.updateConnectionState("stale");
|
||||
}
|
||||
if (elapsed > HEARTBEAT_TIMEOUT_MS) {
|
||||
this.forceReconnect(`heartbeat_timeout:${elapsed}`);
|
||||
}
|
||||
}, HEARTBEAT_CHECK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private stopHeartbeatMonitor(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private startMaxDurationTimer(): void {
|
||||
if (this.maxDurationTimer) return;
|
||||
this.maxDurationTimer = setTimeout(() => {
|
||||
this.forceReconnect("max_duration");
|
||||
}, MAX_CONNECTION_DURATION_MS);
|
||||
}
|
||||
|
||||
private stopMaxDurationTimer(): void {
|
||||
if (this.maxDurationTimer) {
|
||||
clearTimeout(this.maxDurationTimer);
|
||||
this.maxDurationTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private buildRestUrl(): string {
|
||||
const base = this.options?.restBaseUrl ?? DEFAULT_REST_BASE_URL;
|
||||
return base;
|
||||
}
|
||||
|
||||
private buildWsUrl(): string {
|
||||
const base = this.options?.wsBaseUrl ?? DEFAULT_WS_BASE_URL;
|
||||
const stream = `${this.symbol.toLowerCase()}@kline_${this.interval}`;
|
||||
return `${base}/${stream}`;
|
||||
}
|
||||
|
||||
private async seedAndConnect(reason: string): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
try {
|
||||
await this.seedFromRest();
|
||||
} catch (error) {
|
||||
this.options?.logger?.(`binanceRsi seed (${reason})`, error);
|
||||
this.scheduleReconnect(`seed_failed:${reason}`);
|
||||
return;
|
||||
}
|
||||
this.connectWs(reason);
|
||||
}
|
||||
|
||||
private async seedFromRest(): Promise<void> {
|
||||
const limit = Math.max(10, Math.floor(this.options?.limit ?? 500));
|
||||
const base = this.buildRestUrl();
|
||||
const url = new URL("/api/v3/klines", base);
|
||||
url.searchParams.set("symbol", this.symbol.toUpperCase());
|
||||
url.searchParams.set("interval", this.interval);
|
||||
url.searchParams.set("limit", String(limit));
|
||||
|
||||
const res = await fetch(url.toString(), { method: "GET" });
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`Binance klines HTTP ${res.status}: ${text.slice(0, 200)}`);
|
||||
}
|
||||
const data = (await res.json()) as unknown;
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error("Binance klines response is not an array");
|
||||
}
|
||||
|
||||
// Reset RSI from scratch for determinism.
|
||||
this.rsi = new RSI(this.rsiPeriod);
|
||||
this.candleOpenTime = null;
|
||||
this.candleClosed = null;
|
||||
this.lastClose = null;
|
||||
this.updatedAt = null;
|
||||
|
||||
// Binance kline array format:
|
||||
// [ openTime, open, high, low, close, volume, closeTime, ... ]
|
||||
const rows = data
|
||||
.map((row) => (Array.isArray(row) ? row : null))
|
||||
.filter((row): row is any[] => Array.isArray(row) && row.length >= 7)
|
||||
.map((row) => ({
|
||||
openTime: Number(row[0]),
|
||||
close: Number(row[4]),
|
||||
closeTime: Number(row[6]),
|
||||
}))
|
||||
.filter((k) => Number.isFinite(k.openTime) && Number.isFinite(k.close) && Number.isFinite(k.closeTime))
|
||||
.sort((a, b) => a.openTime - b.openTime);
|
||||
|
||||
for (const k of rows) {
|
||||
this.rsi.add(k.close);
|
||||
this.candleOpenTime = k.openTime;
|
||||
this.candleClosed = true;
|
||||
this.lastClose = k.close;
|
||||
this.updatedAt = Date.now();
|
||||
}
|
||||
|
||||
// Last bar may still be forming; we treat it as replaceable.
|
||||
if (rows.length > 0) {
|
||||
this.candleClosed = false;
|
||||
}
|
||||
|
||||
this.emitUpdate();
|
||||
}
|
||||
|
||||
private connectWs(reason: string): void {
|
||||
if (this.ws || this.stopped) return;
|
||||
const url = this.buildWsUrl();
|
||||
this.ws = new WebSocketCtor(url);
|
||||
|
||||
const handleOpen = () => {
|
||||
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
|
||||
this.lastMessageTime = Date.now();
|
||||
this.updateConnectionState("connected");
|
||||
this.startHeartbeatMonitor();
|
||||
this.startMaxDurationTimer();
|
||||
this.options?.logger?.("binanceRsi", `WebSocket connected (${reason})`);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
this.ws = null;
|
||||
this.stopHeartbeatMonitor();
|
||||
this.stopMaxDurationTimer();
|
||||
if (!this.stopped) {
|
||||
this.updateConnectionState("disconnected");
|
||||
this.scheduleReconnect("ws_close");
|
||||
}
|
||||
};
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
this.options?.logger?.("binanceRsi", error);
|
||||
};
|
||||
|
||||
const handlePing = (data: unknown) => {
|
||||
this.lastMessageTime = Date.now();
|
||||
if (this.ws && "pong" in this.ws && typeof this.ws.pong === "function") {
|
||||
try {
|
||||
this.ws.pong(data as any);
|
||||
} catch (error) {
|
||||
this.options?.logger?.("binanceRsi pong", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleMessage = (event: { data: unknown }) => {
|
||||
this.lastMessageTime = Date.now();
|
||||
if (this.connectionState === "stale") {
|
||||
this.updateConnectionState("connected");
|
||||
}
|
||||
this.handlePayload(event.data);
|
||||
};
|
||||
|
||||
if ("addEventListener" in this.ws && typeof this.ws.addEventListener === "function") {
|
||||
this.ws.addEventListener("open", handleOpen);
|
||||
this.ws.addEventListener("message", handleMessage as any);
|
||||
this.ws.addEventListener("close", handleClose);
|
||||
this.ws.addEventListener("error", handleError as any);
|
||||
this.ws.addEventListener("ping", handlePing as any);
|
||||
} else if ("on" in this.ws && typeof (this.ws as any).on === "function") {
|
||||
const nodeSocket = this.ws as any;
|
||||
nodeSocket.on("open", handleOpen);
|
||||
nodeSocket.on("message", (data: unknown) => handleMessage({ data }));
|
||||
nodeSocket.on("close", handleClose);
|
||||
nodeSocket.on("error", handleError);
|
||||
nodeSocket.on("ping", handlePing);
|
||||
} else {
|
||||
(this.ws as any).onopen = handleOpen;
|
||||
(this.ws as any).onmessage = handleMessage;
|
||||
(this.ws as any).onclose = handleClose;
|
||||
(this.ws as any).onerror = handleError;
|
||||
}
|
||||
}
|
||||
|
||||
private handlePayload(data: unknown): void {
|
||||
const parsed = this.parsePayload(data);
|
||||
if (!parsed) return;
|
||||
const openTime = Number(parsed.openTime);
|
||||
const close = Number(parsed.close);
|
||||
const isClosed = Boolean(parsed.isClosed);
|
||||
if (!Number.isFinite(openTime) || !Number.isFinite(close)) return;
|
||||
|
||||
this.applyCandleUpdate({ openTime, close, isClosed });
|
||||
}
|
||||
|
||||
private applyCandleUpdate(params: { openTime: number; close: number; isClosed: boolean }): void {
|
||||
const { openTime, close, isClosed } = params;
|
||||
|
||||
if (this.candleOpenTime == null) {
|
||||
this.rsi.add(close);
|
||||
this.candleOpenTime = openTime;
|
||||
this.candleClosed = isClosed;
|
||||
this.lastClose = close;
|
||||
this.updatedAt = Date.now();
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
if (openTime < this.candleOpenTime) {
|
||||
// Out-of-order update; ignore.
|
||||
return;
|
||||
}
|
||||
|
||||
if (openTime === this.candleOpenTime) {
|
||||
// Same candle: replace last close.
|
||||
this.rsi.replace(close);
|
||||
this.candleClosed = isClosed;
|
||||
this.lastClose = close;
|
||||
this.updatedAt = Date.now();
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
// New candle started.
|
||||
this.rsi.add(close);
|
||||
this.candleOpenTime = openTime;
|
||||
this.candleClosed = isClosed;
|
||||
this.lastClose = close;
|
||||
this.updatedAt = Date.now();
|
||||
this.emitUpdate();
|
||||
}
|
||||
|
||||
private parsePayload(
|
||||
data: unknown
|
||||
): { openTime?: number; close?: number; isClosed?: boolean } | null {
|
||||
try {
|
||||
const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf-8") : null;
|
||||
if (!text) return null;
|
||||
const parsed = JSON.parse(text);
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
// Raw stream payload shape:
|
||||
// { e: "kline", s: "ETHBTC", k: { t: <openTime>, c: <close>, x: <isClosed> } }
|
||||
const k = (parsed as any).k;
|
||||
if (!k || typeof k !== "object") return null;
|
||||
return {
|
||||
openTime: Number(k.t),
|
||||
close: Number(k.c),
|
||||
isClosed: Boolean(k.x),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,7 @@ import { isOrderActiveStatus } from "../utils/order-status";
|
||||
import { getPosition } from "../utils/strategy";
|
||||
import type { PositionSnapshot } from "../utils/strategy";
|
||||
import { computePositionPnl } from "../utils/pnl";
|
||||
import { getTopPrices, getMidOrLast } from "../utils/price";
|
||||
import { getTopPrices, getPricesAtLevel, getMidOrLast } from "../utils/price";
|
||||
import { shouldStopLoss } from "../utils/risk";
|
||||
import {
|
||||
marketClose,
|
||||
@@ -305,10 +305,18 @@ export class MakerEngine {
|
||||
|
||||
// 直接使用orderbook价格,格式化为字符串避免精度问题
|
||||
const priceDecimals = this.getPriceDecimals();
|
||||
// 平仓价格始终使用买1/卖1
|
||||
const closeBidPrice = formatPriceToString(topBid, priceDecimals);
|
||||
const closeAskPrice = formatPriceToString(topAsk, priceDecimals);
|
||||
const bidPrice = formatPriceToString(topBid - this.config.bidOffset, priceDecimals);
|
||||
const askPrice = formatPriceToString(topAsk + this.config.askOffset, priceDecimals);
|
||||
|
||||
// 开仓价格根据 entryDepthLevel 使用指定档位
|
||||
const entryLevel = this.config.entryDepthLevel ?? 1;
|
||||
const { bidAtLevel: entryBid, askAtLevel: entryAsk } = getPricesAtLevel(depth, entryLevel);
|
||||
const entryBidBase = entryBid ?? topBid;
|
||||
const entryAskBase = entryAsk ?? topAsk;
|
||||
|
||||
const bidPrice = formatPriceToString(entryBidBase - this.config.bidOffset, priceDecimals);
|
||||
const askPrice = formatPriceToString(entryAskBase + this.config.askOffset, priceDecimals);
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
const desired: DesiredOrder[] = [];
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBpsTargets } from "./maker-points-logic";
|
||||
|
||||
describe("maker points target builder", () => {
|
||||
it("builds fixed bps targets per enabled band", () => {
|
||||
const targets = buildBpsTargets({
|
||||
band0To10: true,
|
||||
band10To30: true,
|
||||
band30To100: true,
|
||||
});
|
||||
expect(targets).toEqual([9, 29, 99]);
|
||||
});
|
||||
|
||||
it("skips disabled bands", () => {
|
||||
const targets = buildBpsTargets({
|
||||
band0To10: true,
|
||||
band10To30: false,
|
||||
band30To100: true,
|
||||
});
|
||||
expect(targets).toEqual([9, 99]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
export interface MakerPointsBandConfig {
|
||||
band0To10: boolean;
|
||||
band10To30: boolean;
|
||||
band30To100: boolean;
|
||||
}
|
||||
|
||||
export function buildBpsTargets(config: MakerPointsBandConfig): number[] {
|
||||
const targets: number[] = [];
|
||||
if (config.band0To10) targets.push(9);
|
||||
if (config.band10To30) targets.push(29);
|
||||
if (config.band30To100) targets.push(99);
|
||||
return targets.sort((a, b) => a - b);
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import { getPosition, parseSymbolParts } from "../utils/strategy";
|
||||
import type { PositionSnapshot } from "../utils/strategy";
|
||||
import { computeDepthStats } from "../utils/depth";
|
||||
import { computePositionPnl } from "../utils/pnl";
|
||||
import { getTopPrices, getMidOrLast } from "../utils/price";
|
||||
import { getTopPrices, getPricesAtLevel, getMidOrLast } from "../utils/price";
|
||||
import { shouldStopLoss } from "../utils/risk";
|
||||
import {
|
||||
marketClose,
|
||||
@@ -356,10 +356,18 @@ export class OffsetMakerEngine {
|
||||
|
||||
// 直接使用orderbook价格,格式化为字符串避免精度问题
|
||||
const priceDecimals = this.getPriceDecimals();
|
||||
// 平仓价格始终使用买1/卖1
|
||||
const closeBidPrice = formatPriceToString(finalBid, priceDecimals);
|
||||
const closeAskPrice = formatPriceToString(finalAsk, priceDecimals);
|
||||
const rawBidPrice = finalBid - this.config.bidOffset;
|
||||
const rawAskPrice = finalAsk + this.config.askOffset;
|
||||
|
||||
// 开仓价格根据 entryDepthLevel 使用指定档位
|
||||
const entryLevel = this.config.entryDepthLevel ?? 1;
|
||||
const { bidAtLevel: entryBid, askAtLevel: entryAsk } = getPricesAtLevel(latestDepth, entryLevel);
|
||||
const entryBidBase = entryBid ?? finalBid;
|
||||
const entryAskBase = entryAsk ?? finalAsk;
|
||||
|
||||
const rawBidPrice = entryBidBase - this.config.bidOffset;
|
||||
const rawAskPrice = entryAskBase + this.config.askOffset;
|
||||
const safeBid = this.ensureMakerPrice("BUY", rawBidPrice, finalBid, finalAsk);
|
||||
const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk);
|
||||
const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null;
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
import type { ExchangeAdapter } from "../exchanges/adapter";
|
||||
import type { AsterAccountSnapshot, AsterDepth, AsterOrder, AsterTicker } from "../exchanges/types";
|
||||
import { createTradeLog, type TradeLogEntry } from "../logging/trade-log";
|
||||
import { marketClose, placeMarketOrder, placeStopLossOrder, unlockOperating } from "../core/order-coordinator";
|
||||
import type { OrderLockMap, OrderPendingMap, OrderTimerMap } from "../core/order-coordinator";
|
||||
import { extractMessage, isRateLimitError, isUnknownOrderError } from "../utils/errors";
|
||||
import { getPosition, type PositionSnapshot } from "../utils/strategy";
|
||||
import { computePositionPnl } from "../utils/pnl";
|
||||
import { getMidOrLast, getTopPrices } from "../utils/price";
|
||||
import { RateLimitController } from "../core/lib/rate-limit";
|
||||
import { StrategyEventEmitter } from "./common/event-emitter";
|
||||
import { safeSubscribe, type LogHandler } from "./common/subscriptions";
|
||||
import { SessionVolumeTracker } from "./common/session-volume";
|
||||
import { t } from "../i18n";
|
||||
import { BinanceRsiTracker, type BinanceRsiSnapshot } from "./common/binance-rsi";
|
||||
import { createInitialSwingState, stepSwing, type SwingState } from "./swing-logic";
|
||||
import { isOrderActiveStatus } from "../utils/order-status";
|
||||
import type { SwingConfig } from "../config";
|
||||
|
||||
export type SwingRsiZone = "overbought" | "oversold" | "neutral" | "unknown";
|
||||
export type SwingPhase =
|
||||
| "disabled"
|
||||
| "initializing"
|
||||
| "observing"
|
||||
| "waiting_open_short"
|
||||
| "waiting_open_long"
|
||||
| "waiting_close_short"
|
||||
| "waiting_close_long";
|
||||
|
||||
export interface SwingEngineSnapshot {
|
||||
ready: boolean;
|
||||
disabled: boolean;
|
||||
symbol: string;
|
||||
direction: SwingConfig["direction"];
|
||||
|
||||
lastPrice: number | null;
|
||||
phase: SwingPhase;
|
||||
binancePrice: number | null;
|
||||
rsi: number | null;
|
||||
rsiStable: boolean;
|
||||
rsiZone: SwingRsiZone;
|
||||
binanceConnection: BinanceRsiSnapshot["connectionState"];
|
||||
binanceUpdatedAt: number | null;
|
||||
|
||||
armed: Pick<
|
||||
SwingState,
|
||||
"armedShortEntry" | "armedShortExit" | "armedLongEntry" | "armedLongExit"
|
||||
>;
|
||||
|
||||
position: PositionSnapshot;
|
||||
pnl: number;
|
||||
unrealized: number;
|
||||
sessionVolume: number;
|
||||
|
||||
stopLossTarget: number | null;
|
||||
stopLossKillSwitch: boolean;
|
||||
|
||||
openOrders: AsterOrder[];
|
||||
depth: AsterDepth | null;
|
||||
ticker: AsterTicker | null;
|
||||
|
||||
tradeLog: TradeLogEntry[];
|
||||
lastUpdated: number | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
type SwingEvent = "update";
|
||||
type SwingListener = (snapshot: SwingEngineSnapshot) => void;
|
||||
|
||||
const EPS = 1e-5;
|
||||
|
||||
export class SwingEngine {
|
||||
private accountSnapshot: AsterAccountSnapshot | null = null;
|
||||
private openOrders: AsterOrder[] = [];
|
||||
private depthSnapshot: AsterDepth | null = null;
|
||||
private tickerSnapshot: AsterTicker | null = null;
|
||||
|
||||
private readonly locks: OrderLockMap = {};
|
||||
private readonly timers: OrderTimerMap = {};
|
||||
private readonly pending: OrderPendingMap = {};
|
||||
|
||||
private readonly tradeLog: ReturnType<typeof createTradeLog>;
|
||||
private readonly events = new StrategyEventEmitter<SwingEvent, SwingEngineSnapshot>();
|
||||
private readonly sessionVolume = new SessionVolumeTracker();
|
||||
private readonly rateLimit: RateLimitController;
|
||||
|
||||
private readonly binanceRsi: BinanceRsiTracker;
|
||||
private binanceSnapshot: BinanceRsiSnapshot;
|
||||
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private processing = false;
|
||||
private disabled = false;
|
||||
private lastError: string | null = null;
|
||||
|
||||
private ordersSnapshotReady = false;
|
||||
private precisionSync: Promise<void> | null = null;
|
||||
private swingState: SwingState = createInitialSwingState();
|
||||
|
||||
// Stop-loss placement de-bounce
|
||||
private lastStopAttempt: { side: "BUY" | "SELL" | null; price: number | null; at: number } = {
|
||||
side: null,
|
||||
price: null,
|
||||
at: 0,
|
||||
};
|
||||
|
||||
constructor(private readonly config: SwingConfig, private readonly exchange: ExchangeAdapter) {
|
||||
this.tradeLog = createTradeLog(this.config.maxLogEntries);
|
||||
this.rateLimit = new RateLimitController(this.config.pollIntervalMs, (type, detail) =>
|
||||
this.tradeLog.push(type, detail)
|
||||
);
|
||||
|
||||
this.binanceRsi = new BinanceRsiTracker(
|
||||
this.config.signalSymbol,
|
||||
this.config.signalInterval,
|
||||
this.config.rsiPeriod,
|
||||
{
|
||||
limit: 500,
|
||||
logger: (context, error) => {
|
||||
// Keep Binance errors visible but non-fatal.
|
||||
this.tradeLog.push("warn", `[Binance] ${context}: ${String(error)}`);
|
||||
},
|
||||
}
|
||||
);
|
||||
this.binanceSnapshot = this.binanceRsi.getSnapshot();
|
||||
this.binanceRsi.onUpdate((snapshot) => {
|
||||
this.binanceSnapshot = snapshot;
|
||||
this.emitUpdate();
|
||||
});
|
||||
this.binanceRsi.start();
|
||||
|
||||
this.syncPrecision();
|
||||
this.bootstrap();
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
this.timer = setInterval(() => {
|
||||
void this.tick();
|
||||
}, this.config.pollIntervalMs);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
// Binance tracker is external IO; stop it too.
|
||||
this.binanceRsi.stop();
|
||||
}
|
||||
|
||||
on(event: SwingEvent, handler: SwingListener): void {
|
||||
this.events.on(event, handler);
|
||||
}
|
||||
|
||||
off(event: SwingEvent, handler: SwingListener): void {
|
||||
this.events.off(event, handler);
|
||||
}
|
||||
|
||||
getSnapshot(): SwingEngineSnapshot {
|
||||
return this.buildSnapshot();
|
||||
}
|
||||
|
||||
private bootstrap(): void {
|
||||
const log: LogHandler = (type, detail) => this.tradeLog.push(type, detail);
|
||||
|
||||
safeSubscribe<AsterAccountSnapshot>(
|
||||
this.exchange.watchAccount.bind(this.exchange),
|
||||
(snapshot) => {
|
||||
this.accountSnapshot = snapshot;
|
||||
const position = getPosition(snapshot, this.config.symbol);
|
||||
const reference = this.getReferencePrice();
|
||||
this.sessionVolume.update(position, reference);
|
||||
|
||||
// Safe-by-default: refuse short mode on spot accounts.
|
||||
if (
|
||||
snapshot.marketType === "spot" &&
|
||||
(this.config.direction === "short" || this.config.direction === "both")
|
||||
) {
|
||||
if (!this.disabled) {
|
||||
this.disabled = true;
|
||||
this.lastError = "Swing strategy requires perp/margin for shorting; spot accounts cannot short.";
|
||||
this.tradeLog.push("error", this.lastError);
|
||||
}
|
||||
}
|
||||
|
||||
this.emitUpdate();
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => t("log.subscribe.accountFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.accountError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
safeSubscribe<AsterOrder[]>(
|
||||
this.exchange.watchOrders.bind(this.exchange),
|
||||
(orders) => {
|
||||
this.synchronizeLocks(orders);
|
||||
this.openOrders = Array.isArray(orders)
|
||||
? orders.filter(
|
||||
(order) =>
|
||||
order.type !== "MARKET" &&
|
||||
order.symbol === this.config.symbol &&
|
||||
isOrderActiveStatus(order.status)
|
||||
)
|
||||
: [];
|
||||
this.ordersSnapshotReady = true;
|
||||
this.emitUpdate();
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => t("log.subscribe.orderFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.orderError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
safeSubscribe<AsterDepth>(
|
||||
this.exchange.watchDepth.bind(this.exchange, this.config.symbol),
|
||||
(depth) => {
|
||||
this.depthSnapshot = depth;
|
||||
this.emitUpdate();
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => t("log.subscribe.depthFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.depthError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
safeSubscribe<AsterTicker>(
|
||||
this.exchange.watchTicker.bind(this.exchange, this.config.symbol),
|
||||
(ticker) => {
|
||||
this.tickerSnapshot = ticker;
|
||||
this.emitUpdate();
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => t("log.subscribe.tickerFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.tickerError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private synchronizeLocks(orders: AsterOrder[] | null | undefined): void {
|
||||
const list = Array.isArray(orders) ? orders : [];
|
||||
Object.keys(this.pending).forEach((type) => {
|
||||
const pendingId = this.pending[type];
|
||||
if (!pendingId) return;
|
||||
const match = list.find((order) => String(order.orderId) === pendingId);
|
||||
if (!match || (match.status && match.status !== "NEW" && match.status !== "PARTIALLY_FILLED")) {
|
||||
unlockOperating(this.locks, this.timers, this.pending, type);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private isReady(): boolean {
|
||||
return Boolean(
|
||||
this.accountSnapshot &&
|
||||
this.tickerSnapshot &&
|
||||
this.depthSnapshot &&
|
||||
this.ordersSnapshotReady &&
|
||||
this.binanceSnapshot.isStable &&
|
||||
this.binanceSnapshot.rsi != null
|
||||
);
|
||||
}
|
||||
|
||||
private async tick(): Promise<void> {
|
||||
if (this.processing) return;
|
||||
this.processing = true;
|
||||
let hadRateLimit = false;
|
||||
|
||||
try {
|
||||
const decision = this.rateLimit.beforeCycle();
|
||||
if (decision === "paused") {
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
if (decision === "skip") {
|
||||
return;
|
||||
}
|
||||
if (this.disabled) {
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
if (!this.isReady()) {
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
const account = this.accountSnapshot!;
|
||||
const position = getPosition(account, this.config.symbol);
|
||||
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
|
||||
const bid = topBid ?? Number(this.tickerSnapshot?.lastPrice);
|
||||
const ask = topAsk ?? Number(this.tickerSnapshot?.lastPrice);
|
||||
const pnl = computePositionPnl(position, bid, ask);
|
||||
const price = this.getReferencePrice();
|
||||
|
||||
const decisionOut = stepSwing(
|
||||
this.swingState,
|
||||
{ direction: this.config.direction, rsiHigh: this.config.rsiHigh, rsiLow: this.config.rsiLow },
|
||||
{ rsi: this.binanceSnapshot.rsi, positionAmt: position.positionAmt, pnl }
|
||||
);
|
||||
this.swingState = decisionOut.nextState;
|
||||
|
||||
for (const action of decisionOut.actions) {
|
||||
if (action.type === "OPEN_SHORT") {
|
||||
await this.tryOpen("SELL", action.reason);
|
||||
} else if (action.type === "OPEN_LONG") {
|
||||
await this.tryOpen("BUY", action.reason);
|
||||
} else if (action.type === "CLOSE_POSITION") {
|
||||
await this.tryClose(position, action.reason);
|
||||
}
|
||||
}
|
||||
|
||||
// Stop-loss management / kill-switch for any open position.
|
||||
await this.handleStopLoss(position, price);
|
||||
|
||||
this.sessionVolume.update(position, price);
|
||||
this.emitUpdate();
|
||||
} catch (error) {
|
||||
if (isRateLimitError(error)) {
|
||||
hadRateLimit = true;
|
||||
this.rateLimit.registerRateLimit("swing");
|
||||
this.tradeLog.push("warn", `SwingEngine 429: ${String(error)}`);
|
||||
} else {
|
||||
this.lastError = extractMessage(error);
|
||||
this.tradeLog.push("error", `SwingEngine error: ${this.lastError}`);
|
||||
}
|
||||
this.emitUpdate();
|
||||
} finally {
|
||||
try {
|
||||
this.rateLimit.onCycleComplete(hadRateLimit);
|
||||
} finally {
|
||||
this.processing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async tryOpen(side: "BUY" | "SELL", reason: string): Promise<void> {
|
||||
try {
|
||||
// Ensure flat before opening.
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
if (Math.abs(position.positionAmt) > EPS) {
|
||||
return;
|
||||
}
|
||||
await placeMarketOrder(
|
||||
this.exchange,
|
||||
this.config.symbol,
|
||||
this.openOrders,
|
||||
this.locks,
|
||||
this.timers,
|
||||
this.pending,
|
||||
side,
|
||||
this.config.tradeAmount,
|
||||
(type, detail) => this.tradeLog.push(type, detail),
|
||||
false,
|
||||
{
|
||||
markPrice: position.markPrice,
|
||||
expectedPrice: Number(this.tickerSnapshot?.lastPrice) || null,
|
||||
maxPct: this.config.maxCloseSlippagePct,
|
||||
},
|
||||
{ qtyStep: this.config.qtyStep }
|
||||
);
|
||||
this.tradeLog.push("open", `${reason}: ${side} (market)`);
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `Open failed: ${extractMessage(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async tryClose(position: PositionSnapshot, reason: string): Promise<void> {
|
||||
try {
|
||||
if (Math.abs(position.positionAmt) <= EPS) return;
|
||||
const side: "BUY" | "SELL" = position.positionAmt > 0 ? "SELL" : "BUY";
|
||||
const expected =
|
||||
side === "SELL"
|
||||
? Number(this.depthSnapshot?.bids?.[0]?.[0])
|
||||
: Number(this.depthSnapshot?.asks?.[0]?.[0]);
|
||||
await marketClose(
|
||||
this.exchange,
|
||||
this.config.symbol,
|
||||
this.openOrders,
|
||||
this.locks,
|
||||
this.timers,
|
||||
this.pending,
|
||||
side,
|
||||
Math.abs(position.positionAmt),
|
||||
(type, detail) => this.tradeLog.push(type, detail),
|
||||
{
|
||||
markPrice: position.markPrice,
|
||||
expectedPrice: Number.isFinite(expected) ? expected : Number(this.tickerSnapshot?.lastPrice) || null,
|
||||
maxPct: this.config.maxCloseSlippagePct,
|
||||
},
|
||||
{ qtyStep: this.config.qtyStep }
|
||||
);
|
||||
this.tradeLog.push("close", `${reason}: ${side} (market close)`);
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "Close skipped: order missing");
|
||||
} else {
|
||||
this.tradeLog.push("error", `Close failed: ${extractMessage(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async handleStopLoss(position: PositionSnapshot, referencePrice: number | null): Promise<void> {
|
||||
const hasPosition = Math.abs(position.positionAmt) > EPS;
|
||||
if (!hasPosition) {
|
||||
this.lastStopAttempt = { side: null, price: null, at: 0 };
|
||||
return;
|
||||
}
|
||||
|
||||
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
|
||||
if (!hasEntryPrice) {
|
||||
return;
|
||||
}
|
||||
|
||||
const direction = position.positionAmt > 0 ? "long" : "short";
|
||||
const stopSide: "BUY" | "SELL" = direction === "long" ? "SELL" : "BUY";
|
||||
const stopPrice =
|
||||
direction === "long"
|
||||
? position.entryPrice * (1 - Math.max(0, this.config.stopLossPct))
|
||||
: position.entryPrice * (1 + Math.max(0, this.config.stopLossPct));
|
||||
|
||||
const tick = Math.max(1e-9, this.config.priceTick);
|
||||
const lastPrice = referencePrice ?? Number(this.tickerSnapshot?.lastPrice) ?? null;
|
||||
|
||||
// Kill-switch (always-on).
|
||||
const triggerKill =
|
||||
direction === "long"
|
||||
? lastPrice != null && Number.isFinite(lastPrice) && lastPrice <= stopPrice + tick
|
||||
: lastPrice != null && Number.isFinite(lastPrice) && lastPrice >= stopPrice - tick;
|
||||
if (triggerKill) {
|
||||
await this.tryClose(position, "Stop-loss kill-switch");
|
||||
return;
|
||||
}
|
||||
|
||||
// If exchange supports stop orders, keep one active.
|
||||
const currentStop = this.openOrders.find((o) => {
|
||||
const hasStopPrice = Number.isFinite(Number(o.stopPrice)) && Number(o.stopPrice) > 0;
|
||||
return o.side === stopSide && (o.type === "STOP_MARKET" || hasStopPrice);
|
||||
});
|
||||
if (currentStop) return;
|
||||
|
||||
// De-bounce: avoid repeated submissions of same stop.
|
||||
const now = Date.now();
|
||||
if (
|
||||
this.lastStopAttempt.side === stopSide &&
|
||||
this.lastStopAttempt.price != null &&
|
||||
Math.abs(stopPrice - Number(this.lastStopAttempt.price)) < tick &&
|
||||
now - this.lastStopAttempt.at < 5000
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const qty = Math.abs(position.positionAmt);
|
||||
await placeStopLossOrder(
|
||||
this.exchange,
|
||||
this.config.symbol,
|
||||
this.openOrders,
|
||||
this.locks,
|
||||
this.timers,
|
||||
this.pending,
|
||||
stopSide,
|
||||
stopPrice,
|
||||
qty,
|
||||
lastPrice,
|
||||
(type, detail) => this.tradeLog.push(type, detail),
|
||||
{
|
||||
markPrice: position.markPrice,
|
||||
maxPct: this.config.maxCloseSlippagePct,
|
||||
},
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
this.lastStopAttempt = { side: stopSide, price: stopPrice, at: Date.now() };
|
||||
} catch (err) {
|
||||
this.lastStopAttempt = { side: stopSide, price: stopPrice, at: Date.now() };
|
||||
this.tradeLog.push("error", `Failed to place stop-loss order: ${extractMessage(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private emitUpdate(): void {
|
||||
try {
|
||||
const snapshot = this.buildSnapshot();
|
||||
this.events.emit("update", snapshot, (error) => {
|
||||
this.tradeLog.push("error", `SwingEngine update handler error: ${String(error)}`);
|
||||
});
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `SwingEngine snapshot error: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private buildSnapshot(): SwingEngineSnapshot {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const price = this.tickerSnapshot ? Number(this.tickerSnapshot.lastPrice) : null;
|
||||
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
|
||||
const pnl = computePositionPnl(position, topBid ?? price, topAsk ?? price);
|
||||
const reference = this.getReferencePrice();
|
||||
|
||||
const hasPosition = Math.abs(position.positionAmt) > EPS;
|
||||
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
|
||||
const stopLossTarget = hasPosition && hasEntryPrice
|
||||
? (position.positionAmt > 0
|
||||
? position.entryPrice * (1 - Math.max(0, this.config.stopLossPct))
|
||||
: position.entryPrice * (1 + Math.max(0, this.config.stopLossPct)))
|
||||
: null;
|
||||
const tick = Math.max(1e-9, this.config.priceTick);
|
||||
const stopLossKillSwitch =
|
||||
stopLossTarget != null && reference != null && Number.isFinite(reference)
|
||||
? (position.positionAmt > 0 ? reference <= stopLossTarget + tick : reference >= stopLossTarget - tick)
|
||||
: false;
|
||||
|
||||
const zone: SwingRsiZone =
|
||||
this.binanceSnapshot.rsi == null || !Number.isFinite(this.binanceSnapshot.rsi)
|
||||
? "unknown"
|
||||
: this.binanceSnapshot.rsi > this.config.rsiHigh
|
||||
? "overbought"
|
||||
: this.binanceSnapshot.rsi < this.config.rsiLow
|
||||
? "oversold"
|
||||
: "neutral";
|
||||
|
||||
const posAmt = Number(position.positionAmt);
|
||||
const phase: SwingPhase = this.disabled
|
||||
? "disabled"
|
||||
: !this.isReady()
|
||||
? "initializing"
|
||||
: Math.abs(posAmt) <= EPS
|
||||
? this.swingState.armedShortEntry
|
||||
? "waiting_open_short"
|
||||
: this.swingState.armedLongEntry
|
||||
? "waiting_open_long"
|
||||
: "observing"
|
||||
: posAmt < -EPS
|
||||
? this.swingState.armedShortExit
|
||||
? "waiting_close_short"
|
||||
: "observing"
|
||||
: this.swingState.armedLongExit
|
||||
? "waiting_close_long"
|
||||
: "observing";
|
||||
|
||||
return {
|
||||
ready: this.isReady() && !this.disabled,
|
||||
disabled: this.disabled,
|
||||
symbol: this.config.symbol,
|
||||
direction: this.config.direction,
|
||||
|
||||
lastPrice: reference,
|
||||
phase,
|
||||
binancePrice: this.binanceSnapshot.lastClose,
|
||||
rsi: this.binanceSnapshot.rsi,
|
||||
rsiStable: this.binanceSnapshot.isStable,
|
||||
rsiZone: zone,
|
||||
binanceConnection: this.binanceSnapshot.connectionState,
|
||||
binanceUpdatedAt: this.binanceSnapshot.updatedAt,
|
||||
|
||||
armed: {
|
||||
armedShortEntry: this.swingState.armedShortEntry,
|
||||
armedShortExit: this.swingState.armedShortExit,
|
||||
armedLongEntry: this.swingState.armedLongEntry,
|
||||
armedLongExit: this.swingState.armedLongExit,
|
||||
},
|
||||
|
||||
position,
|
||||
pnl,
|
||||
unrealized: position.unrealizedProfit,
|
||||
sessionVolume: this.sessionVolume.value,
|
||||
|
||||
stopLossTarget,
|
||||
stopLossKillSwitch,
|
||||
|
||||
openOrders: this.openOrders,
|
||||
depth: this.depthSnapshot,
|
||||
ticker: this.tickerSnapshot,
|
||||
|
||||
tradeLog: this.tradeLog.all(),
|
||||
lastUpdated: Date.now(),
|
||||
error: this.lastError,
|
||||
};
|
||||
}
|
||||
|
||||
private getReferencePrice(): number | null {
|
||||
return (
|
||||
getMidOrLast(this.depthSnapshot, this.tickerSnapshot) ??
|
||||
(this.tickerSnapshot ? Number(this.tickerSnapshot.lastPrice) : null)
|
||||
);
|
||||
}
|
||||
|
||||
private syncPrecision(): void {
|
||||
if (this.precisionSync) return;
|
||||
const getPrecision = this.exchange.getPrecision?.bind(this.exchange);
|
||||
if (!getPrecision) return;
|
||||
this.precisionSync = getPrecision()
|
||||
.then((precision) => {
|
||||
if (!precision) return;
|
||||
let updated = false;
|
||||
if (Number.isFinite(precision.priceTick) && precision.priceTick > 0) {
|
||||
const delta = Math.abs(precision.priceTick - this.config.priceTick);
|
||||
if (delta > 1e-12) {
|
||||
this.config.priceTick = precision.priceTick;
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(precision.qtyStep) && precision.qtyStep > 0) {
|
||||
const delta = Math.abs(precision.qtyStep - this.config.qtyStep);
|
||||
if (delta > 1e-12) {
|
||||
this.config.qtyStep = precision.qtyStep;
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
if (updated) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`Synced precision: priceTick=${precision.priceTick} qtyStep=${precision.qtyStep}`
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.tradeLog.push("error", `Precision sync failed: ${extractMessage(error)}`);
|
||||
this.precisionSync = null;
|
||||
setTimeout(() => this.syncPrecision(), 2000);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createInitialSwingState, stepSwing, type SwingLogicConfig } from "./swing-logic";
|
||||
|
||||
const baseConfig: SwingLogicConfig = {
|
||||
direction: "both",
|
||||
rsiHigh: 70,
|
||||
rsiLow: 30,
|
||||
};
|
||||
|
||||
describe("swing logic", () => {
|
||||
it("arms short entry on RSI cross up 70, then opens on cross down 70", () => {
|
||||
let state = createInitialSwingState();
|
||||
|
||||
// First observation sets prevRsi, no cross yet.
|
||||
({ nextState: state } = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 69, positionAmt: 0, pnl: 0 }));
|
||||
const a1 = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 71, positionAmt: 0, pnl: 0 });
|
||||
expect(a1.actions).toEqual([]);
|
||||
expect(a1.nextState.armedShortEntry).toBe(true);
|
||||
state = a1.nextState;
|
||||
|
||||
const a2 = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 69, positionAmt: 0, pnl: 0 });
|
||||
expect(a2.actions.map((a) => a.type)).toEqual(["OPEN_SHORT"]);
|
||||
expect(a2.nextState.armedShortEntry).toBe(false);
|
||||
});
|
||||
|
||||
it("arms long entry on RSI cross down 30, then opens on cross up 30", () => {
|
||||
let state = createInitialSwingState();
|
||||
({ nextState: state } = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 31, positionAmt: 0, pnl: 0 }));
|
||||
|
||||
const a1 = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 29, positionAmt: 0, pnl: 0 });
|
||||
expect(a1.actions).toEqual([]);
|
||||
expect(a1.nextState.armedLongEntry).toBe(true);
|
||||
state = a1.nextState;
|
||||
|
||||
const a2 = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 31, positionAmt: 0, pnl: 0 });
|
||||
expect(a2.actions.map((a) => a.type)).toEqual(["OPEN_LONG"]);
|
||||
expect(a2.nextState.armedLongEntry).toBe(false);
|
||||
});
|
||||
|
||||
it("short exit requires profit: arms on cross down 30, closes on cross up 30 if pnl > 0", () => {
|
||||
let state = createInitialSwingState();
|
||||
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: -1 }));
|
||||
|
||||
const a1 = stepSwing(state, baseConfig, { rsi: 29, positionAmt: -1, pnl: -1 });
|
||||
expect(a1.actions).toEqual([]);
|
||||
expect(a1.nextState.armedShortExit).toBe(true);
|
||||
state = a1.nextState;
|
||||
|
||||
const a2 = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0 });
|
||||
expect(a2.actions).toEqual([]); // pnl not strictly positive
|
||||
expect(a2.nextState.armedShortExit).toBe(true);
|
||||
state = a2.nextState;
|
||||
|
||||
const a3 = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0.01 });
|
||||
// No cross (prev=31 -> 31), still armed.
|
||||
expect(a3.actions).toEqual([]);
|
||||
|
||||
// Cross down then up to trigger close with profit
|
||||
const a4 = stepSwing(a3.nextState, baseConfig, { rsi: 29, positionAmt: -1, pnl: 0.01 });
|
||||
const a5 = stepSwing(a4.nextState, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0.01 });
|
||||
expect(a5.actions.map((a) => a.type)).toEqual(["CLOSE_POSITION"]);
|
||||
expect(a5.nextState.armedShortExit).toBe(false);
|
||||
});
|
||||
|
||||
it("long exit requires profit: arms on cross up 70, closes on cross down 70 if pnl > 0", () => {
|
||||
let state = createInitialSwingState();
|
||||
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 1, pnl: 0 }));
|
||||
|
||||
const a1 = stepSwing(state, baseConfig, { rsi: 71, positionAmt: 1, pnl: 0 });
|
||||
expect(a1.actions).toEqual([]);
|
||||
expect(a1.nextState.armedLongExit).toBe(true);
|
||||
state = a1.nextState;
|
||||
|
||||
const a2 = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 1, pnl: 0.01 });
|
||||
expect(a2.actions.map((a) => a.type)).toEqual(["CLOSE_POSITION"]);
|
||||
expect(a2.nextState.armedLongExit).toBe(false);
|
||||
});
|
||||
|
||||
it("clears entry arms when a position is present", () => {
|
||||
let state = createInitialSwingState();
|
||||
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 0, pnl: 0 }));
|
||||
|
||||
// Arm short entry.
|
||||
state = stepSwing(state, baseConfig, { rsi: 71, positionAmt: 0, pnl: 0 }).nextState;
|
||||
expect(state.armedShortEntry).toBe(true);
|
||||
|
||||
// Now position appears: entry arms should be reset.
|
||||
const next = stepSwing(state, baseConfig, { rsi: 71, positionAmt: -1, pnl: 0 });
|
||||
expect(next.nextState.armedShortEntry).toBe(false);
|
||||
expect(next.nextState.armedLongEntry).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
export type SwingDirection = "long" | "short" | "both";
|
||||
|
||||
export interface SwingLogicConfig {
|
||||
direction: SwingDirection;
|
||||
rsiHigh: number; // e.g. 70
|
||||
rsiLow: number; // e.g. 30
|
||||
}
|
||||
|
||||
export interface SwingState {
|
||||
prevRsi: number | null;
|
||||
armedShortEntry: boolean;
|
||||
armedShortExit: boolean;
|
||||
armedLongEntry: boolean;
|
||||
armedLongExit: boolean;
|
||||
}
|
||||
|
||||
export type SwingAction =
|
||||
| { type: "OPEN_SHORT"; reason: string }
|
||||
| { type: "OPEN_LONG"; reason: string }
|
||||
| { type: "CLOSE_POSITION"; reason: string };
|
||||
|
||||
export interface SwingStepInput {
|
||||
rsi: number | null;
|
||||
positionAmt: number;
|
||||
pnl: number;
|
||||
}
|
||||
|
||||
export function createInitialSwingState(): SwingState {
|
||||
return {
|
||||
prevRsi: null,
|
||||
armedShortEntry: false,
|
||||
armedShortExit: false,
|
||||
armedLongEntry: false,
|
||||
armedLongExit: false,
|
||||
};
|
||||
}
|
||||
|
||||
const EPS = 1e-8;
|
||||
|
||||
function crossUp(prev: number | null, next: number, threshold: number): boolean {
|
||||
if (prev == null) return false;
|
||||
return prev <= threshold && next > threshold;
|
||||
}
|
||||
|
||||
function crossDown(prev: number | null, next: number, threshold: number): boolean {
|
||||
if (prev == null) return false;
|
||||
return prev >= threshold && next < threshold;
|
||||
}
|
||||
|
||||
export function stepSwing(
|
||||
state: SwingState,
|
||||
config: SwingLogicConfig,
|
||||
input: SwingStepInput
|
||||
): { nextState: SwingState; actions: SwingAction[] } {
|
||||
const nextState: SwingState = { ...state };
|
||||
const actions: SwingAction[] = [];
|
||||
|
||||
const rsi = input.rsi;
|
||||
const hasRsi = typeof rsi === "number" && Number.isFinite(rsi);
|
||||
const prevRsi = nextState.prevRsi;
|
||||
|
||||
const direction = config.direction;
|
||||
const allowLong = direction === "long" || direction === "both";
|
||||
const allowShort = direction === "short" || direction === "both";
|
||||
|
||||
const positionAmt = Number(input.positionAmt);
|
||||
const pnl = Number(input.pnl);
|
||||
const isFlat = !Number.isFinite(positionAmt) || Math.abs(positionAmt) <= EPS;
|
||||
const isLong = Number.isFinite(positionAmt) && positionAmt > EPS;
|
||||
const isShort = Number.isFinite(positionAmt) && positionAmt < -EPS;
|
||||
|
||||
// If RSI is missing/invalid, avoid mutating state.
|
||||
if (!hasRsi) {
|
||||
return { nextState, actions };
|
||||
}
|
||||
|
||||
// Keep prevRsi updated once we have a valid reading.
|
||||
nextState.prevRsi = rsi;
|
||||
|
||||
if (isFlat) {
|
||||
// When flat, exit arms are irrelevant.
|
||||
nextState.armedShortExit = false;
|
||||
nextState.armedLongExit = false;
|
||||
|
||||
if (!allowShort) {
|
||||
nextState.armedShortEntry = false;
|
||||
} else {
|
||||
if (crossUp(prevRsi, rsi, config.rsiHigh)) {
|
||||
nextState.armedShortEntry = true;
|
||||
}
|
||||
if (nextState.armedShortEntry && crossDown(prevRsi, rsi, config.rsiHigh)) {
|
||||
actions.push({ type: "OPEN_SHORT", reason: "RSI armed above high, then crossed below high" });
|
||||
nextState.armedShortEntry = false;
|
||||
// Avoid impossible dual-entries.
|
||||
nextState.armedLongEntry = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!allowLong) {
|
||||
nextState.armedLongEntry = false;
|
||||
} else {
|
||||
if (crossDown(prevRsi, rsi, config.rsiLow)) {
|
||||
nextState.armedLongEntry = true;
|
||||
}
|
||||
if (nextState.armedLongEntry && crossUp(prevRsi, rsi, config.rsiLow)) {
|
||||
actions.push({ type: "OPEN_LONG", reason: "RSI armed below low, then crossed above low" });
|
||||
nextState.armedLongEntry = false;
|
||||
nextState.armedShortEntry = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (actions.length > 1) {
|
||||
// Defensive: avoid opening both directions in one step.
|
||||
return { nextState: { ...nextState, armedShortEntry: false, armedLongEntry: false }, actions: [] };
|
||||
}
|
||||
|
||||
return { nextState, actions };
|
||||
}
|
||||
|
||||
// When exposed, entry arms are irrelevant (strategy does not pyramid).
|
||||
nextState.armedShortEntry = false;
|
||||
nextState.armedLongEntry = false;
|
||||
|
||||
// Exits are always allowed (even if direction config changes) to avoid trapping positions.
|
||||
if (isShort) {
|
||||
nextState.armedLongExit = false;
|
||||
if (crossDown(prevRsi, rsi, config.rsiLow)) {
|
||||
nextState.armedShortExit = true;
|
||||
}
|
||||
if (nextState.armedShortExit && crossUp(prevRsi, rsi, config.rsiLow) && pnl > 0) {
|
||||
actions.push({ type: "CLOSE_POSITION", reason: "RSI exit armed below low, then crossed above low with profit" });
|
||||
nextState.armedShortExit = false;
|
||||
}
|
||||
return { nextState, actions };
|
||||
}
|
||||
|
||||
if (isLong) {
|
||||
nextState.armedShortExit = false;
|
||||
if (crossUp(prevRsi, rsi, config.rsiHigh)) {
|
||||
nextState.armedLongExit = true;
|
||||
}
|
||||
if (nextState.armedLongExit && crossDown(prevRsi, rsi, config.rsiHigh) && pnl > 0) {
|
||||
actions.push({ type: "CLOSE_POSITION", reason: "RSI exit armed above high, then crossed below high with profit" });
|
||||
nextState.armedLongExit = false;
|
||||
}
|
||||
return { nextState, actions };
|
||||
}
|
||||
|
||||
return { nextState, actions };
|
||||
}
|
||||
|
||||
+32
-9
@@ -1,9 +1,12 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { TrendApp } from "./TrendApp";
|
||||
import { SwingApp } from "./SwingApp";
|
||||
import { GuardianApp } from "./GuardianApp";
|
||||
import { MakerApp } from "./MakerApp";
|
||||
import { MakerPointsApp } from "./MakerPointsApp";
|
||||
import { OffsetMakerApp } from "./OffsetMakerApp";
|
||||
import { LiquidityMakerApp } from "./LiquidityMakerApp";
|
||||
import { GridApp } from "./GridApp";
|
||||
import { BasisApp } from "./BasisApp";
|
||||
import { isBasisStrategyEnabled } from "../config";
|
||||
@@ -12,7 +15,7 @@ import { resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface StrategyOption {
|
||||
id: "trend" | "guardian" | "maker" | "offset-maker" | "basis" | "grid";
|
||||
id: "trend" | "swing" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid";
|
||||
label: string;
|
||||
description: string;
|
||||
component: React.ComponentType<{ onExit: () => void }>;
|
||||
@@ -25,6 +28,12 @@ const BASE_STRATEGIES: StrategyOption[] = [
|
||||
description: t("app.strategy.trend.desc"),
|
||||
component: TrendApp,
|
||||
},
|
||||
{
|
||||
id: "swing",
|
||||
label: t("app.strategy.swing.label"),
|
||||
description: t("app.strategy.swing.desc"),
|
||||
component: SwingApp,
|
||||
},
|
||||
{
|
||||
id: "guardian",
|
||||
label: t("app.strategy.guardian.label"),
|
||||
@@ -49,6 +58,12 @@ const BASE_STRATEGIES: StrategyOption[] = [
|
||||
description: t("app.strategy.offset.desc"),
|
||||
component: OffsetMakerApp,
|
||||
},
|
||||
{
|
||||
id: "liquidity-maker",
|
||||
label: t("app.strategy.liquidityMaker.label"),
|
||||
description: t("app.strategy.liquidityMaker.desc"),
|
||||
component: LiquidityMakerApp,
|
||||
},
|
||||
];
|
||||
|
||||
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
|
||||
@@ -60,19 +75,27 @@ export function App() {
|
||||
const integrityOk = useMemo(() => verifyCopyrightIntegrity(), []);
|
||||
const exchangeId = useMemo(() => resolveExchangeId(), []);
|
||||
const strategies = useMemo(() => {
|
||||
if (!isBasisStrategyEnabled()) {
|
||||
return BASE_STRATEGIES;
|
||||
const next: StrategyOption[] = [...BASE_STRATEGIES];
|
||||
if (exchangeId === "standx") {
|
||||
const gridIndex = next.findIndex((s) => s.id === "grid");
|
||||
const insertAt = gridIndex === -1 ? next.length : gridIndex;
|
||||
next.splice(insertAt, 0, {
|
||||
id: "maker-points" as const,
|
||||
label: t("app.strategy.makerPoints.label"),
|
||||
description: t("app.strategy.makerPoints.desc"),
|
||||
component: MakerPointsApp,
|
||||
});
|
||||
}
|
||||
return [
|
||||
...BASE_STRATEGIES,
|
||||
{
|
||||
if (isBasisStrategyEnabled()) {
|
||||
next.push({
|
||||
id: "basis" as const,
|
||||
label: t("app.strategy.basis.label"),
|
||||
description: t("app.strategy.basis.desc"),
|
||||
component: BasisApp,
|
||||
},
|
||||
];
|
||||
}, []);
|
||||
});
|
||||
}
|
||||
return next;
|
||||
}, [exchangeId]);
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (exchangeId !== "aster" && exchangeId !== "nado") {
|
||||
if (exchangeId !== "aster" && exchangeId !== "nado" && exchangeId !== "standx") {
|
||||
setError(new Error(t("basis.onlyAster")));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { liquidityMakerConfig } from "../config";
|
||||
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { LiquidityMakerEngine, type LiquidityMakerEngineSnapshot } from "../strategy/liquidity-maker-engine";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface LiquidityMakerAppProps {
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
|
||||
|
||||
export function LiquidityMakerApp({ onExit }: LiquidityMakerAppProps) {
|
||||
const [snapshot, setSnapshot] = useState<LiquidityMakerEngineSnapshot | null>(null);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const engineRef = useRef<LiquidityMakerEngine | null>(null);
|
||||
const exchangeId = useMemo(() => resolveExchangeId(), []);
|
||||
const exchangeName = useMemo(() => getExchangeDisplayName(exchangeId), [exchangeId]);
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
if (key.escape) {
|
||||
engineRef.current?.stop();
|
||||
onExit();
|
||||
}
|
||||
},
|
||||
{ isActive: inputSupported }
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const adapter = buildAdapterFromEnv({ exchangeId, symbol: liquidityMakerConfig.symbol });
|
||||
const engine = new LiquidityMakerEngine(liquidityMakerConfig, adapter);
|
||||
engineRef.current = engine;
|
||||
setSnapshot(engine.getSnapshot());
|
||||
const handler = (next: LiquidityMakerEngineSnapshot) => {
|
||||
setSnapshot({ ...next, tradeLog: [...next.tradeLog] });
|
||||
};
|
||||
engine.on("update", handler);
|
||||
engine.start();
|
||||
return () => {
|
||||
engine.off("update", handler);
|
||||
engine.stop();
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
}, [exchangeId]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>{t("liquidityMaker.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const topBid = snapshot.topBid;
|
||||
const topAsk = snapshot.topAsk;
|
||||
const priceDigits = snapshot.priceDecimals ?? 2;
|
||||
const spreadDigits = Math.max(priceDigits + 1, 4);
|
||||
const spreadDisplay =
|
||||
snapshot.spread != null ? `${formatNumber(snapshot.spread, spreadDigits)} USDT` : "-";
|
||||
const hasPosition = Math.abs(snapshot.position.positionAmt) > 1e-5;
|
||||
const sortedOrders = [...snapshot.openOrders].sort((a, b) =>
|
||||
(Number(b.updateTime ?? 0) - Number(a.updateTime ?? 0)) || Number(b.orderId) - Number(a.orderId)
|
||||
);
|
||||
const openOrderRows = sortedOrders.slice(0, 8).map((order) => ({
|
||||
id: order.orderId,
|
||||
side: order.side,
|
||||
price: order.price,
|
||||
qty: order.origQty,
|
||||
filled: order.executedQty,
|
||||
reduceOnly: order.reduceOnly ? "yes" : "no",
|
||||
status: order.status,
|
||||
}));
|
||||
const openOrderColumns: TableColumn[] = [
|
||||
{ key: "id", header: "ID", align: "right", minWidth: 6 },
|
||||
{ key: "side", header: "Side", minWidth: 4 },
|
||||
{ key: "price", header: "Price", align: "right", minWidth: 10 },
|
||||
{ key: "qty", header: "Qty", align: "right", minWidth: 8 },
|
||||
{ key: "filled", header: "Filled", align: "right", minWidth: 8 },
|
||||
{ key: "reduceOnly", header: "RO", minWidth: 4 },
|
||||
{ key: "status", header: "Status", minWidth: 10 },
|
||||
];
|
||||
|
||||
const desiredRows = snapshot.desiredOrders.map((order, index) => ({
|
||||
index: index + 1,
|
||||
side: order.side,
|
||||
price: order.price,
|
||||
amount: order.amount,
|
||||
reduceOnly: order.reduceOnly ? "yes" : "no",
|
||||
}));
|
||||
const desiredColumns: TableColumn[] = [
|
||||
{ key: "index", header: "#", align: "right", minWidth: 2 },
|
||||
{ key: "side", header: "Side", minWidth: 4 },
|
||||
{ key: "price", header: "Price", align: "right", minWidth: 10 },
|
||||
{ key: "amount", header: "Qty", align: "right", minWidth: 8 },
|
||||
{ key: "reduceOnly", header: "RO", minWidth: 4 },
|
||||
];
|
||||
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const imbalanceLabel =
|
||||
snapshot.depthImbalance === "balanced"
|
||||
? t("offset.imbalance.balanced")
|
||||
: snapshot.depthImbalance === "buy_dominant"
|
||||
? t("offset.imbalance.buy")
|
||||
: t("offset.imbalance.sell");
|
||||
const readyStatus = snapshot.ready ? t("status.live") : t("status.waitingData");
|
||||
|
||||
// 显示最近成交信息
|
||||
const lastFillInfo = snapshot.lastFill
|
||||
? `${snapshot.lastFill.side} ${formatNumber(snapshot.lastFill.amount, 6)} @ ${formatNumber(snapshot.lastFill.price, priceDigits)}`
|
||||
: t("liquidityMaker.noFill");
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">{t("liquidityMaker.title")}</Text>
|
||||
<Text>
|
||||
{t("offset.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
bid: formatNumber(topBid, priceDigits),
|
||||
ask: formatNumber(topAsk, priceDigits),
|
||||
spread: spreadDisplay,
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
{t("offset.depthLine", {
|
||||
buy: formatNumber(snapshot.buyDepthSum10, 4),
|
||||
sell: formatNumber(snapshot.sellDepthSum10, 4),
|
||||
status: imbalanceLabel,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
{t("offset.strategyStatus", {
|
||||
buyStatus: snapshot.skipBuySide ? t("common.disabled") : t("common.enabled"),
|
||||
sellStatus: snapshot.skipSellSide ? t("common.disabled") : t("common.enabled"),
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">{t("liquidityMaker.lastFill", { info: lastFillInfo })}</Text>
|
||||
<Text color="gray">{t("trend.statusLine", { status: readyStatus })}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
{t("maker.positionLine", {
|
||||
direction:
|
||||
snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
|
||||
entry: formatNumber(snapshot.position.entryPrice, priceDigits),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
{t("maker.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
accountPnl: formatNumber(snapshot.accountUnrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">{t("maker.targetOrders")}</Text>
|
||||
{desiredRows.length > 0 ? (
|
||||
<DataTable columns={desiredColumns} rows={desiredRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("maker.noTargetOrders")}</Text>
|
||||
)}
|
||||
<Text>
|
||||
{t("trend.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{openOrderRows.length > 0 ? (
|
||||
<DataTable columns={openOrderColumns} rows={openOrderRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("common.noOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
[{item.time}] [{item.type}] {item.detail}
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { makerPointsConfig } from "../config";
|
||||
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { MakerPointsEngine, type MakerPointsSnapshot } from "../strategy/maker-points-engine";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface MakerPointsAppProps {
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
|
||||
|
||||
export function MakerPointsApp({ onExit }: MakerPointsAppProps) {
|
||||
const [snapshot, setSnapshot] = useState<MakerPointsSnapshot | null>(null);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const engineRef = useRef<MakerPointsEngine | null>(null);
|
||||
const exchangeId = useMemo(() => resolveExchangeId(), []);
|
||||
const exchangeName = useMemo(() => getExchangeDisplayName(exchangeId), [exchangeId]);
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
if (key.escape) {
|
||||
engineRef.current?.stop();
|
||||
onExit();
|
||||
}
|
||||
},
|
||||
{ isActive: inputSupported }
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (exchangeId !== "standx") {
|
||||
throw new Error("Maker Points strategy only supports the StandX exchange.");
|
||||
}
|
||||
const adapter = buildAdapterFromEnv({ exchangeId, symbol: makerPointsConfig.symbol });
|
||||
const engine = new MakerPointsEngine(makerPointsConfig, adapter);
|
||||
engineRef.current = engine;
|
||||
setSnapshot(engine.getSnapshot());
|
||||
const handler = (next: MakerPointsSnapshot) => {
|
||||
setSnapshot({ ...next, tradeLog: [...next.tradeLog] });
|
||||
};
|
||||
engine.on("update", handler);
|
||||
engine.start();
|
||||
return () => {
|
||||
engine.off("update", handler);
|
||||
engine.stop();
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
}, [exchangeId]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>{t("makerPoints.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const topBid = snapshot.topBid;
|
||||
const topAsk = snapshot.topAsk;
|
||||
const priceDigits = snapshot.priceDecimals ?? 2;
|
||||
const spreadDigits = Math.max(priceDigits + 1, 4);
|
||||
const spreadDisplay =
|
||||
snapshot.spread != null ? `${formatNumber(snapshot.spread, spreadDigits)} USDT` : "-";
|
||||
const hasPosition = Math.abs(snapshot.position.positionAmt) > 1e-5;
|
||||
|
||||
const sortedOrders = [...snapshot.openOrders].sort((a, b) =>
|
||||
(Number(b.updateTime ?? 0) - Number(a.updateTime ?? 0)) || Number(b.orderId) - Number(a.orderId)
|
||||
);
|
||||
const openOrderRows = sortedOrders.slice(0, 8).map((order) => ({
|
||||
id: order.orderId,
|
||||
side: order.side,
|
||||
price: order.price,
|
||||
qty: order.origQty,
|
||||
filled: order.executedQty,
|
||||
reduceOnly: order.reduceOnly ? "yes" : "no",
|
||||
status: order.status,
|
||||
}));
|
||||
const openOrderColumns: TableColumn[] = [
|
||||
{ key: "id", header: "ID", align: "right", minWidth: 6 },
|
||||
{ key: "side", header: "Side", minWidth: 4 },
|
||||
{ key: "price", header: "Price", align: "right", minWidth: 10 },
|
||||
{ key: "qty", header: "Qty", align: "right", minWidth: 8 },
|
||||
{ key: "filled", header: "Filled", align: "right", minWidth: 8 },
|
||||
{ key: "reduceOnly", header: "RO", minWidth: 4 },
|
||||
{ key: "status", header: "Status", minWidth: 10 },
|
||||
];
|
||||
|
||||
const desiredRows = snapshot.desiredOrders.map((order, index) => ({
|
||||
index: index + 1,
|
||||
side: order.side,
|
||||
price: order.price,
|
||||
amount: order.amount,
|
||||
reduceOnly: order.reduceOnly ? "yes" : "no",
|
||||
}));
|
||||
const desiredColumns: TableColumn[] = [
|
||||
{ key: "index", header: "#", align: "right", minWidth: 2 },
|
||||
{ key: "side", header: "Side", minWidth: 4 },
|
||||
{ key: "price", header: "Price", align: "right", minWidth: 10 },
|
||||
{ key: "amount", header: "Qty", align: "right", minWidth: 8 },
|
||||
{ key: "reduceOnly", header: "RO", minWidth: 4 },
|
||||
];
|
||||
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const feedStatus = snapshot.feedStatus;
|
||||
const feedEntries: Array<{ key: keyof typeof feedStatus; label: string }> = [
|
||||
{ key: "account", label: t("maker.feed.account") },
|
||||
{ key: "orders", label: t("maker.feed.orders") },
|
||||
{ key: "depth", label: t("maker.feed.depth") },
|
||||
{ key: "ticker", label: t("maker.feed.ticker") },
|
||||
{ key: "binance", label: t("makerPoints.feed.binance") },
|
||||
];
|
||||
const readyStatus = snapshot.ready ? t("status.live") : t("status.waitingData");
|
||||
const imbalanceStatus = snapshot.binanceDepth?.imbalance ?? "balanced";
|
||||
const imbalanceLabel =
|
||||
imbalanceStatus === "buy_dominant"
|
||||
? t("offset.imbalance.buy")
|
||||
: imbalanceStatus === "sell_dominant"
|
||||
? t("offset.imbalance.sell")
|
||||
: t("offset.imbalance.balanced");
|
||||
const quoteMode = snapshot.quoteStatus.closeOnly ? t("makerPoints.mode.closeOnly") : t("makerPoints.mode.normal");
|
||||
const formatDepth = (value: number | null) => (value == null ? "-" : formatNumber(value, 4));
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">{t("makerPoints.title")}</Text>
|
||||
<Text>
|
||||
{t("makerPoints.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
bid: formatNumber(topBid, priceDigits),
|
||||
ask: formatNumber(topAsk, priceDigits),
|
||||
spread: spreadDisplay,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">{t("trend.statusLine", { status: readyStatus })}</Text>
|
||||
<Text>
|
||||
{t("makerPoints.quoteLine", {
|
||||
mode: quoteMode,
|
||||
buy: snapshot.quoteStatus.skipBuy ? t("common.disabled") : t("common.enabled"),
|
||||
sell: snapshot.quoteStatus.skipSell ? t("common.disabled") : t("common.enabled"),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
{t("makerPoints.binanceLine", {
|
||||
buy: formatNumber(snapshot.binanceDepth?.buySum ?? 0, 4),
|
||||
sell: formatNumber(snapshot.binanceDepth?.sellSum ?? 0, 4),
|
||||
status: imbalanceLabel,
|
||||
})}
|
||||
</Text>
|
||||
{snapshot.bandDepths.map((band) => (
|
||||
<Text key={band.band} color={band.enabled ? undefined : "gray"}>
|
||||
{t("makerPoints.bandDepthLine", {
|
||||
band: band.band,
|
||||
buy: formatDepth(band.buyDepth),
|
||||
sell: formatDepth(band.sellDepth),
|
||||
})}
|
||||
</Text>
|
||||
))}
|
||||
<Text>
|
||||
{t("maker.dataStatus")}
|
||||
{feedEntries.map((entry, index) => (
|
||||
<Text key={entry.key} color={feedStatus[entry.key] ? "green" : "red"}>
|
||||
{index === 0 ? " " : " "}
|
||||
{entry.label}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
{t("maker.positionLine", {
|
||||
direction:
|
||||
snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
|
||||
entry: formatNumber(snapshot.position.entryPrice, priceDigits),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
{t("maker.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
accountPnl: formatNumber(snapshot.accountUnrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">{t("maker.targetOrders")}</Text>
|
||||
{desiredRows.length > 0 ? (
|
||||
<DataTable columns={desiredColumns} rows={desiredRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("maker.noTargetOrders")}</Text>
|
||||
)}
|
||||
<Text>
|
||||
{t("trend.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{openOrderRows.length > 0 ? (
|
||||
<DataTable columns={openOrderColumns} rows={openOrderRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("common.noOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
[{item.time}] [{item.type}] {item.detail}
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { swingConfig } from "../config";
|
||||
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { SwingEngine, type SwingEngineSnapshot } from "../strategy/swing-engine";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { t } from "../i18n";
|
||||
|
||||
const READY_MESSAGE = t("swing.readyMessage");
|
||||
|
||||
interface SwingAppProps {
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
|
||||
|
||||
export function SwingApp({ onExit }: SwingAppProps) {
|
||||
const [snapshot, setSnapshot] = useState<SwingEngineSnapshot | null>(null);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const engineRef = useRef<SwingEngine | null>(null);
|
||||
const exchangeId = useMemo(() => resolveExchangeId(), []);
|
||||
const exchangeName = useMemo(() => getExchangeDisplayName(exchangeId), [exchangeId]);
|
||||
|
||||
useInput(
|
||||
(_input, key) => {
|
||||
if (key.escape) {
|
||||
engineRef.current?.stop();
|
||||
onExit();
|
||||
}
|
||||
},
|
||||
{ isActive: inputSupported }
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const adapter = buildAdapterFromEnv({ exchangeId, symbol: swingConfig.symbol });
|
||||
const engine = new SwingEngine(swingConfig, adapter);
|
||||
engineRef.current = engine;
|
||||
setSnapshot(engine.getSnapshot());
|
||||
const handler = (next: SwingEngineSnapshot) => {
|
||||
setSnapshot({ ...next, tradeLog: [...next.tradeLog], openOrders: [...next.openOrders] });
|
||||
};
|
||||
engine.on("update", handler);
|
||||
engine.start();
|
||||
return () => {
|
||||
engine.off("update", handler);
|
||||
engine.stop();
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
}, [exchangeId]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>{t("common.initializing", { target: t("swing.name") })}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const zoneLabel =
|
||||
snapshot.rsiZone === "overbought"
|
||||
? t("swing.zone.overbought")
|
||||
: snapshot.rsiZone === "oversold"
|
||||
? t("swing.zone.oversold")
|
||||
: snapshot.rsiZone === "neutral"
|
||||
? t("swing.zone.neutral")
|
||||
: t("swing.zone.unknown");
|
||||
|
||||
const phaseLabel =
|
||||
snapshot.phase === "disabled"
|
||||
? t("swing.phase.disabled")
|
||||
: snapshot.phase === "initializing"
|
||||
? t("swing.phase.initializing")
|
||||
: snapshot.phase === "waiting_open_short"
|
||||
? t("swing.phase.waitingOpenShort")
|
||||
: snapshot.phase === "waiting_close_short"
|
||||
? t("swing.phase.waitingCloseShort")
|
||||
: snapshot.phase === "waiting_open_long"
|
||||
? t("swing.phase.waitingOpenLong")
|
||||
: snapshot.phase === "waiting_close_long"
|
||||
? t("swing.phase.waitingCloseLong")
|
||||
: t("swing.phase.observing");
|
||||
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const sortedOrders = [...snapshot.openOrders].sort(
|
||||
(a, b) => (Number(b.updateTime ?? 0) - Number(a.updateTime ?? 0)) || Number(b.orderId) - Number(a.orderId)
|
||||
);
|
||||
const orderRows = sortedOrders.slice(0, 8).map((order) => ({
|
||||
id: order.orderId,
|
||||
side: order.side,
|
||||
type: order.type,
|
||||
price: order.price,
|
||||
qty: order.origQty,
|
||||
filled: order.executedQty,
|
||||
status: order.status,
|
||||
}));
|
||||
const orderColumns: TableColumn[] = [
|
||||
{ key: "id", header: "ID", align: "right", minWidth: 6 },
|
||||
{ key: "side", header: "Side", minWidth: 4 },
|
||||
{ key: "type", header: "Type", minWidth: 10 },
|
||||
{ key: "price", header: "Price", align: "right", minWidth: 10 },
|
||||
{ key: "qty", header: "Qty", align: "right", minWidth: 8 },
|
||||
{ key: "filled", header: "Filled", align: "right", minWidth: 8 },
|
||||
{ key: "status", header: "Status", minWidth: 10 },
|
||||
];
|
||||
|
||||
const hasPosition = Math.abs(snapshot.position.positionAmt) > 1e-5;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} paddingY={0}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">{t("swing.title")}</Text>
|
||||
<Text>
|
||||
{t("swing.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
direction: snapshot.direction,
|
||||
lastPrice: formatNumber(snapshot.lastPrice, 6),
|
||||
phase: phaseLabel,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
{t("swing.signalLine", {
|
||||
binanceSymbol: "ETHBTC",
|
||||
binancePrice: formatNumber(snapshot.binancePrice, 8),
|
||||
rsi: formatNumber(snapshot.rsi, 2),
|
||||
zone: zoneLabel,
|
||||
connection: snapshot.binanceConnection,
|
||||
})}
|
||||
</Text>
|
||||
<Text color={snapshot.disabled ? "red" : "gray"}>
|
||||
{t("swing.statusLine", {
|
||||
status: snapshot.disabled
|
||||
? t("status.paused")
|
||||
: snapshot.ready
|
||||
? t("status.live")
|
||||
: READY_MESSAGE,
|
||||
})}
|
||||
</Text>
|
||||
{snapshot.error ? <Text color="red">{snapshot.error}</Text> : null}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
{t("swing.positionLine", {
|
||||
direction: snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
|
||||
entry: formatNumber(snapshot.position.entryPrice, 6),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
{t("swing.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
unrealized: formatNumber(snapshot.unrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
<Text color={snapshot.stopLossKillSwitch ? "red" : "gray"}>
|
||||
{t("swing.stopLine", { stop: formatNumber(snapshot.stopLossTarget, 6) })}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">{t("swing.stateTitle")}</Text>
|
||||
<Text color="gray">
|
||||
{t("swing.armedLine", {
|
||||
se: snapshot.armed.armedShortEntry ? "Y" : "N",
|
||||
sx: snapshot.armed.armedShortExit ? "Y" : "N",
|
||||
le: snapshot.armed.armedLongEntry ? "Y" : "N",
|
||||
lx: snapshot.armed.armedLongExit ? "Y" : "N",
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">{t("swing.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{orderRows.length > 0 ? <DataTable columns={orderColumns} rows={orderRows} /> : <Text color="gray">{t("common.noOrders")}</Text>}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">{t("common.section.recentTrades")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
[{item.time}] [{item.type}] {item.detail}
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,3 +61,27 @@ export function isInsufficientBalanceError(error: unknown): boolean {
|
||||
message.includes("NOT ENOUGH")
|
||||
);
|
||||
}
|
||||
|
||||
export function isPrecisionError(error: unknown): boolean {
|
||||
const message = extractMessage(error).toUpperCase();
|
||||
return (
|
||||
message.includes("PRECISION") ||
|
||||
message.includes("TICK_SIZE") ||
|
||||
message.includes("TICKSIZE") ||
|
||||
message.includes("STEP_SIZE") ||
|
||||
message.includes("STEPSIZE") ||
|
||||
message.includes("LOT_SIZE") ||
|
||||
message.includes("LOTSIZE") ||
|
||||
message.includes("INVALID_QUANTITY") ||
|
||||
message.includes("INVALID QUANTITY") ||
|
||||
message.includes("QUANTITY_INVALID") ||
|
||||
message.includes("INVALID_PRICE") ||
|
||||
message.includes("INVALID PRICE") ||
|
||||
message.includes("PRICE_INVALID") ||
|
||||
message.includes("QTY_STEP") ||
|
||||
message.includes("PRICE_TICK") ||
|
||||
message.includes("DECIMAL") ||
|
||||
message.includes("FILTER_FAILURE") ||
|
||||
message.includes("NOTIONAL")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,4 +13,24 @@ export function computePositionPnl(
|
||||
: (position.entryPrice - (priceForPnl as number)) * absAmt;
|
||||
}
|
||||
|
||||
export function computeStopLossPnl(
|
||||
position: PositionSnapshot,
|
||||
bestBid?: number | null,
|
||||
bestAsk?: number | null
|
||||
): number | null {
|
||||
const absAmt = Math.abs(position.positionAmt);
|
||||
if (!Number.isFinite(absAmt) || absAmt <= 0) return 0;
|
||||
|
||||
// If entry price is missing, prefer the exchange-provided unrealized PnL.
|
||||
if (!Number.isFinite(position.entryPrice) || position.entryPrice <= 0) {
|
||||
return Number.isFinite(position.unrealizedProfit) ? position.unrealizedProfit : null;
|
||||
}
|
||||
|
||||
const priceForPnl = position.positionAmt > 0 ? bestBid : bestAsk;
|
||||
if (!Number.isFinite(priceForPnl as number) || (priceForPnl as number) <= 0) {
|
||||
return Number.isFinite(position.unrealizedProfit) ? position.unrealizedProfit : null;
|
||||
}
|
||||
|
||||
return computePositionPnl(position, bestBid, bestAsk);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,46 @@ export function getTopPrices(depth?: AsterDepth | null): { topBid: number | null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定档位的盘口价格
|
||||
* @param depth 深度数据
|
||||
* @param level 档位(1=买1/卖1,2=买2/卖2,以此类推)
|
||||
* @returns 指定档位的买卖价格,如果该档位不存在则回退到最近的有效档位
|
||||
*/
|
||||
export function getPricesAtLevel(
|
||||
depth?: AsterDepth | null,
|
||||
level: number = 1
|
||||
): { bidAtLevel: number | null; askAtLevel: number | null } {
|
||||
const index = Math.max(0, level - 1);
|
||||
|
||||
// 尝试获取指定档位,如果不存在则回退到最近的有效档位
|
||||
const bids = depth?.bids ?? [];
|
||||
const asks = depth?.asks ?? [];
|
||||
|
||||
let bidAtLevel: number | null = null;
|
||||
let askAtLevel: number | null = null;
|
||||
|
||||
// 从指定档位向前查找第一个有效的买价
|
||||
for (let i = Math.min(index, bids.length - 1); i >= 0; i--) {
|
||||
const bid = Number(bids[i]?.[0]);
|
||||
if (Number.isFinite(bid)) {
|
||||
bidAtLevel = bid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 从指定档位向前查找第一个有效的卖价
|
||||
for (let i = Math.min(index, asks.length - 1); i >= 0; i--) {
|
||||
const ask = Number(asks[i]?.[0]);
|
||||
if (Number.isFinite(ask)) {
|
||||
askAtLevel = ask;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { bidAtLevel, askAtLevel };
|
||||
}
|
||||
|
||||
export function getMidOrLast(depth?: AsterDepth | null, ticker?: AsterTicker | null): number | null {
|
||||
const { topBid, topAsk } = getTopPrices(depth);
|
||||
if (topBid != null && topAsk != null) return (topBid + topAsk) / 2;
|
||||
@@ -16,4 +56,58 @@ export function getMidOrLast(depth?: AsterDepth | null, ticker?: AsterTicker | n
|
||||
return Number.isFinite(last) ? last : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算从盘口一档到目标价格之间的挂单总量
|
||||
* @param depth 深度数据
|
||||
* @param side 挂单方向: BUY 检查 bids, SELL 检查 asks
|
||||
* @param targetPrice 目标挂单价格
|
||||
* @returns 从一档到目标价格之间的挂单总量 (不包含目标价格本身)
|
||||
*/
|
||||
export function getDepthBetweenPrices(
|
||||
depth: AsterDepth | null | undefined,
|
||||
side: "BUY" | "SELL",
|
||||
targetPrice: number
|
||||
): number {
|
||||
if (!depth) return 0;
|
||||
if (!Number.isFinite(targetPrice) || targetPrice <= 0) return 0;
|
||||
|
||||
let total = 0;
|
||||
|
||||
if (side === "BUY") {
|
||||
// BUY 订单挂在 bid 侧,检查从 bid1 到目标价格之间的所有 bids
|
||||
// bids 按价格从高到低排序,目标价格 < bid1
|
||||
const bids = depth.bids ?? [];
|
||||
for (const level of bids) {
|
||||
const price = Number(level[0]);
|
||||
const qty = Number(level[1]);
|
||||
if (!Number.isFinite(price) || !Number.isFinite(qty)) continue;
|
||||
// 只计算价格 > 目标价格的档位 (目标价格以上的挂单)
|
||||
if (price > targetPrice) {
|
||||
total += qty;
|
||||
} else {
|
||||
// bids 是从高到低排序,一旦 price <= targetPrice 就停止
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// SELL 订单挂在 ask 侧,检查从 ask1 到目标价格之间的所有 asks
|
||||
// asks 按价格从低到高排序,目标价格 > ask1
|
||||
const asks = depth.asks ?? [];
|
||||
for (const level of asks) {
|
||||
const price = Number(level[0]);
|
||||
const qty = Number(level[1]);
|
||||
if (!Number.isFinite(price) || !Number.isFinite(qty)) continue;
|
||||
// 只计算价格 < 目标价格的档位 (目标价格以下的挂单)
|
||||
if (price < targetPrice) {
|
||||
total += qty;
|
||||
} else {
|
||||
// asks 是从低到高排序,一旦 price >= targetPrice 就停止
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { isStandxTokenExpired, getStandxTokenExpiryInfo, standxTokenConfig } from "../config";
|
||||
|
||||
export type TokenExpiryState = "active" | "expired" | "expired_with_position" | "silent";
|
||||
|
||||
export interface TokenExpiryStatus {
|
||||
state: TokenExpiryState;
|
||||
expired: boolean;
|
||||
expiryTimestamp: number | null;
|
||||
remainingMs: number | null;
|
||||
hasPosition: boolean;
|
||||
hasOpenOrders: boolean;
|
||||
}
|
||||
|
||||
export interface TokenExpiryCheckParams {
|
||||
positionAmt: number;
|
||||
openOrderCount: number;
|
||||
}
|
||||
|
||||
export function checkStandxTokenExpiry(params: TokenExpiryCheckParams): TokenExpiryStatus {
|
||||
const info = getStandxTokenExpiryInfo();
|
||||
const hasPosition = Math.abs(params.positionAmt) > 1e-8;
|
||||
const hasOpenOrders = params.openOrderCount > 0;
|
||||
|
||||
if (!info.expired) {
|
||||
return {
|
||||
state: "active",
|
||||
expired: false,
|
||||
expiryTimestamp: info.expiryTimestamp,
|
||||
remainingMs: info.remainingMs,
|
||||
hasPosition,
|
||||
hasOpenOrders,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasPosition) {
|
||||
return {
|
||||
state: "expired_with_position",
|
||||
expired: true,
|
||||
expiryTimestamp: info.expiryTimestamp,
|
||||
remainingMs: 0,
|
||||
hasPosition: true,
|
||||
hasOpenOrders,
|
||||
};
|
||||
}
|
||||
|
||||
if (!hasOpenOrders) {
|
||||
return {
|
||||
state: "silent",
|
||||
expired: true,
|
||||
expiryTimestamp: info.expiryTimestamp,
|
||||
remainingMs: 0,
|
||||
hasPosition: false,
|
||||
hasOpenOrders: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
state: "expired",
|
||||
expired: true,
|
||||
expiryTimestamp: info.expiryTimestamp,
|
||||
remainingMs: 0,
|
||||
hasPosition,
|
||||
hasOpenOrders,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTokenExpiryMessage(status: TokenExpiryStatus): string | null {
|
||||
if (!status.expired) {
|
||||
if (status.remainingMs != null && status.remainingMs < 3600_000) {
|
||||
const mins = Math.ceil(status.remainingMs / 60_000);
|
||||
return `StandX Token 将在 ${mins} 分钟后过期`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (status.state) {
|
||||
case "expired":
|
||||
return "StandX Token 已过期,正在取消所有挂单";
|
||||
case "expired_with_position":
|
||||
return "StandX Token 已过期,仅保留平仓/止损逻辑";
|
||||
case "silent":
|
||||
return "StandX Token 已过期,进入静默数据接收模式";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isTokenExpiryConfigured(): boolean {
|
||||
return standxTokenConfig.expiryTimestamp != null;
|
||||
}
|
||||
|
||||
export { isStandxTokenExpired, getStandxTokenExpiryInfo };
|
||||
@@ -47,6 +47,47 @@ export function getPosition(snapshot: AsterAccountSnapshot | null, symbol: strin
|
||||
};
|
||||
}
|
||||
|
||||
export function validateAccountSnapshotForSymbol(
|
||||
snapshot: AsterAccountSnapshot | null,
|
||||
symbol: string
|
||||
): { ok: true } | { ok: false; issues: string[] } {
|
||||
if (!snapshot) return { ok: true };
|
||||
const positions = snapshot.positions?.filter((p) => p.symbol === symbol) ?? [];
|
||||
if (positions.length === 0) return { ok: true };
|
||||
|
||||
const NON_ZERO_EPS = 1e-8;
|
||||
const issues: string[] = [];
|
||||
|
||||
for (const position of positions) {
|
||||
const amt = Number(position.positionAmt);
|
||||
if (!Number.isFinite(amt)) {
|
||||
issues.push("invalid_positionAmt");
|
||||
continue;
|
||||
}
|
||||
if (Math.abs(amt) <= NON_ZERO_EPS) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entryPrice = Number(position.entryPrice);
|
||||
if (!Number.isFinite(entryPrice) || entryPrice <= 0) {
|
||||
issues.push("invalid_entryPrice");
|
||||
}
|
||||
|
||||
const unrealizedProfit = Number(position.unrealizedProfit);
|
||||
if (!Number.isFinite(unrealizedProfit)) {
|
||||
issues.push("invalid_unrealizedProfit");
|
||||
}
|
||||
|
||||
const rawMark = Number(position.markPrice);
|
||||
if (position.markPrice != null && position.markPrice !== "" && (!Number.isFinite(rawMark) || rawMark <= 0)) {
|
||||
issues.push("invalid_markPrice");
|
||||
}
|
||||
}
|
||||
|
||||
if (issues.length === 0) return { ok: true };
|
||||
return { ok: false, issues: Array.from(new Set(issues)) };
|
||||
}
|
||||
|
||||
export function getSMA(values: AsterKline[], length: number): number | null {
|
||||
if (!Array.isArray(values) || values.length < length) return null;
|
||||
const window = values.slice(-length);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AsterAccountSnapshot } from "../src/exchanges/types";
|
||||
import { validateAccountSnapshotForSymbol } from "../src/utils/strategy";
|
||||
|
||||
function baseSnapshot(positions: AsterAccountSnapshot["positions"]): AsterAccountSnapshot {
|
||||
return {
|
||||
canTrade: true,
|
||||
canDeposit: true,
|
||||
canWithdraw: true,
|
||||
updateTime: Date.now(),
|
||||
totalWalletBalance: "0",
|
||||
totalUnrealizedProfit: "0",
|
||||
positions,
|
||||
assets: [],
|
||||
marketType: "perp",
|
||||
};
|
||||
}
|
||||
|
||||
describe("validateAccountSnapshotForSymbol", () => {
|
||||
it("accepts empty positions", () => {
|
||||
const result = validateAccountSnapshotForSymbol(baseSnapshot([]), "BTC-USD");
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts zero-sized positions even if entry price is zero", () => {
|
||||
const result = validateAccountSnapshotForSymbol(
|
||||
baseSnapshot([
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
positionAmt: "0",
|
||||
entryPrice: "0",
|
||||
unrealizedProfit: "0",
|
||||
positionSide: "BOTH",
|
||||
updateTime: Date.now(),
|
||||
markPrice: "0",
|
||||
},
|
||||
]),
|
||||
"BTC-USD"
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("flags invalid numeric fields for non-zero positions", () => {
|
||||
const result = validateAccountSnapshotForSymbol(
|
||||
baseSnapshot([
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
positionAmt: "1",
|
||||
entryPrice: "NaN",
|
||||
unrealizedProfit: "oops",
|
||||
positionSide: "BOTH",
|
||||
updateTime: Date.now(),
|
||||
markPrice: "-1",
|
||||
},
|
||||
]),
|
||||
"BTC-USD"
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.issues).toEqual(
|
||||
expect.arrayContaining(["invalid_entryPrice", "invalid_unrealizedProfit", "invalid_markPrice"])
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("flags invalid positionAmt", () => {
|
||||
const result = validateAccountSnapshotForSymbol(
|
||||
baseSnapshot([
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
positionAmt: "abc",
|
||||
entryPrice: "100",
|
||||
unrealizedProfit: "0",
|
||||
positionSide: "BOTH",
|
||||
updateTime: Date.now(),
|
||||
markPrice: "101",
|
||||
},
|
||||
]),
|
||||
"BTC-USD"
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.issues).toContain("invalid_positionAmt");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
});
|
||||
|
||||
async function loadConfig() {
|
||||
vi.resetModules();
|
||||
return await import("../src/config");
|
||||
}
|
||||
|
||||
describe("config env parsing", () => {
|
||||
it("strips shell-style inline comments from symbol values", async () => {
|
||||
process.env.EXCHANGE = "standx";
|
||||
process.env.STANDX_SYMBOL = "BTC-USD # comment";
|
||||
|
||||
const { resolveSymbolFromEnv } = await loadConfig();
|
||||
expect(resolveSymbolFromEnv()).toBe("BTC-USD");
|
||||
});
|
||||
|
||||
it("parses numeric maker-points env values with inline comments", async () => {
|
||||
process.env.EXCHANGE = "standx";
|
||||
process.env.MAKER_POINTS_STOP_LOSS_USD = "1 # comment";
|
||||
process.env.MAKER_POINTS_CLOSE_THRESHOLD = "2 ; comment";
|
||||
|
||||
const { makerPointsConfig } = await loadConfig();
|
||||
expect(makerPointsConfig.stopLossUsd).toBe(1);
|
||||
expect(makerPointsConfig.closeThreshold).toBe(2);
|
||||
});
|
||||
|
||||
it("parses boolean maker-points env values with inline comments", async () => {
|
||||
process.env.EXCHANGE = "standx";
|
||||
process.env.MAKER_POINTS_BAND_10_30 = "false # comment";
|
||||
|
||||
const { makerPointsConfig } = await loadConfig();
|
||||
expect(makerPointsConfig.enableBand10To30).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,5 +42,11 @@ describe("resolveSymbolFromEnv", () => {
|
||||
|
||||
expect(resolveSymbolFromEnv("grvt")).toBe("ETHUSDT");
|
||||
});
|
||||
});
|
||||
|
||||
it("supports standx symbol defaults when explicit exchange id is provided", () => {
|
||||
delete process.env.EXCHANGE;
|
||||
process.env.STANDX_SYMBOL = "ETH-USD";
|
||||
|
||||
expect(resolveSymbolFromEnv("standx")).toBe("ETH-USD");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AsterExchangeAdapter } from "../src/exchanges/aster-adapter";
|
||||
import { GrvtExchangeAdapter } from "../src/exchanges/grvt/adapter";
|
||||
import { BackpackExchangeAdapter } from "../src/exchanges/backpack/adapter";
|
||||
import { ParadexExchangeAdapter } from "../src/exchanges/paradex/adapter";
|
||||
import { StandxExchangeAdapter } from "../src/exchanges/standx/adapter";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
@@ -30,6 +31,7 @@ describe("exchange factory", () => {
|
||||
expect(resolveExchangeId("ASTER")).toBe("aster");
|
||||
expect(resolveExchangeId("BACKPACK")).toBe("backpack");
|
||||
expect(resolveExchangeId("PaRaDeX")).toBe("paradex");
|
||||
expect(resolveExchangeId("StandX")).toBe("standx");
|
||||
});
|
||||
|
||||
it("creates grvt adapter when EXCHANGE=grvt", () => {
|
||||
@@ -67,4 +69,14 @@ describe("exchange factory", () => {
|
||||
expect(adapter).toBeInstanceOf(ParadexExchangeAdapter);
|
||||
expect(adapter.id).toBe("paradex");
|
||||
});
|
||||
|
||||
it("creates standx adapter when EXCHANGE=standx", () => {
|
||||
process.env.EXCHANGE = "standx";
|
||||
process.env.STANDX_TOKEN = "token";
|
||||
process.env.STANDX_SYMBOL = "BTC-USD";
|
||||
|
||||
const adapter = createExchangeAdapter({ symbol: "BTC-USD" });
|
||||
expect(adapter).toBeInstanceOf(StandxExchangeAdapter);
|
||||
expect(adapter.id).toBe("standx");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ExchangeAdapter } from "../src/exchanges/adapter";
|
||||
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
|
||||
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
|
||||
|
||||
class StubAdapter implements ExchangeAdapter {
|
||||
id = "standx";
|
||||
accountSnapshot: AsterAccountSnapshot | null = null;
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
|
||||
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
|
||||
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
|
||||
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
|
||||
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
|
||||
|
||||
async createOrder(): Promise<AsterOrder> {
|
||||
throw new Error("not implemented");
|
||||
}
|
||||
|
||||
async cancelOrder(): Promise<void> {}
|
||||
async cancelOrders(): Promise<void> {}
|
||||
async cancelAllOrders(): Promise<void> {}
|
||||
|
||||
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
|
||||
return this.accountSnapshot;
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("MakerPointsEngine defense-mode account staleness", () => {
|
||||
it("does not enter defense mode for ~21s StandX account gap (REST probe succeeds)", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-24T15:20:00.000Z"));
|
||||
const adapter = new StubAdapter();
|
||||
adapter.accountSnapshot = {
|
||||
canTrade: true,
|
||||
canDeposit: true,
|
||||
canWithdraw: true,
|
||||
updateTime: Date.now(),
|
||||
totalWalletBalance: "0",
|
||||
totalUnrealizedProfit: "0",
|
||||
positions: [],
|
||||
assets: [],
|
||||
marketType: "perp",
|
||||
};
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
const now = Date.now();
|
||||
(engine as any).lastStandxDepthTime = now;
|
||||
(engine as any).lastBinanceDepthTime = now;
|
||||
(engine as any).lastStandxAccountTime = now - 21_000;
|
||||
|
||||
(engine as any).checkDataStaleAndDefense();
|
||||
expect((engine as any).defenseMode).toBe(false);
|
||||
await vi.runAllTimersAsync();
|
||||
engine.stop();
|
||||
});
|
||||
|
||||
it("enters defense mode if StandX account REST probe fails", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-24T15:20:00.000Z"));
|
||||
const adapter = new StubAdapter();
|
||||
adapter.accountSnapshot = null;
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
const now = Date.now();
|
||||
(engine as any).lastStandxDepthTime = now;
|
||||
(engine as any).lastBinanceDepthTime = now;
|
||||
(engine as any).lastStandxAccountTime = now - 121_000;
|
||||
|
||||
(engine as any).checkDataStaleAndDefense();
|
||||
expect((engine as any).defenseMode).toBe(false);
|
||||
|
||||
await vi.runAllTimersAsync();
|
||||
vi.advanceTimersByTime(1000);
|
||||
(engine as any).checkDataStaleAndDefense();
|
||||
expect((engine as any).defenseMode).toBe(true);
|
||||
engine.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ExchangeAdapter } from "../src/exchanges/adapter";
|
||||
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
|
||||
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
|
||||
|
||||
class StubAdapter implements ExchangeAdapter {
|
||||
id = "standx";
|
||||
cancelAllCount = 0;
|
||||
openOrders: AsterOrder[] | Error = [];
|
||||
accountSnapshot: AsterAccountSnapshot | null = null;
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
|
||||
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
|
||||
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
|
||||
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
|
||||
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
|
||||
|
||||
async createOrder(): Promise<AsterOrder> {
|
||||
throw new Error("not implemented");
|
||||
}
|
||||
|
||||
async cancelOrder(): Promise<void> {}
|
||||
async cancelOrders(): Promise<void> {}
|
||||
|
||||
async cancelAllOrders(): Promise<void> {
|
||||
this.cancelAllCount += 1;
|
||||
this.openOrders = [];
|
||||
}
|
||||
|
||||
async queryOpenOrders(): Promise<AsterOrder[]> {
|
||||
if (this.openOrders instanceof Error) throw this.openOrders;
|
||||
return this.openOrders;
|
||||
}
|
||||
|
||||
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
|
||||
return this.accountSnapshot;
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("MakerPointsEngine defense-mode REST polling", () => {
|
||||
it("keeps trying to fetch open orders and cancel all when open orders exist", async () => {
|
||||
vi.useFakeTimers();
|
||||
const adapter = new StubAdapter();
|
||||
adapter.openOrders = [
|
||||
{
|
||||
orderId: "1",
|
||||
clientOrderId: "c1",
|
||||
symbol: "BTC-USD",
|
||||
side: "BUY",
|
||||
type: "LIMIT",
|
||||
status: "NEW",
|
||||
price: "100",
|
||||
origQty: "1",
|
||||
executedQty: "0",
|
||||
time: Date.now(),
|
||||
updateTime: Date.now(),
|
||||
reduceOnly: "false",
|
||||
closePosition: "false",
|
||||
},
|
||||
];
|
||||
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
(engine as any).enterDefenseMode({
|
||||
standxDepthStale: true,
|
||||
binanceStale: false,
|
||||
standxAccountStale: false,
|
||||
accountInvalid: false,
|
||||
standxRestUnhealthy: false,
|
||||
standxRestConsecutiveErrors: 0,
|
||||
standxRestLastError: null,
|
||||
marginModeNotIsolated: false,
|
||||
marginMode: "isolated",
|
||||
standxDepthAge: 6000,
|
||||
binanceAge: 0,
|
||||
standxAccountAge: 0,
|
||||
accountIssues: [],
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(adapter.cancelAllCount).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
engine.stop();
|
||||
});
|
||||
|
||||
it("attempts cancel-all even if open-order query fails", async () => {
|
||||
vi.useFakeTimers();
|
||||
const adapter = new StubAdapter();
|
||||
adapter.openOrders = new Error("boom");
|
||||
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
(engine as any).enterDefenseMode({
|
||||
standxDepthStale: true,
|
||||
binanceStale: false,
|
||||
standxAccountStale: false,
|
||||
accountInvalid: false,
|
||||
standxRestUnhealthy: false,
|
||||
standxRestConsecutiveErrors: 0,
|
||||
standxRestLastError: null,
|
||||
marginModeNotIsolated: false,
|
||||
marginMode: "isolated",
|
||||
standxDepthAge: 6000,
|
||||
binanceAge: 0,
|
||||
standxAccountAge: 0,
|
||||
accountIssues: [],
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(adapter.cancelAllCount).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
engine.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ExchangeAdapter } from "../src/exchanges/adapter";
|
||||
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
|
||||
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
|
||||
|
||||
class StandxStubAdapter implements ExchangeAdapter {
|
||||
id = "standx";
|
||||
marginMode: "cross" | "isolated" = "cross";
|
||||
changeCalls: Array<{ symbol: string; marginMode: "isolated" | "cross" }> = [];
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
|
||||
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
|
||||
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
|
||||
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
|
||||
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
|
||||
|
||||
async createOrder(): Promise<AsterOrder> {
|
||||
throw new Error("not implemented");
|
||||
}
|
||||
async cancelOrder(): Promise<void> {}
|
||||
async cancelOrders(): Promise<void> {}
|
||||
async cancelAllOrders(): Promise<void> {}
|
||||
|
||||
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
|
||||
return {
|
||||
canTrade: true,
|
||||
canDeposit: true,
|
||||
canWithdraw: true,
|
||||
updateTime: Date.now(),
|
||||
totalWalletBalance: "0",
|
||||
totalUnrealizedProfit: "0",
|
||||
marketType: "perp",
|
||||
positions: [
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
positionAmt: "0",
|
||||
entryPrice: "0",
|
||||
unrealizedProfit: "0",
|
||||
positionSide: "BOTH",
|
||||
updateTime: Date.now(),
|
||||
marginType: this.marginMode,
|
||||
},
|
||||
],
|
||||
assets: [],
|
||||
};
|
||||
}
|
||||
|
||||
async changeMarginMode(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void> {
|
||||
this.changeCalls.push(params);
|
||||
this.marginMode = params.marginMode;
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("MakerPointsEngine StandX isolated margin guard", () => {
|
||||
it("switches to isolated before placing orders", async () => {
|
||||
vi.useFakeTimers();
|
||||
const adapter = new StandxStubAdapter();
|
||||
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
// Seed engine state to pass readiness checks without WS.
|
||||
(engine as any).feedStatus = { account: true, depth: true, ticker: true, orders: true, binance: true };
|
||||
(engine as any).initialOrderSnapshotReady = true;
|
||||
(engine as any).accountSnapshot = await adapter.queryAccountSnapshot();
|
||||
(engine as any).depthSnapshot = {
|
||||
lastUpdateId: 1,
|
||||
bids: [["100", "1"]],
|
||||
asks: [["101", "1"]],
|
||||
eventTime: Date.now(),
|
||||
symbol: "BTC-USD",
|
||||
} as AsterDepth;
|
||||
(engine as any).tickerSnapshot = {
|
||||
symbol: "BTC-USD",
|
||||
lastPrice: "100",
|
||||
openPrice: "0",
|
||||
highPrice: "0",
|
||||
lowPrice: "0",
|
||||
volume: "0",
|
||||
quoteVolume: "0",
|
||||
eventTime: Date.now(),
|
||||
} as AsterTicker;
|
||||
|
||||
const syncSpy = vi.fn().mockResolvedValue(undefined);
|
||||
(engine as any).syncOrders = syncSpy;
|
||||
|
||||
// First tick should force margin mode to isolated and then proceed to sync orders.
|
||||
await (engine as any).tick();
|
||||
|
||||
expect(adapter.changeCalls).toEqual([{ symbol: "BTC-USD", marginMode: "isolated" }]);
|
||||
expect(syncSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
engine.stop();
|
||||
});
|
||||
|
||||
it("enters defense mode if it cannot switch to isolated", async () => {
|
||||
vi.useFakeTimers();
|
||||
const adapter = new StandxStubAdapter();
|
||||
adapter.changeMarginMode = vi.fn(async () => {
|
||||
throw new Error("change failed");
|
||||
}) as any;
|
||||
|
||||
const engine = new MakerPointsEngine(
|
||||
{
|
||||
symbol: "BTC-USD",
|
||||
perOrderAmount: 0.01,
|
||||
closeThreshold: 0,
|
||||
stopLossUsd: 1,
|
||||
refreshIntervalMs: 500,
|
||||
maxLogEntries: 10,
|
||||
maxCloseSlippagePct: 0.05,
|
||||
priceTick: 0.1,
|
||||
qtyStep: 0.001,
|
||||
enableBand0To10: true,
|
||||
enableBand10To30: false,
|
||||
enableBand30To100: false,
|
||||
band0To10Amount: 0.01,
|
||||
band10To30Amount: 0.01,
|
||||
band30To100Amount: 0.01,
|
||||
minRepriceBps: 3,
|
||||
enableBinanceDepthCancel: false,
|
||||
filterMinDepth: 0,
|
||||
},
|
||||
adapter
|
||||
);
|
||||
|
||||
(engine as any).feedStatus = { account: true, depth: true, ticker: true, orders: true, binance: true };
|
||||
(engine as any).initialOrderSnapshotReady = true;
|
||||
(engine as any).accountSnapshot = await adapter.queryAccountSnapshot();
|
||||
(engine as any).depthSnapshot = {
|
||||
lastUpdateId: 1,
|
||||
bids: [["100", "1"]],
|
||||
asks: [["101", "1"]],
|
||||
eventTime: Date.now(),
|
||||
symbol: "BTC-USD",
|
||||
} as AsterDepth;
|
||||
(engine as any).tickerSnapshot = {
|
||||
symbol: "BTC-USD",
|
||||
lastPrice: "100",
|
||||
openPrice: "0",
|
||||
highPrice: "0",
|
||||
lowPrice: "0",
|
||||
volume: "0",
|
||||
quoteVolume: "0",
|
||||
eventTime: Date.now(),
|
||||
} as AsterTicker;
|
||||
|
||||
const syncSpy = vi.fn().mockResolvedValue(undefined);
|
||||
(engine as any).syncOrders = syncSpy;
|
||||
|
||||
await (engine as any).tick();
|
||||
|
||||
expect(syncSpy).not.toHaveBeenCalled();
|
||||
expect((engine as any).defenseMode).toBe(true);
|
||||
|
||||
engine.stop();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ParadexGateway } from "../src/exchanges/paradex/gateway";
|
||||
|
||||
describe("ParadexGateway createOrder", () => {
|
||||
it("sets `size` for closePosition MARKET orders even when amount is omitted", async () => {
|
||||
const createOrder = vi.fn(async (symbol, type, side, amount, price, params) => ({
|
||||
id: "1",
|
||||
symbol,
|
||||
type,
|
||||
side,
|
||||
status: "open",
|
||||
price: price ?? 0,
|
||||
amount: amount ?? Number(params?.size ?? 0),
|
||||
filled: 0,
|
||||
stopPrice: undefined,
|
||||
timestamp: Date.now(),
|
||||
lastUpdateTimestamp: Date.now(),
|
||||
info: {
|
||||
reduceOnly: params?.reduceOnly,
|
||||
closePosition: params?.closePosition,
|
||||
},
|
||||
}));
|
||||
|
||||
const gateway = new ParadexGateway({
|
||||
symbol: "BTC/USDC",
|
||||
displaySymbol: "BTC/USDC",
|
||||
privateKey: "test",
|
||||
walletAddress: "test",
|
||||
logger: () => {},
|
||||
usePro: false,
|
||||
}) as any;
|
||||
|
||||
gateway.exchange = { createOrder, markets: {}, symbols: [] };
|
||||
gateway.initialized = true;
|
||||
gateway.marketSymbol = "BTC/USDC";
|
||||
|
||||
await gateway.createOrder({
|
||||
symbol: "BTC/USDC",
|
||||
side: "SELL",
|
||||
type: "MARKET",
|
||||
quantity: 1.23,
|
||||
reduceOnly: "true",
|
||||
closePosition: "true",
|
||||
});
|
||||
|
||||
expect(createOrder).toHaveBeenCalledTimes(1);
|
||||
const [_symbol, _type, _side, amountArg, _price, extraParams] = createOrder.mock.calls[0]!;
|
||||
expect(amountArg).toBeUndefined();
|
||||
expect(extraParams).toMatchObject({
|
||||
closePosition: true,
|
||||
reduceOnly: true,
|
||||
size: "1.23",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeStopLossPnl } from "../src/utils/pnl";
|
||||
|
||||
describe("computeStopLossPnl", () => {
|
||||
it("falls back to exchange-provided unrealized PnL when entryPrice is missing", () => {
|
||||
const pnl = computeStopLossPnl(
|
||||
{ positionAmt: 1, entryPrice: 0, unrealizedProfit: -2000, markPrice: null },
|
||||
40000,
|
||||
40010
|
||||
);
|
||||
expect(pnl).toBe(-2000);
|
||||
});
|
||||
|
||||
it("uses best bid/ask when entryPrice is available", () => {
|
||||
const longPnl = computeStopLossPnl(
|
||||
{ positionAmt: 1, entryPrice: 100, unrealizedProfit: -5, markPrice: null },
|
||||
90,
|
||||
91
|
||||
);
|
||||
expect(longPnl).toBe(-10);
|
||||
|
||||
const shortPnl = computeStopLossPnl(
|
||||
{ positionAmt: -2, entryPrice: 100, unrealizedProfit: -5, markPrice: null },
|
||||
95,
|
||||
105
|
||||
);
|
||||
expect(shortPnl).toBe(-10);
|
||||
});
|
||||
|
||||
it("falls back to exchange-provided unrealized PnL when best prices are unavailable", () => {
|
||||
const pnl = computeStopLossPnl(
|
||||
{ positionAmt: 1, entryPrice: 100, unrealizedProfit: -123, markPrice: null },
|
||||
null,
|
||||
null
|
||||
);
|
||||
expect(pnl).toBe(-123);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { StandxGateway } from "../src/exchanges/standx/gateway";
|
||||
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("StandxGateway REST health", () => {
|
||||
it("emits unhealthy after 3 consecutive REST failures, then healthy after a success", async () => {
|
||||
const gateway = new StandxGateway({
|
||||
token: "test-token",
|
||||
symbol: "BTC-USD",
|
||||
baseUrl: "https://example.com",
|
||||
wsUrl: "wss://example.com/ws",
|
||||
logger: () => {},
|
||||
});
|
||||
|
||||
const events: Array<{ state: string; consecutiveErrors: number }> = [];
|
||||
gateway.onRestHealthEvent((state, info) => {
|
||||
events.push({ state, consecutiveErrors: info.consecutiveErrors });
|
||||
});
|
||||
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => "server error",
|
||||
} as any;
|
||||
}) as any;
|
||||
|
||||
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
|
||||
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
|
||||
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
|
||||
|
||||
expect(events).toEqual([{ state: "unhealthy", consecutiveErrors: 3 }]);
|
||||
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
text: async () => "[]",
|
||||
} as any;
|
||||
}) as any;
|
||||
|
||||
await expect(gateway.queryOpenOrders("BTC-USD")).resolves.toEqual([]);
|
||||
expect(events).toEqual([
|
||||
{ state: "unhealthy", consecutiveErrors: 3 },
|
||||
{ state: "healthy", consecutiveErrors: 0 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user