> ## 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.

# Get Trading History

> Get detailed trading history for a user

## Overview

Retrieve comprehensive trading history including individual trades, transactions, and performance metrics. This endpoint provides detailed transaction data perfect for building trading analytics, tax reporting, and performance tracking.

<Tip>
  Use this endpoint to display individual trades, analyze trading patterns, generate reports, and provide detailed transaction history to users.
</Tip>

## Parameters

<ParamField path="identity" type="string" required>
  User identity (ZKS ID or wallet address)

  <Note>
    ZKS ID is recommended for better performance and user experience
  </Note>
</ParamField>

<ParamField query="limit" type="number">
  Number of trades to return (default: 50, max: 1000)
</ParamField>

<ParamField query="offset" type="number">
  Number of trades to skip for pagination (default: 0)
</ParamField>

<ParamField query="timeframe" type="string">
  Time period for trades

  * `7d` - Last 7 days
  * `30d` - Last 30 days
  * `90d` - Last 90 days
  * `1y` - Last year
  * `all` - All time (default)
</ParamField>

<ParamField query="protocol" type="string">
  Filter by specific protocol

  * `uniswap` - Uniswap
  * `sushiswap` - SushiSwap
  * `1inch` - 1inch
  * `curve` - Curve
  * `balancer` - Balancer
  * `pancakeswap` - PancakeSwap
</ParamField>

<ParamField query="asset" type="string">
  Filter by asset symbol (e.g., ETH, USDC, WBTC)
</ParamField>

<ParamField query="chainId" type="number">
  Filter by specific blockchain

  * `1` - Ethereum mainnet
  * `137` - Polygon
  * `56` - BSC
  * `42161` - Arbitrum
  * `10` - Optimism
  * `250` - Fantom
  * `43114` - Avalanche
</ParamField>

<ParamField query="type" type="string">
  Filter by trade type

  * `swap` - Token swaps
  * `liquidity` - Liquidity provision/removal
  * `lending` - Lending/borrowing
  * `staking` - Staking operations
  * `yield` - Yield farming
</ParamField>

<ParamField query="sortBy" type="string">
  Sort trades by field

  * `timestamp` - By timestamp (default)
  * `value` - By trade value
  * `pnl` - By profit/loss
  * `volume` - By volume
</ParamField>

<ParamField query="sortOrder" type="string">
  Sort order

  * `desc` - Descending (default)
  * `asc` - Ascending
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Indicates if the request was successful
</ResponseField>

<ResponseField name="address" type="string">
  Resolved wallet address
</ResponseField>

<ResponseField name="zksId" type="string">
  ZKS ID if available, null otherwise
</ResponseField>

<ResponseField name="trades" type="array">
  Array of trade objects

  <Expandable title="trade properties">
    <ResponseField name="id" type="string">
      Unique trade identifier
    </ResponseField>

    <ResponseField name="timestamp" type="string">
      ISO 8601 timestamp of the trade
    </ResponseField>

    <ResponseField name="type" type="string">
      Type of trade (swap, liquidity, lending, staking, yield)
    </ResponseField>

    <ResponseField name="protocol" type="string">
      Protocol name where trade occurred
    </ResponseField>

    <ResponseField name="chainId" type="number">
      Blockchain where trade occurred
    </ResponseField>

    <ResponseField name="transactionHash" type="string">
      Blockchain transaction hash
    </ResponseField>

    <ResponseField name="blockNumber" type="number">
      Block number of the transaction
    </ResponseField>

    <ResponseField name="value" type="string">
      Total value of the trade in USD
    </ResponseField>

    <ResponseField name="volume" type="string">
      Trading volume in USD
    </ResponseField>

    <ResponseField name="fees" type="string">
      Fees paid for the trade
    </ResponseField>

    <ResponseField name="pnl" type="string">
      Profit/loss from the trade
    </ResponseField>

    <ResponseField name="assets" type="array">
      Assets involved in the trade

      <Expandable title="asset properties">
        <ResponseField name="symbol" type="string">
          Asset symbol
        </ResponseField>

        <ResponseField name="name" type="string">
          Asset name
        </ResponseField>

        <ResponseField name="amount" type="string">
          Amount of asset
        </ResponseField>

        <ResponseField name="value" type="string">
          Value in USD
        </ResponseField>

        <ResponseField name="action" type="string">
          Action (buy, sell, add, remove, lend, borrow)
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="metadata" type="object">
      Additional trade metadata

      <Expandable title="metadata properties">
        <ResponseField name="gasUsed" type="string">
          Gas used for the transaction
        </ResponseField>

        <ResponseField name="gasPrice" type="string">
          Gas price
        </ResponseField>

        <ResponseField name="slippage" type="number">
          Slippage percentage
        </ResponseField>

        <ResponseField name="priceImpact" type="number">
          Price impact percentage
        </ResponseField>

        <ResponseField name="route" type="array">
          Trading route (for swaps)
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="pagination" type="object">
  Pagination information

  <Expandable title="pagination properties">
    <ResponseField name="total" type="number">
      Total number of trades
    </ResponseField>

    <ResponseField name="limit" type="number">
      Number of trades returned
    </ResponseField>

    <ResponseField name="offset" type="number">
      Current offset
    </ResponseField>

    <ResponseField name="hasMore" type="boolean">
      Whether more trades are available
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="summary" type="object">
  Trading summary for the period

  <Expandable title="summary properties">
    <ResponseField name="totalTrades" type="number">
      Total number of trades
    </ResponseField>

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

    <ResponseField name="totalFees" type="string">
      Total fees paid
    </ResponseField>

    <ResponseField name="totalPnL" type="string">
      Total profit/loss
    </ResponseField>

    <ResponseField name="winRate" type="number">
      Percentage of profitable trades
    </ResponseField>

    <ResponseField name="averageTrade" type="string">
      Average trade value
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="timestamp" type="string">
  ISO 8601 timestamp of the response
