---
updatedAt: 2025-11-05T21:23:16.000Z
agentTools:
  projectIndex: https://developers.modoenergy.com/llms.txt
---

# Calculating EPEX buy/sell curves

```python Python
# Import dependencies
import datetime
import requests
from typing import Optional

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots


def pull_modo_api(url: str, modo_api_key: str, params: Optional[dict] = None) -> pd.DataFrame:
    df = pd.DataFrame()
    headers = {"X-Token": modo_api_key}
    while url is not None:
        response = requests.get(url, headers=headers, params=params)
        if response.status_code != 200:
            raise ConnectionError(f"{response.status_code}: {response.reason}")
        df = pd.concat([df, pd.DataFrame(response.json()["results"])])
        url = response.json()["next"]
    return df
  

# Gather order book data
modo_api_key = <YOUR-MODO-API-KEY>
date_from = datetime.datetime(2024, 5, 9, 9)
date_to = datetime.datetime(2024, 5, 9, 9, 29)

order_book_url = "https://api.modoenergy.com/pub/v1/gb/epex/intra-day/order-book"
date_params = {
    "date_from": date_from,
    "date_to": date_to,
}
order_book = pull_modo_api(
    url=order_book_url,
    modo_api_key=modo_api_key,
    params=date_params,
)

# Filter for the order book of choice
order_book["name"].unique()
order_book = order_book[order_book["name"] == "HH240509-21"]

# Convert datetime types
for field in ["dlvryEnd", "dlvryStart", "orderEntryTime", "orderUpdateTime"]:
    order_book[field] = pd.to_datetime(order_book[field], utc=True)

# Filter for the original orders placed
order_book.sort_values(by="orderUpdateTime", ascending=True, inplace=True)
first_orders = order_book.groupby(["orderId"]).first()

# Calculate buy/sell curves
sell_orders = first_orders[first_orders["orderType"] == "sell"].sort_values("price")
buy_orders = first_orders[first_orders["orderType"] == "buy"].sort_values("price", ascending=False)
sell_orders["cumulative_volume"] = sell_orders["volumeMW"].cumsum()
buy_orders["cumulative_volume"] = buy_orders["volumeMW"].cumsum()

# Filter for outliers
sell_orders["price"].describe([.01, .99])   # Check this out for yourself in your terminal
sell_orders = sell_orders[sell_orders["price"] <= 75]
buy_orders["price"].describe([.01, .99])   # Check this out for yourself in your terminal
buy_orders = buy_orders[buy_orders["price"] >= 43]

# Pull trades for this order book
buy_orders["orderEntryTime"].min()   # Check this out for yourself in your terminal
sell_orders["orderEntryTime"].min()   # Check this out for yourself in your terminal

trades_url = "https://api.modoenergy.com/pub/v1/gb/epex/intra-day/detailed-trades"
trade_params = {
    "date_from": datetime.datetime(2024, 5, 9, 5),
    "date_to": datetime.datetime(2024, 5, 9, 9),
}
trades = pull_modo_api(
    url=trades_url,
    modo_api_key=modo_api_key,
    params=trade_params,
)
trades = trades[trades["name"] == "HH240509-21"]
for field in ["dlvryEnd", "dlvryStart", "tradeExecTime"]:
    trades[field] = pd.to_datetime(trades[field], utc=True)

trades_url = "https://api.modoenergy.com/pub/v1/gb/epex/intra-day/detailed-trades"
trade_params = {
    "date_from": datetime.datetime(2024, 5, 9, 5),
    "date_to": datetime.datetime(2024, 5, 9, 9),
}
trades = pull_modo_api(
    url=trades_url,
    modo_api_key=modo_api_key,
    params=trade_params,
)
trades = trades[trades["name"] == "HH240509-21"]
for field in ["dlvryEnd", "dlvryStart", "tradeExecTime"]:
    trades[field] = pd.to_datetime(trades[field], utc=True)

# Plot results
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
    go.Histogram(
        x=trades["price"],
        y=trades["volumeMW"],
        name="Trades",
        marker=dict(color="#00CC96"),
    )
)
fig.add_trace(
    go.Scatter(
        x=buy_orders["price"],
        y=buy_orders["cumulative_volume"],
        line_shape="hv",
        name="Buy",
        marker=dict(color="#EF553B"),
    ),
    secondary_y=True,
)
fig.add_trace(
    go.Scatter(
        x=sell_orders["price"],
        y=sell_orders["cumulative_volume"],
        line_shape="hv",
        name="Sell",
        marker=dict(color="#636EFA"),
    ),
    secondary_y=True,
)
fig.add_vline(x=57.17, annotation_text="RPD HH")
fig['layout']['yaxis2']['showgrid'] = False
fig.update_yaxes(rangemode='tozero')
fig.update_layout(
    title="EPEX Continuous Order Book: HH240509-21",
    xaxis_title="Price GBP/MWh",
    yaxis_title="Trade volume MW",
    yaxis2_title="Buy/sell volume MW"
)
fig.show()
```

