![Maven Central Adds Sigstore Signature Validation](https://cdn.sanity.io/images/cgdhsj6q/production/7da3bc8a946cfb5df15d7fcf49767faedc72b483-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Maven Central Adds Sigstore Signature Validation
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
coinbase-advancedtrade-python
Advanced tools
The unofficial Python client for the Coinbase Advanced Trade API
This is the unofficial Python client for the Coinbase Advanced Trade API. It allows users to interact with the API to manage their cryptocurrency trading activities on the Coinbase platform.
Install the package using pip:
pip install coinbase-advancedtrade-python
For development, install test dependencies:
pip install -e ".[test]"
Run tests:
python -m unittest discover -s coinbase_advanced_trader/tests
Obtain your API key and secret from the Coinbase Developer Platform. The new API key format looks like:
API Key: organizations/{org_id}/apiKeys/{key_id}
API Secret: -----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n
Here's an example of how to authenticate using the new method:
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient
api_key = "organizations/{org_id}/apiKeys/{key_id}"
api_secret = "-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n"
client = EnhancedRESTClient(api_key=api_key, api_secret=api_secret)
The EnhancedRESTClient
inherits from the Coinbase SDK's RESTClient
, which means you can use all the functions provided by the official SDK. Here's an example of how to use the get_product
function:
product_info = client.get_product(product_id="BTC-USDC")
print(product_info)
Here's an example of how to use the strategies package to buy $10 worth of Bitcoin. By making assumptions about limit price in trading_config.py we are able to simplify the syntax for making orders:
# Perform a market buy
client.fiat_market_buy("BTC-USDC", "10")
#Place a $10 buy order for BTC-USD near the current spot price of BTC-USDC
client.fiat_limit_buy("BTC-USDC", "10")
#Place a $10 buy order for BTC-USD at a limit price of $10,000
client.fiat_limit_buy("BTC-USDC", "10", "10000")
#Place a $10 buy order for BTC-USD at a 10% discount from the current spot price of BTC-USDC
client.fiat_limit_buy("BTC-USDC", "10", price_multiplier=".90")
#Place a $10 sell order for BTC-USD at a limit price of $100,000
client.fiat_limit_sell("BTC-USDC", "10", "100000")
#Place a $10 sell order for BTC-USD near the current spot price of BTC-USDC
client.fiat_limit_sell("BTC-USDC", "5")
#Place a $10 sell order for BTC-USD at a 10% premium to the current spot price of BTC-USDC
client.fiat_limit_sell("BTC-USDC", "5", price_multiplier="1.1")
The EnhancedRESTClient
provides methods to retrieve account balances for cryptocurrencies. These methods are particularly useful for managing and monitoring your cryptocurrency holdings on Coinbase.
To get a dictionary of all cryptocurrencies with non-zero balances in your account:
balances = client.list_held_crypto_balances()
print(balances)
To get the available balance of a specific cryptocurrency in your account, use get_crypto_balance
. It leverages the enhanced caching mechanism for efficient data retrieval and returns a Decimal balance (0 if no account is found):
balance = client.get_crypto_balance("BTC")
print(balance)
Note: Both methods use a caching mechanism to reduce API calls. The account data is cached for one hour before a fresh fetch is made from Coinbase.
In addition to retrieving basic balances, the EnhancedRESTClient
supports fetching detailed account information via the get_account_by_currency
method. This method:
When to Use This:
Use get_account_by_currency
if you need comprehensive details for a specific account—for example, when you need to verify account information prior to initiating deposits or withdrawals.
Example:
# Get detailed account info for the USD account
account = client.get_account_by_currency("USD")
if account:
print(f"Account UUID: {account.uuid}")
print(f"Account Name: {account.name}")
print(f"Balance: {account.available_balance} {account.currency}")
else:
print("No account found for USD")
You can deposit fiat (for example, USD) into your Coinbase account using the deposit functionality. The example below shows how to deposit $25 USD using known account and payment method IDs. (In real use, replace the placeholder IDs with your actual values.)
Example:
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient
# Initialize your client (ensure your API key and secret are set securely)
client = EnhancedRESTClient(api_key="your_api_key", api_secret="your_api_secret")
# Show available deposit methods run this before depositing to get the ID of your payment method (bank account, etc)
client.show_deposit_methods()
# Deposit $25 USD into your Coinbase account using known IDs
client.deposit_fiat(
account_id="your_usd_account_id", # Replace with your actual USD account ID (see get_account_by_currency)
payment_method_id="your_payment_method_id", # Replace with your actual payment method ID (see show_deposit_methods)
amount="25.00",
currency="USD"
)
All deposit details are logged automatically by the service. Be sure to use secure methods for storing and retrieving your keys and account identifiers.
The client uses the fear-and-greed-crypto package to fetch the current Fear and Greed Index value. This index helps determine market sentiment and automate trading decisions.
# Trade based on Fear and Greed Index
client.trade_based_on_fgi("BTC-USDC", "10")
You can customize the trading behavior by updating the Fear and Greed Index schedule:
# Get current FGI schedule
current_schedule = client.get_fgi_schedule()
# Update FGI schedule with custom thresholds and actions
new_schedule = [
{'threshold': 15, 'factor': 1.2, 'action': 'buy'}, # Buy more in extreme fear
{'threshold': 37, 'factor': 1.0, 'action': 'buy'}, # Buy normal amount in fear
{'threshold': 35, 'factor': 0.8, 'action': 'sell'}, # Sell some in greed
{'threshold': 45, 'factor': 0.6, 'action': 'sell'} # Sell more in extreme greed
]
client.update_fgi_schedule(new_schedule)
The schedule determines:
For example, with the above schedule:
This client now includes integration with AlphaSquared, allowing you to execute trading strategies based on AlphaSquared's risk analysis.
Obtain your AlphaSquared API key from AlphaSquared.
Initialize the AlphaSquared client along with the Coinbase client:
from coinbase_advanced_trader import EnhancedRESTClient, AlphaSquaredTrader
from alphasquared import AlphaSquared
# Initialize Coinbase client
coinbase_api_key = "YOUR_COINBASE_API_KEY"
coinbase_api_secret = "YOUR_COINBASE_API_SECRET"
coinbase_client = EnhancedRESTClient(api_key=coinbase_api_key, api_secret=coinbase_api_secret)
# Initialize AlphaSquared client
alphasquared_api_key = "YOUR_ALPHASQUARED_API_KEY"
alphasquared_client = AlphaSquared(alphasquared_api_key, cache_ttl=60)
# Create AlphaSquaredTrader
trader = AlphaSquaredTrader(coinbase_client, alphasquared_client)
To execute a trading strategy based on AlphaSquared's risk analysis:
# Set trading parameters
product_id = "BTC-USDC"
# Your custom strategy name from AlphaSquared
strategy_name = "My Custom Strategy"
# Execute strategy
trader.execute_strategy(product_id, strategy_name)
This will:
Note: Make sure to handle exceptions and implement proper logging in your production code. This integration only works with custom strategies; it does not work with the default strategies provided by AlphaSquared.
You can create custom strategies by modifying the execute_strategy
method in the AlphaSquaredTrader
class. This allows you to define specific trading logic based on the risk levels provided by AlphaSquared.
When using this package in AWS Lambda, ensure your Lambda function is configured to use Python 3.12. The cryptography binaries in the Lambda layer are compiled for Python 3.12, and using a different Python runtime version will result in compatibility issues.
To configure your Lambda function:
For more information about the Coinbase Advanced Trader API, consult the official API documentation.
This project is licensed under the MIT License. See the LICENSE file for more information.
Rhett Reisman
Email: rhett@rhett.blog
GitHub: https://github.com/rhettre/coinbase-advancedtrade-python
This project is not affiliated with, maintained, or endorsed by Coinbase. Use this software at your own risk. Trading cryptocurrencies carries a risk of financial loss. The developers of this software are not responsible for any financial losses or damages incurred while using this software. Nothing in this software should be seen as an inducement to trade with a particular strategy or as financial advice.
FAQs
The unofficial Python client for the Coinbase Advanced Trade API
We found that coinbase-advancedtrade-python demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.