</ResponseField>

## Examples

<CodeGroup>
  ```bash cURL (Basic History) theme={null}
  curl "https://api.onzks.com/v1/trading/history/alice.zks" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (Last 30 Days) theme={null}
  curl "https://api.onzks.com/v1/trading/history/alice.zks?timeframe=30d&limit=100" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (Uniswap Only) theme={null}
  curl "https://api.onzks.com/v1/trading/history/alice.zks?protocol=uniswap&type=swap" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (ETH Trades) theme={null}
  curl "https://api.onzks.com/v1/trading/history/alice.zks?asset=ETH&sortBy=value&sortOrder=desc" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (Wallet Address) theme={null}
  curl "https://api.onzks.com/v1/trading/history/0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  async function getTradingHistory(identity, options = {}) {
    const {
      limit = 50,
      offset = 0,
      timeframe = 'all',
      protocol,
      asset,
      chainId,
      type,
      sortBy = 'timestamp',
      sortOrder = 'desc'
    } = options;

    const params = new URLSearchParams({
      limit: limit.toString(),
      offset: offset.toString(),
      timeframe,
      sortBy,
      sortOrder
    });

    if (protocol) params.append('protocol', protocol);
    if (asset) params.append('asset', asset);
    if (chainId) params.append('chainId', chainId.toString());
    if (type) params.append('type', type);

    const response = await fetch(
      `https://api.onzks.com/v1/trading/history/${identity}?${params}`,
      {
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY'
        }
      }
    );

    const data = await response.json();

    console.log(`Trading History for ${data.zksId || data.address}:`);
    console.log(`Total Trades: ${data.summary.totalTrades}`);
    console.log(`Total Volume: $${parseFloat(data.summary.totalVolume).toLocaleString()}`);
    console.log(`Win Rate: ${data.summary.winRate}%`);
    console.log(`Total P&L: $${parseFloat(data.summary.totalPnL).toLocaleString()}`);

    return data;
  }

  // Usage examples
  await getTradingHistory('alice.zks');
  await getTradingHistory('alice.zks', { timeframe: '30d', limit: 100 });
  await getTradingHistory('alice.zks', { protocol: 'uniswap', type: 'swap' });
  await getTradingHistory('alice.zks', { asset: 'ETH', sortBy: 'value', sortOrder: 'desc' });
  ```

  ```python Python theme={null}
  import requests

  def get_trading_history(identity, limit=50, offset=0, timeframe='all', protocol=None, 
                         asset=None, chain_id=None, type=None, sort_by='timestamp', sort_order='desc'):
      params = {
          'limit': limit,
          'offset': offset,
          'timeframe': timeframe,
          'sortBy': sort_by,
          'sortOrder': sort_order
      }
      
      if protocol:
          params['protocol'] = protocol
      if asset:
          params['asset'] = asset
      if chain_id:
          params['chainId'] = chain_id
      if type:
          params['type'] = type
      
      response = requests.get(
          f'https://api.onzks.com/v1/trading/history/{identity}',
          headers={'Authorization': 'Bearer YOUR_API_KEY'},
          params=params
      )
      
      data = response.json()
      
      print(f"Trading History for {data.get('zksId', data['address'])}:")
      print(f"Total Trades: {data['summary']['totalTrades']}")
      print(f"Total Volume: ${float(data['summary']['totalVolume']):,.2f}")
      print(f"Win Rate: {data['summary']['winRate']}%")
      print(f"Total P&L: ${float(data['summary']['totalPnL']):,.2f}")
      
      return data

  # Usage examples
  get_trading_history('alice.zks')
  get_trading_history('alice.zks', timeframe='30d', limit=100)
  get_trading_history('alice.zks', protocol='uniswap', type='swap')
  get_trading_history('alice.zks', asset='ETH', sort_by='value', sort_order='desc')
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "success": true,
  "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
  "zksId": "alice.zks",
  "trades": [
    {
      "id": "trade_12345",
      "timestamp": "2024-01-20T15:45:00Z",
      "type": "swap",
      "protocol": "Uniswap V3",
      "chainId": 1,
      "transactionHash": "0xabcdef1234567890...",
      "blockNumber": 19000000,
      "value": "5000.00",
      "volume": "5000.00",
      "fees": "15.00",
      "pnl": "250.00",
      "assets": [
        {
          "symbol": "ETH",
          "name": "Ethereum",
          "amount": "2.0",
          "value": "5000.00",
          "action": "sell"
        },
        {
          "symbol": "USDC",
          "name": "USD Coin",
          "amount": "5000.00",
          "value": "5000.00",
          "action": "buy"
        }
      ],
      "metadata": {
        "gasUsed": "150000",
        "gasPrice": "20",
        "slippage": 0.5,
        "priceImpact": 0.1,
        "route": ["ETH", "USDC"]
      }
    },
    {
      "id": "trade_12346",
      "timestamp": "2024-01-20T14:30:00Z",
      "type": "liquidity",
      "protocol": "Uniswap V3",
      "chainId": 1,
      "transactionHash": "0x1234567890abcdef...",
      "blockNumber": 18999950,
      "value": "10000.00",
      "volume": "0.00",
      "fees": "30.00",
      "pnl": "0.00",
      "assets": [
        {
          "symbol": "ETH",
          "name": "Ethereum",
          "amount": "4.0",
          "value": "10000.00",
          "action": "add"
        },
        {
          "symbol": "USDC",
          "name": "USD Coin",
          "amount": "10000.00",
          "value": "10000.00",
          "action": "add"
        }
      ],
      "metadata": {
        "gasUsed": "200000",
        "gasPrice": "20",
        "slippage": 0.0,
        "priceImpact": 0.0,
        "route": []
      }
    },
    {
      "id": "trade_12347",
      "timestamp": "2024-01-20T13:15:00Z",
      "type": "swap",
      "protocol": "1inch",
      "chainId": 1,
      "transactionHash": "0x9876543210fedcba...",
      "blockNumber": 18999900,
      "value": "2500.00",
      "volume": "2500.00",
      "fees": "7.50",
      "pnl": "-50.00",
      "assets": [
        {
          "symbol": "USDC",
          "name": "USD Coin",
          "amount": "2500.00",
          "value": "2500.00",
          "action": "sell"
        },
        {
          "symbol": "WBTC",
          "name": "Wrapped Bitcoin",
          "amount": "0.1",
          "value": "2450.00",
          "action": "buy"
        }
      ],
      "metadata": {
        "gasUsed": "120000",
        "gasPrice": "18",
        "slippage": 1.2,
        "priceImpact": 0.3,
        "route": ["USDC", "ETH", "WBTC"]
      }
    }
  ],
  "pagination": {
    "total": 342,
    "limit": 50,
    "offset": 0,
    "hasMore": true
  },
  "summary": {
    "totalTrades": 342,
    "totalVolume": "1250000.50",
    "totalFees": "3750.00",
    "totalPnL": "125000.75",
    "winRate": 68.5,
    "averageTrade": "3654.97"
  },
  "timestamp": "2024-01-20T15:45:00Z"
}
```

## Use Cases

### 1. Trading Analytics Dashboard

Create a comprehensive trading analytics dashboard:

```javascript theme={null}
function createTradingAnalytics(trades) {
  const analytics = {
    performance: calculatePerformance(trades),
    patterns: analyzeTradingPatterns(trades),
    assets: analyzeAssetDistribution(trades),
    protocols: analyzeProtocolUsage(trades),
    timing: analyzeTradingTiming(trades)
  };
  
  return analytics;
}

