Python SDK for Binance trading with ContextCol API integration
Project description
ContextCol SDK
A comprehensive Python SDK for Binance trading with ContextCol API integration. This SDK provides seamless integration between Binance spot trading and ContextCol's trading bot analytics platform.
Features
- Binance Integration: Complete Binance API wrapper with spot trading capabilities
- Market Data API: Comprehensive market data endpoints using requests directly
- ContextCol API: Full integration with ContextCol's trading bot activity tracking
- Secure Configuration: Environment-based configuration with validation
- Comprehensive Error Handling: Custom exceptions for different error scenarios
- Type Hints: Full type annotation support for better IDE experience
- No External Dependencies: Uses requests directly instead of outdated binance library
Installation
pip install contextcol
Quick Start
Basic Setup
from contextcol import ContextColClient
# Initialize with environment variables
client = ContextColClient()
# Or initialize with direct configuration
client = ContextColClient(
binance_api_key="your_binance_api_key",
binance_api_secret="your_binance_api_secret",
contextcol_api_key="your_contextcol_api_key"
)
Environment Variables
Create a .env file in your project root:
BINANCE_API_KEY=your_binance_api_key
BINANCE_API_SECRET=your_binance_api_secret
BINANCE_TESTNET=false
CONTEXTCOL_API_KEY=your_contextcol_api_key
CONTEXTCOL_BASE_URL=https://api.contextcol.com
Simple Trading Example
from contextcol import ContextColClient
# Initialize client
client = ContextColClient()
# Execute a spot trade and log to ContextCol
result = client.execute_spot_trade(
symbol="BTCUSDT",
side="BUY",
quantity="0.001",
order_type="MARKET",
test=True # Use test mode first
)
print(f"Order result: {result['binance_order']}")
print(f"ContextCol log: {result['contextcol_log']}")
API Reference
ContextColClient
The main client class that provides access to all SDK functionality.
Trading Methods
# Execute spot trade with ContextCol logging
client.execute_spot_trade(symbol, side, quantity, order_type="MARKET", price=None, test=False)
# Create trading bot activity
client.create_trading_bot_activity(activity_data)
# Test trading bot activity
client.test_trading_bot_activity(activity_id, test_data)
Binance Methods
# Get account information
account_info = client.binance.get_account_info()
# Get account balance
balance = client.binance.get_balance("BTC")
# Create spot order
order = client.binance.create_spot_order("BTCUSDT", "BUY", "0.001")
# Get ticker price
price = client.binance.get_ticker_price("BTCUSDT")
Market Data Methods
# Access market data client
market_data = client.binance.market_data
# Get order book
order_book = market_data.get_order_book("BTCUSDT", limit=100)
# Get recent trades
trades = market_data.get_recent_trades("BTCUSDT", limit=500)
# Get historical trades
historical_trades = market_data.get_historical_trades("BTCUSDT", limit=500)
# Get aggregate trades
agg_trades = market_data.get_aggregate_trades("BTCUSDT", limit=500)
# Get klines (candlestick data)
klines = market_data.get_klines("BTCUSDT", "1h", limit=100)
# Get UI klines (optimized for charts)
ui_klines = market_data.get_ui_klines("BTCUSDT", "1h", limit=100)
# Get average price
avg_price = market_data.get_avg_price("BTCUSDT")
# Get 24hr ticker statistics
ticker_24hr = market_data.get_24hr_ticker("BTCUSDT")
# Get trading day ticker
trading_day_ticker = market_data.get_trading_day_ticker("BTCUSDT")
# Get symbol price ticker
price_ticker = market_data.get_symbol_price_ticker("BTCUSDT")
# Get order book ticker
book_ticker = market_data.get_order_book_ticker("BTCUSDT")
# Get rolling window ticker
rolling_ticker = market_data.get_rolling_window_ticker("BTCUSDT", window_size="1d")
ContextCol API Methods
# Create Binance spot transaction log
client.create_binance_spot_transaction(transaction_data)
# Test Binance spot transaction
client.test_binance_spot_transaction(transaction_data)
# Get trading analytics
analytics = client.get_trading_analytics(start_date="2024-01-01", end_date="2024-01-31")
Configuration
Config Class
from contextcol import Config
# Create configuration
config = Config(
binance_api_key="your_key",
binance_api_secret="your_secret",
contextcol_api_key="your_contextcol_key",
binance_testnet=True, # Use testnet
timeout=30,
max_retries=3
)
# Initialize client with config
client = ContextColClient(config=config)
Configuration Options
| Parameter | Type | Default | Description |
|---|---|---|---|
binance_api_key |
str | None | Binance API key |
binance_api_secret |
str | None | Binance API secret |
binance_testnet |
bool | False | Use Binance testnet |
contextcol_api_key |
str | None | ContextCol API key |
contextcol_base_url |
str | https://api.contextcol.com | ContextCol API base URL |
timeout |
int | 30 | Request timeout in seconds |
max_retries |
int | 3 | Maximum retry attempts |
Error Handling
The SDK provides comprehensive error handling with custom exceptions:
from contextcol_binance_spot_sdk.exceptions import (
ContextColError,
APIError,
ConfigError,
BinanceAPIError,
AuthenticationError,
ValidationError
)
try:
result = client.execute_spot_trade("BTCUSDT", "BUY", "0.001")
except BinanceAPIError as e:
print(f"Binance API error: {e.message} (Code: {e.code})")
except APIError as e:
print(f"ContextCol API error: {e} (Status: {e.status_code})")
except ValidationError as e:
print(f"Validation error: {e}")
Advanced Usage
Context Manager
with ContextColClient() as client:
# Your trading logic here
result = client.execute_spot_trade("BTCUSDT", "BUY", "0.001")
print(result)
# Client connections are automatically closed
Validate Configuration
client = ContextColClient()
validation_result = client.validate_configuration()
if validation_result['binance_connection']:
print("Binance connection successful")
if validation_result['contextcol_connection']:
print("ContextCol connection successful")
for error in validation_result['errors']:
print(f"Error: {error}")
Get Account Summary
summary = client.get_account_summary()
print(f"Binance Account: {summary['binance_account']}")
print(f"ContextCol User: {summary['contextcol_user']}")
print(f"Recent Activities: {summary['recent_activities']}")
ContextCol API Endpoints
The SDK supports all major ContextCol API endpoints:
POST /trading-bot-activity- Create trading bot activityPOST /trading-bot-activity/:id/test- Test trading bot activityPOST /binance/spot/transaction- Create Binance spot transactionPOST /binance/spot/transaction/test- Test Binance spot transaction
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support, please contact khemmapich@gmail.com or create an issue on GitHub.
Changelog
0.1.0
- Initial release
- Binance API integration
- ContextCol API integration
- Comprehensive error handling
- Type hints support
- Configuration management
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 contextcol_binance_spot_sdk-0.1.4.tar.gz.
File metadata
- Download URL: contextcol_binance_spot_sdk-0.1.4.tar.gz
- Upload date:
- Size: 18.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.12.3 Darwin/24.3.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1b83c87e1ae176784faf0d1325ee2dfeaffaac8b071f204b3a7719dd5892feb1
|
|
| MD5 |
a9cc50bb40bc36bcde399519a5065fd4
|
|
| BLAKE2b-256 |
604773c9bd11b141241053ca5861be784770a4e44b1a63cc3c1528fb8e755f47
|
File details
Details for the file contextcol_binance_spot_sdk-0.1.4-py3-none-any.whl.
File metadata
- Download URL: contextcol_binance_spot_sdk-0.1.4-py3-none-any.whl
- Upload date:
- Size: 21.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.0.1 CPython/3.12.3 Darwin/24.3.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
978160a8a3a996b95c813a88f20932da5f326e6232b7f166418d0eb7df2464a1
|
|
| MD5 |
2333851c9c108a6586181bb3d9b9f96b
|
|
| BLAKE2b-256 |
a7a74f78cc7a669980b4720054616a67625f2a1e483758f027471adf1a26cfbc
|