Statistics & Analytics

Statistics & Analytics

Transform your aircraft tracking data into actionable insights

SkySpy provides comprehensive statistics and analytics capabilities for tracking aircraft activity, analyzing flight patterns, monitoring system performance, and gamification features. This guide covers all available metrics, real-time streaming, historical analysis, and data export options.


Overview

Architecture

graph TB
    subgraph "Data Sources"
        ADS[ADS-B Receiver]
        ACARS[ACARS Decoder]
    end

    subgraph "Processing Layer"
        CACHE[(Redis Cache)]
        DB[(PostgreSQL)]
        CELERY[Celery Workers]
    end

    subgraph "API Layer"
        REST[REST API]
        WS[Socket.IO]
    end

    subgraph "Frontend"
        DASH[Stats Dashboard]
        GAME[Gamification View]
    end

    ADS --> DB
    ACARS --> DB
    DB --> CELERY
    CELERY --> CACHE
    CACHE --> REST
    CACHE --> WS
    REST --> DASH
    WS --> DASH
    REST --> GAME
    WS --> GAME

Components

ComponentPurposeTechnology
REST APIRequest-response statisticsDjango REST Framework
Socket.IOReal-time streaming updatesSocket.IO
DashboardInteractive visualizationsReact + Recharts
CachePerformance optimizationRedis

Pro Tip: All statistics are cached for performance with configurable TTLs, and most support customizable time ranges.


Aircraft Statistics

Core metrics about tracked aircraft within your coverage area.

Live Metrics Dashboard

MetricIconDescription
Total AircraftplaneCurrently tracked aircraft count with real-time updates
With Positionmap-pinAircraft transmitting valid GPS coordinates
MilitaryshieldActive military aircraft in coverage area
Emergenciestriangle-exclamationAircraft squawking 7500/7600/7700

Altitude Distribution

BandAltitude RangeIconTypical Traffic
GroundGroundgroundTaxiing, parked aircraft
LowBelow 10,000 ftlowDepartures, arrivals, GA
Medium10,000 - 30,000 ftmediumClimbing, regional flights
HighAbove 30,000 fthighCruise altitude, long-haul
Example Response
{
  "total": 42,
  "with_position": 38,
  "military": 3,
  "emergency_squawks": [],
  "altitude": {
    "ground": 2,
    "low": 8,
    "medium": 18,
    "high": 14
  }
}

Top Aircraft Leaderboards

Real-time leaderboards computed from currently tracked aircraft.

RankClosestFastestHighest
1st2.3 nm612 kts45,000 ft
2nd4.8 nm585 kts43,500 ft
3rd7.1 nm560 kts42,000 ft
LeaderboardIconMetricDescription
ClosestcrosshairsDistance (nm)Nearest aircraft to your receiver location
Fastestgauge-highGround Speed (kts)Highest velocity aircraft currently tracked
Highestarrow-upAltitude (ft)Aircraft at highest cruise altitude

Flight Patterns

Flight pattern analytics provide insights into traffic patterns over time.

Busiest Hours Heatmap

Hourly activity distribution for visualization as a heatmap.