function calculatePerformance(trades) {
  const totalPnL = trades.reduce((sum, trade) => sum + parseFloat(trade.pnl), 0);
  const totalVolume = trades.reduce((sum, trade) => sum + parseFloat(trade.volume), 0);
  const totalFees = trades.reduce((sum, trade) => sum + parseFloat(trade.fees), 0);
  
  const profitableTrades = trades.filter(trade => parseFloat(trade.pnl) > 0);
  const winRate = (profitableTrades.length / trades.length) * 100;
  
  return {
    totalPnL,
    totalVolume,
    totalFees,
    winRate,
    averageTrade: totalVolume / trades.length,
    roi: (totalPnL / totalVolume) * 100
  };
}
```

### 2. Trade Analysis

Analyze individual trades:

```javascript theme={null}
function analyzeTrade(trade) {
  const analysis = {
    profitability: parseFloat(trade.pnl) > 0 ? 'Profitable' : 'Loss',
    efficiency: parseFloat(trade.pnl) / parseFloat(trade.value) * 100,
    gasEfficiency: parseFloat(trade.value) / parseFloat(trade.metadata.gasUsed),
    slippage: trade.metadata.slippage,
    priceImpact: trade.metadata.priceImpact
  };
  
  return analysis;
}

function findBestTrades(trades, limit = 10) {
  return trades
    .sort((a, b) => parseFloat(b.pnl) - parseFloat(a.pnl))
    .slice(0, limit);
}

