or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdearn-products.mdindex.mdlending.mdmargin-trading.mdmarket-data.mdspot-trading.mdwebsocket.md

margin-trading.mddocs/

0

# Margin Trading

1

2

Cross and isolated margin trading operations with borrowing, repayment, and position management. Provides access to margin accounts, lending market, and risk management features for leveraged trading.

3

4

## Capabilities

5

6

### Margin Account Management

7

8

Access and manage margin account information.

9

10

```python { .api }

11

def get_margin_account():

12

"""

13

Get margin account information.

14

15

Returns:

16

dict: Margin account details with balances and risk metrics

17

"""

18

19

def query_margin_accounts():

20

"""

21

Query margin account details.

22

23

Returns:

24

dict: Comprehensive margin account information

25

"""

26

27

def get_cross_isolated_margin_account():

28

"""

29

Get cross and isolated margin account information.

30

31

Returns:

32

dict: Combined margin account details

33

"""

34

35

def get_isolated_margin_account(symbol: str):

36

"""

37

Get isolated margin account for specific symbol.

38

39

Args:

40

symbol (str): Trading symbol (e.g., 'BTC-USDT')

41

42

Returns:

43

dict: Isolated margin account details

44

"""

45

46

def get_isolated_margin_accounts():

47

"""

48

Get all isolated margin accounts.

49

50

Returns:

51

list: All isolated margin account information

52

"""

53

```

54

55

### Isolated Margin Account Operations

56

57

Create and manage isolated margin accounts.

58

59

```python { .api }

60

def create_isolated_margin_account(symbol: str):

61

"""

62

Create isolated margin account for a symbol.

63

64

Args:

65

symbol (str): Trading symbol

66

67

Returns:

68

dict: Created account information

69

"""

70

71

def delete_isolated_margin_account(symbol: str):

72

"""

73

Delete isolated margin account.

74

75

Args:

76

symbol (str): Trading symbol

77

78

Returns:

79

dict: Deletion confirmation

80

"""

81

```

82

83

### Borrowing Operations

84

85

Borrow funds for margin trading.

86

87

```python { .api }

88

def post_borrow_order(currency: str, size: str, maxRate: str = '', term: str = ''):

89

"""

90

Place a borrow order.

91

92

Args:

93

currency (str): Currency to borrow

94

size (str): Borrow amount

95

maxRate (str, optional): Maximum interest rate

96

term (str, optional): Borrow term

97

98

Returns:

99

dict: Borrow order information

100

"""

101

102

def get_borrow_order(orderId: str):

103

"""

104

Query borrow order details.

105

106

Args:

107

orderId (str): Borrow order ID

108

109

Returns:

110

dict: Borrow order status and details

111

"""

112

113

def get_repay_record(currency: str):

114

"""

115

Get repayment record for currency.

116

117

Args:

118

currency (str): Currency code

119

120

Returns:

121

list: Repayment history

122

"""

123

124

def get_repayment_record(currency: str, **kwargs):

125

"""

126

Get detailed repayment records.

127

128

Args:

129

currency (str): Currency code

130

currentPage (int, optional): Page number

131

pageSize (int, optional): Page size

132

133

Returns:

134

dict: Paginated repayment records

135

"""

136

```

137

138

### Repayment Operations

139

140

Repay borrowed funds.

141

142

```python { .api }

143

def post_repay_all(currency: str, sequence: str, size: str):

144

"""

145

Repay all borrowed funds for a currency.

146

147

Args:

148

currency (str): Currency to repay

149

sequence (str): Repayment sequence

150

size (str): Repayment amount

151

152

Returns:

153

dict: Repayment confirmation

154

"""

155

156

def post_repay_single(currency: str, tradeId: str, size: str):

157

"""

158

Repay a single borrow order.

159

160

Args:

161

currency (str): Currency to repay

162

tradeId (str): Trade ID to repay

163

size (str): Repayment amount

164

165

Returns:

166

dict: Repayment confirmation

167

"""

168

```

