dipcoin-cli 0.5.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 (50) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +736 -0
  3. package/dist/cli/commands/account.d.ts +3 -0
  4. package/dist/cli/commands/account.d.ts.map +1 -0
  5. package/dist/cli/commands/balance.d.ts +3 -0
  6. package/dist/cli/commands/balance.d.ts.map +1 -0
  7. package/dist/cli/commands/history.d.ts +3 -0
  8. package/dist/cli/commands/history.d.ts.map +1 -0
  9. package/dist/cli/commands/market.d.ts +3 -0
  10. package/dist/cli/commands/market.d.ts.map +1 -0
  11. package/dist/cli/commands/position.d.ts +3 -0
  12. package/dist/cli/commands/position.d.ts.map +1 -0
  13. package/dist/cli/commands/trade.d.ts +3 -0
  14. package/dist/cli/commands/trade.d.ts.map +1 -0
  15. package/dist/cli/commands/vault.d.ts +4 -0
  16. package/dist/cli/commands/vault.d.ts.map +1 -0
  17. package/dist/cli/index.d.ts +2 -0
  18. package/dist/cli/index.d.ts.map +1 -0
  19. package/dist/cli/utils/output.d.ts +7 -0
  20. package/dist/cli/utils/output.d.ts.map +1 -0
  21. package/dist/cli/utils/sdk-factory.d.ts +5 -0
  22. package/dist/cli/utils/sdk-factory.d.ts.map +1 -0
  23. package/dist/cli.cjs +19252 -0
  24. package/dist/config/deployed/mainnet/main_contract.json +550 -0
  25. package/dist/config/deployed/testnet/main_contract.json +550 -0
  26. package/dist/index.cjs.js +4 -0
  27. package/dist/index.cjs.js.map +1 -0
  28. package/dist/index.esm.js +4 -0
  29. package/dist/index.esm.js.map +1 -0
  30. package/dist/index.mjs +4 -0
  31. package/dist/index.mjs.map +1 -0
  32. package/dist/src/__tests__/sdk.test.d.ts +2 -0
  33. package/dist/src/__tests__/sdk.test.d.ts.map +1 -0
  34. package/dist/src/config/index.d.ts +15 -0
  35. package/dist/src/config/index.d.ts.map +1 -0
  36. package/dist/src/constants/index.d.ts +55 -0
  37. package/dist/src/constants/index.d.ts.map +1 -0
  38. package/dist/src/index.d.ts +20 -0
  39. package/dist/src/index.d.ts.map +1 -0
  40. package/dist/src/sdk/index.d.ts +2 -0
  41. package/dist/src/sdk/index.d.ts.map +1 -0
  42. package/dist/src/sdk/sdk.d.ts +300 -0
  43. package/dist/src/sdk/sdk.d.ts.map +1 -0
  44. package/dist/src/services/httpClient.d.ts +25 -0
  45. package/dist/src/services/httpClient.d.ts.map +1 -0
  46. package/dist/src/types/index.d.ts +603 -0
  47. package/dist/src/types/index.d.ts.map +1 -0
  48. package/dist/src/utils/index.d.ts +62 -0
  49. package/dist/src/utils/index.d.ts.map +1 -0
  50. package/package.json +78 -0
