dipcoin-cli 0.5.0 β†’ 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +215 -543
  2. package/dist/cli/commands/account.d.ts.map +1 -1
  3. package/dist/cli/commands/balance.d.ts.map +1 -1
  4. package/dist/cli/commands/history.d.ts.map +1 -1
  5. package/dist/cli/commands/market.d.ts.map +1 -1
  6. package/dist/cli/commands/orders.d.ts +3 -0
  7. package/dist/cli/commands/orders.d.ts.map +1 -0
  8. package/dist/cli/commands/position.d.ts.map +1 -1
  9. package/dist/cli/commands/sub-account.d.ts +3 -0
  10. package/dist/cli/commands/sub-account.d.ts.map +1 -0
  11. package/dist/cli/commands/trade.d.ts.map +1 -1
  12. package/dist/cli/commands/vault.d.ts +0 -1
  13. package/dist/cli/commands/vault.d.ts.map +1 -1
  14. package/dist/cli/index.d.ts +1 -1
  15. package/dist/cli/index.d.ts.map +1 -1
  16. package/dist/cli/utils/output.d.ts +8 -0
  17. package/dist/cli/utils/output.d.ts.map +1 -1
  18. package/dist/cli/utils/sdk-factory.d.ts +35 -2
  19. package/dist/cli/utils/sdk-factory.d.ts.map +1 -1
  20. package/dist/cli/utils/vault-index.d.ts +6 -0
  21. package/dist/cli/utils/vault-index.d.ts.map +1 -0
  22. package/dist/cli.cjs +1179 -217
  23. package/dist/cli.cjs.map +1 -0
  24. package/dist/config/deployed/testnet/main_contract.json +58 -275
  25. package/dist/index.cjs.js +2 -2
  26. package/dist/index.cjs.js.map +1 -1
  27. package/dist/index.esm.js +2 -2
  28. package/dist/index.esm.js.map +1 -1
  29. package/dist/index.mjs +2 -2
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/src/config/index.d.ts.map +1 -1
  32. package/dist/src/constants/index.d.ts +1 -0
  33. package/dist/src/constants/index.d.ts.map +1 -1
  34. package/dist/src/sdk/sdk.d.ts +117 -1
  35. package/dist/src/sdk/sdk.d.ts.map +1 -1
  36. package/dist/src/types/index.d.ts +6 -1
  37. package/dist/src/types/index.d.ts.map +1 -1
  38. package/dist/src/utils/jwt-cache.d.ts +14 -0
  39. package/dist/src/utils/jwt-cache.d.ts.map +1 -0
  40. package/package.json +7 -10
package/README.md CHANGED
@@ -1,544 +1,360 @@
1
- # DipCoin Perpetual Trading SDK
1
+ # DipCoin Perpetual Trading SDK & CLI
2
2
 
3
- TypeScript SDK for DipCoin Perpetual Trading on Sui blockchain.
3
+ TypeScript SDK and CLI for perpetual futures trading on the Sui blockchain.
4
4
 
5
- ## Table of Contents
5
+ ## Installation
6
6
 
