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

# Get Portfolio Chart

> Get historical portfolio performance data for visualizing value changes over time

export const title_0 = undefined

export const cards_0 = undefined

# Portfolio Performance Chart

Get historical data to visualize your portfolio's performance over various time periods. This endpoint provides time-series data showing how your portfolio value has changed, perfect for creating charts and analyzing trends.

## Key Features

* **Multiple Time Ranges**: View data from 24 hours to all-time history
* **Time-Series Data**: Arrays of timestamps and corresponding values
* **Performance Tracking**: Track portfolio growth and declines over time
* **Historical Profit/Loss**: See how your PnL has evolved
* **Trend Analysis**: Identify patterns and market cycles in your portfolio

<Note>
  This endpoint is only available for users with a **Degen plan subscription**. You'll need a share token to access portfolio data. Learn more about [Share Token Authentication](/sharetoken).
</Note>

## Get Portfolio Chart Data

Retrieve historical portfolio performance data:

<CodeGroup>
  ```bash cURL theme={null}
  curl -H "X-API-KEY: your-api-key" \
       -H "sharetoken: YOUR_SHARE_TOKEN" \
    "https://api.coinstats.app/v1/portfolio/chart?type=1w"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.coinstats.app/v1/portfolio/chart?type=1w', {
    headers: {
      'X-API-KEY': 'your-api-key',
      'sharetoken': 'YOUR_SHARE_TOKEN'
    }
  });
  const chartData = await response.json();
  ```

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

  response = requests.get(
      'https://api.coinstats.app/v1/portfolio/chart',
      params={
          'type': '1w'
      },
      headers={
          'X-API-KEY': 'your-api-key',
          'sharetoken': 'YOUR_SHARE_TOKEN'
      }
  )
  chart_data = response.json()
  ```
</CodeGroup>

<Note>
  **8 credits** per request
</Note>

## Headers

| Header       | Required | Description                                               |
| ------------ | -------- | --------------------------------------------------------- |
| `X-API-KEY`  | Yes      | Your CoinStats API key                                    |
| `sharetoken` | Yes      | Your portfolio share token ([how to get it](/sharetoken)) |
| `passcode`   | No       | Passcode if your portfolio is protected                   |

## Query Parameters

| Parameter | Type   | Required | Description               |
| --------- | ------ | -------- | ------------------------- |
| `type`    | string | Yes      | Time range for chart data |

### Time Range Options

| Type  | Description      | Data Points        |
| ----- | ---------------- | ------------------ |
| `24h` | Last 24 hours    | Hourly data points |
| `1w`  | Last 7 days      | 6-hour intervals   |
| `1m`  | Last 30 days     | Daily data points  |
| `3m`  | Last 90 days     | Daily data points  |
| `6m`  | Last 180 days    | Daily data points  |
| `1y`  | Last 365 days    | Daily data points  |
| `all` | All-time history | Variable intervals |

### With Passcode

For passcode-protected portfolios, add the `passcode` header:

```bash theme={null}
curl -H "X-API-KEY: your-api-key" \
     -H "sharetoken: YOUR_SHARE_TOKEN" \
     -H "passcode: 123456" \
     "https://api.coinstats.app/v1/portfolio/chart?type=1m"
```

## Example Response

The response is an array of arrays, where each sub-array contains `[timestamp, value]`:

```json theme={null}
{
  "result": [
    [1701388800000, 125430.52],
    [1701475200000, 128945.76],
    [1701561600000, 126780.44],
    [1701648000000, 130205.18],
    [1701734400000, 132890.92],
    [1701820800000, 131450.38],
    [1701907200000, 134720.65]
  ]
}
```

### Data Format

* **First element**: Unix timestamp in milliseconds
* **Second element**: Portfolio value in USD at that timestamp

## Visualization Examples

### JavaScript Chart Example

Using Chart.js to visualize portfolio performance:

```javascript theme={null}
const response = await fetch('https://api.coinstats.app/v1/portfolio/chart?type=1m', {
  headers: {
    'X-API-KEY': 'your-api-key',
    'sharetoken': 'YOUR_SHARE_TOKEN'
  }
});
const data = await response.json();