function findWorstTrades(trades, limit = 10) {
  return trades
    .sort((a, b) => parseFloat(a.pnl) - parseFloat(b.pnl))
    .slice(0, limit);
}
```

### 3. Protocol Analysis

Analyze trading by protocol:

```javascript theme={null}
function analyzeProtocols(trades) {
  const protocolStats = {};
  
  trades.forEach(trade => {
    if (!protocolStats[trade.protocol]) {
      protocolStats[trade.protocol] = {
        trades: 0,
        volume: 0,
        pnl: 0,
        fees: 0
      };
    }
    
    protocolStats[trade.protocol].trades++;
    protocolStats[trade.protocol].volume += parseFloat(trade.volume);
    protocolStats[trade.protocol].pnl += parseFloat(trade.pnl);
    protocolStats[trade.protocol].fees += parseFloat(trade.fees);
  });
  
  return Object.entries(protocolStats).map(([protocol, stats]) => ({
    protocol,
    ...stats,
    efficiency: stats.pnl / stats.volume * 100,
    averageTrade: stats.volume / stats.trades
  }));
}
```

### 4. Asset Analysis

Analyze trading by asset:

```javascript theme={null}
function analyzeAssets(trades) {
  const assetStats = {};
  
  trades.forEach(trade => {
    trade.assets.forEach(asset => {
      if (!assetStats[asset.symbol]) {
        assetStats[asset.symbol] = {
          name: asset.name,
          trades: 0,
          volume: 0,
          pnl: 0,
          actions: { buy: 0, sell: 0, add: 0, remove: 0 }
        };
      }
      
      assetStats[asset.symbol].trades++;
      assetStats[asset.symbol].volume += parseFloat(asset.value);
      assetStats[asset.symbol].actions[asset.action]++;
    });
  });
  
  return Object.entries(assetStats).map(([symbol, stats]) => ({
    symbol,
    ...stats,
    averageTrade: stats.volume / stats.trades
  }));
}
```

### 5. Time-based Analysis

Analyze trading patterns over time:

```javascript theme={null}
function analyzeTradingTiming(trades) {
  const hourlyStats = {};
  const dailyStats = {};
  const monthlyStats = {};
  
  trades.forEach(trade => {
    const date = new Date(trade.timestamp);
    const hour = date.getHours();
    const day = date.getDay();
    const month = date.getMonth();
    
    // Hourly analysis
    if (!hourlyStats[hour]) {
      hourlyStats[hour] = { trades: 0, volume: 0, pnl: 0 };
    }
    hourlyStats[hour].trades++;
    hourlyStats[hour].volume += parseFloat(trade.volume);
    hourlyStats[hour].pnl += parseFloat(trade.pnl);
    
    // Daily analysis
    if (!dailyStats[day]) {
      dailyStats[day] = { trades: 0, volume: 0, pnl: 0 };
    }
    dailyStats[day].trades++;
    dailyStats[day].volume += parseFloat(trade.volume);
    dailyStats[day].pnl += parseFloat(trade.pnl);
    
    // Monthly analysis
    if (!monthlyStats[month]) {
      monthlyStats[month] = { trades: 0, volume: 0, pnl: 0 };
    }
    monthlyStats[month].trades++;
    monthlyStats[month].volume += parseFloat(trade.volume);
    monthlyStats[month].pnl += parseFloat(trade.pnl);
  });
  
  return {
    hourly: hourlyStats,
    daily: dailyStats,
    monthly: monthlyStats
  };
}
```

## Best Practices

### 1. Pagination

Handle large trading histories with pagination:

```javascript theme={null}
async function getAllTradingHistory(identity, options = {}) {
  const allTrades = [];
  let offset = 0;
  const limit = 100;
  
  while (true) {
    const data = await getTradingHistory(identity, {
      ...options,
      limit,
      offset
    });
    
    allTrades.push(...data.trades);
    
    if (!data.pagination.hasMore) {
      break;
    }
    
    offset += limit;
  }
  
  return allTrades;
}
```

### 2. Filtering

Implement efficient filtering:

```javascript theme={null}
function filterTrades(trades, filters) {
  return trades.filter(trade => {
    if (filters.protocol && trade.protocol !== filters.protocol) return false;
    if (filters.type && trade.type !== filters.type) return false;
    if (filters.asset && !trade.assets.some(a => a.symbol === filters.asset)) return false;
    if (filters.chainId && trade.chainId !== filters.chainId) return false;
    if (filters.minValue && parseFloat(trade.value) < filters.minValue) return false;
    if (filters.maxValue && parseFloat(trade.value) > filters.maxValue) return false;
    if (filters.profitable && parseFloat(trade.pnl) <= 0) return false;
    
    return true;
  });
}
```

### 3. Caching

Cache trading history for performance:

```javascript theme={null}
let tradingHistoryCache = new Map();
const CACHE_TTL = 2 * 60 * 1000; // 2 minutes

