# Panzer: Binance API Connection Manager
Panzer is a Python-based library designed to manage Binance API interactions efficiently, handling both signed and unsigned requests. It includes features like secure credential management, automatic request signing, and a sophisticated rate-limiting and weight-control system.
## Key Features
- **Secure Credential Management**: AES-encrypted storage for API credentials. Credentials are decrypted **just-in-time** for security, meaning you never handle decrypted keys directly.
- **Request Signing**: Automatic signing for secure Binance API endpoints.
- **Rate-Limiting System**: Dynamic control of API request weight and order limits.
- **Weight Control**: Tracks and logs changes in Binance API request weights, enabling visibility of weight fluctuations.
- **Exception Handling**: Centralized error management for API requests.
## Installation
You can install Panzer via `pip`:
```bash
pip install panzer
```
Alternatively, clone the repository:
```bash
git clone https://github.com/nand0san/panzer.git
```
And then install the dependencies:
```bash
pip install -r requirements.txt
```
## Quick Start
Panzer is meant to manage all the ugly API things like, reate limits, manage secure credentials and keep track of API endpoint weights updates automatically. But also you can
manage objects from the module if you want to.
### Rate-Limit Control
The `BinanceRateLimiter` fetches rate limits directly from Binance and adapts accordingly.
```python
from panzer.limits import BinanceRateLimiter
rate_limiter = BinanceRateLimiter()
# Show automatically fetched rate limits
rate_limiter.get()
{'orders_limit_per_ten_seconds': 100,
'orders_limit_per_day': 200000,
'weight_limit_per_minute': 6000,
'raw_limit_per_5_minutes': 61000,
'server_time_offset': 113,
'five_minutes_counts': {5755608: 2},
'minutes_weights': {28778040: 21},
'ten_seconds_orders_counts': {},
'daily_orders_count': {}}
```
### Error Handling
Panzer offers centralized exception handling for all API requests.
```python
from panzer.errors import BinanceAPIException
from panzer.request import get
try:
# missing symbol example
response = get(url="https://api.binance.com/api/v3/klines", params=[("interval", "1m"),])
except BinanceAPIException as e:
print(f"Error: {e}")
Error: BinanceAPIException(code=-1102, status_code=400): Mandatory parameter 'symbol' was not sent, was empty/null, or malformed.
```
### Manage Credentials Securely
Panzer manages creds in a very automated way. It will save securely to a file: ' "~/.panzer_creds"' for every future API request if needed.
First call to API that requires credentials, will prompt the user to enter credentials if necessary. Also can be added to the credential manager.
```python
from panzer.keys import CredentialManager
credentials = CredentialManager()
credentials.add("api_key", "your_api_key", is_sensitive=True)
```
### Retrieve Kline Data (Public API)
```python
from panzer.request import get
url = 'https://api.binance.com/api/v3/klines'
weight=2
params = {
"symbol": "BTCUSDT", # Par BTCUSDT
"interval": "1m", # Intervalo de 1 minuto
"limit": 3 # Limitar a las últimas 5 velas
}
if rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):
response, headers = get(params=params,
url=url,
full_sign=False,
server_time_offset=rate_limiter.server_time_offset)
rate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)
print(response)
```
### Place a Test Order (Signed API)
```python
from panzer.request import post
url = 'https://api.binance.com/api/v3/order/test'
weight = 1
# timestamp is automatically added when signed call
params = {'symbol': "BTCUSDT",
'side': "SELL",
'type': "LIMIT",
'timeInForce': 'GTC',
'quantity': 0.001,
'price': 80000,
'recvWindow': 10000}
if rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):
response, headers = post(params=params,
url=url,
full_sign=True,
server_time_offset=rate_limiter.server_time_offset,)
rate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)
print(response)
```
### Retrieve Trade History (Signed API)
```python
from panzer.request import get
url = 'https://api.binance.com/api/v3/myTrades'
weight = 20
params = {
'symbol': 'BTCUSDT', # The trading pair
'limit': 3, # Optional: Limit the number of trades to retrieve (default 500)
'recvWindow': 5000 # Optional: Time window for the request (default 5000 ms)
}
if rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):
response, headers = get(params=params,
url=url,
full_sign=True,
server_time_offset=rate_limiter.server_time_offset,)
rate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)
print(response)
```
## Some classes
### 1. Setup Credentials
Panzer securely manages Binance credentials. Credentials are stored encrypted in the home directory (`~/panzer_creds`). If a credential is requested and not found, it
will be **prompted automatically**. You can also manually add credentials if needed.
Example:
```python
from panzer.keys import CredentialManager
# Initialize the credential manager
credentials = CredentialManager()
# The keys are always decrypted just-in-time, meaning you don't need to manually decrypt them.
api_key = credentials.get("api_key", decrypt=True) # Prompted if not available
api_secret = credentials.get("api_secret", decrypt=True) # Prompted if not available
```
You can add credentials manually using:
```python
credentials.add("api_key", "your_api_key", is_sensitive=True)
credentials.add("api_secret", "your_api_secret", is_sensitive=True)
```
### 2. Make API Requests
Panzer simplifies both public and private Binance API requests.
#### Public API Request (Unsigned)
```python
from panzer.request import get
url = "https://api.binance.com/api/v3/ticker/price"
params = [('symbol', 'BTCUSDT')]
response, headers = get(url=url, params=params)
print(response)
```
#### Private API Request (Signed)
```python
from panzer.request import get
url = "https://api.binance.com/api/v3/account"
response, headers = get(url=url, full_sign=True)
print(response)
```
### 3. Rate Limiting
The `BinanceRateLimiter` manages rate limits dynamically to ensure compliance with Binance's rules.
```python
from panzer.limits import BinanceRateLimiter
rate_limiter = BinanceRateLimiter()
# Check if a request can be made
url = "https://api.binance.com/api/v3/account"
params = {}
if rate_limiter.can_make_request(url=url, params_qty=len(params), weight=10, is_order=False):
print("Request can proceed")
else:
print("Rate limit exceeded, waiting...")
```
### 4. Weight Control
Panzer includes a feature that tracks and logs changes in Binance API request weights. The **WeightControl** class stores these weights in a file (`~/.panzer_weights.csv`), and updates them automatically as API requests are made. Initially, no weights are stored, but entries will accumulate as requests are logged.
Example:
```python
from panzer.weights import WeightControl
# Initialize the weight control system
weight_control = WeightControl()
# Fetch the current weight for a specific API call
url = "https://api.binance.com/api/v3/ticker/price"
params_qty = 1 # Number of parameters in the request
weight = weight_control.get(url, params_qty)
print(f"Current weight for {url} with {params_qty} params: {weight}")
# If the weight changes, update it
new_weight = 5 # New weight as observed
weight_control.update_weight(url, params_qty, new_weight)
print(f"Updated weight for {url} to {new_weight}")
```
As you use the API, the **weights file** will accumulate more entries, logging the weights for various API calls and parameter combinations. This will help you track changes in Binance’s rate-limiting policies.
### 5. Logging
Panzer logs all API interactions for debugging purposes, with logs stored in the `logs/` directory.
```python
from panzer.logs import LogManager
logger = LogManager(filename='logs/request.log', info_level='DEBUG')
logger.info("Logging API request details")
```
## Conclusion
Panzer is a robust and secure solution for interacting with Binance's API. It provides request signing, secure credential management, built-in rate-limiting controls, and now a **weight control system** for tracking API weight changes. Install via `pip` and start using it to manage Binance API interactions efficiently.
Raw data
{
"_id": null,
"home_page": "https://github.com/nand0san/panzer",
"name": "panzer",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": null,
"author": "nand0san",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/56/19/054aea1ed5aa3851b0e094712bc689f2688d726f37f6ca779a4dc1f37165/panzer-1.0.11.tar.gz",
"platform": null,
"description": "# Panzer: Binance API Connection Manager\r\n\r\nPanzer is a Python-based library designed to manage Binance API interactions efficiently, handling both signed and unsigned requests. It includes features like secure credential management, automatic request signing, and a sophisticated rate-limiting and weight-control system.\r\n\r\n## Key Features\r\n\r\n- **Secure Credential Management**: AES-encrypted storage for API credentials. Credentials are decrypted **just-in-time** for security, meaning you never handle decrypted keys directly.\r\n- **Request Signing**: Automatic signing for secure Binance API endpoints.\r\n- **Rate-Limiting System**: Dynamic control of API request weight and order limits.\r\n- **Weight Control**: Tracks and logs changes in Binance API request weights, enabling visibility of weight fluctuations.\r\n- **Exception Handling**: Centralized error management for API requests.\r\n\r\n## Installation\r\n\r\nYou can install Panzer via `pip`:\r\n\r\n```bash\r\npip install panzer\r\n```\r\n\r\nAlternatively, clone the repository:\r\n\r\n```bash\r\ngit clone https://github.com/nand0san/panzer.git\r\n```\r\n\r\nAnd then install the dependencies:\r\n\r\n```bash\r\npip install -r requirements.txt\r\n```\r\n\r\n## Quick Start\r\n\r\nPanzer is meant to manage all the ugly API things like, reate limits, manage secure credentials and keep track of API endpoint weights updates automatically. But also you can \r\nmanage objects from the module if you want to.\r\n\r\n### Rate-Limit Control\r\nThe `BinanceRateLimiter` fetches rate limits directly from Binance and adapts accordingly.\r\n\r\n```python\r\nfrom panzer.limits import BinanceRateLimiter\r\n\r\nrate_limiter = BinanceRateLimiter()\r\n\r\n# Show automatically fetched rate limits\r\nrate_limiter.get()\r\n\r\n {'orders_limit_per_ten_seconds': 100,\r\n 'orders_limit_per_day': 200000,\r\n 'weight_limit_per_minute': 6000,\r\n 'raw_limit_per_5_minutes': 61000,\r\n 'server_time_offset': 113,\r\n 'five_minutes_counts': {5755608: 2},\r\n 'minutes_weights': {28778040: 21},\r\n 'ten_seconds_orders_counts': {},\r\n 'daily_orders_count': {}}\r\n```\r\n\r\n### Error Handling\r\nPanzer offers centralized exception handling for all API requests.\r\n\r\n```python\r\nfrom panzer.errors import BinanceAPIException\r\nfrom panzer.request import get\r\n\r\ntry:\r\n # missing symbol example\r\n response = get(url=\"https://api.binance.com/api/v3/klines\", params=[(\"interval\", \"1m\"),])\r\n\r\nexcept BinanceAPIException as e:\r\n print(f\"Error: {e}\")\r\n\r\nError: BinanceAPIException(code=-1102, status_code=400): Mandatory parameter 'symbol' was not sent, was empty/null, or malformed.\r\n```\r\n\r\n### Manage Credentials Securely\r\nPanzer manages creds in a very automated way. It will save securely to a file: ' \"~/.panzer_creds\"' for every future API request if needed.\r\n\r\nFirst call to API that requires credentials, will prompt the user to enter credentials if necessary. Also can be added to the credential manager.\r\n\r\n```python\r\nfrom panzer.keys import CredentialManager\r\n\r\ncredentials = CredentialManager()\r\ncredentials.add(\"api_key\", \"your_api_key\", is_sensitive=True)\r\n```\r\n\r\n### Retrieve Kline Data (Public API)\r\n```python\r\nfrom panzer.request import get\r\n\r\nurl = 'https://api.binance.com/api/v3/klines'\r\nweight=2\r\nparams = {\r\n \"symbol\": \"BTCUSDT\", # Par BTCUSDT\r\n \"interval\": \"1m\", # Intervalo de 1 minuto\r\n \"limit\": 3 # Limitar a las \u00faltimas 5 velas\r\n}\r\n\r\nif rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):\r\n \r\n response, headers = get(params=params, \r\n url=url,\r\n full_sign=False,\r\n server_time_offset=rate_limiter.server_time_offset)\r\n \r\n rate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)\r\n \r\nprint(response)\r\n```\r\n\r\n### Place a Test Order (Signed API)\r\n```python\r\nfrom panzer.request import post\r\n\r\nurl = 'https://api.binance.com/api/v3/order/test'\r\nweight = 1\r\n\r\n# timestamp is automatically added when signed call\r\nparams = {'symbol': \"BTCUSDT\",\r\n 'side': \"SELL\",\r\n 'type': \"LIMIT\",\r\n 'timeInForce': 'GTC',\r\n 'quantity': 0.001,\r\n 'price': 80000,\r\n 'recvWindow': 10000}\r\n\r\nif rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):\r\n \r\n response, headers = post(params=params, \r\n url=url,\r\n full_sign=True,\r\n server_time_offset=rate_limiter.server_time_offset,)\r\n \r\nrate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)\r\n\r\nprint(response)\r\n```\r\n\r\n### Retrieve Trade History (Signed API)\r\n```python\r\nfrom panzer.request import get\r\n\r\nurl = 'https://api.binance.com/api/v3/myTrades'\r\nweight = 20\r\nparams = {\r\n 'symbol': 'BTCUSDT', # The trading pair\r\n 'limit': 3, # Optional: Limit the number of trades to retrieve (default 500)\r\n 'recvWindow': 5000 # Optional: Time window for the request (default 5000 ms)\r\n}\r\n\r\nif rate_limiter.can_make_request(url=url, params_qty=len(params), weight=weight, is_order=False):\r\n \r\n response, headers = get(params=params, \r\n url=url,\r\n full_sign=True,\r\n server_time_offset=rate_limiter.server_time_offset,)\r\n \r\nrate_limiter.update_from_headers(url=url, params_qty=len(params), headers=headers, expected_weight=weight)\r\n\r\nprint(response)\r\n```\r\n\r\n## Some classes\r\n\r\n### 1. Setup Credentials\r\nPanzer securely manages Binance credentials. Credentials are stored encrypted in the home directory (`~/panzer_creds`). If a credential is requested and not found, it \r\nwill be **prompted automatically**. You can also manually add credentials if needed.\r\n\r\nExample:\r\n```python\r\nfrom panzer.keys import CredentialManager\r\n\r\n# Initialize the credential manager\r\ncredentials = CredentialManager()\r\n\r\n# The keys are always decrypted just-in-time, meaning you don't need to manually decrypt them.\r\napi_key = credentials.get(\"api_key\", decrypt=True) # Prompted if not available\r\napi_secret = credentials.get(\"api_secret\", decrypt=True) # Prompted if not available\r\n```\r\n\r\nYou can add credentials manually using:\r\n\r\n```python\r\ncredentials.add(\"api_key\", \"your_api_key\", is_sensitive=True)\r\ncredentials.add(\"api_secret\", \"your_api_secret\", is_sensitive=True)\r\n```\r\n\r\n### 2. Make API Requests\r\nPanzer simplifies both public and private Binance API requests.\r\n\r\n#### Public API Request (Unsigned)\r\n```python\r\nfrom panzer.request import get\r\n\r\nurl = \"https://api.binance.com/api/v3/ticker/price\"\r\nparams = [('symbol', 'BTCUSDT')]\r\nresponse, headers = get(url=url, params=params)\r\nprint(response)\r\n```\r\n\r\n#### Private API Request (Signed)\r\n```python\r\nfrom panzer.request import get\r\n\r\nurl = \"https://api.binance.com/api/v3/account\"\r\nresponse, headers = get(url=url, full_sign=True)\r\nprint(response)\r\n```\r\n\r\n### 3. Rate Limiting\r\nThe `BinanceRateLimiter` manages rate limits dynamically to ensure compliance with Binance's rules.\r\n\r\n```python\r\nfrom panzer.limits import BinanceRateLimiter\r\n\r\nrate_limiter = BinanceRateLimiter()\r\n\r\n# Check if a request can be made\r\nurl = \"https://api.binance.com/api/v3/account\"\r\nparams = {}\r\n\r\nif rate_limiter.can_make_request(url=url, params_qty=len(params), weight=10, is_order=False):\r\n print(\"Request can proceed\")\r\nelse:\r\n print(\"Rate limit exceeded, waiting...\")\r\n```\r\n\r\n### 4. Weight Control\r\nPanzer includes a feature that tracks and logs changes in Binance API request weights. The **WeightControl** class stores these weights in a file (`~/.panzer_weights.csv`), and updates them automatically as API requests are made. Initially, no weights are stored, but entries will accumulate as requests are logged.\r\n\r\nExample:\r\n```python\r\nfrom panzer.weights import WeightControl\r\n\r\n# Initialize the weight control system\r\nweight_control = WeightControl()\r\n\r\n# Fetch the current weight for a specific API call\r\nurl = \"https://api.binance.com/api/v3/ticker/price\"\r\nparams_qty = 1 # Number of parameters in the request\r\nweight = weight_control.get(url, params_qty)\r\nprint(f\"Current weight for {url} with {params_qty} params: {weight}\")\r\n\r\n# If the weight changes, update it\r\nnew_weight = 5 # New weight as observed\r\nweight_control.update_weight(url, params_qty, new_weight)\r\nprint(f\"Updated weight for {url} to {new_weight}\")\r\n```\r\n\r\nAs you use the API, the **weights file** will accumulate more entries, logging the weights for various API calls and parameter combinations. This will help you track changes in Binance\u2019s rate-limiting policies.\r\n\r\n### 5. Logging\r\nPanzer logs all API interactions for debugging purposes, with logs stored in the `logs/` directory.\r\n\r\n```python\r\nfrom panzer.logs import LogManager\r\n\r\nlogger = LogManager(filename='logs/request.log', info_level='DEBUG')\r\nlogger.info(\"Logging API request details\")\r\n```\r\n\r\n\r\n\r\n## Conclusion\r\nPanzer is a robust and secure solution for interacting with Binance's API. It provides request signing, secure credential management, built-in rate-limiting controls, and now a **weight control system** for tracking API weight changes. Install via `pip` and start using it to manage Binance API interactions efficiently.\r\n",
"bugtrack_url": null,
"license": null,
"summary": "REST API manager for Binance API. Manages weights and credentials simply and securely.",
"version": "1.0.11",
"project_urls": {
"Homepage": "https://github.com/nand0san/panzer"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "5619054aea1ed5aa3851b0e094712bc689f2688d726f37f6ca779a4dc1f37165",
"md5": "9cf8eb88038970be46762ee1b40707d3",
"sha256": "b35177d61ca2d27e6b6c46be88118148e1cab06b0ed2330c91532c4e6c2959fb"
},
"downloads": -1,
"filename": "panzer-1.0.11.tar.gz",
"has_sig": false,
"md5_digest": "9cf8eb88038970be46762ee1b40707d3",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 26116,
"upload_time": "2024-10-20T16:18:16",
"upload_time_iso_8601": "2024-10-20T16:18:16.022250Z",
"url": "https://files.pythonhosted.org/packages/56/19/054aea1ed5aa3851b0e094712bc689f2688d726f37f6ca779a4dc1f37165/panzer-1.0.11.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-20 16:18:16",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "nand0san",
"github_project": "panzer",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "py-cpuinfo",
"specs": [
[
">=",
"9.0.0"
]
]
},
{
"name": "pycryptodome",
"specs": [
[
">=",
"3.19.0"
]
]
},
{
"name": "pytz",
"specs": [
[
">=",
"2023.3.post1"
]
]
},
{
"name": "requests",
"specs": [
[
">=",
"2.31.0"
]
]
},
{
"name": "tqdm",
"specs": [
[
">=",
"4.66.1"
]
]
},
{
"name": "typing",
"specs": [
[
"~=",
"3.7.4.3"
]
]
}
],
"lcname": "panzer"
}