or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-python-binance

Unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs with comprehensive trading, market data, and account management functionality

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-binance@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-python-binance@1.0.0

0

# Python-Binance

1

2

An unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs. This library provides comprehensive access to Binance's trading, market data, wallet, and account management endpoints through both synchronous and asynchronous implementations with built-in authentication, error handling, and connection management.

3

4

## Package Information

5

6

- **Package Name**: python-binance

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install python-binance`

10

- **Documentation**: https://python-binance.readthedocs.io/en/latest/

11

- **License**: MIT

12

13

## Core Imports

14

15

```python

16

from binance import Client, AsyncClient

17

```

18

19

For WebSocket streaming:

20

21

```python

22

from binance import BinanceSocketManager, ThreadedWebsocketManager

23

```

24

25

For depth caching:

26

27

```python

28

from binance import DepthCacheManager, ThreadedDepthCacheManager

29

```

30

31

For constants and enums:

32

33

```python

34

from binance import * # Imports all constants, enums, and exceptions

35

```

36

37

## Basic Usage

38

39

### Synchronous REST API Client

40

41

```python

42

from binance import Client

43

44

# Initialize client with API credentials

45

client = Client(api_key='your_api_key', api_secret='your_api_secret')

46

47

# Get account information

48

account = client.get_account()

49

print(f"Account balances: {account['balances']}")

50

51

# Get current market price

52

ticker = client.get_symbol_ticker(symbol="BTCUSDT")

53

print(f"BTC price: {ticker['price']}")

54

55

# Place a test order (no actual trade)

56

order = client.create_test_order(

57

symbol='BTCUSDT',

58

side='BUY',

59

type='MARKET',

60

quantity=0.001

61

)

62

63

# Get recent trades

64

trades = client.get_recent_trades(symbol='BTCUSDT', limit=10)

65

```

66

67

### Asynchronous REST API Client

68

69

```python

70

import asyncio

71

from binance import AsyncClient

72

73

async def main():

74

# Initialize async client

75

client = await AsyncClient.create(api_key='your_api_key', api_secret='your_api_secret')

76

77

# Get market data

78

tickers = await client.get_all_tickers()

79

print(f"Total symbols: {len(tickers)}")

80

81

# Close the client

82

await client.close_connection()

83

84

# Run async function

85

asyncio.run(main())

86

```

87

88

### WebSocket Streaming

89

90

```python

91

import asyncio

92

from binance import AsyncClient, BinanceSocketManager

93

94

async def handle_socket_message(msg):

95

print(f"Received: {msg}")

96

97

async def main():

98

client = await AsyncClient.create()

99

bm = BinanceSocketManager(client)

100

101

# Start kline (candlestick) stream

102

ts = bm.kline_socket(symbol='BTCUSDT', interval='1m')

103

104

async with ts as tscm:

105

while True:

106

res = await tscm.recv()

107

await handle_socket_message(res)

108

109

asyncio.run(main())

110

```

111

112

## Architecture

113

114

Python-binance follows a layered architecture:

115

116

- **BaseClient**: Foundation class with shared constants, authentication, and HTTP request handling

117

- **Client/AsyncClient**: REST API implementations (sync vs async) inheriting core functionality

118

- **WebSocket Managers**: Real-time streaming with connection management and reconnection logic

119

- **Depth Cache System**: Efficient order book management with automatic synchronization

120

- **Authentication Layer**: Support for API keys, RSA/EDDSA private keys, and signature generation

121

- **Exception Hierarchy**: Comprehensive error handling for API, network, and trading-specific errors

122

123

The library supports all Binance API endpoints across spot, margin, futures, and options trading, with consistent interfaces and automatic timestamp management.

124

125

## Capabilities

126

127

### REST API Clients

128

129

Core synchronous and asynchronous REST API clients for interacting with all Binance endpoints. Provides 760+ methods covering spot trading, futures, margin, options, and account management with built-in authentication and error handling.

130

131

```python { .api }

132

class Client:

133

def __init__(

134

self,

135

api_key: Optional[str] = None,

136

api_secret: Optional[str] = None,

137

requests_params: Optional[Dict[str, Any]] = None,

138

tld: str = "com",

139

base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,

140

testnet: bool = False,

141

private_key: Optional[Union[str, Path]] = None,

142

private_key_pass: Optional[str] = None,

143

ping: Optional[bool] = True,

144

time_unit: Optional[str] = None,

145

): ...

