or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account.mdconvert-api.mddepth-cache.mdfutures.mdindex.mdmargin.mdmarket-data.mdrest-clients.mdstaking-mining.mdtrading.mdwebsockets.md

rest-clients.mddocs/

0

# REST API Clients

1

2

The core synchronous and asynchronous REST API clients provide access to all Binance endpoints. Both clients inherit from BaseClient and implement the same comprehensive method set with different execution patterns.

3

4

## Capabilities

5

6

### Client Class (Synchronous)

7

8

Synchronous REST API client using the requests library. Best for simple scripts, interactive use, and applications that don't require high concurrency.

9

10

```python { .api }

11

class Client(BaseClient):

12

def __init__(

13

self,

14

api_key: Optional[str] = None,

15

api_secret: Optional[str] = None,

16

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

17

tld: str = "com",

18

base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,

19

testnet: bool = False,

20

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

21

private_key_pass: Optional[str] = None,

22

ping: Optional[bool] = True,

23

time_unit: Optional[str] = None,

24

): ...

25

```

26

27

#### Usage Example

28

29

```python

30

from binance import Client

31

32

# Initialize with API credentials

33

client = Client(

34

api_key='your_api_key',

35

api_secret='your_api_secret',

36

testnet=True # Use testnet for testing

37

)

38

39

# Basic connectivity test

40

server_time = client.get_server_time()

41

print(f"Server time: {server_time['serverTime']}")

42

43

# Get account information

44

account = client.get_account()

45

balances = {b['asset']: b['free'] for b in account['balances'] if float(b['free']) > 0}

46

print(f"Non-zero balances: {balances}")

47

```

48

49

### AsyncClient Class (Asynchronous)

50

51

Asynchronous REST API client using aiohttp. Provides better performance for high-frequency operations and concurrent request handling.

52

53

```python { .api }

54

class AsyncClient(BaseClient):

55

def __init__(

56

self,

57

api_key: Optional[str] = None,

58

api_secret: Optional[str] = None,

59

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

60

tld: str = "com",

61

base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,

62

testnet: bool = False,

63

loop=None,

64

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

65

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

66

private_key_pass: Optional[str] = None,

67

https_proxy: Optional[str] = None,

68

time_unit: Optional[str] = None,

69

): ...

70

71

@classmethod

72

async def create(

73

cls,

74

api_key: Optional[str] = None,

75

api_secret: Optional[str] = None,

76

**kwargs

77

) -> 'AsyncClient': ...

78

79

async def close_connection(self): ...

80

```

81

82

#### Usage Example

83

84

```python

85

import asyncio

86

from binance import AsyncClient

87

88

async def main():

89

# Create async client

90

client = await AsyncClient.create(

91

api_key='your_api_key',

92

api_secret='your_api_secret'

93

)

94

95

try:

96

# Concurrent requests for better performance

97

tasks = [

98

client.get_server_time(),

99

client.get_exchange_info(),

100

client.get_all_tickers()

101

]

102

103

server_time, exchange_info, tickers = await asyncio.gather(*tasks)

104

105

print(f"Server time: {server_time['serverTime']}")

106

print(f"Total symbols: {len(exchange_info['symbols'])}")

107

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

108

109

finally:

110

# Always close the connection

111

await client.close_connection()

112

113

asyncio.run(main())

114

```

115

116

### Authentication Options

117

118

Both clients support multiple authentication methods:

119

120

#### API Key Authentication

121

122

```python

123

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

124

```

125

126

#### RSA Private Key Authentication

127

128

```python

129

from pathlib import Path

130

131

client = Client(

132

api_key='your_api_key',

133

private_key=Path('path/to/private_key.pem'),

134

private_key_pass='optional_passphrase'

135

)

136

```

137

138

#### EdDSA Private Key Authentication

139

140

```python

141

client = Client(

142

api_key='your_api_key',

143

private_key='path/to/ed25519_private_key.pem'

144

)

145

```

146

147

### Configuration Options

148

149

#### Testnet Usage

150

151

```python

152

# Use Binance testnet

153

client = Client(

154

api_key='testnet_api_key',

155

api_secret='testnet_api_secret',

156

testnet=True

157

)

158

```

159

160

#### Custom TLD and Endpoints

161

162

```python

163

# Use different TLD

164

client = Client(tld='us') # For Binance.US

165

166

# Use different base endpoint

167

client = Client(base_endpoint='1') # Alternative endpoint

168

```

169

170

#### Request Configuration

171

172

```python

173

# Custom request parameters

174

client = Client(

175

requests_params={

176

'timeout': 30,

177

'proxies': {'https': 'https://proxy:8080'}

178

}

179

)

180

181

# For AsyncClient

182

client = await AsyncClient.create(

183

session_params={

184

'timeout': aiohttp.ClientTimeout(total=30)

185

},

186

https_proxy='https://proxy:8080'

187

)

188

```

189

190

### Connection Management

191

192

#### Synchronous Client

193

194

```python

195

# Connection is managed automatically

196

client = Client(api_key='key', api_secret='secret')

197

198

# Optional: Disable initial ping

199

client = Client(api_key='key', api_secret='secret', ping=False)

200

```

201

202

#### Asynchronous Client

203

204

```python

205

# Proper async connection management

206

async def main():

207

client = await AsyncClient.create()

208

209

try:

210

# Use client for operations

211

result = await client.get_account()

212

finally:

213

# Always close connection

214

await client.close_connection()

215

216

# Or use as async context manager

217

async def main():

218

async with AsyncClient.create() as client:

219

result = await client.get_account()

220

# Connection closed automatically

221

```

222

223

### Error Handling

224

225

Both clients raise the same exception types:

226

227

```python

228

from binance import Client, BinanceAPIException, BinanceRequestException

229

230

client = Client(api_key='key', api_secret='secret')

231

232

try:

233

order = client.create_order(

234

symbol='BTCUSDT',

235

side='BUY',

236

type='MARKET',

237

quantity=0.001

238

)

239

except BinanceAPIException as e:

240

print(f"API Error {e.code}: {e.message}")

241

except BinanceRequestException as e:

242

print(f"Request Error: {e.message}")

243

except Exception as e:

244

print(f"Unexpected error: {e}")

245

```

246

247

### Time Synchronization

248

249

The clients automatically handle timestamp requirements:

250

251

```python

252

# Automatic timestamp generation

253

client = Client(api_key='key', api_secret='secret')

254

255

# Custom time unit (milliseconds by default)

256

client = Client(api_key='key', api_secret='secret', time_unit='seconds')

257

```

258

259

Both clients provide identical method signatures and functionality - the only difference is the execution model (synchronous vs asynchronous).