Buying Units Programmatically
Send your first Trading API request
1
Generate a Key Pair
from nacl.signing import SigningKey
import base64
private_key = SigningKey.generate()
public_key = private_key.verify_key
private_key_b64 = base64.b64encode(bytes(private_key)).decode()
public_key_b64 = base64.b64encode(bytes(public_key)).decode()
print(f'Private Key: {private_key_b64}')
print(f'Public Key: {public_key_b64}')import nacl from 'tweetnacl';
import util from 'tweetnacl-util';
const keyPair = nacl.sign.keyPair();
const privateKey = util.encodeBase64(keyPair.secretKey);
const publicKey = util.encodeBase64(keyPair.publicKey);
console.log('Private Key:', privateKey);
console.log('Public Key:', publicKey);
3
Choose an instrument, and send a buy order
import base64
import json
import os
import time
import requests
from nacl.signing import SigningKey
BASE_URL = "https://trading.api.thegrid.ai"
class SignatureAuth:
def __init__(self, private_key_b64, fingerprint):
self.private_key = SigningKey(base64.b64decode(private_key_b64)[:32])
self.fingerprint = fingerprint
def get_headers(self, method, path, body=""):
timestamp = str(int(time.time()))
message = f"{timestamp}{method.upper()}{path}{body}"
signature = self.private_key.sign(message.encode()).signature
return {
"x-thegrid-signature": base64.b64encode(signature).decode(),
"x-thegrid-timestamp": timestamp,
"x-thegrid-fingerprint": self.fingerprint,
}
auth = SignatureAuth(
os.environ["GRID_TRADING_PRIVATE_KEY"],
os.environ["GRID_TRADING_FINGERPRINT"],
)
order_data = {
"market_id": "market_788dcbd5-ac68-4c61-acf1-4443beaf2a1c",
"side": "buy",
"type": "limit",
"quantity": 1,
"price": "2.50",
"time_in_force": "gtc",
"client_order_id": f"buy-{int(time.time())}",
}
path = "/api/v1/trading/orders"
body = json.dumps(order_data)
headers = auth.get_headers("POST", path, body)
headers["Content-Type"] = "application/json"
response = requests.post(f"{BASE_URL}{path}", data=body, headers=headers)
response.raise_for_status()
print("Order ID:", response.json()["data"]["order_id"])
4
See the Unit transferred to your Consumption Account
import base64
import os
import time
import requests
from nacl.signing import SigningKey
BASE_URL = "https://trading.api.thegrid.ai"
class SignatureAuth:
def __init__(self, private_key_b64, fingerprint):
self.private_key = SigningKey(base64.b64decode(private_key_b64)[:32])
self.fingerprint = fingerprint
def get_headers(self, method, path, body=""):
timestamp = str(int(time.time()))
message = f"{timestamp}{method.upper()}{path}{body}"
signature = self.private_key.sign(message.encode()).signature
return {
"x-thegrid-signature": base64.b64encode(signature).decode(),
"x-thegrid-timestamp": timestamp,
"x-thegrid-fingerprint": self.fingerprint,
}
auth = SignatureAuth(
os.environ["GRID_TRADING_PRIVATE_KEY"],
os.environ["GRID_TRADING_FINGERPRINT"],
)
# Consumption accounts
consumption_path = "/api/v1/trading/consumption-accounts"
consumption_resp = requests.get(
f"{BASE_URL}{consumption_path}?order_by=created_at",
headers=auth.get_headers("GET", consumption_path),
)
consumption_resp.raise_for_status()
print("=== Consumption Accounts ===")
for acct in consumption_resp.json()["data"]:
print(
f"{acct['account_id']}: {acct['available_balance']} available, {acct['total_balance']} total (instrument {acct['instrument_id']})"
)
5
Last updated
Was this helpful?