[Python] Create market order example

Hello,

I’d like to share a Python script that I made to create a market (buy) order. It was largely inspired by this example Trying to create limit_limit_gtd sell order.

The example allowed me to understand how to fill-in payload and headers, especially since payload is not updated in the reference guide example Create Order | Coinbase Cloud with the entries specified under order_configuration.

One important thing that I did was to add a random client_order_id generator. I realized that the order needs a new ID every time otherwise it just outputs the same (previous) order all the time. This was confirmed here Creating Order Sometimes Returns Old Orders?.

For the beginners, another caveat is related to account permissions, see Source Account Not Tradable - #6 by adamastor

#!/usr/bin/env python3

import http.client
import hmac
import hashlib
import time
import json
import datetime
import base64
import numpy as np

timestamp = str(int(time.time()))

secretKey='***'
accessKey='***'

conn = http.client.HTTPSConnection("api.coinbase.com")
method = "POST"
path = "/api/v3/brokerage/orders"
int_order_id = np.random.randint(2**63)

payload = "{\"client_order_id\":" + "\"" + str(int_order_id) + "\"" + ",\"product_id\":\"BTC-EUR\",\"side\":\"BUY\",\"order_configuration\": {\"market_market_ioc\": {\"quote_size\":\"5\"}}}"
message = timestamp + method + path.split('?')[0] + str(payload)
signature = hmac.new(secretKey.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()

headers={
'CB-ACCESS-KEY': accessKey,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-SIGN': signature,
'accept':'application/json'
}

print(payload)
conn.request(method, path, payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Thanks for sharing this example. I discovered this after 3 hours of head scratching - trying to code this same example by hand.
Cheers!

@adamastor, when I run your code i get the error that the unique order id is too large for int 32 so i had to use 2**31 or i would get an error but i think that i get a bad gateway response because my order id is too short.

Thank you for the client_order_id generator. The information will be a great help.

Thanks for posting this. It will help a great deal. Do you have a similar example in Python for the websocket?