Skip to content

Repository files navigation

⚡ Decentralized Energy Trading Platform with AI/ML Forecasting

A blockchain-based peer-to-peer energy trading platform that enables users to buy and sell renewable energy tokens (kWh) with integrated AI/ML forecasting, real-time order book, and persistent balance tracking.

Status: ✅ Production-Ready for Local Development


🌟 Key Features

🔄 Energy Trading

  • Token-Based Trading: 1 token = 0.01 kWh of energy ($0.16 per token)
  • P2P Marketplace: Direct user-to-user energy orders with order book
  • Token Economics: Sellers earn tokens (no cost), Buyers spend tokens
  • Self-Trading Prevention: Users cannot trade with their own orders
  • Order Matching: Real-time buy/sell order execution

💰 Wallet & Balance Management

  • Ephemeral Wallets: Session-based wallets with no permanent server storage
  • Initial Allocation: 10,000 KWH tokens per new user signup
  • Balance Persistence: Balances survive blockchain redeployment
  • Auto-Sync: Blockchain ↔ Database synchronization
  • Multi-Session Support: Different wallets per trading session

📊 Dashboard

  • Real-Time Balance: Live token display and updates
  • Order Book: Browse and execute buy/sell orders
  • Transaction History: Complete trade records with timestamps
  • Session Wallet: View current wallet address
  • User Profile: Account management and statistics

🤖 AI/ML Energy Forecasting

  • Hybrid Model System: XGBoost base model + Random Forest user models
  • 24-Hour Prediction: Forecast next day energy consumption
  • Personalized Accuracy: Blends general patterns with user-specific behavior
  • Auto-Training: User models trained on historical meter consumption data
  • Weighted Ensemble: Combines predictions with adaptive confidence blending

📈 Smart Meter Simulation

  • Realistic Consumption: 5-7 kWh/day average with time-of-use patterns
  • Time Variation: Morning peak (6-9am), Evening peak (6-10pm), Night low
  • Weekend Adjustment: 20% higher on weekends
  • MQTT Publisher: Real-time data streaming to energy/meter topic
  • 15-Min Intervals: Simulated meter readings every 15 minutes

🏗️ Architecture Overview

LayerComponentsTechnology
FrontendDashboard, Login, Order Book, Trading PanelHTML5, CSS3, JavaScript
Backend APIUser Auth, Trading, Tokens, ML, BlockchainFlask, Python
Smart ContractsKWhToken (ERC-20), Market, Escrow, MeterRegistrySolidity 0.8.28
BlockchainToken transfers, balance tracking, settlementHardhat Node, Web3.py
DatabaseUsers, wallets, balances, meter readingsPostgreSQL
ML/AIEnergy forecasting, consumption predictionScikit-learn, Random Forest
IoT/SimulationMeter data generation and publishingMQTT, Paho

Core Components

1. Frontend Layer (index3.html, app.js, styles.css)

  • Login/registration with session management
  • Trading dashboard with real-time balance
  • Order book for buy/sell orders
  • User profile and transaction history
  • Responsive design for all devices

2. Backend API (api.py)

  • User authentication and session management
  • Trading order creation and execution
  • Token minting, burning, transfers
  • Balance persistence and sync with blockchain
  • ML model training and energy forecasting
  • 20+ REST endpoints for all operations

3. Smart Contracts (blockchain/contracts/)

  • KWhToken.sol: ERC-20 energy token with mint/burn
  • Market.sol: Trading marketplace with settlement tracking
  • Escrow.sol: Secure trade escrow with confirmation flow
  • MeterRegistry.sol: Meter registration and ECDSA verification

4. Blockchain Integration (blockchain_integration.py)

  • Web3.py connection to Hardhat node (localhost:8545)
  • Burn-mint token transfer pattern (no approval needed)
  • Contract ABI loading and instance creation
  • Gas management and transaction handling

5. Database (create_tables.sql)

  • Users table: email, password, wallet_address, token_balance
  • Meter_readings table: timestamp, consumption_kwh per user
  • Indexes for fast queries
  • Automatic balance sync after redeployment

6. Machine Learning (model.py)

  • Hybrid system: base model + user-specific models
  • Random Forest Regression (100 trees)
  • Temporal features: month, day_of_week, hour
  • Automatic training on meter data
  • 24-hour consumption forecasting