// Transform data for Chart.js
const chartData = {
  labels: data.result.map(point => new Date(point[0]).toLocaleDateString()),
  datasets: [{
    label: 'Portfolio Value (USD)',
    data: data.result.map(point => point[1]),
    borderColor: 'rgb(75, 192, 192)',
    tension: 0.1
  }]
};

// Create chart
new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Portfolio Performance - Last 30 Days'
      }
    }
  }
});
```

### Python Visualization

Using matplotlib to plot portfolio data:

```python theme={null}
import requests
import matplotlib.pyplot as plt
from datetime import datetime

response = requests.get(
    'https://api.coinstats.app/v1/portfolio/chart',
    params={'type': '1m'},
    headers={
        'X-API-KEY': 'your-api-key',
        'sharetoken': 'YOUR_SHARE_TOKEN'
    }
)
data = response.json()

# Extract timestamps and values
timestamps = [datetime.fromtimestamp(point[0]/1000) for point in data['result']]
values = [point[1] for point in data['result']]

# Create plot
plt.figure(figsize=(12, 6))
plt.plot(timestamps, values, linewidth=2)
plt.title('Portfolio Performance - Last 30 Days')
plt.xlabel('Date')
plt.ylabel('Value (USD)')
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
```

## Use Cases

<CardGroup cols={2}>
  <Card title="Performance Dashboard" icon="chart-line">
    Build interactive dashboards showing portfolio growth over time
  </Card>

  <Card title="Trend Analysis" icon="magnifying-glass-chart">
    Identify bull and bear market cycles in your portfolio
  </Card>

  <Card title="Goal Tracking" icon="bullseye">
    Monitor progress toward investment goals with visual charts
  </Card>

  <Card title="Historical Reports" icon="file-chart-column">
    Generate historical performance reports for any time period
  </Card>
</CardGroup>

## Calculate Performance Metrics

Use chart data to calculate custom metrics:

```javascript theme={null}
async function getPortfolioMetrics(shareToken, period) {
  const response = await fetch(
    `https://api.coinstats.app/v1/portfolio/chart?type=${period}`,
    {
      headers: {
        'X-API-KEY': 'your-api-key',
        'sharetoken': shareToken
      }
    }
  );
  const data = await response.json();
  
  const values = data.result.map(p => p[1]);
  const firstValue = values[0];
  const lastValue = values[values.length - 1];
  const maxValue = Math.max(...values);
  const minValue = Math.min(...values);
  
  return {
    currentValue: lastValue,
    startValue: firstValue,
    change: lastValue - firstValue,
    changePercent: ((lastValue - firstValue) / firstValue * 100).toFixed(2),
    highValue: maxValue,
    lowValue: minValue,
    volatility: ((maxValue - minValue) / minValue * 100).toFixed(2)
  };
}

// Usage
const metrics = await getPortfolioMetrics('YOUR_SHARE_TOKEN', '1m');
console.log(`30-Day Performance: ${metrics.changePercent}%`);
console.log(`Volatility: ${metrics.volatility}%`);
```

## Comparing Time Periods

Compare performance across different time ranges:

```javascript theme={null}
async function comparePerformance(shareToken) {
  const periods = ['24h', '1w', '1m', '1y'];
  const results = {};
  
  for (const period of periods) {
    const response = await fetch(
      `https://api.coinstats.app/v1/portfolio/chart?type=${period}`,
      {
        headers: {
          'X-API-KEY': 'your-api-key',
          'sharetoken': shareToken
        }
      }
    );
    const data = await response.json();
    const values = data.result.map(p => p[1]);
    const change = ((values[values.length - 1] - values[0]) / values[0] * 100).toFixed(2);
    results[period] = `${change}%`;
  }
  
  return results;
}

