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

# TradingClient

> Use TradingClient methods for token holder distribution, sniper and bundler detection, trending pools, OHLCV charts, and Solana trading-lite analysis.

Use the `TradingClient` to access Webacy's trading analysis APIs. You can analyze token holder distribution, detect snipers and bundlers, and get quick trading insights.

## Initialization

<Info>
  **Prerequisites:**

  * SDK installed (`npm install @webacy-xyz/sdk`)
  * API key available (from your Webacy dashboard)
</Info>

```typescript theme={null}
import { TradingClient, Chain } from '@webacy-xyz/sdk';

const client = new TradingClient({
  apiKey: process.env.WEBACY_API_KEY,
  defaultChain: Chain.SOL, // Optional: set default chain
});
```

## Resources

The TradingClient provides access to these resources:

| Resource         | Description                                             |
| ---------------- | ------------------------------------------------------- |
| `holderAnalysis` | Token holder distribution, sniper/bundler detection     |
| `tradingLite`    | Quick trading analysis (Solana only)                    |
| `tokens`         | Token pools, trending data, economics, and OHLCV charts |

***

## Holder Analysis

### Get Holder Analysis

Get comprehensive analysis of token holder distribution.

```typescript theme={null}
const result = await client.holderAnalysis.get(
  'TokenMintAddress...',
  { chain: Chain.SOL }
);

console.log(`Total holders: ${result.totalHolders}`);
console.log(`Top 10 hold: ${result.top10Percentage}%`);
console.log(`Snipers detected: ${result.sniperCount}`);
```

**Response includes:**

* Top holders with wallet addresses and percentages
* First buyers analysis
* Sniper detection with confidence scores
* Bundler detection
* Developer wallet tracking
* Concentration metrics

### Response Example

```json theme={null}
{
  "totalHolders": 1523,
  "top10Percentage": 45.2,
  "top10Holders": [
    {
      "address": "ABC123...",
      "percentage": 12.5,
      "isSuspicious": false
    }
  ],
  "sniperCount": 8,
  "snipers": [
    {
      "address": "DEF456...",
      "confidence": 0.95,
      "buyBlock": 123456,
      "percentage": 2.1
    }
  ],
  "bundlerCount": 3,
  "devWallets": ["GHI789..."]
}
```

**Options:**

| Option  | Type    | Description                                          |
| ------- | ------- | ---------------------------------------------------- |
| `chain` | `Chain` | Blockchain to analyze (optional if defaultChain set) |

***

## Trading Lite

Quick, simplified token analysis optimized for trading decisions.

<Warning>
  Trading Lite is currently available for **Solana only**.
</Warning>

### Analyze Token

```typescript theme={null}
const result = await client.tradingLite.analyze('PumpTokenAddress...');

console.log(`Risk score: ${result.riskScore}`);
console.log(`Liquidity: $${result.liquidity}`);
console.log(`Is honeypot: ${result.isHoneypot}`);
```

**Response includes:**

* Quick risk assessment
* Liquidity metrics
* Honeypot detection
* Basic holder stats

***

## Tokens

### Fetch Token Pools

Retrieve liquidity pool information for a token.

```typescript theme={null}
const result = await client.tokens.getPools(
  '0xTokenAddress...',
  { chain: Chain.ETH }
);

for (const pool of result.pools) {
  console.log(`DEX: ${pool.dex}`);
  console.log(`Liquidity: $${pool.liquidity}`);
  console.log(`Pair: ${pool.pairToken}`);
}
```

### List Trending Tokens

Retrieve currently trending tokens on a chain.

```typescript theme={null}
const result = await client.tokens.getTrending({ chain: Chain.SOL });

for (const token of result.tokens) {
  console.log(`${token.symbol}: ${token.priceChange24h}%`);
}
```

### List Trending Pools

Use this method to retrieve the liquidity pools that are currently trending based on trading volume and activity.

```typescript theme={null}
const result = await client.tokens.getTrendingPools({ chain: Chain.ETH });

for (const pool of result.pools) {
  console.log(`${pool.name}`);
  console.log(`FDV: ${pool.fdv}`);
  console.log(`24h Volume: ${pool.volume.h24}`);
}
```

### Get Token Economics

Retrieve token economics data including supply, market cap, and holder statistics.

