A python BingX API sync/async client
Project description
BingX API Client
This Python client facilitates communication with the BingX API, providing options for both synchronous and asynchronous request handling. It features caching, error management, and automatic request signing to improve your development workflow.
Features
- Fully Typed: Utilizes Python's type hints and Pydantic models for enhanced type safety.
- Caching Support: Minimizes API calls by caching GET requests. (
temporarily disabled) - Error Handling: Robust error management with specific exceptions for various API error codes.
- Request Signing: Automatically signs requests using your API credentials.
- Synchronous and Asynchronous: Capable of handling both synchronous and asynchronous requests.
For more details, please check out the documentation.
TODOs
- Make coverage tests.
- Add websocket stream support.
- Refactor models to use Generics for better type hints.
- Add
use_cacheparam for method calls. - Add support to async decode response by
msgspec - Prettify documentation
Installation
Install the client using pip:
pip install bingx-py
Or, if you're using Poetry:
poetry add bingx-py
Usage
Synchronous Client
You can use the client synchronously with a context manager or manually using try-except-finally.
Using Context Manager
from bingx_py import BingXHttpClient
with BingXHttpClient(api_key="your_api_key", api_secret="your_api_secret", base_url="https://api.bingx.com") as client:
response = client.spot.query_assets()
print(response)
Using Try-Except-Finally
from bingx_py import BingXHttpClient, exceptions
client = BingXHttpClient(api_key="your_api_key", api_secret="your_api_secret", base_url="https://api.bingx.com")
try:
client.connect()
response = client.spot.query_assets()
print(response)
except exceptions.APIError as e:
print("An error occurred:", e)
finally:
client.close()
Asynchronous Client
You can also use the client asynchronously with an async context manager or manually using try-except-finally.
Using Async Context Manager
import asyncio
from bingx_py import BingXHttpClient
async def main():
async with BingXHttpClient(api_key="your_api_key", api_secret="your_api_secret", base_url="https://api.bingx.com") as client:
response = await client.spot.query_assets()
print(response)
asyncio.run(main())
Using Try-Except-Finally
import asyncio
from bingx_py import BingXHttpClient, exceptions
async def main():
client = BingXHttpClient(api_key="your_api_key", api_secret="your_api_secret", base_url="https://api.bingx.com")
try:
await client.connect_async()
response = await client.spot.query_assets()
print(response)
except exceptions.APIError as e:
print("An error occurred:", e)
finally:
await client.close_async()
asyncio.run(main())
Caching Configuration
The client supports flexible caching configuration. You can set up caching globally or pass a cache instance directly to the client.
Supported Cache Types
- AsyncRedisCache: Asynchronous Redis-based caching (
async-redis). - SyncRedisCache: Synchronous Redis-based caching (
sync-redis). - AsyncMemoryCache: Asynchronous in-memory caching (
async-memory). - SyncMemoryCache: Synchronous in-memory caching (
sync-memory).
By default, the client uses a synchronous in-memory cache.
Setting Cache Globally
Use the set_cache function to configure the cache globally:
from bingx_py.config import set_cache
# Set up synchronous Redis cache
set_cache(cache_type="sync-redis", host="localhost", port=6379, db=0)
# Set up asynchronous Redis cache
set_cache(cache_type="async-redis", host="localhost", port=6379, db=0)
# Set up synchronous in-memory cache
set_cache(cache_type="sync-memory")
# Set up asynchronous in-memory cache
set_cache(cache_type="async-memory")
Passing Cache to the Client
Alternatively, pass a cache instance directly when initializing the client:
from bingx_py import BingXHttpClient
from bingx_py.caching import SyncMemoryCache
# Create a synchronous in-memory cache
cache = SyncMemoryCache()
# Pass the cache to the client
client = BingXHttpClient(
api_key="your_api_key",
api_secret="your_api_secret",
base_url="https://api.bingx.com",
cache=cache,
)
Enabling Unsafe Caching
By default, caching is only supported for GET requests. To enable caching for other HTTP methods (e.g., POST, PUT, DELETE), enable unsafe caching globally:
from bingx_py import cache_config
cache_config.enable_unsafe_cache() # Enable unsafe caching
Example: Using Redis Cache
Here’s an example of setting up and using a Redis cache:
from bingx_py import BingXHttpClient
from bingx_py.config import set_cache
# Set up synchronous Redis cache globally
set_cache(cache_type="sync-redis", host="localhost", port=6379, db=0)
# Initialize the client
client = BingXHttpClient(
api_key="your_api_key",
api_secret="your_api_secret",
)
# Make a request with caching
response = client.spot.query_assets(use_cache=True)
print(response)
Example: Using In-Memory Cache
Here’s an example of using an in-memory cache:
from bingx_py import BingXHttpClient
from bingx_py.caching import SyncMemoryCache
# Create a synchronous in-memory cache
cache = SyncMemoryCache()
# Pass the cache to the client
client = BingXHttpClient(
api_key="your_api_key",
api_secret="your_api_secret",
cache=cache,
)
# Make a request with caching
response = client._request("GET", "/api/v1/ping", use_cache=True)
print(response)
Cache Key Generation
Cache keys are generated based on the HTTP method, endpoint, parameters, and an optional unique attribute. For example, a request to /api/v1/ping with parameters {"foo": "bar"} generates a cache key like: GET:api/v1/ping:foo=bar.
You can also provide a unique_cache_attribute to customize the cache key:
response = client._request(
"GET",
"/api/v1/ping",
params={"foo": "bar"},
use_cache=True,
unique_cache_attribute="custom_key",
)
This generates a cache key like: GET:api/v1/ping:foo=bar:custom_key.
Error Handling
The client includes comprehensive error handling. If the API returns an error, the client raises a specific exception based on the error code.
try:
response = client._request("GET", "/api/v1/invalid_endpoint")
except exceptions.NotFoundError as e:
print(f"Not Found: {e.message}")
except exceptions.APIError as e:
print(f"API Error: {e.message}")
Contributing
Merge Requests
- Branch Naming: Name your branch according to the feature or bugfix (e.g.,
feature/add-new-endpointorbugfix/fix-issue-123). - Code Style: Follow the existing code style and ensure your code is fully typed.
- Tests: Include tests for new features or bugfixes.
- Documentation: Update the README or other documentation if necessary.
Issues
- Bug Reports: Provide a detailed description of the bug, including steps to reproduce and expected vs. actual behavior.
- Feature Requests: Describe the feature you would like to see, including relevant use cases.
Special Thanks
Special thanks to the Deepseek team for developing the AI model that powers a significant portion of this library.
Projects Using This Library
If your project uses this library, let me know by creating an issue, and I’ll add it to this list!
License
This project is licensed under the MIT License. See the LICENSE file for details.
Feel free to contribute by submitting merge requests or reporting issues. Happy coding! 🚀
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file bingx_py-0.1.0.tar.gz.
File metadata
- Download URL: bingx_py-0.1.0.tar.gz
- Upload date:
- Size: 79.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.11.11 Linux/6.8.0-1017-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4c856883ded925754936abe092db8a8e20c88c38a63e9635edcf2de731a6e096
|
|
| MD5 |
30e035a888868df069eecceef368b4c7
|
|
| BLAKE2b-256 |
5bb654cf272f485b2fc3baecb687eeeddb6f679dba80aa6042d2083ddbab7175
|
File details
Details for the file bingx_py-0.1.0-py3-none-any.whl.
File metadata
- Download URL: bingx_py-0.1.0-py3-none-any.whl
- Upload date:
- Size: 104.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.11.11 Linux/6.8.0-1017-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e9ead084cf8db8d0863485be1c5b1556c28878d7f95b8d46e9a82b9781acd18d
|
|
| MD5 |
70fcbec1f953674883dc94aa4390dd72
|
|
| BLAKE2b-256 |
c2fc8390aeb1fd66897f513cad6a178fff5c89712926c39457fda693a256d8a6
|