← back to Watches
API_DOCUMENTATION.md
848 lines
# Omega Watch Price History API Documentation



## Table of Contents
- [Overview](#overview)
- [Getting Started](#getting-started)
- [Authentication](#authentication)
- [Base URL](#base-url)
- [Endpoints](#endpoints)
- [Client SDKs](#client-sdks)
- [WebSocket API](#websocket-api)
- [Code Examples](#code-examples)
- [Error Handling](#error-handling)
- [Rate Limiting](#rate-limiting)
- [Changelog](#changelog)
---
## Overview
The Omega Watch Price History API provides comprehensive access to historical price data, market analytics, and investment insights for Omega luxury watches.
### Features
- **50+ Omega Watches**: Complete historical data for Speedmaster, Seamaster, De Ville, and more
- **Historical Price Tracking**: Track price evolution from introduction to present
- **AI-Powered Predictions**: Machine learning price forecasts with confidence scores
- **Market Analytics**: Comprehensive market statistics and trends
- **Real-time Updates**: WebSocket support for live data streams
- **Advanced Search**: Full-text search with multiple filter options
- **Data Export**: Export data in JSON or CSV format
- **Watchlist Management**: Track favorite watches
- **Collection Statistics**: Analyze entire watch series
---
## Getting Started
### Quick Start (cURL)
```bash
# Get system health
curl http://45.61.58.125:7600/api/health
# Get all Speedmaster watches
curl "http://45.61.58.125:7600/api/watches?series=Speedmaster&limit=10"
# Search for moonwatch
curl "http://45.61.58.125:7600/api/search?q=moonwatch"
# Get price predictions
curl http://45.61.58.125:7600/api/price-predictions/speedmaster-moonwatch-1969
```
### Quick Start (JavaScript)
```javascript
// Using the SDK
import OmegaWatchAPI from './sdk/omega-api-client.js';
const api = new OmegaWatchAPI();
// Get all watches
const watches = await api.getWatches({ series: 'Speedmaster', limit: 10 });
console.log(`Found ${watches.total} watches`);
// Get trending watches
const trending = await api.getTrending(5);
console.log('Trending:', trending);
```
### Quick Start (Python)
```python
from omega_api_client import OmegaWatchAPI
# Initialize client
api = OmegaWatchAPI()
# Get statistics
stats = api.get_statistics()
print(f"Total Watches: {stats['totalWatches']}")
print(f"Average Appreciation: {stats['averageAppreciation']:.2f}%")
# Search for watches
results = api.search('moonwatch', series='Speedmaster')
for watch in results['results']:
print(f" - {watch['model']}")
```
---
## Authentication
Currently, most endpoints are **publicly accessible** without authentication.
Admin endpoints (cache management, backups) require an API key:
```bash
curl -H "X-API-Key: your-api-key" \
http://45.61.58.125:7600/api/admin/clear-cache
```
---
## Base URL
**Production**: `http://45.61.58.125:7600`
**WebSocket**: `ws://45.61.58.125:7600`
---
## Endpoints
### Health & System
#### GET `/api/health`
Get system health status with detailed metrics.
**Response:**
```json
{
"status": "healthy",
"timestamp": "2024-11-17T10:30:00.000Z",
"uptime": 3600.5,
"memory": {
"rss": 85678080,
"heapTotal": 54321664,
"heapUsed": 42123456
},
"cache": {
"keys": 15,
"size": 245678
},
"database": {
"watches": 52,
"collections": 8
},
"websocket": {
"connections": 3
}
}
```
---
### Watches
#### GET `/api/watches`
Get all watches with optional filtering and pagination.
**Query Parameters:**
| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `series` | string | Filter by series | `Speedmaster` |
| `minYear` | integer | Minimum year introduced | `1960` |
| `maxYear` | integer | Maximum year introduced | `2000` |
| `minPrice` | integer | Minimum current price (USD) | `5000` |
| `maxPrice` | integer | Maximum current price (USD) | `50000` |
| `page` | integer | Page number (default: 1) | `1` |
| `limit` | integer | Items per page (default: 50) | `20` |
**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/watches?series=Speedmaster&minYear=1960&limit=10"
```
**Example Response:**
```json
{
"total": 18,
"page": 1,
"limit": 10,
"totalPages": 2,
"watches": [
{
"id": "speedmaster-moonwatch-1969",
"model": "Speedmaster Professional Moonwatch ST 105.012",
"series": "Speedmaster",
"reference": "ST 105.012",
"yearIntroduced": 1963,
"description": "The legendary Moon Watch",
"priceHistory": [
{
"year": 1963,
"price": 95,
"condition": "new"
},
{
"year": 2024,
"price": 125000,
"condition": "vintage"
}
],
"specifications": {
"caseSize": "42mm",
"movement": "Calibre 321 (manual-winding)",
"caseMaterial": "Stainless steel"
}
}
]
}
```
#### GET `/api/watches/{id}/history`
Get complete price history for a specific watch.
**Path Parameters:**
- `id` (required): Watch identifier (e.g., `speedmaster-moonwatch-1969`)
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/watches/speedmaster-moonwatch-1969/history
```
**Example Response:**
```json
{
"watch": {
"id": "speedmaster-moonwatch-1969",
"model": "Speedmaster Professional Moonwatch ST 105.012",
"series": "Speedmaster",
"reference": "ST 105.012",
"yearIntroduced": 1963,
"specifications": {
"caseSize": "42mm",
"movement": "Calibre 321 (manual-winding)"
}
},
"priceHistory": [
{
"year": 1963,
"price": 95,
"condition": "new",
"source": "Launch price"
},
{
"year": 2024,
"price": 125000,
"condition": "vintage",
"source": "Current market"
}
],
"views": 1542
}
```
#### GET `/api/watches/trending`
Get most viewed watches.
**Query Parameters:**
- `limit` (optional): Number of results (default: 10, max: 50)
**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/watches/trending?limit=5"
```
---
### Search
#### GET `/api/search`
Advanced search with filters.
**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `q` | string | Yes | Search query |
| `series` | string | No | Filter by series |
| `movement` | string | No | Filter by movement type |
| `minPrice` | integer | No | Minimum price |
| `maxPrice` | integer | No | Maximum price |
| `page` | integer | No | Page number |
| `limit` | integer | No | Items per page |
**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/search?q=moonwatch&movement=manual&limit=5"
```
**Example Response:**
```json
{
"query": "moonwatch",
"total": 8,
"page": 1,
"limit": 5,
"totalPages": 2,
"results": [...]
}
```
---
### Analytics
#### GET `/api/price-predictions/{id}`
Get AI-generated price predictions for next 3 years.
**Path Parameters:**
- `id` (required): Watch identifier
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/price-predictions/speedmaster-moonwatch-1969
```
**Example Response:**
```json
{
"model": "Speedmaster Professional Moonwatch ST 105.012",
"currentPrice": 125000,
"trend": "increasing",
"averageAnnualChange": 8.5,
"predictions": [
{
"year": 2025,
"predictedPrice": 135625,
"confidence": 87
},
{
"year": 2026,
"predictedPrice": 147103,
"confidence": 82
},
{
"year": 2027,
"predictedPrice": 159607,
"confidence": 76
}
]
}
```
#### GET `/api/statistics`
Get comprehensive market statistics.
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/statistics
```
**Example Response:**
```json
{
"totalWatches": 52,
"totalSeries": 8,
"averageAppreciation": 247.85,
"topPerformers": [
{
"id": "speedmaster-moonwatch-1957",
"model": "Speedmaster Professional CK2915",
"appreciation": 210426.32,
"currentPrice": 200000
}
],
"lastUpdated": "2024-11-17T10:30:00.000Z",
"priceRanges": {
"Under $5,000": 8,
"$5,000 - $10,000": 12,
"$10,000 - $25,000": 15,
"$25,000 - $50,000": 10,
"Over $50,000": 7
},
"movementTypes": {
"Automatic": 35,
"Manual": 15,
"Other": 2
},
"appreciationByDecade": {
"1940s": 312.45,
"1950s": 285.67,
"1960s": 268.91,
"1970s": 198.34
}
}
```
#### GET `/api/analytics/investment-opportunities`
Get top investment opportunities.
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/analytics/investment-opportunities
```
#### GET `/api/analytics/risk-metrics`
Get risk-adjusted performance metrics.
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/analytics/risk-metrics
```
---
### Collections
#### GET `/api/collections`
Get all watch collections with statistics.
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/collections
```
**Example Response:**
```json
{
"collections": [
{
"series": "Speedmaster",
"count": 18,
"avgPrice": 45234,
"avgAppreciation": 312.45,
"avgYearIntroduced": 1969,
"watches": [...]
}
],
"totalCollections": 8
}
```
---
### Comparison
#### POST `/api/compare`
Compare multiple watches side-by-side.
**Request Body:**
```json
{
"watchIds": [
"speedmaster-moonwatch-1969",
"seamaster-300-1957"
]
}
```
**Example Request:**
```bash
curl -X POST http://45.61.58.125:7600/api/compare \
-H "Content-Type: application/json" \
-d '{"watchIds": ["speedmaster-moonwatch-1969", "seamaster-300-1957"]}'
```
**Example Response:**
```json
{
"watches": [
{
"id": "speedmaster-moonwatch-1969",
"model": "Speedmaster Professional Moonwatch",
"currentPrice": 125000,
"appreciation": 131478.95,
"priceHistory": [...]
}
],
"count": 2
}
```
---
### Export
#### GET `/api/export/{format}`
Export complete database.
**Path Parameters:**
- `format` (required): Export format (`json` or `csv`)
**Example Request (JSON):**
```bash
curl http://45.61.58.125:7600/api/export/json -o watches.json
```
**Example Request (CSV):**
```bash
curl http://45.61.58.125:7600/api/export/csv -o watches.csv
```
---
### Watchlist
#### POST `/api/watchlist`
Add or remove watches from user watchlist.
**Request Body:**
```json
{
"userId": "user123",
"watchId": "speedmaster-moonwatch-1969",
"action": "add"
}
```
**Example Request:**
```bash
curl -X POST http://45.61.58.125:7600/api/watchlist \
-H "Content-Type: application/json" \
-d '{
"userId": "user123",
"watchId": "speedmaster-moonwatch-1969",
"action": "add"
}'
```
#### GET `/api/watchlist/{userId}`
Get user watchlist.
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/watchlist/user123
```
---
### Admin
#### POST `/api/admin/clear-cache`
Clear server cache (requires API key).
**Example Request:**
```bash
curl -X POST http://45.61.58.125:7600/api/admin/clear-cache \
-H "X-API-Key: your-api-key"
```
#### GET `/api/admin/backup`
Create database backup (requires API key).
**Example Request:**
```bash
curl http://45.61.58.125:7600/api/admin/backup \
-H "X-API-Key: your-api-key"
```
---
## Client SDKs
### JavaScript/TypeScript SDK
**Installation:**
```bash
# Copy SDK file to your project
cp sdk/omega-api-client.js ./
```
**Usage:**
```javascript
import OmegaWatchAPI from './omega-api-client.js';
const api = new OmegaWatchAPI({
baseURL: 'http://45.61.58.125:7600',
timeout: 10000
});
// Get watches
const watches = await api.getWatches({ series: 'Speedmaster' });
// Search
const results = await api.search('moonwatch');
// Get predictions
const predictions = await api.getPricePredictions('speedmaster-moonwatch-1969');
// WebSocket
api.connectWebSocket({
onUpdate: (data) => console.log('Update:', data),
onError: (error) => console.error('Error:', error)
});
api.subscribeToWatch('speedmaster-moonwatch-1969');
```
### Python SDK
**Installation:**
```bash
# Copy SDK file to your project
cp sdk/omega_api_client.py ./
```
**Usage:**
```python
from omega_api_client import OmegaWatchAPI
# Initialize
api = OmegaWatchAPI(base_url='http://45.61.58.125:7600')
# Get watches
watches = api.get_watches(series='Speedmaster', limit=10)
print(f"Found {watches['total']} watches")
# Search
results = api.search('moonwatch', movement='manual')
# Get statistics
stats = api.get_statistics()
print(f"Average Appreciation: {stats['averageAppreciation']:.2f}%")
# Use context manager for automatic cleanup
with OmegaWatchAPI() as api:
health = api.get_health()
print(f"Status: {health['status']}")
```
---
## WebSocket API
Connect to real-time updates via WebSocket.
**Connection URL:** `ws://45.61.58.125:7600`
### Subscribe to Watch Updates
```javascript
const ws = new WebSocket('ws://45.61.58.125:7600');
ws.onopen = () => {
// Subscribe to specific watch
ws.send(JSON.stringify({
type: 'subscribe',
watchId: 'speedmaster-moonwatch-1969'
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'subscribed') {
console.log('Subscribed to:', data.watchId);
}
if (data.type === 'update') {
console.log('Price update:', data.data);
}
};
```
---
## Code Examples
### Get Top Performers
```javascript
const api = new OmegaWatchAPI();
const stats = await api.getStatistics();
console.log('Top 5 Performers:');
stats.topPerformers.forEach((watch, index) => {
console.log(`${index + 1}. ${watch.model}`);
console.log(` Appreciation: ${watch.appreciation.toFixed(2)}%`);
console.log(` Current Price: $${watch.currentPrice.toLocaleString()}`);
});
```
### Calculate ROI
```python
api = OmegaWatchAPI()
watch_id = 'speedmaster-moonwatch-1969'
watch = api.get_watch_by_id(watch_id)
price_history = watch['priceHistory']
original_price = price_history[0]['price']
current_price = price_history[-1]['price']
roi = ((current_price - original_price) / original_price) * 100
print(f"Watch: {watch['watch']['model']}")
print(f"Original Price (1963): ${original_price:,.0f}")
print(f"Current Price (2024): ${current_price:,.0f}")
print(f"ROI: {roi:,.2f}%")
```
### Compare Collections
```javascript
const api = new OmegaWatchAPI();
const collections = await api.getCollections();
// Sort by average appreciation
const sorted = collections.collections.sort((a, b) =>
b.avgAppreciation - a.avgAppreciation
);
console.log('Best Performing Collections:');
sorted.slice(0, 3).forEach(collection => {
console.log(`${collection.series}: ${collection.avgAppreciation.toFixed(2)}% avg appreciation`);
});
```
---
## Error Handling
All errors return a consistent format:
```json
{
"error": "Error message",
"details": "Additional error information"
}
```
### HTTP Status Codes
| Code | Description |
|------|-------------|
| 200 | Success |
| 400 | Bad Request - Invalid parameters |
| 404 | Not Found - Resource doesn't exist |
| 500 | Internal Server Error |
### Example Error Handling (JavaScript)
```javascript
try {
const watch = await api.getWatchById('invalid-id');
} catch (error) {
console.error('Error:', error.message);
// Error: HTTP 404: Watch not found
}
```
### Example Error Handling (Python)
```python
from omega_api_client import OmegaWatchAPI, OmegaWatchAPIError
api = OmegaWatchAPI()
try:
watch = api.get_watch_by_id('invalid-id')
except OmegaWatchAPIError as e:
print(f"API Error: {e}")
```
---
## Rate Limiting
Currently, there is **no rate limiting** enforced. However, fair usage is expected.
**Best Practices:**
- Cache responses when possible
- Use pagination for large datasets
- Implement exponential backoff for retries
- Use WebSocket for real-time updates instead of polling
---
## Changelog
### Version 2.0.0 (2024-11-17)
**New Features:**
- Interactive Swagger UI documentation at `/api/docs/swagger`
- Complete OpenAPI 3.0 specification
- JavaScript/TypeScript SDK with WebSocket support
- Python client library
- Postman collection for testing
- Enhanced caching with stale-while-revalidate
- Improved compression with Brotli support
**Analytics Endpoints:**
- `/api/analytics/predictions` - ML predictions
- `/api/analytics/market` - Market analysis
- `/api/analytics/investment-opportunities` - Investment insights
- `/api/analytics/risk-metrics` - Risk analysis
**Improvements:**
- Better error messages
- Response caching headers
- Performance optimizations
- Documentation improvements
---
## Interactive Documentation
### Swagger UI
Access interactive API documentation with "Try it out" functionality:
**URL:** http://45.61.58.125:7600/api/docs/swagger
Features:
- Test all endpoints directly in browser
- View request/response schemas
- Download OpenAPI specification
- See example responses
### OpenAPI Specification
Download the complete OpenAPI 3.0 specification:
- **JSON:** http://45.61.58.125:7600/api/docs/openapi.json
- **YAML:** http://45.61.58.125:7600/api/docs/openapi.yaml
---
## Support
For questions, issues, or feature requests:
- **API Docs:** http://45.61.58.125:7600/api/docs
- **Swagger UI:** http://45.61.58.125:7600/api/docs/swagger
- **Health Status:** http://45.61.58.125:7600/api/health
---
## License
MIT License - See LICENSE file for details