# Import dependencies

<!-- python@1-20 -->

Import the required dependencies and create a function to call the Modo API. You can reuse this API call
function wherever you like, and it neatly handles pagination and error codes.

# Gather order book data

<!-- python@23-37 -->

Call the EPEX order book endpoint using the function we just created.
The order book endpoint has two required paramaters: date_from and date_to.
These filter on the `dlvryStart` field of the order book dataset. 
In this example, I want to return the order books for trading products which deliver energy between 10am and 10:30am UK time on the 9th May 2024. Note that all the timestamps in this dataset are in UTC, and I've set date_to as 09:29am, as date_to filters as less than or equal to.

# Filter for the order book of choice

<!-- python@39-41 -->

You can see that this API call returns two different products, an hourly and a half-hourly product.
For this example I am interested in the half-hour product, so I will filter for HH240509-21.

# Convert datetime types

<!-- python@43-45 -->

As always, the API returns datetimes as strings, so I need to convert these to datetime objects

# Filter for the original orders placed

<!-- python@47-49 -->

The order book endpoint contains every update to the order book. This means that whenever an order is updated, either because a trade is executed or the order owner changes the price/volume, or cancels the order, a new entry is added to the database. This is super useful if you want to time travel through the order book, but for our analysis we want to know the total depth of the market.
Therefore, here we filter the dataset to keep only the first entry of every order.

# Calculate buy/sell curves

<!-- python@51-55 -->

For this graph I want to plot the cumulative MW volume of buy/sell orders at each price point. These will be the buy and sell curves on our final plot.

# Filter for outliers

<!-- python@57-61 -->

Let's look at the prices that orders were placed at. You can see that there was a sell order placed at 5,442 GBP/MWh. This is probably a trader error, or someone is really trying their luck! We'll filter out sell orders priced above the 99th percentile, which we can see is a much more reasonable 75 GBP/MWh.

There's also an extreme buy order at 6 GBP/MWh, so we'll filter that out as well at the 1st percentile of a more reasonable 43 GBP/MWh

# Pull trades for this order book

<!-- python@63-94 -->

Lastly, it'll be useful to overlay our buy and sell order curves on the distribution of executed trades. For this we'll need to pull from our detailed trades endpoint. This endpoint filters on the trade execution time. By looking at the first orderEntryTime for buy and sell orders, we can see that no trades for this product occurred before 5am, so we will use this as the start time for our API call. 
This will return trades for all products during this period though, so we'll need to filter using the product name we used to filter the order book.

# Plot results

<!-- python@96-135 -->

Now we can make a super useful plot to explore market depth of this particular half-hour product. I'm going to use plotly.graph_objects but you can use whichever plotting library you prefer.
From this chart you can see that there was a total of 30 GW of sell orders placed, and 40 GW of buy orders.
I also know (from our RPD HH endpoint) that RPD for this period was 57.17 GBP/MWh, so I'll plot that as well.