Coinbase Python API - Basic Example

CK CK 3788 
Created at
Updated at  
464 0 0

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:

  1. Account ID: You can find your account ID in your Coinbase account or by using the client.get_accounts() method.
  2. 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.

Tags Coinbase Coinbase Python API Crypto Currency Facebook X
Comments 0
Similar posts
  1. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    365
  2. PHP Code to Fetch current Coinbase Assets (Balances)
    443
  1. How to run Python 3.9 on Mac?
    656
  2. Python Quizs
    502
  3. Automated OpenAPI documentation for a Python Flask API
    1,125
  4. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,032
  5. Uploading a file to a Google Drive Folder programmatically with Python
    3,309
  6. Garbage Collection when your system does not have enough memory in your Python App
    1,021
  7. Method to maximize full CPU performance with Python
    325
  8. How do I get the maximum available of thread in python?
    994
  9. Using Queue Algorithm with Redis - RPUSH and LPOP
    774
  10. Use cache concept with Redis : Let's do Redis programming with Python
    539
  11. Installing Python 3.8 in a venv environment on CentOS 7
    465
  12. CUDA versus OpenCL
    584
  13. Simple gRPC server based on Python
    398
  14. Python code to convert PDF file to Excel Spreadsheet
    705
  15. Python script to list files on your Google Drive and download one of them
    941
  16. AWS Lambda Code Example based on Python
    334
  17. Python code using GPU on CentOS with AWS
    1,258
  18. Video Scence Detection with PySceneDetect
    2,338
  19. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,452
  20. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    912
  21. Deleting a specific user voice from the original audio track with Python
    553
  22. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    443
  23. Creating mp3 audio file based on the text input with Python
    469
  24. Implementing Text To Speech / Audio with Python3 and pyttsx3
    357
  25. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    560
  26. Python Simplified Assignment Operators
    535
  27. Trackback module used for Python Threading debugging
    847
  28. Python Flask with simple HTML files to server web pages along with API
    931
  29. Python Flask web server tutorial from the scratch
    626
  30. Simple Web Server based in Python
    381
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    28
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,829
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232