169

170

### Lending Operations

171

172

Lend funds to earn interest.

173

174

```python { .api }

175

def post_lend_order(currency: str, size: str, dailyIntRate: str, term: int):

176

"""

177

Place a lending order.

178

179

Args:

180

currency (str): Currency to lend

181

size (str): Lending amount

182

dailyIntRate (str): Daily interest rate

183

term (int): Lending term in days

184

185

Returns:

186

dict: Lending order information

187

"""

188

189

def cancel_lend_order(orderId: str):

190

"""

191

Cancel a lending order.

192

193

Args:

194

orderId (str): Lending order ID

195

196

Returns:

197

dict: Cancellation confirmation

198

"""

199

200

def set_auto_lend(currency: str, isEnable: bool, retainSize: str, dailyIntRate: str, term: int):

201

"""

202

Set auto-lending configuration.

203

204

Args:

205

currency (str): Currency for auto-lending

206

isEnable (bool): Enable/disable auto-lending

207

retainSize (str): Amount to retain (not lend)

208

dailyIntRate (str): Daily interest rate

209

term (int): Lending term in days

210

211

Returns:

212

dict: Auto-lending configuration

213

"""

214

```

215

216

### Lending History

217

218

Access lending and borrowing history.

219

220

```python { .api }

221

def get_active_order(currency: str, **kwargs):

222

"""

223

Get active lending orders.

224

225

Args:

226

currency (str): Currency code

227

currentPage (int, optional): Page number

228

pageSize (int, optional): Page size

229

230

Returns:

231

dict: Active lending orders

232

"""

233

234

def get_lent_history(currency: str, **kwargs):

235

"""

236

Get lending history.

237

238

Args:

239

currency (str): Currency code

240

currentPage (int, optional): Page number

241

pageSize (int, optional): Page size

242

243

Returns:

244

dict: Lending transaction history

245

"""

246

247

def get_active_lent_history(currency: str, **kwargs):

248

"""

249

Get active lending history.

250

251

Args:

252

currency (str): Currency code

253

currentPage (int, optional): Page number

254

pageSize (int, optional): Page size

255

256

Returns:

257

dict: Active lending positions

258

"""

259

260

def get_settled_lent_history(currency: str, **kwargs):

261

"""

262

Get settled lending history.

263

264

Args:

265

currency (str): Currency code

266

currentPage (int, optional): Page number

267

pageSize (int, optional): Page size

268

269

Returns:

270

dict: Settled lending transactions

271

"""

272

273

def get_account_lend_record(currency: str, **kwargs):

274

"""

275

Get account lending record.

276

277

Args:

278

currency (str): Currency code

279

currentPage (int, optional): Page number

280

pageSize (int, optional): Page size

281

282

Returns:

283

dict: Account lending records

284

"""

285

```

286

287

### Market Information

288

289

Access margin trading market data.

290

291

```python { .api }

292

def get_market_interestRate(currency: str):

293

"""

294

Get market interest rates for a currency.

295

296

Args:

297

currency (str): Currency code

298

299

Returns:

300

list: Market interest rate information

301

"""

302

303

def get_lend_record(currency: str):

304

"""

305

Get lending record for market analysis.

306

307

Args:

308

currency (str): Currency code

309

310

Returns:

311

list: Market lending records

312

"""

313

314

def get_margin_currencies():

315

"""

316

Get currencies available for margin trading.

317

318

Returns:

319

dict: Margin-enabled currencies with parameters

320

"""

321

322

def get_isolated_margin_symbols():

323

"""

324

Get symbols available for isolated margin trading.

325

326

Returns:

327

dict: Isolated margin trading pairs

328

"""

329

```

330

331

### Risk Management

332

333

Risk limits and ETF information.

334

335