7. IoT Simulation (meter_sim.py)

  • MQTT publisher to localhost:1883
  • Realistic consumption patterns (5-7 kWh/day)
  • Time-of-use variation and weekend adjustment
  • 15-minute interval simulated readings

🧠 Machine Learning System (Hybrid Forecasting)

Architecture: Two-Model Ensemble

The ML system uses a hybrid hybrid-based approach combining a general base model with personalized user-specific models:

Input: month, day_of_week, hour, temperature, lag_features
↓
├─ Base Model (XGBoost)
│ └─ Trained on synthetic dataset (year of India-like consumption patterns)
│ Features: 15-min consumption, temperature, seasonal patterns
│ RMSE: 0.006081 kWh
│
├─ User Model (Random Forest) [if available]
│ └─ Trained on user's actual meter readings (70% of historical data)
│ Features: Same as base model
│ Updated weekly as new data arrives
│
└─ Hybrid Prediction
└─ Weighted blend: α·base_pred + (1-α)·user_pred
Where α = adaptive confidence (based on user data volume)

Component Details

Base Model Training (base_model.pkl - XGBoost)

  • Data Source: Synthetic annual consumption data simulating India's climate
  • Features:
    • Temporal: month (1-12), day_of_week (0-6), hour (0-23)
    • Weather: temperature_c (seasonal variation)
    • Lag features: lag1 (15min ago), lag4 (1hr ago), lag96 (1 day ago)
  • Algorithm: XGBoost Regressor (boosted ensemble)
  • Performance: RMSE 0.006081 kWh, R² 0.9876

User-Specific Models (user_model_{id}.pkl - Random Forest)

  • Data Source: User's actual meter readings from meter_readings table
  • Training Frequency: Weekly auto-retraining when new consumption data available
  • Features: Same 8-feature set as base model
  • Algorithm: Random Forest Regressor (100 trees, bagging ensemble)
  • Personalization: Captures user's unique consumption patterns:
    • Individual peak hours (may differ from average)
    • Appliance usage habits
    • Seasonal adjustments based on actual behavior
    • Weekend vs weekday variations
  • Data Split: 70% training, 30% testing (ongoing)

Hybrid Prediction Pipeline

defhybrid_predict(user_id, month, day_of_week, hour):
# 1. Load general base model (always available)base_model=joblib.load("base_model.pkl") # XGBoostbase_prediction=base_model.predict(features)
# 2. Try to load user-specific model (if exists)try:
user_model=joblib.load(f"user_model_{user_id}.pkl") # Random Forestuser_prediction=user_model.predict(features)
user_has_data=TrueexceptFileNotFoundError:
user_has_data=False# 3. Adaptive blending based on data confidenceifuser_has_data:
confidence=min(0.8, user_data_points/1000) # Scale 0-0.8hybrid_prediction=confidence*user_prediction+ (1-confidence) *base_predictionelse:
hybrid_prediction=base_prediction# Fallback to basereturnhybrid_prediction

Why This Approach?

Base Model (XGBoost) handles general patterns

  • Trained on diverse, representative data
  • Captures average consumption, seasonal trends
  • Provides stable baseline for all users

User Model (Random Forest) adds personalization

  • Learns individual quirks and preferences
  • Improves accuracy as user accumulates history
  • Random Forest faster to retrain than XGBoost

Hybrid Blend gets best of both worlds

  • New user? Use base model until they have data
  • Experienced user? User model dominates
  • Graceful degradation if user model fails

Performance: Hybrid vs Base-Only

Testing Result (simulated user with different peak hours):

MetricBase Model OnlyHybrid (Base + User)Improvement
RMSE0.006081 kWh0.005342 kWh12.1% better
MAE0.003891 kWh0.003204 kWh17.6% better
MAPE7.94%6.38%19.6% better
0.98760.9905+0.29% variance

Conclusion: Personalization reduces error by ~15-20% on average.

Algorithm Comparison (Base Model Candidates)

We tested 5 algorithms as potential base models:

