Skip to content

Commit 657c29e

Browse files
committed
v2.0.4
1 parent a512fb9 commit 657c29e

10 files changed

Lines changed: 1624 additions & 1 deletion

File tree

API_V3_MIGRATION.md

Lines changed: 350 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,350 @@
1+
# BingX Python SDK - API v3 Migration Guide
2+
3+
## Overview
4+
5+
This guide covers the migration from BingX API v1/v2 to v3. The good news: **your existing code still works**. All v3 features are opt-in additions.
6+
7+
## What's New in API v3
8+
9+
### 1. Enhanced Market Data
10+
11+
New endpoints for institutional-grade market analysis:
12+
13+
```python
14+
# Open Interest - track total open positions
15+
oi = client.market().get_open_interest("BTC-USDT")
16+
print(f"Open Interest: {oi['openInterest']}")
17+
18+
# Open Interest History
19+
oi_history = client.market().get_open_interest_history(
20+
symbol="BTC-USDT",
21+
period="5m", # 5m, 15m, 30m, 1h, 4h, 1d
22+
limit=100
23+
)
24+
25+
# Funding Rate Info
26+
funding = client.market().get_funding_rate_info("BTC-USDT")
27+
print(f"Current Rate: {funding['fundingRate']}")
28+
print(f"Next Payment: {funding['fundingTime']}")
29+
30+
# Book Ticker - best bid/ask without full depth
31+
ticker = client.market().get_book_ticker("BTC-USDT")
32+
print(f"Best Bid: {ticker['bidPrice']} @ {ticker['bidQty']}")
33+
print(f"Best Ask: {ticker['askPrice']} @ {ticker['askQty']}")
34+
35+
# Index Price
36+
index = client.market().get_index_price("BTC-USDT")
37+
print(f"Index: {index['indexPrice']}")
38+
```
39+
40+
### 2. Position Risk Monitoring
41+
42+
Real-time risk metrics to prevent liquidations:
43+
44+
```python
45+
# Get detailed position risk
46+
risk = client.account().get_position_risk("BTC-USDT")
47+
48+
print(f"Position Size: {risk['positionAmt']}")
49+
print(f"Entry Price: {risk['entryPrice']}")
50+
print(f"Mark Price: {risk['markPrice']}")
51+
print(f"Liquidation Price: {risk['liquidationPrice']}")
52+
print(f"Margin Ratio: {risk['marginRatio']}%")
53+
print(f"Unrealized P&L: {risk['unrealizedProfit']}")
54+
55+
# Monitor risk in real-time
56+
import time
57+
58+
while True:
59+
risk = client.account().get_position_risk("BTC-USDT")
60+
61+
if float(risk['marginRatio']) > 80:
62+
print(f"⚠️ WARNING: Margin at {risk['marginRatio']}%!")
63+
# Take action: add margin, close positions, etc.
64+
65+
time.sleep(60)
66+
```
67+
68+
### 3. Income & Commission Tracking
69+
70+
Track every dollar in and out:
71+
72+
```python
73+
# Get all income types
74+
income = client.account().get_income_history(
75+
symbol="BTC-USDT",
76+
limit=100
77+
)
78+
79+
# Filter by income type
80+
pnl = client.account().get_income_history(
81+
symbol="BTC-USDT",
82+
income_type="REALIZED_PNL" # Actual profits/losses
83+
)
84+
85+
funding = client.account().get_income_history(
86+
symbol="BTC-USDT",
87+
income_type="FUNDING_FEE" # 8-hour funding payments
88+
)
89+
90+
# Commission history
91+
fees = client.account().get_commission_history("BTC-USDT")
92+
93+
# Build P&L dashboard
94+
stats = {
95+
'total_pnl': 0,
96+
'total_fees': 0,
97+
'total_funding': 0,
98+
}
99+
100+
for record in income:
101+
if record['incomeType'] == 'REALIZED_PNL':
102+
stats['total_pnl'] += float(record['income'])
103+
elif record['incomeType'] == 'COMMISSION':
104+
stats['total_fees'] += float(record['income'])
105+
elif record['incomeType'] == 'FUNDING_FEE':
106+
stats['total_funding'] += float(record['income'])
107+
108+
print(f"Net P&L: {stats['total_pnl']}")
109+
print(f"Fees Paid: {stats['total_fees']}")
110+
print(f"Funding Received: {stats['total_funding']}")
111+
```
112+
113+
### 4. Multi-Assets Margin
114+
115+
Use your entire portfolio as collateral:
116+
117+
```python
118+
# Enable multi-assets margin mode
119+
client.trade().switch_multi_assets_mode(True)
120+
121+
# Check status
122+
mode = client.trade().get_multi_assets_mode()
123+
print(f"Multi-assets: {'ON' if mode['multiAssetsMargin'] else 'OFF'}")
124+
125+
# Get margin info
126+
margin = client.trade().get_multi_assets_margin()
127+
print(f"Total Collateral: {margin['totalCollateral']}")
128+
print(f"Total Margin Used: {margin['totalMargin']}")
129+
print(f"Available Margin: {margin['availableMargin']}")
130+
print(f"Margin Ratio: {margin['marginRatio']}%")
131+
132+
# Breakdown by asset
133+
for asset in margin['assets']:
134+
print(f"{asset['asset']}: Balance: {asset['walletBalance']}, "
135+
f"Collateral: {asset['crossMarginAsset']}")
136+
137+
# Get multi-assets rules (haircuts, supported assets)
138+
rules = client.trade().get_multi_assets_rules()
139+
140+
# Disable multi-assets mode
141+
client.trade().switch_multi_assets_mode(False)
142+
```
143+
144+
**⚠️ Warning**: In multi-assets mode, liquidation affects your entire portfolio, not just individual positions.
145+
146+
### 5. TWAP Orders (Time-Weighted Average Price)
147+
148+
Execute large orders without moving the market:
149+
150+
```python
151+
# Create TWAP buy order
152+
twap = client.twap().buy(
153+
symbol="BTC-USDT",
154+
quantity=10.0,
155+
duration=3600, # Execute over 1 hour (in seconds)
156+
position_side="LONG"
157+
)
158+
159+
print(f"TWAP Order ID: {twap['orderId']}")
160+
161+
# Monitor progress
162+
import time
163+
164+
while True:
165+
details = client.twap().get_order_detail(twap['orderId'])
166+
167+
if details['status'] == 'FILLED':
168+
print(f"Completed at avg price: {details['avgPrice']}")
169+
break
170+
171+
progress = (float(details['executedQty']) / float(details['totalQty'])) * 100
172+
print(f"Progress: {progress:.2f}%")
173+
174+
time.sleep(60)
175+
176+
# Create TWAP sell order
177+
twap_sell = client.twap().sell(
178+
symbol="BTC-USDT",
179+
quantity=5.0,
180+
duration=1800, # 30 minutes
181+
position_side="SHORT"
182+
)
183+
184+
# Get all open TWAP orders
185+
open_orders = client.twap().get_open_orders("BTC-USDT")
186+
187+
# Get TWAP order history
188+
history = client.twap().get_order_history(
189+
symbol="BTC-USDT",
190+
limit=50
191+
)
192+
193+
# Cancel TWAP order
194+
client.twap().cancel_order(twap['orderId'])
195+
```
196+
197+
### 6. Advanced Order Types
198+
199+
New order types for sophisticated trading:
200+
201+
```python
202+
# Trailing Stop Market Order
203+
trailing_stop = client.trade().create_order({
204+
"symbol": "BTC-USDT",
205+
"side": "SELL",
206+
"positionSide": "LONG",
207+
"type": "TRAILING_STOP_MARKET",
208+
"quantity": 1.0,
209+
"activationPrice": 50000, # Start trailing at $50k
210+
"callbackRate": 2.0 # Trail 2% behind peak
211+
})
212+
213+
# How it works:
214+
# 1. Price hits $50k → Start trailing
215+
# 2. Price climbs to $55k → Stop follows to $53.9k (2% behind)
216+
# 3. Price rockets to $60k → Stop moves to $58.8k
217+
# 4. Price drops to $58.8k → SOLD!
218+
219+
# Trigger Limit Order
220+
trigger_limit = client.trade().create_order({
221+
"symbol": "BTC-USDT",
222+
"side": "BUY",
223+
"positionSide": "LONG",
224+
"type": "TRIGGER_LIMIT",
225+
"quantity": 1.0,
226+
"stopPrice": 48000, # Trigger when price hits $48k
227+
"price": 48100 # Execute limit order at $48.1k
228+
})
229+
230+
# Trailing Take Profit / Stop Loss
231+
trailing_tp_sl = client.trade().create_order({
232+
"symbol": "BTC-USDT",
233+
"side": "SELL",
234+
"positionSide": "LONG",
235+
"type": "TRAILING_TP_SL",
236+
"quantity": 1.0,
237+
"takeProfitPrice": 55000,
238+
"stopLossPrice": 48000,
239+
"trailingStopPercent": 1.5
240+
})
241+
```
242+
243+
### 7. Auto-Add Margin
244+
245+
Automatic margin addition to prevent liquidation:
246+
247+
```python
248+
# Enable auto-add margin for LONG positions
249+
client.trade().set_auto_add_margin(
250+
symbol="BTC-USDT",
251+
position_side="LONG",
252+
enabled=True
253+
)
254+
255+
# Check status
256+
status = client.trade().get_auto_add_margin("BTC-USDT", "LONG")
257+
if status['autoAddMargin']:
258+
print("Auto-add margin is ON")
259+
260+
# Disable auto-add margin
261+
client.trade().set_auto_add_margin(
262+
symbol="BTC-USDT",
263+
position_side="LONG",
264+
enabled=False
265+
)
266+
```
267+
268+
**Note**: Only works in hedge mode. Uses your available balance.
269+
270+
### 8. One-Click Position Reversal
271+
272+
Atomically reverse your position:
273+
274+
```python
275+
# Currently LONG 1.0 BTC
276+
# This closes the long AND opens SHORT 1.0 BTC atomically
277+
client.trade().one_click_reverse_position("BTC-USDT")
278+
279+
# Now you're SHORT 1.0 BTC - no gap, no slippage
280+
```
281+
282+
Perfect for trend reversal strategies and "oh crap, I was wrong" moments.
283+
284+
## Backward Compatibility
285+
286+
**All your existing code continues to work.** No breaking changes.
287+
288+
```python
289+
# This still works exactly as before
290+
price = client.market().get_latest_price("BTC-USDT")
291+
balance = client.account().get_balance()
292+
293+
order = client.trade().create_order({
294+
"symbol": "BTC-USDT",
295+
"side": "BUY",
296+
"type": "MARKET",
297+
"quantity": 0.001
298+
})
299+
```
300+
301+
## Migration Checklist
302+
303+
- [ ] Update package: `pip install --upgrade bingx-python`
304+
- [ ] Test existing code (it should work unchanged)
305+
- [ ] Try position risk monitoring
306+
- [ ] Experiment with new order types on small positions
307+
- [ ] Test TWAP orders with minimal amounts
308+
- [ ] Consider multi-assets margin (only if experienced)
309+
- [ ] Update your bots with new features when ready
310+
311+
## Income Types Reference
312+
313+
| Income Type | Description |
314+
|-------------|-------------|
315+
| `REALIZED_PNL` | Actual profits/losses from closed trades |
316+
| `FUNDING_FEE` | 8-hour funding payments (can be positive or negative) |
317+
| `COMMISSION` | Trading fees paid to BingX |
318+
| `TRANSFER` | Money moving between accounts |
319+
| `INSURANCE_CLEAR` | Insurance fund settlements (rare) |
320+
321+
## Order Types Reference
322+
323+
| Order Type | Description | Use Case |
324+
|------------|-------------|----------|
325+
| `MARKET` | Execute immediately at market price | Quick entry/exit |
326+
| `LIMIT` | Execute at specific price or better | Price control |
327+
| `STOP` | Trigger market order at stop price | Stop-loss |
328+
| `STOP_LIMIT` | Trigger limit order at stop price | Stop-loss with price control |
329+
| `TRAILING_STOP_MARKET` | Stop that follows price | Lock in profits |
330+
| `TRIGGER_LIMIT` | Conditional limit order | Advanced entries |
331+
| `TRAILING_TP_SL` | Trailing take profit/stop loss | Advanced exits |
332+
333+
## Best Practices
334+
335+
1. **Start Small**: Test new features with minimal amounts
336+
2. **Monitor Risk**: Use position risk monitoring in production
337+
3. **Track Income**: Understand where your money goes
338+
4. **Use TWAP**: For orders > $10k to minimize slippage
339+
5. **Be Careful**: Multi-assets margin is powerful but risky
340+
341+
## Support
342+
343+
- **Documentation**: See README.md
344+
- **Examples**: Check examples/ directory
345+
- **Issues**: https://github.com/tigusigalpa/bingx-python/issues
346+
- **BingX API Docs**: https://bingx-api.github.io/docs-v3/
347+
348+
## License
349+
350+
MIT License - see LICENSE file for details.

0 commit comments

Comments
 (0)