Skip to main content

Trading & Transfers Solution

Build powerful trading and transfer applications with NUVA Labs' comprehensive trading APIs. This solution covers everything from order placement to trade execution and settlement.

Overview

The Trading & Transfers solution provides APIs for:

  • Order Management: Place, modify, and cancel orders
  • Trade Execution: Execute trades with optimal pricing
  • Transfer Operations: Send and receive assets
  • Settlement: Handle trade settlement and clearing
  • Portfolio Management: Track positions and performance

Key Features

📈 Order Management

  • Place market and limit orders
  • Modify existing orders
  • Cancel orders before execution
  • Track order status and history

💱 Trade Execution

  • Execute trades with best available prices
  • Handle partial fills and slippage
  • Support for different order types
  • Real-time trade notifications

💸 Transfer Operations

  • Send assets between accounts
  • Batch transfer operations
  • Scheduled transfers
  • Transfer validation and approval

📊 Settlement & Clearing

  • Automatic trade settlement
  • Clearing and reconciliation
  • Settlement reporting
  • Risk management

Quick Start

1. Place a Market Order

import { NUClient } from '@nu/sdk';

const client = new NUClient({
clientId: process.env.NU_CLIENT_ID,
clientSecret: process.env.NU_CLIENT_SECRET,
environment: 'production',
});

await client.authenticate();

// Place a market buy order
const order = await client.placeOrder({
type: 'market',
side: 'buy',
assetId: 'asset_1234567890',
quantity: 100,
accountId: 'acc_1234567890',
});

console.log('Order placed:', order.id);

2. Check Order Status

// Get order details
const orderDetails = await client.getOrder(order.id);
console.log('Order status:', orderDetails.status);

// Get order history
const orderHistory = await client.getOrderHistory({
accountId: 'acc_1234567890',
limit: 50,
});

console.log('Order history:', orderHistory.length);

3. Execute Transfer

// Transfer assets
const transfer = await client.transferAssets({
from: 'acc_1234567890',
to: 'acc_0987654321',
assetId: 'asset_1234567890',
amount: 50,
memo: 'Payment for services',
});

console.log('Transfer executed:', transfer.id);

API Reference

Trading Endpoints

EndpointMethodDescription
/ordersGETList orders
/ordersPOSTPlace order
/orders/{id}GETGet order details
/orders/{id}PUTModify order
/orders/{id}DELETECancel order
/tradesGETList trades
/trades/{id}GETGet trade details

Transfer Endpoints

EndpointMethodDescription
/transfersGETList transfers
/transfersPOSTExecute transfer
/transfers/{id}GETGet transfer details
/transfers/batchPOSTBatch transfers

Order Types

Market Orders

// Market buy order
const marketOrder = await client.placeOrder({
type: 'market',
side: 'buy',
assetId: 'asset_1234567890',
quantity: 100,
accountId: 'acc_1234567890',
});

// Market sell order
const sellOrder = await client.placeOrder({
type: 'market',
side: 'sell',
assetId: 'asset_1234567890',
quantity: 50,
accountId: 'acc_1234567890',
});

Limit Orders

// Limit buy order
const limitOrder = await client.placeOrder({
type: 'limit',
side: 'buy',
assetId: 'asset_1234567890',
quantity: 100,
price: 10.5,
accountId: 'acc_1234567890',
});

// Stop loss order
const stopLoss = await client.placeOrder({
type: 'stop-loss',
side: 'sell',
assetId: 'asset_1234567890',
quantity: 100,
stopPrice: 9.5,
accountId: 'acc_1234567890',
});

Advanced Orders

// Take profit order
const takeProfit = await client.placeOrder({
type: 'take-profit',
side: 'sell',
assetId: 'asset_1234567890',
quantity: 100,
price: 12.0,
accountId: 'acc_1234567890',
});

// OCO (One-Cancels-Other) order
const ocoOrder = await client.placeOrder({
type: 'oco',
side: 'sell',
assetId: 'asset_1234567890',
quantity: 100,
price: 12.0,
stopPrice: 9.5,
accountId: 'acc_1234567890',
});

Transfer Operations

Single Transfer

const transfer = await client.transferAssets({
from: 'acc_1234567890',
to: 'acc_0987654321',
assetId: 'asset_1234567890',
amount: 100,
memo: 'Payment for services',
});

Batch Transfers

const batchTransfer = await client.batchTransfer({
transfers: [
{
from: 'acc_1234567890',
to: 'acc_0987654321',
assetId: 'asset_1234567890',
amount: 100,
},
{
from: 'acc_1234567890',
to: 'acc_1122334455',
assetId: 'asset_1234567890',
amount: 50,
},
],
memo: 'Batch payment',
});

Scheduled Transfers

const scheduledTransfer = await client.scheduleTransfer({
from: 'acc_1234567890',
to: 'acc_0987654321',
assetId: 'asset_1234567890',
amount: 100,
executeAt: '2024-12-31T23:59:59Z',
memo: 'Year-end bonus',
});

Portfolio Management

Get Portfolio

