entsoe-edi 0.49.0

ENTSO-E ESS 2.3 schedule documents for German intra-area electricity trades
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use std::collections::{HashMap, HashSet};
use std::fmt::Write;

use jiff::tz::{self, TimeZone};
use thiserror::Error;
use time::{Date, OffsetDateTime, UtcOffset, macros::format_description};

use crate::{BilanzierungsgebietId, BilanzkreisId, EicCode, ScheduleQuantity};

/// One German ESS 2.3 schedule for trades inside a single control area (A02).
#[derive(Clone, Debug)]
pub struct ScheduleMessage {
    /// Sender-assigned ID shared by revisions of this schedule.
    pub id: String,
    /// Message revision, from 1 through 999.
    pub revision: u16,
    /// Nominating Bilanzkreis.
    pub sender: BilanzkreisId,
    /// Receiving ÜNB's party EIC (10X).
    pub receiver: EicCode,
    /// Receiving ÜNB's control-area EIC (10Y).
    pub area: BilanzierungsgebietId,
    /// Delivery day in Europe/Berlin.
    pub day: Date,
    /// Preparation instant, emitted in UTC to whole seconds.
    pub created_at: OffsetDateTime,
    /// All directional trades for this nomination in wire order.
    pub series: Vec<TradeSeries>,
}

/// Netted physical delivery from one Bilanzkreis to another within the same area.
#[derive(Clone, Debug)]
pub struct TradeSeries {
    /// Sender-assigned time series ID.
    pub id: String,
    /// Message revision in which the series last changed.
    pub revision: u16,
    /// Source Bilanzkreis, the ESS OutParty.
    pub delivering: BilanzkreisId,
    /// Destination Bilanzkreis, the ESS InParty.
    pub receiving: BilanzkreisId,
    /// Consecutive quarter-hours starting at Berlin midnight, in elapsed time order.
    pub quantities: Vec<ScheduleQuantity>,
}

/// Reason a nomination cannot be encoded as a German ESS 2.3 schedule.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ScheduleError {
    /// The shortest exact MW representation is wider than the wire field.
    #[error("{0} kW exceeds the ESS quantity field width")]
    QuantityTooLong(u64),
    /// Message or series ID violates the ESS alphanumeric grammar.
    #[error("{0} must contain 1 to 35 ASCII letters or digits")]
    InvalidId(&'static str),
    /// Revision lies outside the permitted range.
    #[error("{field} must be between 1 and {maximum}, got {value}")]
    InvalidRevision {
        /// Offending field.
        field: &'static str,
        /// Highest allowed value.
        maximum: u16,
        /// Supplied revision.
        value: u16,
    },
    /// The EIC supplied for a control area or recipient belongs to the wrong class.
    #[error("{0}")]
    InvalidRecipient(&'static str),
    /// The XML time format cannot represent an instant or day boundary.
    #[error("{0} cannot be represented in the ESS UTC format")]
    InvalidTime(&'static str),
    /// The interval falls outside the contiguous years qualified against the ESS core schema.
    #[error("the delivery interval must start in UTC year 2000 through 2099")]
    DayOutsideSchemaRange,
    /// An A02 trade nomination requires at least one series.
    #[error("the nomination needs at least one trade series")]
    EmptySchedule,
    /// The series ID appears more than once in the document.
    #[error("duplicate series ID {0}")]
    DuplicateId(String),
    /// A series must connect the sender and a distinct Bilanzkreis.
    #[error("series {0} must connect the sender and a different Bilanzkreis")]
    InvalidParties(String),
    /// Two series describe the same directional flow.
    #[error("series {0} repeats a directional trade")]
    DuplicateTrade(String),
    /// Series coverage differs from the length of the delivery day.
    #[error("series {id} needs {expected} quarter-hours, got {actual}")]
    IntervalCount {
        /// Sender-assigned series ID.
        id: String,
        /// Length of the Berlin delivery day in quarter-hours.
        expected: usize,
        /// Number of supplied quantities.
        actual: usize,
    },
    /// A quarter-hour contains delivery in both directions for a pair.
    #[error("series {id} and its reverse both deliver at position {position}")]
    OverlappingFlows {
        /// Series ID of the second direction.
        id: String,
        /// One-based quarter-hour position.
        position: usize,
    },
}

/// UTC boundaries of a Berlin delivery day whose UTC start year is 2000–2099, with an exclusive end.
#[must_use = "the delivery day must have representable ESS boundaries"]
pub fn delivery_window(day: Date) -> Result<std::ops::Range<OffsetDateTime>, ScheduleError> {
    static BERLIN: TimeZone = tz::get!("Europe/Berlin");
    let invalid = || ScheduleError::InvalidTime("delivery day");
    let midnight = |date: Date| {
        let year = date.year().try_into().map_err(|_| invalid())?;
        let local = jiff::civil::Date::new(year, date.month() as i8, date.day() as i8)
            .map_err(|_| invalid())?;
        let time = BERLIN
            .to_ambiguous_timestamp(local.at(0, 0, 0, 0))
            .unambiguous()
            .map_err(|_| invalid())?;
        let utc = OffsetDateTime::from_unix_timestamp(time.as_second()).map_err(|_| invalid())?;
        if !(1..=9999).contains(&utc.year()) || utc.second() != 0 {
            return Err(invalid());
        }
        Ok(utc)
    };
    let start = midnight(day)?;
    // The published ESS core TimeIntervalType limits 31-day start months to 20xx.
    // Qualify one continuous range so adjacent months follow the same contract.
    if !(2000..=2099).contains(&start.year()) {
        return Err(ScheduleError::DayOutsideSchemaRange);
    }
    let end = midnight(day.next_day().ok_or_else(invalid)?)?;
    let seconds = (end - start).whole_seconds();
    if !matches!(seconds, 82_800 | 86_400 | 90_000) {
        return Err(invalid());
    }
    Ok(start..end)
}

impl ScheduleMessage {
    /// Encodes a validated snapshot. A refusal returns no partial XML.
    #[must_use = "the schedule must pass the ESS profile"]
    pub fn to_xml(&self) -> Result<String, ScheduleError> {
        let window = delivery_window(self.day)?;
        validate_id("message ID", &self.id)?;
        validate_revision("message revision", self.revision, 999)?;
        if !self.receiver.starts_with("10X") {
            return Err(ScheduleError::InvalidRecipient(
                "receiver must be a 10X ÜNB EIC",
            ));
        }
        if !self.area.starts_with("10Y") {
            return Err(ScheduleError::InvalidRecipient(
                "area must be a 10Y control-area EIC",
            ));
        }
        self.validate_series(((window.end - window.start).whole_minutes() / 15) as usize)?;
        let minute = format_description!("[year]-[month]-[day]T[hour]:[minute]Z");
        let format_boundary = |instant: OffsetDateTime| {
            instant
                .format(minute)
                .map_err(|_| ScheduleError::InvalidTime("delivery day"))
        };
        let interval = format!(
            "{}/{}",
            format_boundary(window.start)?,
            format_boundary(window.end)?
        );
        let invalid = || ScheduleError::InvalidTime("message timestamp");
        let utc = self
            .created_at
            .checked_to_offset(UtcOffset::UTC)
            .ok_or_else(invalid)?;
        if !(1..=9999).contains(&utc.year()) {
            return Err(invalid());
        }
        let created_at = utc
            .format(format_description!(
                "[year]-[month]-[day]T[hour]:[minute]:[second]Z"
            ))
            .map_err(|_| invalid())?;

        // Every interpolated attribute is a checked identifier, a number, or a generated UTC time.
        let mut xml = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<ScheduleMessage DtdVersion="2" DtdRelease="3">
<MessageIdentification v="{}"/><MessageVersion v="{}"/>
<MessageType v="A01"/><ProcessType v="A17"/><ScheduleClassificationType v="A01"/>
<SenderIdentification v="{}" codingScheme="A01"/><SenderRole v="A08"/>
<ReceiverIdentification v="{}" codingScheme="A01"/><ReceiverRole v="A04"/>
<MessageDateTime v="{created_at}"/><ScheduleTimeInterval v="{}"/>
"#,
            self.id, self.revision, self.sender, self.receiver, interval
        );
        for series in &self.series {
            series.write_xml(&mut xml, &self.area, &interval);
        }
        xml.push_str("</ScheduleMessage>\n");
        Ok(xml)
    }

    fn validate_series(&self, positions: usize) -> Result<(), ScheduleError> {
        if self.series.is_empty() {
            return Err(ScheduleError::EmptySchedule);
        }
        let mut ids = HashSet::new();
        let mut trades = HashMap::new();
        for series in &self.series {
            validate_id("series ID", &series.id)?;
            validate_revision("series revision", series.revision, self.revision)?;
            if !ids.insert(&series.id) {
                return Err(ScheduleError::DuplicateId(series.id.clone()));
            }
            if series.delivering == series.receiving
                || (series.delivering != self.sender && series.receiving != self.sender)
            {
                return Err(ScheduleError::InvalidParties(series.id.clone()));
            }
            if series.quantities.len() != positions {
                return Err(ScheduleError::IntervalCount {
                    id: series.id.clone(),
                    expected: positions,
                    actual: series.quantities.len(),
                });
            }
            if trades
                .insert((&series.delivering, &series.receiving), &series.quantities)
                .is_some()
            {
                return Err(ScheduleError::DuplicateTrade(series.id.clone()));
            }
            if let Some(reverse) = trades.get(&(&series.receiving, &series.delivering))
                && let Some(index) = series
                    .quantities
                    .iter()
                    .zip(*reverse)
                    .position(|(a, b)| a.0 > 0 && b.0 > 0)
            {
                return Err(ScheduleError::OverlappingFlows {
                    id: series.id.clone(),
                    position: index + 1,
                });
            }
        }
        Ok(())
    }
}

fn validate_id(field: &'static str, value: &str) -> Result<(), ScheduleError> {
    if !(1..=35).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_alphanumeric()) {
        return Err(ScheduleError::InvalidId(field));
    }
    Ok(())
}