```python { .api }

336

def get_risk_limit(marginModel: str):

337

"""

338

Get risk limits for margin model.

339

340

Args:

341

marginModel (str): Margin model type

342

343

Returns:

344

list: Risk limit information

345

"""

346

347

def get_etf_info():

348

"""

349

Get ETF information for margin trading.

350

351

Returns:

352

dict: ETF details and parameters

353

"""

354

```

355

356

### Margin Orders

357

358

Place margin trading orders (inherits from TradeData).

359

360

```python { .api }

361

def create_limit_margin_order(symbol: str, side: str, size: str, price: str, clientOid: str = '', **kwargs):

362

"""

363

Place a margin limit order.

364

365

Args:

366

symbol (str): Trading symbol

367

side (str): Order side ('buy' or 'sell')

368

size (str): Order size

369

price (str): Order price

370

clientOid (str, optional): Client order ID

371

**kwargs: Additional margin order parameters

372

373

Returns:

374

dict: Margin order response with borrow information

375

"""

376

377

def create_market_margin_order(symbol: str, side: str, clientOid: str = '', **kwargs):

378

"""

379

Place a margin market order.

380

381

Args:

382

symbol (str): Trading symbol

383

side (str): Order side

384

clientOid (str, optional): Client order ID

385

size (str, optional): Order size (for sell orders)

386

funds (str, optional): Order funds (for buy orders)

387

**kwargs: Additional parameters

388

389

Returns:

390

dict: Margin order response with borrow information

391

"""

392

393

def place_margin_order_test(symbol: str, side: str, type: str, clientOid: str = '', **kwargs):

394

"""

395

Test margin order placement.

396

397

Args:

398

symbol (str): Trading symbol

399

side (str): Order side

400

type (str): Order type

401

clientOid (str, optional): Client order ID

402

**kwargs: Additional parameters

403

404

Returns:

405

dict: Test order response

406

"""

407

```

408

409

## Usage Examples

410

411

### Basic Margin Trading

412

413

```python

414

from kucoin.client import Margin, Trade

415

416

# Initialize margin client

417

margin = Margin(api_key, api_secret, api_passphrase, is_sandbox=False)

418

trade = Trade(api_key, api_secret, api_passphrase, is_sandbox=False)

419

420

# Check margin account

421

account = margin.get_margin_account()

422

print(f"Margin level: {account.get('marginLevel')}")

423

print(f"Total liability: {account.get('totalLiabilityOfQuoteCurrency')}")

424

425

# Borrow USDT for trading

426

borrow_order = margin.post_borrow_order(

427

currency='USDT',

428

size='1000',

429

maxRate='0.001' # 0.1% daily rate

430

)

431

print(f"Borrow order: {borrow_order}")

432

```

433

434

### Isolated Margin Trading

435

436

```python

437

# Create isolated margin account for BTC-USDT

438

isolated_account = margin.create_isolated_margin_account('BTC-USDT')

439

print(f"Created isolated account: {isolated_account}")

440

441

# Get isolated margin account details

442

account_details = margin.get_isolated_margin_account('BTC-USDT')

443

print(f"Available balance: {account_details}")

444

445

# Place margin order for isolated account

446

margin_order = trade.create_limit_margin_order(

447

symbol='BTC-USDT',

448

side='buy',

449

size='0.001',

450

price='30000',

451

marginModel='isolated' # Specify isolated margin

452

)

453

print(f"Margin order: {margin_order}")

454

```

455

456

### Lending Operations

457

458

```python

459

# Place a lending order to earn interest

460

lend_order = margin.post_lend_order(

461

currency='USDT',

462

size='1000',

463

dailyIntRate='0.0001', # 0.01% daily

464

term=7 # 7 days

465

)

466

print(f"Lending order: {lend_order}")

467

468

# Set up auto-lending

469

auto_lend = margin.set_auto_lend(

470

currency='USDT',

471

isEnable=True,

472

retainSize='100', # Keep 100 USDT unlent

473

dailyIntRate='0.0001',

474

term=7

475

)

476

print(f"Auto-lending configured: {auto_lend}")

477

478

# Check active lending orders

479

active_orders = margin.get_active_order('USDT')

480

for order in active_orders['items']:

481

print(f"Lending: {order['size']} USDT at {order['dailyIntRate']} daily rate")

482

```