146

147

class AsyncClient:

148

def __init__(

149

self,

150

api_key: Optional[str] = None,

151

api_secret: Optional[str] = None,

152

requests_params: Optional[Dict[str, Any]] = None,

153

tld: str = "com",

154

base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,

155

testnet: bool = False,

156

loop=None,

157

session_params: Optional[Dict[str, Any]] = None,

158

private_key: Optional[Union[str, Path]] = None,

159

private_key_pass: Optional[str] = None,

160

https_proxy: Optional[str] = None,

161

time_unit: Optional[str] = None,

162

): ...

163

```

164

165

[REST API Clients](./rest-clients.md)

166

167

### Market Data

168

169

Comprehensive market data access including tickers, order books, trade history, klines/candlesticks, and price statistics. Supports both spot and derivatives markets with real-time and historical data retrieval.

170

171

```python { .api }

172

def get_exchange_info(self) -> Dict: ...

173

def get_all_tickers(self) -> List[Dict[str, str]]: ...

174

def get_order_book(self, **params) -> Dict: ...

175

def get_recent_trades(self, **params) -> Dict: ...

176

def get_klines(self, **params) -> Dict: ...

177

def get_historical_klines(

178

self,

179

symbol: str,

180

interval: str,

181

start_str: str,

182

end_str: Optional[str] = None,

183

limit: int = 1000,

184

klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,

185

) -> List[List]: ...

186

```

187

188

[Market Data](./market-data.md)

189

190

### Trading Operations

191

192

Complete trading functionality including order placement, management, and execution across spot, margin, futures, and options markets. Supports all order types with comprehensive status tracking and modification capabilities.

193

194

```python { .api }

195

def create_order(self, **params): ...

196

def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): ...

197

def order_market(self, **params): ...

198

def create_oco_order(self, **params): ...

199

def get_order(self, **params): ...

200

def cancel_order(self, **params): ...

201

def get_open_orders(self, **params): ...

202

```

203

204

[Trading Operations](./trading.md)

205

206

### Account Management

207

208

Account information, balance management, trade history, and API permissions. Includes wallet operations, asset transfers, and comprehensive account status monitoring.

209

210

```python { .api }

211

def get_account(self, **params): ...

212

def get_asset_balance(self, asset=None, **params): ...

213

def get_my_trades(self, **params): ...

214

def get_account_status(self, version=1, **params): ...

215

def get_account_api_trading_status(self, **params): ...

216

def get_account_api_permissions(self, **params): ...

217

```

218

219

[Account Management](./account.md)

220

221

### WebSocket Streaming

222

223

Real-time market data and account update streaming with automatic connection management, reconnection logic, and message queuing. Supports all Binance WebSocket streams including user data, market data, and futures streams.

224

225

```python { .api }

226

class BinanceSocketManager:

227

def __init__(

228

self,

229

client: AsyncClient,

230

user_timeout=KEEPALIVE_TIMEOUT,

231

max_queue_size: int = 100,

232

): ...

233

234

def symbol_ticker_socket(self, symbol: str): ...

235

def all_ticker_socket(self): ...

236

def kline_socket(self, symbol: str, interval: str): ...

237

def depth_socket(self, symbol: str, depth: Optional[str] = None): ...

238

def user_socket(self): ...

239

240

class ThreadedWebsocketManager:

241

def start(self): ...

242

def stop(self): ...

243

def start_symbol_ticker_socket(self, callback, symbol: str): ...

244

def start_kline_socket(self, callback, symbol: str, interval: str): ...

245

```

246

247

[WebSocket Streaming](./websockets.md)

248

249

### Depth Caching

250

251

Efficient real-time order book management with automatic synchronization from WebSocket streams. Provides sorted bid/ask access and maintains consistent order book state with configurable precision and conversion types.

252

253

```python { .api }

254

class DepthCacheManager:

255

def __init__(

256

self,

257

client: AsyncClient,

258

symbol: str,

259

refresh_interval: Optional[int] = None,

260

bm: Optional[BinanceSocketManager] = None,

261

limit: int = 500,

262

conv_type: Callable = float

263

): ...

264

265

class DepthCache:

266

def __init__(self, symbol, conv_type: Callable = float): ...

267

def add_bid(self, bid): ...

268

