Skip to main content

Python Sample for the Ember REST API

The following code demonstrates how to access the Ember REST API from Python. Additionally, this sample shows how to obtain REST API credentials from the KeyCloak service and perform a simple order submission.

import requests
import json
import hashlib
import hmac
import datetime
import uuid

API_KEY = 'w6AcfksrG7GiEFoN'
SECRET = 'gZ0kkI9p8bHHDaBjO3Cyij87SrToYPA3'
KEYCLOAK_URL = "http://localhost:8080"
USER = "admin"
PASSWORD = "deltixadmin"
CLIENT_ID = 'ember_monitor'

#get keycloak token to work with ember monitor
def getKeycloakToken():

header = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'password',
'client_id': CLIENT_ID,
'username': USER,
'password': PASSWORD,
'scope': 'openid',
}
response = requests.post(KEYCLOAK_URL + "/auth/realms/marketmaker/protocol/openid-connect/token", headers=header, data=data)
accessDetails = response.json()
return accessDetails

accessData = getKeycloakToken()
token = accessData["access_token"]

order = json.dumps({
"orderId": uuid.uuid4().hex,
"timestamp": datetime.datetime.utcnow().isoformat(),
"side": "BUY",
"quantity": 1,
"symbol": "BTCUSD",
"orderType": "LIMIT",
"destinationId": "DERIBIT",
"limitPrice": 37000,
"timeInForce": "GOOD_TILL_CANCEL",
"exchangeId": "COINBASE"
});

signature = hmac.new(SECRET.encode('utf-8'), order.encode('utf-8'), hashlib.sha384).hexdigest()

headers = {
"Content-Type": "application/json",
'Authorization': 'bearer ' + token, #use token from keycloak for ember api requests
"X-API-KEY": API_KEY,
"X-SIGNATURE": signature,
}

response = requests.post('http://localhost:8988/api/v1/order/new', data=order, headers=headers)

print("Server responded with [%s] %s" % (response.status_code, response.text))