| Here's a basic example of using the Coinbase Python API to check the price of a cryptocurrency and place buy or sell orders. This requires the coinbase Python library, which you can install via pip install coinbase. Note: Replace 'API_KEY' and 'API_SECRET' with your actual API key and secret, which you can create on your Coinbase account under API settings. Make sure your API key has the appropriate permissions for trading. Setup # Install the Coinbase library
!pip install coinbase
Import Libraries and Set Up API Client from coinbase.wallet.client import Client
# Initialize the client
API_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'
client = Client(API_KEY, API_SECRET)
Check Price def check_price(currency_pair='BTC-USD'):
price = client.get_spot_price(currency_pair=currency_pair)
print(f"The current price of {currency_pair} is: {price['amount']} {price['currency']}")
return price['amount']
# Check price of Bitcoin in USD
check_price()
Place a Buy Order def place_buy_order(amount, currency='BTC', currency_pair='BTC-USD'):
buy = client.buy(
account_id='YOUR_ACCOUNT_ID', # Replace with your Coinbase account ID for the asset
amount=amount,
currency=currency,
payment_method='YOUR_PAYMENT_METHOD_ID' # Replace with your payment method ID
)
print(f"Placed a buy order for {amount} {currency}. Transaction details:", buy)
return buy
# Example: Buy 0.001 BTC
place_buy_order(0.001)
Place a Sell Order def place_sell_order(amount, currency='BTC', currency_pair='BTC-USD'):
sell = client.sell(
account_id='YOUR_ACCOUNT_ID', # Replace with your Coinbase account ID for the asset
amount=amount,
currency=currency,
payment_method='YOUR_PAYMENT_METHOD_ID' # Replace with your payment method ID
)
print(f"Placed a sell order for {amount} {currency}. Transaction details:", sell)
return sell
# Example: Sell 0.001 BTC
place_sell_order(0.001)
Notes: - Account ID: You can find your account ID in your Coinbase account or by using the
client.get_accounts() method. - Payment Method ID: Required for placing trades, find it by using
client.get_payment_methods().
This code allows checking prices and executing basic buy/sell orders. Make sure to test in a controlled environment or use a sandbox API if available, as transactions in live mode affect real funds. |