def add_ask(self, ask): ...

269

def get_bids(self): ...

270

def get_asks(self): ...

271

def get_top_bids(self, k: int): ...

272

def get_top_asks(self, k: int): ...

273

```

274

275

[Depth Caching](./depth-cache.md)

276

277

### Futures Trading

278

279

Complete futures trading functionality for both USD-margined and coin-margined futures. Includes position management, leverage control, funding rate information, and specialized futures order types.

280

281

```python { .api }

282

def futures_get_exchange_info(self): ...

283

def futures_create_order(self, **params): ...

284

def futures_account(self, **params): ...

285

def futures_account_balance(self, **params): ...

286

def futures_position_information(self, **params): ...

287

def futures_change_leverage(self, **params): ...

288

def futures_change_margin_type(self, **params): ...

289

```

290

291

[Futures Trading](./futures.md)

292

293

### Margin Trading

294

295

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.

296

297

```python { .api }

298

def get_margin_account(self, **params): ...

299

def get_isolated_margin_account(self, **params): ...

300

def create_margin_order(self, **params): ...

301

def create_margin_loan(self, **params): ...

302

def repay_margin_loan(self, **params): ...

303

def get_margin_interest_history(self, **params): ...

304

```

305

306

[Margin Trading](./margin.md)

307

308

### Convert API

309

310

Asset conversion functionality for instant and limit conversions between cryptocurrencies. Provides quote-based conversions, limit order conversions, and comprehensive conversion history tracking across spot, margin, and futures accounts.

311

312

```python { .api }

313

def convert_request_quote(self, **params): ...

314

def convert_accept_quote(self, **params): ...

315

def get_convert_trade_history(self, **params): ...

316

def margin_v1_get_convert_exchange_info(self, **params): ...

317

def margin_v1_post_convert_limit_place_order(self, **params): ...

318

def futures_v1_post_convert_get_quote(self, **params): ...

319

```

320

321

[Convert API](./convert-api.md)

322

323

### Staking and Mining

324

325

Comprehensive staking and mining functionality including DeFi staking, ETH/SOL staking, locked staking products, and mining operations. Provides access to staking rewards, mining statistics, and portfolio management across various blockchain networks.

326

327

```python { .api }

328

def get_staking_product_list(self, **params): ...

329

def purchase_staking_product(self, **params): ...

330

def redeem_staking_product(self, **params): ...

331

def get_staking_position(self, **params): ...

332

def margin_v2_post_eth_staking_eth_stake(self, **params): ...

333

def margin_v1_post_sol_staking_sol_stake(self, **params): ...

334

```

335

336

[Staking and Mining](./staking-mining.md)

337

338

## Constants and Enums

339

340

```python { .api }

341

# Order Types

342

ORDER_TYPE_LIMIT = "LIMIT"

343

ORDER_TYPE_MARKET = "MARKET"

344

ORDER_TYPE_STOP_LOSS = "STOP_LOSS"

345

ORDER_TYPE_STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT"

346

ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT"

347

ORDER_TYPE_TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT"

348

ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER"

349

350

# Futures Order Types

351

FUTURE_ORDER_TYPE_LIMIT = "LIMIT"

352

FUTURE_ORDER_TYPE_MARKET = "MARKET"

353

FUTURE_ORDER_TYPE_STOP = "STOP"

354

FUTURE_ORDER_TYPE_STOP_MARKET = "STOP_MARKET"

355

FUTURE_ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT"

356

FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET"

357

FUTURE_ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER"

358

FUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = "TRAILING_STOP_MARKET"

359

360

# Time in Force

361

TIME_IN_FORCE_GTC = "GTC" # Good till cancelled

362

TIME_IN_FORCE_IOC = "IOC" # Immediate or cancel

363

TIME_IN_FORCE_FOK = "FOK" # Fill or kill

364

TIME_IN_FORCE_GTX = "GTX" # Post only order

365

TIME_IN_FORCE_GTD = "GTD" # Good till date

366

367

# Order Sides

368

SIDE_BUY = "BUY"

369

SIDE_SELL = "SELL"

370

371

# Order Status

372

ORDER_STATUS_NEW = "NEW"

373

ORDER_STATUS_PARTIALLY_FILLED = "PARTIALLY_FILLED"

374

ORDER_STATUS_FILLED = "FILLED"

375

ORDER_STATUS_CANCELED = "CANCELED"

