A clean, reusable Python library for fetching OHLCV data from multiple providers (Binance, Twelve Data) with flexible provider selection
Project description
Candlecraft
A production-ready Python library for fetching OHLCV data from Cryptocurrency, Forex, and U.S. Equities markets.
📦 Package on PyPI | 📚 Documentation | ⚖️ License: MIT
Data Sources
Candlecraft supports multiple data providers, giving you flexibility to choose the best option for your needs:
- Twelve Data Finance - Comprehensive market data for Forex, U.S. Equities, and Cryptocurrency
- Binance - Leading cryptocurrency exchange with public API access
- More providers coming soon! - We're continuously adding support for additional data sources
You can choose which provider to use, or let Candlecraft automatically select the best available option based on your asset class and configured API keys.
Candlecraft Library
candlecraft is a Python library for fetching OHLCV data from multiple providers. Published on PyPI.
Current Version: v0.1.4
What's New in v0.1.4
- 🔄 Branch Consolidation - Merged master into main, unified codebase
- 🏷️ Repository Updates - Updated to new Candlecraft repository structure
What's New in v0.1.3
- ✨ Provider Selection - Choose which data provider to use (Binance or Twelve Data)
- 🔍 Provider Availability Checks - Check which providers are available before fetching data
- 🛡️ Better Error Messages - Clear guidance when providers aren't configured
- 🔄 Smart Fallbacks - Automatic provider selection with intelligent fallbacks
- 📚 Enhanced Documentation - Comprehensive examples and troubleshooting guide
Installation
pip install candlecraft
Quick Start
from candlecraft import fetch_ohlcv, OHLCV, AssetClass, Provider
# Fetch OHLCV data (auto-detects asset class and provider)
data = fetch_ohlcv(
symbol="BTCUSDT",
timeframe="1h",
limit=100
)
# Access OHLCV data
for candle in data:
print(f"{candle.timestamp}: {candle.close}")
# Explicit asset class
data = fetch_ohlcv(
symbol="EUR/USD",
timeframe="1h",
asset_class=AssetClass.FOREX,
limit=50
)
# Choose a specific provider
data = fetch_ohlcv(
symbol="BTCUSDT",
timeframe="1h",
provider=Provider.TWELVEDATA, # Use Twelve Data instead of default Binance
limit=100
)
# Check available providers
from candlecraft import get_available_providers
available = get_available_providers()
print(f"Available providers: {[p.value for p in available]}")
API Reference
fetch_ohlcv()- Fetch OHLCV data from appropriate providerlist_indicators()- List available technical indicatorsget_available_providers()- Get list of available providersis_provider_available()- Check if a specific provider is availableOHLCV- Data model for OHLCV candlesAssetClass- Enum for asset class types (CRYPTO, FOREX, EQUITY)Provider- Enum for provider types (BINANCE, TWELVEDATA)
Configuration
Set environment variables for API authentication:
# Binance API (Optional - for higher rate limits)
export BINANCE_API_KEY=your_key_here
export BINANCE_API_SECRET=your_secret_here
# Twelve Data API (Required for Forex and US Equities)
export TWELVEDATA_SECRET=your_key_here
API Keys:
- Binance: API Management (optional, works without keys for public data)
- Twelve Data: Sign up (required for Forex/Equities)
Rate Limits & Provider Behavior
Candlecraft does not enforce rate limits by default. Market data providers apply their own rate limits based on your subscription plan, and these limits vary significantly between free tiers and paid plans.
When rate limits are exceeded, providers may return HTTP status codes (such as 429) along with retry-after information indicating when you can make your next request. By default, Candlecraft will raise a RateLimitException when a rate limit is encountered, allowing you to implement your own retry logic, backoff strategies, or error handling as appropriate for your application.
Candlecraft provides an optional opt-in mechanism for automatic waiting. If you explicitly enable rate_limit_strategy="sleep", the library will wait for the provider-specified retry duration before retrying the request. This is useful for simple scripts or applications where automatic waiting is acceptable.
Example with default behavior (fail fast):
from candlecraft import fetch_ohlcv, RateLimitException
try:
data = fetch_ohlcv(symbol="AAPL", timeframe="1h", limit=100)
except RateLimitException as e:
print(f"Rate limit hit for {e.provider}")
print(f"Retry after {e.retry_after} seconds")
# Implement your own retry logic here
Example with opt-in automatic waiting:
from candlecraft import fetch_ohlcv
# Automatically wait and retry on rate limits
data = fetch_ohlcv(
symbol="AAPL",
timeframe="1h",
limit=100,
rate_limit_strategy="sleep"
)
Users are responsible for implementing rate limiting, retries, or backoff logic in their own applications based on their specific needs and subscription plans.
Provider Selection
Candlecraft allows you to choose which provider to use for fetching data. This is especially useful if you only have API keys for one provider. The library will automatically select the best available provider, but you can also specify one explicitly.
Why Provider Selection Matters:
- Use the provider you have API keys for
- Avoid errors when a default provider isn't configured
- Flexibility to switch between providers based on your needs
Example: Using a specific provider
from candlecraft import fetch_ohlcv, Provider
# Use Twelve Data for crypto (if you don't have Binance API)
data = fetch_ohlcv(
symbol="BTCUSDT",
timeframe="1h",
provider=Provider.TWELVEDATA, # Explicitly choose Twelve Data
limit=100
)
# Use Binance for crypto (default, but explicit)
data = fetch_ohlcv(
symbol="ETHUSDT",
timeframe="1h",
provider=Provider.BINANCE,
limit=100
)
Example: Check available providers
from candlecraft import get_available_providers, is_provider_available, Provider
# Get all available providers
available = get_available_providers()
print(f"Available providers: {[p.value for p in available]}")
# Check specific provider
if is_provider_available(Provider.BINANCE):
print("✓ Binance is available")
if is_provider_available(Provider.TWELVEDATA):
print("✓ Twelve Data is available")
Default Provider Selection:
- Cryptocurrency: Binance (if available), automatically falls back to Twelve Data
- Forex: Twelve Data (required)
- U.S. Equities: Twelve Data (required)
If no provider is specified, the library automatically selects an available provider based on the asset class. If your preferred provider isn't available, you'll get a clear error message with instructions on how to set it up.
Supported Asset Classes
| Asset Class | Default Provider | Alternative Provider | Example Symbols |
|---|---|---|---|
| Cryptocurrency | Binance | Twelve Data | BTCUSDT, ETHUSDT, BNBUSDT |
| Forex | Twelve Data | - | EUR/USD, GBP/USD, USD/JPY |
| U.S. Equities | Twelve Data | - | AAPL, MSFT, TSLA, GOOGL |
Supported Timeframes
1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M
CLI Interface (Optional)
pull_ohlcv.py is a command-line interface for the same functionality. Use this repository for CLI access or development.
Installation (CLI)
git clone https://github.com/alfredalpino/Candlecraft.git
cd Candlecraft
python -m venv dpa
source dpa/bin/activate # On Windows: dpa\Scripts\activate
pip install -r requirements.txt
Quick Start (CLI)
# Cryptocurrency
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --limit 100
# Forex
python pull_ohlcv.py --symbol EUR/USD --timeframe 1h --limit 100
# U.S. Equities
python pull_ohlcv.py --symbol AAPL --timeframe 1h --limit 100
# Real-time streaming
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --stream
# Polling mode (Forex/Equities)
python pull_ohlcv.py --symbol EUR/USD --timeframe 1m --limit 1 --poll
Historical Data
# Fetch last N candles
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --limit 100
# Fetch by date range
python pull_ohlcv.py --symbol AAPL --timeframe 1d --start 2024-01-01 --end 2024-01-31
# Output formats
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --limit 10 --format csv
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --limit 10 --format json
Real-time Streaming
# Stream only
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --stream
# Fetch historical, then stream
python pull_ohlcv.py --symbol BTCUSDT --timeframe 1h --limit 100 --stream
Polling Mode (Forex/Equities)
# Poll for latest candle every 60 seconds
python pull_ohlcv.py --symbol EUR/USD --timeframe 1m --limit 1 --poll
Command Reference
Required Arguments:
--symbol: Trading pair or stock symbol--timeframe: Time interval (required for historical data)
Optional Arguments:
--limit N: Fetch last N candles--start YYYY-MM-DD: Start date (requires--end)--end YYYY-MM-DD: End date (requires--start)--format {table,csv,json}: Output format (default: table)--stream: Enable WebSocket streaming--poll: Enable polling mode (60s intervals, Forex/Equities only)--timezone TZ: Timezone (e.g.,UTC,America/New_York)--indicator NAME: Calculate technical indicator (e.g.,macd)
Output Formats
- Table (default): Formatted table output
- CSV: Comma-separated values
- JSON: JSON array of OHLCV objects
Rate Limiting (CLI)
The CLI interface (pull_ohlcv.py) includes built-in rate limiting for convenience. This behavior is separate from the library's default behavior.
- Binance: Public access unlimited; with API keys: 1200 requests/minute
- Twelve Data (Free Tier): 1 REST API request per minute (automatically handled in CLI)
- Polling Mode: Automatically respects rate limits with 60-second intervals
Troubleshooting
1. "TWELVEDATA_SECRET environment variable not set"
export TWELVEDATA_SECRET=your_key_here
# Or add to .env file
2. "No provider available for crypto" If you only have Twelve Data API keys and want to fetch crypto data:
from candlecraft import fetch_ohlcv, Provider
# Explicitly use Twelve Data for crypto
data = fetch_ohlcv(
symbol="BTCUSDT", # or use Twelve Data format like "BTC/USD"
timeframe="1h",
provider=Provider.TWELVEDATA,
limit=100
)
3. "ModuleNotFoundError"
source dpa/bin/activate
pip install -r requirements.txt
4. "Subscription failed" (WebSocket)
- Free tier may not support WebSocket for all symbols
- Use polling mode instead:
--poll - Check your Twelve Data plan tier
5. "Provider not available" Check which providers are available:
from candlecraft import get_available_providers, is_provider_available, Provider
available = get_available_providers()
print(f"Available providers: {[p.value for p in available]}")
# Check specific provider
if is_provider_available(Provider.BINANCE):
print("Binance is available")
Legacy Scripts
The following scripts are legacy/development-only and should not be used in production:
pull_fx.py- Usepull_ohlcv.pyinsteadpull_us-eq.py- Usepull_ohlcv.pyinsteadmy_ohlcv.py- Usepull_ohlcv.pyinstead
All functionality is available in pull_ohlcv.py.
License
MIT License - See LICENSE for details.
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
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 candlecraft-0.1.4.tar.gz.
File metadata
- Download URL: candlecraft-0.1.4.tar.gz
- Upload date:
- Size: 23.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7f997ab87135115579770343febecdeac06c406c2cfbefc9f5338544fea53fec
|
|
| MD5 |
1e88847773f70e552eb889cd241ebdbb
|
|
| BLAKE2b-256 |
5be827d9c2d01d600294310d759381fda91caeca487d35e44eddf2a3e36b30ca
|
Provenance
The following attestation bundles were made for candlecraft-0.1.4.tar.gz:
Publisher:
publish.yml on alfredalpino/Candlecraft
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
candlecraft-0.1.4.tar.gz -
Subject digest:
7f997ab87135115579770343febecdeac06c406c2cfbefc9f5338544fea53fec - Sigstore transparency entry: 824143692
- Sigstore integration time:
-
Permalink:
alfredalpino/Candlecraft@c0c15fb2e2c6fc763ba8522e35f0202bb0243e41 -
Branch / Tag:
refs/tags/v0.1.4 - Owner: https://github.com/alfredalpino
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@c0c15fb2e2c6fc763ba8522e35f0202bb0243e41 -
Trigger Event:
push
-
Statement type:
File details
Details for the file candlecraft-0.1.4-py3-none-any.whl.
File metadata
- Download URL: candlecraft-0.1.4-py3-none-any.whl
- Upload date:
- Size: 14.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8f80e09beb483df48a3ac30669d428c8f8fe1e9bc04744a963540ba152934c27
|
|
| MD5 |
45d447c922acb159083a236b1b63849f
|
|
| BLAKE2b-256 |
dc47b3de6e90a8b8efb4a801d33f7a7f382b2a5aa786e39e78b535299f720ab5
|
Provenance
The following attestation bundles were made for candlecraft-0.1.4-py3-none-any.whl:
Publisher:
publish.yml on alfredalpino/Candlecraft
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
candlecraft-0.1.4-py3-none-any.whl -
Subject digest:
8f80e09beb483df48a3ac30669d428c8f8fe1e9bc04744a963540ba152934c27 - Sigstore transparency entry: 824143745
- Sigstore integration time:
-
Permalink:
alfredalpino/Candlecraft@c0c15fb2e2c6fc763ba8522e35f0202bb0243e41 -
Branch / Tag:
refs/tags/v0.1.4 - Owner: https://github.com/alfredalpino
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@c0c15fb2e2c6fc763ba8522e35f0202bb0243e41 -
Trigger Event:
push
-
Statement type: