If you are working with a large number of proxies ā for arbitrage, scraping, or multi-accounting ā manually monitoring traffic consumption becomes a nightmare. Proxy provider APIs allow for the automation of statistics retrieval: remaining traffic, active sessions, consumption by IP addresses, and usage history. In this guide, we will explore how to integrate the API for accounting statistics with code examples in Python, Node.js, and cURL.
Why Automation of Proxy Statistics is Needed
When you manage 10-50 proxies for different projects, manually checking the balance and traffic consumption through the provider's personal account becomes inefficient. The API solves several critical tasks:
Key Tasks of the API Statistics:
- Monitoring Remaining Traffic ā automatic notifications when limits are reached
- Control of Consumption by Projects ā allocation of costs among clients or tasks
- Effectiveness Analysis ā which proxies consume more traffic and why
- Preventing Downtime ā topping up the balance before traffic runs out
- Integration into CRM/Billing ā automatic accounting of proxy costs in business processes
For arbitrage specialists running ads through multiple accounts, it is critically important to know which proxies are active and how much traffic is left ā a sudden block due to exhausted limits can cost thousands of dollars in lost profits. For SMM agencies managing client accounts on Instagram or TikTok, automation allows for accurate billing for proxy usage.
Marketplace scrapers (Wildberries, Ozon, Avito) can automatically switch to backup proxies when the limit on the main ones is exhausted. The API enables the construction of fault-tolerant systems that operate 24/7 without manual intervention.
Basics of Working with Proxy Provider APIs
Most modern proxy providers offer a RESTful API for managing the service. The API operates on a standard scheme: you send an HTTP request to a specific endpoint with authentication parameters, and the server returns JSON with data.
| API Component | Description | Example |
|---|---|---|
| Base URL | Base address of the provider's API | https://api.provider.com/v1 |
| Authentication | API key or Bearer Token | Authorization: Bearer YOUR_API_KEY |
| Endpoints | Specific paths for different operations | /statistics, /balance |
| Response Format | Data structure | JSON with fields status, data, error |
| Rate Limits | Request limits per minute | 60-300 requests/minute |
A typical JSON response structure from a proxy provider API looks like this:
{
"status": "success",
"data": {
"balance": 1250.50,
"traffic_used_gb": 45.2,
"traffic_remaining_gb": 54.8,
"active_proxies": 15,
"last_updated": "2024-01-15T10:30:00Z"
},
"error": null
}
When working with the API, it is important to consider rate limits. Most providers allow 60-300 requests per minute. For monitoring statistics, this is more than enough ā usually, requests are made every 5-15 minutes.
Authentication and Obtaining API Key
The first step in working with the API is obtaining an authentication key. The process varies among providers, but the general logic is the same:
Step-by-step instructions for obtaining an API key:
- Log in to the proxy provider's personal account
- Find the "API" section or "Settings" ā "API Access"
- Click the "Create API Key" or "Generate Token" button
- Copy the key and save it in a secure place (it is shown only once)
- Set up an IP whitelist if the provider requires IP address binding
- Test the key with a test request via cURL or Postman
There are two main methods of authentication in proxy provider APIs:
| Method | How it Works | Example Header |
|---|---|---|
| Bearer Token | Token is passed in the Authorization header | Authorization: Bearer abc123... |
| API Key in Parameters | Key is passed as a GET/POST parameter | ?api_key=abc123... |
Important: never store API keys in code that goes into a Git repository. Use environment variables (.env files) or secret managers (AWS Secrets Manager, HashiCorp Vault). If a key leaks ā immediately revoke it in the personal account and generate a new one.
Main Endpoints for Retrieving Statistics
Although each provider has its own API structure, most provide a standard set of endpoints for retrieving statistics. Let's look at typical methods:
| Endpoint | Method | Returns |
|---|---|---|
/balance |
GET | Current balance and remaining traffic |
/statistics |
GET | Overall usage statistics for the period |
/statistics/proxy/{id} |
GET | Statistics for a specific proxy |
/sessions/active |
GET | List of active proxy sessions |
/traffic/history |
GET | Traffic consumption history by days |
/proxies/list |
GET | List of all proxies with their statuses |
Request parameters typically include time ranges and filters:
GET /statistics?from=2024-01-01&to=2024-01-15&proxy_type=residential
GET /traffic/history?period=7d&group_by=day
GET /sessions/active?status=online&country=US
For working with residential proxies, the endpoint for retrieving session statistics is particularly important, as they often use IP rotation. The API allows tracking how many unique IPs have been used over a period and how much traffic has passed through each session.
Python Code Examples for Retrieving Statistics
Python is the most popular language for automating work with proxies thanks to the requests library. Let's look at practical examples of retrieving statistics via the API.
Basic Request for Balance and Traffic
import requests
import os
from datetime import datetime
# API credentials from environment variables
API_KEY = os.getenv('PROXY_API_KEY')
BASE_URL = 'https://api.proxyprovider.com/v1'
def get_balance_statistics():
"""Retrieve balance and overall statistics"""
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
try:
response = requests.get(
f'{BASE_URL}/balance',
headers=headers,
timeout=10
)
response.raise_for_status()
data = response.json()
print(f"=== Proxy Statistics as of {datetime.now().strftime('%Y-%m-%d %H:%M')} ===")
print(f"Balance: ${data['balance']:.2f}")
print(f"Traffic Used: {data['traffic_used_gb']:.2f} GB")
print(f"Traffic Remaining: {data['traffic_remaining_gb']:.2f} GB")
print(f"Active Proxies: {data['active_proxies']}")
return data
except requests.exceptions.RequestException as e:
print(f"Error during request: {e}")
return None
# Call the function
stats = get_balance_statistics()
Retrieving Detailed Statistics for a Period
from datetime import datetime, timedelta
import requests
def get_traffic_history(days=7):
"""Retrieve traffic consumption history for N days"""
headers = {'Authorization': f'Bearer {API_KEY}'}
# Calculate time range
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
params = {
'from': start_date.strftime('%Y-%m-%d'),
'to': end_date.strftime('%Y-%m-%d'),
'group_by': 'day'
}
response = requests.get(
f'{BASE_URL}/traffic/history',
headers=headers,
params=params,
timeout=10
)
if response.status_code == 200:
data = response.json()
print(f"\n=== Traffic Consumption for the Last {days} Days ===")
for day in data['daily_stats']:
print(f"{day['date']}: {day['traffic_gb']:.2f} GB "
f"({day['requests']} requests)")
total = sum(day['traffic_gb'] for day in data['daily_stats'])
print(f"\nTotal for the Period: {total:.2f} GB")
return data
else:
print(f"Error {response.status_code}: {response.text}")
return None
# Retrieve statistics for a week
history = get_traffic_history(7)
Monitoring Statistics for Individual Proxies
def get_proxy_statistics(proxy_id):
"""Retrieve statistics for a specific proxy"""
headers = {'Authorization': f'Bearer {API_KEY}'}
response = requests.get(
f'{BASE_URL}/statistics/proxy/{proxy_id}',
headers=headers,
timeout=10
)
if response.status_code == 200:
data = response.json()
print(f"\n=== Statistics for Proxy {proxy_id} ===")
print(f"IP Address: {data['ip_address']}")
print(f"Country: {data['country']}")
print(f"Type: {data['proxy_type']}")
print(f"Status: {data['status']}")
print(f"Traffic Used: {data['traffic_used_mb']:.2f} MB")
print(f"Total Requests: {data['total_requests']}")
print(f"Last Activity: {data['last_activity']}")
return data
else:
print(f"Proxy {proxy_id} not found")
return None
def get_all_proxies_stats():
"""Retrieve statistics for all proxies"""
headers = {'Authorization': f'Bearer {API_KEY}'}
# First, get the list of all proxies
response = requests.get(
f'{BASE_URL}/proxies/list',
headers=headers,
timeout=10
)
if response.status_code == 200:
proxies = response.json()['proxies']
print(f"\n=== Statistics for {len(proxies)} Proxies ===\n")
total_traffic = 0
for proxy in proxies:
stats = get_proxy_statistics(proxy['id'])
if stats:
total_traffic += stats['traffic_used_mb']
print(f"\n=== Total Traffic Consumption: {total_traffic/1024:.2f} GB ===")
return proxies
else:
print("Error retrieving the list of proxies")
return None
# Retrieve statistics for all proxies
all_stats = get_all_proxies_stats()
These examples demonstrate basic interaction with the API. For production systems, add error handling, retry logic for network failures, and caching of results to avoid exceeding the provider's rate limits.
Node.js Code Examples for Traffic Monitoring
Node.js is great for creating monitoring microservices that run in the background and send notifications for critical events. We will use the axios library for HTTP requests.
Basic Class for Working with Proxy API
const axios = require('axios');
require('dotenv').config();
class ProxyAPIClient {
constructor() {
this.baseURL = 'https://api.proxyprovider.com/v1';
this.apiKey = process.env.PROXY_API_KEY;
this.client = axios.create({
baseURL: this.baseURL,
timeout: 10000,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
});
}
async getBalance() {
try {
const response = await this.client.get('/balance');
return response.data;
} catch (error) {
console.error('Error retrieving balance:', error.message);
throw error;
}
}
async getStatistics(params = {}) {
try {
const response = await this.client.get('/statistics', { params });
return response.data;
} catch (error) {
console.error('Error retrieving statistics:', error.message);
throw error;
}
}
async getTrafficHistory(days = 7) {
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - days);
const params = {
from: startDate.toISOString().split('T')[0],
to: endDate.toISOString().split('T')[0],
group_by: 'day'
};
try {
const response = await this.client.get('/traffic/history', { params });
return response.data;
} catch (error) {
console.error('Error retrieving traffic history:', error.message);
throw error;
}
}
async getProxyStats(proxyId) {
try {
const response = await this.client.get(`/statistics/proxy/${proxyId}`);
return response.data;
} catch (error) {
console.error(`Error retrieving statistics for proxy ${proxyId}:`, error.message);
throw error;
}
}
}
module.exports = ProxyAPIClient;
Automatic Monitoring with Notifications
const ProxyAPIClient = require('./ProxyAPIClient');
const nodemailer = require('nodemailer');
class ProxyMonitor {
constructor(checkIntervalMinutes = 15) {
this.api = new ProxyAPIClient();
this.checkInterval = checkIntervalMinutes * 60 * 1000;
this.thresholds = {
trafficWarning: 10, // GB - warning threshold
trafficCritical: 5, // GB - critical level
balanceWarning: 50 // USD - balance warning
};
}
async checkAndNotify() {
try {
const balance = await this.api.getBalance();
console.log(`[${new Date().toISOString()}] Checking statistics...`);
console.log(`Balance: $${balance.balance.toFixed(2)}`);
console.log(`Remaining Traffic: ${balance.traffic_remaining_gb.toFixed(2)} GB`);
// Check critical thresholds
const alerts = [];
if (balance.traffic_remaining_gb <= this.thresholds.trafficCritical) {
alerts.push({
level: 'critical',
message: `CRITICALLY LOW TRAFFIC: only ${balance.traffic_remaining_gb.toFixed(2)} GB left!`
});
} else if (balance.traffic_remaining_gb <= this.thresholds.trafficWarning) {
alerts.push({
level: 'warning',
message: `Low traffic: only ${balance.traffic_remaining_gb.toFixed(2)} GB left`
});
}
if (balance.balance <= this.thresholds.balanceWarning) {
alerts.push({
level: 'warning',
message: `Low balance: $${balance.balance.toFixed(2)}`
});
}
// Send notifications
if (alerts.length > 0) {
await this.sendAlerts(alerts, balance);
}
return { balance, alerts };
} catch (error) {
console.error('Monitoring error:', error);
await this.sendErrorNotification(error);
}
}
async sendAlerts(alerts, balance) {
console.log('\nā ļø ATTENTION! Issues detected:');
alerts.forEach(alert => {
console.log(`[${alert.level.toUpperCase()}] ${alert.message}`);
});
// Send email (configure SMTP)
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
const emailBody = `
Issues detected with proxies:
${alerts.map(a => `- ${a.message}`).join('\n')}
Current statistics:
- Balance: $${balance.balance.toFixed(2)}
- Remaining Traffic: ${balance.traffic_remaining_gb.toFixed(2)} GB
- Used: ${balance.traffic_used_gb.toFixed(2)} GB
- Active Proxies: ${balance.active_proxies}
It is recommended to top up the balance or reduce the load.
`;
await transporter.sendMail({
from: process.env.ALERT_FROM_EMAIL,
to: process.env.ALERT_TO_EMAIL,
subject: 'ā ļø Proxy Warning',
text: emailBody
});
}
start() {
console.log(`Starting proxy monitoring (check every ${this.checkInterval / 60000} minutes)`);
// First check immediately
this.checkAndNotify();
// Periodic checks
setInterval(() => {
this.checkAndNotify();
}, this.checkInterval);
}
}
// Start monitoring
const monitor = new ProxyMonitor(15); // check every 15 minutes
monitor.start();
This code creates a background service that checks statistics every 15 minutes and sends email notifications when critical thresholds are reached. For mobile proxies, which are usually more expensive than residential ones, such monitoring is especially important for controlling expenses.
cURL Request Examples
cURL is a versatile tool for testing APIs from the command line. It is useful for quickly checking endpoints and debugging integrations.
Retrieving Balance
# Basic balance request
curl -X GET "https://api.proxyprovider.com/v1/balance" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"
# With pretty JSON formatting (via jq)
curl -X GET "https://api.proxyprovider.com/v1/balance" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.'
# Extracting a specific field
curl -s "https://api.proxyprovider.com/v1/balance" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.traffic_remaining_gb'
Retrieving Statistics for a Period
# Statistics for the last 7 days
curl -X GET "https://api.proxyprovider.com/v1/traffic/history?from=2024-01-08&to=2024-01-15&group_by=day" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.daily_stats'
# Statistics for a specific type of proxy
curl -X GET "https://api.proxyprovider.com/v1/statistics?proxy_type=residential&country=US" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.'
Retrieving List of Active Proxies
# List of all active proxies
curl -X GET "https://api.proxyprovider.com/v1/proxies/list?status=active" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.proxies[] | {id, ip_address, country, proxy_type}'
# Counting the number of active proxies
curl -s "https://api.proxyprovider.com/v1/proxies/list?status=active" \
-H "Authorization: Bearer YOUR_API_KEY" \
| jq '.proxies | length'
Bash Script for Automatic Checking
#!/bin/bash
# Configuration
API_KEY="YOUR_API_KEY"
BASE_URL="https://api.proxyprovider.com/v1"
TRAFFIC_THRESHOLD=10 # GB - warning threshold
# Retrieve statistics
response=$(curl -s "${BASE_URL}/balance" \
-H "Authorization: Bearer ${API_KEY}")
# JSON parsing
traffic_remaining=$(echo "$response" | jq -r '.traffic_remaining_gb')
balance=$(echo "$response" | jq -r '.balance')
active_proxies=$(echo "$response" | jq -r '.active_proxies')
# Output statistics
echo "=== Proxy Statistics $(date '+%Y-%m-%d %H:%M:%S') ==="
echo "Remaining Traffic: ${traffic_remaining} GB"
echo "Balance: \$${balance}"
echo "Active Proxies: ${active_proxies}"
# Check thresholds
if (( $(echo "$traffic_remaining < $TRAFFIC_THRESHOLD" | bc -l) )); then
echo "ā ļø WARNING: Low traffic! Only ${traffic_remaining} GB left"
# Send notification (e.g., via Telegram)
# curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
# -d chat_id="${TELEGRAM_CHAT_ID}" \
# -d text="ā ļø Low proxy traffic: ${traffic_remaining} GB"
fi
Save this script as check_proxy_stats.sh, give it execute permissions (chmod +x check_proxy_stats.sh), and add it to cron for automatic execution every hour:
0 * * * * /path/to/check_proxy_stats.sh >> /var/log/proxy_monitor.log 2>&1
Automation of Monitoring and Notifications
Manual checking of statistics is inefficient ā automation with smart notifications is needed. Let's consider a complete monitoring system with integrations.
Integration with Telegram for Notifications
import requests
import os
from datetime import datetime
class TelegramNotifier:
def __init__(self):
self.bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
self.chat_id = os.getenv('TELEGRAM_CHAT_ID')
self.base_url = f'https://api.telegram.org/bot{self.bot_token}'
def send_message(self, text, parse_mode='Markdown'):
"""Send a message to Telegram"""
url = f'{self.base_url}/sendMessage'
payload = {
'chat_id': self.chat_id,
'text': text,
'parse_mode': parse_mode
}
try:
response = requests.post(url, json=payload, timeout=10)
return response.status_code == 200
except Exception as e:
print(f"Error sending to Telegram: {e}")
return False
def monitor_proxy_with_telegram():
"""Monitoring with notifications in Telegram"""
api = ProxyAPIClient()
notifier = TelegramNotifier()
try:
balance = api.get_balance()
# Forming the message
message = f"""
š *Proxy Statistics* ({datetime.now().strftime('%H:%M %d.%m.%Y')})
š° Balance: ${balance['balance']:.2f}
š Used: {balance['traffic_used_gb']:.2f} GB
š Remaining: {balance['traffic_remaining_gb']:.2f} GB
š Active Proxies: {balance['active_proxies']}
"""
# Check critical thresholds
if balance['traffic_remaining_gb'] < 5:
message += "\nā ļø *CRITICALLY LOW TRAFFIC!*"
notifier.send_message(message)
elif balance['traffic_remaining_gb'] < 10:
message += "\nā” It is recommended to top up traffic"
notifier.send_message(message)
return balance
except Exception as e:
error_msg = f"ā *Proxy Monitoring Error*\n\n{str(e)}"
notifier.send_message(error_msg)
raise
# Start monitoring
monitor_proxy_with_telegram()
Integration with Slack
import requests
import json
class SlackNotifier:
def __init__(self, webhook_url):
self.webhook_url = webhook_url
def send_alert(self, title, message, level='warning'):
"""Send a notification to Slack"""
color = {
'info': '#36a64f',
'warning': '#ff9900',
'critical': '#ff0000'
}.get(level, '#cccccc')
payload = {
'attachments': [{
'color': color,
'title': title,
'text': message,
'footer': 'Proxy Monitor',
'ts': int(datetime.now().timestamp())
}]
}
try:
response = requests.post(
self.webhook_url,
data=json.dumps(payload),
headers={'Content-Type': 'application/json'},
timeout=10
)
return response.status_code == 200
except Exception as e:
print(f"Error sending to Slack: {e}")
return False
def check_proxy_health():
"""Check the health of proxies with notifications"""
api = ProxyAPIClient()
slack = SlackNotifier(os.getenv('SLACK_WEBHOOK_URL'))
balance = api.get_balance()
proxies = api.get_all_proxies()
# Analyze status
offline_proxies = [p for p in proxies if p['status'] != 'active']
if len(offline_proxies) > 0:
message = f"Detected {len(offline_proxies)} inactive proxies:\n"
for proxy in offline_proxies[:5]: # first 5
message += f"- {proxy['ip_address']} ({proxy['country']})\n"
slack.send_alert(
'Inactive Proxies',
message,
level='warning'
)
if balance['traffic_remaining_gb'] < 5:
slack.send_alert(
'Critically Low Traffic!',
f"Only {balance['traffic_remaining_gb']:.2f} GB left. "
f"Balance: ${balance['balance']:.2f}",
level='critical'
)
check_proxy_health()
Setting Up Automatic Top-Up
Some providers allow not only retrieving statistics via the API but also automatically topping up the balance when a threshold is reached:
def auto_topup_if_needed(threshold_gb=10, topup_amount_usd=100):
"""Automatic top-up when balance is low"""
api = ProxyAPIClient()
balance = api.get_balance()
if balance['traffic_remaining_gb'] < threshold_gb:
print(f"Traffic below threshold ({threshold_gb} GB), starting top-up...")
# Request top-up via API
topup_response = requests.post(
f'{api.base_url}/billing/topup',
headers={'Authorization': f'Bearer {api.api_key}'},
json={
'amount': topup_amount_usd,
'payment_method': 'card',
'auto_topup': True
},
timeout=10
)
if topup_response.status_code == 200:
print(f"ā
Balance topped up by ${topup_amount_usd}")
# Send notification
notifier = TelegramNotifier()
notifier.send_message(
f"š³ Automatic Top-Up\n\n"
f"Amount: ${topup_amount_usd}\n"
f"Traffic before: {balance['traffic_remaining_gb']:.2f} GB\n"
f"Reason: reached threshold of {threshold_gb} GB"
)
else:
print(f"ā Top-up error: {topup_response.text}")
else:
print(f"Traffic is sufficient: {balance['traffic_remaining_gb']:.2f} GB")
# Start check (can be added to cron)
auto_topup_if_needed()
Creating Your Own Statistics Dashboard
To visualize data from the API, you can create a web dashboard with traffic consumption charts, distribution by countries, and types of proxies. Let's consider a simple example using Flask + Chart.js.
Backend on Flask
from flask import Flask, jsonify, render_template
from datetime import datetime, timedelta
import requests
app = Flask(__name__)
class ProxyDashboard:
def __init__(self):
self.api_key = os.getenv('PROXY_API_KEY')
self.base_url = 'https://api.proxyprovider.com/v1'
def get_dashboard_data(self):
"""Retrieve all data for the dashboard"""
headers = {'Authorization': f'Bearer {self.api_key}'}
# Balance and overall statistics
balance = requests.get(
f'{self.base_url}/balance',
headers=headers
).json()
# History for the last 30 days
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
history = requests.get(
f'{self.base_url}/traffic/history',
headers=headers,
params={
'from': start_date.strftime('%Y-%m-%d'),
'to': end_date.strftime('%Y-%m-%d'),
'group_by': 'day'
}
).json()
# List of proxies
proxies = requests.get(
f'{self.base_url}/proxies/list',
headers=headers
).json()
# Aggregating data
traffic_by_country = {}
traffic_by_type = {}
for proxy in proxies.get('proxies', []):
country = proxy.get('country', 'Unknown')
proxy_type = proxy.get('proxy_type', 'Unknown')
traffic = proxy.get('traffic_used_mb', 0) / 1024 # in GB
traffic_by_country[country] = traffic_by_country.get(country, 0) + traffic
traffic_by_type[proxy_type] = traffic_by_type.get(proxy_type, 0) + traffic
return {
'balance': balance,
'history': history.get('daily_stats', []),
'traffic_by_country': traffic_by_country,
'traffic_by_type': traffic_by_type,
'total_proxies': len(proxies.get('proxies', []))
}
dashboard = ProxyDashboard()
@app.route('/')
def index():
"""Dashboard main page"""
return render_template('dashboard.html')
@app.route('/api/stats')
def get_stats():
"""API endpoint for retrieving statistics"""
try:
data = dashboard.get_dashboard_data()
return jsonify(data)
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, port=5000)
Frontend with Charts (dashboard.html)
<!DOCTYPE html>
<html>
<head>
<title>Proxy Statistics Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
.stats-card { background: white; padding: 20px; margin: 10px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.stat-value { font-size: 2rem; font-weight: bold; color: #2563eb; }
.chart-container { height: 300px; margin: 20px 0; }
</style>
</head>
<body>
<h1>š Proxy Statistics Dashboard</h1>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
<div class="stats-card">
<div>Balance</div>
<div class="stat-value" id="balance">-</div>
</div>
<div class="stats-card">
<div>Remaining Traffic</div>
<div class="stat-value" id="traffic-remaining">-</div>
</div>
<div class="stats-card">
<div>Used</div>
<div class="stat-value" id="traffic-used">-</div>
</div>
<div class="stats-card">
<div>Active Proxies</div>
<div class="stat-value" id="active-proxies">-</div>
</div>
</div>
<div class="chart-container">
<canvas id="trafficChart"></canvas>
</div>
<script>
async function fetchStats() {
const response = await fetch('/api/stats');
const data = await response.json();
document.getElementById('balance').innerText = data.balance.balance;
document.getElementById('traffic-remaining').innerText = data.balance.traffic_remaining_gb;
document.getElementById('traffic-used').innerText = data.balance.traffic_used_gb;
document.getElementById('active-proxies').innerText = data.balance.active_proxies;
// Update chart
const ctx = document.getElementById('trafficChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: data.history.map(stat => stat.date),
datasets: [{
label: 'Traffic Used (GB)',
data: data.history.map(stat => stat.traffic_gb),
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1,
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
fetchStats();
</script>
</body>
</html>
This example demonstrates how to create a simple dashboard that retrieves and displays proxy statistics. You can expand it by adding more visualizations and features as needed.