async function getCachedTradingHistory(identity, options = {}) {
  const cacheKey = `${identity}-${JSON.stringify(options)}`;
  const cached = tradingHistoryCache.get(cacheKey);
  
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }
  
  const data = await getTradingHistory(identity, options);
  tradingHistoryCache.set(cacheKey, {
    data,
    timestamp: Date.now()
  });
  
  return data;
}
```

### 4. Real-time Updates

Subscribe to new trades:

```javascript theme={null}
function subscribeToNewTrades(identity, callback) {
  const ws = new WebSocket(`wss://api.onzks.com/v1/trading/history/${identity}/subscribe`);
  
  ws.onmessage = (event) => {
    const newTrade = JSON.parse(event.data);
    callback(newTrade);
  };
  
  return () => ws.close();
}
```

## Related Endpoints

* [Get Trading Stats](/api-reference/trading/get-stats) - Trading statistics
* [Get Trading Leaderboard](/api-reference/trading/get-leaderboard) - Top traders
* [Get Score](/api-reference/scores/get-score) - Overall ZKScore

## Troubleshooting

### "No trading history found"

**Cause**: User has no trading activity or filters are too restrictive.

**Solution**:

* Remove filters to see all trades
* Check if the user has any trading activity
* Try a longer timeframe

### "Invalid protocol"

**Cause**: Unsupported protocol value.

**Solution**:

* Use supported protocols: uniswap, sushiswap, 1inch, curve, balancer, pancakeswap
* Check for typos

### "Invalid asset"

**Cause**: Unsupported asset symbol.

**Solution**:

* Use standard asset symbols (ETH, USDC, WBTC, etc.)
* Check for typos

## Rate Limits

Trading history requests are subject to rate limits:

* **Free tier**: 60 requests per minute
* **Starter tier**: 300 requests per minute
* **Professional tier**: 1,000 requests per minute
* **Enterprise tier**: Custom limits

Implement caching to reduce API calls.
