Implementing On-Chain Settlement for Renewable Energy Certificates: Integrating Energy API with Smart Contracts for Auditable REC Transfers
Renewable Energy Certificates (RECs) move value between generators, corporates, and markets — but the audit trail is often a patchwork of spreadsheets, bilateral contracts, and PDFs. If you want to settle RECs on-chain with auditable, programmatic rules, you quickly run into two hard requirements: (1) reliable energy market data to price, timestamp, and validate each transfer, and (2) a reference source for emissions metrics to link a REC’s green value to actual grid conditions. This post shows how to implement on-chain settlement for RECs using Energy API market and emissions data as the off-chain truth layer, then integrate that data into smart contracts through an oracle or relayer pattern.
The result is a deterministic, testable, and transparent process: the REC transfer is recorded on-chain; the price index, settlement window, and carbon context are committed to the transaction; and the entire flow is reproducible with a unified, normalized data interface. Whether you are connecting Iberian day-ahead auctions to a corporate offtake, using EU ETS allowances as a hedge, or calculating a green premium tied to intraday curves or grid carbon intensity, this guide provides the foundation to ship production-grade REC settlement logic in days, not weeks.
What you will build: a flow that queries electricity prices, carbon intensity, and carbon allowance prices via a single REST surface; runs validation and pricing logic server-side; and pushes final settlement parameters into a smart contract for finalization. Along the way, you will see how to use intraday electricity curves for precision, day-ahead forecasts for forward contracts, and historical series for dispute resolution — all powered by Energy API.
Introduction
On-chain settlement for RECs sounds straightforward: transmit a certificate, lock a price, and publish a receipt. In practice, real-world inputs complicate the happy path. REC pricing may reference day-ahead electricity auctions, intraday index snapshots, or a blended benchmark across electricity, gas, and carbon allowances. Additionally, corporate buyers increasingly require auditable links between REC claims and actual grid emissions intensity at the time and place of production. Missing or inconsistent data turns settlement into an argument; delayed sources introduce latency; and heterogeneous formats make reconciliation brittle.
The challenge is data normalization under time pressure. Without a unified interface, you’ll scrape ENTSO-E or OMIE for day-ahead curves, EIA/FRED for hydrocarbon references, ESIOS for PVPC retail context, and Ember for carbon intensity. Each has different endpoints, parameter names, calendars, and time zones. Even if you wire it up, you still need to align calendars, handle missing values for weekends and holidays, unify currencies, and resolve symbol naming. This is all work that does not move your on-chain product forward.
The solution is to put a clean, auditable data plane beneath your REC contracts. With Energy API, you fetch electricity, gas, oil, coal, EU ETS allowances, and grid carbon intensity through one normalized JSON schema — and you can query multiple commodities in a single call. That unlocks fast and consistent settlement logic: you price a REC off the Iberian day-ahead auction, add a carbon premium referenced to EUA_CO2, validate the production hour against the local grid intensity, and store all the values and timestamps into a smart contract event. One interface, many sources, zero duct tape.
Why Energy API
There are plenty of places to find energy data, but almost none give you a developer-grade, unified interface designed for production applications. Here’s why Energy API is a fit for on-chain REC settlement and energy product workflows:
- One normalized REST surface for many official sources. Stop translating between OMIE day-ahead auction fields, ENTSO-E schedules, ESIOS PVPC formats, and EIA/FRED conventions. You call a single endpoint, pass symbols, receive the same JSON schema across all commodities. That means one data model in your microservices, oracles, and smart contract verifiers.
- Multiple commodities in a single request. A single /latest call can return electricity (e.g., OMIE_ES_DA), gas (TTF_GAS), carbon allowances (EUA_CO2), and carbon intensity (CARBON_INT_EU). For REC settlement, this enables composite pricing formulas and hedges with just one round trip.
- Intraday and day-ahead electricity curves where sources publish them. Precision matters when you prove that a REC maps to a particular hour of generation. The /electricity/hourly endpoint gives you time-sliced values to pin down a fair settlement price and carbon attribution window.
- Deterministic utilities for production reliability. The /forecast endpoint (for supported auction symbols) lets you fetch the next published day-ahead price once it is officially available, while /status exposes the freshness of upstream providers so you can implement health checks, fallbacks, and circuit breakers in your data pipeline. This is critical for automated on-chain finalization windows.
Taken together, these features let you architect a clean off-chain data service that feeds consistent inputs to your on-chain logic. You reduce ETL overhead, you get simpler observability, and you ship faster. If you want to see it in action, you can Try Energy API for free.
Quick Start
Base URL: https://energy-api.com/api/v1
Below we fetch three reference symbols in one go: Brent crude (as a macro energy benchmark), TTF gas (European gas reference), and EU ETS carbon allowances — useful if your REC price embeds a carbon-linked uplift. You can add electricity symbols in the same list to compute blended indexes.
curl -G https://energy-api.com/api/v1/latest \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS,EUA_CO2" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response:
{
"success": true,
"date": "2026-06-11",
"base": "MIXED",
"rates": {
"BRENT_CRUDE": 74.82,
"TTF_GAS": 38.15,
"EUA_CO2": 67.40
},
"dates": {
"BRENT_CRUDE": "2026-06-11",
"TTF_GAS": "2026-06-11",
"EUA_CO2": "2026-06-11"
},
"currencies": {
"BRENT_CRUDE": "USD",
"TTF_GAS": "EUR",
"EUA_CO2": "EUR"
}
}
Key fields:
- success: Indicates request success.
- date: The response reference date (useful when cross-checking mixed calendars).
- rates: Symbol-to-latest price mapping.
- dates: Per-symbol publication date (some commodities publish at different times).
- currencies: Per-symbol currency code; align or convert as needed in your pricing engine.
This single call gives you immediate inputs for pricing models, hedges, and portfolio context. For a REC settlement engine, you might combine OMIE_ES_DA for the production country’s day-ahead, EUA_CO2 for carbon-linked premium, and CARBON_INT_EU for metadata tagging of the transaction.
Core Endpoints for On-Chain REC Settlement
1) Discover Symbols: GET /symbols
Purpose: Programmatically list available instruments and their metadata (category, country code, currency, frequency, and description). This is useful for dynamic configuration — e.g., allowing a buyer to choose EPEX_DE_DA vs OMIE_ES_DA at contract initialization without hardcoding every option.
Key params:
- category: Filter by commodity (e.g., electricity, gas).
- provider: Optional filter by source.
- base: Optional currency filter.
curl -G https://energy-api.com/api/v1/symbols \
--data-urlencode "category=gas" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response:
{
"success": true,
"count": 3,
"symbols": [
{
"symbol": "TTF_GAS",
"name": "TTF Natural Gas Day-Ahead",
"category": "gas",
"country_code": "EU",
"currency_code": "EUR",
"frequency": "daily",
"description": "TTF day-ahead price published by EEX."
}
]
}
Practical uses:
- Render a symbol picker in your dashboard UI.
- Validate a smart contract’s allowed symbols against an off-chain allowlist that you refresh daily.
- Store currency_code and frequency to pre-validate settlement windows and FX normalization.
2) Latest Prices: GET /latest
Purpose: Pull the last published price for one or more symbols, even across commodity types. For REC settlement, this is often the base index you lock into an escrow smart contract at transfer finalization.
Key params:
- symbols: Comma-separated list (e.g., OMIE_ES_DA,EUA_CO2,TTF_GAS).
- base: Optional currency filter; if omitted, currencies vary by symbol.
- category: Optional filter.
curl -G https://energy-api.com/api/v1/latest \
--data-urlencode "symbols=OMIE_ES_DA,EUA_CO2,TTF_GAS" \
--data-urlencode "api_key=YOUR_API_KEY"
Field interpretation:
- rates: Use directly for pricing; apply your FX conversion if needed.
- dates: Store these per-symbol timestamps on-chain for auditability (e.g., in an event).
- currencies: Normalize your amounts into the payout currency to avoid confusion downstream.
3) Historical Point-in-Time: GET /historical
Purpose: Fetch prices for a specific past date. This is essential for dispute resolution and retroactive settlement windows (e.g., when a REC is matched to a backdated production hour or when you need a prior-day close).
Key params:
- date: YYYY-MM-DD
- symbols: Comma-separated list.
- base: Optional currency filter.
curl -G https://energy-api.com/api/v1/historical \
--data-urlencode "date=2025-09-15" \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response:
{
"success": true,
"date": "2025-09-15",
"base": "MIXED",
"rates": {
"BRENT_CRUDE": 71.45,
"TTF_GAS": 36.20
},
"currencies": {
"BRENT_CRUDE": "USD",
"TTF_GAS": "EUR"
}
}
Note: If the requested date is a non-publishing day, you get the last available value before it. That makes historical validation deterministic even across weekends and holidays.
4) Time Series for Valuation Windows: GET /timeseries
Purpose: Pull a date-keyed series between two dates. This is ideal for computing average settlement prices over a window (e.g., weekly or monthly index for REC transfers), building candlestick charts for a trading cockpit, or backtesting pricing formulas.
Key params:
- start, end: YYYY-MM-DD inclusive range.
- symbols: One or many.
curl -G https://energy-api.com/api/v1/timeseries \
--data-urlencode "start=2025-01-01" \
--data-urlencode "end=2025-03-31" \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response:
{
"success": true,
"base": "MIXED",
"start_date": "2025-01-01",
"end_date": "2025-03-31",
"rates": {
"BRENT_CRUDE": {
"2025-01-02": 76.30,
"2025-01-03": 75.90
},
"TTF_GAS": {
"2025-01-02": 46.80,
"2025-01-03": 47.10
}
},
"frequencies": {
"BRENT_CRUDE": "daily",
"TTF_GAS": "daily"
},
"currencies": {
"BRENT_CRUDE": "USD",
"TTF_GAS": "EUR"
}
}
Practical use:
- Compute volume-weighted or time-weighted averages for settlement.
- Compare REC price components over time (e.g., gas vs carbon uplift).
- Render charts for auditors or counterparties during dispute resolution.
5) Intraday Curves for Hour-Matched RECs: GET /electricity/hourly
Purpose: Retrieve the full intraday or hourly curve for an electricity symbol on a specific date. This is the backbone for hour-matched REC pricing, where the buyer requires a price index aligned to the exact generation hour.
Key params:
- symbol: e.g., OMIE_ES_DA, EPEX_DE_DA, AEMO_NSW1.
- date: YYYY-MM-DD (local to the market’s publishing calendar).
curl -G https://energy-api.com/api/v1/electricity/hourly \
--data-urlencode "symbol=OMIE_ES_DA" \
--data-urlencode "date=2026-06-11" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response (shape representative; actual arrays contain all intervals):
{
"success": true,
"symbol": "OMIE_ES_DA",
"date": "2026-06-11",
"interval": "hourly",
"timezone": "Europe/Madrid",
"currency_code": "EUR",
"points": [
{ "timestamp": "2026-06-11T00:00:00+02:00", "value": 72.14 },
{ "timestamp": "2026-06-11T01:00:00+02:00", "value": 69.83 },
{ "timestamp": "2026-06-11T02:00:00+02:00", "value": 68.21 }
]
}
How to use:
- Map the REC’s production hour to the corresponding timestamp in points. Use timezone to avoid DST errors.
- Average multiple hours if your contract defines a block (e.g., 10:00–14:00).
- Store the per-interval timestamp and value alongside the on-chain settlement record for a tamper-evident audit trail.
6) Grid Carbon Context: GET /carbon-intensity
Purpose: Fetch grid carbon intensity in gCO2eq/kWh by country. Corporates often want each REC to include a carbon context metadata tag. Your contract or off-chain hook can fetch the intensity for the country and date that match the REC’s production.
Key params:
- country: ISO-2 code (e.g., DE, ES).
curl -G https://energy-api.com/api/v1/carbon-intensity \
--data-urlencode "country=ES" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response (representative):
{
"success": true,
"country": "ES",
"unit": "gCO2eq/kWh",
"date": "2026-06-11",
"value": 156.2,
"source": "official"
}
Recommendation:
- Attach value and date to your on-chain transfer as metadata (e.g., emitted in a SettlementFinalized event). This enables automated ESG reporting later.
7) EU ETS Allowances: GET /emissions/latest
Purpose: Pull the latest EU ETS EUA_CO2 allowance price in one call. Commonly used to add a carbon-cost component to REC pricing or hedging strategies.
curl -G https://energy-api.com/api/v1/emissions/latest \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON response (representative):
{
"success": true,
"date": "2026-06-11",
"symbol": "EUA_CO2",
"rate": 67.40,
"currency_code": "EUR"
}
Usage tip:
- Store this rate and date as the EUA reference used at settlement. If your REC premium tracks carbon cost exposure, this creates a verifiable trail.
8) Day-Ahead Auction Forecast (Deterministic Lookup): GET /forecast
Purpose: For supported auction-sourced electricity symbols, obtain the next published day-ahead price once it is available from the official source. It is not a predictive model; it is a deterministic retrieval of already-published forward values, letting you finalize forward-settled contracts as soon as data posts.
Key params:
- symbol: Electricity auction symbol (e.g., OMIE_ES_DA).
curl -G https://energy-api.com/api/v1/forecast \
--data-urlencode "symbol=OMIE_ES_DA" \
--data-urlencode "api_key=YOUR_API_KEY"
Representative JSON response:
{
"success": true,
"symbol": "OMIE_ES_DA",
"target_date": "2026-06-12",
"currency_code": "EUR",
"interval": "hourly",
"points": [
{ "timestamp": "2026-06-12T00:00:00+02:00", "value": 71.52 },
{ "timestamp": "2026-06-12T01:00:00+02:00", "value": 69.10 }
]
}
Application:
- Enable auto-finalization windows: when the day-ahead posts for your settlement date, your off-chain service retrieves it and commits to the contract.
- Guard against premature settlement by checking target_date aligns with the intended delivery period.
9) Fluctuation Metrics: GET /fluctuation
Purpose: Get the start and end values over a period plus absolute and percentage change. This supports risk controls (e.g., if volatility exceeds X%, require manual review before on-chain finalization).
Key params:
- start, end: Range to analyze.
- symbols: One or many.
curl -G https://energy-api.com/api/v1/fluctuation \
--data-urlencode "start=2026-05-01" \
--data-urlencode "end=2026-06-01" \
--data-urlencode "symbols=EUA_CO2,TTF_GAS" \
--data-urlencode "api_key=YOUR_API_KEY"
Representative JSON response:
{
"success": true,
"base": "MIXED",
"period": {
"start": "2026-05-01",
"end": "2026-06-01"
},
"symbols": {
"EUA_CO2": {
"start_value": 64.10,
"end_value": 67.40,
"change": 3.30,
"change_pct": 5.15
},
"TTF_GAS": {
"start_value": 34.90,
"end_value": 38.15,
"change": 3.25,
"change_pct": 9.31
}
}
}
Integration advice:
- Before committing to-chain, compute volatility and enforce governance thresholds to reduce pricing disputes.
10) OHLC Candles: GET /ohlc
Purpose: Retrieve weekly, monthly, or quarterly OHLC candles. This supports dashboards, volatility analysis, and governance — for example, if your policy says “use monthly average plus premium,” you can cross-check the computed average against close or high to ensure consistency.
Key params:
- symbols: One or many.
- period: weekly | monthly | quarterly.
- start, end: Optional.
curl -G https://energy-api.com/api/v1/ohlc \
--data-urlencode "symbols=OMIE_ES_DA,EUA_CO2" \
--data-urlencode "period=monthly" \
--data-urlencode "start=2026-01-01" \
--data-urlencode "end=2026-06-30" \
--data-urlencode "api_key=YOUR_API_KEY"
Representative JSON response:
{
"success": true,
"symbols": {
"OMIE_ES_DA": [
{ "period": "2026-01", "open": 65.1, "high": 89.3, "low": 54.2, "close": 70.4, "data_points": 31 },
{ "period": "2026-02", "open": 70.4, "high": 92.2, "low": 60.1, "close": 73.5, "data_points": 28 }
],
"EUA_CO2": [
{ "period": "2026-01", "open": 62.9, "high": 70.2, "low": 58.6, "close": 66.0, "data_points": 22 }
]
}
}
Use cases:
- Compute monthly settlement references directly from OHLC data.
- Flag outlier months to trigger enhanced review before REC issuance.
11) Provider Health: GET /status
Purpose: Check last fetch status per data provider. Build a robust pipeline with health checks and fallbacks; if a provider is late, delay finalization or switch to a pre-agreed alternative index for that cycle.
curl -G https://energy-api.com/api/v1/status \
--data-urlencode "api_key=YOUR_API_KEY"
Representative JSON response:
{
"success": true,
"providers": {
"omie": { "last_success": "2026-06-11T12:10:00Z", "status": "ok" },
"entsoe": { "last_success": "2026-06-11T11:55:00Z", "status": "ok" },
"eia": { "last_success": "2026-06-10T22:00:00Z", "status": "ok" },
"fred": { "last_success": "2026-06-10T23:10:00Z", "status": "ok" },
"esios": { "last_success": "2026-06-11T12:05:00Z", "status": "ok" }
}
}
Best practice:
- Fail closed when a provider is delayed: prevent on-chain finalization for a given symbol until /status shows “ok” and your own data checks pass.
Implementing On-Chain REC Settlement with Energy API
Let’s connect the data layer to your smart contracts. In most production setups, you do not call a REST API directly from a smart contract; instead, you use an off-chain component (oracle or relayer) that fetches authoritative values, applies business rules, and then sends a transaction to your contract with the finalized numbers.
Architecture overview:
- Off-chain service (Node.js or Python) fetches data from Energy API using /latest, /electricity/hourly, /forecast, /emissions/latest, and /carbon-intensity. It applies your pricing formula and settlement logic.
- The service writes settlement parameters to the chain through a function like finalizeSettlement(settlementId, price, currency, references, proofHash).
- The contract stores the submitted values and emits an event capturing symbol list, per-symbol publication dates, and a hash of the raw JSON payloads retained off-chain for audit.
JavaScript example (off-chain relayer):
import fetch from "node-fetch";
import { ethers } from "ethers";
const API_BASE = "https://energy-api.com/api/v1";
const API_KEY = process.env.ENERGY_API_KEY;
async function getHourly(symbol, date) {
const url = new URL(`${API_BASE}/electricity/hourly`);
url.searchParams.set("symbol", symbol);
url.searchParams.set("date", date);
url.searchParams.set("api_key", API_KEY);
const res = await fetch(url.toString());
if (!res.ok) throw new Error(`hourly fetch failed: ${res.status}`);
return res.json();
}
async function getEUA() {
const url = new URL(`${API_BASE}/emissions/latest`);
url.searchParams.set("api_key", API_KEY);
const res = await fetch(url.toString());
if (!res.ok) throw new Error(`eua fetch failed: ${res.status}`);
return res.json();
}
async function getCarbonIntensity(country) {
const url = new URL(`${API_BASE}/carbon-intensity`);
url.searchParams.set("country", country);
url.searchParams.set("api_key", API_KEY);
const res = await fetch(url.toString());
if (!res.ok) throw new Error(`intensity fetch failed: ${res.status}`);
return res.json();
}
// Sample pricing formula: hour-matched price + alpha * EUA
function priceREC(hourlyPoint, euaRate, alpha = 0.05) {
return hourlyPoint.value + alpha * euaRate;
}
async function finalize(settlementId, symbol, date, hourISO, country, contract) {
const [curve, eua, intensity] = await Promise.all([
getHourly(symbol, date),
getEUA(),
getCarbonIntensity(country)
]);
// Find the matching hour in the curve
const match = curve.points.find(p => p.timestamp === hourISO);
if (!match) throw new Error("no matching hour in curve");
const recPrice = priceREC(match, eua.rate);
// Prepare references for on-chain storage
const references = {
symbol,
date,
hour: hourISO,
electricity_value: match.value,
eua_rate: eua.rate,
eua_date: eua.date,
carbon_intensity_country: intensity.country,
carbon_intensity_value: intensity.value,
carbon_intensity_date: intensity.date,
currency: curve.currency_code
};
// Send transaction (ethers.js)
const tx = await contract.finalizeSettlement(
settlementId,
ethers.parseUnits(recPrice.toFixed(6), 6), // 6 decimals
references.currency,
JSON.stringify(references)
);
await tx.wait();
console.log(`Settlement ${settlementId} finalized at ${recPrice} ${references.currency}`);
}
Solidity example (storage and event):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract RECSettlement {
event SettlementFinalized(
bytes32 indexed settlementId,
uint256 price, // scaled by 1e6
string currency,
string referencesJson, // serialized references
address indexed operator
);
mapping(bytes32 => bool) public settled;
function finalizeSettlement(
bytes32 settlementId,
uint256 priceScaled1e6,
string calldata currency,
string calldata referencesJson
) external {
require(!settled[settlementId], "already settled");
// Optionally: add access-control (oracle signer, role, etc.)
settled[settlementId] = true;
emit SettlementFinalized(settlementId, priceScaled1e6, currency, referencesJson, msg.sender);
}
}
Operational tips:
- Align timezones carefully. Use the timezone field from /electricity/hourly to build precise hour-matching, particularly across DST transitions.
- Persist raw API responses off-chain (object storage) and include a hash in referencesJson or a separate field. This creates a strong audit link from on-chain records to exact source payloads.
- Add contracts-level checks to prevent duplicate settlement and to gate who can call finalizeSettlement (e.g., a known oracle signer).
- Before sending the transaction, query /status to ensure upstream providers are healthy. If not, pause until confirmed.
Python and cURL: Data Retrieval Patterns
If you prefer Python, here’s a succinct retrieval and pricing flow using requests. This pattern is ideal for a serverless job that runs every hour to detect settle-ready certificates and post finalization transactions.
import os
import json
import requests
from decimal import Decimal
API_BASE = "https://energy-api.com/api/v1"
API_KEY = os.environ["ENERGY_API_KEY"]
def get(path, params):
params = dict(params or {})
params["api_key"] = API_KEY
r = requests.get(f"{API_BASE}{path}", params=params, timeout=30)
if r.status_code == 404:
raise RuntimeError("no data found")
if r.status_code == 422:
raise ValueError(r.json().get("error", "validation error"))
if not r.ok:
raise RuntimeError(f"bad status: {r.status_code} {r.text}")
return r.json()
def get_hourly(symbol, date):
return get("/electricity/hourly", {"symbol": symbol, "date": date})
def get_eua():
return get("/emissions/latest", {})
def get_intensity(country):
return get("/carbon-intensity", {"country": country})
def price_rec(hour_value, eua_rate, alpha=Decimal("0.05")):
return Decimal(str(hour_value)) + alpha * Decimal(str(eua_rate))
def compute_settlement(symbol, date, hour_iso, country):
curve = get_hourly(symbol, date)
eua = get_eua()
intensity = get_intensity(country)
pts = curve["points"]
match = next((p for p in pts if p["timestamp"] == hour_iso), None)
if not match:
raise RuntimeError("matching hour not found")
price = price_rec(match["value"], eua["rate"])
references = {
"symbol": symbol,
"date": date,
"hour": hour_iso,
"electricity_value": match["value"],
"eua_rate": eua["rate"],
"eua_date": eua["date"],
"carbon_intensity_value": intensity["value"],
"carbon_intensity_date": intensity["date"],
"currency": curve["currency_code"]
}
return price, references
if __name__ == "__main__":
p, refs = compute_settlement("OMIE_ES_DA", "2026-06-11",
"2026-06-11T10:00:00+02:00", "ES")
print("price:", p)
print("references:", json.dumps(refs, indent=2))
This approach provides a deterministic pipeline with robust error handling for 404 (no data) and 422 (validation). Incorporate retries and exponential backoff on transient errors and use /status to detect upstream issues proactively.
Real-World Use Cases
Below are concrete patterns we see developers, utilities, and ESG teams implement with Energy API for on-chain energy products.
- On-Chain REC Escrow and Final Settlement: A buyer and seller lock a provisional REC price at transfer initiation, then finalize after the next day-ahead auction posts. Use /forecast (for supported symbols) to retrieve the published day-ahead for the target date, /emissions/latest for EUA_CO2 premium, and /electricity/hourly to match the production hour. Commit the final blended price and references to a SettlementFinalized event.
- ESG Dashboard with Hour-Granular Attribution: Corporate offtakers want visibility into the carbon context of their renewable procurement. Use /electricity/hourly for the price context and /carbon-intensity to tag each hour by country, then aggregate by site or region. The dashboard reads the same references stored on-chain in your events to ensure data consistency.
- Hedged Green Tariff Calculator: A utility or fintech app quotes a green energy tariff to small businesses, referencing the local day-ahead electricity price and adding a carbon allowance hedge. Use /latest or /timeseries for OMIE_ES_DA/EPEX_DE_DA and EUA_CO2, then /fluctuation to assess recent volatility and adjust the risk margin. The UI shows transparent inputs pulled directly from the API.
Error Handling and Troubleshooting Best Practices
Strong error handling reduces disputes and failed on-chain finalizations.
- Validation errors (422): Always check your query parameters (e.g., date format, valid symbol names). If you are building a dynamic symbol picker, back it by /symbols rather than hardcoding lists.
- Data not found (404): For historical dates that are non-publishing days, remember /historical returns the most recent value before the date. If you must have exact-day values, document that constraint to counterparties.
- Backoff strategy: Implement retries with exponential backoff for transient HTTP errors. Log both the HTTP status and the API’s error message body for root-cause analysis.
- Health checks: Use /status to confirm upstream data freshness before triggering an on-chain finalization window. If a provider is behind schedule, fail closed and notify operators.
- Auditable references: Persist the raw JSON responses from endpoints you use in settlement, compute a content hash, and store that hash on-chain in your event. This makes re-verification straightforward in the future.
End-to-End Example: From Data to On-Chain Event
Let’s walk through a full cycle where a REC produced in Spain on 2026-06-11 from 10:00–11:00 local time is settled on-chain using the OMIE day-ahead price for that hour plus a 5% carbon premium referenced to EUA_CO2. We will fetch, compute, and generate a settlement payload ready for your finalizeSettlement call.
- Fetch the intraday curve for OMIE_ES_DA on 2026-06-11 via /electricity/hourly. Locate the point with timestamp 2026-06-11T10:00:00+02:00.
- Fetch EUA_CO2 via /emissions/latest. Extract rate and date.
- Fetch Spain’s carbon intensity via /carbon-intensity. Extract value and date for audit tagging.
- Compute price = hour_value + 0.05 * EUA_rate.
- Assemble references with symbol, hour, values, source dates, and currency_code.
- Emit finalizeSettlement on-chain with a standardized decimal scaling (e.g., 1e6).
Sample settlement payload (to store in referencesJson):
{
"symbol": "OMIE_ES_DA",
"date": "2026-06-11",
"hour": "2026-06-11T10:00:00+02:00",
"electricity_value": 73.25,
"currency": "EUR",
"eua_rate": 67.40,
"eua_date": "2026-06-11",
"carbon_intensity_country": "ES",
"carbon_intensity_value": 156.2,
"carbon_intensity_date": "2026-06-11",
"formula": "price = electricity_value + 0.05 * eua_rate"
}
With these fields published as an event, both counterparties — and auditors — can reconstruct the logic and verify each source at the time of settlement.
Performance and Reliability Tips for Production
- Batch queries: Use /latest with multiple symbols to reduce round trips when you need cross-commodity references (e.g., TTF_GAS, BRENT_CRUDE, EUA_CO2).
- Deterministic cutovers: For forward-settled contracts, poll /forecast for supported symbols on a schedule so you can finalize as soon as the day-ahead posts.
- Cache-and-hash: Cache JSON responses for a short TTL during finalization windows and hash them. Store hash references on-chain to anchor your audit trail.
- Time zone safety: Always rely on timezone returned by /electricity/hourly and treat timestamps as ISO-8601 with offsets. Normalize in your off-chain service before on-chain submission.
Additional Endpoint Highlights Worth Knowing
- GET /electricity/latest: Pull the latest prices for all electricity symbols (optionally filtered by country). Ideal for UI dropdown defaults or market-overview panels.
- GET /gas/latest and GET /coal/latest: Useful when your REC premium model references thermal generation cost backdrops or broader energy market trends.
- POST /cost-estimate: Compute a simple monthly electricity cost estimate for a given symbol or country from latest price × kWh/month. Great for “what-if” calculators embedded in sustainability portals.
Example: electricity market overview (all electricity symbols, then pick your target by country).
curl -G https://energy-api.com/api/v1/electricity/latest \
--data-urlencode "country=ES" \
--data-urlencode "api_key=YOUR_API_KEY"
Representative JSON response:
{
"success": true,
"date": "2026-06-11",
"symbols": {
"OMIE_ES_DA": {
"rate": 73.25,
"currency_code": "EUR",
"country_code": "ES"
},
"PVPC_ES_2TD": {
"rate": 24.11,
"currency_code": "EUR",
"country_code": "ES"
}
}
}
For a quick retail-facing calculation:
curl -X POST https://energy-api.com/api/v1/cost-estimate \
-H "Content-Type: application/json" \
-d '{
"symbol": "OMIE_ES_DA",
"kwh_per_month": 12000,
"api_key": "YOUR_API_KEY"
}'
Representative JSON response:
{
"success": true,
"symbol": "OMIE_ES_DA",
"kwh_per_month": 12000,
"latest_rate": 73.25,
"currency_code": "EUR",
"estimated_cost": 879000.00,
"note": "Wholesale reference only; excludes taxes, network charges, and hourly profile."
}
These utilities simplify prototyping tools around your REC contracts — pricing popovers, buyer education, and support workflows that reduce friction in negotiation and confirmation.
FAQ
How often do day-ahead electricity prices update?
Day-ahead auction schedules are market-specific, but once the official results are published, the /latest and /electricity/hourly endpoints reflect them. For forward dates where the day-ahead has been published, /forecast provides deterministic retrieval of the published values so you can automate finalization.
Can I query multiple commodities in a single request?
Yes. The /latest, /historical, /timeseries, /fluctuation, and /ohlc endpoints support multiple symbols across gas, electricity, oil, coal, carbon allowances, and carbon intensity. This is ideal for composite REC pricing and hedging logic that references more than one index.
Is there intraday or hourly granularity for electricity?
Where official sources publish intraday or hourly curves, /electricity/hourly exposes them with timestamps and a timezone field. This is designed for hour-matched REC settlement and precise ESG attribution.
How do I handle missing data on weekends or holidays?
Use /historical, which returns the most recent value before the requested date if data is not published that day. In contracts, document your fallback rule (e.g., “use prior business day close”) and store the returned date alongside the value for auditability.
What error responses should I expect, and how should I react?
Expect structured errors with HTTP codes such as 404 (no data for symbol/date) and 422 (validation error). Log the error field from the JSON response, retry with backoff where appropriate, and use /status for provider health to decide whether to delay on-chain finalization.
Conclusion + CTA
On-chain settlement for RECs becomes straightforward when the data plane is simple, consistent, and auditable. With Energy API, you cut through the complexity of multiple official sources and formats, align your settlement windows to exact hours, and attach carbon context that meets the expectations of modern ESG reporting. The result is a transparent contract pipeline that counterparties trust — because every number can be traced back to a single source of truth.
Whether you are building a REC marketplace, a corporate procurement portal, or a utility-grade settlement engine, the combination of unified endpoints, intraday curves, and cross-commodity queries accelerates delivery from proof-of-concept to production. Start with a few endpoints — /electricity/hourly, /emissions/latest, and /carbon-intensity — then layer in /forecast and /timeseries for robust automation and analytics. Explore the full catalog at Energy API and begin integrating today.
Ready to ship a verifiable, auditable REC settlement flow? Try Energy API for free and plug production-grade energy and emissions data directly into your smart contracts and apps.
Ready to get started?
Get your API key and start querying energy commodity prices in minutes.
Get API KeyRelated posts
Discover how Energy API can automate demand response programs, streamline event triggering, and enhance enroll...
Read more →
Discover how to optimize Renewable Energy Certificates management with Energy API. Streamline trading, access...
Read more →
Discover how Energy API enhances tracking of Renewable Energy Certificates, empowering sustainability teams wi...
Read more →
Unlock the potential of Renewable Energy Certificates with our guide on using Energy API for efficient trackin...
Read more →
Discover how to streamline Renewable Energy Certificates with Energy API. Enhance decision-making and efficien...
Read more →