Skip to main content

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 activity
  • POST /trading-bot-activity/:id/test - Test trading bot activity
  • POST /binance/spot/transaction - Create Binance spot transaction
  • POST /binance/spot/transaction/test - Test Binance spot transaction

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contextcol_binance_spot_sdk-0.1.3.tar.gz (19.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

contextcol_binance_spot_sdk-0.1.3-py3-none-any.whl (21.6 kB view details)

Uploaded Python 3

File details

Details for the file contextcol_binance_spot_sdk-0.1.3.tar.gz.

File metadata

  • Download URL: contextcol_binance_spot_sdk-0.1.3.tar.gz
  • Upload date:
  • Size: 19.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.0.1 CPython/3.12.3 Darwin/24.3.0

File hashes

Hashes for contextcol_binance_spot_sdk-0.1.3.tar.gz
Algorithm Hash digest
SHA256 953748d5f7148e2261477a0f8f562f344d82833093eb43450de8d12c1bc70ce7
MD5 0d8b7270216c51063186958f4f1474e7
BLAKE2b-256 dfbb77ef353c9c9f45ab16f5c54e22a0860e61ff5300f33717598b013a76cc57

See more details on using hashes here.

File details

Details for the file contextcol_binance_spot_sdk-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for contextcol_binance_spot_sdk-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 41741dcc313a33e500def046c4f43313aa5185bac0b78800843dc3b2e1e2124d
MD5 283c647a8fae7342121c71ba0edf9718
BLAKE2b-256 1d4986686c6b745b0ec9aedcc2108cc1b6fe6a0ece91ff529a9ecc0ad5a65ffa

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page