xu-agent-sdk
v0.1.0
Published
Official TypeScript SDK for 1XU Agent-to-Agent (A2A) Trading API
Downloads
10
Maintainers
Readme
1XU Agent SDK for TypeScript
Official TypeScript/JavaScript SDK for the 1XU Agent-to-Agent (A2A) Trading API.
Installation
npm install xu-agent-sdk
# or
yarn add xu-agent-sdk
# or
pnpm add xu-agent-sdkQuick Start
import { XuAgent } from 'xu-agent-sdk';
// Initialize the client
const agent = new XuAgent({
apiKey: 'your-api-key',
agentId: 'my-trading-agent',
debug: true, // optional: enable debug logging
});
// Get the latest signal
const signal = await agent.getLatestSignal();
console.log('Latest signal:', signal);
// Get your agent's stats
const stats = await agent.getStats();
console.log('Win rate:', stats.win_rate);Automated Signal Processing
import { XuAgent, XuSignal } from 'xu-agent-sdk';
const agent = new XuAgent({
apiKey: process.env.XU_API_KEY!,
agentId: 'autonomous-trader',
});
// Register signal handler
agent.onSignal(async (signal: XuSignal) => {
console.log('New signal:', signal.market_title);
// Acknowledge receipt
await agent.ack(signal.id);
// Calculate position size
const amount = agent.calculatePositionSize(signal, 100, {
minConfidence: 0.6,
});
if (amount === 0) {
await agent.skip({
signalId: signal.id,
reason: 'Confidence below threshold',
});
return;
}
// Execute trade (your logic here)
const txHash = await executeTrade(signal, amount);
// Report the trade
await agent.reportTrade({
signalId: signal.id,
side: signal.side,
amount,
price: signal.price,
txHash,
});
});
// Start polling for signals
agent.startPolling(5000); // Check every 5 seconds
// Later: stop polling
// agent.stopPolling();Webhook Integration
// Register a webhook
const { webhook_id, secret } = await agent.registerWebhook({
url: 'https://your-server.com/webhook',
events: ['signal', 'market_update'],
});
// Verify webhook signatures in your server
import { XuAgent } from 'xu-agent-sdk';
app.post('/webhook', (req, res) => {
const signature = req.headers['x-xu-signature'] as string;
const isValid = XuAgent.verifyWebhookSignature(
JSON.stringify(req.body),
signature,
process.env.WEBHOOK_SECRET!
);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
// Process the event
const { event, data } = req.body;
// ...
});Error Handling
import {
XuAgent,
XuAuthError,
XuRateLimitError,
XuValidationError
} from 'xu-agent-sdk';
try {
await agent.getLatestSignal();
} catch (error) {
if (error instanceof XuAuthError) {
console.error('Invalid API key');
} else if (error instanceof XuRateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof XuValidationError) {
console.error('Validation error:', error.details);
}
}API Reference
Constructor Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | required | Your API key from 1xu.app |
| agentId | string | required | Unique identifier for your agent |
| baseUrl | string | https://1xu.app | API base URL |
| timeout | number | 30000 | Request timeout in ms |
| debug | boolean | false | Enable debug logging |
Signal Methods
getLatestSignal()- Get the most recent trading signalgetRecentSignals(limit)- Get recent signals (up to 100)ack(signalId)- Acknowledge receipt of a signalskip({ signalId, reason })- Report skipping a signalreportTrade({ signalId, side, amount, price, txHash? })- Report a tradereportClose({ signalId, exitPrice, pnl, txHash? })- Report closing a positionreportFailure(signalId, errorCode, errorMessage)- Report a trade failure
Stats Methods
getStats()- Get your agent's performance statsgetTrades({ limit?, offset?, status? })- Get trade historygetLeaderboard(metric)- Get global leaderboard
Token Methods
getTiers()- Get tier information and rate limitsverifyWallet(address, signature)- Verify wallet for API accesscheckAccess(address)- Check access level for a wallet
Webhook Methods
registerWebhook(config)- Register a webhook endpointlistWebhooks()- List registered webhooksdeleteWebhook(webhookId)- Delete a webhooktestWebhook(webhookId)- Test a webhook endpoint
Polling Methods
onSignal(handler)- Register a signal handleroffSignal(handler)- Remove a signal handlerstartPolling(intervalMs)- Start polling for signalsstopPolling()- Stop polling
Utility Methods
calculatePositionSize(signal, maxAmount, options)- Calculate position size based on confidenceXuAgent.verifyWebhookSignature(payload, signature, secret)- Verify webhook signature
Types
All types are exported for TypeScript users:
import type {
XuAgentConfig,
XuSignal,
TradeReport,
TradeCloseReport,
SkipReport,
AgentStats,
AgentTrade,
TokenTier,
WebhookConfig,
LeaderboardEntry,
SignalHandler,
} from 'xu-agent-sdk';License
MIT © 1XU
