> ## Documentation Index
> Fetch the complete documentation index at: https://natureloved-staxiq-48.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Analyzing Your Portfolio

> Understand your Bitcoin DeFi holdings, track performance, and identify protocol positions with Staxiq analytics

## Overview

Staxiq provides comprehensive portfolio analytics for your Stacks wallet, showing your STX and sBTC balances, protocol positions, transaction history, and 30-day performance trends.

## Portfolio Dashboard Components

Your portfolio dashboard displays several key components:

<CardGroup cols={2}>
  <Card title="Balance Overview" icon="wallet">
    Real-time STX and sBTC balances with USD valuations
  </Card>

  <Card title="Performance Chart" icon="chart-line">
    30-day portfolio value trend with percentage gains
  </Card>

  <Card title="Protocol Positions" icon="layer-group">
    Active positions across detected DeFi protocols
  </Card>

  <Card title="Transaction History" icon="clock-rotate-left">
    Recent wallet activity and interactions
  </Card>
</CardGroup>

## Viewing Your Balances

### STX Balance

Your STX holdings are displayed in the portfolio summary:

```jsx theme={null}
<div className="bg-[#141c2e]/50 border border-[#2a3f6a] p-4 rounded-xl">
  <p className="text-sm text-[#8899bb] uppercase">STX Balance</p>
  <p className="text-3xl font-bold text-white">
    {stxBalance} <span className="text-lg">STX</span>
  </p>
</div>
```

### sBTC Balance

Your Bitcoin holdings on Stacks (sBTC) are highlighted:

```jsx theme={null}
<div className="bg-bitcoin/10 border border-bitcoin/20 p-4 rounded-xl">
  <p className="text-sm text-bitcoin font-semibold uppercase">sBTC Balance</p>
  <p className="text-3xl font-bold text-white">
    {sbtcBalance} <span className="text-lg">sBTC</span>
  </p>
</div>
```

<Note>
  sBTC (Stacks Bitcoin) is a 1:1 Bitcoin-backed asset on Stacks. It represents actual BTC locked in the protocol.
</Note>

## Understanding Portfolio Performance

### 30-Day Chart

Staxiq generates a portfolio performance chart showing your value trend:

```javascript theme={null}
function generateChartData(currentValue, address) {
  const data = [];
  const days = 30;
  const baseValue = currentValue * 0.8;
  
  for (let i = days; i >= 0; i--) {
    const noise = (customRandom() - 0.45) * currentValue * 0.08;
    const trend = (currentValue - baseValue) * ((days - i) / days);
    data.push({
      day: i === 0 ? 'Today' : `${i}d`,
      value: parseFloat(Math.max(0, baseValue + trend + noise).toFixed(2)),
    });
  }
  return data.reverse();
}
```

The chart displays:

* **X-axis**: Time period (30 days ago to today)
* **Y-axis**: Portfolio value in USD
* **Gradient fill**: Visual representation of value trend
* **Performance badge**: Percentage gain/loss with direction indicator

<Steps>
  <Step title="Hover Over Chart">
    Hover over any point on the chart to see the exact portfolio value for that day:

    ```jsx theme={null}
    <CustomTooltip>
      <p style={{ color: '#F7931A' }}>${payload[0].value.toLocaleString()}</p>
      <p style={{ color: '#8899bb' }}>{payload[0].payload.day}</p>
    </CustomTooltip>
    ```
  </Step>

  <Step title="Check Performance Badge">
    The performance badge shows your overall gain:

    ```jsx theme={null}
    <span style={{
      background: '#22c55e22',
      color: '#22c55e',
      border: '1px solid #22c55e44'
    }}>
      ↑ +12.5%
    </span>
    ```
  </Step>

  <Step title="Compare Time Periods">
    Use the chart to identify trends and compare your current value to previous periods.
  </Step>
</Steps>

## Detecting Protocol Positions

Staxiq automatically detects which DeFi protocols you have active positions in by analyzing:

1. **Token Balances**: Checks for protocol receipt tokens (stSTX, LP tokens, etc.)
2. **Transaction History**: Identifies recent interactions with protocol contracts

### How Protocol Detection Works

```javascript theme={null}
export async function detectWalletProtocols(address) {
  // Fetch token balances and recent transactions
  const [tokenBalances, recentTxs] = await Promise.all([
    fetchTokenBalances(address),
    fetchRecentTxs(address),
  ]);
  
  const detected = [];
  
  for (const protocol of PROTOCOL_CONTRACTS) {
    const tokenBalance = tokenBalances[protocol.tokenContract]?.balance ?? '0';
    const hasToken = BigInt(tokenBalance) > 0n;
    
    // Check if wallet has transacted with protocol
    const hasInteracted = recentTxs.some(tx =>
      tx.contract_call?.contract_id?.startsWith(protocol.contractAddr)
    );
    
    if (hasToken || hasInteracted) {
      detected.push({
        ...protocol,
        balance: tokenBalance,
        confidence: hasToken ? 'confirmed' : 'likely',
      });
    }
  }
  
  return detected;
}
```

### Supported Protocol Detections

Staxiq can detect positions in:

