1 Introduction

Electricity has become an essential underpinning constituent in the developing world. It supports and elevates the research and creation of technologies that serve humankind. It also serves as a main deriving force, in the absence of which, the modern technologies can not work properly. Electricity has found its critical role from transportation to education and business, and its importance cannot be repudiated. Due to this, the demand for electricity and power is increasing rapidly. This imposes utility energy grids to install more conventional power grids that result in higher production costs and an increase in the emission of harmful gasses. Hence, other than the increasing cost of electric commodity, mankind is also facing problems such as global warming.

Modern electricity markets have seen the introduction of new players that generate and distribute electricity using Renewable Energy Sources (RES) that has acquired popularity because it is environment friendly and cost-efficient. Hence, more and more small scale prosumers have emerged who can sell the surplus energy to other consumers. This demands the creation of a communication system that can allow two-way communication between buyers and producers, hence emerged a modern smart grid (SG) that eliminated the complete dependency over thermal power plants and provided a RES alternative to energy demands. Recently, several communication protocols are paving ways to support direct communication of peers including energy generating and consuming parties in the market. For the participants to get more benefits for trading in local markets, secure and trustworthy trading mechanisms are required that promise improvement in system performance. Using such systems, the P2P (peer-to-peer) coalition has the potential to empower small scale producers and encourage them to participate in local energy markets. That would also support the energy industry as more equipment such as solar panels, smart meters, and energy management systems would be sold.

Although P2P trading decreases the energy cost for the local consumers, the consumer still has to buy energy from the utility grids because of limited energy generation in the local microgrid. This increases the load over the hazardous energy generators, such as thermal power generators, that are involved in the creation of greenhouse gas emissions. Energy trading among microgrids is a potential solution to reduce energy requirements from energy generators of polluting utility grids. Current literature lacks the system model where all P2P, M2M (microgrid-to-microgrid), and energy trading paradigms are discovered. The state-of-the- art energy management systems between and among microgrids have a few shortcomings. Most of these approaches are centralized and are not scalable. Due to centralized nature, the solutions provide limited trust as the centralized entity might be malicious or be subject to attacks. There exist other security challenges such as denial of service attacks on the centralized computational infrastructure that make the system vulnerable. Hence a more efficient and secure way of creating trading systems is required. Blockchain, as a technology, has emerged as a secure and efficient alternative as it provides path towards implementing trustful and decentralized energy trading markets [1, 2]. Due to this nature, it has been successful in attracting attention from various researchers and has become a new important part of energy trading systems. The blockchain is now being used to create coalitions, keeping user data, and executing smart contracts amongst the users [3, 4]. Smart contracts are moving towards blockchain assisted environments using smart meters for better energy management and creating a reliable smart power grid environment [5].

Motivated by the existing work and use of blockchain in energy markets, an autonomous blockchain assisted P2P and M2M energy trading system named SynergyGrids is developed to improve the social utility and overall benefits of prosumers and consumers in the microgrids. SynergyGrids has the following novelties.

  1. 1.

    A blockchain-based trading system involving prosumers, consumers, and the microgrids is proposed, where the energy can be traded both between the peers within the microgrids and the peers from different microgrids. Smart contracts are used to provide secure platform for trading.

  2. 2.

    A pricing mechanism that ensures the increase in utility of the participants is proposed. The presented pricing technique takes into account the total available energy, the usage, and the distance between consumer and prosumer for cost calculation.

  3. 3.

    The proposed model utilizes the Hourly energy data set. The effect of hybrid trading is discussed making this work reference for relevant future works. The presented model reduces the load over the utility grid and increases the sale of prosumers.

  4. 4.

    Most of the current energy trading models consider the profit maximization of an individual hence does not consider the effect of the price of energy on the overall system. The proposed model calculates the energy price considering different factors that reduce the price in comparison to utility grid energy prices. Moreover, the proposed model utilizes all available energy to minimize the total energy cost of the consumer.

The rest of the paper contains the related work in Section 2 that discusses the literature work on energy trading and blockchain. Section 3 outlines the problem statement and the proposed solution. Section 4 contains the details of system architecture and an explanation of the entities involved. Further, Section 5 explains the energy trading and price calculation while Section 6 presents the implementation over the smart contracts. The conducted experiments and results are presented in Section 7 and the paper concludes in Section 9.

2 Related work

This section discusses different models for conducting P2P energy trade that have emerged and the use of blockchain in energy trading. Most of the proposed systems utilize technologies such as smart meters, cloud storage, and edge computing for development and implementation. Smart microgrids [6, 7] are early examples, that have local prosumers connected with each other with energy trading capabilities. Zhang et al. [8] proposes peer-to-peer energy trade between the prosumers and consumers within the microgrid to create smart microgrids. A centralized system is used where the prosumers can sell energy to consumers through a bidding system. A similar approach is proposed by [9] where local prosumer management is done within the residential prosumers in the locality. Another work [10] creates a system with the objective of this community is to minimize the costs of electricity consumption from the transmission grid by prioritizing self-sufficiency. Petri et al. [11] proposes a rather different system to provide a trading platform. The proposed model introduces the concept of a federation for better price optimization.

The first hybrid approach was introduced by [13] where the trading is possible between both prosumers within microgrids and from the utility grids. Afterward, different game theoretical models for energy equilibrium creation were proposed. Paudel et al. [17] proposes a novel game-theoretical model for P2P energy trade that empowers buyer to be able to adjust its energy consumption pattern depending on energy price. An M-leader and N-follower Stackelberg gaming technique is used to devise the buyer-seller interaction for pricing competition. The presented results conclude that P2P trading has emerged as alternative to traditional energy systems that provide community with strong technical and financial benefits. Similarly, [14] aims to create a Nash equilibrium using Game theory, hence reduce dependency on central grids. Most of the mentioned works [13, 14, 17] have drawbacks that are faced due to their centralized nature.

The use of blockchain technology in P2P energy trading has various benefits and has encouraged the emerging of blockchain energy trading research. For instance, [16] creates blockchain for scalable and secure energy trade. Also, blockchain based resilient market for the prosumers and consumers has been presented in [19] where smart contract technology is utilized to realize real-time P2P trade. The concept of the aggregator is used for better energy management. Similarly, [20] uses the consortium blockchain concept for energy trading and crowd-sourcing for smart grids. Further, blockchain-based decentralized solution for demand management in [21]. The validation and testing of blockchain is done by creating a prototype that decreases the cost and improve reliability by removing part of third party. Ali et al. [22] provides a comprehensive outline of several use cases of energy trading in various scenarios. These papers provide proof of the concept of the blockchain impact on energy trading, however, they do not tackle the virtual grouping problem over the blockchain.

Following the concept of blockchain in energy trade, the authors of [12] have used blockchain for hybrid energy trading between consumers and prosumers, and utility grids without using the microgrid concept. Bidding over the price is done before the trading starts. The bid with the lowest price is selected as the trading price for the next time-step. During trading, the buying requests are matched with the available prosumers and the remaining amount is bought from the utility grids. Ethereum smart contracts have been used for implementation and show improvement in the energy price and performance of the system. Similarly, the authors of [23] have provided a marketplace created on top of smart contracts to facilitate decentralized energy trading. In [24], blockchain is used to create the prosumer groups for improved profitability by providing increased cumulative energy to be traded. This work was extended in [15], by adding a reinforcement learning module to create a self-adaptive grouping technique that further improves the overall system performance and profitability. The study of [18] creates microgrids coalition for the microgrid-to-microgrid energy trading through blockchain. An asynchronous coalition formation method is proposed which is distributed and robust. Multiple coalition algorithms are executed to reduce computation time hence increasing the frequency of energy trade between the microgrids. The results have shown, after successful simulation, that the proposed model achieves the desired results such as an increase in prosumer sales and a reduction in consumer cost. Although separately available, there is a lack of an existing solution that performs energy trade within and across microgrids. Table 1 summarizes the drawbacks and targets of the discussed solutions.

Table 1 Energy trading literature review summary

From the literature review, it is evident that blockchain technology has evolved as a compelling solution to replace the centralized systems that face several security and performance issues. Also, there is a need of creating an eco-system that handles both P2P and M2M trading to create a positive impact on the environment by using all the renewable energy within the system and reducing the load over utility grids. For these reasons, this paper investigates the use of blockchain technology with energy trading by proposing a blockchain-supported distributed m microgrid energy trading model. The model also consider a pricing mechanism that ensures the increase in utility of all participants.

3 Problem statement

Due to increase in energy generation and energy demand, there is a need for development of newer management and trading systems that provide monetary incentives to encourage users taking part in energy trading. Although Blockchain-based smart management exists, these methods have inherent limitations. For example, demand response programs are presented for smart management [21, 25] done through load curtailment, that is not an efficient solution when considering participants comfort. Furthermore, these methods are limited to local markets and do not include other microgrids and utility grids in energy trading

To overcome these limitations, a model that performs P2P and M2M energy trading would be a feasible solution. It will increase the profit of the individual prosumer, sustain energy consumers, reduces dependence on utility grids, and aid in stabilizing the energy across microgrids. In such a model, electricity prosumers can use RES to generate energy locally. The surplus energy, that remains after fulfillment of their energy demands, can then be traded with energy consumers within the microgrids and across the microgrids. These trading markets also require a pricing mechanism such that the price of buying from fellow prosumers is less than that of the utility grid. An open book trading mechanism (bidding) can be used for such markets [26] however in such systems, some consumers pay more than others that create an imbalance in trading. Besides, the trading system should be autonomous and should be able to identify Who to sell energy with? How can energy be traded?

3.1 Microgrids energy trading

Microgrids energy trading system aims to reduce electricity consumption cost and consumer dependence on utility grids. A stable blockchain-based hybrid trading mechanism is proposed where consumers can both use P2P and M2M energy transactions to fulfill the energy requirements. This drastically reduces the load over utility and also helps utility grids to smartly use and distribute energy to the areas that are not self-sufficient hence improving the overall efficiency of energy systems of the country. Unlike [12], the coalition between microgrids can also be done to maximize the utilization of available renewable energy within the system. This study also formulates pricing mechanisms that take into account the load and generation of locality and energy losses due to transmission to provide low prices to consumers that also benefit prosumers in the system. The proposed solution considers the following:

  1. 1.

    Eliminates the main grid monopoly by decentralizing the energy trading markets and creates an environment where local consumers can get energy at lower prices.

  2. 2.

    Implements smart contracts, with self-triggering capability, that are designed for devising transactions between entities hence reducing the demand from the main grid.

  3. 3.

    Helps utility grid by decreasing its load that can then be used in low energy areas for better management.

  4. 4.

    Implements a matching mechanism that takes into account energy requirements and matches buyers with the sellers.

4 System architecture

4.1 Model components

As shown in Fig. 1 the main components of our model are:

  1. 1.

    Prosumers/Consumers: That sell/buy the energy.

  2. 2.

    Microgrids: That fulfill the local energy demands.

  3. 3.

    Utility grids: The main grids that facilitate energy transfer.

  4. 4.

    Blockchain: For decentralization purposes.

Fig. 1
figure 1

System architecture and interactions

In the proposed model, a cost-effective trade of energy and planning for distributed energy is achieved by leveraging the community prosumers and the utility grids. The utility grids are usually owned by the governments and are composed of:

  1. 1.

    Large Energy Storage: These are storage places containing large batteries that can store the surplus energy.

  2. 2.

    Conventional Energy Generators: These contain the energy generated by the gas, oil and coal.

  3. 3.

    Renewable Energy Generators: These generate energy through renewable energy. The energy is taken from solar panels, windmills, and water power.

Prosumers are the consumers that can generate energy through renewable sources, as mentioned above, but on a smaller scale than the utility grids. These prosumers have the capability of generating the surplus energy that is stored in the battery storage and can be traded with the other consumers in the community. This is also done through the Energy Management System (EMS) which takes in the buying request and completes it by selling the energy available. Both the prosumers and consumers can be houses, office buildings, and electric cars, which are equipped with EMS. The collection of these prosumers gives out the concept of the Microgrids.

4.2 Microgrid definition

A microgrid can be deemed as electricity distribution systems consisting of a set of individuals with DER capabilities within same geographical area, that have a common medium-voltage/low-voltage (MV/LV) transformer [8] and are connected with the electrical wires. The capabilities of the microgrids involve the following.

  1. 1.

    The microgrids can operate, control, and coordinate the distributed energy resources.

  2. 2.

    Microgrids are connected with the main power network (utility grids) to buy the energy from the main grids.

  3. 3.

    Microgrids are connected through the centralized control systems that are responsible for the trading among the buyers and the sellers.

All the trading among the microgrids is considered P2P in nature as the buyers and sellers can directly sell to each other. Conventional microgrids are centralized in nature i.e. all the trades are done through the centralized authority. There has been a rigorous amount of work done to make them decentralized using the blockchain. Microgrids do not contain centralized storages like utility grids. Moreover, a microgrid does not contain information about other microgrids that might be connected with the utility grids neither do they have any physical connection with the other microgrids [27].

The participants in a microgrid fulfill the energy demands by trading energy amongst each other. The consumer buys energy from the prosumers at a fixed price. If the energy demand is more than the produced energy, the microgrid communicates with the main power grid network to fulfill the energy demand which might be more expensive than the energy bought from the prosumer in the microgrid.

4.3 Use of the blockchain

The blockchain is used to handle the trade between the prosumers in the microgrids along with the trade between the microgrids and the utility grids. Blockchain also stores the information of the prosumers/consumer/utility grids and the microgrids. The smart contracts are used to create contracts that are used to facilitate the above-mentioned trades.

4.4 Interaction between system components and participants

In this sub-section, the overview of different modules and interaction between participants and system components are explained.

  1. 1.

    A prosumer sends the registration request with location, available energy, and microgrid information. This information is stored over the blockchain.

  2. 2.

    A consumer sends the registration request along with energy demand. This information is also kept over the blockchain.

  3. 3.

    The proposed system sets the energy price (as explained is Section 5.2) for M2M trading. Also, depending on the consumer requests in step 1, each microgrid separates the energy that will be required for the local consumers. The rest of the energy can then be used for energy trade across the microgrids.

  4. 4.

    The consumers can then send energy trading (explained in Section 5) request. The system matches the request with the appropriate prosumer in locality or microgrid that has surplus energy.

  5. 5.

    If the energy request has to be fulfilled by the microgrid, another matching loop is executed to find the prosumers that will sell the energy, hence removing the requirement of the microgrid manager. Also, the utility grid is paid for the usage of its resource.

  6. 6.

    The main contract transfers the payment from the consumer account to the prosumer account. If the consumer has no e-wallet, a payment request is sent to the consumer.

  7. 7.

    At the end of the timestep, prosumers update the available energy for the next timestep.

Algorithm 1 explains how energy requests are handled in the system.

5 Energy trading

The energy trading process can be done in two stages. First, the prosumers post the advertisements for the energy to sell. The consumers can see the advertisements and choose to buy the energy from any of the prosumers. The target of the work is to develop a balance between power and price within the microgrids and the prosumers, and also to reduce the dependency on the main utility grids hence reducing the losses caused during energy transfer and also final cost of energy. Table 2 shows the most used symbols in the paper.

Table 2 Notation and explanations

5.1 Selling energy

As discussed earlier, the prosumers in a microgrid can sell the energy to the consumers, there can be a possibility where the energy demands of the consumers in a microgrid are fulfilled and still there is surplus energy to be sold. In this case, the prosumers in a microgrid can benefit by (1) Selling the energy to the utility grid, (2) Selling the energy to other microgrids.

In the first case, the prosumers sell the energy directly to the main grids at a price fixed by the utility grids. The cost of transfer of energy through the wires and the cost of energy losses is also incorporated while the trade is done [12].

In the second case, energy can be sold to the other microgrids using the P2P communication between the centralized systems of the two microgrids. This helps in reduction of community microgrid dependency on the utility grids by balancing the discrepancy present between energy demand and supply through energy trading with other microgrids. This encourages to create a hybrid approach with following trading options: 1) P2P energy trade among the prosumers within a microgrid, 2) P2P energy trade between the community microgrids, and 3) P2P energy trade between microgrids and the utility grids.

figure e

5.2 Energy pricing for energy trading

All the energy prosumers within a microgrid comprise of different renewable energy resources. Moreover, there are consumers within the microgrid that have different load demands. The load demands and energy generations within a microgrid MGn can be expressed as:

$$ \begin{array}{@{}rcl@{}} D_{MG_{n}}^{t} &=& [{D_{1}^{t}}, {D_{2}^{t}}, {D_{3}^{t}}, .... , {D_{i}^{t}}] \end{array} $$
(1)
$$ \begin{array}{@{}rcl@{}} Gen_{MG_{n}}^{t} &=& [Ge{n_{1}^{t}}, Ge{n_{2}^{t}}, Ge{n_{3}^{t}}, .... , Ge{n_{i}^{t}}] \end{array} $$
(2)

where \(D_{MG_{n}}\) is the demand while \(Gen_{MG_{n}}^{t}\) is the generation of microgrid MGn during timestep t.

Depending on the information from Eqs. 1 and 2, the price calculation for energy trading for the next time-step is done in two stages. First, the price calculation for the microgrid-to-microgrid trading is done. Let’s call this value “EPM”. Afterward, the price for peer-to-peer trading within a microgrid is calculated. Let’s call this value “EPP”. These energy price values depend upon the energy price of utility, “EPU”. To make the system beneficial, the following property should hold:

$$ \begin{array}{@{}rcl@{}} EPP \leq EPM \leq EPU \end{array} $$
(3)

Now, for the calculation of the energy price for M2M trading, first calulate the total energy generation to demand ration:

$$ \begin{array}{@{}rcl@{}} TED_{MG_{n}} &=& {\sum}_{i=1}^{np} {D_{i}^{t}} \end{array} $$
(4)
$$ \begin{array}{@{}rcl@{}} TEG_{MG_{n}} &=& {\sum}_{i=1}^{nc} Ge{n_{i}^{t}} \end{array} $$
(5)
$$ \begin{array}{@{}rcl@{}} GDR_{MG_{n}} &=& \frac{TEG_{MG_{n}}}{TED_{MG_{n}}} \end{array} $$
(6)

where np is the number of prosumers and nc is the number of consumers within a microgrid. Now, using Eq. 6, the price of M2M energy trade for next time-step becomes:

$$ \begin{array}{@{}rcl@{}} EPM_{MG_{n}} = \left\{ \begin{array}{ll} \frac{EPU}{GDR_{MG_{n}}} & \text{if } GDR_{MG_{n}} \geq 1 \\ EPU & \text{if } GDR_{MG_{n}} < 1 \end{array} \right. \end{array} $$
(7)

\(EPM_{MG_{n}}\) is the price that has to be paid by the consumer that sends the trading request from any other microgrid to the microgrid MGn and is decided at the start of the time slot.

The energy pricing mode for peer-to-peer trade varies with different energy trading requests because it depends on the distance between the consumer and the prosumer and the type of energy resource (ET) the prosumer is using. This price value is calculated when energy trading request from consumer Ci is received. The system then calculates energy price for energy request to prosumer Pi as follows:

$$ \begin{array}{@{}rcl@{}} GDR_{P_{i}} &=& \frac{Gen_{P_{i}}}{D_{C_{i}}} \end{array} $$
(8)
$$ \begin{array}{@{}rcl@{}} Dist &=& Distance(P_{i}, C_{i}) \end{array} $$
(9)
$$ \begin{array}{@{}rcl@{}} EPP_{P_{i}} &=& \left\{ \begin{array}{ll} \frac{EPM_{MG_{n}} + Dist \times ET_{P_{i}}}{GDR_{P_{i}}} & \text{if } GDR_{P_{i}} \geq 1 \\ EPM_{MG_{n}} & \text{if } GDR_{P_{i}} < 1 \end{array} \right. \end{array} $$
(10)

If a consumer Ci buys EBUG, \(EB_{MG_{n}}\), and \(EB_{P_{i}}\) from utility grid (Energy Bought (EB) is the amount of Energy Bought), M2M and P2P trading, then the overall cost of a consumer Ci can then be calculated as:

  • For prosumer to grid (P2G) energy trading:

    $$ \begin{array}{@{}rcl@{}} TC_{C_{i}}^{UG} = EB_{UG} \times EPU \end{array} $$
    (11)
  • For microgrid-to-microgrid (M2M) energy trading:

    $$ \begin{array}{@{}rcl@{}} TC_{C_{i}}^{MG} = {\sum}_{i=1}^{n} [ EPM_{MG_{n}} \times EB_{MG_{n}}] \end{array} $$
    (12)
  • For peer-to-peer (P2P) energy trading:

    $$ \begin{array}{@{}rcl@{}} TC_{C_{i}}^{PP} = {\sum}_{i=1}^{i} [ EPP_{P_{i}} \times EB_{P_{i}}] \end{array} $$
    (13)

where TC is the total cost for different trading settings. After the price calculation, the total cost transfers from consumer to prosumer.

6 Smart contracts implementation

A smart contract is a set of self-executable commands that can be run over the blockchain. The smart contract keeps the record of necessary rules that, if satisfied, trigger specific instructions that are embedded in the smart contract. In an energy trading paradigm, the smart contract can be used to control energy transactions between peers. The rules for energy transactions can be placed over smart contracts that can not be altered to realize a secure system. Moreover, a smart contract can ensure transparent energy trading markets where all participants trust the contracts hence eliminating the requirement of central parties to control energy management. Due to this nature of the smart contract, this paper develops the system for efficient P2P and M2M energy trading. Figure 2 depicts the overall workflow that is executed by participants and the smart contracts. Descriptions of main interactions in the figure are as follows.

  • Buying request: contains the amount of energy to be bought, as well as the consumer wallet ID.

  • Check status: contains the amount of energy to be bought.

  • Respond request: contains the energy that can be sold, list of prosumers that can sell energy, is transaction within/across grid (0/1).

  • Payment request: the amount to be paid.

Fig. 2
figure 2

Interaction Between System Components and Participants

The following subsection further explain the smart contracts used in microgrids energy trading with details.

6.1 Manager smart contract

This contract is deployed to execute all energy trading operations within the system. All participants directly communicate with this smart contract. This contract is used for:

  1. 1.

    Registering new prosumers and consumers.

  2. 2.

    Registering the microgrids.

  3. 3.

    Matching prosumers and consumers within and across the microgrids for energy trading.

  4. 4.

    Calculation of pricing for the next time-step and compensating the prosumers for their provided energy.

All participants (prosumers or consumers) need to be registered before generating any requests. All the energy surplus and deficit requests are also handled through the main contract. Upon receiving the energy surplus request, this contract updates the information of the M2M contract and P2P contract. In case an energy buying request is received, it first checks the type of request. If the request is for buying, it calls findProsumer function of P2P smart contract that matches the consumer with local prosumers. In case there is still energy to be bought, the findMicrogrid function is called that finds the microgrid with surplus energy for energy trade. The total cost for energy is calculated and transferred from proper buyers to the match sellers. In case there is still energy to be bought, the consumer’s contact grids to buy the energy.

6.2 P2P smart contract

P2P contract is responsible to keep the information of the local prosumers and consumers when any participant is registered through the manager smart contract. The participants in the system can not invoke the P2P contract directly. All the necessary information and commands for invocation can only be sent from the main contract to the P2P contract. The findProsumer function of the contract checks the microgrid id of the consumer and find the list of prosumers that can fulfill the energy demands of the buyer.

6.3 M2M smart contract

M2M contract keeps the information of all the microgrids in a dictionary-like data structure called maps. If there is surplus energy within a microgrid and there is energy requirement in another microgrid, M2M smart contract is used to facilitate consumers through energy trade amongst the microgrids. The price of this energy transaction depends on the price of energy provided by the utility. findGrid function in a smart contract is used to find an appropriate grid that can fulfill the energy demand of the consumer.

6.4 P2G smart contract

This smart contract is created to keep the energy price and resource price of the utility. Moreover, once all the energy transactions between peers and microgrids are done, this contract can be used by the buyers to buy the energy, and it is directly accessible by the system participants and is deployed only by the utility grid.

6.5 Who owns the blockchain and the system

The overall system can be deployed by any entity with access to smart contract codes. The smart contracts are designed in a way that they can be deployed both over the public blockchain and the privately-owned blockchain. The benefits of using public blockchain are faster creation of blocks as there are many miners available while using a private blockchain, the participants can be limited and as most of the miners are self-owned, there is less probability of attack occurrence.

7 Experimental analysis and results

The smart contracts were written on Remix IDEFootnote 1 for testing the correctness of the contracts using over Solidity language. The smart contracts were then deployed over local Ethereum using the Ganache framework and Geth to understand the performance of the system. Following constraints on the system are kept for energy requests:

  1. 1.

    All the participants have to register to the system using the main contract. A participant can either be a prosumer or a consumer in a specific time-step. The set of prosumers and consumers are disjoint.

  2. 2.

    Energy trading price for M2M should be lower than the utility price and price for P2P should be lower than M2M energy price.

All participants communicate with smart contracts through Energy Management Systems (EMS) that is developed using Python Language with web3Footnote 2 library. Moreover, each participant has an e-wallet that has different addresses. These wallets are provided by Ganache. Web3 library loads wallet using web3.eth.accounts function.

7.1 Dataset

Hourly data are used to simulate energy trading based on Hourly energy demand generation and weather.Footnote 3 The dataset contains the data from hourly usage of different cities of Spain. It contains two major information needed for the proposed model:

  • the energy generated by reusable energy resources such as wind and solar energy for each timestamp.

  • the data for energy demand of each timestep.

This makes this dataset suitable and useful for the proposed system. There are several other datasets available but there are following issues with them such as either not contain the specific data values that we require (e.g. missing solar energy values), or private datasets.

The energy prosumers produce energy from Renewable energy resources such as PV panels and windmills. The values for energy consumption and generation are extracted from dataset and distributed amongst the participants. The energy transaction is executed using the blockchain assisted P2P+M2M system suggested in this paper. Different studies are made that prove the efficacy of the system that i.e. increase in the energy profit of the prosumers and decrease in energy prices of energy consumers. An added advantage is for utility grid where the load over utility decreases, increasing the stability of energy in an area where utility works.

7.2 Cost and profit analysis in energy trading

To validate the performance of the system in terms of consumer energy cost and prosumer profit, the energy production and energy load values are taken from the dataset. The system is tested for different scenarios. First, load and generation values are divided into five microgrids. Moreover, the total prosumers in the system are considered to be 300, while total consumers to be 500, divided amongst the microgrids using random allocation. For comparison purposes, microgrid 1 is kept to have higher amount of energy generated and utilized while microgrid 5 is kept to have large energy generated to energy utilization difference. Figures 3 and 4 show the load and generation respectively, of each microgrid in the system. A total of 12 hours (from 8 am to 8 pm) are considered where hours between 6-10 (1 pm to 5 pm) are peak hours. Once the registration of prosumers and consumers is done, the energy trading requests are sent. Two different algorithms are considered for comparison, i.e. P2P and SynergyGrids. The solution based on P2P trading which is the closest algorithm to the proposed model since it is based on trading between the various peers. An external source (the utility) is considered with the P2P algorithm. Figures 567 and 8 show the average energy price, total prosumer sale, load over utility and total consumer cost respectively. It can be seen that the proposed model improves the system by decreasing the load over utility when compared to the model that considers only P2P trading. This reduction stabilizes the utility grid and prevents the possibility of blackouts. For the consumer side, the system reduces the price of energy (Fig. 5) that results in a decrease in the total cost of the consumer as shown in Fig. 8. These reduced prices motivate consumers to buy from local markets and hence increase the energy sale of prosumers (Fig. 6). This shows that the system benefits all participants including utility grids, prosumers, and consumers.

Fig. 3
figure 3

Energy Load of each microgrid

Fig. 4
figure 4

Energy generation of each microgrid

Fig. 5
figure 5

Average energy price with 5 microgrids

Fig. 6
figure 6

Total energy sale with 5 microgrids

Fig. 7
figure 7

Energy load over utility with 5 microgrids

Fig. 8
figure 8

Total consumer cost with 5 microgrids

Another set of results was produced to understand the effect of the number of microgrids, while keeping the same amount of total prosumers and consumers, over the cost and profit of the system. Again, P2P and P2G energy trading is compared with SynergyGrids. Figures 91011, and 12 show the average energy price, total prosumer sale, load over utility and total consumer cost respectively. It was noticed that the decrease in the number of microgrids affects utility+P2P trading more than the proposed model. As can be seen by Fig. 10, there is no increase in the sale of prosumers in the case of the proposed system but the increase in sales is noticed for utility+P2P trading. This is because now more energy resides in local microgrids, which increase the chances of consumers getting enough energy from the local grids. The effect of microgrids can be seen in Fig. 9. The decrease in energy prices can be seen. This trend is in accordance with Eq. 7, here more energy availability within microgrids decreases the energy price, hence decreasing the overall energy cost. Figures 13 and 14 shows the effect of varying price on the total cost and average energy price of the system. The energy price of the proposed system stays less with different utility energy prices.

Fig. 9
figure 9

Average energy price with 3 microgrids

Fig. 10
figure 10

Load over utility with 3 Microgrids

Fig. 11
figure 11

Total energy sale with 3 microgrids

Fig. 12
figure 12

Total consumer cost with 3 microgrids

Fig. 13
figure 13

Total consumer cost with 5 microgrids and varying utility energy price

Fig. 14
figure 14

Average energy price with 5 microgrids and varying utility price

7.3 Network performance

This section describes performance results of the proposed architecture. There exist two types of communication between participants and the smart contract, namely registration request and energy request. The performance is evaluated by monitoring the average time taken to fulfil an energy trading request using Eq. 14. In the experiments, we exploited our system with a range of requests by:

  1. 1.

    Varying the number of prosumers in the system while sending 500 energy requests.

  2. 2.

    Varying amount of energy requests while keeping 500 prosumers in the system.

  3. 3.

    Varying the number of grids in the system while keeping 300 prosumers and sending 500 energy requests.

    $$ \begin{array}{@{}rcl@{}} res = rec - req \end{array} $$
    (14)

Figure 15 compares the average request time by sending a varying amount of energy requests. The presented system has comparable performance with the systems that consider utility and P2P energy trading. The request time is higher because, in the case of SynergyGrids, the system has to do an extra search across the microgrids. The time for the request completion increases with the increase in the number of energy request. Another comparison of time requests with varying amounts of prosumers is shown in Fig. 16. As the number of prosumers in the system increases, the search space for the system increases accordingly which affects the request completion time. The third result, shown in Fig. 17, depicts the effect of grid size on request time. As seen, the number of grids that affects the SynergyGrids system is more than Utility + P2P scenario. This is because an increase in the number of grids decreases search space for Utility + P2P systems as fewer prosumers are present in one grid, but this is not the same case for SynergyGrids. The figures show that the system is scalable with very little overhead in comparison with utility + P2P energy trading systems.

Fig. 15
figure 15

Average request completion time varying number of energy requests

Fig. 16
figure 16

Average request completion time varying prosumers

Fig. 17
figure 17

Average request completion time varying number of grids

8 Challenges and developments

The research of managing different energy resources using futuristic technologies is evolving and there exist many authorities and research groups working on it. We have seen development projects building sustainable communities and offering the possibilities to produce, sell, and trade energy among peers. Blockchain-based renewable energy marketplaces have gained huge attention in the past couple of years. The leading energy-focused companies are Energy Web Token (EWT), Power Ledger (POWR) and WePower (WPR). The interest in these companies and the technologies they build are increasing. The ultimate goal of these companies is to bring blockchain and smart contracts technologies to the open and global energy market to promote renewable energy generation by creating an innovative medium that ties buyers and sellers of energy. We anticipate that the successful development and deployment of this technology still need:

  • Regulations of energy communities and energy industry.

  • Consideration of technical issues in energy communities of different countries.

  • Establishing policy(s) and guidelines of clean energy generation/distribution, regulations, and governance involvement.

  • Energy-as-a-Service related costs as well as the cost of the energy itself.

9 Conclusion

Integrating blockchain technology in peer-to-peer microgrids energy trading is beneficial. This paper investigates the influence of creating an energy trading platform over smart contracts to reduce the dependency of individuals (Microgrids participants) on the utility grid. Therefore, a decentralized P2P energy trading system is implemented where the energy traded both within and across the microgrids using price prediction and matching techniques. A consortium blockchain is used for accessing peer’s information and transactions. The whole trading process is conducted through a manager smart contract that performs user registration, matching procedure, and considers the resources usage cost. The final implementation is tested using real-time data and the results show improvement in both consumer energy price and prosumer energy sale. Although, there might be some consumers that lack the resources to buy the energy. In the future, we aim at developing the concept of federated energy sharing where prosumers can share energy with other prosumers/consumers.