// Output example:
// { '24h': '+2.4%', '1w': '+5.8%', '1m': '+12.3%', '1y': '+45.6%' }
```

## Error Handling

<AccordionGroup>
  <Accordion title="Missing Share Token (400)">
    ```json theme={null}
    {
      "error": "shareToken is required"
    }
    ```

    **Solution**: Include the share token in your request
  </Accordion>

  <Accordion title="Invalid Type Parameter (400)">
    ```json theme={null}
    {
      "error": "Invalid time range type"
    }
    ```

    **Solution**: Use one of the valid time range options (24h, 1w, 1m, 3m, 6m, 1y, all)
  </Accordion>

  <Accordion title="Unauthorized (401)">
    ```json theme={null}
    {
      "error": "Invalid API key"
    }
    ```

    **Solution**: Check that your API key is correct and active
  </Accordion>

  <Accordion title="Subscription Required (403)">
    ```json theme={null}
    {
      "error": "This endpoint requires a Degen plan subscription"
    }
    ```

    **Solution**: Upgrade to a Degen plan to access portfolio endpoints
  </Accordion>

  <Accordion title="Portfolio Not Found (404)">
    ```json theme={null}
    {
      "error": "Shared portfolio not found"
    }
    ```

    **Solution**: Verify your share token is correct
  </Accordion>

  <Accordion title="Passcode Required (409)">
    ```json theme={null}
    {
      "error": "Passcode required for this portfolio"
    }
    ```

    **Solution**: Include the correct passcode in your request
  </Accordion>
</AccordionGroup>

<Warning>
  Chart data availability depends on your portfolio's history. New portfolios may have limited historical data for longer time ranges.
</Warning>

## Best Practices

<AccordionGroup>
  <Accordion title="Optimize API Calls">
    * Cache chart data and refresh periodically rather than on every page load
    * Use appropriate time ranges for your use case (24h for real-time, 1m for recent trends)
  </Accordion>

  <Accordion title="Handle Missing Data">
    * Check for empty arrays or null values in responses
    * Implement fallbacks for portfolios with limited history
  </Accordion>

  <Accordion title="Visualization Tips">
    * Use line charts for continuous data
    * Add annotations for significant events (large deposits/withdrawals)
    * Include percentage changes in chart titles for context
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Portfolio Value" icon="wallet" href="/openapi/get-portfolio-value">
    Get current portfolio value and overall metrics
  </Card>

  <Card title="Portfolio Coins" icon="coins" href="/portfolio/portfolio-coins">
    View detailed holdings and coin-level performance
  </Card>

  <Card title="Portfolio Transactions" icon="clock-rotate-left" href="/openapi/get-portfolio-transactions">
    Access complete transaction history
  </Card>

  <Card title="Portfolio Snapshots" icon="camera" href="/openapi/get-portfolio-snapshot-items">
    Get historical portfolio snapshot data
  </Card>
</CardGroup>

## {title_0 || "Support"}

{cards_0 ? (
<CardGroup cols={2}>
<Card title="Support Documentation" icon="question" href="https://help.coinstats.app/en/articles/12002063">
  Check our comprehensive help center
</Card>

<Card title="Telegram Support" icon="telegram" href="https://t.me/+JPUMD1QAMTNmNGQy">
  Join our API support channel for real-time help
</Card>

 <Card title="Email Support" icon="telegram" href="mailto:api.support@coinstats.app">
  You can reach us directly at api.support@coinstats.app
</Card>
</CardGroup>
) : (
  <ul>
      <li><strong>Documentation</strong>: This site contains comprehensive API documentation</li>
      <li><strong>Telegram Chat</strong>: For quick help and to connect with other developers, join our <a href="https://t.me/+JPUMD1QAMTNmNGQy">API Support Telegram group</a></li>
      <li><strong>Email Support</strong>: You can reach us directly at <a href="mailto:api.support@coinstats.app"><strong><u>api.support@coinstats.app</u></strong></a> for personalized assistance.</li>
  </ul>
)}
