Quotes Analytics API - Market Data Analytics & Reporting
Overview
The QuotesAnalyticsController is a C++ REST API controller that generates comprehensive market analytics reports by analyzing quote data across multiple asset classes. It provides insights into market movements, top performers, and statistical summaries.
Features
- Multi-Asset Coverage: Analyzes stocks, crypto, ETFs, commodities, currencies, and more
- Top Performers Analysis: Identifies top gainers, losers, and most active assets
- Market Statistics: Calculates aggregate metrics by asset type
- Real-time Reporting: Generates JSON reports from current market data
- MongoDB Integration: Queries quote data from multiple collections
Architecture
Data Models
QuoteData
struct QuoteData {
std::string sravz_id;
std::string symbol;
std::string name;
std::string asset_type; // stocks, crypto, etf, etc.
double last_price;
double change;
double change_percent;
double volume;
double open;
double high;
double low;
double previous_close;
std::string price_capture_time;
};
AnalyticsSummary
struct AnalyticsSummary {
int total_assets;
std::vector<QuoteData> top_gainers;
std::vector<QuoteData> top_losers;
std::vector<QuoteData> most_active;
std::map<std::string, int> asset_type_counts;
std::map<std::string, double> avg_change_by_type;
double overall_market_change;
std::string report_timestamp;
};
API Endpoint
Generate Quotes Analytics Report
Endpoint: GET /api/analytics/quotes?top_count=10
Generates a comprehensive market analytics report.
Query Parameters:
top_count(optional): Number of top performers to include (default: 10)
Response:
{
"report_timestamp": "2024-11-24T10:30:00Z",
"total_assets": 5247,
"overall_market_change": 0.45,
"top_gainers": [
{
"sravz_id": "NVDA",
"symbol": "NVDA",
"name": "NVIDIA Corporation",
"asset_type": "stocks",
"last_price": 485.50,
"change": 25.30,
"change_percent": 5.50,
"volume": 45000000
}
],
"top_losers": [
{
"sravz_id": "XYZ",
"symbol": "XYZ",
"name": "XYZ Corp",
"asset_type": "stocks",
"last_price": 45.20,
"change": -3.50,
"change_percent": -7.20,
"volume": 12000000
}
],
"most_active": [
{
"sravz_id": "TSLA",
"symbol": "TSLA",
"name": "Tesla Inc",
"asset_type": "stocks",
"last_price": 245.00,
"volume": 125000000
}
],
"asset_type_counts": {
"stocks": 3500,
"crypto": 250,
"etf": 1200,
"commodities": 50,
"currency": 200,
"index": 25,
"futures": 22
},
"avg_change_by_type": {
"stocks": 0.35,
"crypto": 1.25,
"etf": 0.28,
"commodities": -0.15,
"currency": 0.05
}
}
Supported Asset Classes
The controller analyzes quotes from the following MongoDB collections:
- quotes_stocks - Stock market quotes
- quotes_crypto - Cryptocurrency quotes
- quotes_etf - ETF quotes
- quotes_commodities - Commodity quotes
- quotes_currency - Foreign exchange quotes
- quotes_index - Market index quotes
- quotes_futures - Futures contracts
- quotes_mortgage - Mortgage rates
- quotes_rates - Interest rates
- quotes_vix - Volatility index
Implementation Details
Analytics Calculation Workflow
- Load All Quotes: Query all quote collections from MongoDB
- Parse Quote Data: Convert MongoDB documents to QuoteData structures
- Calculate Top Gainers: Sort by
change_percent(descending) - Calculate Top Losers: Sort by
change_percent(ascending) - Calculate Most Active: Sort by
volume(descending) - Aggregate by Type: Count and average changes by asset type
- Calculate Overall Market: Weighted average of all asset changes
- Generate Report: Serialize analytics to JSON
Top Performers Logic
// Top Gainers: Sort by change_percent descending
std::sort(quotes.begin(), quotes.end(),
[](const QuoteData& a, const QuoteData& b) {
return a.change_percent > b.change_percent;
});
// Top Losers: Sort by change_percent ascending
std::sort(quotes.begin(), quotes.end(),
[](const QuoteData& a, const QuoteData& b) {
return a.change_percent < b.change_percent;
});
// Most Active: Sort by volume descending
std::sort(quotes.begin(), quotes.end(),
[](const QuoteData& a, const QuoteData& b) {
return a.volume > b.volume;
});
Usage Example
Generate Analytics Report
#include <quotes_analytics_controller.hpp>
auto mongoClient = std::make_shared<MongoClient>();
auto analyticsController = std::make_shared<QuotesAnalyticsController>(mongoClient);
// Generate report with top 10 performers
std::string report = analyticsController->generateQuotesReport(10);
// Generate report with top 25 performers
std::string detailed_report = analyticsController->generateQuotesReport(25);
Integration with Router
// In router.cpp
void router::handle_get_analytics_quotes(http::request<http::string_body> &req,
http::response<http::string_body> &res) {
// Parse top_count from query parameters (default: 10)
int top_count = extract_query_param(req.target(), "top_count", 10);
std::string report = quotesAnalyticsController_->generateQuotesReport(top_count);
res.body() = report;
res.set(http::field::content_type, "application/json");
res.result(http::status::ok);
}
Performance Considerations
Optimization Strategies
- Efficient Queries: Use MongoDB projection to fetch only needed fields
- Parallel Collection Queries: Query multiple collections concurrently
- In-Memory Sorting: All sorting done in-memory for speed
- Minimal Allocations: Reuse vectors and avoid unnecessary copies
- Lazy Evaluation: Only calculate requested analytics
Scaling for Large Datasets
// For very large datasets, consider:
// 1. Pagination
// 2. MongoDB aggregation pipelines
// 3. Pre-calculated daily summaries
// 4. Caching frequent reports
Error Handling
try {
std::string report = analyticsController->generateQuotesReport(10);
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "Analytics generation failed: " << e.what();
// Return error response
}
Use Cases
1. Market Dashboard
Display real-time market overview with top movers:
fetch('/api/analytics/quotes?top_count=10')
.then(response => response.json())
.then(data => {
displayMarketOverview(data);
displayTopGainers(data.top_gainers);
displayTopLosers(data.top_losers);
});
2. Alerts & Notifications
Monitor for significant market movements:
auto report = generateQuotesReport(50);
auto summary = parseReport(report);
if (summary.overall_market_change > 2.0) {
sendAlert("Significant market rally: +" +
std::to_string(summary.overall_market_change) + "%");
}
3. Research & Analysis
Analyze sector performance:
auto report = generateQuotesReport(100);
// Filter by asset_type
auto tech_stocks = filterByType(report, "tech_stocks");
// Calculate sector metrics
auto sector_analytics = calculateSectorMetrics(tech_stocks);
4. Trading Signals
Identify trading opportunities:
auto report = generateQuotesReport(25);
// Find high-volume gainers
auto signals = findHighVolumeGainers(report.most_active, report.top_gainers);
Testing
Unit Tests
TEST_F(QuotesAnalyticsTest, GenerateReport) {
auto controller = createQuotesAnalyticsController();
std::string report = controller->generateQuotesReport(10);
ASSERT_FALSE(report.empty());
// Validate JSON structure
auto json_report = boost::json::parse(report);
ASSERT_TRUE(json_report.is_object());
}
TEST_F(QuotesAnalyticsTest, TopGainers) {
auto summary = loadTestData();
ASSERT_EQ(summary.top_gainers.size(), 10);
ASSERT_GT(summary.top_gainers[0].change_percent,
summary.top_gainers[1].change_percent);
}
Integration Tests
Tests verify:
- Correct data loading from all quote collections
- Accurate sorting of top performers
- Proper JSON serialization
- Error handling for missing data
Monitoring & Logging
The controller logs important metrics:
[INFO] Loading quotes from 10 collections...
[INFO] Loaded 5247 total quotes
[INFO] Calculated analytics: Top 10 performers
[INFO] Generated analytics report (12.5KB)
[DEBUG] Top gainer: NVDA +5.50%
[DEBUG] Top loser: XYZ -7.20%
[DEBUG] Overall market change: +0.45%
Future Enhancements
- Historical Trends: Track and compare analytics over time
- Sector Analysis: Group stocks by industry/sector
- Correlation Analysis: Find correlated asset movements
- Volatility Metrics: Calculate standard deviation and beta
- Custom Filters: Allow filtering by market cap, sector, etc.
- Real-time Streaming: WebSocket updates for live analytics
- Machine Learning: Predictive analytics using historical data
- Alerts Configuration: User-defined alert thresholds
See Also
- PnL Controller - Portfolio profit/loss calculations
- MongoDB Service - Database integration
- REST API Router - Routing architecture
- Boost Beast REST API - HTTP server implementation
