Quick Start
This guide walks you through the complete journey from installation to executing your first trade on Cadenza.
Prerequisites
- A Cadenza account (email/password)
- Exchange API credentials (see Supported Venues for setup instructions)
Language requirements:
- Python: Python 3.9+
- TypeScript: Node.js 18+
- Go: Go 1.21+
1. Installation
- Python
- TypeScript
- Go
pip install git+https://github.com/cyberapper/cadenza-client-python.git
npm install cadenza-client-typescript@github:cyberapper/cadenza-client-typescript#v3.0.0
go get github.com/cyberapper/cadenza-client-go
2. Environment Configuration
| Environment | HTTP API | WebSocket |
|---|---|---|
| Production | https://cadenza-api.algo724.com | wss://cadenza-ws.algo724.com |
| UAT | https://cadenza-api-uat.algo724.com | wss://cadenza-ws-uat.algo724.com |
- Python
- TypeScript
- Go
# Production Environment
BASE_URL = "https://cadenza-api.algo724.com"
WS_URL = "wss://cadenza-ws.algo724.com/connection/websocket"
# UAT Environment
# BASE_URL = "https://cadenza-api-uat.algo724.com"
# WS_URL = "wss://cadenza-ws-uat.algo724.com/connection/websocket"
// Production Environment
const CADENZA_API_URL = 'https://cadenza-api.algo724.com'
const CADENZA_WS_URL = 'wss://cadenza-ws.algo724.com/connection/websocket'
// UAT Environment
// const CADENZA_API_URL = 'https://cadenza-api-uat.algo724.com'
// const CADENZA_WS_URL = 'wss://cadenza-ws-uat.algo724.com/connection/websocket'
package main
const (
// Production Environment
BaseURL = "https://cadenza-api.algo724.com"
WsURL = "wss://cadenza-ws.algo724.com/connection/websocket"
// UAT Environment
// BaseURL = "https://cadenza-api-uat.algo724.com"
// WsURL = "wss://cadenza-ws-uat.algo724.com/connection/websocket"
)
3. Authentication
Log in with your Cadenza account to get an access token:
- Python
- TypeScript
- Go
import cadenza_client
# Create configuration
configuration = cadenza_client.Configuration(host=BASE_URL)
# Login to get access token
with cadenza_client.ApiClient(configuration) as api_client:
auth_api = cadenza_client.AuthenticationApi(api_client)
response = auth_api.auth_login(
cadenza_client.AuthLoginRequest(
email="your@email.com",
password="your-password"
)
)
session = response.data
access_token = session.access_token
print(f"Logged in, expires at: {session.expires_at}")
import { Configuration, AuthenticationApi } from 'cadenza-client-typescript'
// Create configuration
const config = new Configuration({ basePath: CADENZA_API_URL })
const authApi = new AuthenticationApi(config)
// Login to get access token
const response = await authApi.authLogin({
email: 'your@email.com',
password: 'your-password',
})
const session = response.data.data
const accessToken = session.accessToken
console.log('Logged in, expires at:', session.expiresAt)
import (
"context"
"fmt"
client "github.com/cyberapper/cadenza-client-go"
)
// Create configuration
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{{URL: BaseURL}}
apiClient := client.NewAPIClient(cfg)
// Login to get access token
response, _, err := apiClient.AuthenticationAPI.AuthLogin(context.Background()).
AuthLoginRequest(client.AuthLoginRequest{
Email: "your@email.com",
Password: "your-password",
}).Execute()
if err != nil {
panic(err)
}
session := response.Data
accessToken := *session.AccessToken
fmt.Printf("Logged in, expires at: %v\n", *session.ExpiresAt)
4. Create API Client
Configure the API client with your access token:
- Python
- TypeScript
- Go
# Configure with access token
configuration = cadenza_client.Configuration(
host=BASE_URL,
access_token=access_token
)
# Create API client and instances
api_client = cadenza_client.ApiClient(configuration)
market_api = cadenza_client.MarketApi(api_client)
trade_order_api = cadenza_client.TradeOrderApi(api_client)
trading_account_api = cadenza_client.TradingAccountApi(api_client)
credential_api = cadenza_client.TradingAccountCredentialApi(api_client)
portfolio_api = cadenza_client.TradingAccountPortfolioApi(api_client)
import {
Configuration,
MarketApi,
TradeOrderApi,
TradingAccountApi,
TradingAccountCredentialApi,
TradingAccountPortfolioApi
} from 'cadenza-client-typescript'
// Create configuration with access token
const config = new Configuration({
basePath: CADENZA_API_URL,
accessToken: accessToken,
})
// Create API instances
const marketApi = new MarketApi(config)
const tradeOrderApi = new TradeOrderApi(config)
const tradingAccountApi = new TradingAccountApi(config)
const credentialApi = new TradingAccountCredentialApi(config)
const portfolioApi = new TradingAccountPortfolioApi(config)
// Configure with access token
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{{URL: BaseURL}}
apiClient := client.NewAPIClient(cfg)
// Create authenticated context
ctx := context.WithValue(context.Background(), client.ContextAccessToken, accessToken)
// Access APIs via apiClient
// apiClient.MarketAPI
// apiClient.TradeOrderAPI
// apiClient.TradingAccountAPI
// apiClient.TradingAccountCredentialAPI
// apiClient.TradingAccountPortfolioAPI
5. Check Available Venues
Verify which exchanges are available:
- Python
- TypeScript
- Go
response = market_api.list_market_venues()
venues = response.data
print("Available venues:")
for venue in venues:
print(f" - {venue.venue}")
const response = await marketApi.listMarketVenues()
const venues = response.data.data
console.log('Available venues:')
venues.forEach(venue => {
console.log(` - ${venue.venue}`)
})
response, _, err := apiClient.MarketAPI.ListMarketVenues(ctx).Execute()
if err != nil {
panic(err)
}
fmt.Println("Available venues:")
for _, venue := range response.Data {
fmt.Printf(" - %s\n", *venue.Venue)
}
6. Add Credential
Store your exchange API keys securely. See Supported Venues for exchange-specific setup instructions.
- Python
- TypeScript
- Go
# Create credential with your exchange API keys
response = credential_api.create_trading_account_credential(
cadenza_client.CreateTradingAccountCredentialRequest(
venue=cadenza_client.Venue.BINANCE,
credential_type=cadenza_client.CredentialType.EXCHANGE,
api_key="your-api-key",
api_secret="your-api-secret",
# api_passphrase="your-passphrase" # Required for OKX
nickname="My Binance API"
)
)
credential = response.data
credential_id = credential.credential_id
print(f"Credential created: {credential_id}")
print(f"Status: {credential.status}") # PENDING
// Create credential with your exchange API keys
const response = await credentialApi.createTradingAccountCredential({
venue: 'BINANCE',
credentialType: 'EXCHANGE',
apiKey: 'your-api-key',
apiSecret: 'your-api-secret',
// apiPassphrase: 'your-passphrase', // Required for OKX
nickname: 'My Binance API',
})
const credential = response.data.data
const credentialId = credential.credentialId
console.log('Credential created:', credentialId)
console.log('Status:', credential.status) // PENDING
// Create credential with your exchange API keys
response, _, err := apiClient.TradingAccountCredentialAPI.CreateTradingAccountCredential(ctx).
CreateTradingAccountCredentialRequest(client.CreateTradingAccountCredentialRequest{
Venue: client.VENUE_BINANCE,
CredentialType: client.CREDENTIALTYPE_EXCHANGE,
ApiKey: client.PtrString("your-api-key"),
ApiSecret: client.PtrString("your-api-secret"),
// ApiPassphrase: client.PtrString("your-passphrase"), // Required for OKX
Nickname: client.PtrString("My Binance API"),
}).Execute()
if err != nil {
panic(err)
}
credential := response.Data
credentialId := *credential.CredentialId
fmt.Printf("Credential created: %s\n", credentialId)
fmt.Printf("Status: %s\n", *credential.Status) // PENDING
Verify Credential
Verify your API keys and discover available trading accounts:
- Python
- TypeScript
- Go
response = credential_api.verify_trading_account_credential(
cadenza_client.VerifyTradingAccountCredentialRequest(
credential_id=credential_id
)
)
credential = response.data
print(f"Status: {credential.status}") # VERIFIED
# Available trading accounts on this exchange
print(f"Available accounts: {credential.identities}")
# Example: ['spot', 'margin', 'futures']
const response = await credentialApi.verifyTradingAccountCredential({
credentialId: credentialId,
})
const credential = response.data.data
console.log('Status:', credential.status) // VERIFIED
// Available trading accounts on this exchange
console.log('Available accounts:', credential.identities)
// Example: ['spot', 'margin', 'futures']
response, _, err := apiClient.TradingAccountCredentialAPI.VerifyTradingAccountCredential(ctx).
VerifyTradingAccountCredentialRequest(client.VerifyTradingAccountCredentialRequest{
CredentialId: credentialId,
}).Execute()
if err != nil {
panic(err)
}
credential := response.Data
fmt.Printf("Status: %s\n", *credential.Status) // VERIFIED
// Available trading accounts on this exchange
fmt.Printf("Available accounts: %v\n", credential.Identities)
// Example: ['spot', 'margin', 'futures']
7. Connect Trading Account
Connect an exchange account using your verified credential:
- Python
- TypeScript
- Go
response = trading_account_api.connect_trading_account(
cadenza_client.ConnectTradingAccountRequest(
credential_ids=[credential_id],
external_trading_account_id="spot", # From identities list
nickname="My Binance Spot"
)
)
account = response.data
trading_account_id = account.trading_account_id
print(f"Connected: {trading_account_id}")
print(f"Venue: {account.venue}")
print(f"Status: {account.status}") # CONNECTED
const response = await tradingAccountApi.connectTradingAccount({
credentialIds: [credentialId],
externalTradingAccountId: 'spot', // From identities list
nickname: 'My Binance Spot',
})
const account = response.data.data
const tradingAccountId = account.tradingAccountId
console.log('Connected:', tradingAccountId)
console.log('Venue:', account.venue)
console.log('Status:', account.status) // CONNECTED
response, _, err := apiClient.TradingAccountAPI.ConnectTradingAccount(ctx).
ConnectTradingAccountRequest(client.ConnectTradingAccountRequest{
CredentialIds: []string{credentialId},
ExternalTradingAccountId: "spot", // From identities list
Nickname: client.PtrString("My Binance Spot"),
}).Execute()
if err != nil {
panic(err)
}
account := response.Data
tradingAccountId := *account.TradingAccountId
fmt.Printf("Connected: %s\n", tradingAccountId)
fmt.Printf("Venue: %s\n", *account.Venue)
fmt.Printf("Status: %s\n", *account.Status) // CONNECTED
8. Check Portfolio
View your account balances:
- Python
- TypeScript
- Go
response = portfolio_api.list_trading_account_portfolios(
trading_account_id=trading_account_id
)
for portfolio in response.data:
print(f"Account: {portfolio.trading_account_id}")
print("Balances:")
for balance in portfolio.balances:
if float(balance.total) > 0:
print(f" {balance.asset}: {balance.total} (free: {balance.free}, locked: {balance.locked})")
const response = await portfolioApi.listTradingAccountPortfolios(
tradingAccountId
)
response.data.data.forEach(portfolio => {
console.log(`Account: ${portfolio.tradingAccountId}`)
console.log('Balances:')
portfolio.balances?.forEach(balance => {
if (parseFloat(balance.total || '0') > 0) {
console.log(` ${balance.asset}: ${balance.total} (free: ${balance.free}, locked: ${balance.locked})`)
}
})
})
response, _, err := apiClient.TradingAccountPortfolioAPI.ListTradingAccountPortfolios(ctx).
TradingAccountId(tradingAccountId).
Execute()
if err != nil {
panic(err)
}
for _, portfolio := range response.Data {
fmt.Printf("Account: %s\n", *portfolio.TradingAccountId)
fmt.Println("Balances:")
for _, balance := range portfolio.Balances {
total, _ := strconv.ParseFloat(*balance.Total, 64)
if total > 0 {
fmt.Printf(" %s: %s (free: %s, locked: %s)\n",
*balance.Asset, *balance.Total, *balance.Free, *balance.Locked)
}
}
}
9. Get Market Data
Check the order book before trading:
- Python
- TypeScript
- Go
response = market_api.get_market_order_book(
venue=cadenza_client.Venue.BINANCE,
symbol="BTC/USDT"
)
order_book = response.data
print(f"Best bid: {order_book.bids[0]}") # [price, quantity]
print(f"Best ask: {order_book.asks[0]}") # [price, quantity]
const response = await marketApi.getMarketOrderBook(
undefined, // instrumentId
'BINANCE', // venue
'BTC/USDT' // symbol
)
const orderBook = response.data.data
console.log('Best bid:', orderBook.bids[0]) // [price, quantity]
console.log('Best ask:', orderBook.asks[0]) // [price, quantity]
venue := client.VENUE_BINANCE
symbol := "BTC/USDT"
response, _, err := apiClient.MarketAPI.GetMarketOrderBook(ctx).
Venue(venue).
Symbol(symbol).
Execute()
if err != nil {
panic(err)
}
orderBook := response.Data
fmt.Printf("Best bid: %v\n", orderBook.Bids[0]) // [price, quantity]
fmt.Printf("Best ask: %v\n", orderBook.Asks[0]) // [price, quantity]
10. Connect WebSocket for Real-time Updates
Connect to WebSocket and subscribe for order and portfolio updates:
- Python
- TypeScript
- Go
import asyncio
from cadenza_client.ws import Client
# Create and connect WebSocket client
ws_client = Client(WS_URL, token=access_token)
await ws_client.connect()
print("WebSocket connected")
# Subscribe to trading account updates
sub = ws_client.new_subscription(f"tradingAccount:{trading_account_id}")
def on_publication(ctx):
data = ctx.data
event_type = data.get("type")
if event_type == "tradeOrderUpdatedEvent":
order = data["data"]
print(f"[Order Update] {order['tradeOrderId']}: {order['status']}")
if order.get("executedPrice"):
print(f" Executed at: {order['executedPrice']}")
if order.get("executedQuantity"):
print(f" Quantity: {order['executedQuantity']}")
elif event_type == "portfolioUpdatedEvent":
portfolio = data["data"]
print("[Portfolio Update]")
for balance in portfolio.get("balances", []):
if float(balance.get("total", 0)) > 0:
print(f" {balance['asset']}: {balance['total']}")
sub.on_publication(on_publication)
await sub.subscribe()
print("Subscribed to real-time updates")
import { Centrifuge } from 'cadenza-client-typescript/ws'
// Create and connect WebSocket client
const wsClient = new Centrifuge(CADENZA_WS_URL, { token: accessToken })
wsClient.connect()
console.log('WebSocket connected')
// Subscribe to trading account updates
const sub = wsClient.newSubscription(`tradingAccount:${tradingAccountId}`)
sub.on('publication', (ctx) => {
const data = ctx.data
if (data.type === 'tradeOrderUpdatedEvent') {
const order = data.data
console.log(`[Order Update] ${order.tradeOrderId}: ${order.status}`)
if (order.executedPrice) {
console.log(` Executed at: ${order.executedPrice}`)
}
if (order.executedQuantity) {
console.log(` Quantity: ${order.executedQuantity}`)
}
}
else if (data.type === 'portfolioUpdatedEvent') {
const portfolio = data.data
console.log('[Portfolio Update]')
portfolio.balances?.forEach((balance: any) => {
if (parseFloat(balance.total || '0') > 0) {
console.log(` ${balance.asset}: ${balance.total}`)
}
})
}
})
sub.subscribe()
console.log('Subscribed to real-time updates')
import "github.com/centrifugal/centrifuge-go"
// Create and connect WebSocket client
wsClient := centrifuge.NewJsonClient(WsURL, centrifuge.Config{
Token: accessToken,
})
_ = wsClient.Connect()
fmt.Println("WebSocket connected")
// Subscribe to trading account updates
sub, _ := wsClient.NewSubscription(fmt.Sprintf("tradingAccount:%s", tradingAccountId))
sub.OnPublication(func(e centrifuge.PublicationEvent) {
var data map[string]interface{}
json.Unmarshal(e.Data, &data)
eventType := data["type"].(string)
if eventType == "tradeOrderUpdatedEvent" {
order := data["data"].(map[string]interface{})
fmt.Printf("[Order Update] %s: %s\n", order["tradeOrderId"], order["status"])
if price, ok := order["executedPrice"]; ok {
fmt.Printf(" Executed at: %v\n", price)
}
if qty, ok := order["executedQuantity"]; ok {
fmt.Printf(" Quantity: %v\n", qty)
}
} else if eventType == "portfolioUpdatedEvent" {
portfolio := data["data"].(map[string]interface{})
fmt.Println("[Portfolio Update]")
if balances, ok := portfolio["balances"].([]interface{}); ok {
for _, b := range balances {
balance := b.(map[string]interface{})
fmt.Printf(" %s: %s\n", balance["asset"], balance["total"])
}
}
}
})
_ = sub.Subscribe()
fmt.Println("Subscribed to real-time updates")
11. Submit Market Order
Execute your first trade with a market order:
- Python
- TypeScript
- Go
response = trade_order_api.submit_trade_order(
cadenza_client.SubmitTradeOrderRequest(
trading_account_id=trading_account_id,
instrument_id="BINANCE:BTC/USDT",
order_side=cadenza_client.OrderSide.BUY,
order_type=cadenza_client.OrderType.MARKET,
quantity="0.001"
)
)
order = response.data
print(f"Order submitted: {order.trade_order_id}")
print(f"Status: {order.status}")
# Real-time updates will print automatically via WebSocket:
# [Order Update] xxx: FILLED
# Executed at: 50123.45
# Quantity: 0.001
# [Portfolio Update]
# BTC: 0.501
# USDT: 9949.87
const response = await tradeOrderApi.submitTradeOrder({
tradingAccountId: tradingAccountId,
instrumentId: 'BINANCE:BTC/USDT',
orderSide: 'BUY',
orderType: 'MARKET',
quantity: '0.001',
})
const order = response.data.data
console.log('Order submitted:', order.tradeOrderId)
console.log('Status:', order.status)
// Real-time updates will print automatically via WebSocket:
// [Order Update] xxx: FILLED
// Executed at: 50123.45
// Quantity: 0.001
// [Portfolio Update]
// BTC: 0.501
// USDT: 9949.87
response, _, err := apiClient.TradeOrderAPI.SubmitTradeOrder(ctx).
SubmitTradeOrderRequest(client.SubmitTradeOrderRequest{
TradingAccountId: tradingAccountId,
InstrumentId: "BINANCE:BTC/USDT",
OrderSide: client.ORDERSIDE_BUY,
OrderType: client.ORDERTYPE_MARKET,
Quantity: "0.001",
}).Execute()
if err != nil {
panic(err)
}
order := response.Data
fmt.Printf("Order submitted: %s\n", *order.TradeOrderId)
fmt.Printf("Status: %s\n", *order.Status)
// Real-time updates will print automatically via WebSocket:
// [Order Update] xxx: FILLED
// Executed at: 50123.45
// Quantity: 0.001
// [Portfolio Update]
// BTC: 0.501
// USDT: 9949.87
After submitting, you'll receive real-time updates through the WebSocket subscription:
tradeOrderUpdatedEvent- Order status changes (PENDING → FILLED) with execution detailsportfolioUpdatedEvent- Balance updates reflecting the trade
Limit Order
For more control over execution price:
- Python
- TypeScript
- Go
response = trade_order_api.submit_trade_order(
cadenza_client.SubmitTradeOrderRequest(
trading_account_id=trading_account_id,
instrument_id="BINANCE:BTC/USDT",
order_side=cadenza_client.OrderSide.BUY,
order_type=cadenza_client.OrderType.LIMIT,
quantity="0.001",
limit_price="50000.00"
)
)
order = response.data
print(f"Limit order placed: {order.trade_order_id}")
const response = await tradeOrderApi.submitTradeOrder({
tradingAccountId: tradingAccountId,
instrumentId: 'BINANCE:BTC/USDT',
orderSide: 'BUY',
orderType: 'LIMIT',
quantity: '0.001',
limitPrice: '50000.00',
})
const order = response.data.data
console.log('Limit order placed:', order.tradeOrderId)
response, _, err := apiClient.TradeOrderAPI.SubmitTradeOrder(ctx).
SubmitTradeOrderRequest(client.SubmitTradeOrderRequest{
TradingAccountId: tradingAccountId,
InstrumentId: "BINANCE:BTC/USDT",
OrderSide: client.ORDERSIDE_BUY,
OrderType: client.ORDERTYPE_LIMIT,
Quantity: "0.001",
LimitPrice: client.PtrString("50000.00"),
}).Execute()
if err != nil {
panic(err)
}
order := response.Data
fmt.Printf("Limit order placed: %s\n", *order.TradeOrderId)
Complete Example
Here's the full workflow with real-time updates:
- Python
- TypeScript
- Go
import asyncio
import cadenza_client
from cadenza_client.ws import Client
BASE_URL = "https://cadenza-api.algo724.com"
WS_URL = "wss://cadenza-ws.algo724.com/connection/websocket"
async def main():
# 1. Authenticate
configuration = cadenza_client.Configuration(host=BASE_URL)
with cadenza_client.ApiClient(configuration) as api_client:
auth_api = cadenza_client.AuthenticationApi(api_client)
response = auth_api.auth_login(
cadenza_client.AuthLoginRequest(
email="your@email.com",
password="your-password"
)
)
access_token = response.data.access_token
print("Authenticated")
# 2. Create API clients
configuration = cadenza_client.Configuration(host=BASE_URL, access_token=access_token)
api_client = cadenza_client.ApiClient(configuration)
credential_api = cadenza_client.TradingAccountCredentialApi(api_client)
trading_account_api = cadenza_client.TradingAccountApi(api_client)
portfolio_api = cadenza_client.TradingAccountPortfolioApi(api_client)
trade_order_api = cadenza_client.TradeOrderApi(api_client)
# 3. Create and verify credential
response = credential_api.create_trading_account_credential(
cadenza_client.CreateTradingAccountCredentialRequest(
venue=cadenza_client.Venue.BINANCE,
credential_type=cadenza_client.CredentialType.EXCHANGE,
api_key="your-api-key",
api_secret="your-api-secret"
)
)
credential_id = response.data.credential_id
response = credential_api.verify_trading_account_credential(
cadenza_client.VerifyTradingAccountCredentialRequest(credential_id=credential_id)
)
print(f"Available accounts: {response.data.identities}")
# 4. Connect trading account
response = trading_account_api.connect_trading_account(
cadenza_client.ConnectTradingAccountRequest(
credential_ids=[credential_id],
external_trading_account_id="spot"
)
)
trading_account_id = response.data.trading_account_id
print(f"Connected: {trading_account_id}")
# 5. Check portfolio
response = portfolio_api.list_trading_account_portfolios(
trading_account_id=trading_account_id
)
for portfolio in response.data:
for balance in portfolio.balances:
if float(balance.total) > 0:
print(f"{balance.asset}: {balance.total}")
# 6. Connect WebSocket for real-time updates
ws_client = Client(WS_URL, token=access_token)
await ws_client.connect()
sub = ws_client.new_subscription(f"tradingAccount:{trading_account_id}")
def on_publication(ctx):
data = ctx.data
if data.get("type") == "tradeOrderUpdatedEvent":
order = data["data"]
print(f"[Order Update] {order['tradeOrderId']}: {order['status']}")
elif data.get("type") == "portfolioUpdatedEvent":
print("[Portfolio Update] Balances changed")
sub.on_publication(on_publication)
await sub.subscribe()
print("Subscribed to real-time updates")
# 7. Submit market order
response = trade_order_api.submit_trade_order(
cadenza_client.SubmitTradeOrderRequest(
trading_account_id=trading_account_id,
instrument_id="BINANCE:BTC/USDT",
order_side=cadenza_client.OrderSide.BUY,
order_type=cadenza_client.OrderType.MARKET,
quantity="0.001"
)
)
print(f"Order submitted: {response.data.trade_order_id}")
# Wait for real-time updates
await asyncio.sleep(5)
await ws_client.disconnect()
asyncio.run(main())
import {
Configuration,
AuthenticationApi,
TradingAccountApi,
TradingAccountCredentialApi,
TradingAccountPortfolioApi,
TradeOrderApi,
} from 'cadenza-client-typescript'
import { Centrifuge } from 'cadenza-client-typescript/ws'
const CADENZA_API_URL = 'https://cadenza-api.algo724.com'
const CADENZA_WS_URL = 'wss://cadenza-ws.algo724.com/connection/websocket'
async function main() {
// 1. Authenticate
let config = new Configuration({ basePath: CADENZA_API_URL })
const authApi = new AuthenticationApi(config)
const authResponse = await authApi.authLogin({
email: 'your@email.com',
password: 'your-password',
})
const accessToken = authResponse.data.data.accessToken
console.log('Authenticated')
// 2. Create API clients
config = new Configuration({ basePath: CADENZA_API_URL, accessToken })
const credentialApi = new TradingAccountCredentialApi(config)
const tradingAccountApi = new TradingAccountApi(config)
const portfolioApi = new TradingAccountPortfolioApi(config)
const tradeOrderApi = new TradeOrderApi(config)
// 3. Create and verify credential
const createResponse = await credentialApi.createTradingAccountCredential({
venue: 'BINANCE',
credentialType: 'EXCHANGE',
apiKey: 'your-api-key',
apiSecret: 'your-api-secret',
})
const credentialId = createResponse.data.data.credentialId
const verifyResponse = await credentialApi.verifyTradingAccountCredential({
credentialId: credentialId,
})
console.log('Available accounts:', verifyResponse.data.data.identities)
// 4. Connect trading account
const connectResponse = await tradingAccountApi.connectTradingAccount({
credentialIds: [credentialId],
externalTradingAccountId: 'spot',
})
const tradingAccountId = connectResponse.data.data.tradingAccountId
console.log('Connected:', tradingAccountId)
// 5. Check portfolio
const portfolioResponse = await portfolioApi.listTradingAccountPortfolios(tradingAccountId)
portfolioResponse.data.data.forEach(portfolio => {
portfolio.balances?.forEach(balance => {
if (parseFloat(balance.total || '0') > 0) {
console.log(`${balance.asset}: ${balance.total}`)
}
})
})
// 6. Connect WebSocket for real-time updates
const wsClient = new Centrifuge(CADENZA_WS_URL, { token: accessToken })
wsClient.connect()
const sub = wsClient.newSubscription(`tradingAccount:${tradingAccountId}`)
sub.on('publication', (ctx) => {
const data = ctx.data
if (data.type === 'tradeOrderUpdatedEvent') {
console.log(`[Order Update] ${data.data.tradeOrderId}: ${data.data.status}`)
} else if (data.type === 'portfolioUpdatedEvent') {
console.log('[Portfolio Update] Balances changed')
}
})
sub.subscribe()
console.log('Subscribed to real-time updates')
// 7. Submit market order
const orderResponse = await tradeOrderApi.submitTradeOrder({
tradingAccountId: tradingAccountId,
instrumentId: 'BINANCE:BTC/USDT',
orderSide: 'BUY',
orderType: 'MARKET',
quantity: '0.001',
})
console.log('Order submitted:', orderResponse.data.data.tradeOrderId)
// Wait for real-time updates
await new Promise((resolve) => setTimeout(resolve, 5000))
wsClient.disconnect()
}
main()
package main
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
client "github.com/cyberapper/cadenza-client-go"
"github.com/centrifugal/centrifuge-go"
)
const (
BaseURL = "https://cadenza-api.algo724.com"
WsURL = "wss://cadenza-ws.algo724.com/connection/websocket"
)
func main() {
// 1. Authenticate
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{{URL: BaseURL}}
apiClient := client.NewAPIClient(cfg)
authResponse, _, _ := apiClient.AuthenticationAPI.AuthLogin(context.Background()).
AuthLoginRequest(client.AuthLoginRequest{
Email: "your@email.com",
Password: "your-password",
}).Execute()
accessToken := *authResponse.Data.AccessToken
fmt.Println("Authenticated")
// 2. Create authenticated context
ctx := context.WithValue(context.Background(), client.ContextAccessToken, accessToken)
// 3. Create and verify credential
createResponse, _, _ := apiClient.TradingAccountCredentialAPI.CreateTradingAccountCredential(ctx).
CreateTradingAccountCredentialRequest(client.CreateTradingAccountCredentialRequest{
Venue: client.VENUE_BINANCE,
CredentialType: client.CREDENTIALTYPE_EXCHANGE,
ApiKey: client.PtrString("your-api-key"),
ApiSecret: client.PtrString("your-api-secret"),
}).Execute()
credentialId := *createResponse.Data.CredentialId
verifyResponse, _, _ := apiClient.TradingAccountCredentialAPI.VerifyTradingAccountCredential(ctx).
VerifyTradingAccountCredentialRequest(client.VerifyTradingAccountCredentialRequest{
CredentialId: credentialId,
}).Execute()
fmt.Printf("Available accounts: %v\n", verifyResponse.Data.Identities)
// 4. Connect trading account
connectResponse, _, _ := apiClient.TradingAccountAPI.ConnectTradingAccount(ctx).
ConnectTradingAccountRequest(client.ConnectTradingAccountRequest{
CredentialIds: []string{credentialId},
ExternalTradingAccountId: "spot",
}).Execute()
tradingAccountId := *connectResponse.Data.TradingAccountId
fmt.Printf("Connected: %s\n", tradingAccountId)
// 5. Check portfolio
portfolioResponse, _, _ := apiClient.TradingAccountPortfolioAPI.ListTradingAccountPortfolios(ctx).
TradingAccountId(tradingAccountId).
Execute()
for _, portfolio := range portfolioResponse.Data {
for _, balance := range portfolio.Balances {
total, _ := strconv.ParseFloat(*balance.Total, 64)
if total > 0 {
fmt.Printf("%s: %s\n", *balance.Asset, *balance.Total)
}
}
}
// 6. Connect WebSocket for real-time updates
wsClient := centrifuge.NewJsonClient(WsURL, centrifuge.Config{
Token: accessToken,
})
_ = wsClient.Connect()
sub, _ := wsClient.NewSubscription(fmt.Sprintf("tradingAccount:%s", tradingAccountId))
sub.OnPublication(func(e centrifuge.PublicationEvent) {
var data map[string]interface{}
json.Unmarshal(e.Data, &data)
eventType := data["type"].(string)
if eventType == "tradeOrderUpdatedEvent" {
order := data["data"].(map[string]interface{})
fmt.Printf("[Order Update] %s: %s\n", order["tradeOrderId"], order["status"])
} else if eventType == "portfolioUpdatedEvent" {
fmt.Println("[Portfolio Update] Balances changed")
}
})
_ = sub.Subscribe()
fmt.Println("Subscribed to real-time updates")
// 7. Submit market order
orderResponse, _, _ := apiClient.TradeOrderAPI.SubmitTradeOrder(ctx).
SubmitTradeOrderRequest(client.SubmitTradeOrderRequest{
TradingAccountId: tradingAccountId,
InstrumentId: "BINANCE:BTC/USDT",
OrderSide: client.ORDERSIDE_BUY,
OrderType: client.ORDERTYPE_MARKET,
Quantity: "0.001",
}).Execute()
fmt.Printf("Order submitted: %s\n", *orderResponse.Data.TradeOrderId)
// Wait for real-time updates
time.Sleep(5 * time.Second)
wsClient.Disconnect()
}
Next Steps
Learn More
- Supported Venues - Exchange setup instructions and requirements
- Credentials - Credential management in depth
- Trading Accounts - Account connection and management
Advanced Topics
- Market Data - Instruments and order books
- Trading - Order types and management
Client SDKs
| Language | Package | Repository |
|---|---|---|
| Python | cadenza-client | cadenza-client-python |
| TypeScript | cadenza-client-typescript | cadenza-client-typescript |
| Go | cadenza-client-go | cadenza-client-go |
API Documentation
- HTTP API Reference - Complete endpoint documentation
- WebSocket API Reference - RPC and channel documentation
- Interactive API Docs - OpenAPI documentation