Requesting a Python example how to place an order using Coinbase Advanced Trade API

Can someone please provide a working example how to place a buy or sell order on Coinbase Advanced Trade API using Python? I have an application which currently uses Coinbase Pro. I am unable to migrate it until I get this working. The documentation for the new API doesn’t work. I’ve tried a message in this forum a few months back and nobody responded. I’ve tried chat GPT but the code does not work. I just need some basic code to show how the signing works and how to place an order. I can work out the rest.

Here ya go. Not sure it’s the best example, it’s just a generic demo I was playing around with a while ago, but I just tested it and it works. Obviously you’ll want to replace the parameters (api secret, key, etc), but this should get you started. Something worth noting is that you need a unique client_order_id for every order. I just have it in there as whatever8 and was just changing the number as I tested, but if you use the same id for a future order, Coinbase will just return you the details of the first order to use that id.

import requests
from requests.auth import AuthBase
import hmac
import hashlib
import time
import json

api_key = 'xxxxxxxxx'
api_secret = 'xxxxxxxxx'

api_url = 'https://coinbase.com'
orderep = '/api/v3/brokerage/orders'
payload = {
    "side": "BUY",
    "order_configuration": {
        "limit_limit_gtc": {
            "base_size": "0.001",
            "limit_price": "1000"
        },
    },
    "product_id": "BTC-USD",
    "client_order_id": "whatever8"
}

class CBAuth(AuthBase):

    def __init__(self, api_secret, api_key, orderep):
        # setup any auth-related data here
        self.api_secret = api_secret
        self.api_key = api_key
        self.api_url = orderep
        print(api_secret, api_key, api_url)

    def __call__(self, request):
        timestamp = str(int(time.time()))
        message = timestamp + request.method + self.api_url + json.dumps(payload)
        signature = hmac.new(self.api_secret.encode(
            'utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).digest()

        request.headers.update({
            'CB-ACCESS-SIGN': signature.hex(),
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-KEY': api_key,
            'accept': "application/json"

        })
        print(message, '<--- MESSAGE!!!!')
        print(request.headers)
        return request

auth = CBAuth(api_secret, api_key, orderep)
print(api_secret, api_key, orderep)

print(api_url)
print(orderep)
print(api_url + orderep)
r = requests.post(api_url + orderep, json=payload, auth=auth)  # .json()
print(r)

That’s great, thank you. I’ll try it out.

Check out my post from today! It doesn’t have a full buy-sell execution but it does have the authentication set up in a fairly simple way. Feel free to ask if any of it is confusing!

I got it working, thanks. I’ll share my code when it’s finished.

2 Likes