483

484

### Repayment Operations

485

486

```python

487

# Get repayment records

488

repay_records = margin.get_repayment_record('USDT')

489

total_owed = sum(float(record['principal']) for record in repay_records['items'])

490

print(f"Total owed: {total_owed} USDT")

491

492

# Repay all outstanding for a currency

493

if total_owed > 0:

494

repay_result = margin.post_repay_all(

495

currency='USDT',

496

sequence='RECENTLY_EXPIRE_FIRST',

497

size=str(total_owed)

498

)

499

print(f"Repayment completed: {repay_result}")

500

```

501

502

### Risk Monitoring

503

504

```python

505

# Check margin currencies and their parameters

506

margin_currencies = margin.get_margin_currencies()

507

for currency_info in margin_currencies['data']:

508

print(f"{currency_info['currency']}: Max leverage {currency_info['maxLeverage']}")

509

510

# Monitor risk limits

511

risk_limits = margin.get_risk_limit('cross')

512

for limit in risk_limits:

513

print(f"Risk level {limit['level']}: Max borrowable {limit['maxBorrowableAmount']}")

514

515

# Check market interest rates

516

interest_rates = margin.get_market_interestRate('USDT')

517

for rate in interest_rates:

518

print(f"Term {rate['term']} days: {rate['dailyIntRate']} daily rate")

519

```

520

521

## Types

522

523

```python { .api }

524

MarginAccountInfo = dict

525

# {

526

# "debtRatio": str, # Debt ratio

527

# "totalDebtOfBaseCurrency": str, # Total debt in base currency

528

# "totalLiabilityOfQuoteCurrency": str, # Total liability in quote currency

529

# "marginLevel": str, # Margin level

530

# "totalAssetOfQuoteCurrency": str, # Total assets in quote currency

531

# "accounts": list # Account details

532

# }

533

534

BorrowOrderInfo = dict

535

# {

536

# "orderId": str, # Borrow order ID

537

# "currency": str, # Borrowed currency

538

# "size": str, # Borrow amount

539

# "filled": str, # Filled amount

540

# "matchList": list, # Match details

541

# "status": str # Order status

542

# }

543

544

LendOrderInfo = dict

545

# {

546

# "orderId": str, # Lending order ID

547

# "currency": str, # Lending currency

548

# "size": str, # Lending amount

549

# "filledSize": str, # Filled amount

550

# "dailyIntRate": str, # Daily interest rate

551

# "term": int, # Lending term in days

552

# "createdAt": int # Creation timestamp

553

# }

554

555

RepaymentRecord = dict

556

# {

557

# "tradeId": str, # Trade ID

558

# "currency": str, # Currency

559

# "principal": str, # Principal amount

560

# "interest": str, # Interest amount

561

# "createdAt": int, # Creation time

562

# "repaidSize": str, # Repaid amount

563

# "dailyIntRate": str, # Daily interest rate

564

# "term": int # Term in days

565

# }

566

567

IsolatedMarginAccountInfo = dict

568

# {

569

# "totalConversionBalance": str, # Total conversion balance

570

# "liabilityConversionBalance": str, # Liability conversion balance

571

# "assets": list, # Asset details

572

# "symbol": str, # Trading symbol

573

# "isolatedMarginLevel": str, # Isolated margin level

574

# "debtRatio": str, # Debt ratio

575

# "status": str # Account status

576

# }

577

578

MarginOrderResponse = dict

579

# {

580

# "orderId": str, # Order ID

581

# "borrowSize": float, # Borrowed size for the order

582

# "loanApplyId": str # Loan application ID (if applicable)

583

# }

584

```