跳至主要内容

AI 交易 API

AI 交易 API 提供了 18 个以上的方法,用于与 AI 驱动的量化交易 Agent 进行交互。涵盖策略发现、订单生命周期管理、投资组合跟踪、市场数据、交易信号和 Agent 配置。

策略方法

方法参数返回值描述
getAIStrategies(filters?)filters?: AIStrategyFiltersApiResponse<AIStrategy[]>列出可用的 AI 交易策略,可选筛选。
getAIStrategy(strategyId)strategyId: stringApiResponse<AIStrategy>返回单个策略的详细信息。
getAIStrategyPerformance(strategyId, period?)strategyId: string, period?: stringApiResponse<AIStrategyPerformance>返回策略的历史表现指标。
getAIStrategyMarketData(strategyId)strategyId: stringApiResponse<AIMarketData>返回与策略交易对相关的实时市场数据。

订单方法

方法参数返回值描述
createAIOrder(request)request: AIOrderRequestApiResponse<AIOrder>创建新的 AI 交易订单(投资)。
getAIOrders(filters?)filters?: AIOrderFiltersApiResponse<AIOrder[]>列出用户的 AI 交易订单,可选筛选。
getAIOrder(orderId)orderId: stringApiResponse<AIOrder>返回单个订单的详细信息。
pauseAIOrder(orderId)orderId: stringApiResponse<AIOrder>暂停活跃订单。Agent 停止交易但持仓保持不变。
resumeAIOrder(orderId)orderId: stringApiResponse<AIOrder>恢复已暂停的订单。
redeemAIOrder(orderId)orderId: stringApiResponse<AIOrderRedemption>发起订单的提前赎回/提现。

投资组合方法

方法参数返回值描述
getAIPortfolio()--ApiResponse<AIPortfolio>返回所有 AI 订单的汇总投资组合指标。
getAITradeAllocations(orderId?)orderId?: stringApiResponse<AITradeAllocation[]>返回当前资金分配情况,可选限定到单个订单。
getAITradeHistory(options?)options?: AITradeHistoryOptionsApiResponse<AITradeRecord[]>返回 AI Agent 执行的历史交易记录。

信号方法

方法参数返回值描述
executeAISignals(signals)signals: AISignal[]ApiResponse<AISignalResult[]>手动执行一个或多个 AI 生成的交易信号。

Agent 配置方法

方法参数返回值描述
getAgentConfigs()--ApiResponse<AgentConfig[]>列出所有可用的 Agent 配置(等级、参数)。
calculateAgentParams(request)request: AgentParamsRequestApiResponse<AgentParams>根据给定的投资金额和等级计算 Agent 参数。
getTradingPairs(chainId?)chainId?: stringApiResponse<TradingPair[]>列出支持的交易对,可选按链筛选。

类型

AIStrategy

interface AIStrategy {
id: string;
name: string;
description: string;
tier: 'conservative' | 'moderate' | 'aggressive';
chainId: string;
tradingPairs: string[];
minInvestment: string;
maxInvestment: string;
cycleDays: number;
expectedApy: { min: number; max: number };
riskScore: number;
status: 'active' | 'paused' | 'deprecated';
createdAt: string;
}

AIStrategyFilters

interface AIStrategyFilters {
tier?: 'conservative' | 'moderate' | 'aggressive';
chainId?: string;
status?: 'active' | 'paused';
minInvestment?: string;
}

AIStrategyPerformance

interface AIStrategyPerformance {
strategyId: string;
period: string;
totalReturn: number;
annualizedReturn: number;
sharpeRatio: number;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitFactor: number;
dailyReturns: { date: string; return: number }[];
}

AIMarketData

interface AIMarketData {
strategyId: string;
pairs: {
pair: string;
price: string;
change24h: number;
volume24h: string;
high24h: string;
low24h: string;
}[];
timestamp: string;
}

AIOrderRequest

interface AIOrderRequest {
/** Strategy ID to invest in. */
strategyId: string;
/** Investment amount in USDC (or strategy base currency). */
amount: string;
/** Wallet address funding the order. */
walletAddress: string;
/** Optional: override the default cycle duration. */
cycleDays?: number;
}

AIOrder

interface AIOrder {
id: string;
strategyId: string;
strategyName: string;
userId: string;
walletAddress: string;
/** Original investment amount. */
investedAmount: string;
/** Current value of the order. */
currentValue: string;
/** Unrealised P&L. */
pnl: string;
pnlPercentage: number;
status: 'active' | 'paused' | 'completed' | 'redeeming' | 'redeemed';
cycleDays: number;
cycleStartDate: string;
cycleEndDate: string;
createdAt: string;
updatedAt: string;
}

AIOrderFilters

interface AIOrderFilters {
status?: 'active' | 'paused' | 'completed' | 'redeemed';
strategyId?: string;
limit?: number;
cursor?: string;
}

AIOrderRedemption