376

ORDER_STATUS_PENDING_CANCEL = "PENDING_CANCEL"

377

ORDER_STATUS_REJECTED = "REJECTED"

378

ORDER_STATUS_EXPIRED = "EXPIRED"

379

380

# Order Response Types

381

ORDER_RESP_TYPE_ACK = "ACK"

382

ORDER_RESP_TYPE_RESULT = "RESULT"

383

ORDER_RESP_TYPE_FULL = "FULL"

384

385

# Side Effect Types

386

NO_SIDE_EFFECT_TYPE = "NO_SIDE_EFFECT"

387

MARGIN_BUY_TYPE = "MARGIN_BUY"

388

AUTO_REPAY_TYPE = "AUTO_REPAY"

389

390

# Kline Intervals

391

KLINE_INTERVAL_1SECOND = "1s"

392

KLINE_INTERVAL_1MINUTE = "1m"

393

KLINE_INTERVAL_3MINUTE = "3m"

394

KLINE_INTERVAL_5MINUTE = "5m"

395

KLINE_INTERVAL_15MINUTE = "15m"

396

KLINE_INTERVAL_30MINUTE = "30m"

397

KLINE_INTERVAL_1HOUR = "1h"

398

KLINE_INTERVAL_2HOUR = "2h"

399

KLINE_INTERVAL_4HOUR = "4h"

400

KLINE_INTERVAL_6HOUR = "6h"

401

KLINE_INTERVAL_8HOUR = "8h"

402

KLINE_INTERVAL_12HOUR = "12h"

403

KLINE_INTERVAL_1DAY = "1d"

404

KLINE_INTERVAL_3DAY = "3d"

405

KLINE_INTERVAL_1WEEK = "1w"

406

KLINE_INTERVAL_1MONTH = "1M"

407

408

# WebSocket Depth Levels

409

WEBSOCKET_DEPTH_5 = "5"

410

WEBSOCKET_DEPTH_10 = "10"

411

WEBSOCKET_DEPTH_20 = "20"

412

413

class HistoricalKlinesType(Enum):

414

SPOT = 1

415

FUTURES = 2

416

FUTURES_COIN = 3

417

FUTURES_MARK_PRICE = 4

418

FUTURES_INDEX_PRICE = 5

419

FUTURES_COIN_MARK_PRICE = 6

420

FUTURES_COIN_INDEX_PRICE = 7

421

422

class FuturesType(Enum):

423

USD_M = 1

424

COIN_M = 2

425

426

class ContractType(Enum):

427

PERPETUAL = "perpetual"

428

CURRENT_QUARTER = "current_quarter"

429

NEXT_QUARTER = "next_quarter"

430

431

class BinanceSocketType(str, Enum):

432

SPOT = "Spot"

433

USD_M_FUTURES = "USD_M_Futures"

434

COIN_M_FUTURES = "Coin_M_Futures"

435

OPTIONS = "Vanilla_Options"

436

ACCOUNT = "Account"

437

```

438

439

## Exception Classes

440

441

```python { .api }

442

class BinanceAPIException(Exception):

443

def __init__(self, response, status_code, text): ...

444

445

class BinanceRequestException(Exception):

446

def __init__(self, message): ...

447

448

class BinanceOrderException(Exception):

449

def __init__(self, code, message): ...

450

451

class BinanceOrderMinAmountException(BinanceOrderException): ...

452

class BinanceOrderMinPriceException(BinanceOrderException): ...

453

class BinanceOrderMinTotalException(BinanceOrderException): ...

454

class BinanceOrderUnknownSymbolException(BinanceOrderException): ...

455

class BinanceOrderInactiveSymbolException(BinanceOrderException): ...

456

457

class BinanceWebsocketUnableToConnect(Exception): ...

458

class BinanceWebsocketQueueOverflow(Exception): ...

459

class BinanceWebsocketClosed(Exception): ...

460

461

class NotImplementedException(Exception): ...

462

class UnknownDateFormat(Exception): ...

463

```

464

465

## Helper Functions

466

467

```python { .api }

468

def date_to_milliseconds(date_str: str) -> int: ...

469

def interval_to_milliseconds(interval: str) -> Optional[int]: ...

470

def convert_ts_str(ts_str): ...

471

def convert_list_to_json_array(list_items): ...

472

def get_loop(): ...

473

```