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
- 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
- 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
- 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
- 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
- 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/metertopic - 15-Min Intervals: Simulated meter readings every 15 minutes
| Layer | Components | Technology |
|---|---|---|
| Frontend | Dashboard, Login, Order Book, Trading Panel | HTML5, CSS3, JavaScript |
| Backend API | User Auth, Trading, Tokens, ML, Blockchain | Flask, Python |
| Smart Contracts | KWhToken (ERC-20), Market, Escrow, MeterRegistry | Solidity 0.8.28 |
| Blockchain | Token transfers, balance tracking, settlement | Hardhat Node, Web3.py |
| Database | Users, wallets, balances, meter readings | PostgreSQL |
| ML/AI | Energy forecasting, consumption prediction | Scikit-learn, Random Forest |
| IoT/Simulation | Meter data generation and publishing | MQTT, Paho |
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
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)
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_readingstable - 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)
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✅ 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
Testing Result (simulated user with different peak hours):
| Metric | Base Model Only | Hybrid (Base + User) | Improvement |
|---|---|---|---|
| RMSE | 0.006081 kWh | 0.005342 kWh | 12.1% better |
| MAE | 0.003891 kWh | 0.003204 kWh | 17.6% better |
| MAPE | 7.94% | 6.38% | 19.6% better |
| R² | 0.9876 | 0.9905 | +0.29% variance |
Conclusion: Personalization reduces error by ~15-20% on average.
We tested 5 algorithms as potential base models:
| Algorithm | Type | RMSE | Winner? | Notes |
|---|---|---|---|---|
| Random Forest | Bagging | 0.005454 | ⭐ Best | Fast, stable, good generalization |
| XGBoost | Boosting | 0.006081 | ✅ Current | Slightly slower but consistent |
| Gradient Boosting | Boosting | 0.007085 | ✅ Good | Similar to XGBoost, less optimized |
| ARIMA | Time Series | 0.010031 | ❌ Poor | R² negative (worse than mean) |
| LSTM | Deep Learning | 0.011522 | ❌ Worst | R² 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.
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
})
returnforecastsReturns 24-element list of hourly predictions for the next day.
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
- User A creates SELL order (50 kWh) - no tokens needed
- User B buys the order with tokens (50 tokens → User A)
- Blockchain: BURN 50 tokens from User B, MINT 50 to User A
- Database: Balances persist across sessions
- Result: User A gains tokens, User B spends tokens
- Node.js v16+, Python 3.8+, PostgreSQL 12+
Terminal 1 - Blockchain:
cd blockchain && npm install && npx hardhat nodeTerminal 2 - Deploy Contracts:
cd blockchain
npx hardhat run scripts/deploy_contracts.js --network localhostTerminal 3 - Backend:
pip install -r requirements.txt
createdb energy_data && psql energy_data < create_tables.sql
python api.pyOpen http://localhost:5001/login in browser
- Regular window: Create User 1 account, sell energy
- Incognito window: Create User 2 account, buy energy
- Tokens transfer automatically
- 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
| Component | Technology | Version |
|---|---|---|
| Smart Contracts | Solidity | 0.8.28 |
| Contract Framework | Hardhat | 3.0.7 |
| Blockchain Lib | Ethers.js / web3.py | 6.15.0 / 7.0.0 |
| Backend | Flask | 2.3.3 |
| Database | PostgreSQL | 12+ |
| ML Framework | Scikit-learn | 1.3.0 |
| Data Processing | Pandas, NumPy | 2.1.1, 1.24.3 |
| IoT Protocol | MQTT | 3.1.1 |
| Frontend | HTML5/CSS3/JS | ES6+ |
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
- ✅ Self-trading prevention
- ✅ Burn-mint token pattern
- ✅ Session-based ephemeral wallets
- ✅ Database balance persistence
⚠️ For production: use MetaMask, implement EIP-4337, add rate limiting
- QUICK_START.md - Quick setup guide
- TOKEN_ECONOMICS.md - Token system details
- BLOCKCHAIN_IMPROVEMENTS.md - Roadmap
Contributions welcome! Fork, create a feature branch, and submit a pull request.
MIT License - see LICENSE
- Hardhat, web3.py, OpenZeppelin, Flask, scikit-learn, PostgreSQL
Last Updated: 2026-08-29 | Status: ✅ Local Development Ready