Skip to main content

flexpool_plan/
orders.rs

1//! Limit orders from the schedule and the water value, and their paper execution.
2
3use flexpool_core::{Granularity, quantize};
4use rust_decimal::Decimal;
5use rust_decimal::prelude::ToPrimitive;
6use serde::Serialize;
7use time::OffsetDateTime;
8
9use crate::PlanError;
10use crate::lp::{SOC_MAX, SOC_MIN, Schedule, Storage};
11
12/// Buy or sell.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
14#[serde(rename_all = "lowercase")]
15pub enum Side {
16    /// Charge: buy at or below the limit.
17    Buy,
18    /// Discharge: sell at or above the limit.
19    Sell,
20}
21
22/// One day-ahead limit order.
23#[derive(Debug, Clone, PartialEq, Serialize)]
24pub struct Order {
25    /// Market time unit start (UTC).
26    #[serde(with = "time::serde::rfc3339")]
27    pub start: OffsetDateTime,
28    /// Buy or sell.
29    pub side: Side,
30    /// Volume, MW, on the volume granularity (toward zero).
31    #[serde(with = "rust_decimal::serde::str")]
32    pub mw: Decimal,
33    /// Protective limit price, €/MWh, on the price granularity, within the price limits.
34    #[serde(with = "rust_decimal::serde::str")]
35    pub limit: Decimal,
36    /// The expected price at this unit, €/MWh.
37    pub expected_price: f64,
38    /// The water value the limit comes from, €/MWh.
39    pub water_value: f64,
40}
41
42/// What the market rules say about orders on the day.
43#[derive(Debug, Clone, Copy)]
44pub struct Market {
45    /// Volume granularity.
46    pub volume: Granularity,
47    /// Price granularity.
48    pub price: Granularity,
49    /// Lowest price, €/MWh.
50    pub lo: f64,
51    /// Highest price, €/MWh.
52    pub hi: f64,
53}
54
55impl Market {
56    /// The day-ahead order rules in force on `day`.
57    ///
58    /// # Errors
59    /// [`PlanError::Rules`] naming the missing rule.
60    pub fn from_rules(
61        rules: &flexpool_rules::RuleBook,
62        day: time::Date,
63    ) -> Result<Self, PlanError> {
64        let missing = |e: flexpool_rules::Missing| PlanError::Rules(e.to_string());
65        let (lo, hi, _) = rules.da_price_limits(day).map_err(missing)?;
66        Ok(Self {
67            volume: rules
68                .granularity("da.volume-granularity", day)
69                .map_err(missing)?
70                .0,
71            price: rules
72                .granularity("da.price-granularity", day)
73                .map_err(missing)?
74                .0,
75            lo: lo.value().to_f64().unwrap_or(-500.0),
76            hi: hi.value().to_f64().unwrap_or(4000.0),
77        })
78    }
79}
80
81/// One limit order per unit with a net flow, for the net volume, with protective limits: a sell
82/// at or above the lowest scenario price, a buy at or below the highest. Each order carries the
83/// expected price and the water value that explain it.
84///
85/// # Errors
86/// [`PlanError::Limits`] if a number cannot be quantised (a solver failure).
87pub fn orders(
88    schedule: &Schedule,
89    starts: &[OffsetDateTime],
90    expected: &[f64],
91    band: &[(f64, f64)],
92    market: &Market,
93) -> Result<Vec<Order>, PlanError> {
94    let q = |v: f64, g: Granularity| {
95        quantize(v, g)
96            .map(|x| x.value)
97            .map_err(|e| PlanError::Limits(e.to_string()))
98    };
99    let mut out = Vec::new();
100    for (t, start) in starts.iter().enumerate() {
101        let net = schedule.discharge[t] - schedule.charge[t];
102        let w = schedule.water_value[t];
103        // Protective limits: sell at any price a scenario considered possible, buy up to the highest.
104        // Water-value limits sit near the expected price, so a day a little below forecast fills the
105        // buys and misses the sells; the 14-day backtest captured 41–45 % with them, 94 % with these.
106        let (side, limit) = if net > 0.0 {
107            (Side::Sell, band[t].0)
108        } else {
109            (Side::Buy, band[t].1)
110        };
111        let mw = q(net.abs(), market.volume)?;
112        if mw.is_zero() {
113            continue;
114        }
115        out.push(Order {
116            start: *start,
117            side,
118            mw,
119            limit: q(limit.clamp(market.lo, market.hi), market.price)?,
120            expected_price: expected[t],
121            water_value: w,
122        });
123    }
124    Ok(out)
125}
126
127/// An order after the auction.
128#[derive(Debug, Clone, PartialEq, Serialize)]
129pub struct Fill {
130    /// Market time unit start (UTC).
131    #[serde(with = "time::serde::rfc3339")]
132    pub start: OffsetDateTime,
133    /// Whether the price met the limit.
134    pub filled: bool,
135    /// MW delivered (less than ordered only where the storage was empty or full).
136    pub mw: f64,
137    /// The published price, €/MWh.
138    pub price: f64,
139}
140
141/// Paper execution of `orders` against published `prices` (one per unit starting at `starts`):
142/// a sell fills at a price at or above its limit, a buy at or below; the storage's window holds.
143/// Returns the fills and the revenue, €.
144#[must_use]
145pub fn execute(
146    orders: &[Order],
147    starts: &[OffsetDateTime],
148    prices: &[f64],
149    storage: &Storage,
150    hours: f64,
151) -> (Vec<Fill>, f64) {
152    let (lo, hi) = (SOC_MIN * storage.energy_mwh, SOC_MAX * storage.energy_mwh);
153    let mut level = storage.start_mwh();
154    let mut revenue = 0.0;
155    let mut fills = Vec::with_capacity(orders.len());
156    for (t, start) in starts.iter().enumerate() {
157        let Some(order) = orders.iter().find(|o| o.start == *start) else {
158            continue;
159        };
160        let price = prices[t];
161        let limit = order.limit.to_f64().unwrap_or(0.0);
162        let mw = order.mw.to_f64().unwrap_or(0.0);
163        let (filled, delivered) = match order.side {
164            Side::Sell if price >= limit => {
165                let room = ((level - lo) * storage.eta_discharge() / hours).max(0.0);
166                let mw = mw.min(room);
167                level -= mw * hours / storage.eta_discharge();
168                revenue += (price - storage.cycle_cost) * mw * hours;
169                (true, mw)
170            }
171            Side::Buy if price <= limit => {
172                let room = ((hi - level) / (storage.eta_charge() * hours)).max(0.0);
173                let mw = mw.min(room);
174                level += mw * hours * storage.eta_charge();
175                revenue -= price * mw * hours;
176                (true, mw)
177            }
178            _ => (false, 0.0),
179        };
180        fills.push(Fill {
181            start: *start,
182            filled,
183            mw: delivered,
184            price,
185        });
186    }
187    // Energy above (or below) the start is worth the day's mean price: the next day can sell (or
188    // must buy) it.
189    #[expect(clippy::cast_precision_loss, reason = "at most 100 units")]
190    let mean = prices.iter().sum::<f64>() / prices.len().max(1) as f64;
191    revenue += (level - storage.start_mwh()) * mean;
192    (fills, revenue)
193}