7
- 1. [Installation](#-installation)
8
- 2. [Quick Start](#-quick-start)
9
- 3. [Unified Demo Script](#-unified-demo-script)
10
- 4. [Usage Guide](#-usage-guide)
11
- 5. [Core Features](#core-features)
12
- 6. [API Reference](#api-reference)
13
- 7. [Examples](#examples)
14
- 8. [License](#license)
15
-
16
- ## πŸ“¦ Installation
7
+ **CLI (global):**
17
8
 
18
9
  ```bash
19
- npm install @dipcoinlab/perp-client-ts
20
- # or
21
- yarn add @dipcoinlab/perp-client-ts
10
+ npm install -g dipcoin-cli
22
11
  ```
23
12
 
24
- ## πŸš€ Quick Start
25
-
26
- ### 1. Install Dependencies
13
+ **SDK (as dependency):**
27
14
 
28
15
  ```bash
29
- npm install
16
+ npm install dipcoin-cli
30
17
  ```
31
18
 
32
- ### 2. Configure Environment
19
+ ## CLI Quick Start
20
+
21
+ ### Configuration
33
22
 
34
- Create a `.env` file in the project root:
23
+ Create a `.env` file in your working directory (or at `~/.config/dipcoin/env` for global config):
35
24
 
36
25
  ```bash
37
- PRIVATE_KEY=your-private-key-here
26
+ MNEMONIC=word1 word2 word3 ... word12
27
+ NETWORK=testnet # or mainnet
38
28
  ```
39
29
 
40
- ### 3. Run Example
30
+ Index 0 of the HD derivation path is the main account. Use `--vault-index` for sub-accounts.
31
+
32
+ ### Basic Workflow
41
33
 
42
34
  ```bash
43
- npm run example
44
- # or
45
- RUN_LIMIT_ORDER=1 npm run example
46
- ```
35
+ # Check available pairs
36
+ dipcoin-cli market pairs
47
37
 
48
- This command executes the unified script at `examples/index.ts`.
49
- Each trading action (deposits, withdrawals, order placement, margin edits, TP/SL flows, etc.) is disabled by default and can be opt‑in via environment flags. See [USAGE.md](./USAGE.md) for the complete flag matrix and safety notes.
38
+ # Get current price
39
+ dipcoin-cli market ticker BTC
50
40
 
51
- ## 🎯 Unified Demo Script
41
+ # Check account balance
42
+ dipcoin-cli account info
52
43
 
53
- The legacy example files have been consolidated into `examples/index.ts`.
54
- It executes a curated workflow in the following order:
44
+ # Open a long position: buy BTC with 100 USDC at 10x leverage
45
+ dipcoin-cli trade buy BTC 100USDC 10x --tp 105000 --sl 90000
55
46
 
56
- 1. Wallet setup & authentication (prints the derived wallet address and target network)
57
- 2. Optional on-chain funding (deposit / withdraw) driven by `DEPOSIT_AMOUNT` and `WITHDRAW_AMOUNT`
58
- 3. Account, position, and open-order snapshots for the primary `DEMO_SYMBOL`
59
- 4. Market and limit order placement with optional post-placement cancellation
60
- 5. Market data inspection (order book snapshot + ticker snapshot with spread calculations)
61
- 6. Leverage & margin utilities, including preferred leverage adjustments and isolated margin add/remove flows
62
- 7. TP/SL lifecycle management (create, list, edit, and cancel position-level TP/SL plans)
47
+ # Monitor position
48
+ dipcoin-cli position list
63
49
 
64
- All on-chain or order-creating steps are opt-in. Enable only the pieces you wish to test:
50
+ # Close position (reduce-only sell)
51
+ dipcoin-cli trade sell BTC 0 10x --qty 0.01 --reduce-only
65
52
 
66
- | Flag | Purpose | Default |
67
- | --- | --- | --- |
68
- | `RUN_DEPOSIT` / `RUN_WITHDRAW` | Move funds between wallet & exchange | `0` |
69
- | `RUN_MARKET_ORDER` | Submit a market order | `0` |
70
- | `RUN_LIMIT_ORDER` | Submit a limit order (configure `LIMIT_ORDER_PRICE`) | `0` |
71
- | `RUN_CANCEL_ORDER` | Cancel the first open order | `0` |
72
- | `RUN_MARKET_DATA` | Print order book + ticker snapshots | `1` |
73
- | `RUN_ADJUST_LEVERAGE` | Update preferred leverage (off-chain) | `0` |
74
- | `RUN_MARGIN_ADD` / `RUN_MARGIN_REMOVE` | Add/remove isolated margin (on-chain) | `0` |
75
- | `RUN_TPSL_DEMO` | Create TP/SL orders for a position | `0` |
76
- | `RUN_TPSL_EDIT` | Edit existing TP/SL plans (needs plan IDs) | `0` |
53
+ # Review history
54
+ dipcoin-cli history orders --symbol BTC-PERP
55
+ ```
77
56
 
78
- Additional tuning variables such as `DEPOSIT_AMOUNT`, `MARKET_ORDER_QTY`, `LIMIT_ORDER_SIDE`, `MARGIN_SYMBOL`, `TPSL_SYMBOL`, etc. mirror the names from the previous standalone scripts to remain backwards compatible.
57
+ ## CLI Commands
79
58
 
80
- > Need a quick way to only inspect or update preferred leverage? Run `npm run example:leverage` (see `USAGE.md` for flags such as `SET_LEVERAGE`, `LEVERAGE_TARGET`, `LEVERAGE_SYMBOL`).
59
+ ### Global Options
81
60
 
82
- ### Script Flow Details
61
+ | Option | Description |
62
+ |--------|-------------|
63
+ | `--json` | Output in JSON format (machine-readable) |
64
+ | `--vault-index <n>` | Use HD-derived sub-account at index N (placed before subcommand) |
65
+ | `-V, --version` | Show version |
83
66
 
84
- Each major block inside `examples/index.ts` is wrapped in a helper such as `maybeDeposit`, `maybePlaceMarketOrder`, or `maybeRunTpSlFlow`.
85
- Those helpers gate their logic behind the environment switches above, print labeled sections (via `logSection`), and provide success/error emojis so you can visually trace the execution in your terminal logs. The script also:
67
+ ### market
86
68
 
87
- - Fetches trading pairs and resolves the `perpId` automatically for the configured symbol (falls back to `sdk.getPerpetualID`).
88
- - Shows wallet/account diagnostics before any trading action so you can confirm balances and exposure.
89
- - Prints the top-of-book bids/asks plus percentage spread by using BigNumber math, making it easier to compare against the web UI.
90
- - Surfaces TP/SL plan IDs and hashes so that subsequent edits or cancellations can reuse real identifiers without manual API calls.
69
+ ```bash
70
+ dipcoin-cli market pairs # List all trading pairs
71
+ dipcoin-cli market ticker <symbol> # Ticker (price, volume, funding)
72
+ dipcoin-cli market orderbook <symbol> # Order book
73
+ dipcoin-cli market oracle <symbol> # Oracle price
74
+ ```
91
75
 
92
- ### Environment Parameters
76
+ Symbols auto-normalize: `BTC` becomes `BTC-PERP`.
93
77
 
94
- Beyond the boolean toggles, the demo reads the following configuration values (all optional, shown with defaults from the script):
78
+ ### account
95
79
 
96
- | Variable | Purpose | Default |
97
- | --- | --- | --- |
98
- | `NETWORK` | `mainnet` or `testnet` selection passed to `initDipCoinPerpSDK`. | `testnet` |
99
- | `DEMO_SYMBOL` | Primary symbol inspected by the snapshots and trading actions. | `BTC-PERP` |
100
- | `PRIVATE_KEY` | Private key for signing transactions (required). | _none_ |
101
- | `DEPOSIT_AMOUNT` / `WITHDRAW_AMOUNT` | USDC amounts for bank transfers. | `10` / `5` |
102
- | `MARKET_ORDER_QTY`, `MARKET_ORDER_LEVERAGE`, `MARKET_ORDER_SIDE` | Market order size, leverage, and side (`BUY`/`SELL`). | `0.01`, `20`, `BUY` |
103
- | `LIMIT_ORDER_QTY`, `LIMIT_ORDER_PRICE`, `LIMIT_ORDER_LEVERAGE`, `LIMIT_ORDER_SIDE` | Limit order parameters. | `0.01`, `85000`, `20`, `BUY` |
104
- | `MARGIN_SYMBOL`, `MARGIN_ADD_AMOUNT`, `MARGIN_REMOVE_AMOUNT` | Target symbol and USDC sizes for margin utilities. | `DEMO_SYMBOL`, `10`, `5` |
105
- | `MARGIN_TARGET_LEVERAGE`, `MARGIN_TYPE` | Preferred leverage update payload. | `20`, `ISOLATED` |
106
- | `TPSL_SYMBOL`, `POSITION_ID` | Symbol/position used when fetching TP/SL plans (falls back to detected positions). | `DEMO_SYMBOL`, _auto-detected_ |
107
- | `TPSL_EDIT_TP_PLAN_ID`, `TPSL_EDIT_SL_PLAN_ID`, `TPSL_CANCEL_HASH` | Explicit plan IDs/hashes for TP/SL edit and cancel flows. | _auto-resolved when possible_ |
80
+ ```bash
81
+ dipcoin-cli account info # Balance, margin, PnL
82
+ dipcoin-cli account info --vault <address> # Info for specific vault address
83
+ dipcoin-cli account deposit <amount> # Deposit USDC to exchange
84
+ dipcoin-cli account withdraw <amount> # Withdraw USDC from exchange
85
+ ```
108
86
 
109
- Example: run just the limit-order workflow against ETH with a tighter size.
87
+ ### balance
110
88
 
111
89
  ```bash
112
- DEMO_SYMBOL=ETH-PERP RUN_LIMIT_ORDER=1 LIMIT_ORDER_QTY=0.05 LIMIT_ORDER_PRICE=3800 npm run example
90
+ dipcoin-cli balance # On-chain coin balances
113
91
  ```
114
92
 
115
- Because the script exits on authentication failure or missing `PRIVATE_KEY`, you can safely iterate by tweaking `.env` without risking partial executions. When testing on-chain actions, double-check gas budgets and balances before enabling their flags.
93
+ ### trade
116
94
 
117
- ### Leverage Utility Recipes
95
+ ```bash
96
+ # Buy/Sell with USDC margin amount (auto-converts to quantity)
97
+ dipcoin-cli trade buy <symbol> <amount> <leverage>
98
+ dipcoin-cli trade sell <symbol> <amount> <leverage>
118
99
 
119
- The demo exposes two leverage helpers:
100
+ # Limit order (auto-detected from --price)
101
+ dipcoin-cli trade buy BTC 100USDC 10x --price 95000
120
102
 
121
- - `showPreferredLeverage` β†’ calls `sdk.getUserConfig(symbol)` to fetch the current leverage, margin type, and raw on-chain value.
122
- - `maybeAdjustPreferredLeverage` β†’ conditionally invokes `sdk.adjustLeverage(...)` when `RUN_ADJUST_LEVERAGE=1` (or `RUN_SET_LEVERAGE=1`) and prints the post-update config.
103
+ # With TP/SL
104
+ dipcoin-cli trade buy BTC 100USDC 10x --tp 105000 --sl 90000
123
105
 
124
- Run the leverage inspection on its own:
106
+ # Explicit quantity instead of USDC margin
107
+ dipcoin-cli trade buy BTC 100USDC 10x --qty 0.01
125
108
 
126
- ```bash
127
- RUN_MARKET_DATA=0 RUN_ADJUST_LEVERAGE=0 npm run example
128
- ```
109
+ # Reduce-only (for closing)
110
+ dipcoin-cli trade sell BTC 0 10x --qty 0.01 --reduce-only
129
111
 
130
- Update the preferred leverage for ETH perpetuals to 12x isolated:
131
-
132
- ```bash
133
- MARGIN_SYMBOL=ETH-PERP RUN_ADJUST_LEVERAGE=1 MARGIN_TARGET_LEVERAGE=12 MARGIN_TYPE=ISOLATED npm run example
112
+ # Cancel orders
113
+ dipcoin-cli trade cancel <symbol> <hash1> [hash2...]
134
114
  ```
135
115
 
136
- Behind the scenes the SDK sequence is:
116
+ **Trade Options:**
137
117
 
138
- ```typescript
139
- const current = await sdk.getUserConfig("ETH-PERP");
140
- console.log("Current leverage:", current.data?.leverage);
141
- await sdk.adjustLeverage({ symbol: "ETH-PERP", leverage: "12", marginType: "ISOLATED" });
142
- ```
118
+ | Option | Description |
119
+ |--------|-------------|
120
+ | `--qty <quantity>` | Specify order quantity directly (amount arg ignored) |
121
+ | `--price <p>` | Limit order price (auto-enables limit order type) |
122
+ | `--reduce-only` | Reduce-only order |
123
+ | `--tp <price>` | Take profit trigger price |
124
+ | `--sl <price>` | Stop loss trigger price |
125
+ | `--vault <address>` | Vault/creator address (fallback) |
143
126
 
144
- ### TP/SL Utility Recipes
127
+ ### position
145
128
 
146
- `maybeRunTpSlFlow` orchestrates the entire lifecycle:
129
+ ```bash
130
+ dipcoin-cli position list # List open positions
131
+ dipcoin-cli position list --symbol BTC-PERP # Filter by symbol
147
132
 
148
- 1. Detect or fetch `POSITION_ID` for the configured `TPSL_SYMBOL`.
149
- 2. Place TP/SL plans when `RUN_TPSL_DEMO=1` via `sdk.placePositionTpSlOrders`.
150
- 3. Read back the plan list with `sdk.getPositionTpSl(positionId, "position")`.
151
- 4. Edit existing plans when `RUN_TPSL_EDIT=1` and `TPSL_EDIT_TP_PLAN_ID` / `TPSL_EDIT_SL_PLAN_ID` are provided (or auto-detected).
152
- 5. Cancel a specific plan by hash with `sdk.cancelTpSlOrders`.
133
+ # Set TP/SL on existing position
134
+ dipcoin-cli position tpsl <symbol> --side <buy|sell> --quantity <q> --leverage <n> \
135
+ --tp-trigger <price> --sl-trigger <price>
153
136
 
154
- Minimal command to list current TP/SL plans for BTC and stop after the fetch:
137
+ # TP/SL with limit type
138
+ dipcoin-cli position tpsl <symbol> --side sell --quantity 0.01 --leverage 10 \
139
+ --tp-trigger 105000 --tp-type limit --tp-price 105000
155
140
 
156
- ```bash
157
- RUN_TPSL_DEMO=0 RUN_TPSL_EDIT=0 TPSL_SYMBOL=BTC-PERP POSITION_ID=<position-id> npm run example
141
+ # Margin operations (on-chain)
142
+ dipcoin-cli position margin add <symbol> <amount>
143
+ dipcoin-cli position margin remove <symbol> <amount>
158
144
  ```
159
145
 
160
- Demo new TP/SL orders on ETH using the auto-detected position and Perpetual ID:
146
+ The `--side` is the **closing side**: use `sell` for long positions, `buy` for short.
147
+
148
+ ### orders
161
149
 
162
150
  ```bash
163
- TPSL_SYMBOL=ETH-PERP RUN_TPSL_DEMO=1 npm run example
151
+ dipcoin-cli orders # List all open orders
152
+ dipcoin-cli orders --symbol BTC-PERP # Filter by symbol
153
+ dipcoin-cli orders --vault <address> # Filter by vault
164
154
  ```
165
155
 
166
- Edit an existing TP plan and cancel another by hash:
156
+ ### vault
157
+
158
+ On-chain vault operations (DipCoin vault contracts):
167
159
 
168
160
  ```bash
169
- RUN_TPSL_EDIT=1 TPSL_EDIT_TP_PLAN_ID=<plan-id> TPSL_CANCEL_HASH=<plan-hash> npm run example
170
- ```
161
+ dipcoin-cli vault create --name <name> --trader <address> --max-cap <usdc> \
162
+ --min-deposit <usdc> --creator-share <pct> --profit-share <pct> --initial <usdc>
171
163
 
172
- These flows map directly to the SDK calls shown in the [Manage Existing Position TP/SL Orders](#manage-existing-position-tpsl-orders) section if you prefer to script them manually.
164
+ dipcoin-cli vault list # List vaults created by wallet
165
+ dipcoin-cli vault info <vaultId> # Vault details
166
+ dipcoin-cli vault deposit <vaultId> <amount>
167
+ dipcoin-cli vault withdraw <vaultId> <shares>
168
+ dipcoin-cli vault fill <vaultId> <requestIDs...> [--markets <ids>]
169
+ dipcoin-cli vault close <vaultId> [--markets <ids>]
170
+ dipcoin-cli vault remove <vaultId>
171
+ dipcoin-cli vault claim <vaultId>
172
+ dipcoin-cli vault set-trader <vaultId> <address>
173
+ dipcoin-cli vault set-sub-trader <vaultId> <address> [--disable]
174
+ dipcoin-cli vault set-deposit-status <vaultId> [--disable]
175
+ dipcoin-cli vault set-max-cap <vaultId> <amount>
176
+ dipcoin-cli vault set-min-deposit <vaultId> <amount>
177
+ dipcoin-cli vault set-auto-close <vaultId> [--disable]
178
+ ```
173
179
 
174
- ## πŸ“– Usage Guide
180
+ ### sub-account
175
181
 
176
- ### Initialize SDK
182
+ HD-derived sub-account management:
177
183
 
178
- ```typescript
179
- import { initDipCoinPerpSDK } from "@dipcoinlab/perp-client-ts";
184
+ ```bash
185
+ dipcoin-cli sub-account list [--count <n>] # List derived addresses (default 5)
186
+ dipcoin-cli sub-account setup <index> # Derive and register sub-account on-chain
187
+ dipcoin-cli sub-account set <subAddress> # Authorize a sub-account address
188
+ ```
180
189
 
181
- // Initialize with private key string
182
- const sdk = initDipCoinPerpSDK("your-private-key-string", {
183
- network: "mainnet", // or "testnet"
184
- apiBaseUrl: "https://api.dipcoin.io", // Optional, defaults based on network
185
- });
190
+ ### history
186
191
 
187
- // Or initialize with Keypair
188
- import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
189
- const keypair = Ed25519Keypair.fromSecretKey(/* your secret key */);
190
- const sdk = initDipCoinPerpSDK(keypair, {
191
- network: "mainnet",
192
- });
192
+ ```bash
193
+ dipcoin-cli history orders [--symbol <s>] [--page <n>] [--size <n>]
194
+ dipcoin-cli history funding [--symbol <s>] [--page <n>] [--size <n>]
195
+ dipcoin-cli history balance [--page <n>] [--size <n>]
193
196
  ```
194
197
 
195
- ## Core Features
198
+ All history commands support `--vault <address>` and `--begin-time <ms>`.
196
199
 
197
- ### Authentication (Onboarding)
200
+ ## Multi-Vault Workflow
198
201
 
199
- Before using the SDK, you need to authenticate first. The SDK will automatically handle authentication when you call any API method, but you can also authenticate manually:
202
+ The CLI uses HD key derivation from your mnemonic. Index 0 is the main account, index 1+ are sub-accounts.
200
203
 
201
- ```typescript
202
- // Manual authentication
203
- const authResult = await sdk.authenticate();
204
- if (authResult.status) {
205
- console.log("Authenticated! JWT Token:", authResult.data);
206
- } else {
207
- console.error("Authentication failed:", authResult.error);
208
- }
204
+ ```bash
205
+ # List derived addresses
206
+ dipcoin-cli sub-account list
209
207
 
210
- // Get JWT token (authenticates if needed)
211
- const tokenResult = await sdk.getJWTToken();
212
- if (tokenResult.status) {
213
- console.log("JWT Token:", tokenResult.data);
214
- }
208
+ # Register sub-account 1 on-chain
209
+ dipcoin-cli sub-account setup 1
215
210
 
216
- // Force refresh token
217
- const refreshResult = await sdk.getJWTToken(true);
211
+ # Deposit to sub-account 1
212
+ dipcoin-cli --vault-index 1 account deposit 100
218
213
 
219
- // Clear authentication (logout)
220
- sdk.clearAuth();
214
+ # Trade on sub-account 1
215
+ dipcoin-cli --vault-index 1 trade buy BTC 50USDC 10x
216
+
217
+ # Check sub-account 1 positions
218
+ dipcoin-cli --vault-index 1 position list
221
219
  ```
222
220
 
223
- **Note:** All API methods automatically authenticate if needed, so you don't need to call `authenticate()` manually in most cases.
221
+ `--vault-index` is always a **global option** placed before the subcommand.
224
222
 
225
- ### Account Information
223
+ ## SDK Usage
226
224
 
227
- Get account balance and trading information:
225
+ ### Initialize
228
226
 
229
227
  ```typescript
230
- const accountInfo = await sdk.getAccountInfo();
228
+ import { initDipCoinPerpSDK } from "dipcoin-cli";
229
+ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
231
230
 
232
- if (accountInfo.status && accountInfo.data) {
233
- console.log("Wallet Balance:", accountInfo.data.walletBalance);
234
- console.log("Account Value:", accountInfo.data.accountValue);
235
- console.log("Free Collateral:", accountInfo.data.freeCollateral);
236
- console.log("Unrealized PnL:", accountInfo.data.totalUnrealizedProfit);
237
- }
238
- ```
231
+ const keypair = Ed25519Keypair.deriveKeypair("your mnemonic phrase ...");
232
+ const sdk = initDipCoinPerpSDK(keypair, { network: "mainnet" });
239
233
 
240
- ### Deposit and Withdraw
234
+ // With sub-account for vault trading
235
+ const subKeypair = Ed25519Keypair.deriveKeypair("your mnemonic", "m/44'/784'/1'/0'/0'");
236
+ const vaultSdk = initDipCoinPerpSDK(keypair, { network: "mainnet", subAccountKey: subKeypair });
237
+ ```
241
238
 
242
- Deposit USDC to the exchange bank account for trading collateral, or withdraw USDC back to your wallet:
239
+ ### Authentication
243
240
 
244
241
  ```typescript
245
- // Deposit USDC to bank (deposit funds for trading)
246
- const depositResult = await sdk.depositToBank(100); // Deposit 100 USDC
247
- if (depositResult) {
248
- console.log("Deposit successful!");
242
+ const authResult = await sdk.authenticate();
243
+ if (authResult.status) {
244
+ console.log("Authenticated:", authResult.data);
249
245
  }
250
246
 
251
- // Withdraw USDC from bank (withdraw funds to wallet)
252
- const withdrawResult = await sdk.withdrawFromBank(50); // Withdraw 50 USDC
253
- if (withdrawResult) {
254
- console.log("Withdraw successful!");
255
- }
247
+ // All API methods auto-authenticate when needed
256
248
  ```
257
249
 
258
- **Note:** These methods execute on-chain transactions on Sui blockchain. Make sure you have sufficient USDC balance in your wallet before depositing, and sufficient balance in your exchange account before withdrawing.
259
-
260
- ### Adjust Preferred Leverage
261
-
262
- Match the web client's leverage settings through the same REST API:
250
+ ### Account Info
263
251
 
264
252
  ```typescript
265
- await sdk.adjustLeverage({
266
- symbol: "BTC-PERP",
267
- leverage: "5", // 5x leverage
268
- marginType: "ISOLATED", // optional, defaults to ISOLATED
269
- });
253
+ const info = await sdk.getAccountInfo();
254
+ if (info.status && info.data) {
255
+ console.log("Balance:", info.data.walletBalance);
256
+ console.log("Free Collateral:", info.data.freeCollateral);
257
+ }
270
258
  ```
271
259
 
272
- ### Add or Remove Position Margin (On-chain)
273
-
274
- Interact with the on-chain contracts to add or remove isolated margin. These actions spend gas and require sufficient balances.
260
+ ### Deposit & Withdraw
275
261
 
276
262
  ```typescript
277
- // Add 2 USDC margin to BTC-PERP
278
- await sdk.addMargin({
279
- amount: 2,
280
- symbol: "BTC-PERP",
281
- });
282
-
283
- // Remove 1 USDC margin from BTC-PERP
284
- await sdk.removeMargin({
285
- amount: 1,
286
- symbol: "BTC-PERP",
287
- });
263
+ // On-chain transactions (USDC to/from exchange)
264
+ await sdk.depositToBank(100); // 100 USDC
265
+ await sdk.withdrawFromBank(50); // 50 USDC
288
266
  ```
289
267
 
290
- > ⚠️ Margin operations are on-chain transactions. Double-check the amount and symbol before running them.
291
-
292
268
  ### Place Order
293
269
 
294
- Place a market or limit order:
295
-
296
270
  ```typescript
297
- import { OrderSide, OrderType } from "@dipcoinlab/perp-client-ts";
271
+ import { OrderSide, OrderType } from "dipcoin-cli";
298
272
 
299
273
  // Market order
300
274
  const result = await sdk.placeOrder({
301
275
  symbol: "BTC-PERP",
302
276
  side: OrderSide.BUY,
303
277
  orderType: OrderType.MARKET,
304
- quantity: "0.1", // 0.1 BTC
305
- leverage: "10", // 10x leverage
278
+ quantity: "0.1",
279
+ leverage: "10",
306
280
  });
307
281
 
308
282
  // Limit order
309
- const limitResult = await sdk.placeOrder({
283
+ const limit = await sdk.placeOrder({
310
284
  symbol: "BTC-PERP",
311
285
  side: OrderSide.BUY,
312
286
  orderType: OrderType.LIMIT,
313
287
  quantity: "0.1",
314
- price: "50000", // Limit price
288
+ price: "95000",
315
289
  leverage: "10",
316
- reduceOnly: false, // Optional: only reduce position
317
290
  });
318
291
 
319
- if (result.status) {
320
- console.log("Order placed successfully:", result.data);
321
- } else {
322
- console.error("Order failed:", result.error);
323
- }
324
- ```
325
-
326
- ### Place Order with TP/SL
327
-
328
- Place an order with take profit and stop loss:
329
-
330
- ```typescript
331
- const result = await sdk.placeOrder({
292
+ // With TP/SL
293
+ const withTpSl = await sdk.placeOrder({
332
294
  symbol: "BTC-PERP",
333
295
  side: OrderSide.BUY,
334
296
  orderType: OrderType.MARKET,
335
297
  quantity: "0.1",
336
298
  leverage: "10",
337
- // Take profit
338
- tpTriggerPrice: "55000",
339
- tpOrderType: OrderType.MARKET,
340
- // Stop loss
341
- slTriggerPrice: "45000",
342
- slOrderType: OrderType.MARKET,
299
+ tpTriggerPrice: "105000",
300
+ slTriggerPrice: "90000",
343
301
  });
344
302
  ```
345
303
 
346
- ### Manage Existing Position TP/SL Orders
304
+ ### Position TP/SL
347
305
 
348
306
  ```typescript
349
307
  await sdk.placePositionTpSlOrders({
350
308
  symbol: "BTC-PERP",
351
309
  market: "<perpetual-id>",
352
310
  side: OrderSide.SELL,
353
- isLong: false,
311
+ isLong: true,
354
312
  leverage: "10",
355
- quantity: "0.05",
356
- tp: {
357
- triggerPrice: "90000",
358
- orderType: OrderType.LIMIT,
359
- orderPrice: "90000",
360
- tpslType: "position",
361
- },
362
- sl: {
363
- triggerPrice: "70000",
364
- orderType: OrderType.MARKET,
365
- tpslType: "position",
366
- },
367
- });
368
-
369
- const tpSlOrders = await sdk.getPositionTpSl("<position-id>", "position");
370
-
371
- await sdk.cancelTpSlOrders({
372
- symbol: "BTC-PERP",
373
- orderHashes: ["0xabc..."],
313
+ quantity: "0.1",
314
+ tp: { triggerPrice: "105000", orderType: OrderType.MARKET, tpslType: "position" },
315
+ sl: { triggerPrice: "90000", orderType: OrderType.MARKET, tpslType: "position" },
374
316
  });
375
317
  ```
376
318
 
377
- ### Market Data (Ticker & Order Book)
319
+ ### Market Data
378
320
 
379
321
  ```typescript
380
322
  const ticker = await sdk.getTicker("BTC-PERP");
381
323
  const orderBook = await sdk.getOrderBook("BTC-PERP");
324
+ const oraclePrice = await sdk.getOraclePrice("BTC-PERP");
325
+ const pairs = await sdk.getTradingPairs();
382
326
  ```
383
327
 
384
328
  ### Cancel Order
385
329
 
386
- Cancel one or more orders:
387
-
388
330
  ```typescript
389
- const result = await sdk.cancelOrder({
331
+ await sdk.cancelOrder({
390
332
  symbol: "BTC-PERP",
391
- orderHashes: ["0x1234...", "0x5678..."], // Array of order hashes
333
+ orderHashes: ["0x1234..."],
392
334
  });
393
-
394
- if (result.status) {
395
- console.log("Orders cancelled successfully");
396
- } else {
397
- console.error("Cancel failed:", result.error);
398
- }
399
335
  ```
400
336
 
401
- ### Get Positions
402
-
403
- Get current positions:
337
+ ### Positions & Open Orders
404
338
 
405
339
  ```typescript
406
- // Get all positions
407
340
  const positions = await sdk.getPositions();
408
-
409
- // Get positions for specific symbol
410
- const btcPositions = await sdk.getPositions("BTC-PERP");
411
-
412
- if (positions.status && positions.data) {
413
- positions.data.forEach((position) => {
414
- console.log("Symbol:", position.symbol);
415
- console.log("Side:", position.side);
416
- console.log("Quantity:", position.quantity);
417
- console.log("Entry Price:", position.avgEntryPrice);
418
- console.log("Unrealized PnL:", position.unrealizedProfit);
419
- console.log("Liquidation Price:", position.liquidationPrice);
420
- });
421
- }
422
- ```
423
-
424
- ### Get Open Orders
425
-
426
- Get current open orders:
427
-
428
- ```typescript
429
- // Get all open orders
430
341
  const orders = await sdk.getOpenOrders();
431
-
432
- // Get open orders for specific symbol
433
- const btcOrders = await sdk.getOpenOrders("BTC-PERP");
434
-
435
- if (orders.status && orders.data) {
436
- orders.data.forEach((order) => {
437
- console.log("Symbol:", order.symbol);
438
- console.log("Side:", order.side);
439
- console.log("Type:", order.orderType);
440
- console.log("Price:", order.price);
441
- console.log("Quantity:", order.quantity);
442
- console.log("Filled:", order.filledQty);
443
- });
444
- }
445
342
  ```
446
343
 
447
- ## API Reference
448
-
449
- ### DipCoinPerpSDK
450
-
451
- Main SDK class for interacting with DipCoin Perpetual Trading.
452
-
453
- #### Methods
454
-
455
- ##### `placeOrder(params: PlaceOrderParams): Promise<SDKResponse<OrderResponse>>`
456
-
457
- Place a new order.
458
-
459
- **Parameters:**
460
- - `symbol`: Trading symbol (e.g., "BTC-PERP")
461
- - `side`: Order side (`OrderSide.BUY` or `OrderSide.SELL`)
462
- - `orderType`: Order type (`OrderType.MARKET` or `OrderType.LIMIT`)
463
- - `quantity`: Order quantity (number or string)
464
- - `price`: Order price (required for LIMIT orders)
465
- - `leverage`: Leverage multiplier (number or string)
466
- - `market`: Optional market ID
467
- - `reduceOnly`: Optional, only reduce position
468
- - `clientId`: Optional client order ID
469
- - `tpTriggerPrice`: Optional take profit trigger price
470
- - `tpOrderType`: Optional take profit order type
471
- - `tpOrderPrice`: Optional take profit order price
472
- - `slTriggerPrice`: Optional stop loss trigger price
473
- - `slOrderType`: Optional stop loss order type
474
- - `slOrderPrice`: Optional stop loss order price
475
-
476
- ##### `cancelOrder(params: CancelOrderParams): Promise<SDKResponse<OrderResponse>>`
477
-
478
- Cancel one or more orders.
479
-
480
- **Parameters:**
481
- - `symbol`: Trading symbol
482
- - `orderHashes`: Array of order hashes to cancel
483
- - `parentAddress`: Optional parent address (defaults to wallet address)
484
-
485
- ##### `getAccountInfo(): Promise<SDKResponse<AccountInfo>>`
486
-
487
- Get account information including balance, collateral, and PnL.
488
-
489
- ##### `getPositions(symbol?: string): Promise<SDKResponse<Position[]>>`
490
-
491
- Get current positions. Optionally filter by symbol.
492
-
493
- ##### `getOpenOrders(symbol?: string): Promise<SDKResponse<OpenOrder[]>>`
494
-
495
- Get current open orders. Optionally filter by symbol.
496
-
497
- ##### `depositToBank(amount: number): Promise<any>`
498
-
499
- Deposit USDC from wallet to exchange bank account for trading collateral.
500
-
501
- **Parameters:**
502
- - `amount`: Deposit amount in USDC (standard units, e.g., 100 means 100 USDC)
503
-
504
- **Returns:** On-chain transaction result
505
-
506
- **Note:** This is an on-chain transaction on Sui blockchain. Ensure you have sufficient USDC balance in your wallet.
507
-
508
- ##### `withdrawFromBank(amount: number): Promise<any>`
509
-
510
- Withdraw USDC from exchange bank account back to wallet.
511
-
512
- **Parameters:**
513
- - `amount`: Withdraw amount in USDC (standard units, e.g., 50 means 50 USDC)
514
-
515
- **Returns:** On-chain transaction result
516
-
517
- **Note:** This is an on-chain transaction on Sui blockchain. Ensure you have sufficient balance in your exchange account.
518
-
519
- ## Types
520
-
521
- ### OrderSide
344
+ ### Leverage & Margin
522
345
 
523
346
  ```typescript
524
- enum OrderSide {
525
- BUY = "BUY",
526
- SELL = "SELL",
527
- }
347
+ await sdk.adjustLeverage({ symbol: "BTC-PERP", leverage: "10", marginType: "ISOLATED" });
348
+ await sdk.addMargin({ symbol: "BTC-PERP", amount: 5 });
349
+ await sdk.removeMargin({ symbol: "BTC-PERP", amount: 2 });
528
350
  ```
529
351
 
530
- ### OrderType
352
+ ## Types
531
353
 
532
354
  ```typescript
533
- enum OrderType {
534
- MARKET = "MARKET",
535
- LIMIT = "LIMIT",
536
- }
537
- ```
538
-
539
- ### AccountInfo
355
+ enum OrderSide { BUY = "BUY", SELL = "SELL" }
356
+ enum OrderType { MARKET = "MARKET", LIMIT = "LIMIT" }
540
357
 
541
- ```typescript
542
358
  interface AccountInfo {
543
359
  walletBalance: string;
544
360
  totalUnrealizedProfit: string;
@@ -546,191 +362,47 @@ interface AccountInfo {
546
362
  freeCollateral: string;
547
363
  totalMargin: string;
548
364
  }
549
- ```
550
-
551
- ### Position
552
365
 
553
- ```typescript
554
366
  interface Position {
555
- symbol: string;
556
- side: string;
557
- quantity: string;
558
- avgEntryPrice: string;
559
- leverage: string;
560
- margin: string;
561
- unrealizedProfit: string;
562
- liquidationPrice: string;
563
- // ... more fields
367
+ symbol: string; side: string; quantity: string;
368
+ avgEntryPrice: string; leverage: string; margin: string;
369
+ unrealizedProfit: string; liquidationPrice: string;
564
370
  }
565
- ```
566
371
 
567
- ### OpenOrder
568
-
569
- ```typescript
570
372
  interface OpenOrder {
571
- hash: string;
572
- symbol: string;
573
- side: string;
574
- orderType: string;
575
- price: string;
576
- quantity: string;
577
- filledQty: string;
578
- leverage: string;
579
- status: string;
580
- // ... more fields
373
+ hash: string; symbol: string; side: string;
374
+ orderType: string; price: string; quantity: string;
375
+ filledQty: string; leverage: string; status: string;
581
376
  }
582
- ```
583
-
584
- ## Error Handling
585
377
 
586
- All SDK methods return a `SDKResponse` object with the following structure:
587
-
588
- ```typescript
589
378
  interface SDKResponse<T> {
590
- status: boolean; // Operation success status
591
- data?: T; // Response data if successful
592
- error?: string; // Error message if failed
379
+ status: boolean;
380
+ data?: T;
381
+ error?: string;
593
382
  }
594
383
  ```
595
384
 
596
- Always check the `status` field before accessing `data`:
385
+ ## Error Handling
386
+
387
+ All SDK methods return `SDKResponse<T>`. Check `status` before accessing `data`:
597
388
 
598
389
  ```typescript
599
390
  const result = await sdk.placeOrder(/* ... */);
600
-
601
391
  if (result.status) {
602
- // Success - use result.data
603
392
  console.log(result.data);
604
393
  } else {
605
- // Error - use result.error
606
394
  console.error(result.error);
607
395
  }
608
396
  ```
609
397
 
610
- ## Examples
611
-
612
- ### Complete Trading Flow
398
+ ## Development
613
399
 
614
- ```typescript
615
- import { initDipCoinPerpSDK, OrderSide, OrderType } from "@dipcoinlab/perp-client-ts";
616
-
617
- // Initialize SDK
618
- const sdk = initDipCoinPerpSDK("your-private-key", {
619
- network: "testnet",
620
- });
621
-
622
- async function tradingFlow() {
623
- // 1. Deposit funds to exchange bank account
624
- console.log("Depositing 100 USDC to bank...");
625
- await sdk.depositToBank(100);
626
-
627
- // 2. Check account balance
628
- const account = await sdk.getAccountInfo();
629
- if (account.status) {
630
- console.log("Account Value:", account.data?.accountValue);
631
- }
632
-
633
- // 3. Check existing positions
634
- const positions = await sdk.getPositions();
635
- if (positions.status) {
636
- console.log("Current Positions:", positions.data);
637
- }
638
-
639
- // 4. Place a market order
640
- const orderResult = await sdk.placeOrder({
641
- symbol: "BTC-PERP",
642
- side: OrderSide.BUY,
643
- orderType: OrderType.MARKET,
644
- quantity: "0.1",
645
- leverage: "10",
646
- });
647
-
648
- if (orderResult.status) {
649
- console.log("Order placed:", orderResult.data);
650
- }
651
-
652
- // 5. Adjust preferred leverage for BTC perpetuals
653
- const leverageUpdate = await sdk.adjustLeverage({
654
- symbol: "BTC-PERP",
655
- leverage: "12",
656
- marginType: "ISOLATED",
657
- });
658
-
659
- if (leverageUpdate.status) {
660
- console.log("Leverage updated:", leverageUpdate.data);
661
- } else {
662
- console.warn("Leverage update failed:", leverageUpdate.error);
663
- }
664
-
665
- // 6. Create and manage TP/SL plans for the active BTC position
666
- const tpSlResult = await sdk.placePositionTpSlOrders({
667
- symbol: "BTC-PERP",
668
- side: OrderSide.SELL,
669
- isLong: true,
670
- leverage: "10",
671
- quantity: "0.1",
672
- tp: {
673
- triggerPrice: "55000",
674
- orderType: OrderType.LIMIT,
675
- orderPrice: "55000",
676
- tpslType: "position",
677
- },
678
- sl: {
679
- triggerPrice: "45000",
680
- orderType: OrderType.MARKET,
681
- tpslType: "position",
682
- },
683
- });
684
-
685
- if (tpSlResult.status) {
686
- console.log("TP/SL plans placed:", tpSlResult.data);
687
- const positionId = tpSlResult.data?.positionId ?? "<position-id>";
688
- const plans = await sdk.getPositionTpSl(positionId, "position");
689
-
690
- if (plans.status) {
691
- console.log("Current TP/SL plans:", plans.data);
692
-
693
- if (plans.data && plans.data.length > 0) {
694
- const cancelTpSl = await sdk.cancelTpSlOrders({
695
- symbol: "BTC-PERP",
696
- orderHashes: [plans.data[0].hash],
697
- });
698
- console.log("Cancelled TP/SL plan:", cancelTpSl);
699
- }
700
- }
701
- } else {
702
- console.warn("TP/SL placement failed:", tpSlResult.error);
703
- }
704
-
705
- // 7. Check open orders
706
- const openOrders = await sdk.getOpenOrders("BTC-PERP");
707
- if (openOrders.status) {
708
- console.log("Open Orders:", openOrders.data);
709
- }
710
-
711
- // 8. Cancel an order (if needed)
712
- if (openOrders.status && openOrders.data && openOrders.data.length > 0) {
713
- const cancelResult = await sdk.cancelOrder({
714
- symbol: "BTC-PERP",
715
- orderHashes: [openOrders.data[0].hash],
716
- });
717
- console.log("Cancel result:", cancelResult);
718
- }
719
-
720
- // 9. Withdraw funds from exchange bank account
721
- console.log("Withdrawing 50 USDC from bank...");
722
- await sdk.withdrawFromBank(50);
723
-
724
-
725
- }
726
-
727
- tradingFlow();
400
+ ```bash
401
+ npm run cli # Run CLI in dev mode (tsx)
402
+ npm run build # Build for distribution
403
+ npm run example # Run example script
728
404
  ```
729
405
 
730
- ### Example Scripts
731
-
732
- - `npm run example` – Runs `examples/index.ts`. Enable extra steps with env flags such as `RUN_LIMIT_ORDER=1`, `RUN_MARGIN_ADD=1`, `RUN_TPSL_DEMO=1`, etc.
733
-
734
406
  ## License
735
407
 
736
408
  Apache License 2.0