<CardGroup cols={3}>
  <Card title="StackingDAO" icon="coins">
    **stSTX** liquid stacking tokens
  </Card>

  <Card title="ALEX Lab" icon="shuffle">
    **atALEX** auto-compounding positions
  </Card>

  <Card title="Zest Protocol" icon="building-columns">
    **zsBTC** lending positions
  </Card>

  <Card title="Bitflow" icon="water">
    **LP tokens** for liquidity pools
  </Card>

  <Card title="Hermetica" icon="circle-dollar">
    **USDh** synthetic dollar positions
  </Card>

  <Card title="Velar" icon="chart-candlestick">
    **LP tokens** and perpetuals
  </Card>
</CardGroup>

### Protocol Contract References

Here are the contract addresses Staxiq monitors:

```javascript theme={null}
const PROTOCOL_CONTRACTS = [
  {
    id: 'stackingdao',
    name: 'StackingDAO',
    asset: 'stSTX',
    tokenContract: 'SP4SZE494VC2YC5JYG7AYFQ44F5Q4PYV7DVMDPBG.ststx-token',
  },
  {
    id: 'zest',
    name: 'Zest Protocol',
    asset: 'zsBTC',
    tokenContract: 'SP2VCQJGH7PHP2DJK7Z0V48AGBHQAW3R3ZW1QF4N.zest-reward-dist',
  },
  {
    id: 'alex',
    name: 'ALEX Lab',
    asset: 'atALEX',
    tokenContract: 'SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9.auto-alex-v3',
  },
  // ... more protocols
];
```

<Tip>
  If you hold protocol tokens but they're not showing up, wait for the next refresh cycle (30 seconds) or check that you're on the correct network.
</Tip>

## Understanding Your Data

### Portfolio Refresh Cycle

Your portfolio data automatically refreshes:

```javascript theme={null}
useEffect(() => {
  fetchPortfolio();
  
  // Auto-refresh every 30 seconds
  const interval = setInterval(fetchPortfolio, 30000);
  return () => clearInterval(interval);
}, [address]);
```

* **Initial load**: When you first connect
* **Automatic refresh**: Every 30 seconds
* **Manual refresh**: Reload the page

### Data Sources

Staxiq pulls data from:

1. **Hiro API**: For wallet balances and transaction history
2. **Stacks Blockchain**: For real-time network data
3. **DeFi Llama**: For protocol TVL and APY data
4. **CoinGecko**: For STX price data

## Analyzing Your Activity

<Steps>
  <Step title="Check Total Value">
    Review your total portfolio value in USD, calculated from:

    ```javascript theme={null}
    totalUSD = (stxBalance * stxPrice) + (sbtcBalance * btcPrice)
    ```
  </Step>

  <Step title="Identify Protocol Positions">
    See which protocols you're actively using in the "Wallet Protocols" section.
  </Step>

  <Step title="Review Transaction Count">
    Your transaction count (`txCount`) influences AI strategy recommendations:

    * **\< 3 txs**: Considered a new user, gets beginner-friendly advice
    * **> 20 txs**: Considered experienced, gets advanced strategies
  </Step>

  <Step title="Track Performance Trend">
    Use the 30-day chart to understand if your portfolio is growing or declining.
  </Step>
</Steps>

## Portfolio Insights

### New User Detection

If you're new to Stacks DeFi, Staxiq provides extra context:

```javascript theme={null}
const isNewUser = strategyCount === 0 && txCount < 3;

if (isNewUser) {
  // Shows beginner-friendly explanations
  // Recommends safe starting protocols
  // Provides educational content
}
```

### Experienced User Recognition

For experienced users, Staxiq offers advanced insights:

```javascript theme={null}
const isExperienced = strategyCount > 5 || txCount > 20;

if (isExperienced) {
  // Advanced multi-protocol strategies
  // Yield optimization tactics
  // Compounding recommendations
}
```

## Troubleshooting

### Portfolio Shows "--" or Loading State

<Warning>
  If your portfolio stays in loading state:

  1. Check your internet connection
  2. Verify the Hiro API is accessible
  3. Try disconnecting and reconnecting your wallet
  4. Clear browser cache and refresh
</Warning>

### Protocol Positions Not Detected

If you know you have a protocol position but it's not showing:

* Ensure you hold the protocol's receipt token (not just the base asset)
* Check that you've completed the deposit transaction
* Wait for the next blockchain confirmation
* Verify you're on the correct network

### Performance Chart Not Updating

The chart uses your current value and address to generate historical data. If it seems stuck:

```javascript theme={null}
// Chart regenerates when these values change:
const data = useMemo(() => 
  generateChartData(value, address), 
  [value, address]
);
```

Disconnect and reconnect to force a regeneration.

## Next Steps

With your portfolio analyzed, you can:

* [Use the AI Copilot](/guides/using-ai-copilot) for personalized strategy recommendations
* [Compare protocols](/guides/comparing-protocols) to optimize your yields
* [Understand risk profiles](/guides/understanding-risk) before making moves

## Related Resources

* [API Reference: Portfolio Hook](/api/hooks/use-portfolio)
* [Connecting Your Wallet](/guides/connecting-wallet)
* [Protocol Comparison Guide](/guides/comparing-protocols)
