Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
9db02f4
binanceusdm integration skeleton
coccoinomane May 6, 2025
aa7a015
feat: tool getBalance
coccoinomane May 6, 2025
9069c7c
fix: made it clear that balance is futures balance, not spot
coccoinomane May 6, 2025
7051cd6
feat: reimplemented tool getCurrencyMarkets for USDM
coccoinomane May 6, 2025
f577dcd
feat: reimplemented tool getMarketInfo for USDM
coccoinomane May 6, 2025
12ae82c
feat: adapted tool getOrderByIdAndMarket for USDM
coccoinomane May 6, 2025
421ae4a
feat: tool transferFunds
coccoinomane May 6, 2025
d29f69e
fix: implement MAX_MARKETS_IN_RESULTS mechanism to save tokens
coccoinomane May 7, 2025
cfbae47
fix: implemented MAX_ORDERS_IN_RESULTS mechanism to save tokens
coccoinomane May 7, 2025
fe985a1
feat: position fetching tools
coccoinomane May 7, 2025
d9b43b3
feat: first attempt at showing risky positions
coccoinomane May 9, 2025
b0ee0dd
fix: transformed errors in messages in list functions
coccoinomane May 9, 2025
f6523ad
feat: cancel order actions
coccoinomane May 9, 2025
6b06953
fix: show whether order will close position
coccoinomane May 9, 2025
273230a
fix: minor display bug
coccoinomane May 9, 2025
d4173b1
ux: add size limit for max leverage in market info
coccoinomane May 9, 2025
d1573c2
fix: remove marginRatio as CCXT margin computation is unclear
coccoinomane May 9, 2025
75bc40c
ux: allow market inference from partial symbols for cancel tools
coccoinomane May 9, 2025
55abb2d
ux: improve order output (use long/short)
coccoinomane May 10, 2025
54fd5a6
docs: explain leverage and margin in binance
coccoinomane May 12, 2025
71aa9b4
feat: create simple order
coccoinomane May 12, 2025
cff5865
feat: tool getUserLeverageAndMarginModeOnMarket
coccoinomane May 12, 2025
843fe8c
refac: minor change order of arguments
coccoinomane May 12, 2025
ebb690d
feat: tool setLeverage
coccoinomane May 12, 2025
cec49d3
refac: try/catch all tools
coccoinomane May 12, 2025
1d28037
feat: tool setMarginMode
coccoinomane May 12, 2025
1867648
feat: tool closePosition
coccoinomane May 12, 2025
c49dad1
ux: reduceOnly when closing position
coccoinomane May 12, 2025
9b68485
feat: createTriggerOrder.ts tool
coccoinomane May 12, 2025
25142fc
fix: error whereby agent tried to use deepseek API key
coccoinomane May 13, 2025
b6aad18
fix: now correctly showing filled percent
coccoinomane May 13, 2025
e51bb21
feat: reduce only support for TP/SL orders
coccoinomane May 13, 2025
5c8fc2c
feat: tool createTrailingStopOrder
coccoinomane May 15, 2025
3402234
feat: tools to add and reduce margin
coccoinomane May 15, 2025
5324301
ux: show same margin metric as in Binance UI
coccoinomane May 15, 2025
9f2ab61
ux: improved delivery contracts support
coccoinomane May 16, 2025
c492a77
feat: support margin based order creation
coccoinomane Jun 9, 2025
c3fcc6c
fix: type in closePosition(s)
coccoinomane Jun 16, 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
19 changes: 19 additions & 0 deletions projects/binanceusdm/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Variables for running askBinance.ts

# OpenAI API Key
OPENAI_API_KEY=

# DeepSeek API Key. If set, will be used instead of OpenAI.
DEEPSEEK_API_KEY=

# Binance API key and secret key
# Get your key in Account > API Management
# You need to restrict the API with IP
BINANCEUSDM_API_KEY=
BINANCEUSDM_SECRET_KEY=

# Testnet configuration
# Get your key here: https://testnet.binancefuture.com/
BINANCEUSDM_USE_TESTNET=false
BINANCEUSDM_TESTNET_API_KEY=
BINANCEUSDM_TESTNET_SECRET_KEY=
4 changes: 4 additions & 0 deletions projects/binanceusdm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.vscode
.env
dist
6 changes: 6 additions & 0 deletions projects/binanceusdm/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4,
"printWidth": 180
}
177 changes: 177 additions & 0 deletions projects/binanceusdm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Binance USDM Futures Trading

Integration between HeyAnon.ai and Binance USDM Futures trading, supporting both perpetuals and delivery futures.

## Common Tasks

### Markets

- Show all BTC future markets on @binanceusdm
- Show last price and volume of BTC/USDT on @binanceusdm
- Show max leverage for BTC/USDT on @binanceusdm

### Info on positions and balances

- Show all my positions on @binanceusdm
- Show my BTC/USDT position on @binanceusdm
- Show all of my BTC positions on @binanceusdm
- Show all of my delivery positions on @binanceusdm

### Info on open orders

- Show all my open orders on @binanceusdm
- Show my BTC open orders on @binanceusdm
- Show details on order 232168017 on @binanceusdm
- Show my balance on @binanceusdm

