Skip to content

Commit 4351a6e

Browse files
authored
v2.0.0-rc1 release (#187)
* v2.0.0-rc1 release * fixing rst format * update readme
1 parent 925fe11 commit 4351a6e

File tree

235 files changed

+873
-706
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

235 files changed

+873
-706
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Changelog
22

3+
## 2.0.0-rc1 - 2022-11-29
4+
5+
### Added
6+
- Add support for use of RSA Key to generate signatures
7+
38
## 1.18.0 - 2022-09-29
49

510
### Added

README.md

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pip install binance-connector
3030

3131
Usage examples:
3232
```python
33-
from binance.spot import Spot
33+
from binance.spot import Spot
3434

3535
client = Spot()
3636

@@ -41,8 +41,8 @@ print(client.klines("BTCUSDT", "1m"))
4141
# Get last 10 klines of BNBUSDT at 1h interval
4242
print(client.klines("BNBUSDT", "1h", limit=10))
4343

44-
# api key/secret are required for user data endpoints
45-
client = Spot(key='<api_key>', secret='<api_secret>')
44+
# API key/secret are required for user data endpoints
45+
client = Spot(api_key='<api_key>', api_secret='<api_secret>')
4646

4747
# Get account and balance information
4848
print(client.account())
@@ -62,6 +62,27 @@ print(response)
6262
```
6363
Please find `examples` folder to check for more endpoints.
6464

65+
### Authentication
66+
67+
Binance supports HMAC and RSA API authentication.
68+
69+
```python
70+
71+
# HMAC: pass API key and secret
72+
client = Client(api_key, api_secret)
73+
print(client.account())
74+
75+
# RSA Keys
76+
client = Client(api_key=api_key, private_key=private_key)
77+
print(client.account())
78+
79+
# Encrypted RSA Key
80+
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')
81+
print(client.account())
82+
```
83+
84+
Please find `examples/spot/trade/get_account.py` for more details.
85+
6586
### Testnet
6687

6788
[Spot Testnet](https://testnet.binance.vision/) is available, it can be used to test `/api/*` endpoints.
@@ -109,7 +130,7 @@ Anything beyond the limit will result in an error response from Binance server.
109130
```python
110131
from binance.spot import Spot as Client
111132

112-
client = Client(key, secret)
133+
client = Client(api_key, api_secret)
113134
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)
114135
```
115136

@@ -182,7 +203,7 @@ There are 2 types of error returned from the library:
182203
- `status_code` - HTTP status code
183204
- `error_code` - Server's error code, e.g. `-1102`
184205
- `error_message` - Server's error message, e.g. `Unknown order sent.`
185-
- `header` - Full response header.
206+
- `header` - Full response header.
186207
- `binance.error.ServerError`
187208
- This is thrown when server returns `5XX`, it's an issue from server side.
188209

binance/__version__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.18.0"
1+
__version__ = "2.0.0-rc1"

binance/api.py

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
import hmac
21
import json
3-
import logging
4-
import hashlib
52
from json import JSONDecodeError
6-
3+
import logging
74
import requests
85
from .__version__ import __version__
96
from binance.error import ClientError, ServerError
107
from binance.lib.utils import get_timestamp
118
from binance.lib.utils import cleanNoneValue
129
from binance.lib.utils import encoded_string
1310
from binance.lib.utils import check_required_parameter
11+
from binance.lib.authentication import hmac_hashing, rsa_signature
1412

1513

1614
class API(object):
@@ -22,36 +20,40 @@ class API(object):
2220
proxies (obj, optional): Dictionary mapping protocol to the URL of the proxy. e.g. {'https': 'http://1.2.3.4:8080'}
2321
show_limit_usage (bool, optional): whether return limit usage(requests and/or orders). By default, it's False
2422
show_header (bool, optional): whether return the whole response header. By default, it's False
23+
private_key (str, optional): RSA private key for RSA authentication
24+
private_key_pass(str, optional): Password for PSA private key
2525
"""
2626

2727
def __init__(
2828
self,
29-
key=None,
30-
secret=None,
29+
api_key=None,
30+
api_secret=None,
3131
base_url=None,
3232
timeout=None,
3333
proxies=None,
3434
show_limit_usage=False,
3535
show_header=False,
36+
private_key=None,
37+
private_key_pass=None,
3638
):
37-
self.key = key
38-
self.secret = secret
39+
self.api_key = api_key
40+
self.api_secret = api_secret
41+
self.base_url = base_url
3942
self.timeout = timeout
43+
self.proxies = None
4044
self.show_limit_usage = False
4145
self.show_header = False
42-
self.proxies = None
46+
self.private_key = private_key
47+
self.private_key_pass = private_key_pass
4348
self.session = requests.Session()
4449
self.session.headers.update(
4550
{
4651
"Content-Type": "application/json;charset=utf-8",
4752
"User-Agent": "binance-connector/" + __version__,
48-
"X-MBX-APIKEY": key,
53+
"X-MBX-APIKEY": api_key,
4954
}
5055
)
5156

52-
if base_url:
53-
self.base_url = base_url
54-
5557
if show_limit_usage is True:
5658
self.show_limit_usage = True
5759

@@ -70,16 +72,15 @@ def query(self, url_path, payload=None):
7072
def limit_request(self, http_method, url_path, payload=None):
7173
"""limit request is for those endpoints require API key in the header"""
7274

73-
check_required_parameter(self.key, "apiKey")
75+
check_required_parameter(self.api_key, "api_key")
7476
return self.send_request(http_method, url_path, payload=payload)
7577

7678
def sign_request(self, http_method, url_path, payload=None):
7779
if payload is None:
7880
payload = {}
7981
payload["timestamp"] = get_timestamp()
8082
query_string = self._prepare_params(payload)
81-
signature = self._get_sign(query_string)
82-
payload["signature"] = signature
83+
payload["signature"] = self._get_sign(query_string)
8384
return self.send_request(http_method, url_path, payload)
8485

8586
def limited_encoded_sign_request(self, http_method, url_path, payload=None):
@@ -95,8 +96,9 @@ def limited_encoded_sign_request(self, http_method, url_path, payload=None):
9596
payload = {}
9697
payload["timestamp"] = get_timestamp()
9798
query_string = self._prepare_params(payload)
98-
signature = self._get_sign(query_string)
99-
url_path = url_path + "?" + query_string + "&signature=" + signature
99+
url_path = (
100+
url_path + "?" + query_string + "&signature=" + self._get_sign(query_string)
101+
)
100102
return self.send_request(http_method, url_path)
101103

102104
def send_request(self, http_method, url_path, payload=None):
@@ -146,9 +148,10 @@ def send_request(self, http_method, url_path, payload=None):
146148
def _prepare_params(self, params):
147149
return encoded_string(cleanNoneValue(params))
148150

149-
def _get_sign(self, data):
150-
m = hmac.new(self.secret.encode("utf-8"), data.encode("utf-8"), hashlib.sha256)
151-
return m.hexdigest()
151+
def _get_sign(self, payload):
152+
if self.private_key:
153+
return rsa_signature(self.private_key, payload, self.private_key_pass)
154+
return hmac_hashing(self.api_secret, payload)
152155

153156
def _dispatch_request(self, http_method):
154157
return {

binance/lib/authentication.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import hmac
2+
import hashlib
3+
from base64 import b64encode
4+
from Crypto.PublicKey import RSA
5+
from Crypto.Hash import SHA256
6+
from Crypto.Signature import pkcs1_15
7+
8+
9+
def hmac_hashing(api_secret, payload):
10+
m = hmac.new(api_secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256)
11+
return m.hexdigest()
12+
13+
14+
def rsa_signature(private_key, payload, private_key_pass=None):
15+
private_key = RSA.import_key(private_key, passphrase=private_key_pass)
16+
h = SHA256.new(payload.encode("utf-8"))
17+
signature = pkcs1_15.new(private_key).sign(h)
18+
return b64encode(signature)

binance/spot/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33

44
class Spot(API):
5-
def __init__(self, key=None, secret=None, **kwargs):
5+
def __init__(self, api_key=None, api_secret=None, **kwargs):
66
if "base_url" not in kwargs:
77
kwargs["base_url"] = "https://api.binance.com"
8-
super().__init__(key, secret, **kwargs)
8+
super().__init__(api_key, api_secret, **kwargs)
99

1010
# MARKETS
1111
from binance.spot.market import ping

docs/source/CHANGELOG.rst

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22
Changelog
33
=========
44

5+
2.0.0-rc1 - 2022-11-29
6+
----------------------
7+
8+
Added
9+
^^^^^
10+
11+
* Add support for use of RSA Key to generate signatures
12+
513
1.18.0 - 2022-09-29
614
-------------------
715

@@ -55,7 +63,7 @@ Added
5563
^^^^^
5664

5765
* New endpoint for Portfolio Margin:
58-
66+
5967
* ``GET /sapi/v1/portfolio/pmLoan`` to query Portfolio Margin Bankruptcy Loan Record.
6068
* ``POST /sapi/v1/portfolio/repay`` to repay Portfolio Margin Bankruptcy Loan.
6169
* ``GET /sapi/v1/portfolio/collateralRate`` to get Portfolio Margin Collateral Rate.
@@ -64,17 +72,17 @@ Update
6472
^^^^^^
6573

6674
* Changes to ``POST /api/v3/order`` and ``POST /api/v3/order/cancelReplace``
67-
75+
6876
* New optional field ``strategyId`` is a parameter used to identify an order as part of a strategy.
6977
* New optional field ``strategyType`` is a parameter used to identify what strategy was running. (E.g. If all the orders are part of spot grid strategy, it can be set to strategyType=1000000)
7078
* Note: ``strategyType`` cannot be less than 1000000.
71-
79+
7280
* Changes to ``POST /api/v3/order/oco``
7381

7482
* New optional fields ``limitStrategyId``, ``limitStrategyType``, ``stopStrategyId``, ``stopStrategyType``
7583
* These are the strategy metadata parameters for both legs of the OCO orders.
7684
* ``limitStrategyType`` and ``stopStrategyType`` both cannot be less than 1000000.
77-
85+
7886
* ``asset`` is no longer mandatory in ``GET /sapi/v1/lending/project/position/list``
7987

8088
1.15.0 - 2022-07-19

docs/source/getting_started.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Usage example:
4040
print(client.klines("BNBUSDT", "1h", limit=10))
4141
4242
# api key/secret are required for user data endpoints
43-
client = Spot(key='<api_key>', secret='<api_secret>')
43+
client = Spot(api_key='<api_key>', api_secret='<api_secret>')
4444
4545
# Get account and balance information
4646
print(client.account())
@@ -104,7 +104,7 @@ Anything beyond the limit will result in an error response from Binance server.
104104
105105
from binance.spot import Spot as Client
106106
107-
client = Client(key, secret)
107+
client = Client(api_key, api_secret)
108108
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)
109109
110110

docs/source/intro.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,12 @@ RESTful APIs
8989

9090
.. code-block:: python
9191
92-
from binance.spot import Spot
92+
from binance.spot import Spot
9393
9494
client = Spot()
9595
print(client.time())
9696
97-
client = Spot(key='<api_key>', secret='<api_secret>')
97+
client = Spot(api_key='<api_key>', api_secret='<api_secret>')
9898
9999
# Get account information
100100
print(client.account())

examples/spot/blvt/blvt_info.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313

1414
logger = logging.getLogger(__name__)
1515
logger.info(client.blvt_info(tokenName="LINKUP"))

examples/spot/blvt/redeem_blvt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(client.redeem_blvt(tokenName="LINKUP", amount="10.05022099"))

examples/spot/blvt/redemption_record.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(client.redemption_record(tokenName="LINKUP"))

examples/spot/blvt/subscribe_blvt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(client.subscribe_blvt(tokenName="LINKUP", cost="9.99999995"))

examples/spot/blvt/subscription_record.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(client.subscription_record(tokenName="LINKUP"))

examples/spot/blvt/user_limit_info.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(client.user_limit_info(tokenName="BTCDOWN"))

examples/spot/bswap/bswap_add_liquidity_preview.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
config_logging(logging, logging.DEBUG)
88

9-
key = ""
10-
secret = ""
9+
api_key = ""
10+
api_secret = ""
1111

12-
client = Client(key, secret)
12+
client = Client(api_key, api_secret)
1313
logging.info(
1414
client.bswap_add_liquidity_preview(
1515
poolId=2, type="SINGLE", quoteAsset="USDT", quoteQty=0.01

0 commit comments

Comments
 (0)