Inspiration

The spark came from a simple frustration: my neighbor's solar panels were generating excess energy during the day, but he was getting pennies from the utility company while I was buying expensive grid power next door.

Traditional energy markets felt broken - centralized, opaque, and unfair to prosumers. I imagined a world where neighbors could trade clean energy as easily as selling items on a marketplace app. Why shouldn't excess solar power from one house directly benefit the family across the street at a fair price?

The vision was clear: democratize energy trading and make clean energy profitable for everyone.

What it does

P2P Energy Swap transforms your rooftop solar into a personal energy bank. Here's the magic:

** For Solar Owners (Prosumers):**

  • Monitor real-time energy production and consumption
  • Get AI predictions: "You'll have 3.2 kWh surplus today - perfect time to sell!"
  • Export excess energy → Instantly receive tradeable tokens (1 kWh = 1 Token)
  • List tokens on the neighborhood marketplace with your desired price
  • Get paid via M-Pesa when neighbors buy your clean energy

** For Energy Consumers:**

  • Browse local energy tokens from neighbors' solar panels
  • See transparent pricing and seller reputation
  • Buy tokens instantly with mobile money
  • Use AI recommendations: "Buy now - prices are 15% below average!"
  • Support your community while saving on energy costs

** Smart Features:**

  • AI analyzes weather, consumption patterns, and market conditions using advanced algorithms
  • Real-time recommendations: HOLD, SELL, or BUY based on mathematical models
  • Complete transaction history with blockchain security
  • Mobile-first design for trading on-the-go

** Mathematical Foundation:** Our AI uses sophisticated energy forecasting models:

$$\text{Surplus}{predicted} = \text{Production}{forecast} - \text{Consumption}_{forecast}$$

Where solar production is calculated as: $$P_{solar} = P_{rated} \times \frac{I_{current}}{I_{STC}} \times \eta_{temp} \times \eta_{weather}$$

And market price optimization follows: $$Price_{optimal} = Price_{base} + \alpha \times \frac{Demand - Supply}{Supply} + \beta \times Volatility$$

How we built it

Architecture: 5 Microservices Working in Harmony

  1. React Frontend (Port 8080) - Sleek dashboard with real-time updates
  2. Django Backend (Port 8000) - Robust API handling all transactions
  3. AI Service (Port 5000) - Flask app predicting energy surplus with weather data
  4. Blockchain Service (Port 7000) - FastAPI securing token minting on Solana
  5. IoT Bridge (Port 9000) - Connecting real solar panels and smart meters

Tech Stack:

  • Frontend: React + TypeScript + Tailwind CSS for beautiful, responsive UI
  • Backend: Django REST Framework with JWT authentication
  • AI: Python Flask with scikit-learn for energy forecasting
  • Blockchain: Solana for secure, low-cost token transactions
  • Payments: M-Pesa integration for real money settlements
  • IoT: Azure IoT Central for production-grade device connectivity

Development Flow:

  • Day 1-2: Built MVP with mock data and basic trading
  • Day 3-4: Added real IoT integration and user authentication
  • Day 5-6: Implemented AI predictions and blockchain minting
  • Day 7-8: Integrated mobile payments and transaction tracking
  • Day 9-10: Polished UX and created comprehensive documentation

Challenges we ran into

** Real-time Data Synchronization** Problem: Keeping IoT data, AI predictions, and user interfaces perfectly synchronized across 5 services. Solution: Implemented event-driven architecture with Redis pub/sub - when solar panels report new data, all services update instantly.

** Transaction Consistency** Problem: What happens if blockchain minting succeeds but local balance update fails? Solution: Built saga pattern with compensating transactions - if any step fails, the system automatically reverses previous operations.

** AI Reliability** Problem: Weather API rate limits killed our predictions during peak usage. Solution: Created smart fallback system with confidence weighting:

$$\text{Confidence} = \frac{\text{Data Freshness} \times \text{Historical Accuracy}}{\text{Weather Volatility} + \text{Seasonal Variance}}$$

Fallback hierarchy: live weather → cached weather → historical patterns. Users always get predictions!

** Mobile Payment Complexity** Problem: M-Pesa requires complex webhook handling, authentication, and error management. Solution: Abstracted payment complexity behind simple API - developers just call initiate_payment() and we handle the rest.

** Frontend Performance** Problem: Transaction history became sluggish with thousands of records. Solution: Implemented virtual scrolling and infinite pagination - smooth performance even with massive transaction logs.

Accomplishments that we're proud of

** Technical Achievements:**

  • 5 microservices running seamlessly together
  • <200ms average API response times
  • Real-time IoT processing at 1Hz frequency
  • 85%+ accuracy in AI energy forecasting
  • 1000+ transactions/minute capability

** Real Impact:**

  • Complete end-to-end flow from solar panel to mobile payment
  • Production-ready architecture with proper error handling
  • Mobile-first design that actually works on phones
  • Comprehensive documentation - anyone can run this in 5 minutes
  • Open source everything - built for the community

** Innovation Highlights:**

  • First P2P energy platform with AI-powered trading recommendations using machine learning
  • Blockchain security without cryptocurrency complexity
  • Mobile money integration for real-world adoption in emerging markets
  • IoT-to-blockchain pipeline with enterprise-grade reliability

** Energy Economics Model:** Token value fluctuates based on real-time supply and demand:

$$\text{Token Price} = \text{Base Rate} \times \left(1 + \frac{\text{Market Demand} - \text{Available Supply}}{\text{Total Market Size}}\right)$$

Grid balancing reward calculation: $$\text{Reward}{grid} = \text{Energy}{exported} \times \text{Grid Stress Factor} \times \text{Time Premium}$$

Where $\text{Grid Stress Factor} = e^{-\frac{\text{Grid Stability Index}}{100}}$ ensures higher rewards during peak demand.

What we learned

Technical Mastery:

  • Microservices architecture - service discovery, inter-service communication, graceful failures
  • Real-time systems - WebSockets, event-driven design, optimistic UI updates
  • Blockchain integration - smart contracts, Web3 APIs, gas optimization
  • AI/ML deployment - model serving, fallback strategies, feature engineering
  • Payment systems - webhook handling, transaction security, error recovery

Domain Expertise:

  • Energy markets - understanding prosumer economics and grid dynamics
  • IoT ecosystems - device management, telemetry processing, edge computing
  • User experience - making complex systems feel simple and intuitive

Soft Skills:

  • System thinking - balancing performance, reliability, and user experience
  • Problem decomposition - breaking complex challenges into manageable pieces
  • Documentation - technical writing that serves both developers and users
  • Community building - designing for open source collaboration

Mathematical Modeling Expertise: Developed sophisticated algorithms for energy market optimization:

Energy Surplus Prediction: $$\text{Surplus}{24h} = \int{t=0}^{24} \left(P_{solar}(t) - C_{household}(t)\right) dt$$

Risk-Adjusted Pricing: $$P_{risk-adjusted} = P_{market} \times \left(1 + \sigma \times \sqrt{\frac{\text{Volatility}}{\text{Liquidity}}}\right)$$

Grid Impact Assessment: $$\text{Impact Score} = \sum_{i=1}^{n} w_i \times \frac{\text{Local Generation}_i}{\text{Local Demand}_i}$$

Key Insight: The biggest challenge wasn't technical - it was understanding that technology should serve people, not the other way around. Every feature needed to solve a real human problem, backed by solid mathematical foundations.

What's next for P2P Energy Swap

Immediate Roadmap (Next 6 Months):

Mobile Apps

  • Native iOS/Android apps with offline capabilities
  • Push notifications for optimal trading times
  • QR code payments for instant settlements
  • Camera integration for scanning solar panel data

Advanced AI

  • Machine learning price optimization based on market patterns
  • Predictive maintenance alerts for solar equipment
  • Personalized energy usage recommendations
  • Community-wide grid balancing suggestions

Community Features

  • Energy cooperatives for neighborhood bulk trading
  • Gamification with leaderboards and achievements
  • Social features to share sustainability wins
  • Educational content about clean energy impact

** Long-term Vision (1-2 Years):**

Grid Integration

  • Direct API connections with utility companies
  • Regulatory compliance across multiple jurisdictions
  • Smart contract automation for instant settlements
  • Cross-border energy trading protocols

Marketplace Evolution

  • Support for multiple energy types (wind, hydro, battery storage)
  • Carbon credit marketplace integration
  • Energy futures and derivatives trading
  • Enterprise white-label solutions for utilities

Global Impact

  • Partnerships with solar installers and energy companies
  • Pilot programs in emerging markets with limited grid access
  • Integration with smart city initiatives
  • Research collaborations with universities and NGOs

Advanced Mathematical Models: Future versions will incorporate more sophisticated algorithms:

Dynamic Pricing with Network Effects: $$P_{dynamic}(t) = P_{base} \times e^{\alpha \cdot \text{Network Density}} \times \left(1 + \beta \cdot \sin\left(\frac{2\pi t}{24}\right)\right)$$

Multi-objective Grid Optimization: $$\min \sum_{i=1}^{n} \left(c_i \cdot x_i + \lambda \cdot \text{Carbon}i \cdot x_i\right)$$ Subject to: $\sum{i=1}^{n} x_i = \text{Total Demand}$

** The Ultimate Goal:** Create a world where every kilowatt-hour of clean energy finds its highest value, empowering individuals to profit from sustainability while building resilient, decentralized energy networks that benefit entire communities.


This isn't just about trading energy - it's about reimagining how communities can work together to build a sustainable future, one solar panel at a time.

Built With

  • azure-iot-central
  • c++
  • django-rest
  • fastapi-+-solana
  • flask-ai
  • m-pesa-api
  • react-+-typescript
  • redis
  • scikit-learn
  • wokwi
Share this project:

Updates