### Transfer funds between accounts

- Transfer 5,000 USDT to my futures account on @binanceusdm
- Transfer all my USDT from my futures account to my spot account on @binanceusdm

### Market & limit orders

- Long 1 BTC with USDT on @binanceusdm
- Long 1 BTC with USDT with isolated margin on @binanceusdm
- 100x long 1 BTC with USDT on @binanceusdm
- Long 1 BTC at limit price of 40,000 USDT on @binanceusdm
- Short BTC with limit price of 150,000 USDT on @binanceusdm
- 30x long BTC with a margin of 10 USDT on @binanceusdm

By default, the agent assumes you want to trade on perpetual markets. To use a delivery market instead, ask for it:

- Long 1 BTC with USDT on the June 2025 delivery market
- Long 1 BTC on USDT:USDT-250926

**IMPORTANT:** If you specify a leverage (5x, 10x, etc) or a margin mode (cross, isolated) for your order, the specified leverage and margin mode will be applied to the whole position, and not just to the amount you are adding/removing. This is because on Binance the leverage and margin mode are applied at the market level, and not at the order level. For more details, see the [Leverage and margin mode](#changing-leverage-and-margin-mode) section.

### Leverage and margin

- Show my margin on BTC/USDT on @binanceusdm
- What is my leverage on BTC/USDT on @binanceusdm?
- Set 50x leverage on BTC/USDT on @binanceusdm
- Set isolated margin mode on BTC/USDT on @binanceusdm
- Set cross margin mode on BTC/USDT on @binanceusdm
- Add 100 USDT margin to my BTC/USDT position on @binanceusdm
- Remove 200 USDT margin from my BTC/USDT position on @binanceusdm

Please note that the margin shown by the tools is the same shown in the Binance UI. For cross positions, that is the initial margin, while for isolated positions it is the actual margin set aside by the user for the position.

**IMPORTANT**: If you change leverage and margin mode of a pair, your existing position in that pair will be affected. See the [Leverage and margin mode](#changing-leverage-and-margin-mode) section for more details.

### Conditional orders

- Long 1 BTC on @binanceusdm when the price crosses 50,000 USDT
- Long 1 BTC at 45,000 USDT on @binanceusdm when the price crosses 50,000 USDT

### Stop Loss & Take Profit

- Add a 10% TP and a 15% SL to my existing BTC/USDT position
- 20x long 1 BTC with USDT, then place a stop loss at 15% and three take profit targets at 10%-20%-30%
- Short 1 BTC with USDT, then place an order to close the position at 10% profit on @binanceusdm
- Long 1 BTC with USDT, then place a 10% take profit and 15% stop loss on @binanceusdm

When it is clear from context that the TP and SL orders are attached to a position, they will be issued as **reduce-only** orders, to prevent accidentally increase the position size or open a new position. To force a reduce only order, just ask for it, e.g.

- Long 1 BTC on @binanceusdm when the price crosses 50,000 USDT, _reduce only_

### Trailing stop orders

- Place an order to long 1 BTC with USDT with a 0.5% trailing stop
- Place a reduce-only order to long 1 BTC with USDT with a 0.5% trailing stop
- Place an order to long 1 BTC with USDT with a 0.5% trailing stop, with activation at 95,000 USDT
- Place an order to short 1 BTC with USDT with a 8% trailing stop
- Place a reduce-only order to short 1 BTC with USDT with a 8% trailing stop
- Place an order to short 1 BTC with USDT with a 8% trailing stop, with activation at 130,000 USDT

Please note that:

1. The trailing percent must be a number between 0.1% and 10%.
2. The trailing stop order will be triggered as a market order once the price moves by the specified percentage in the desired direction.
3. Contrary to spot, on futures you cannot specify whether the trailing stop order is SL or TP.

### Close positions

- Close my BTC/USDT position on @binanceusdm
- Close all my positions on @binanceusdm
- Close all of my BTC positions on @binanceusdm

### Cancel orders

- Cancel all my orders on @binanceusdm
- Cancel all my orders on BTC/USDT on @binanceusdm
- Cancel order 232168017 on @binanceusdm

## Changing leverage and margin mode

When you create a position without specifying the leverage or the margin mode, the position will be created with whatever is the current configuration for the market.

Changing a market's leverage will affect your existing position in that market. Regardless of whether the position is isolated or cross margin, the act of increasing the leverage will have the following effects:

- will free up margin
- will NOT affect the liquidation price of existing positions, unless you use the freed margin to open new positions or withdraw from the futures account
- will NOT affect your present or future profits on the existing position, because the position size is not affected

Decreasing the market's leverage, instead, will have the following effects:

- will increase the margin needed to keep the position open
- if the margin needed is greater than the margin available, you won't be able to decrease the leverage
- IS NOT ALLOWED if you have an isolated position on the market, because Binance requires you to manually add margin to isolated positions
- will NOT change the liquidation price of existing positions, because liquidation price in cross-margin positions (the only ones for which you can decrease the leverage) only depends on position size and total margin in the account
- will NOT affect your present or future profits on the existing position, because the position size is not affected

Things are simpler when it comes to **changing the margin mode**: Binance does not allow you to change the margin mode of a market if you have an open position in that market.

## CCXT

We use the [CCXT](https://github.com/ccxt/ccxt/) library to interact with the various Binance Futures APIs. Some of Binance's features are not supported by CCXT; for these cases, we implemented some helper functions to cover the gaps, that you can find in the [exchange.ts](./src/helpers/exchange.ts) file.

## Test with the askBinance agent

I've built a simple agent called `askBinance` to test the integration. To run it, you need to configure .env:

```bash
cd projects/binanceusdm
pnpm install
cp .env.example .env
# insert OpenAI key into .env
# insert Binance Futures API credentials into .env
# optionally insert Binance Futures API testnet credentials into .env
# you can take testnet credentials from https://testnet.binancefuture.com
```

and then you can ask questions directly:

```bash
pnpm ask-binance "Show me the price of BTC/USDT:USDT"
```

To show all the requests and responses to the LLM, run `askBinance` with `--debug-llm` flag:

```bash
pnpm ask-binance "Show me the price of BTC/USDT:USDT" --debug-llm
```

## Binance specific behaviors

- Binance Futures trailing stop orders always execute as market orders when triggered, that is, you cannot set a limit price for the order. This is different from spot where you can specify a limit price for trailing stop orders. This is accounted for via the constant `SUPPORTS_LIMIT_PRICE_FOR_TRAILING_STOP_ORDERS`.
- Binance fAPI does not support OTOCO orders, that is, the creation in one go of position + TP + SL. Therefore, we send 3 separate orders ([link](https://dev.binance.vision/t/how-to-implement-otoco-tp-sl-orders-using-api/1622/14)).
- CCXT does not support `fetchPosition` for Binance future and perpetual markets, see workaround in `getUserOpenPositionBySymbol`
- Binance fAPI does not support `closePosition`, see workaround in `closePositionBySendingOppositeMarketOrder`
- In Binance it seems the settle currency is always the same as the quote currency. When implementing other exchanges, if this is not the case, we should consider reviewing the `completeMarketSymbol` function.

## Reference

- [Binance future types of orders](https://www.binance.com/en/support/faq/detail/360033779452)
- [Binance fAPI docs](https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info)
- [Binance fAPI orders](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api)
- [Binance Futures FAQ](https://www.binance.com/en/blog/futures/10-most-frequently-asked-questions-about-binance-futures-421499824684903916)
- [Binance max leverage table](https://www.binance.com/en/futures/trading-rules/perpetual/leverage-margin)
- [Binance FAQ on delivery futures](https://www.binance.com/en/square/post/43566)
- [CCXT leverage tiers](https://docs.ccxt.com/#/README?id=leverage-tiers)
- [CCXT Order structure](https://docs.ccxt.com/#/?id=order-structure)
- [CCXT Querying orders](https://docs.ccxt.com/#/README?id=querying-orders)
- [CCXT Placing orders](https://docs.ccxt.com/#/README?id=placing-orders)
- [CCXT Conditional/trigger orders](https://docs.ccxt.com/#/README?id=conditional-orders)
- [CCXT Binance createOrder](https://docs.ccxt.com/#/exchanges/binance?id=createorder)
- [Isolated margin order](https://discord.com/channels/690203284119617602/690203284727660739/1119234330775007262)
17 changes: 17 additions & 0 deletions projects/binanceusdm/TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
## Bug fixes

## Features

## Minor

- Test transferFunds function on mainnet (testnet does not have spot account)

## Future

- Include trailing percent in the order formatting function
- Allow to get market funding rates
- Support for hedged positions (2 positions on the same market, one long, one short)
- Open orders pagination
- Open positions pagination
- Show margin ratio in position output, and allow to show positions at risk of liquidation
- Include position information in order output (e.g. size, PnL if order executes, etc)
49 changes: 49 additions & 0 deletions projects/binanceusdm/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"name": "@heyanon/project-binanceusdm",
"version": "1.0.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"module": "dist/index.mjs",
"files": [
"dist"
],
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"start": "tsup --watch",
"build": "tsup",
"test": "vitest --run",
"lint": "tsdx lint",
"prepare": "pnpm run build",
"size": "size-limit",
"analyze": "size-limit --why",
"format": "prettier --write \"*/**/*.ts\"",
"ask-binance": "tsup src/ask_binance/run.ts > /dev/null && node dist/run.js"
},
"devDependencies": {
"@size-limit/preset-small-lib": "^9.0.0",
"@types/big.js": "^6.2.0",
"@types/jest": "^29.5.12",
"@types/node": "^22.13.4",
"chalk": "4",
"commander": "^12.1.0",
"dotenv": "^16.4.7",
"openai": "^4.80.0",
"prettier": "^3.4.2",
"tsdx": "^0.14.1",
"tslib": "^2.6.2",
"tsup": "^7.2.0",
"typescript": "^5.7.3"
},
"dependencies": {
"@heyanon/sdk": "^2.1.13",
"ccxt": "^4.4.77",
"vitest": "^2.1.8"
},
"description": "Binance USDM Futures Trading integration for HeyAnon"
}
Loading