fn validate_revision(field: &'static str, value: u16, maximum: u16) -> Result<(), ScheduleError> {
    if !(1..=maximum).contains(&value) {
        return Err(ScheduleError::InvalidRevision {
            field,
            maximum,
            value,
        });
    }
    Ok(())
}

impl TradeSeries {
    fn write_xml(&self, xml: &mut String, area: &BilanzierungsgebietId, interval: &str) {
        write!(
            xml,
            r#"<ScheduleTimeSeries>
<SendersTimeSeriesIdentification v="{}"/><SendersTimeSeriesVersion v="{}"/>
<BusinessType v="A02"/><Product v="8716867000016"/><ObjectAggregation v="A01"/>
<InArea v="{area}" codingScheme="A01"/><OutArea v="{area}" codingScheme="A01"/>
<InParty v="{}" codingScheme="A01"/><OutParty v="{}" codingScheme="A01"/>
<MeasurementUnit v="MAW"/><Period><TimeInterval v="{interval}"/><Resolution v="PT15M"/>
"#,
            self.id, self.revision, self.receiving, self.delivering
        )
        .expect("writing to String is infallible");
        for (index, qty) in self.quantities.iter().enumerate() {
            writeln!(
                xml,
                r#"<Interval><Pos v="{}"/><Qty v="{qty}"/></Interval>"#,
                index + 1
            )
            .expect("writing to String is infallible");
        }
        xml.push_str("</Period></ScheduleTimeSeries>\n");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use time::macros::{date, datetime};

    fn schedule() -> ScheduleMessage {
        let sender = BilanzkreisId::new("11XSUEDWESTSTRO8").unwrap();
        ScheduleMessage {
            id: "Msg".into(),
            revision: 2,
            sender: sender.clone(),
            receiver: "10XDE-EON-NETZ-C".parse().unwrap(),
            area: "10YDE-EON------1".parse().unwrap(),
            day: date!(2026 - 03 - 29),
            created_at: datetime!(2026-03-28 11:22 UTC),
            series: vec![TradeSeries {
                id: "Sale".into(),
                revision: 1,
                delivering: sender,
                receiving: "11XENERGIE2----H".parse().unwrap(),
                quantities: vec![ScheduleQuantity::from_kw(1).unwrap(); 92],
            }],
        }
    }

    #[test]
    fn ids_and_revisions_must_fit_the_wire_fields() {
        let mut doc = schedule();
        for invalid in ["", "one two", "A&B", "A\"B", "ä", &"Z".repeat(36)] {
            doc.id = invalid.into();
            assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("message ID")));
        }
        doc.id = "A".repeat(35);
        doc.series[0].id = "bad/id".into();
        assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("series ID")));
        doc.series[0].id = "a9".repeat(17);
        for (message, series) in [(0, 1), (1000, 1), (2, 0), (2, 3)] {
            doc.revision = message;
            doc.series[0].revision = series;
            assert!(matches!(
                doc.to_xml(),
                Err(ScheduleError::InvalidRevision { .. })
            ));
        }
        doc.revision = 999;
        doc.series[0].revision = 999;
        assert!(doc.to_xml().is_ok());
    }

    #[test]
    fn header_and_trade_parties_have_distinct_roles() {
        let mut doc = schedule();
        doc.receiver = "10YDE-EON------1".parse().unwrap();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::InvalidRecipient(_))
        ));
        doc = schedule();
        doc.area = "11YN-0000-0001-Q".parse().unwrap();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::InvalidRecipient(_))
        ));
        doc = schedule();
        doc.series[0].receiving = doc.sender.clone();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::InvalidParties(_))
        ));
        doc = schedule();
        doc.sender = "11XENAGISME----J".parse().unwrap();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::InvalidParties(_))
        ));
    }

    #[test]
    fn delivery_days_stay_inside_the_qualified_schema_range() {
        assert_eq!(
            delivery_window(date!(2000 - 01 - 01)),
            Err(ScheduleError::DayOutsideSchemaRange)
        );
        for day in [date!(2000 - 01 - 02), date!(2100 - 01 - 01)] {
            let window = delivery_window(day).unwrap();
            assert_eq!((window.end - window.start).whole_hours(), 24);
        }
        assert_eq!(
            delivery_window(date!(2100 - 01 - 02)),
            Err(ScheduleError::DayOutsideSchemaRange)
        );
    }

    #[test]
    fn complete_day_is_required_even_for_an_explicit_zero() {
        let mut doc = schedule();
        doc.series[0].quantities.pop();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::IntervalCount {
                expected: 92,
                actual: 91,
                ..
            })
        ));
        doc.series[0].quantities.extend([ScheduleQuantity(0); 2]);
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::IntervalCount {
                expected: 92,
                actual: 93,
                ..
            })
        ));
        doc.series.clear();
        assert_eq!(doc.to_xml(), Err(ScheduleError::EmptySchedule));
        assert!(delivery_window(Date::MAX).is_err());
        assert!(delivery_window(Date::MIN).is_err());
    }

    #[test]
    fn a_bilateral_trade_has_at_most_one_flow_per_position() {
        let mut doc = schedule();
        doc.series.push(doc.series[0].clone());
        assert!(matches!(doc.to_xml(), Err(ScheduleError::DuplicateId(_))));
        doc.series[1].id = "Return".into();
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::DuplicateTrade(_))
        ));
        let reverse = &mut doc.series[1];
        std::mem::swap(&mut reverse.receiving, &mut reverse.delivering);
        reverse.quantities.fill(ScheduleQuantity(0));
        reverse.quantities[91] = ScheduleQuantity(1);
        assert!(matches!(
            doc.to_xml(),
            Err(ScheduleError::OverlappingFlows { position: 92, .. })
        ));
        doc.series[0].quantities[91] = ScheduleQuantity(0);
        let xml = doc.to_xml().unwrap();
        assert_eq!(xml.matches("<ScheduleTimeSeries>").count(), 2);
        assert_eq!(doc.to_xml().unwrap(), xml);
    }
}