Working with Trading and Consumption Balances
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']})")
# Currency balance (USD)
currency_path = '/api/v1/trading/currency-trading-accounts'
currency_resp = requests.get(f'{BASE_URL}{currency_path}', headers=auth.get_headers('GET', currency_path))
currency_resp.raise_for_status()
print('=== Currency Balance ===')
for acct in currency_resp.json()['data']:
print(f"{acct['currency'].upper()}: ${acct['available_balance']} available, ${acct['total_balance']} total")
# Trading accounts (instruments)
trading_path = '/api/v1/trading/trading-accounts'
trading_resp = requests.get(f'{BASE_URL}{trading_path}', headers=auth.get_headers('GET', trading_path))
trading_resp.raise_for_status()
print('\n=== Trading Accounts ===')
for acct in trading_resp.json()['data']:
print(f"{acct['instrument_symbol']}: {acct['available_balance']} available, {acct['total_balance']} total")
Last updated
Was this helpful?