```typescript theme={null}
const result = await client.tokens.getToken(
  '0xTokenAddress...',
  {
    chain: Chain.ETH,
    metricsDate: '20-01-2024',  // DD-MM-YYYY format
  }
);

console.log(`Token: ${result.name} (${result.symbol})`);
console.log(`Price: $${result.metrics.priceUsd}`);
console.log(`Market Cap: $${result.metrics.marketCap}`);
console.log(`24h Volume: $${result.metrics.volume24h}`);
console.log(`Holders: ${result.metrics.holderCount}`);
```

**Supported chains:** ETH, BASE, BSC, POL, OPT, ARB, SOL

**Options:**

| Option        | Type     | Description               |
| ------------- | -------- | ------------------------- |
| `chain`       | `Chain`  | Blockchain to query       |
| `metricsDate` | `string` | Date in DD-MM-YYYY format |

### Get Pool OHLCV

Retrieve Open, High, Low, Close, Volume candlestick data for a liquidity pool.

```typescript theme={null}
const result = await client.tokens.getPoolOhlcv(
  '0xPoolAddress...',
  {
    chain: Chain.ETH,
    timeFrame: 'hour',  // 'minute', 'hour', or 'day'
    limit: 24,          // Number of data points
  }
);

console.log(`Pool: ${result.poolName}`);

for (const candle of result.data) {
  const time = new Date(candle.timestamp * 1000).toISOString();
  console.log(`${time} - O: ${candle.open} H: ${candle.high} L: ${candle.low} C: ${candle.close}`);
  console.log(`  Volume: ${candle.volume}`);
}
```

**Options:**

| Option            | Type     | Description                                                                                                           |
| ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------- |
| `chain`           | `Chain`  | Blockchain to query                                                                                                   |
| `timeFrame`       | `string` | `minute`, `hour`, or `day`                                                                                            |
| `beforeTimestamp` | `number` | Unix timestamp in **seconds** to fetch data before (use `Math.floor(Date.now() / 1000)` to convert from milliseconds) |
| `limit`           | `number` | Number of data points to return                                                                                       |

***

## Full Example

```typescript theme={null}
import { TradingClient, Chain, ValidationError } from '@webacy-xyz/sdk';

const client = new TradingClient({
  apiKey: process.env.WEBACY_API_KEY,
  defaultChain: Chain.SOL,
});

async function analyzeToken(tokenAddress: string) {
  try {
    // Get holder analysis
    const holders = await client.holderAnalysis.get(tokenAddress);

    // Check for red flags
    const redFlags: string[] = [];

    // High concentration
    if (holders.top10Percentage > 80) {
      redFlags.push(`High concentration: Top 10 hold ${holders.top10Percentage}%`);
    }

    // Snipers
    if (holders.sniperCount > 5) {
      redFlags.push(`${holders.sniperCount} snipers detected`);
    }

    // Bundlers
    if (holders.bundlerCount > 0) {
      redFlags.push(`${holders.bundlerCount} bundlers detected`);
    }

    // Quick analysis (Solana)
    const quickAnalysis = await client.tradingLite.analyze(tokenAddress);

    if (quickAnalysis.isHoneypot) {
      redFlags.push('Honeypot detected!');
    }

    return {
      safe: redFlags.length === 0,
      redFlags,
      holders,
      quickAnalysis,
    };

  } catch (error) {
    if (error instanceof ValidationError) {
      console.error('Invalid token address:', error.message);
    }
    throw error;
  }
}

// Usage
const analysis = await analyzeToken('PumpTokenMint...');

if (!analysis.safe) {
  console.warn('Red flags detected:');
  analysis.redFlags.forEach(flag => console.warn(`  - ${flag}`));
}
```

## Use Cases

<CardGroup cols={2}>
  <Card title="Token Launch Analysis" icon="rocket">
    Detect snipers and bundlers on new token launches
  </Card>

  <Card title="Rug Pull Detection" icon="triangle-exclamation">
    Identify concentrated holdings and dev wallets
  </Card>

  <Card title="Trading Signals" icon="signal">
    Quick risk assessment for trading decisions
  </Card>

  <Card title="Due Diligence" icon="magnifying-glass">
    Comprehensive holder analysis before investing
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="ThreatClient" icon="shield" href="/sdk/threat-client">
    Address and contract security analysis
  </Card>

  <Card title="Error Handling" icon="bug" href="/sdk/error-handling">
    Handle errors gracefully
  </Card>
</CardGroup>
