flexpool-plan 0.2.0

flexpool day-ahead planning: price scenarios from forecast quantiles, a storage LP with a CVaR term, water values from the duals, limit orders and their paper execution. No I/O.
Documentation
//! Limit orders from the schedule and the water value, and their paper execution.

use flexpool_core::{Granularity, quantize};
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::Serialize;
use time::OffsetDateTime;

use crate::PlanError;
use crate::lp::{SOC_MAX, SOC_MIN, Schedule, Storage};

/// Buy or sell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Side {
    /// Charge: buy at or below the limit.
    Buy,
    /// Discharge: sell at or above the limit.
    Sell,
}

/// One day-ahead limit order.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Order {
    /// Market time unit start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub start: OffsetDateTime,
    /// Buy or sell.
    pub side: Side,
    /// Volume, MW, on the volume granularity (toward zero).
    #[serde(with = "rust_decimal::serde::str")]
    pub mw: Decimal,
    /// Protective limit price, €/MWh, on the price granularity, within the price limits.
    #[serde(with = "rust_decimal::serde::str")]
    pub limit: Decimal,
    /// The expected price at this unit, €/MWh.
    pub expected_price: f64,
    /// The water value the limit comes from, €/MWh.
    pub water_value: f64,
}

/// What the market rules say about orders on the day.
#[derive(Debug, Clone, Copy)]
pub struct Market {
    /// Volume granularity.
    pub volume: Granularity,
    /// Price granularity.
    pub price: Granularity,
    /// Lowest price, €/MWh.
    pub lo: f64,
    /// Highest price, €/MWh.
    pub hi: f64,
}

impl Market {
    /// The day-ahead order rules in force on `day`.
    ///
    /// # Errors
    /// [`PlanError::Rules`] naming the missing rule.
    pub fn from_rules(
        rules: &flexpool_rules::RuleBook,
        day: time::Date,
    ) -> Result<Self, PlanError> {
        let missing = |e: flexpool_rules::Missing| PlanError::Rules(e.to_string());
        let (lo, hi, _) = rules.da_price_limits(day).map_err(missing)?;
        Ok(Self {
            volume: rules
                .granularity("da.volume-granularity", day)
                .map_err(missing)?
                .0,
            price: rules
                .granularity("da.price-granularity", day)
                .map_err(missing)?
                .0,
            lo: lo.value().to_f64().unwrap_or(-500.0),
            hi: hi.value().to_f64().unwrap_or(4000.0),
        })
    }
}

/// One limit order per unit with a net flow, for the net volume, with protective limits: a sell
/// at or above the lowest scenario price, a buy at or below the highest. Each order carries the
/// expected price and the water value that explain it.
///
/// # Errors
/// [`PlanError::Limits`] if a number cannot be quantised (a solver failure).
pub fn orders(
    schedule: &Schedule,
    starts: &[OffsetDateTime],
    expected: &[f64],
    band: &[(f64, f64)],
    market: &Market,
) -> Result<Vec<Order>, PlanError> {
    let q = |v: f64, g: Granularity| {
        quantize(v, g)
            .map(|x| x.value)
            .map_err(|e| PlanError::Limits(e.to_string()))
    };
    let mut out = Vec::new();
    for (t, start) in starts.iter().enumerate() {
        let net = schedule.discharge[t] - schedule.charge[t];
        let w = schedule.water_value[t];
        // Protective limits: sell at any price a scenario considered possible, buy up to the highest.
        // Water-value limits sit near the expected price, so a day a little below forecast fills the
        // buys and misses the sells; the 14-day backtest captured 41–45 % with them, 94 % with these.
        let (side, limit) = if net > 0.0 {
            (Side::Sell, band[t].0)
        } else {
            (Side::Buy, band[t].1)
        };
        let mw = q(net.abs(), market.volume)?;
        if mw.is_zero() {
            continue;
        }
        out.push(Order {
            start: *start,
            side,
            mw,
            limit: q(limit.clamp(market.lo, market.hi), market.price)?,
            expected_price: expected[t],
            water_value: w,
        });
    }
    Ok(out)
}

/// An order after the auction.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Fill {
    /// Market time unit start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub start: OffsetDateTime,
    /// Whether the price met the limit.
    pub filled: bool,
    /// MW delivered (less than ordered only where the storage was empty or full).
    pub mw: f64,
    /// The published price, €/MWh.
    pub price: f64,
}

/// Paper execution of `orders` against published `prices` (one per unit starting at `starts`):
/// a sell fills at a price at or above its limit, a buy at or below; the storage's window holds.
/// Returns the fills and the revenue, €.
#[must_use]
pub fn execute(
    orders: &[Order],
    starts: &[OffsetDateTime],
    prices: &[f64],
    storage: &Storage,
    hours: f64,
) -> (Vec<Fill>, f64) {
    let (lo, hi) = (SOC_MIN * storage.energy_mwh, SOC_MAX * storage.energy_mwh);
    let mut level = storage.start_mwh();
    let mut revenue = 0.0;
    let mut fills = Vec::with_capacity(orders.len());
    for (t, start) in starts.iter().enumerate() {
        let Some(order) = orders.iter().find(|o| o.start == *start) else {
            continue;
        };
        let price = prices[t];
        let limit = order.limit.to_f64().unwrap_or(0.0);
        let mw = order.mw.to_f64().unwrap_or(0.0);
        let (filled, delivered) = match order.side {
            Side::Sell if price >= limit => {
                let room = ((level - lo) * storage.eta_discharge() / hours).max(0.0);
                let mw = mw.min(room);
                level -= mw * hours / storage.eta_discharge();
                revenue += (price - storage.cycle_cost) * mw * hours;
                (true, mw)
            }
            Side::Buy if price <= limit => {
                let room = ((hi - level) / (storage.eta_charge() * hours)).max(0.0);
                let mw = mw.min(room);
                level += mw * hours * storage.eta_charge();
                revenue -= price * mw * hours;
                (true, mw)
            }
            _ => (false, 0.0),
        };
        fills.push(Fill {
            start: *start,
            filled,
            mw: delivered,
            price,
        });
    }
    // Energy above (or below) the start is worth the day's mean price: the next day can sell (or
    // must buy) it.
    #[expect(clippy::cast_precision_loss, reason = "at most 100 units")]
    let mean = prices.iter().sum::<f64>() / prices.len().max(1) as f64;
    revenue += (level - storage.start_mwh()) * mean;
    (fills, revenue)
}