> ## Documentation Index
> Fetch the complete documentation index at: https://core.anylayer.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Trading SDK

> Access and analyze trading activity and statistics

## Overview

The Trading SDK provides comprehensive access to on-chain trading data, statistics, and leaderboards. Track DEX activity, analyze trading patterns, and build trader reputation systems.

## Get Trading Stats

Retrieve comprehensive trading statistics for a wallet:

```typescript theme={null}
const stats = await sdk.trading.getStats('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1');

console.log(stats);
// {
//   address: "0x742d35...",
//   totalTrades: 1234,
//   totalVolume: "1234567.89",
//   uniqueTokens: 45,
//   uniqueDexs: 8,
//   firstTradeAt: "2023-01-15T10:30:00Z",
//   lastTradeAt: "2024-10-23T14:22:00Z",
//   avgTradeSize: "1001.28",
//   largestTrade: "50000.00",
//   profitLoss: "+15234.56",
//   winRate: 0.68,
//   topTokens: [
//     { symbol: "ETH", trades: 456, volume: "500000" },
//     { symbol: "USDC", trades: 389, volume: "450000" }
//   ],
//   topDexs: [
//     { name: "Uniswap", trades: 567, volume: "650000" },
//     { name: "Curve", trades: 234, volume: "300000" }
//   ]
// }
```

### Parameters

<ParamField path="address" type="string" required>
  Ethereum address to query
</ParamField>

<ParamField path="options" type="object">
  Optional query parameters

  <Expandable title="Options">
    <ParamField path="timeRange" type="string">
      Time range filter: `'7d'`, `'30d'`, `'90d'`, `'1y'`, `'all'`
    </ParamField>

    <ParamField path="chain" type="string">
      Specific chain to query (defaults to all chains)
    </ParamField>

    <ParamField path="includeDetails" type="boolean">
      Include detailed breakdowns (default: `true`)
    </ParamField>
  </Expandable>
</ParamField>

### Returns

<ResponseField name="address" type="string">
  Wallet address
</ResponseField>

<ResponseField name="totalTrades" type="number">
  Total number of trades executed
</ResponseField>

<ResponseField name="totalVolume" type="string">
  Total trading volume in USD
</ResponseField>

<ResponseField name="uniqueTokens" type="number">
  Number of unique tokens traded
</ResponseField>

<ResponseField name="uniqueDexs" type="number">
  Number of unique DEXs used
</ResponseField>

<ResponseField name="winRate" type="number">
  Percentage of profitable trades (0-1)
</ResponseField>

## Get Trading History

Fetch detailed trading history with pagination:

```typescript theme={null}
const history = await sdk.trading.getHistory('0x742d35...', {
  limit: 50,
  offset: 0,
  sortBy: 'timestamp',
  order: 'desc',
});

console.log(history);
// {
//   trades: [
//     {
//       txHash: "0xabc123...",
//       timestamp: "2024-10-23T14:22:00Z",
//       dex: "Uniswap V3",
//       type: "swap",
//       tokenIn: {
//         symbol: "ETH",
//         amount: "1.5",
//         valueUsd: "3750.00"
//       },
//       tokenOut: {
//         symbol: "USDC",
//         amount: "3750",
//         valueUsd: "3750.00"
//       },
//       gasUsed: "0.015",
//       profit: null,
//       status: "success"
//     },
//     // ... more trades
//   ],
//   pagination: {
//     total: 1234,
//     limit: 50,
//     offset: 0,
//     hasMore: true
//   }
// }
```

### Parameters

<ParamField path="address" type="string" required>
  Ethereum address to query
</ParamField>

<ParamField path="options" type="object">
  Query options

  <Expandable title="Options">
    <ParamField path="limit" type="number">
      Number of trades to return (max: 100, default: 50)
    </ParamField>

    <ParamField path="offset" type="number">
      Pagination offset (default: 0)
    </ParamField>

    <ParamField path="sortBy" type="string">
      Sort field: `'timestamp'`, `'volume'`, `'profit'`
    </ParamField>

    <ParamField path="order" type="string">
      Sort order: `'asc'` or `'desc'`
    </ParamField>

    <ParamField path="tokenSymbol" type="string">
      Filter by token symbol
    </ParamField>

    <ParamField path="dex" type="string">
      Filter by DEX name
    </ParamField>

    <ParamField path="minValue" type="string">
      Minimum trade value in USD
    </ParamField>

    <ParamField path="startDate" type="string">
      Start date (ISO 8601)
    </ParamField>

    <ParamField path="endDate" type="string">
      End date (ISO 8601)
    </ParamField>
  </Expandable>
</ParamField>

## Get Trading Leaderboard

View top traders globally or filtered by specific criteria:

```typescript theme={null}
const leaderboard = await sdk.trading.getLeaderboard({
  metric: 'volume',
  timeRange: '30d',
  limit: 100,
});

console.log(leaderboard);
// {
//   metric: "volume",
//   timeRange: "30d",
//   updatedAt: "2024-10-23T14:00:00Z",
//   leaders: [
//     {
//       rank: 1,
//       address: "0x123...",
//       username: "defi_whale",
//       value: "15234567.89",
//       change24h: +2.5,
//       zkid: "zkid_abc123"
//     },
//     {
//       rank: 2,
//       address: "0x456...",
//       username: "trader_pro",
//       value: "12456789.12",
//       change24h: -1.2,
//       zkid: "zkid_def456"
//     },
//     // ... more traders
//   ],
//   userRank: {
//     rank: 1234,
//     value: "12345.67",
//     percentile: 85.5
//   }
// }
```

### Parameters

<ParamField path="options" type="object">
  Leaderboard options

  <Expandable title="Options">
    <ParamField path="metric" type="string" required>
      Ranking metric: `'volume'`, `'trades'`, `'profit'`, `'winRate'`
    </ParamField>

    <ParamField path="timeRange" type="string">
      Time period: `'24h'`, `'7d'`, `'30d'`, `'all'` (default: `'30d'`)
    </ParamField>

    <ParamField path="limit" type="number">
      Number of leaders to return (max: 500, default: 100)
    </ParamField>

    <ParamField path="chain" type="string">
      Filter by specific chain
    </ParamField>

    <ParamField path="userAddress" type="string">
      Include user's rank in response
    </ParamField>
  </Expandable>
</ParamField>

## Get Token Trading Stats

Analyze trading activity for a specific token:

```typescript theme={null}
const tokenStats = await sdk.trading.getTokenStats('ETH', {
  address: '0x742d35...',
});

console.log(tokenStats);
// {
//   token: "ETH",
//   trades: 456,
//   volume: "500000.00",
//   bought: "250.5",
//   sold: "248.2",
//   netPosition: "+2.3",
//   avgBuyPrice: "2450.25",
//   avgSellPrice: "2515.80",
//   realizedPnL: "+12345.67",
//   firstTrade: "2023-03-15T10:00:00Z",
//   lastTrade: "2024-10-23T14:22:00Z"
// }
```

## Get DEX Statistics

View trading statistics per DEX:

```typescript theme={null}
const dexStats = await sdk.trading.getDexStats('0x742d35...', {
  dex: 'Uniswap',
});

console.log(dexStats);
// {
//   dex: "Uniswap",
//   version: "v3",
//   trades: 567,
//   volume: "650000.00",
//   avgSlippage: 0.25,
//   avgGas: "0.012",
//   totalGas: "6.804",
//   pools: [
//     {
//       pair: "ETH/USDC",
//       trades: 234,
//       volume: "350000.00"
//     },
//     // ... more pools
//   ]
// }
```

## Advanced Examples

### Build a Trading Dashboard

```typescript theme={null}
async function buildTradingDashboard(address: string) {
  // Fetch all data in parallel
  const [stats, recentTrades, leaderboard] = await Promise.all([
    sdk.trading.getStats(address, { timeRange: '30d' }),
    sdk.trading.getHistory(address, { limit: 10 }),
    sdk.trading.getLeaderboard({
      metric: 'volume',
      timeRange: '30d',
      userAddress: address,
    }),
  ]);

  return {
    overview: {
      totalVolume: stats.totalVolume,
      totalTrades: stats.totalTrades,
      winRate: `${(stats.winRate * 100).toFixed(1)}%`,
      profitLoss: stats.profitLoss,
    },
    recentActivity: recentTrades.trades,
    ranking: {
      rank: leaderboard.userRank?.rank || 'Unranked',
      percentile: leaderboard.userRank?.percentile,
    },
    topTokens: stats.topTokens.slice(0, 5),
    topDexs: stats.topDexs.slice(0, 5),
  };
}
```

### Track Trading Performance

```typescript theme={null}
async function trackPerformance(address: string) {
  const timeRanges = ['7d', '30d', '90d', '1y'] as const;
  
  const performance = await Promise.all(
    timeRanges.map(async (range) => {
      const stats = await sdk.trading.getStats(address, {
        timeRange: range,
      });
      
      return {
        period: range,
        volume: stats.totalVolume,
        trades: stats.totalTrades,
        profit: stats.profitLoss,
        winRate: stats.winRate,
      };
    })
  );
  
  return performance;
}
```

### Filter Profitable Trades

```typescript theme={null}
async function getProfitableTrades(address: string) {
  const history = await sdk.trading.getHistory(address, {
    limit: 100,
    sortBy: 'profit',
    order: 'desc',
  });
  
  const profitable = history.trades.filter(
    (trade) => trade.profit && parseFloat(trade.profit) > 0
  );
  
  const totalProfit = profitable.reduce(
    (sum, trade) => sum + parseFloat(trade.profit!),
    0
  );
  
  return {
    trades: profitable,
    count: profitable.length,
    totalProfit: totalProfit.toFixed(2),
    avgProfit: (totalProfit / profitable.length).toFixed(2),
  };
}
```