package/README.md ADDED
@@ -0,0 +1,736 @@
1
+ # DipCoin Perpetual Trading SDK
2
+
3
+ TypeScript SDK for DipCoin Perpetual Trading on Sui blockchain.
4
+
5
+ ## Table of Contents
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
17
+
18
+ ```bash
19
+ npm install @dipcoinlab/perp-client-ts
20
+ # or
21
+ yarn add @dipcoinlab/perp-client-ts
22
+ ```
23
+
24
+ ## 🚀 Quick Start
25
+
26
+ ### 1. Install Dependencies
27
+
28
+ ```bash
29
+ npm install
30
+ ```
31
+
32
+ ### 2. Configure Environment
33
+
34
+ Create a `.env` file in the project root:
35
+
36
+ ```bash
37
+ PRIVATE_KEY=your-private-key-here
38
+ ```
39
+
40
+ ### 3. Run Example
41
+
42
+ ```bash
43
+ npm run example
44
+ # or
45
+ RUN_LIMIT_ORDER=1 npm run example
46
+ ```
47
+
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.
50
+
51
+ ## 🎯 Unified Demo Script
52
+
53
+ The legacy example files have been consolidated into `examples/index.ts`.
54
+ It executes a curated workflow in the following order:
55
+
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)
63
+
64
+ All on-chain or order-creating steps are opt-in. Enable only the pieces you wish to test:
65
+
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` |
77
+
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.
79
+
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`).
81
+
82
+ ### Script Flow Details
83
+
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:
86
+
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.
91
+
92
+ ### Environment Parameters
93
+
94
+ Beyond the boolean toggles, the demo reads the following configuration values (all optional, shown with defaults from the script):
95
+
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_ |
108
+
109
+ Example: run just the limit-order workflow against ETH with a tighter size.
110
+
111
+ ```bash
112
+ DEMO_SYMBOL=ETH-PERP RUN_LIMIT_ORDER=1 LIMIT_ORDER_QTY=0.05 LIMIT_ORDER_PRICE=3800 npm run example
113
+ ```
114
+
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.
116
+
117
+ ### Leverage Utility Recipes
118
+
119
+ The demo exposes two leverage helpers:
120
+
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.
123
+
124
+ Run the leverage inspection on its own:
125
+
126
+ ```bash
127
+ RUN_MARKET_DATA=0 RUN_ADJUST_LEVERAGE=0 npm run example
128
+ ```
129
+
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
134
+ ```
135
+
136
+ Behind the scenes the SDK sequence is:
137
+
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
+ ```
143
+
144
+ ### TP/SL Utility Recipes
145
+
146
+ `maybeRunTpSlFlow` orchestrates the entire lifecycle:
147
+
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`.
153
+
154
+ Minimal command to list current TP/SL plans for BTC and stop after the fetch:
155
+
156
+ ```bash
157
+ RUN_TPSL_DEMO=0 RUN_TPSL_EDIT=0 TPSL_SYMBOL=BTC-PERP POSITION_ID=<position-id> npm run example
158
+ ```
159
+
160
+ Demo new TP/SL orders on ETH using the auto-detected position and Perpetual ID:
161
+
162
+ ```bash
163
+ TPSL_SYMBOL=ETH-PERP RUN_TPSL_DEMO=1 npm run example
164
+ ```
165
+
166
+ Edit an existing TP plan and cancel another by hash:
167
+
168
+ ```bash
169
+ RUN_TPSL_EDIT=1 TPSL_EDIT_TP_PLAN_ID=<plan-id> TPSL_CANCEL_HASH=<plan-hash> npm run example
170
+ ```
171
+
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.
173
+
174
+ ## 📖 Usage Guide
175
+
176
+ ### Initialize SDK
177
+
178
+ ```typescript
179
+ import { initDipCoinPerpSDK } from "@dipcoinlab/perp-client-ts";
180
+
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
+ });
186
+
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
+ });
193
+ ```
194
+
195
+ ## Core Features
196
+
197
+ ### Authentication (Onboarding)
198
+
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:
200
+
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
+ }
209
+
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
+ }
215
+
216
+ // Force refresh token
217
+ const refreshResult = await sdk.getJWTToken(true);
218
+
219
+ // Clear authentication (logout)
220
+ sdk.clearAuth();
221
+ ```
222
+
223
+ **Note:** All API methods automatically authenticate if needed, so you don't need to call `authenticate()` manually in most cases.
224
+
225
+ ### Account Information
226
+
227
+ Get account balance and trading information:
228
+
229
+ ```typescript
230
+ const accountInfo = await sdk.getAccountInfo();
231
+
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
+ ```
239
+
240
+ ### Deposit and Withdraw
241
+
242
+ Deposit USDC to the exchange bank account for trading collateral, or withdraw USDC back to your wallet:
243
+
244
+ ```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!");
249
+ }
250
+
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
+ }
256
+ ```
257
+
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:
263
+
264
+ ```typescript
265
+ await sdk.adjustLeverage({
266
+ symbol: "BTC-PERP",
267
+ leverage: "5", // 5x leverage
268
+ marginType: "ISOLATED", // optional, defaults to ISOLATED
269
+ });
270
+ ```
271
+
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.
275
+
276
+ ```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
+ });
288
+ ```
289
+
290
+ > ⚠️ Margin operations are on-chain transactions. Double-check the amount and symbol before running them.
291
+
292
+ ### Place Order
293
+
294
+ Place a market or limit order:
295
+
296
+ ```typescript
297
+ import { OrderSide, OrderType } from "@dipcoinlab/perp-client-ts";
298
+
299
+ // Market order
300
+ const result = await sdk.placeOrder({
301
+ symbol: "BTC-PERP",
302
+ side: OrderSide.BUY,
303
+ orderType: OrderType.MARKET,
304
+ quantity: "0.1", // 0.1 BTC
305
+ leverage: "10", // 10x leverage
306
+ });
307
+
308
+ // Limit order
309
+ const limitResult = await sdk.placeOrder({
310
+ symbol: "BTC-PERP",
311
+ side: OrderSide.BUY,
312
+ orderType: OrderType.LIMIT,
313
+ quantity: "0.1",
314
+ price: "50000", // Limit price
315
+ leverage: "10",
316
+ reduceOnly: false, // Optional: only reduce position
317
+ });
318
+
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({
332
+ symbol: "BTC-PERP",
333
+ side: OrderSide.BUY,
334
+ orderType: OrderType.MARKET,
335
+ quantity: "0.1",
336
+ leverage: "10",
337
+ // Take profit
338
+ tpTriggerPrice: "55000",
339
+ tpOrderType: OrderType.MARKET,
340
+ // Stop loss
341
+ slTriggerPrice: "45000",
342
+ slOrderType: OrderType.MARKET,
343
+ });
344
+ ```
345
+
346
+ ### Manage Existing Position TP/SL Orders
347
+
348
+ ```typescript
349
+ await sdk.placePositionTpSlOrders({
350
+ symbol: "BTC-PERP",
351
+ market: "<perpetual-id>",
352
+ side: OrderSide.SELL,
353
+ isLong: false,
354
+ 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..."],
374
+ });
375
+ ```
376
+
377
+ ### Market Data (Ticker & Order Book)
378
+
379
+ ```typescript
380
+ const ticker = await sdk.getTicker("BTC-PERP");
381
+ const orderBook = await sdk.getOrderBook("BTC-PERP");
382
+ ```
383
+
384
+ ### Cancel Order
385
+
386
+ Cancel one or more orders:
387
+
388
+ ```typescript
389
+ const result = await sdk.cancelOrder({
390
+ symbol: "BTC-PERP",
391
+ orderHashes: ["0x1234...", "0x5678..."], // Array of order hashes
392
+ });
393
+
394
+ if (result.status) {
395
+ console.log("Orders cancelled successfully");
396
+ } else {
397
+ console.error("Cancel failed:", result.error);
398
+ }
399
+ ```
400
+
401
+ ### Get Positions
402
+
403
+ Get current positions:
404
+
405
+ ```typescript
406
+ // Get all positions
407
+ 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
+ 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
+ ```
446
+
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
522
+
523
+ ```typescript
524
+ enum OrderSide {
525
+ BUY = "BUY",
526
+ SELL = "SELL",
527
+ }
528
+ ```
529
+
530
+ ### OrderType
531
+
532
+ ```typescript
533
+ enum OrderType {
534
+ MARKET = "MARKET",
535
+ LIMIT = "LIMIT",
536
+ }
537
+ ```
538
+
539
+ ### AccountInfo
540
+
541
+ ```typescript
542
+ interface AccountInfo {
543
+ walletBalance: string;
544
+ totalUnrealizedProfit: string;
545
+ accountValue: string;
546
+ freeCollateral: string;
547
+ totalMargin: string;
548
+ }
549
+ ```
550
+
551
+ ### Position
552
+
553
+ ```typescript
554
+ 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
564
+ }
565
+ ```
566
+
567
+ ### OpenOrder
568
+
569
+ ```typescript
570
+ 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
581
+ }
582
+ ```
583
+
584
+ ## Error Handling
585
+
586
+ All SDK methods return a `SDKResponse` object with the following structure:
587
+
588
+ ```typescript
589
+ interface SDKResponse<T> {
590
+ status: boolean; // Operation success status
591
+ data?: T; // Response data if successful
592
+ error?: string; // Error message if failed
593
+ }
594
+ ```
595
+
596
+ Always check the `status` field before accessing `data`:
597
+
598
+ ```typescript
599
+ const result = await sdk.placeOrder(/* ... */);
600
+
601
+ if (result.status) {
602
+ // Success - use result.data
603
+ console.log(result.data);
604
+ } else {
605
+ // Error - use result.error
606
+ console.error(result.error);
607
+ }
608
+ ```
609
+
610
+ ## Examples
611
+
612
+ ### Complete Trading Flow
613
+
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();
728
+ ```
729
+
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
+ ## License
735
+
736
+ Apache License 2.0