Skip to content
Merged
Show file tree
Hide file tree
Changes from 129 commits
Commits
Show all changes
171 commits
Select commit Hold shift + click to select a range
b946518
chore(): bump axios, jest, ts-jest and typescript versions
tiagosiebler Jan 30, 2025
508dc39
chore(): bump axios, jest, ts-jest and typescript versions
tiagosiebler Jan 30, 2025
632bfed
chore(): remove unnecssary tsconfig src, update example
tiagosiebler Jan 30, 2025
dcc299b
feat(): upgrade WsStore to latest generation. Refactor DefaultLogger.…
tiagosiebler Jan 30, 2025
9b46c1a
Merge branch 'master' into wsapi
tiagosiebler Jan 30, 2025
7be6bf2
feat(): prepare wskey url map
tiagosiebler Feb 1, 2025
40614f7
Merge branch 'master' into wsapi
tiagosiebler Feb 14, 2025
6fc641a
feat(): improve event handling for multiplex public ws
tiagosiebler Feb 17, 2025
0d2c924
feat(): fix eventType extraction for new multiplex streams
tiagosiebler Feb 17, 2025
610900c
feat(): migrate subscribeTo util methods to new client. Fix ws endpoi…
tiagosiebler Feb 17, 2025
e657741
feat(): improve emittable preparation and handling, fix beautifier bu…
tiagosiebler Feb 17, 2025
722a0e1
feat(): rebrand old ws client, refactoring, fix plumbing workflows fo…
tiagosiebler Feb 18, 2025
bb3130f
feat(): refactor rest client cache out of ws client
tiagosiebler Feb 19, 2025
1af8dd5
feat(): complete user data workflows for spot markets
tiagosiebler Feb 20, 2025
3fa5145
Merge branch 'master' into wsapi
tiagosiebler Feb 20, 2025
88502d8
chore(): tidying in ws client
tiagosiebler Feb 20, 2025
92525d3
feat(): migrate subscribeTo methods for other existing user data streams
tiagosiebler Feb 20, 2025
a29225f
feat(): test and update futures and margin user data streams
tiagosiebler Feb 20, 2025
53d9431
feat(): workflow & stability improvements for stream heartbeats & rec…
tiagosiebler Feb 24, 2025
9362492
feat(): extract listen key management & handling into utility class
tiagosiebler Feb 27, 2025
ea6a63c
Merge branch 'master' into wsapi
tiagosiebler Feb 28, 2025
d4ea51c
feat(): integrate ed25519 auth, test wsapi workflows for spot & futur…
tiagosiebler Mar 12, 2025
730fcc2
chore(v3.0.0-beta.0): publish first beta
tiagosiebler Mar 12, 2025
fe08fa6
chore(): fix return type wrapper
tiagosiebler Mar 12, 2025
2036070
fix(): type resolver for ws order req
tiagosiebler Mar 12, 2025
0b78f2b
feat(): add ws api example
tiagosiebler Mar 13, 2025
2d873ac
chore(): add ed25519 example
tiagosiebler Mar 13, 2025
8eeafec
feat(): added Spot Market Types
JJ-Cro Mar 13, 2025
5f05323
feat(): added all spot wsapi operations except trading
JJ-Cro Mar 13, 2025
9e0b24d
feat(): finished spot trading wsapi types
JJ-Cro Mar 13, 2025
5cacd89
feat(): added futures market wsapi operatiosn
JJ-Cro Mar 13, 2025
33a5a89
feat(): added wsapi futures trading endpoints
JJ-Cro Mar 13, 2025
48bb8fe
feat(): finished usdm futures wsapi aditions
JJ-Cro Mar 13, 2025
47e3c58
feat(): removed apiKey, signature, made recvwindow and timestamp opti…
JJ-Cro Mar 14, 2025
0795c9d
Merge pull request #530 from JJ-Cro/wsapi-types
tiagosiebler Mar 14, 2025
66e7bfd
chore(): minor updates
tiagosiebler Mar 26, 2025
514372c
Merge branch 'master' into wsapi
tiagosiebler Mar 31, 2025
14cb4ca
chore(): add rest-like wrapper
tiagosiebler Mar 31, 2025
4939b2a
Merge branch 'master' into wsapi
tiagosiebler Mar 31, 2025
90ec5b5
feat(): flesh out wsapi client
tiagosiebler Apr 1, 2025
a4f8f25
feat(): improve rounding example, add rounding fns as export, improve…
tiagosiebler Apr 2, 2025
aaed088
chore(): remove unnecessary async
tiagosiebler Apr 2, 2025
9d8624a
feat(): add ws api client example
tiagosiebler Apr 2, 2025
f7a2ac6
feat(): add coinm ws api domains, tidying around testnet workflows, d…
tiagosiebler Apr 3, 2025
42983f3
chore(): expand wskey types
tiagosiebler Apr 3, 2025
3a7b276
fix(): handle potentially undefined param
tiagosiebler Apr 3, 2025
b679af1
feat(): added all spot and usdm wsapi endpoints
JJ-Cro Apr 2, 2025
1a3046a
feat(): added coinm, cleaned types and functions for wsapi.
JJ-Cro Apr 3, 2025
24c8b6d
fix(): moved back to interfaces from inline types
JJ-Cro Apr 3, 2025
62f7197
fix(): moved back to interfaces from inline types for wsapi
JJ-Cro Apr 3, 2025
27a8df2
chore(): updated import
JJ-Cro Apr 3, 2025
f7d71c9
Merge pull request #534 from JJ-Cro/WsApiEndpoints
tiagosiebler Apr 3, 2025
940d48e
feat(): fix testnet suffix handling for wsapi, update type resolution…
tiagosiebler Apr 7, 2025
d5d6461
chore(): linter fixes
tiagosiebler Apr 7, 2025
6281622
chore(): update ws api error handling
tiagosiebler Apr 7, 2025
7a6831b
feat(): enforce testnet wskey if useTestnet, add basic resub user dat…
tiagosiebler Apr 7, 2025
3e506d2
chore(): reduce noisy log, add minimal example
tiagosiebler Apr 7, 2025
06ccb62
chore(): cleaning & text fix
tiagosiebler Apr 7, 2025
db6d64d
chore(): fix repo url npm warning
tiagosiebler Apr 7, 2025
f061970
feat(): integrate new listen key workflow, integrate new user data st…
tiagosiebler Apr 8, 2025
bd167e4
chore(): remove keepalive plumbing for wsapi listen key
tiagosiebler Apr 10, 2025
01da34a
feat(): add user data utility method to close dedicated connection. c…
tiagosiebler Apr 10, 2025
a110cb5
feat(): finish testnet workflows for REST and WS
tiagosiebler Apr 10, 2025
60046ab
feat(): minimal response enrichment mechanism
tiagosiebler Apr 10, 2025
d3d4659
feat(): improve sign workflows & rsa detection. Use node crypto by de…
tiagosiebler Apr 11, 2025
9b388e6
feat(v3.0.0-beta.5): default to node crypto for sign, clean up sign w…
tiagosiebler Apr 11, 2025
26b13c1
chore(): add simple testnet examples
tiagosiebler Apr 17, 2025
dec6be2
feat(): readme updates
tiagosiebler Apr 17, 2025
3c69d3e
feat(): add missing futures ws book ticker properties
tiagosiebler Apr 21, 2025
2b926d8
feat(): add http keep alive support
tiagosiebler Apr 21, 2025
9f75933
chore(): simple rest example
tiagosiebler Apr 21, 2025
6601e81
chore(): remove deprecated endpoints with typos in function name
tiagosiebler Apr 21, 2025
9f95af6
feat(): disable heartbeats by default if ping/pong frames are not ava…
tiagosiebler Apr 21, 2025
914a86f
feat(): simple example on how to unsubscribe from ws topics
tiagosiebler Apr 21, 2025
68c829d
feat(): readme updates with new clients
tiagosiebler Apr 22, 2025
9f2d776
chore(): readme updates
tiagosiebler Apr 22, 2025
05bd08f
chore(): misc test fix
tiagosiebler Apr 22, 2025
63b22f7
chore(): prevent listen key conflict in tests
tiagosiebler Apr 22, 2025
f7a79ae
chore(): refine candles example
tiagosiebler Apr 22, 2025
c59e7ed
chore(): misc cleaning
tiagosiebler Apr 22, 2025
da26413
feat(): update examples, update testnet links, escape new lines for s…
tiagosiebler Apr 22, 2025
9bebf47
chore(): misc cleaning
tiagosiebler Apr 22, 2025
40233d4
feat(): breaking change, rename `useTestnet` to `testnet` for consist…
tiagosiebler Apr 22, 2025
f59ed00
feat(): add TOC
tiagosiebler Apr 22, 2025
97fef8d
feat(): updated examples, moved to separate directories
JJ-Cro Apr 22, 2025
daf67d3
chore(): accidental push
JJ-Cro Apr 22, 2025
997cd6b
chore(): wrong change
JJ-Cro Apr 22, 2025
bab2c0e
Merge pull request #539 from JJ-Cro/wsapiJerko2
tiagosiebler Apr 22, 2025
af61652
chore(): move examples
tiagosiebler Apr 22, 2025
a83fc1e
chore(): move examples
tiagosiebler Apr 22, 2025
b906f17
feat(): wsapi request/response type refactoring & consistency
tiagosiebler Apr 23, 2025
6a4a418
feat(): wsapi & user data docs
tiagosiebler Apr 23, 2025
69c020e
Merge branch 'master' into wsapi
tiagosiebler Apr 23, 2025
5fb152c
feat(): improve user data docs + example
tiagosiebler Apr 23, 2025
e853d3b
feat(v3.0.0-beta.6): publish beta release
tiagosiebler Apr 23, 2025
38c3982
feat(3.0.0-beta.7): enable custom sign fn for REST clients
tiagosiebler Apr 24, 2025
145dc74
feat(3.0.0-beta.8): fix custom sign hook, update examples
tiagosiebler Apr 24, 2025
3ffd3b9
Merge branch 'master' into wsapi
tiagosiebler Apr 24, 2025
a75ea69
feat(v3.0.0-beta.9): pull in changes from #541
tiagosiebler Apr 24, 2025
1046bb0
fix(): isWsPartialBookDepthEventFormatted type guard event recognition
tiagosiebler Apr 24, 2025
7b914df
feat(): wrap emit in error handler, emit array events as before, fix …
tiagosiebler Apr 24, 2025
ca95fa7
chore(): testing type guards
tiagosiebler Apr 24, 2025
848e2dd
chore(): disable test topic
tiagosiebler Apr 24, 2025
a8ccd5f
chore(): checked all ws public topics for type guards
JJ-Cro Apr 25, 2025
9f2b187
chore(): tidy example again
tiagosiebler Apr 25, 2025
9677208
Merge branch 'master' into wsapi
tiagosiebler Apr 28, 2025
2348669
Merge branch 'wsapi' into wsapiTypeGuards
tiagosiebler Apr 28, 2025
96be9c4
Merge pull request #544 from JJ-Cro/wsapiTypeGuards
tiagosiebler Apr 28, 2025
21fb8e4
fix(): type guards for new multiplex subs
tiagosiebler Apr 28, 2025
f531179
feat(): implement per ws command sign, handle timestamp offset from a…
tiagosiebler Apr 29, 2025
0813aa0
feat(): add amend keep priority wsapi, breaking change: rename amend/…
tiagosiebler Apr 29, 2025
877f09d
feat(): fix user data type guards for new workflows
tiagosiebler Apr 29, 2025
01fed1d
feat(): peg original request to resolved ws api response
tiagosiebler Apr 30, 2025
6df4624
Merge branch 'master' into wsapi
tiagosiebler Apr 30, 2025
f42e2b7
chore(): skip fussy test for deprecated listen key workflow
tiagosiebler Apr 30, 2025
f8641bc
feat(v3.0.0-beta.10): publish next beta with timestamp & type guard f…
tiagosiebler Apr 30, 2025
2582e00
chore(): clean example
tiagosiebler Apr 30, 2025
ff26b78
chore(): update readme
tiagosiebler May 1, 2025
505abb0
chore(): rename file
tiagosiebler May 1, 2025
04c2e78
chore(): rename readme
tiagosiebler May 1, 2025
0cbbae9
chore(): update user data readme
tiagosiebler May 1, 2025
369a46d
chore(): fix file case issue
tiagosiebler May 1, 2025
377107c
chore(): put readme back
tiagosiebler May 1, 2025
8ade34e
chore(): update example
tiagosiebler May 1, 2025
16a2d0a
chore(): update example, chore(): don't warn missing beautifier key b…
tiagosiebler May 1, 2025
25d9cdd
chore(): fix webpack config
tiagosiebler May 1, 2025
a48a5eb
chore(): minor fixes
tiagosiebler May 1, 2025
e037062
chore(): cleaning
tiagosiebler May 1, 2025
c416c92
chore(): improve example
tiagosiebler May 2, 2025
08e6cb3
chore(): use single quotes for env doc, chore(): comment out type gua…
tiagosiebler May 5, 2025
3ecccfa
fix(#551): resolve wsMarket with assumption on wsKey
tiagosiebler May 5, 2025
a012ab5
chore(): add link to binance docs
tiagosiebler May 6, 2025
4f8d01a
chore(): improve ws event parsing behaviour
tiagosiebler May 8, 2025
7afc2e5
feat(v3.0.0-beta.11): fix top-level parsing/handling/enrichment for i…
tiagosiebler May 9, 2025
e69fe25
chore(): fix test
tiagosiebler May 9, 2025
6ec5fa2
feat(): added all examples for ws-api client for every single functio…
JJ-Cro May 9, 2025
038138f
chore(): misc cleaning
tiagosiebler May 9, 2025
8940f52
chore(): clean comment
tiagosiebler May 9, 2025
14a5dc0
Merge branch 'wsapi' into wsapi_example
tiagosiebler May 9, 2025
75ce110
chore(): update generic
JJ-Cro May 9, 2025
b28e567
Merge branch 'wsapi_example' of https://github.com/JJ-Cro/binance int…
JJ-Cro May 9, 2025
128f574
Merge pull request #553 from JJ-Cro/wsapi_example
tiagosiebler May 9, 2025
68142be
feat(#554): add conditional order event to beautifier
tiagosiebler May 12, 2025
55b22e9
feat(#554): add liability change event to beautifier
tiagosiebler May 12, 2025
767c48f
feat(v3.0.0-beta.12): add missing beautifier events, misc cleaning
tiagosiebler May 12, 2025
fc8d822
chore(): update note on ws request sign. chore(): update sample link
tiagosiebler May 12, 2025
94a75ff
feat(): added apidoc examples and endpoint map to wsapi branch
JJ-Cro May 12, 2025
e1b089e
Merge pull request #556 from JJ-Cro/wsapi5
tiagosiebler May 12, 2025
e647d48
chore(): add clarification to listen key methods
tiagosiebler May 13, 2025
9201e8c
add WsMessageMarkPriceUpdateEventRaw
aweiu May 14, 2025
32f652d
Merge pull request #557 from aweiu/patch-1
tiagosiebler May 14, 2025
030e6a4
feat(v3.0.0-beta.13): add methods to unsubscribe user data streams (c…
tiagosiebler May 14, 2025
56ba6d7
fix(#558): remove invalid new spot order wsapi parameters
tiagosiebler May 15, 2025
76ddd6f
fix(#560): post-close handler should purge topic state after intentio…
tiagosiebler May 15, 2025
f3a0252
feat(v3.0.0-beta.14): fix ws api spot order type & post ws-close stat…
tiagosiebler May 15, 2025
92bcb94
fix(v3.0.0-beta.15): urlencode sign parameter to fix conflict with ed…
tiagosiebler May 15, 2025
c15a9c8
chore(): check/throw on missing credentials for wsapi auth
tiagosiebler May 19, 2025
7538f86
feat(v3.0.0-beta.16): add flag for public wsapi commands that do not …
tiagosiebler May 23, 2025
b14e3dc
feat(): marked all public futures WSAPI methods with optional auth
JJ-Cro May 29, 2025
97cfbd8
Merge pull request #561 from JJ-Cro/updateOptionalWSAPIFutures
tiagosiebler May 29, 2025
2a04ed2
Merge branch 'master' into wsapi
tiagosiebler Jun 2, 2025
eeb4274
feat(v3.0.0-beta.17): improve handling around non-authenticated ws ap…
tiagosiebler Jun 4, 2025
3f8b32e
Merge branch 'master' into wsapi
tiagosiebler Jun 5, 2025
27254b7
feat(v3.0.0): Introduce Binance WebSocket API, introduce multiplex We…
tiagosiebler Jun 20, 2025
da57d59
Merge branch 'master' into wsapi
tiagosiebler Jun 23, 2025
fdf1424
fix(): prevent the keep alive flag from completely overwriting an exi…
tiagosiebler Jun 24, 2025
438a3c5
feat(): add test to validate advanced https agent configuration isn't…
tiagosiebler Jun 24, 2025
64059ad
chore(): update test matcher
tiagosiebler Jun 24, 2025
a1d2dac
chore(): added endpoint map
JJ-Cro Jun 24, 2025
732c9ba
chore(): improve pinning test
tiagosiebler Jun 24, 2025
0ba48ee
Merge pull request #565 from JJ-Cro/wsapiFinalRegex
tiagosiebler Jun 24, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ module.exports = {
'array-bracket-spacing': ['error', 'never'],
'linebreak-style': ['error', 'unix'],
'lines-between-class-members': ['warn', 'always'],
allowObjectTypes: 0,
semi: ['error', 'always'],
'new-cap': 'off',
'no-console': 'off',
Expand Down
383 changes: 308 additions & 75 deletions README.md

Large diffs are not rendered by default.

88 changes: 80 additions & 8 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,95 @@
# Binance API - Examples

This folder contains ready to go examples demonstrating various aspects of this API implementation, written in typescript.
This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects).

Found something difficult to implement? Contribute to these examples and help others!

## Getting started

- Clone the project (or install the module in your own project `npm install binance`).
- Edit the sample as needed (some samples require edits, e.g APi keys or import statements).
- Execute the sample using ts-node: `ts-node examples/rest-spot-public.ts`.
- Clone the project (or download it as a zip, or install the module in your own project `npm install binance`).
- Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src).
- Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`.

Samples that API credentials using `process.env.APIKEY` can be spawned with environment variables. Unix/macOS example:
Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example:
```
APIKEY="apikeypastedhere" APISECRET="apisecretpastedhere" ts-node examples/ws-userdata.ts
APIKEY="apikeypastedhere" APISECRET="apisecretpastedhere" tsx examples/WebSockets/ws-userdata-listenkey.ts
```

Or edit the example directly to hardcode your API keys.

## REST USDM Examples
### WebSockets

All examples relating to WebSockets can be found in the [examples/WebSockets](./WebSockets/) folder. High level summary of available examples:

#### Consumers

These are purely for receiving data from Binance's WebSockets (market data, account updates, etc).

##### Market Data

These examples demonstrate subscribing to & receiving market data from Binance's WebSockets:

- ws-public.ts
- Demonstration on general usage of the WebSocket client to subscribe to / unsubscribe from one or more market data topics.
- ws-public-spot-orderbook.ts
- Subscribing to orderbook events for multiple symbols in spot markets.
- ws-public-spot-trades.ts
- Subscribing to raw trades for multiple symbols in spot markets.
- ws-unsubscribe.ts
- Subscribing to a list of topics, and then unsubscribing from a few topics in that list.
- ws-public-usdm-funding.ts
- Simple example subscribing to a general topic, and how to process incoming events to only extract funding rates from those events.

##### Account Data

These examples demonstrate receiving account update events from Binance's WebSockets:

- ws-userdata-listenkey.ts
- Demonstration on subscribing to various user data streams (spot, margin, futures),
- Handling incoming user data events
- Using provided type guards to determine which product group the user data event is for (spot, margin, futures, etc).
- ws-userdata-listenKey-testnet.ts
- Similar to above, but on testnet.
- ws-userdata-connection-safety.ts
- Demonstration on extra safety around the first user data stream connection.
- Note: this is overkill in most situations...

##### WebSocket API

These examples demonstrate how to send commands using Binance's WebSocket API (e.g. submitting orders). Very similar to the REST API, but using a persisted WebSocket connection instead of HTTP requests.

- ws-api-client.ts
- Demonstration of using Binance's WebSocket API in Node.js/JavaScript/TypeScript, using the WebsocketAPIClient.
- This WebsocketAPIClient is very similar to a REST client, with one method per available command (endpoint) and fully typed requests & responses.
- Routing is automatically handled via the WebsocketClient, including authentication and connection persistence. Just call the functions you need - the SDK does the rest.
- From a usage perspective, it feels like a REST API - you can await responses just like a HTTP request.
- ws-api-raw-promises.ts
- More verbose usage of the WebSocket API using the `sendWSAPIRequest()` method.
- The `WebsocketAPIClient` uses this method too, so in most cases it is simple to just use the `WebsocketAPIClient` instead.
- ws-userdata-wsapi.ts
- The listenKey workflow for the user data stream is deprecated (in spot markets).
- This example demonstrates how to subscribe to the user data stream in spot markets, without a listen key, using the WebSocket API.

##### Misc Workflows

These are miscellaneous examples that cover one or more of the above categories:

- ws-close.ts
- Closing the (old listen-key driven) user data stream.
- Unsubscribing from various topics.
- ws-proxy-socks.ts
- Using WebSockets over a SOCKS proxy.
- deprecated-ws-public.ts


### REST APIs

All examples relating to REST APIs can be found in the [examples/REST](./REST/) folder. Most examples are named around functionality & product group. Any examples with "private" involve API calls relating to your account (such as changing settings or submitting orders, etc),

High level summary for some of the available examples, but check the folder for a complete list:

#### REST USDM Examples

- `rest-future-bracket-order.ts` Creates three order, entry, TP, SL and submit them all at once using `submitMultipleOrders`
- `rest-usdm-order.ts` Creates single entry, using `submitNewOrder`
- `rest-usdm-order-sl.ts` Modify current Stop Loss order(HedgeMode only)
- `rest-usdm-order-sl.ts` Modify current Stop Loss order(HedgeMode only)
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { USDMClient, NewFuturesOrderParams } from '../src/index';
import { NewFuturesOrderParams, USDMClient } from '../../src/index';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new USDMClient({
api_key: key,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PortfolioClient } from '../src/index';
import { PortfolioClient } from '../../src/index';

// or
// import { PortfolioClient } from 'binance';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PortfolioClient } from '../src/index';
import { PortfolioClient } from '../../src/index';

// or
// import { PortfolioClient } from 'binance';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MainClient } from '../src/index';
import { MainClient } from '../../src/index';

// or
// import { MainClient } from 'binance';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MainClient } from '../src/index';
import { MainClient } from '../../src/index';

// or
// import { MainClient } from 'binance';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {
MainClient,
NewSpotOrderParams,
OrderResponseFull,
MainClient,
SymbolPrice,
} from '../src/index';
} from '../../src/index';

// or
// import { MainClient } from 'binance';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new MainClient({
api_key: key,
Expand Down Expand Up @@ -89,13 +89,13 @@ function trimToDecimalPlaces(number: number, precision: number): number {
newOrderRespType: 'FULL',
};

console.log(`Submitting buy order: `, buyOrderRequest);
console.log('Submitting buy order: ', buyOrderRequest);
await client.testNewOrder(buyOrderRequest);
const buyOrderResult = (await client.submitNewOrder(
buyOrderRequest,
)) as OrderResponseFull;
console.log(
`Order result: `,
'Order result: ',
JSON.stringify(
{ request: buyOrderRequest, response: buyOrderResult },
null,
Expand Down Expand Up @@ -126,14 +126,14 @@ function trimToDecimalPlaces(number: number, precision: number): number {
newOrderRespType: 'FULL',
};

console.log(`Submitting sell order: `, sellOrderRequest);
console.log('Submitting sell order: ', sellOrderRequest);
await client.testNewOrder(sellOrderRequest);
const sellOrderResult = (await client.submitNewOrder(
sellOrderRequest,
)) as OrderResponseFull;

console.log(
`Order result: `,
'Order result: ',
JSON.stringify(
{ request: sellOrderRequest, response: sellOrderResult },
null,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MainClient } from '../src/index';
import { MainClient } from '../../src/index';

// or
// import { MainClient } from 'binance';
Expand All @@ -19,16 +19,16 @@ const client = new MainClient({
// JSON.stringify(await client.getExchangeInfo(), null, 2),
// );

const oneTicker = await client.get24hrChangeStatististics({
const oneTicker = await client.get24hrChangeStatistics({
symbol: 'BTCUSDT',
});
console.log('getTickers', oneTicker);

const manyTickers = await client.get24hrChangeStatististics({
const manyTickers = await client.get24hrChangeStatistics({
symbols: ['BTCUSDT', 'ETHUSDT'],
});
console.log('getTickers many', manyTickers);
const allTickers = await client.get24hrChangeStatististics();
const allTickers = await client.get24hrChangeStatistics();
console.log('getTickers all', allTickers);
} catch (e) {
console.error('request failed: ', e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { USDMClient } from '../src/index';
/* eslint-disable @typescript-eslint/no-unused-vars */
import { USDMClient } from '../../src/index';

// or
// import { USDMClient } from 'binance';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new USDMClient({
api_secret: secret,
Expand All @@ -26,8 +27,8 @@ async function start() {
*/
const [
{ positionAmt: longAmount, ...long },
{ positionAmt: shortAmount, ...short }
]: any = await client.getPositions({ symbol });
{ positionAmt: shortAmount, ...short },
]: any = await client.getPositionsV3({ symbol });

// if longAmount is bigger than 0 means we have open long position and if shortAmount is below 0 means we have open short position
const hasLong = parseFloat(longAmount) > 0;
Expand All @@ -36,16 +37,17 @@ async function start() {

// if we have any open position then we continue
if (hasOpen) {

// we get ourstop loss here
const orders = await client.getAllOpenOrders({ symbol });
const stopOrders = orders.filter(({ type }) => type === 'STOP_MARKET') ?? {};
const stopOrders =
orders.filter(({ type }) => type === 'STOP_MARKET') ?? [];

// we want to modify our long position SL here
// we want to modify our long position SL here
if (hasLong) {

// we get the StopLoss order which is realted to long
const { orderId }: any = stopOrders.find(({ positionSide: ps }) => ps == 'LONG');
const { orderId }: any = stopOrders.find(
({ positionSide: ps }) => ps == 'LONG',
);

// if it exists, cancel it.
if (orderId) {
Expand All @@ -62,8 +64,8 @@ async function start() {
timeInForce: 'GTC',
type: 'STOP_MARKET',
closePosition: 'true', // this is here because we don't have the position quantity value, and it means closee all quantity
stopPrice: parseFloat((markPrice * .99).toFixed(3)), // set sl price 1% below current price
workingType: 'MARK_PRICE'
stopPrice: parseFloat((markPrice * 0.99).toFixed(3)), // set sl price 1% below current price
workingType: 'MARK_PRICE',
});
console.log('SL Modifiled sell result: ', result);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { USDMClient } from '../src/index';
import { USDMClient } from '../../src/index';

// or
// import { USDMClient } from 'binance';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new USDMClient({
api_secret: secret,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { USDMClient } from '../src/index';
import { USDMClient } from '../../src/index';
// import axios from 'axios';

// or
// import { USDMClient } from 'binance';

const key = process.env.APIKEY || 'APIKEY';
const secret = process.env.APISECRET || 'APISECRET';
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new USDMClient({
api_key: key,
Expand Down
15 changes: 15 additions & 0 deletions examples/REST/rest-usdm-public.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { USDMClient } from '../../src';

const client = new USDMClient({
testnet: true,
// keepAlive: true,
// ... any other params,
});

client
.getRecentTrades({
symbol: 'BTCUSDT',
limit: 2,
})
.then((r) => console.log('results: ', r))
.catch((e) => console.error('exception: ', e));
39 changes: 39 additions & 0 deletions examples/REST/rest-usdm-testnet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { USDMClient } from '../../src/index';

// or
// import { USDMClient } from 'binance';

const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';

const client = new USDMClient({
api_secret: secret,
api_key: key,
beautifyResponses: true,
/**
* Note: testnet is NOT a good place to test strategy performance.
*
* For more information and guidance, refer to:
* https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets
*/
testnet: true,
});

async function start() {
try {
// To open a short position - if you don't have a position yet, and your account is set to one-way mode, just place a sell order to open a short position
const result = await client.submitNewOrder({
side: 'SELL',
symbol: 'BTCUSDT',
type: 'MARKET',
quantity: 0.001,
// newOrderRespType: 'FULL',
});

console.log('market sell result: ', result);
} catch (e) {
console.error('market sell failed: ', e);
}
}

start();
Loading