# Public Price API

### Overview

The W-Chain Price API provides real-time price data for tokens within the W-Chain ecosystem. Currently supporting WCO and WAVE tokens, this API delivers USD-denominated prices with caching for optimal performance. Future token additions will follow the same endpoint structure and response format.

### Base URL

`https://oracle.w-chain.com/api/price`

### Authentication

All Price API endpoints are publicly accessible and do not require authentication.

### Common Response Format

All price endpoints return a consistent JSON structure:

```json
{
  "price": 1.2345,
  "asset": "TOKEN_SYMBOL",
  "base_currency": "USD"
}
```

#### Response Fields

* `price`: Current price of the asset in USD (number)
* `asset`: Token symbol/identifier (string)
* `base_currency`: Always "USD" for price denomination (string)

***

### Supported Tokens

#### 1. WCO Token Price

**Endpoint:** `GET /wco`\
**Cache:** 1 minute\
**Description:** Retrieves the current USD price of WCO token from the latest price feed data.

**Example Request**

```
GET https://oracle.w-chain.com/api/price/wco
```

**Example Response**

```json
{
  "price": 0.0234,
  "asset": "WCO",
  "base_currency": "USD"
}
```

**Data Source**

* **Source**: Internal price feed database (`price_feed_wco` table)
* **Update Frequency**: Real-time price feed updates
* **Precision**: Full decimal precision as stored in database
* **Fallback**: Returns `null` if no price data available

**Technical Implementation**

* Queries the most recent price entry from `price_feed_wco` table
* Implements 60-second caching to reduce database load
* Orders by timestamp descending to get latest price
* Handles database errors gracefully

***

#### 2. WAVE Token Price

**Endpoint:** `GET /wave`\
**Cache:** Inherits from WCO cache (1 minute)\
**Description:** Retrieves the current USD price of WAVE token, calculated using WCO price and WAVE/WCO trading pair data.

**Example Request**

```
GET https://oracle.w-chain.com/api/price/wave
```

**Example Response**

```json
{
  "price": 1.4567,
  "asset": "WAVE",
  "base_currency": "USD"
}
```

**Price Calculation**

WAVE USD price is calculated using the formula:

```
WAVE_USD_Price = WAVE_WCO_Rate × WCO_USD_Price
```

Where:

* `WAVE_WCO_Rate`: Latest trading pair price from pair ID 1
* `WCO_USD_Price`: Current WCO price from `/api/price/wco`

**Data Sources**

* **Primary**: Trading pair data (pair ID: 1) for WAVE/WCO rate
* **Secondary**: WCO USD price from internal price feed
* **Dependencies**: Requires both WCO price and trading pair data

**Technical Implementation**

* Makes internal API call to `/api/price/wco` for WCO price
* Fetches latest WAVE/WCO pair price using `getLatestPairPricesById(1)`
* Multiplies pair rate by WCO USD price for final WAVE USD price
* Inherits caching behavior from WCO endpoint

***

### Future Token Support

Additional tokens will be added following the same patterns:

#### Endpoint Structure

```
GET /api/price/{token_symbol}
```

#### Response Format

All future tokens will maintain the same response structure:

```json
{
  "price": number,
  "asset": "TOKEN_SYMBOL",
  "base_currency": "USD"
}
```

#### Implementation Patterns

New tokens will follow one of these implementation patterns:

1. **Direct Price Feed** (like WCO):
   * Dedicated price feed table
   * Direct USD pricing
   * Simple database query
2. **Calculated Price** (like WAVE):
   * Based on trading pair data
   * Calculated against base token (typically WCO)
   * Derived USD pricing

***

### Error Handling

#### Database Errors

When price data cannot be retrieved:

```json
{
  "price": null,
  "asset": "TOKEN_SYMBOL",
  "base_currency": "USD"
}
```

#### Missing Dependencies

For calculated prices (like WAVE), if dependencies are unavailable:

* Returns appropriate error response
* Logs error details for debugging
* Maintains API consistency

### Caching Strategy

#### WCO Token

* **Cache Key**: `api_price_wco`
* **TTL**: 60 seconds
* **Strategy**: Database query caching
* **Invalidation**: Time-based expiration

#### WAVE Token

* **Cache Dependency**: Inherits from WCO caching
* **Additional Caching**: Trading pair data may have separate caching
* **Effective TTL**: Minimum of dependent cache TTLs

#### Benefits

* Reduces database load
* Improves response times
* Maintains data freshness
* Handles high-frequency requests efficiently

### Rate Limiting

No explicit rate limiting is enforced, but the caching mechanism naturally throttles database queries. Clients should:

* Respect cache durations
* Avoid excessive polling
* Implement client-side caching for frequently accessed data

### Use Cases

#### For DeFi Applications

* **Portfolio Valuation**: Calculate total portfolio value in USD
* **Trading Interfaces**: Display current market prices
* **Yield Farming**: Calculate APY and rewards in USD terms
* **Liquidity Pools**: Price LP tokens and calculate impermanent loss