### Compare Traders

```typescript theme={null}
async function compareTraders(addresses: string[]) {
  const traders = await Promise.all(
    addresses.map(async (address) => {
      const stats = await sdk.trading.getStats(address);
      return {
        address,
        stats,
      };
    })
  );
  
  // Sort by volume
  traders.sort((a, b) => 
    parseFloat(b.stats.totalVolume) - parseFloat(a.stats.totalVolume)
  );
  
  return traders.map((trader, index) => ({
    rank: index + 1,
    address: trader.address,
    volume: trader.stats.totalVolume,
    trades: trader.stats.totalTrades,
    winRate: trader.stats.winRate,
  }));
}
```

### Monitor Real-Time Trading

```typescript theme={null}
async function monitorTrading(address: string) {
  let lastTrade: string | null = null;
  
  setInterval(async () => {
    const history = await sdk.trading.getHistory(address, {
      limit: 1,
    });
    
    if (history.trades.length > 0) {
      const latestTrade = history.trades[0];
      
      if (latestTrade.txHash !== lastTrade) {
        console.log('🔔 New trade detected!');
        console.log(`${latestTrade.tokenIn.symbol} → ${latestTrade.tokenOut.symbol}`);
        console.log(`Value: $${latestTrade.tokenIn.valueUsd}`);
        
        lastTrade = latestTrade.txHash;
      }
    }
  }, 30000); // Check every 30 seconds
}
```

### Calculate Trading Score

```typescript theme={null}
async function calculateTradingScore(address: string) {
  const stats = await sdk.trading.getStats(address);
  
  // Custom scoring algorithm
  const volumeScore = Math.min(
    (parseFloat(stats.totalVolume) / 1000000) * 100,
    100
  );
  
  const winRateScore = stats.winRate * 100;
  
  const activityScore = Math.min(
    (stats.totalTrades / 1000) * 100,
    100
  );
  
  const diversityScore = Math.min(
    ((stats.uniqueTokens + stats.uniqueDexs) / 50) * 100,
    100
  );
  
  const overallScore = (
    volumeScore * 0.4 +
    winRateScore * 0.3 +
    activityScore * 0.2 +
    diversityScore * 0.1
  );
  
  return {
    overall: Math.round(overallScore),
    breakdown: {
      volume: Math.round(volumeScore),
      winRate: Math.round(winRateScore),
      activity: Math.round(activityScore),
      diversity: Math.round(diversityScore),
    },
  };
}
```

## Error Handling

```typescript theme={null}
try {
  const stats = await sdk.trading.getStats(address);
} catch (error) {
  if (error.code === 'INSUFFICIENT_DATA') {
    console.log('Not enough trading history');
  } else if (error.code === 'INVALID_ADDRESS') {
    console.log('Invalid Ethereum address');
  } else {
    console.error('Error fetching trading stats:', error);
  }
}
```

## TypeScript Types

```typescript theme={null}
interface TradingStats {
  address: string;
  totalTrades: number;
  totalVolume: string;
  uniqueTokens: number;
  uniqueDexs: number;
  firstTradeAt: string;
  lastTradeAt: string;
  avgTradeSize: string;
  largestTrade: string;
  profitLoss: string;
  winRate: number;
  topTokens: TokenStats[];
  topDexs: DexStats[];
}

interface Trade {
  txHash: string;
  timestamp: string;
  dex: string;
  type: 'swap' | 'add_liquidity' | 'remove_liquidity';
  tokenIn: TokenAmount;
  tokenOut: TokenAmount;
  gasUsed: string;
  profit?: string;
  status: 'success' | 'failed';
}

interface TokenAmount {
  symbol: string;
  amount: string;
  valueUsd: string;
}
```

## Rate Limits

Trading endpoints have the following rate limits:

* `getStats`: 100 requests/minute
* `getHistory`: 60 requests/minute
* `getLeaderboard`: 20 requests/minute

See [Rate Limiting](/guides/rate-limiting) for more details.

## Next Steps

<CardGroup cols={2}>
  <Card title="Trust Layer SDK" icon="shield" href="/sdk/javascript/trust-layer">
    Work with attestations and trust
  </Card>

  <Card title="ZK Proofs SDK" icon="lock" href="/sdk/javascript/zk-proofs">
    Generate privacy-preserving proofs
  </Card>

  <Card title="Trading Use Cases" icon="chart-line" href="/use-cases/marketplace">
    See trading integration examples
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/trading/get-stats">
    Explore the Trading API
  </Card>
</CardGroup>