xychart-beta
    title "Typical Daily Traffic Pattern"
    x-axis [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
    y-axis "Aircraft Count" 0 --> 60
    bar [5, 3, 2, 8, 25, 42, 48, 52, 50, 45, 35, 15]
API: GET /api/v1/stats/flight-patterns/busiest-hours

Response Fields:

FieldTypeDescription
busiest_hours[]arrayHourly data (0-23)
peak_hourintegerHour with most activity
peak_aircraft_countintegerMax aircraft during peak
quietest_hourintegerHour with least activity
day_night_ratiofloatDaytime to nighttime ratio

Top Routes

Most frequent origin-destination pairs based on ACARS data and callsign analysis.

Request:

GET /api/v1/flight-patterns/routes?hours=24&limit=20

Response:

{
  "routes": [
    {
      "origin": "KJFK",
      "destination": "KLAX",
      "count": 45,
      "airlines": ["AAL", "UAL", "DAL"]
    }
  ],
  "total_routes": 156,
  "time_range_hours": 24
}
ParameterTypeDefaultDescription
hoursinteger24Time range in hours
limitinteger20Maximum routes to return

Aircraft Types Distribution

API: GET /api/v1/flight-patterns/aircraft-types

Response includes:

FieldDescription
type_codeICAO type designator (e.g., "B738")
type_nameFull type name
countSession count
unique_aircraftUnique ICAO hex codes
military_pctPercentage military
avg_duration_minAverage tracking duration

Flight Duration by Type

API: GET /api/v1/flight-patterns/duration-by-type
{
  "duration_by_type": [
    {
      "type": "B738",
      "avg_minutes": 45.2,
      "min_minutes": 5.0,
      "max_minutes": 180.5,
      "session_count": 234
    }
  ]
}

Geographic Statistics

Geographic analytics based on aircraft registration and origin data.

Countries of Origin

Breakdown by country based on registration prefix.

PrefixCountryExample
NUnited StatesN12345
G-United KingdomG-ABCD
D-GermanyD-AIBC
F-FranceF-GHIJ
JAJapanJA8088

Request:

GET /api/v1/stats/geographic/countries

Response:

{
  "countries": [
    {
      "country": "United States",
      "country_code": "US",
      "count": 234,
      "military_count": 12,
      "military_pct": 5.1
    }
  ],
  "total_countries": 28
}

Airlines/Operators

API: GET /api/v1/stats/geographic/operators

Response includes:

  • operator - Operator name
  • operator_icao - ICAO airline code
  • aircraft_count - Unique aircraft
  • session_count - Total tracking sessions

Connected Airports

Airports most connected to your coverage area based on ACARS mentions.

Example Response
{
  "airports": [
    {
      "icao": "KJFK",
      "iata": "JFK",
      "name": "John F Kennedy International Airport",
      "country": "United States",
      "count": 156
    }
  ]
}

Military vs Civilian

Endpoint: GET /api/v1/stats/geographic/military-breakdown

Returns military/civilian split by country with counts and percentages.


System Performance

Tracking Quality Metrics

Quality metrics for your ADS-B reception.

MetricIconTargetDescription
Quality Scoregaugegreater than 80Composite score (0-100)
Update Rateboltgreater than 1.0 HzPosition updates per second
Coveragesignalgreater than 90%Expected positions received
RSSIwave-squaregreater than -20 dBAverage signal strength

Quality Grades

GradeBadgeCompletenessUpdate Rate
Excellent5 stars90% or higher10/min or higher
Good4 stars70% or higher6/min or higher
Fair3 stars50% or higherAny
Poor1 starless than 50%Any
API: GET /api/v1/stats/tracking-quality/session/icao_hex
{
  "icao_hex": "A1B2C3",
  "callsign": "UAL123",
  "session": {
    "first_seen": "2024-01-15T10:30:00Z",
    "last_seen": "2024-01-15T11:45:00Z",
    "duration_minutes": 75.0,
    "total_positions": 892
  },
  "quality": {
    "grade": "excellent",
    "update_rate_per_min": 11.89,
    "expected_positions": 900,
    "completeness_pct": 99.1
  },
  "gaps": {
    "total_count": 2,
    "total_time_seconds": 45,
    "gap_percentage": 1.0,
    "max_gap_seconds": 30
  },
  "signal": {
    "avg_rssi": -18.5,
    "min_rssi": -25.2,
    "max_rssi": -12.1
  }
}

Coverage Gaps Analysis

Endpoint: GET /api/v1/stats/tracking-quality/gaps

ParameterTypeDefaultDescription
hoursinteger24Time range to analyze
limitinteger100Max sessions to analyze

Antenna Metrics

Beta Feature - Advanced antenna performance analytics

Polar Coverage Plot

Reception data by bearing (direction) for antenna pattern visualization.

pie showData
    title "Coverage by Quadrant"
    "North (0-90°)" : 28
    "East (90-180°)" : 24
    "South (180-270°)" : 22
    "West (270-360°)" : 26
Data Structure
{
  "bearing_data": [
    {
      "bearing_start": 0,
      "bearing_end": 10,
      "count": 1234,
      "max_distance_nm": 185.5,
      "avg_rssi": -18.2
    }
  ],
  "summary": {
    "coverage_pct": 94,
    "total_sightings": 45678,
    "sectors_with_data": 34
  }
}

RSSI vs Distance Correlation

Signal strength analysis by distance for antenna performance evaluation.

BandDistanceAvg RSSIStatus
Near0-25 nm-12.5 dBGood
Mid25-50 nm-16.2 dBGood
Far50-100 nm-20.8 dBFair
Extended100+ nm-25.5 dBMarginal
Full Data Structure
{
  "scatter_data": [
    {"distance_nm": 50.5, "rssi": -15.2},
    {"distance_nm": 120.3, "rssi": -22.8}
  ],
  "band_statistics": [
    {"band": "0-25nm", "avg_rssi": -12.5, "count": 500},
    {"band": "25-50nm", "avg_rssi": -16.2, "count": 800}
  ],
  "trend_line": {
    "slope": -0.05,
    "intercept": -10.5,
    "interpretation": "Normal signal degradation with distance"
  },
  "overall_statistics": {
    "avg_rssi": -17.5,
    "min_rssi": -28.0,
    "max_rssi": -8.5
  }
}

Real-Time Stats Streaming

SkySpy provides Socket.IO-based real-time statistics streaming.

Connection Flow

sequenceDiagram
    participant Client
    participant SocketIO as Socket.IO
    participant Cache
    participant Database

    Client->>SocketIO: Connect to /stats namespace
    SocketIO-->>Client: stats.connected (available types)

    Client->>SocketIO: stats.subscribe (flight_patterns)
    SocketIO-->>Client: stats.subscribed

    loop Every 5 seconds
        Cache->>SocketIO: Stats updated
        SocketIO-->>Client: stats.update
    end

    Client->>SocketIO: stats.request (specific query)
    SocketIO->>Cache: Check cache
    alt Cache hit
        Cache-->>SocketIO: Cached data
    else Cache miss
        SocketIO->>Database: Query
        Database-->>SocketIO: Fresh data
        SocketIO->>Cache: Store
    end
    SocketIO-->>Client: stats.response

Available Stat Types

Flight Stats

Stat TypeDescription
flight_patternsFlight pattern statistics
geographicGeographic breakdown
busiest_hoursHourly activity
common_aircraft_typesAircraft types seen

Geographic Stats

Stat TypeDescription
countriesCountries of origin
airlinesAirline frequency
airportsConnected airports

Session Stats

Stat TypeDescription
tracking_qualityTracking metrics
coverage_gapsCoverage gap analysis
engagementEngagement statistics

Time Stats

Stat TypeDescription
week_comparisonWeek-over-week stats
seasonal_trendsMonthly/seasonal trends
day_nightDay vs night traffic
weekend_weekdayWeekend vs weekday
daily_totalsDaily time series
weekly_totalsWeekly time series
monthly_totalsMonthly time series

ACARS Stats

Stat TypeDescription
acars_statsACARS message stats
acars_trendsACARS trends
acars_airlinesACARS by airline

Gamification Stats

Stat TypeDescription
personal_recordsPersonal records
rare_sightingsNotable sightings
collection_statsCollection progress
spotted_by_typeSpotted by type
spotted_by_operatorSpotted by operator
streaksSighting streaks
daily_statsDaily gamification
lifetime_statsLifetime totals

Socket.IO Messages

Subscribe:

socket.emit('stats.subscribe', {
  stat_types: ['flight_patterns', 'tracking_quality']
});

Request Data:

socket.emit('stats.request', {
  stat_type: 'flight_patterns',
  filters: {
    hours: 24,
    limit: 50
  },
  request_id: 'req-123'
});

Set Filters:

socket.emit('stats.set_filters', {
  filters: {
    hours: 48,
    aircraft_type: 'B738'
  }
});

Refresh Cache:

socket.emit('stats.refresh', {
  stat_type: 'geographic'
});

Listening for Updates:

socket.on('stats.update', (data) => {
  console.log('Stats updated:', data);
});

socket.on('stats.response', (data) => {
  console.log('Stats response:', data);
});

Historical Data Analysis

Trends Over Time

Request:

GET /api/v1/history/trends?hours=24&interval=hour

Response:

{
  "intervals": [
    {
      "timestamp": "2024-01-15T10:00:00Z",
      "unique_aircraft": 42,
      "total_positions": 1234,
      "military_count": 3
    }
  ],
  "summary": {
    "total_unique_aircraft": 156,
    "peak_concurrent": 52,
    "total_intervals": 24
  }
}
ParameterTypeDefaultDescription
hoursinteger24Time range
intervalstring"hour"Grouping (hour/day)

Top Performers

Endpoint: GET /api/v1/history/top

CategoryIconDescription
longest_trackedstopwatchLongest session duration
furthest_distancecrosshairsMaximum distance from receiver
highest_altitudearrow-upMaximum altitude reached
closest_approachlocation-dotMinimum distance to receiver
Example Response
{
  "longest_tracked": [
    {
      "icao_hex": "A1B2C3",
      "callsign": "UAL123",
      "aircraft_type": "B738",
      "duration_min": 185.5,
      "is_military": false
    }
  ],
  "furthest_distance": [...],
  "highest_altitude": [...],
  "closest_approach": [...]
}

Distance Analytics

Endpoint: GET /api/v1/history/analytics/distance

Response Structure
{
  "statistics": {
    "mean_nm": 45.2,
    "median_nm": 38.5,
    "max_nm": 245.8,
    "percentile_90": 125.0
  },
  "distribution": {
    "0-25nm": 234,
    "25-50nm": 567,
    "50-100nm": 890,
    "100-150nm": 345,
    "150+nm": 123
  }
}

Speed Analytics

Endpoint: GET /api/v1/history/analytics/speed

Response Structure
{
  "statistics": {
    "mean_kt": 285,
    "max_kt": 612,
    "percentile_90": 480
  },
  "fastest_sessions": [
    {
      "icao_hex": "A1B2C3",
      "callsign": "UAL789",
      "max_speed": 612
    }
  ]
}

Correlation Analysis

Endpoint: GET /api/v1/history/analytics/correlation

xychart-beta
    title "Altitude vs Speed Correlation"
    x-axis ["0-10k", "10-20k", "20-30k", "30k+"]
    y-axis "Avg Speed (kts)" 0 --> 500
    bar [180, 320, 420, 480]

Engagement Statistics

Peak Tracking Periods

API: GET /api/v1/stats/engagement/peak-tracking
{
  "peak_periods": [
    {
      "hour": "2024-01-15T14:00:00Z",
      "unique_aircraft": 52,
      "position_count": 3456,
      "military_count": 4
    }
  ],
  "summary": {
    "avg_aircraft_per_hour": 35.2,
    "max_aircraft_in_hour": 52
  }
}

Return Visitors

Aircraft seen multiple times within the time range.

ParameterTypeDefaultDescription
hoursinteger24Time range
min_sessionsinteger2Minimum session count
limitinteger30Results limit
Response Example
{
  "return_visitors": [
    {
      "icao_hex": "A1B2C3",
      "registration": "N12345",
      "session_count": 5,
      "total_positions": 2345,
      "first_session": "2024-01-15T06:00:00Z",
      "last_session": "2024-01-15T18:00:00Z"
    }
  ],
  "stats": {
    "total_unique_aircraft": 156,
    "returning_aircraft": 23,
    "return_rate_pct": 14.7
  }
}

Most Watched Aircraft

Endpoint: GET /api/v1/stats/engagement/most-watched


Gamification Features

Level up your aircraft spotting experience!

SkySpy includes gamification elements to make aircraft spotting more engaging.

Personal Records

Track your best achievements across multiple categories.

RecordIconDescriptionUnit
Max DistancebullseyeFurthest aircraft trackednautical miles
Max Altitudearrow-upHighest aircraft trackedfeet
Max Speedgauge-highFastest aircraft observedknots
Longest SessionstopwatchLongest tracking durationminutes
Most Positionschart-lineMost positions in single sessioncount
Closest Approachlocation-dotNearest to receivernautical miles
Max Climbarrow-trend-upFastest climb rateft/min
Max Descentarrow-trend-downFastest descent rateft/min
API Response Example
{
  "records": [
    {
      "record_type": "max_distance",
      "record_type_display": "Maximum Distance",
      "icao_hex": "A1B2C3",
      "callsign": "UAL123",
      "aircraft_type": "B77W",
      "registration": "N12345",
      "operator": "United Airlines",
      "value": 245.8,
      "achieved_at": "2024-01-15T14:30:00Z",
      "previous_value": 220.5,
      "previous_icao_hex": "B2C3D4"
    }
  ]
}

Rare Sightings

Notable and rare aircraft detections.

ParameterTypeDefaultDescription
hoursinteger24Time range
limitinteger50Maximum results
include_acknowledgedbooleanfalseInclude dismissed

Rarity Types and Scores

TypeIconDescriptionScore
first_hexnewFirst time tracking this aircraft3
militaryshieldMilitary aircraft4
air_ambulanceambulanceMedical evacuation flights5
law_enforcementbadgePolice/Coast Guard aircraft5-6
rare_typegemRare aircraft type6-10
test_flightflaskManufacturer test flights7
governmentlandmarkGovernment aircraft (e.g., N1xx)9

Notable Registration Patterns

PatternDescriptionExample
N1xxUS GovernmentN100, N175
SAM, AF1, AF2Air Force One/TwoExecutive transport
N7xxBoeing TestN787BX
F-WW*Airbus TestF-WWDD
Contains "NASA"NASA ResearchNASA941

Ultra-Rare Aircraft Types

AircraftRarity ScoreDescription
Boeing E-4B Nightwatch10"Doomsday Plane"
Lockheed U-29High-altitude reconnaissance
Boeing E-6B Mercury9Airborne command post
Boeing B-528Strategic bomber
Airbus A3807Superjumbo
Boeing 747-86Jumbo variant

Collection Progress

Endpoint: GET /api/v1/stats/gamification/collection

Response Example
{
  "total_unique_aircraft": 1234,
  "military_aircraft": 156,
  "unique_types": 89,
  "unique_operators": 234,
  "unique_countries": 45,
  "first_aircraft": {
    "icao_hex": "A1B2C3",
    "registration": "N12345",
    "first_seen": "2023-06-15T10:00:00Z"
  },
  "most_seen": [
    {
      "icao_hex": "B2C3D4",
      "registration": "N54321",
      "operator": "Southwest Airlines",
      "times_seen": 156
    }
  ]
}

Sighting Streaks

Track consecutive day streaks for various categories.

Streak TypeIconQualification
any_sightingcalendarAny aircraft tracked
militaryshieldAt least one military aircraft
unique_newnewA new unique aircraft
high_altituderocketAircraft at 40,000+ ft
long_rangecrosshairsAircraft at 100+ nm
rare_typegemA rare aircraft type
Response Example
{
  "streaks": [
    {
      "streak_type": "any_sighting",
      "streak_type_display": "Daily Sighting",
      "current_streak_days": 15,
      "current_streak_start": "2024-01-01",
      "last_qualifying_date": "2024-01-15",
      "best_streak_days": 45,
      "best_streak_start": "2023-10-01",
      "best_streak_end": "2023-11-15"
    }
  ]
}

Daily Statistics

Endpoint: GET /api/v1/stats/gamification/daily?days=30

Response Example
{
  "days": [
    {
      "date": "2024-01-15",
      "unique_aircraft": 156,
      "new_aircraft": 12,
      "total_sessions": 234,
      "total_positions": 45678,
      "military_count": 8,
      "max_distance_nm": 185.5,
      "max_altitude": 45000,
      "max_speed": 580,
      "top_types": {"B738": 45, "A320": 38},
      "top_operators": {"United": 25, "American": 22}
    }
  ]
}

Lifetime Statistics

Endpoint: GET /api/v1/stats/gamification/lifetime

MetricIconDescription
Total AircraftplaneAll-time unique aircraft spotted
Total SessionsclockCumulative tracking sessions
Total Positionsmap-pinPosition updates received
Full Response
{
  "total_unique_aircraft": 12345,
  "total_sessions": 56789,
  "total_positions": 2345678,
  "unique_aircraft_types": 156,
  "unique_operators": 456,
  "unique_countries": 78,
  "active_tracking_days": 365,
  "total_rare_sightings": 234,
  "all_time_records": {
    "max_distance": {"value": 285.5, "icao_hex": "A1B2C3"},
    "max_altitude": {"value": 51000, "icao_hex": "B2C3D4"}
  },
  "first_sighting": {
    "icao_hex": "C3D4E5",
    "timestamp": "2023-01-01T10:00:00Z"
  }
}

API Endpoints Reference

Stats API

EndpointMethodDescription
/api/v1/stats/tracking-qualityGETTracking quality metrics
/api/v1/stats/tracking-quality/gapsGETCoverage gaps analysis
/api/v1/stats/tracking-quality/session/{icao_hex}GETSession-specific quality
/api/v1/stats/engagementGETEngagement statistics
/api/v1/stats/engagement/most-watchedGETMost favorited aircraft
/api/v1/stats/engagement/return-visitorsGETReturning aircraft
/api/v1/stats/engagement/peak-trackingGETPeak concurrent periods
/api/v1/stats/flight-patternsGETFlight pattern analytics
/api/v1/stats/flight-patterns/routesGETTop routes
/api/v1/stats/flight-patterns/busiest-hoursGETHourly heatmap data
/api/v1/stats/flight-patterns/aircraft-typesGETAircraft types breakdown
/api/v1/stats/flight-patterns/duration-by-typeGETDuration by type
/api/v1/stats/geographicGETAll geographic stats
/api/v1/stats/geographic/countriesGETCountries breakdown
/api/v1/stats/geographic/operatorsGETOperators frequency
/api/v1/stats/geographic/airportsGETConnected airports
/api/v1/stats/geographic/military-breakdownGETMilitary vs civilian
/api/v1/stats/combinedGETAll stats combined
/api/v1/stats/combined/summaryGETHigh-level summary

History API

EndpointMethodDescription
/api/v1/history/statsGETHistorical statistics
/api/v1/history/trendsGETActivity trends
/api/v1/history/topGETTop performers
/api/v1/history/analytics/distanceGETDistance analytics
/api/v1/history/analytics/speedGETSpeed analytics
/api/v1/history/analytics/correlationGETCorrelation analysis

Favorites API

EndpointMethodDescription
/api/v1/stats/favoritesGETList user favorites
/api/v1/stats/favorites/toggle/{icao_hex}POSTAdd/remove favorite
/api/v1/stats/favorites/check/{icao_hex}GETCheck if favorited
/api/v1/stats/favorites/{id}/notesPATCHUpdate notes

Gamification API

EndpointMethodDescription
/api/v1/stats/gamification/recordsGETPersonal records
/api/v1/stats/gamification/rare-sightingsGETRare sightings
/api/v1/stats/gamification/collectionGETCollection progress
/api/v1/stats/gamification/spotted/typesGETSpotted by type
/api/v1/stats/gamification/spotted/operatorsGETSpotted by operator
/api/v1/stats/gamification/streaksGETSighting streaks
/api/v1/stats/gamification/dailyGETDaily stats
/api/v1/stats/gamification/lifetimeGETLifetime totals

Common Query Parameters

ParameterTypeDefaultDescription
hoursinteger24Time range in hours
refreshbooleanfalseForce cache refresh
limitintegervariesMaximum results
military_onlybooleanfalseFilter to military only

Exporting Data

JSON Export

All API endpoints return JSON data that can be exported directly.

Flight Patterns:

# Export flight patterns for last 48 hours
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://your-server/api/v1/stats/flight-patterns?hours=48" \
  > flight_patterns.json

Gamification:

# Export gamification stats
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://your-server/api/v1/stats/gamification/lifetime" \
  > lifetime_stats.json

Combined:

# Export all stats
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://your-server/api/v1/stats/combined" \
  > all_stats.json

CSV Export

For tabular data, convert JSON to CSV:

# Using jq to convert routes to CSV
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://your-server/api/v1/flight-patterns/routes" | \
  jq -r '.routes[] | [.origin, .destination, .count] | @csv' \
  > routes.csv

Output format:

"KJFK","KLAX",45
"KORD","KJFK",38
"KLAX","KSFO",32

Scheduled Exports

Use Celery tasks for scheduled data exports:

from skyspy.tasks import export_daily_stats

# Schedule via Celery Beat
CELERY_BEAT_SCHEDULE = {
    'export-daily-stats': {
        'task': 'skyspy.tasks.export_daily_stats',
        'schedule': crontab(hour=0, minute=5),  # 12:05 AM daily
    },
}

Frontend Integration

Using the Stats Hook

The useStatsData hook provides access to all statistics data:

import { useStatsData } from '../hooks';

function MyStatsComponent({ apiBase, wsRequest, wsConnected }) {
  const data = useStatsData({
    apiBase,
    wsRequest,
    wsConnected,
    filters: {
      timeRange: '24h',
      showMilitaryOnly: false
    }
  });

  const {
    stats,              // Current aircraft stats
    top,                // Top aircraft leaderboards
    histStats,          // Historical stats
    flightPatternsData, // Flight patterns
    geographicData,     // Geographic breakdown
    trackingQualityData,// Quality metrics
    engagementData,     // Engagement stats
    antennaAnalytics,   // Antenna performance
    throughputHistory,  // Message rate history
    aircraftHistory     // Aircraft count history
  } = data;

  return (
    // Your component JSX
  );
}

Filter Options

const filters = {
  timeRange: '24h',       // '1h', '6h', '24h', '48h', '7d'
  showMilitaryOnly: false,
  categoryFilter: '',     // 'Commercial', 'GA', 'Military', etc.
  aircraftType: '',       // 'B738', 'A320', etc.
  minAltitude: '',
  maxAltitude: '',
  minDistance: '',
  maxDistance: ''
};

Time Range Mappings

DisplayHoursUse Case
1h1Real-time monitoring
6h6Recent activity
24h24Daily overview
48h48Extended analysis
7d168Weekly trends

Caching Strategy

Statistics are cached at multiple levels for performance:

Cache KeyTTLCategory
flight_patterns_stats5 minFlight
geographic_stats5 minGeographic
tracking_quality_stats5 minQuality
engagement_stats5 minEngagement
gamification:personal_records5 minGamification
gamification:rare_sightings2 minGamification
gamification:collection_stats5 minGamification
gamification:streaks10 minGamification
gamification:daily_stats5 minGamification
gamification:lifetime_stats10 minGamification

Forcing Cache Refresh

REST API:

GET /api/v1/stats/flight-patterns?refresh=true

Socket.IO:

socket.emit('stats.request', {
  stat_type: 'flight_patterns',
  filters: { force_refresh: true }
});

Best Practices

PracticeIconDescription
Use Socket.IO for Real-TimeboltSubscribe to stat types you need updates for rather than polling REST endpoints.
Cache AppropriatelydatabaseDo not force-refresh unless necessary. Default cache TTLs are optimized for typical use cases.
Filter at the SourcefilterUse query parameters to filter data server-side rather than fetching everything and filtering client-side.
Batch Requestsboxes-stackedUse the combined endpoints (/api/v1/stats/combined) when you need multiple stat types.
Time Range OptimizationclockShorter time ranges (1h, 6h) compute faster. Use 24h or longer for trend analysis.
Handle Loading StatesspinnerAll data fetches may take time. Show loading indicators while data is being retrieved.
Error Handlingtriangle-exclamationStats endpoints return 503 if unable to calculate. Implement appropriate retry logic.
Choose Right Chartschart-simpleUse heatmaps for hourly data, line charts for trends, and pie charts for distributions.

Related Documentation