Buying Units Programmatically

Start interacting with our Trading API to buy units programmatically using the following steps.

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}')
2

Register the Public Key

Open your app and head to API Keysarrow-up-right. Follow the following steps to register your API key and obtain a fingerprint for that key.

[Insert Product Screenshots]

3

Choose an instrument, and send a buy order

Use the fingerprint in the following script to Market or Limit Buy 1 Unit of your chosen Instrument (Chat Fast or Chat Prime).

  • Chat Fast: suited for latency-sensitive UX, high throughput, instantaneous responses

  • Chat Prime: suited for higher reasoning quality, thoughtful or calculative responses, deeper workflows

Read more about Current Instruments to guide your decision.

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

Note: Today, Units bought in your Trading Account transfer to your Consumption Account automatically. You can use this script to check the Units that have been transferred to your Consumption account and are active.

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
  • Use our Onboarding Guides for ready-to-go scripts to automate your buying and inference consumption on The Grid. These scripts cover common use cases for production implementation.

  • To ensure performant and efficient service, follow our Best Practices for moving your workloads from other inference providers/aggregators to The Grid

Last updated

Was this helpful?