AlgorithmTypeRMSEWinner?Notes
Random ForestBagging0.005454⭐ BestFast, stable, good generalization
XGBoostBoosting0.006081✅ CurrentSlightly slower but consistent
Gradient BoostingBoosting0.007085✅ GoodSimilar to XGBoost, less optimized
ARIMATime Series0.010031❌ PoorR² negative (worse than mean)
LSTMDeep Learning0.011522❌ WorstR² negative, poor on tabular data

Current Choice: XGBoost kept as base model for stability and proven performance in production. Random Forest offers ~10% better RMSE but XGBoost's consistency is preferred.

24-Hour Forecast Generation

defforecast_next24_series(user_id, start_hour=0):
"""Generate 24-hour consumption forecast"""forecasts= []
forhourinrange(24):
prediction=hybrid_predict(
user_id,
month=current_month,
day_of_week=current_day_of_week,
hour=hour
)
forecasts.append({
'hour': hour,
'predicted_consumption_kwh': prediction
})
returnforecasts

Returns 24-element list of hourly predictions for the next day.

Integration with Trading System

Forecasts help users make smarter energy decisions:

  • Low forecast hour? Wait to buy energy (prices may drop)
  • High forecast hour? Sell excess energy (buyers will need it)
  • Weekend spike? Plan to sell AC surplus on Fridays
  • Seasonal trend? Pre-purchase tokens for high-consumption season

� Quick Start

Trading Flow

  1. User A creates SELL order (50 kWh) - no tokens needed
  2. User B buys the order with tokens (50 tokens → User A)
  3. Blockchain: BURN 50 tokens from User B, MINT 50 to User A
  4. Database: Balances persist across sessions
  5. Result: User A gains tokens, User B spends tokens

Setup

Prerequisites

  • Node.js v16+, Python 3.8+, PostgreSQL 12+

3-Terminal Setup

Terminal 1 - Blockchain:

cd blockchain && npm install && npx hardhat node

Terminal 2 - Deploy Contracts:

cd blockchain
npx hardhat run scripts/deploy_contracts.js --network localhost

Terminal 3 - Backend:

pip install -r requirements.txt
createdb energy_data && psql energy_data < create_tables.sql
python api.py

Open http://localhost:5001/login in browser

Multi-User Testing

  • Regular window: Create User 1 account, sell energy
  • Incognito window: Create User 2 account, buy energy
  • Tokens transfer automatically

� Token Economics

  • Signup Bonus: 10,000 KWH per user (one-time)
  • Seller: Earn tokens when energy sold (no token cost)
  • Buyer: Spend tokens to buy energy
  • Price: $0.16 USD per token ($16/token)
  • Conversion: 1 token = 0.01 kWh energy
  • Rules: No self-trading, unlimited supply via sales

🛠️ Tech Stack

ComponentTechnologyVersion
Smart ContractsSolidity0.8.28
Contract FrameworkHardhat3.0.7
Blockchain LibEthers.js / web3.py6.15.0 / 7.0.0
BackendFlask2.3.3
DatabasePostgreSQL12+
ML FrameworkScikit-learn1.3.0
Data ProcessingPandas, NumPy2.1.1, 1.24.3
IoT ProtocolMQTT3.1.1
FrontendHTML5/CSS3/JSES6+

📁 Project Files

energy-trading-platform/
├── api.py # Flask backend
├── app.js # Frontend logic
├── blockchain_integration.py # Web3 integration
├── model.py # ML forecasting
├── meter_sim.py # MQTT simulator
├── create_tables.sql # Database schema
├── requirements.txt # Python deps
├── index3.html, login.html # Frontend pages
├── styles.css # Styling
│
└── blockchain/ # Smart contracts
├── contracts/ # .sol files
├── scripts/deploy_contracts.js
├── hardhat.config.ts
└── package.json

🔐 Security Notes

  • ✅ Self-trading prevention
  • ✅ Burn-mint token pattern
  • ✅ Session-based ephemeral wallets
  • ✅ Database balance persistence
  • ⚠️ For production: use MetaMask, implement EIP-4337, add rate limiting

📚 Documentation


🤝 Contributing

Contributions welcome! Fork, create a feature branch, and submit a pull request.

📄 License

MIT License - see LICENSE

🙏 Acknowledgments

  • Hardhat, web3.py, OpenZeppelin, Flask, scikit-learn, PostgreSQL

Last Updated: 2026-08-29 | Status: ✅ Local Development Ready

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages