Local Flexibility Market Design for Aggregators Providing Multiple Flexibility Services at Distribution Network Level

This paper presents a general description of local flexibility markets as a market-based management mechanism for aggregators. The high penetration of distributed energy resources introduces new flexibility services like prosumer or community self-balancing, congestion management and time-of-use optimization. This work is focused on the flexibility framework to enable multiple participants to compete for selling or buying flexibility. In this framework, the aggregator acts as a local market operator and supervises flexibility transactions of the local energy community. Local market participation is voluntary. Potential flexibility stakeholders are the distribution system operator, the balance responsible party and end-users themselves. Flexibility is sold by means of loads, generators, storage units and electric vehicles. Finally, this paper presents needed interactions between all local market stakeholders, the corresponding inputs and outputs of local market operation algorithms from participants and a case study to highlight the application of the local flexibility market in three scenarios. The local market framework could postpone grid upgrades, reduce energy costs and increase distribution grids’ hosting capacity.


Introduction
Decarbonization of the European electricity system has been set in motion with the rapid proliferation of distributed and renewable energy production sources. The EU has the commitment to cut greenhouse gas emissions in the European Union by at least 40% until 2030 with an expected share of 50% of renewables by 2030 [1]. Recently, European regulatory bodies included the Local Energy Community (LEC) definition in Article 16 of the proposal for a directive on common rules for the internal market in electricity [1] and considered them to be an efficient way to manage energy at the community level. As a result, there is a global surge in interest in LEC managed by Local Flexibility Markets (LFMs).
LECs are an emergent trend with the aim of engaging end-users in a sustainable energy future. There is not an agreed LEC definition in the literature because they can be organized in different ways. As stated in Sajn et al. [2], LECs are citizen-led renewable energy cooperatives, housing associations, foundations or charities, which are not commercial actors, but produce energy meant for self-consumption, mainly by solar PV panels and wind turbines. Additionally, Schoor et al. [3] analyzed LECs in The Netherlands, and their common characteristic is their intention to prioritize community benefits. However, it is not clear if an LEC should be under the same Distribution System Operator (DSO) or within the same Balance Responsible Party's (BRP) portfolio in all cases. In this context, BRPs are responsible for balancing demand and supply for a certain metering point according to Eurelectric [4]. Either way, end-user aggregation would constitute an opportunity to create flexibility exchanges regardless of the LEC characteristics. Hence, the concept of LFM as a market-based mechanism to manage demand response at the LEC level for multiple objectives is adopted in the present paper.
Moreover, the presence of more intermittent distributed generation, the empowerment of consumers and new electric loads like Electric Vehicles (EVs) are forcing the power system to evolve. In the past, centralized, dispatchable and predictable generation provided flexibility at the transmission level to the electric system to balance generation and demand. Now, the increasing amount of installed distributed renewable generation is transforming the generation side into a more variable and intermittent source of energy that needs to be managed adequately. In addition, the demand side is becoming more active, emphasizing the empowerment and engagement of consumers. The proper management of available flexibility, both in generation and demand side, can help to compensate the lack of certainty of renewable sources.
Currently, small generators participate in wholesale electricity markets aggregatively without considering their location within the distribution network. In the future, with a high share of Distributed Energy Resources (DER) in the distribution networks, the power quality could be compromised in terms of voltage limit violations and overloaded lines. DSOs could expand the grid with redundant transformers, but demand response, storage and DER could constitute an economically more profitable way to solve grid constraints [5]. Hence, it is necessary to explore operation algorithms to increase the hosting capacity of distribution systems. One option might be that the DSO could send command signals to DER to reduce the active power injected to the grid [6]. However, this approach could compromise DSO regulated activities acting as an energy manager.
An alternative option is to implement market-based initiatives to deal with these situations. Such initiatives have recently caught the attention of policy-makers, regulatory bodies and researchers alike, as the general consensus is that the current electricity market design has limitations when it comes to integrating renewable energy into the grid.
From a national market perspective, R.Schleicher-Tappeser [7] presented integration limitations of the current market design for scenarios with large-scale penetration of weather-dependent generators. The forthcoming energy sector transformation with massive penetration of photovoltaic panels combined with load management has been introduced without identifying an appropriate market framework for dealing with them. Winkler et al. [8] analyzed the support schemes for renewable energies and their impact on wholesale electricity markets. Kyritsis et al. [9] analyzed the effect of intermittent renewable energy on German wholesale markets. Both references agree on the positive effects of using more flexibility to integrate renewable intermittent generation effectively.
In contrast to wholesale-focused solutions, recent literature presents different price settlement methodologies and energy transactions mechanisms for local transactions. Bayram et al. [10] reviewed different concepts of local trading, enabling technologies and required frameworks. Additionally, Lopez-Rodriguez et al. [11] elaborated on a survey about different market-based control methodologies for DER. In terms of price settlement, Nanduri et al. [12] presented two types of electricity auctions: uniform price and discriminatory auctions at the neighborhood level. In contrast, Ampatzis et al. [13] presented a continuous double-sided auction to settle energy prices. Ilic et al. [14] presented a stock exchange-based model with discrete fixed time slots.
A shortcoming that may arise from demand response activities in LFM is the risk for faults occurrences. The reason is the generators' operation on a wide output range to increase elasticity. There should be a balance between elasticity and risk, which might lead to an increase of the system cost. It should be further analyzed at the global system level, covering TSO and DSO domains, so as to assess the risks and associated costs of flexibility from demand-side activities in smart grids. N. Paterakis et al. in Chapter 5 of [15] describe the relation between demand response activities and renewables uncertainty. A. Syrri et al. [16] provide a framework for reliability and risk assessment in demand-response activities for capacity procurement at the distribution level, which could be implemented to determine the benefits of demand-response schemes.
Finally, in terms of energy transactions mechanisms, Kahrobaee et al. [17,18] analyzed a local market platform controlled by a central entity that minimizes the operation cost for each household trader. Similarly, Ampatzis et al. [13] presented a distributed market-based control that divides the grid into nodes and uses zero-intelligent automatic agents to maximize the profits for each household. In that case, the market operator is in charge of executing the energy auctions for maximizing total market surplus. Pavlovic et al. [19] presented an LFM model based on auctions without studying the flexibility services from the local market. Torbaghan et al. [20] described a LFM for bidding in the Day-Ahead Market (DAM) and Intraday Markets (IDM) without considering interactions between local market operator and the Transmission System Operator (TSO). In contrast, Mihaylov et al. [21] formulated the NRGcoins as a virtual currency for energy injected into the grid that is traded between prosumers and pure consumers based on blockchain technology. In this approach, the DSO acts as a local market supervision entity.
The main difference between Mihaylov et al. [21] and the LFM proposed in this paper is the regulatory approach. On the one hand, the LFM operator supervises the local trading, aggregating flexible resources and selling flexibility services to third parties. In the case of aggregators being a BRP at the same time, it can access wholesale markets for trading corresponding energy surplus or deficit. However, NRGcoins is a parallel market not related to the retail business. Moreover, NRGcoins uses the DSO as a supervision entity instead of the aggregator as proposed in this LFM approach. Mihaylov's proposal may not fit in the European liberalized regulatory regimes that do not allow DSOs to participate in energy trading-related businesses.
In contrast with the previous peer-to-platform approaches, Kok et al. [22] and Teotia et al. [23] described Peer-to-Peer (P2P) negotiation mechanisms. The main advantage of P2P is to avoid the need for a central entity. However, this approach could result in low negotiation power when selling flexibility services to bigger stakeholders, such as BRPs, DSOs or TSOs. Furthermore, individual market players like prosumers would not have access to wholesale markets depending on their size and national regulations.
The peer-to-platform approach offers some advantages for trading flexibility in contrast to the classic P2P approach. First of all, decisions on local issues are made centrally, and they are supervised by the aggregator. Thus, the aggregator has a complete LEC status overview and can make decisions to benefit the LEC as a group, and not every participant individually. This could be a disadvantage in some specific situations. For example, prosumers with thermal flexibility could be activated frequently, which may result in a significant loss of comfort and causing a drop of user acceptance being a flexibility contributor to the LEC. Nevertheless, prosumer economic rewards should be higher than their opportunity cost, and they can request higher payments. The most beneficial decision should be analyzed case by case.
Regarding flexibility services, Poudineh et al. [5] and [24] analyzed the usage of demand response for DSO services using a centralized platform. In contrast, Kok et al. [22] and Chen et al. [25] described a P2P mechanism to attend to DSO requests. Furthermore, Eid et al. [26] highlight different flexibility market frameworks across Europe, being mostly based on a centralized approach. At the BRP level, Diekerhof et al. [27] proposed a centralized platform system to provide flexibility services to BRP, participating as a market actor within the European Energy Exchange Spot Market. The P2P approach has not been considered yet to provide flexibility services to BRPs, a centralized approach currently being the main application. In [28], flexibility market-based schemes are defined for TSO-DSO coordination. This deliverable is provided by the SmartNet H2020 European Project that is currently being developed. There, two LFM are detailed: a Local Ancillary Services (AS) real-time market, to consider balancing and congestion management services for DSO and TSO. DSO operates the local market to solve distribution grid problems and then aggregates the remaining flexibility offers to TSO markets. The second model is a common TSO-DSO AS market model, which is also based on a real-time dispatching. It is based in a local market operated by the DSO, but satisfying the needs for both TSO and DSO. It is worth noting that only one flexibility customer is being considered on the previous literature references, and so, they do not take into account the grid status when flexibility services are dispatched.
The present paper provides several insights and novelties in terms of flexibility services. Firstly, it is based on a centralized approach for flexibility services providing, with the new market agent, the so-called aggregator. The aggregator manages the flexible loads to provide services to DSO and BRPs, the TSO being out of the scope at the present time. Secondly, to be able to manage these flexible loads, this paper proposes the Traffic Light Concept (TLC) explained below, allowing the coordination between flexibility customers. In the LFM that is being presented, the role of the aggregator and the consideration of the grid status under the TLC concept permit the interaction between more than one flexibility customer and allow one to dispatch flexibility services transparently.
Moreover, the centralized LFM approach requires less computational power per flexibility device because they do not need to install local intelligent devices to make decisions in each flexible asset or house. All flexible assets could be forecasted in the centralized platform, and optimization operation algorithms could take into account uncertainties in a more efficient way than with a distributed approach. Thus, the centralized concept alleviates the burden on each trader, supports pool-oriented flexibility exchanges and provides the aggregator with essential information pertinent to future and past assessments.
The contribution of this paper lies in the design of an LFM operated by an aggregator who manages flexible devices with direct control for providing multiple services in distribution grids with DER to different stakeholders. The aggregator uses an Information and Communication Technology (ICT) trading platform, from now on called the aggregator platform. The design includes a description of objectives, contracts and role details, among other issues.
In this paper, the authors present a selection of the results on local market design and operation that has been developed in the EMPOWER Horizon 2020 project [29] and the initial findings of the Horizon 2020 INVADE project [30].
Section 2 provides a general overview of the local market and delves into the local market concept describing the objectives, roles, contracts, wholesale-local market interactions and their timelines. Section 3 explains the LFM in detail, and Section 4 shows a simulation test case that compares three scenarios. Finally, Section 5 introduces a discussion about the current regulatory barriers, and Section 6 presents the main conclusions of this paper.

Local Market Overview
An LFM is an electricity trading platform to sell and buy flexibility within the LEC. In order to run the LFM, an aggregator provides a trading platform for sharing information, exchanging flexibility and scheduling flexible devices. The aggregator acts as the local market facilitator for the LEC. This implies that the aggregator takes actions to increase local market interactions, in order to ensure enough liquidity.
LFMs are voluntary, and they represent a market-based energy coordination framework. Their main contribution is to monetize the flexibility sold within the community. LFMs enable the P2P flexibility transactions at a certain level. However, the LFM includes an aggregator as a central entity, which supervises the LEC in terms of electricity production and consumption, settlements and contract fulfillment. Therefore, LFM creates a peer-to-platform business model. This is similar to several other network-based markets as described by Parker et al. [31].
Earlier, Ilieva et al. [32] described the Smart Energy Service Provider, the local market structure and relationships and its platform. Helms [33] defined four new business models of flexibility creation based on interviews and industry research. Additionally, the Smart Grid Coordination Group [34] specified the general framework for flexibility markets at a high level. This paper presents the concept of the local flexibility market based on both references. Henceforth, aggregator is the title used in this paper to follow its definition included in the Clean Energy for All Europeans proposal of measures [1].

Concept
In this paper, the authors present multiple geographically-distributed and voluntary LFMs managed by aggregators as a complement to the current wholesale markets. Following our understanding, aggregators could be flexibility managers selling to third parties like BRPs and DSOs. Additionally, aggregators could control end-user flexibility to reduce their electricity bill during periods without third party requests. Therefore, our vision of aggregators includes energy service company functionalities to increase the benefits of using the aggregator platform. Aggregators could be current BRPs or energy retail companies adding new functionalities in their daily business. This paper is mainly focused on the aggregator functionalities, but includes some specificities of BRP being an aggregator at the same time.
As shown in Figure 1, the aggregator supervises local market operations with the aim to maximize profits for its LEC members. The cooperation between LECs and aggregators could increase their negotiation power with BRPs and DSOs. An aggregator can generate new earnings offering flexibility to DSOs, BRPs and prosumers themselves. For example, each LEC connected to the same DSO within the same BRP portfolio could have its own LFM managed by an aggregator. In this case, this aggregator could offer flexibility services from LECs to the BRP and the DSO at the same time. However, our approach is not limited to LECs. An aggregator could manage customers out of LECs, as well. For example, a group of customers under the same DSO could offer services for grid congestion management. Similarly, customers under the same BRP could offer flexibility to reduce deviation penalties, for instance. However, an LEC could have more benefits from the LFM and gain stronger negotiation power than customers individually. This paper explains flexibility services, the roles and responsibilities for local market stakeholders, trading processes, high-level operation algorithms for flexibility activation and the relation between local and wholesale markets. Additionally, the presented framework includes the individual-collective flexibility usage dilemma, which has not been included previously. LECs will face controversial situations when some individuals could profit optimizing individually rather than maximizing community welfare. Under the LFM umbrella, community members can establish internal reward mechanisms to partially compensate adversely-affected members. Finally, the present paper highlights the benefits of the local flexibility market framework to coordinate actions in situations with different flexibility requests at the same time.
The local market proposed in this paper has been designed considering the current European regulatory framework, and hence, some aspects of this design may not be applicable for other regions. However, it is assumed that the energy regulation allows prosumers to sell flexibility, and the regulation provides a clear definition of flexibility at the distribution level. In the European context, up-regulation flexibility at the transmission system level refers to more generation or less consumption and vice versa for down-regulation. For example, Wangensteen [35] in the academic context and the Danish TSO Energinet [36] in the commercial sector follow this criterion. Based on that, the LFM follows the same principle. However, this paper does not include a regulatory review. Additionally, this paper assumes that distribution system operators are allowed to buy flexibility from distributed resources for grid operation purposes.
Finally, this work follows the flexibility and baseline definitions proposed by the the Expert Group 3 (EG3) [34]. An agreed consumption and generation baseline is needed for all involved actors to have a common reference when doing the settlement process. In this framework, the aggregator calculates the baseline, and it is accepted by the DSO and BRP in case there is not a regulated entity for this task. However, the recommendation from the INVADE project for future regulatory proposals is to create a separate and regulated entity to define baselines. This new entity should not have any incentive to over-predict or under-predict the energy assets' performance.

Objectives
The LFM ambition is to develop a local market place to encourage local generation and active participation of prosumers to exploit the flexibility that they can provide, for the benefit of all LEC members and stakeholders. The LFM objectives are listed as follows: 1. Promote the installation of distributed renewable generators.
(a) To create an attractive and competitive trading platform that forges incentives to buy energy from local and renewable resources. (b) To cater to increased investment in distributed renewable resources.
2. Support the trade of end-user flexibility for the benefit of the DSO and its operations.

Flexibility Services
Two sources have been identified as key references to define the flexibility services. One of them is the Universal Smart Energy Framework (USEF) [37,38], which delivers one common standard on which to build an integral market for the trading of flexible energy usage. The second source is the conclusions and advice regarding flexibility implementation from the EG3 about regulatory recommendations for smart grid deployment [34]. They are normally classified as a function of the flexibility customer, namely DSO, BRP and prosumers.

DSO Services
The DSO requests correspond to the amount of flexible resources needed to operate the distribution grid within the safe operation zone. The INVADE project is focused on the following services that the ICT platform can provide to the DSO, and they are:

•
Congestion management: to avoid the thermal overload of system components by reducing peak loads where failure due to overloading may occur.

•
Voltage/reactive power control: to use load flexibility as an option to avoid exceeding the voltage limits.

•
Controlled islanding: to prevent supply interruption in a given grid section when a fault occurs.

BRP Services
Aggregators can help BRPs to balance their portfolio and commitments in wholesale markets. Flexibility sources could be used for managing forthcoming imbalances due different reasons like forecasting errors or for minimizing BRP electricity costs. Flexibility services to BRPs could be: • Day-ahead portfolio optimization: to shift loads from a high-price time interval to a low-price time interval before the day-ahead market closure. It enables the BRP to reduce its overall electricity purchase costs. • Intraday portfolio optimization: to enable value creation on the intraday market, equivalent to the day-ahead market. • Self-balancing portfolio optimization: to reduce imbalance by the BRP within its portfolio to avoid imbalance charges. The BRP does not actively bid on the imbalance market using its load flexibility, but uses it within its own portfolio.

Prosumer Services
Finally, flexible assets behind the meter can be used to minimize prosumer electricity costs. An aggregator can implement some home energy management algorithm in the aggregator platform. Zhou et al. [39] reviewed and compared different algorithms for different applications. USEF listed the following potential flexibility services to prosumers [37]: • Time-of-use (ToU) optimization: to use flexibility from high-price intervals to low-price intervals. • kWmax control: to reduce prosumer consumption peaks within a predefined duration. • Self-balancing: to use the price difference for consuming, producing and selling electricity favorably.

•
Controlled islanding: to maintain electricity supply behind the meter during grid outage situations.

Multiple Service Compatibility
The services offered to BRP, DSO or final customers/prosumers can be requested at the same time, and requests could be contradictory between them. For this reason, it is necessary to classify flexibility requests according to a certain criterion. Our basis is the TLC applied to power systems introduced by the German Association of Energy and Water Industry (BDEW). The BDEW [40] described the need for aggregators to receive certain information about the current grid status and how the TLC can contribute to that.
Following the TLC approach, this paper assumes that grid operators announce if the grid is under threat or not codifying the grid status into three levels: green, amber and red. This information would be used for prioritizing flexibility services.

•
Green state: This is the normal operating state in which the grid does not face threats in the near future. Under the green state, the LFM operates freely. Then, the grid operators may not request flexibility services, and BRP or prosumer services have the highest priority. BRP and prosumer services would compete by price in the LFM.

•
Amber state: This indicates the state where grid operators actively engage with the LFM in order to prevent the grid system from becoming saturated and entering over the red state. Under this state, a grid operator has the highest priority and may request flexibility services. It is a temporary state until the grid operation becomes safe again.

•
Red state: The grid operator needs to take control of LFM interactions in a certain area where a grid constraint has occurred. Under this state, the grid operator can override existing contracts in the LFM and execute dedicated emergency actions through the aggregator in order to re-stabilize the system. Table 1 shows flexibility services possible in each grid state indicated with X, and Figure 2 compares regularity, flexibility services and grid status priority. In red and amber states, the aggregator offers its available flexibility to the DSO to solve or avoid problems in the grid, which should only occur on a few specific occasions. These services have higher priority than other flexibility requests, and consequently, these are supposed to be highly rewarded. The DSO is responsible for the identification of the grid state and necessities to inform aggregators about them. Controlled islanding service at prosumer premises can also be performed in the red state. Table 1. Flexibility services to be offered in each grid state by local energy communities.

DSO
Congestion management X X Voltage/reactive power control X X Controlled islanding X X BRP Day-ahead portfolio optimization X Intraday portfolio optimization X Self-balancing portfolio optimization X X Prosumer ToU optimization X kWmax control X X Self-balancing X X Controlled islanding X In the amber state, surplus flexibility, which is not used to avoid grid problems (DSO services), can be utilized to satisfy some BRP and prosumer services if they help to relieve the grid. For instance, self-balancing BRP portfolio optimization can be used during the amber state if the BRP request is in the same direction as the DSO request. However, day-ahead and intraday optimization services could compromise flexibility sources needed for real-time grid operations. Similarly, kWmax control and prosumer self-balancing could be useful if the DSO need is to reduce energy consumption or production.
On the other hand, flexibility in the green state can be offered to the BRP or to prosumers interchangeably. Here, services to the BRP (portfolio optimization for instance) and to the final customer have to compete for the same available flexibility. Before flexibility is offered to other customers in an aggregated way, a prosumer can use its own flexibility for in-home or building optimization. As a first approach, services to the BRP may be less frequent, but highly rewarded compared to the services to the final customer, which are always present by default if no other flexibility request is in place.

Roles and Responsibilities
The main participants in the LFM are an aggregator, DSOs, BRPs and LEC members (consumers, producers and prosumers). The LEC members in the LFM are attracted from neighborhoods and organized by an aggregator. Participation in the LEC is purely voluntary. In the future, members of the same neighborhood could choose between different LECs. Interactions between LECs are not considered in this paper. The aggregator and the governing body of the community can also decide on certain rules and requirements that must be satisfied before membership can be granted. Figure 3 shows an example of a small LEC with different types of community members, such as households with photovoltaic generators, storage units and demand-response from water heaters and electric vehicles. The LEC could be managed for different purposes like maximizing the renewable energy usage or the economic profitability. This could be decided by the LEC, and the aggregator could offer different optimization approaches. All flexible members with distributed energy resources need to have a local controller. It has to monitor electricity consumption and production of each flexible device. Moreover, the local controller should be capable of receiving control signals from the aggregator platform for each flexible device. As stated before, the local controller does not necessarily include intelligence to make decisions locally.
The LEC members and prosumers in the LFM are responsible for: • Fulfilling the established contracts.

•
Providing the required information about flexible resources.

•
Installing local control devices connected to the aggregator platform.
The various roles of aggregators are listed as follows: • Local market operator: to organize flexibility exchanges and maintain the trading platform.

•
Risk manager: to manage all risks such as energy deviations and technical failures.
Additionally, an aggregator could represent LEC members in wholesale markets in the case of it being a BRP at the same time.
For the reason that the DSO cannot publish grid status transparently for privacy and security reasons, the aggregator is not aware of the grid constraints. Therefore, the LFM could disturb the distribution grid operations in certain situations. To avoid potential dangerous circumstances, the aggregator could communicate and share consumption and generation plans with the DSO during such cases. Section 3.4 digs into the DSO-aggregator interaction timeline. In addition, the LFM offers to the DSO the possibility to interact with the aggregator in the case of flexibility need. These new aggregator functionalities could constitute an update of the DSO and BRP business models.

Aggregator Platform
The aggregator platform must facilitate all processes associated with creating an on-line community of consumers, prosumers and producers. The overall life-cycle process for a community member consists of the following distinct steps: • Recruitment: includes all processes related to attracting users, signing in and profile creation.

•
Commissioning: includes all activities related to introducing equipment technical data into the platform and checking their veracity. • Engagement: includes all the processes related to defining contract prices and renewal processes. Moreover, engagement also involves the member so that they become active LEC members.

•
Exchanges: includes all processes related to verifying and monitoring flexibility trades and exchanges. • Settlement: defines the total amount of flexibility activated and requested. It produces the delivery note to be sent to LFM participants.

Local Flexibility Market
In the LFM, the aggregator controls its members' flexible resources such as loads, generators, EVs and batteries during certain time intervals and rewards them according to their flexibility contract activation prices. Flexibility contracts for loads, EVs and batteries are explained in detail in [41]. The LFM defines flexibility plans according to allocated and reserved flexibility for future needs, respectively.
The goal of the LFM is three-fold: • Complying with DSO requests to prevent grid overloads caused by consumption or generation from community members or others connected to the same grid. Thus, the LFM allows the DSO to prevent grid damages and postpone grid reinforcements. • Compensating BRP deviations due to forecasting errors or other issues to reduce deviation penalties for the BRP in wholesale markets. The aggregator uses the ICT platform to send flexibility control signals to compensate LEC deviations if the deviation penalty is higher than the flexibility costs.

•
Complying with prosumer needs. In the case of no external request, the aggregator can activate flexibility to reduce electricity cost individually.
The following sections describe the LFM in detail.

Contracts
All LFM participants need to have a contract with the aggregator. Nowadays, consumers can have separate or unified contracts with the BRP for consuming and producing electricity depending on the national regulations. Additionally, the LFM adds a new contract for activating flexibility. They settle an activation price for every flexibility asset, and they can include additional constraints like permitted activation periods or the number of flexibility activations per day. These contracts can be renewed periodically every month, week or day depending on participation levels. The aggregator issues all contracts and offers a brokering, clearing and price settlement service.
The LFM contracts are introduced below: • Aggregator-DSO contract: This defines the information shared, message exchanges, actions, timetable, responsibilities of each partner and the rewards for each service provided by the aggregator. The prosumer's contract reservation price stipulates the cost paid by the aggregator for periods during which the aggregator can manage flexibility devices. The activation price stipulates the fee when the aggregator activates demand-response. Contract details could differ case by case.

Flexibility Portfolio Balance
The fundamental guiding principle for aggregator operations in the case of exchanging flexibility with external agents is represented by the function (1) following the goals explained previously: The E ∆ function is the flexibility that the aggregator has to provide, and this function is composed by external requests from agents like DSOs (E REQ,DSO ) and BRPs (E REQ,BRP ). Additionally, the prosumer flexibility need (E REQ,Prosumer ) is considered, as well. In principle, if there is no external flexibility requests, the prosumer need prevails. Moreover, prosumer needs could be more beneficial than the external offers in some specific cases. When external agents request up-regulation, it is defined as positive (E REQ > 0) and negative for down-regulation (E REQ < 0).
Depending on the flexibility regulation direction, simultaneous external requests can be complementary or contradictory. In the case of allowing multiple flexibility services, the aggregator has to follow a certain criterion. The criterion applied in the case study shown below follows the TLC explained before. Therefore, the DSO requests always have higher priority than others in the case of opposite requests.
In the case of contradictory requests, the aggregator should pay a penalty to the BRP for increasing its deviation. However, the DSO economic reward for the flexibility must be higher than the BRP penalty.
In contrast, if the BRP and DSO requests have the same direction, the aggregator applies the biggest request. In the case that the DSO request is bigger than the BRP request and it is in the same direction, there are no penalizations because the BRP will not pay a deviation penalty to the system. This is based on the assumption that the BRP requests make its portfolio deviate in favor of the power system balancing, helping the TSO to keep generation and consumption equilibrated. In that case, the BRP only pays for the energy consumed, but without penalty. That is applicable in most of the European electricity markets at least.
Finally, in the case that the BRP request is higher than the DSO and they are in the same direction, the aggregator applies the BRP request as it does not cause trouble for the DSO. Nevertheless, the DSO only pays for the amount requested, not for the activated flexibility.
The E ∆ function can be decomposed into the following flexibility providers: where E STO (t) is the flexibility available from storage units for charged energy (E STO (t) > 0) and discharged energy (E STO (t) < 0), E FL (t) is the flexibility available from loads for up-regulation (E FL (t) < 0) and down-regulation (E FL (t) > 0) including EV and E FG (t) is the flexibility available from generators for up-regulation (E FG (t) < 0) and down-regulation (E FG (t) > 0).

Local and Wholesale Markets' Interaction
The LFM could interact with wholesale markets depending on the implemented services. BRP services could provide flexibility to reduce electricity costs while DAM and IDM are open. Additionally, aggregators could provide additional benefits trading in balancing markets. Figure 4 shows the parallelism between local and wholesale markets. Flexibility markets are limited to short-term wholesale markets for simplicity. The potential value of distributed flexibility in capacity markets is out of the scope.

LFM Timeline
The actions executed in the LFM are represented in Figure 5 as an example. It is divided in two main parts: operations needed to schedule flexible resources and the flexibility settlement process. It contains the case where the BRP and the DSO can request flexibility at the same time. For simplicity, the flexible resource represented in this figure is a single battery, but it applies to a portfolio of different flexible assets. Scheduling tasks can happen days, hours or minutes ahead of the final delivery.
This figure is open to be adapted to different cases. The action sequence of LFM is listed as follows: First of all, it is necessary to carry out the operation process a certain time ahead of the actual energy delivery or consumption, and it is as follows: • The DSO receives grid metered values from its SCADA or similar systems. This information is used by a grid congestion detection algorithm to quantify the flexibility to requests in the forthcoming periods. If it is needed, it sends a flexibility request (Flex. request) to the aggregator.

•
Similarly, the BRP receives the portfolio forecasts and estimates the future unbalances using an internal algorithm. If it is needed, it sends a flexibility request number i to the aggregator.

•
The aggregator receives all flexibility requests and establishes a prioritization according to the grid status. This includes the compatibility of multiple requests for the same period. If there is no flexibility requests, the LFM algorithm will optimize for the individual benefit of every LEC member.
• Before scheduling flexibility, the aggregator checks the availability of every flexible asset like the battery unit b using the local controller.

•
Once the aggregator knows the available flexible assets, it schedules them to meet the external requests, and it produces the flexibility plan (Flex. plan) containing all management signals for the request i to be sent later on.
Once the operation management signals have been applied, the settlement process audits what happened during every period. This process certifies that the flexibility has been activated. For example, it checks the metered values at the flexible device level. The settlement process is as follows: • The aggregator platform receives metered values about flexibility activated during request i from local controllers.

•
The aggregator calculates flexibility activated during operation.

•
The aggregator settles contracts with the BRP, the DSO and flexible assets according to flexibility contracts.

•
The aggregator sends delivery notes and bills to the BRP and the DSO with the effective flexibility activated.

LFM Algorithm
The flexibility plan is the LFM optimization problem of scheduling flexible resources. The aggregator executes this process sequentially during the operation day in order to adjust the baseline with new foresight and requirements as explained in Section 3.4. Time resolution could be 5, 15 or 30 min, depending on the case. The optimization problem could include temporal constraints from batteries, EVs and space heaters such as the battery state of charge or building thermal inertia. Therefore, the planning horizon could be the entire operation day or even two days in advance. However, multiple LFM operation algorithms can be designed depending on flexibility services and requests. In this algorithm, end-users settle a price in their flexibility contract for activating demand response. This work does not focus on all possible LFM optimization approaches as it does not affect the general LFM design.
The LFM algorithm is an optimization problem that minimizes cost involved in scheduling flexibility devices to meet required flexibility. It can be formulated in two different approaches. The first approach could formulate the objective function as a maximization welfare function, and the flexibility auction could be a single-side auction between flexibility providers and the aggregator requesting flexibility. Figure 6 shows an example of a flexibility auction for a single period. In this example case, the DSO requested a consumption curtailment and presented a bid accordingly. Moreover, different offers from flexible assets for up-regulation are sent and included in the auction.
The corresponding offer curve is generated according to their activation fees if they are reserved during this period, and also considering their available estimated power curtailment capacity. The offer curve is sorted in ascending order to prioritize the least expensive offer instead of the most expensive one. The flexibility offer curve is composed of different EV disconnection offers from different EVs at the same price. Later on, a group of Electric Water Heaters (EWH) is included as up-regulation sources. They are aggregated at two price levels according to their flexibility contracts. Finally, a group of batteries offers their up-regulation capability at the highest price. In this case, all EV, all EWH and some batteries are used to fulfil the DSO request. The auction approach is transparent in order to clearly show which flexible devices are the least expensive for every period. However, it could present difficulties in being implemented. For instance, the offer formulation from every flexibility contract of EVs and batteries could be too complex to generate automatically because their flexibility capacity is linked to their state-of-charge.
In contrast with the auction formulation, the problem can be formulated as a multi-period minimization cost objective function for an aggregator allocating the least expensive flexibility offers. This approach facilitates the inclusion battery and EV time-based constraints, and the information from flexibility contracts can be easily included in the objective function. For instance, Olivella-Rosell et al. [41] formulated the first LFM algorithm for meeting DSO requests at minimum aggregator cost as a multi-period optimization problem, and it has been implemented in the EMPOWER H2020 project [29]. Figure 7 shows the algorithm high-level flow diagram, the general inputs and outputs together with the potential required functionalities. The first step is to forecast the energy consumed and produced in the aggregator portfolio. This is done using historic consumption and weather data, among others. This forecast must distinguish between flexible and inflexible resources. Additionally, it is necessary to estimate the status of flexible assets considering their physical and contractual constraints. All this information is introduced in the optimization problem, and it returns the flexibility plan explained before. This process can be repeated every time there is a new event in the forecasting system or an external agent creates a new flexibility request.

Simulation Test Case
The following simulation test case aims to show the application of the LFM under different situations. In this case, the aggregator provides flexibility services to the DSO for congestion management and to the BRP for self-balancing portfolio optimization. The case study and all input parameters to the optimization problem are the same as in [41]. Figure 8 shows the flexibility requests applied to the same case study and they constitute three comparative scenarios:  Applying the optimization problem presented in [41] in the same case study to the previous flexibility requests, Figure 9 shows how the loads, batteries and generators contribute to fulfil the requirement. Disconnectable loads contribute to up-regulation during the evenings; generators can be disconnected during mid-day to provide down-regulation; and batteries and shiftable loads can contribute in both directions.
All scenarios could be profitable for the aggregator depending on the flexibility contracts and the DSO and BRP flexibility fees. The analysis of the aggregator profitability is out of the scope and could depend on the case study.

Discussion
In the context of massive distributed energy sources' installation, especially photovoltaic panels on rooftops, electric vehicles and distributed batteries, coordination mechanisms are needed. Additionally, intermittent renewable generation requests flexibility mechanisms to secure operation of the power system.
The local flexibility market proposed in this work has important implications for energy policy and regulation. First of all, aggregators should have new consumption and generation data every quarter-hour or hour to favor local flexibility markets deployment. Another policy implication is about the conflict resolution between DSOs and aggregators when the flexibility requested by the DSO is not enough to prevent a grid outage. This could be due to a flexibility deficit requested by the DSO or a lack of flexibility provided by the aggregator. In order to resolve their dispute, the regulatory energy agency should be capable of auditing flexibility requests and activations to clarify who was responsible for the damage. Therefore, standard communication protocols are needed to supervise DSO-aggregator interactions. Thus, flexibility penalties included in DSO-aggregator contracts could be easily settled. Additionally, this implies a common understanding about the way to measure flexibility activations, which is not standardized nowadays.
Moreover, future local flexibility market implementations could attract multiple aggregators competing to provide flexibility to the same DSO. The DSO would then get an additional role as a market provider enabling competition for flexibility in a similar manner to current tertiary reserve markets. This new DSO role should be analyzed carefully and included in the DSO regulated activities jointly with the grid operator role.
Finally, TSOs could be flexibility buyers, as well, including demand response from aggregators as an asset for tertiary markets. In that situation, the aggregator could become an agent that offers flexibility to the TSO. In the case of activation, the aggregator should use the LFM as a market-based mechanism to allocate flexibility devices and meet the TSO request. However, this paper is focused in the distribution network domain.

Conclusions
The present work proposes a market-based framework to manage multiple flexibility services. This framework is the LFM, and it is a platform-based mechanism to clearly distinguish priorities in smart grid-dominated scenarios with an aggregating central entity. This framework is an implementation case of the USEF standard including prosumer services. The novelty of this LFM remains in the individual-collective flexibility usage and the provision of multiple services to prosumers, DSOs and BRPs simultaneously.
This framework has been introduced by the EMPOWER H2020 project [29], and the DSO services have been partially and successfully tested. This project was mainly focused on the technical viability demonstration in the local market. INVADE H2020 [30] aims to implement BRP and prosumer services in real test-pilots, to improve DSO services and estimate stakeholders' economic viability for flexibility. This paper elaborates on the principles of LFMs for multiple flexibility buyers. It is focused on defining services, contracts, market timelines and operation algorithms. The proposed trading platform is generally designed to be scalable, adaptable and customizable in order to suit the diverse conditions and regulations.
The paper delves into the intricacies of operating a local flexibility market in conjunction with wholesale markets and stipulates the rules for planning and operating the LFM. In particular, the interactions between DSO-BRP-aggregator-LEC-prosumer have been outlined and described. The trading model applies to multiple facets of flexibility-related trade, and this paper has studied most of the associated technical aspects including optimization issues required for the aggregator operations and a simulation of a case study.
To conclude, multiple questions remain open such as the minimum viable LFM size. The LFM needs enough liquidity to ensure a certain competition level to attract new LEC members. Another question is the local market economic profitability for all involved stakeholders. Both questions could depend on each case. Nevertheless, future studies should analyze reference scenarios and regulatory regimes to demonstrate local market viability.