0
# Margin Trading
1
2
Cross-margin and isolated margin trading with loan management, interest calculations, and margin-specific order types. Supports margin asset transfers and comprehensive margin account monitoring.
3
4
## Capabilities
5
6
### Margin Account Information
7
8
Get margin account details and trading capabilities.
9
10
```python { .api }
11
def get_margin_account(self, **params): ...
12
def get_isolated_margin_account(self, **params): ...
13
def get_margin_asset(self, **params): ...
14
def get_margin_symbol(self, **params): ...
15
def get_margin_all_assets(self, **params): ...
16
def get_margin_all_pairs(self, **params): ...
17
def get_isolated_margin_symbol(self, **params): ...
18
def get_isolated_margin_all_symbols(self, **params): ...
19
```
20
21
#### Usage Examples
22
23
```python
24
# Get cross margin account information
25
margin_account = client.get_margin_account()
26
27
print(f"Total asset of BTC: {margin_account['totalAssetOfBtc']}")
28
print(f"Total liability of BTC: {margin_account['totalLiabilityOfBtc']}")
29
print(f"Total net asset of BTC: {margin_account['totalNetAssetOfBtc']}")
30
print(f"Margin level: {margin_account['marginLevel']}")
31
print(f"Index price: {margin_account['indexPrice']}")
32
33
# Check specific asset balances
34
for balance in margin_account['userAssets']:
35
if float(balance['netAsset']) != 0:
36
print(f"{balance['asset']}: Free={balance['free']}, Locked={balance['locked']}, Borrowed={balance['borrowed']}, Interest={balance['interest']}")
37
38
# Get isolated margin account info
39
isolated_account = client.get_isolated_margin_account()
40
41
for asset in isolated_account['assets']:
42
if asset['symbol'] in ['BTCUSDT', 'ETHUSDT']: # Check specific symbols
43
base_asset = asset['baseAsset']
44
quote_asset = asset['quoteAsset']
45
46
print(f"Symbol: {asset['symbol']}")
47
print(f"Isolated: {asset['isolated']}")
48
print(f"Margin level: {asset['marginLevel']}")
49
print(f"Margin ratio: {asset['marginRatio']}")
50
print(f"Index price: {asset['indexPrice']}")
51
print(f"Liquidate price: {asset['liquidatePrice']}")
52
53
print(f"Base asset ({base_asset['asset']}): Free={base_asset['free']}, Locked={base_asset['locked']}, Borrowed={base_asset['borrowed']}")
54
print(f"Quote asset ({quote_asset['asset']}): Free={quote_asset['free']}, Locked={quote_asset['locked']}, Borrowed={quote_asset['borrowed']}")
55
56
# Get margin asset information
57
btc_margin_asset = client.get_margin_asset(asset='BTC')
58
print(f"BTC borrowable: {btc_margin_asset['isBorrowable']}")
59
print(f"BTC mortgageable: {btc_margin_asset['isMortgageable']}")
60
61
# Get margin trading pair information
62
btcusdt_margin = client.get_margin_symbol(symbol='BTCUSDT')
63
print(f"BTCUSDT margin trading: {btcusdt_margin['isMarginTrade']}")
64
print(f"Is buy allowed: {btcusdt_margin['isBuyAllowed']}")
65
print(f"Is sell allowed: {btcusdt_margin['isSellAllowed']}")
66
```
67
68
### Margin Trading Orders
69
70
Place and manage margin trading orders.
71
72
```python { .api }
73
def create_margin_order(self, **params): ...
74
def cancel_margin_order(self, **params): ...
75
def get_margin_order(self, **params): ...
76
def get_open_margin_orders(self, **params): ...
77
def get_all_margin_orders(self, **params): ...
78
def get_margin_trades(self, **params): ...
79
```
80
81
#### Usage Examples
82
83
```python
84
# Place margin buy order (borrows automatically if needed)
85
margin_buy = client.create_margin_order(
86
symbol='BTCUSDT',
87
side='BUY',
88
type='MARKET',
89
quantity=0.001,
90
isIsolated='FALSE' # Cross margin
91
)
92
93
# Place isolated margin order
94
isolated_order = client.create_margin_order(
95
symbol='BTCUSDT',
96
side='BUY',
97
type='LIMIT',
98
timeInForce='GTC',
99
quantity=0.001,
100
price='45000',
101
isIsolated='TRUE' # Isolated margin
102
)
103
104
# Place margin sell order
105
margin_sell = client.create_margin_order(
106
symbol='BTCUSDT',
107
side='SELL',
108
type='LIMIT',
109
timeInForce='GTC',
110
quantity=0.001,
111
price='55000'
112
)
113
114
# Get margin order status
115
margin_order = client.get_margin_order(
116
symbol='BTCUSDT',
117
orderId=12345678,
118
isIsolated='FALSE'
119
)
120
121
# Get all open margin orders
122
open_orders = client.get_open_margin_orders(symbol='BTCUSDT')
123
124
# Get margin trading history
125
margin_trades = client.get_margin_trades(symbol='BTCUSDT', limit=100)
126
127
for trade in margin_trades:
128
print(f"Trade ID: {trade['id']}")
129
print(f"Price: {trade['price']}, Qty: {trade['qty']}")
130
print(f"Commission: {trade['commission']} {trade['commissionAsset']}")
131
print(f"Is isolated: {trade['isIsolated']}")
132
```
133
134
### Loan Management
135
136
Borrow and repay assets for margin trading.
137
138
```python { .api }
139
def create_margin_loan(self, **params): ...
140
def repay_margin_loan(self, **params): ...
141
def get_margin_loan_details(self, **params): ...
142
def get_margin_repay_details(self, **params): ...
143
def get_margin_interest_history(self, **params): ...
144
def get_margin_force_liquidation_record(self, **params): ...
145
```
146
147
#### Usage Examples
148
149
```python
150
# Borrow USDT for cross margin
151
loan_result = client.create_margin_loan(
152
asset='USDT',
153
amount=1000,
154
isIsolated='FALSE' # Cross margin
155
)
156
print(f"Loan transaction ID: {loan_result['tranId']}")
157
158
# Borrow for isolated margin
159
isolated_loan = client.create_margin_loan(
160
asset='USDT',
161
amount=500,
162
symbol='BTCUSDT', # Required for isolated margin
163
isIsolated='TRUE'
164
)
165
166
# Repay loan
167
repay_result = client.repay_margin_loan(
168
asset='USDT',
169
amount=100,
170
isIsolated='FALSE'
171
)
172
173
# Repay isolated margin loan
174
isolated_repay = client.repay_margin_loan(
175
asset='USDT',
176
amount=50,
177
symbol='BTCUSDT',
178
isIsolated='TRUE'
179
)
180
181
# Get loan details
182
loan_details = client.get_margin_loan_details(
183
asset='USDT',
184
isolatedSymbol='BTCUSDT', # Optional, for isolated margin
185
limit=100
186
)
187
188
for loan in loan_details['rows']:
189
print(f"Loan ID: {loan['txId']}")
190
print(f"Amount: {loan['principal']} {loan['asset']}")
191
print(f"Timestamp: {loan['timestamp']}")
192
print(f"Status: {loan['status']}") # PENDING, CONFIRMED, FAILED
193
194
# Get repayment history
195
repay_details = client.get_margin_repay_details(
196
asset='USDT',
197
limit=100
198
)
199
200
# Get interest history
201
interest_history = client.get_margin_interest_history(
202
asset='USDT',
203
limit=100
204
)
205
206
for interest in interest_history['rows']:
207
print(f"Interest: {interest['interest']} {interest['asset']}")
208
print(f"Interest rate: {interest['interestRate']}")
209
print(f"Type: {interest['type']}") # PERIODIC (daily), ON_BORROW
210
print(f"Time: {interest['interestAccuredTime']}")
211
212
# Get liquidation records
213
liquidation_records = client.get_margin_force_liquidation_record(limit=100)
214
```
215
216
### Margin Transfers
217
218
Transfer assets between spot and margin accounts.
219
220
```python { .api }
221
def margin_stream_get_listen_key(self): ...
222
def margin_stream_keepalive(self, **params): ...
223
def margin_stream_close(self, **params): ...
224
def transfer_spot_to_margin(self, **params): ...
225
def transfer_margin_to_spot(self, **params): ...
226
def transfer_isolated_margin_to_spot(self, **params): ...
227
def transfer_spot_to_isolated_margin(self, **params): ...
228
```
229
230
#### Usage Examples
231
232
```python
233
# Transfer from spot to cross margin
234
spot_to_margin = client.transfer_spot_to_margin(
235
asset='USDT',
236
amount=100
237
)
238
239
# Transfer from cross margin to spot
240
margin_to_spot = client.transfer_margin_to_spot(
241
asset='USDT',
242
amount=50
243
)
244
245
# Transfer from spot to isolated margin
246
spot_to_isolated = client.transfer_spot_to_isolated_margin(
247
asset='USDT',
248
symbol='BTCUSDT',
249
amount=200
250
)
251
252
# Transfer from isolated margin to spot
253
isolated_to_spot = client.transfer_isolated_margin_to_spot(
254
asset='USDT',
255
symbol='BTCUSDT',
256
amount=100
257
)
258
```
259
260
### Margin Account Calculations
261
262
Calculate maximum borrowable amounts and transferable quantities.
263
264
```python { .api }
265
def get_max_margin_loan(self, **params): ...
266
def get_max_margin_transfer(self, **params): ...
267
def get_margin_price_index(self, **params): ...
268
def get_margin_fee(self, **params): ...
269
def get_isolated_margin_fee(self, **params): ...
270
```
271
272
#### Usage Examples
273
274
```python
275
# Get maximum borrowable amount
276
max_borrow = client.get_max_margin_loan(
277
asset='USDT',
278
isolatedSymbol='BTCUSDT' # Optional, for isolated margin
279
)
280
print(f"Max borrowable USDT: {max_borrow['amount']}")
281
282
# Get maximum transferable amount
283
max_transfer = client.get_max_margin_transfer(
284
asset='USDT',
285
isolatedSymbol='BTCUSDT' # Optional
286
)
287
print(f"Max transferable USDT: {max_transfer['amount']}")
288
289
# Get margin price index
290
price_index = client.get_margin_price_index(symbol='BTCUSDT')
291
print(f"BTCUSDT price index: {price_index['price']}")
292
293
# Get margin trading fees
294
margin_fee = client.get_margin_fee()
295
for fee in margin_fee:
296
print(f"VIP level {fee['vipLevel']}: Maker={fee['makerCommission']}, Taker={fee['takerCommission']}")
297
298
# Get isolated margin trading fees
299
isolated_fee = client.get_isolated_margin_fee(symbol='BTCUSDT')
300
print(f"BTCUSDT isolated margin fees: Maker={isolated_fee['makerCommission']}, Taker={isolated_fee['takerCommission']}")
301
```
302
303
### Cross Margin vs Isolated Margin
304
305
#### Cross Margin
306
- Shares margin across all positions
307
- Lower risk of liquidation
308
- Requires `isIsolated='FALSE'` or omit parameter
309
- No symbol parameter needed for loans/transfers
310
311
```python
312
# Cross margin examples
313
cross_account = client.get_margin_account()
314
cross_loan = client.create_margin_loan(asset='USDT', amount=1000)
315
cross_order = client.create_margin_order(
316
symbol='BTCUSDT',
317
side='BUY',
318
type='MARKET',
319
quantity=0.001
320
)
321
```
322
323
#### Isolated Margin
324
- Margin isolated per trading pair
325
- Higher risk but limited losses
326
- Requires `isIsolated='TRUE'` and symbol for most operations
327
- Independent risk management per pair
328
329
```python
330
# Isolated margin examples
331
isolated_account = client.get_isolated_margin_account()
332
isolated_loan = client.create_margin_loan(
333
asset='USDT',
334
amount=500,
335
symbol='BTCUSDT',
336
isIsolated='TRUE'
337
)
338
isolated_order = client.create_margin_order(
339
symbol='BTCUSDT',
340
side='BUY',
341
type='MARKET',
342
quantity=0.001,
343
isIsolated='TRUE'
344
)
345
```
346
347
### Margin Risk Management
348
349
Monitor margin levels and liquidation risks.
350
351
```python { .api }
352
def get_margin_dribblet(self, **params): ...
353
def margin_dust_log(self, **params): ...
354
def get_cross_margin_collateral_ratio(self, **params): ...
355
def get_margin_interest_rate_history(self, **params): ...
356
```
357
358
#### Usage Examples
359
360
```python
361
# Monitor margin levels
362
margin_account = client.get_margin_account()
363
margin_level = float(margin_account['marginLevel'])
364
365
if margin_level < 1.3:
366
print("WARNING: Margin level is low, risk of liquidation!")
367
print(f"Current margin level: {margin_level}")
368
print("Consider adding more collateral or reducing positions")
369
370
# Get interest rate history
371
interest_rates = client.get_margin_interest_rate_history(
372
asset='USDT',
373
vipLevel=0,
374
limit=100
375
)
376
377
for rate in interest_rates:
378
print(f"Date: {rate['timestamp']}")
379
print(f"Daily interest rate: {rate['dailyInterestRate']}")
380
381
# Get collateral ratio information
382
collateral_ratio = client.get_cross_margin_collateral_ratio()
383
for ratio in collateral_ratio:
384
print(f"Collaterals: {ratio['collaterals']}")
385
print(f"Asset names: {ratio['assetNames']}")
386
```
387
388
### Small Balance Exchange (Margin Dust)
389
390
Convert small margin balances to BNB.
391
392
```python { .api }
393
def get_margin_dribblet(self, **params): ...
394
def margin_dust_log(self, **params): ...
395
```
396
397
#### Usage Examples
398
399
```python
400
# Get margin dust assets
401
margin_dust = client.get_margin_dribblet()
402
print(f"Total transferable BTC: {margin_dust['totalTransferBtc']}")
403
404
for detail in margin_dust['details']:
405
print(f"Asset: {detail['asset']}")
406
print(f"Amount: {detail['amount']}")
407
print(f"From BNB: {detail['fromBNB']}")
408
print(f"To BNB: {detail['toBNB']}")
409
410
# Get margin dust conversion history
411
dust_log = client.margin_dust_log()
412
for entry in dust_log['userAssetDribblets']:
413
print(f"Conversion time: {entry['operateTime']}")
414
print(f"Total transferred: {entry['totalTransferedAmount']} BNB")
415
print(f"Total service charge: {entry['totalServiceChargeAmount']} BNB")
416
```
417
418
This comprehensive margin trading functionality provides complete control over both cross-margin and isolated margin trading with advanced loan management, risk monitoring, and account optimization features.