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"))