#### For Analytics Platforms

* **Market Data**: Real-time price tracking and charts
* **Market Cap Calculations**: Combine with supply data for market cap
* **Price Alerts**: Trigger notifications on price movements
* **Historical Analysis**: Track price trends over time

#### For Wallets and Exchanges

* **Balance Display**: Show USD values of token holdings
* **Trading Pairs**: Price discovery for trading interfaces
* **Order Books**: Reference pricing for limit orders
* **Fee Calculations**: Calculate transaction fees in USD

### Data Freshness

#### WCO Price Updates

* **Source**: Real-time price feed system
* **Frequency**: Continuous updates based on market activity
* **Latency**: Sub-minute from price feed to API (with caching)

#### WAVE Price Updates

* **Source**: Trading pair activity on W-Chain DEX
* **Frequency**: Updates with each trade in WAVE/WCO pair
* **Latency**: Depends on WCO price freshness + pair data updates

### Best Practices

#### For Developers

1. **Handle Null Prices**: Always check for `null` price values
2. **Implement Fallbacks**: Have backup pricing sources when possible
3. **Cache Appropriately**: Respect API cache durations in your application
4. **Error Handling**: Implement robust error handling for network issues

#### For High-Frequency Applications

1. **Batch Requests**: Group multiple price requests when possible
2. **WebSocket Alternative**: Consider WebSocket connections for real-time updates
3. **Local Caching**: Implement application-level caching
4. **Rate Management**: Avoid overwhelming the API with requests

#### For Financial Applications

1. **Precision Handling**: Use appropriate decimal precision for financial calculations
2. **Timestamp Tracking**: Track when prices were last updated
3. **Audit Trails**: Log price data usage for compliance
4. **Backup Systems**: Implement redundant price sources

### Integration Examples

#### JavaScript/TypeScript

```javascript
// Fetch single token price
async function getTokenPrice(symbol) {
  try {
    const response = await fetch(`https://oracle.w-chain.com/api/price/${symbol.toLowerCase()}`);
    const data = await response.json();
    return data.price;
  } catch (error) {
    console.error(`Error fetching ${symbol} price:`, error);
    return null;
  }
}

// Fetch multiple token prices
async function getPortfolioValue(holdings) {
  const prices = await Promise.all([
    fetch('https://oracle.w-chain.com/api/price/wco').then(r => r.json()),
    fetch('https://oracle.w-chain.com/api/price/wave').then(r => r.json())
  ]);
  
  let totalValue = 0;
  holdings.forEach(holding => {
    const price = prices.find(p => p.asset === holding.symbol)?.price || 0;
    totalValue += holding.amount * price;
  });
  
  return totalValue;
}
```

#### Python

```python
import requests
import asyncio
import aiohttp

def get_token_price(symbol):
    """Fetch token price synchronously"""
    try:
        response = requests.get(f'https://oracle.w-chain.com/api/price/{symbol.lower()}')
        response.raise_for_status()
        return response.json()['price']
    except requests.RequestException as e:
        print(f"Error fetching {symbol} price: {e}")
        return None

async def get_multiple_prices(symbols):
    """Fetch multiple token prices asynchronously"""
    async with aiohttp.ClientSession() as session:
        tasks = []
        for symbol in symbols:
            url = f'https://oracle.w-chain.com/api/price/{symbol.lower()}'
            tasks.append(session.get(url))
        
        responses = await asyncio.gather(*tasks)
        prices = {}
        
        for response, symbol in zip(responses, symbols):
            if response.status == 200:
                data = await response.json()
                prices[symbol] = data['price']
            else:
                prices[symbol] = None
        
        return prices
```

### Monitoring and Observability

#### Health Checks

* Monitor API response times
* Track cache hit/miss ratios
* Alert on price data staleness
* Monitor database connectivity

#### Key Metrics

* **Response Time**: API endpoint latency
* **Cache Efficiency**: Cache hit percentage
* **Data Freshness**: Time since last price update
* **Error Rate**: Failed requests percentage
* **Dependency Health**: WCO price availability for WAVE calculations

### Support and Troubleshooting

#### Common Issues

1. **Null Prices**: Check if price feed is active and database is accessible
2. **Stale Data**: Verify cache TTL settings and price feed updates
3. **WAVE Price Errors**: Ensure both WCO price and trading pair data are available
4. **High Latency**: Check database performance and network connectivity

#### Getting Help

* Verify endpoint URLs and request format
* Check for network connectivity issues
* Review error messages in API responses
* Monitor W-Chain network status for underlying issues

***

*This API documentation covers the current implementation of WCO and WAVE price endpoints. As new tokens are added to the W-Chain ecosystem, they will follow similar patterns and be documented with the same level of detail.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.w-chain.com/advanced-features/public-price-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