interface AIOrderRedemption {
orderId: string;
/** Amount returned to wallet after exit. */
redeemedAmount: string;
/** Fee deducted for early withdrawal (if applicable). */
earlyWithdrawalFee?: string;
txHash?: string;
status: 'processing' | 'completed' | 'failed';
estimatedCompletionAt: string;
}

AIPortfolio

interface AIPortfolio {
totalInvested: string;
totalCurrentValue: string;
totalPnl: string;
totalPnlPercentage: number;
activeOrders: number;
completedOrders: number;
orders: AIOrder[];
}

AITradeAllocation

interface AITradeAllocation {
orderId: string;
pair: string;
allocationPercentage: number;
allocationAmount: string;
currentValue: string;
pnl: string;
side: 'long' | 'short';
}

AITradeRecord

interface AITradeRecord {
id: string;
orderId: string;
pair: string;
side: 'buy' | 'sell';
amount: string;
price: string;
fee: string;
pnl?: string;
timestamp: string;
}

AITradeHistoryOptions

interface AITradeHistoryOptions {
orderId?: string;
pair?: string;
side?: 'buy' | 'sell';
limit?: number;
cursor?: string;
startDate?: string;
endDate?: string;
}

AISignal

interface AISignal {
pair: string;
side: 'buy' | 'sell';
amount: string;
/** Target price. */
price?: string;
/** Order type. */
type: 'market' | 'limit';
}

AISignalResult

interface AISignalResult {
signalIndex: number;
success: boolean;
txHash?: string;
executedPrice?: string;
error?: string;
}

AgentConfig

interface AgentConfig {
id: string;
name: string;
tier: 'conservative' | 'moderate' | 'aggressive';
description: string;
maxPositions: number;
maxLeverage: number;
stopLossPercentage: number;
takeProfitPercentage: number;
rebalanceFrequency: string;
supportedChains: string[];
}

AgentParamsRequest

interface AgentParamsRequest {
tier: 'conservative' | 'moderate' | 'aggressive';
investmentAmount: string;
chainId: string;
cycleDays?: number;
}

AgentParams

interface AgentParams {
tier: string;
positionSize: string;
maxPositions: number;
stopLoss: number;
takeProfit: number;
rebalanceInterval: string;
estimatedApy: { min: number; max: number };
riskScore: number;
}

TradingPair

interface TradingPair {
pair: string;
baseToken: string;
quoteToken: string;
chainId: string;
minTradeSize: string;
maxTradeSize: string;
pricePrecision: number;
status: 'active' | 'inactive';
}

示例

浏览策略

const res = await engine.getAIStrategies({ tier: 'moderate', status: 'active' });

if (res.success && res.data) {
for (const s of res.data) {
console.log(`${s.name} | APY: ${s.expectedApy.min}-${s.expectedApy.max}% | Risk: ${s.riskScore}`);
}
}

创建 AI 订单

const res = await engine.createAIOrder({
strategyId: 'strat_abc123',
amount: '1000',
walletAddress: '0xABC...',
cycleDays: 30,
});

if (res.success && res.data) {
console.log('Order created:', res.data.id);
console.log('Cycle ends:', res.data.cycleEndDate);
}

查看投资组合

const res = await engine.getAIPortfolio();

if (res.success && res.data) {
const p = res.data;
console.log(`Invested: $${p.totalInvested} | Value: $${p.totalCurrentValue}`);
console.log(`P&L: $${p.totalPnl} (${p.totalPnlPercentage.toFixed(2)}%)`);
console.log(`Active orders: ${p.activeOrders}`);
}

暂停和恢复订单

// Pause
await engine.pauseAIOrder('order_123');

// Resume
await engine.resumeAIOrder('order_123');

提前赎回

const res = await engine.redeemAIOrder('order_123');

if (res.success && res.data) {
console.log(`Redeemed: $${res.data.redeemedAmount}`);
if (res.data.earlyWithdrawalFee) {
console.log(`Early withdrawal fee: $${res.data.earlyWithdrawalFee}`);
}
}

交易历史

const res = await engine.getAITradeHistory({
orderId: 'order_123',
limit: 50,
});

if (res.success && res.data) {
for (const t of res.data) {
console.log(`${t.timestamp} | ${t.side} ${t.pair} | ${t.amount} @ ${t.price}`);
}
}

Agent 配置

// List agent configs
const configs = await engine.getAgentConfigs();

// Calculate parameters for a specific investment
const params = await engine.calculateAgentParams({
tier: 'aggressive',
investmentAmount: '5000',
chainId: 'ethereum',
cycleDays: 14,
});

if (params.success && params.data) {
console.log(`Position size: $${params.data.positionSize}`);
console.log(`Max positions: ${params.data.maxPositions}`);
console.log(`Est. APY: ${params.data.estimatedApy.min}-${params.data.estimatedApy.max}%`);
}

// List trading pairs
const pairs = await engine.getTradingPairs('ethereum');

后续步骤