const portfolio = await client.getPortfolio('acc_1234567890');
console.log('Portfolio value:', portfolio.totalValue);
console.log('Positions:', portfolio.positions);

Get Position

const position = await client.getPosition('acc_1234567890', 'asset_1234567890');
console.log('Quantity:', position.quantity);
console.log('Average price:', position.averagePrice);
console.log('Unrealized P&L:', position.unrealizedPnL);

Get Performance

const performance = await client.getPerformance('acc_1234567890', {
period: '30d',
includeFees: true,
});

console.log('Total return:', performance.totalReturn);
console.log('Daily returns:', performance.dailyReturns);

Real-time Updates

WebSocket Connection

const ws = client.createWebSocket();

ws.on('orderUpdate', (order) => {
console.log('Order updated:', order.id, order.status);
});

ws.on('tradeExecuted', (trade) => {
console.log('Trade executed:', trade.id, trade.price);
});

ws.on('transferCompleted', (transfer) => {
console.log('Transfer completed:', transfer.id);
});

Event Subscriptions

// Subscribe to order updates
await client.subscribeToOrders('acc_1234567890');

// Subscribe to trade updates
await client.subscribeToTrades('acc_1234567890');

// Subscribe to transfer updates
await client.subscribeToTransfers('acc_1234567890');

Use Cases

1. Trading Bot

class TradingBot {
constructor(client) {
this.client = client;
}

async startTrading() {
// Monitor market conditions
const marketData = await this.client.getMarketData('asset_1234567890');

if (marketData.price < 10.0) {
// Place buy order
await this.client.placeOrder({
type: 'limit',
side: 'buy',
assetId: 'asset_1234567890',
quantity: 100,
price: 9.95,
});
}
}
}

2. Payment System

class PaymentSystem {
constructor(client) {
this.client = client;
}

async processPayment(from, to, amount, assetId) {
try {
const transfer = await this.client.transferAssets({
from,
to,
assetId,
amount,
memo: 'Payment',
});

return { success: true, transferId: transfer.id };
} catch (error) {
return { success: false, error: error.message };
}
}
}

3. Portfolio Tracker

class PortfolioTracker {
constructor(client) {
this.client = client;
}

async trackPortfolio(accountId) {
const portfolio = await this.client.getPortfolio(accountId);
const performance = await this.client.getPerformance(accountId, {
period: '1d',
});

return {
totalValue: portfolio.totalValue,
dailyReturn: performance.dailyReturn,
positions: portfolio.positions,
};
}
}

Best Practices

1. Order Management

  • Use appropriate order types for your strategy
  • Implement proper risk management
  • Monitor order status regularly
  • Handle partial fills appropriately

2. Transfer Operations

  • Validate transfer parameters
  • Implement proper error handling
  • Use batch transfers for efficiency
  • Monitor transfer status

3. Performance Optimization

  • Use WebSocket for real-time updates
  • Implement proper caching
  • Monitor API rate limits
  • Use pagination for large datasets

4. Security

  • Validate all inputs
  • Implement proper authentication
  • Use HTTPS for all requests
  • Monitor for suspicious activity

Error Handling

Common Errors

try {
const order = await client.placeOrder(orderData);
} catch (error) {
switch (error.code) {
case 'INSUFFICIENT_BALANCE':
console.error('Insufficient balance for order');
break;
case 'INVALID_ORDER':
console.error('Invalid order parameters');
break;
case 'MARKET_CLOSED':
console.error('Market is currently closed');
break;
case 'RATE_LIMITED':
console.error('Too many requests, please wait');
break;
default:
console.error('Unexpected error:', error.message);
}
}

Integration Examples

React Trading Component

import React, { useState, useEffect } from 'react';
import { NUClient } from '@nu/sdk';

function TradingInterface() {
const [orders, setOrders] = useState([]);
const [portfolio, setPortfolio] = useState(null);

useEffect(() => {
const client = new NUClient({
clientId: process.env.REACT_APP_NU_CLIENT_ID,
clientSecret: process.env.REACT_APP_NU_CLIENT_SECRET,
environment: 'production',
});

const loadData = async () => {
try {
await client.authenticate();
const [orderList, portfolioData] = await Promise.all([
client.getOrders(),
client.getPortfolio(),
]);
setOrders(orderList);
setPortfolio(portfolioData);
} catch (error) {
console.error('Failed to load data:', error);
}
};

loadData();
}, []);

const placeOrder = async (orderData) => {
try {
const order = await client.placeOrder(orderData);
setOrders((prev) => [order, ...prev]);
} catch (error) {
console.error('Failed to place order:', error);
}
};

return (
<div>
<h2>Trading Interface</h2>
<div>
<h3>Portfolio Value: ${portfolio?.totalValue}</h3>
<h3>Orders ({orders.length})</h3>
{orders.map((order) => (
<div key={order.id}>
<span>
{order.side} {order.quantity} @ {order.price}
</span>
<span>Status: {order.status}</span>
</div>
))}
</div>
</div>
);
}

Next Steps


Ready to start building? Let's explore Data Querying to access market data and analytics!