Building a Local Sandbox for Market Microstructure Testing: Simulating Order Books and Latency with Energy API for Trading Devs
In finance, the fastest way to validate a trading idea is to bring it as close to production as possible—locally. If you build execution or market-making systems for energy-linked assets (power, gas, oil, coal, carbon, and carbon-intensity overlays), you need realistic microstructure: time series for price formation, intraday curves for electricity auctions, and a way to simulate timing, jitter, and partial data availability. The challenge is that official market portals publish data on different schedules, with incompatible formats, symbol conventions, and time zones. Stitching that into a consistent sandbox costs weeks you’d rather spend on strategy logic and P&L controls.
This post shows how to build a local market microstructure sandbox for energy-linked trading systems using Energy API. We will simulate a consolidated order book, introduce controllable network latency, and rehearse fills against spot updates and intraday electricity curves—without scraping exchanges or maintaining fragile ETL pipelines. The goal is to ship a realistic backtest and live-dry-run harness quickly, then scale it incrementally into production.
You’ll learn how to hydrate symbols across commodities into a unified JSON schema, load historical and intraday curves for realistic limit-order matching, and wire status checks to degrade gracefully when upstream providers delay updates. We’ll focus on the endpoints and patterns that matter for finance: consolidated quoting, OHLC candles for volatility models, day-ahead auction lookups for power trading, and cost-estimates and carbon-intensity overlays for risk and ESG reporting feeds.
Why Energy API
Energy trading devs don’t struggle with math; they struggle with data plumbing. Each official source (OMIE, ENTSO-E, EIA/FRED, ESIOS, and others) ships different formats and symbol conventions, and posts on different timetables. Energy API removes that friction with a single normalized REST surface and consistent JSON schema across commodities. Here’s why that matters in a trading sandbox:
- One schema across six commodity categories. Query BRENT_CRUDE in USD, TTF_GAS in EUR, and EUA_CO2 in EUR in one call. That means you can run cross-commodity arbitrage logic without writing adapters for every provider and schedule.
- Comprehensive coverage with intraday power curves. Energy API exposes electricity intraday curves (15-min or hourly, where the source publishes them). You can seed an order book with realistic hourly slices for OMIE_ES_DA or match retail PVPC hourly reference prices to replay retail-to-wholesale spread strategies.
- Unambiguous symbol discovery. The /symbols endpoint returns active instruments with metadata (country_code, currency_code, frequency), so your pipeline can auto-configure routing and charting—no hardcoding exchange quirks.
- Provider health transparency. With /status you can program watchdogs and circuit breakers. If ENTSO-E is late, you can freeze your replay window or switch to last-known-good values and record an audit trail for downstream risk sign-off.
In short, you get durable building blocks for a realistic finance-grade microstructure emulator—minus the ETL grind.
Quick Start
Energy API uses a straightforward REST interface under a single base URL. You can query multiple symbols in one request and get consistent JSON back—ideal for plumbing into a local simulator.
Base URL:
https://energy-api.com/api/v1
Authentication is passed as a query parameter in your requests. Below is a one-liner to fetch recent values for oil, gas, and carbon allowances together, ideal for cross-asset correlation tests and P&L attribution.
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 in a trading sandbox:
- rates: Numerical price per symbol. Use this to seed your mid-price or last-trade field for order book initialization.
- dates: Per-symbol publication date. Use this for time alignment across commodities. If your simulator replays at wall-clock cadence, advance time only when the underlying date ticks.
- currencies: Currency per symbol. If your P&L ledger is in a single reporting currency, apply FX at ingestion or downstream in your risk engine.
Core Endpoints For A Microstructure Sandbox
Below are the endpoints I reach for when building a local energy-market sandbox that’s realistic enough for execution algorithms, hedging logic, and P&L controls.
1) Discover Tradable Instruments: GET /symbols
You need a canonical symbol dictionary before you can configure routes or instruments in a simulator. /symbols exposes active instruments, currencies, categories, and frequency, so your pipeline can derive storage cadence and visualization defaults—without hardcoding metadata.
Endpoint:
GET /symbols
Key params:
- category (optional): gas | electricity | oil | coal | carbon_intensity, etc.
- base (optional): Currency code filter.
- provider (optional): Source identifier filter (e.g., fred, omie).
cURL:
curl -G https://energy-api.com/api/v1/symbols \
--data-urlencode "category=electricity" \
--data-urlencode "api_key=YOUR_API_KEY"
JSON response (truncated for brevity but structurally complete):
{
"success": true,
"count": 4,
"symbols": [
{
"symbol": "OMIE_ES_DA",
"name": "OMIE Spain Day-Ahead",
"category": "electricity",
"country_code": "ES",
"currency_code": "EUR",
"frequency": "daily",
"description": "OMIE day-ahead auction price for Spain."
},
{
"symbol": "EPEX_DE_DA",
"name": "EPEX Germany Day-Ahead",
"category": "electricity",
"country_code": "DE",
"currency_code": "EUR",
"frequency": "daily",
"description": "EPEX day-ahead auction price for Germany."
},
{
"symbol": "PVPC_ES_2TD",
"name": "Spain PVPC 2.0TD",
"category": "electricity",
"country_code": "ES",
"currency_code": "EUR",
"frequency": "hourly",
"description": "Spanish PVPC retail reference prices."
},
{
"symbol": "AEMO_NSW1",
"name": "AEMO New South Wales",
"category": "electricity",
"country_code": "AU",
"currency_code": "AUD",
"frequency": "hourly",
"description": "AEMO NSW region spot price."
}
]
}
Field notes:
- frequency guides storage and replay. For “hourly” series, you’ll version curves per day and step through hours to generate events in your simulator. For “daily” series, treat updates as session opens.
- country_code allows geo-partitioned routing (e.g., align with region-specific tax or balancing rules in your risk scenarios).
- description is useful for UI labels in a local dashboard to make analyst handoff easier.
2) Seed Live Ticks and Cross-Asset Views: GET /latest
For a cross-commodity trading harness, you want a single call to get the latest prices across gas, power, oil, coal, and carbon. That enables spread calculations, correlation checks, and fast P&L what-ifs. Energy API returns a mixed-currency result with per-symbol currency metadata.
Endpoint:
GET /latest
Key params:
- symbols (required): Comma-separated list, e.g., BRENT_CRUDE,TTF_GAS,EUA_CO2.
- base (optional): For filtering or normalization.
cURL:
curl -G https://energy-api.com/api/v1/latest \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS,EUA_CO2,COAL_ROTTERDAM" \
--data-urlencode "api_key=YOUR_API_KEY"
Use cases:
- Real-time spread computation: EUA_CO2 vs TTF_GAS for carbon cost overlays on gas-fired generation.
- Hedge ratio suggestion: BRENT_CRUDE vs power exposure when your procurement desk prices retail offers.
3) Replay Sessions With Ground Truth: GET /timeseries
To test execution and hedging logic, you must replay history with stable, deterministic data. /timeseries delivers date-keyed values across a window, perfect for event replayer loops that drive your synthetic order book snapshots.
Endpoint:
GET /timeseries
Key params:
- start, end (required): YYYY-MM-DD for historical windows.
- symbols (required): Comma-separated list.
cURL:
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,EUA_CO2" \
--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,
"2025-01-06": 76.05
},
"TTF_GAS": {
"2025-01-02": 46.80,
"2025-01-03": 47.10,
"2025-01-06": 47.90
},
"EUA_CO2": {
"2025-01-02": 69.20,
"2025-01-03": 69.00,
"2025-01-06": 68.75
}
},
"frequencies": {
"BRENT_CRUDE": "daily",
"TTF_GAS": "daily",
"EUA_CO2": "daily"
},
"currencies": {
"BRENT_CRUDE": "USD",
"TTF_GAS": "EUR",
"EUA_CO2": "EUR"
}
}
How to use it in your sandbox:
- rates: Iterate by ascending date to “tick” your simulation clock. For daily series, emit a session open event; for intraday series, integrate with hourly curves (see /electricity/hourly) for fine-grained matching.
- frequencies: Drive sampling step (daily vs hourly). For mismatched frequencies in cross-asset strategies, choose a lead asset to drive time and forward-fill others.
- currencies: Normalize to your reporting currency at ingestion time or store alongside prices and convert in P&L calculation to keep provenance.
4) Build Intraday Order Books For Power: GET /electricity/hourly
Power trading revolves around hourly (and sometimes 15-min) slices. /electricity/hourly returns the full intraday curve for a symbol and date—perfect to simulate order books by hour, reprice block orders, and test latency-sensitive fills when transitioning between hours.
Endpoint:
GET /electricity/hourly
Key params:
- symbol (required): e.g., OMIE_ES_DA, EPEX_DE_DA, PVPC_ES_2TD.
- date (required): YYYY-MM-DD.
cURL:
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 (illustrative structure):
{
"success": true,
"symbol": "OMIE_ES_DA",
"date": "2026-06-11",
"currency": "EUR",
"interval": "hourly",
"curve": [
{"hour": "00:00", "price": 62.40},
{"hour": "01:00", "price": 60.80},
{"hour": "02:00", "price": 59.10},
{"hour": "03:00", "price": 58.70},
{"hour": "04:00", "price": 58.90},
{"hour": "05:00", "price": 60.20},
{"hour": "06:00", "price": 66.45},
{"hour": "07:00", "price": 78.10},
{"hour": "08:00", "price": 85.00},
{"hour": "09:00", "price": 88.50},
{"hour": "10:00", "price": 86.30},
{"hour": "11:00", "price": 81.95},
{"hour": "12:00", "price": 80.10},
{"hour": "13:00", "price": 79.25},
{"hour": "14:00", "price": 77.10},
{"hour": "15:00", "price": 74.95},
{"hour": "16:00", "price": 76.05},
{"hour": "17:00", "price": 83.20},
{"hour": "18:00", "price": 91.50},
{"hour": "19:00", "price": 94.80},
{"hour": "20:00", "price": 93.10},
{"hour": "21:00", "price": 88.60},
{"hour": "22:00", "price": 75.25},
{"hour": "23:00", "price": 66.90}
]
}
Sandbox integration:
- curve: For each hour, generate a pseudo-order book by adding synthetic depth around the price (e.g., ±X% ladder), or combine with volatility from /ohlc to scale depth/width realistically.
- interval: If the symbol supports 15-min granularity, the interval value indicates “15min,” and your simulator should emit 4 ticks per hour.
5) Volatility and Risk Windows: GET /ohlc
If you target risk-aware execution or volatility-driven position sizing, you need OHLC aggregates. /ohlc delivers weekly, monthly, or quarterly candles, allowing you to back out simple realized volatility, define stop bands, and calibrate synthetic depth in the order book for replay sessions.
Endpoint:
GET /ohlc
Key params:
- symbols (required)
- period (optional): weekly | monthly | quarterly (default monthly)
- start, end (optional): Bound the candle window
cURL:
curl -G https://energy-api.com/api/v1/ohlc \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS" \
--data-urlencode "period=monthly" \
--data-urlencode "start=2025-01-01" \
--data-urlencode "end=2025-06-30" \
--data-urlencode "api_key=YOUR_API_KEY"
Example JSON:
{
"success": true,
"period": "monthly",
"data": {
"BRENT_CRUDE": [
{"period": "2025-01", "open": 77.20, "high": 82.10, "low": 74.80, "close": 80.35, "data_points": 21},
{"period": "2025-02", "open": 80.40, "high": 84.50, "low": 78.00, "close": 83.10, "data_points": 20}
],
"TTF_GAS": [
{"period": "2025-01", "open": 48.20, "high": 52.00, "low": 44.50, "close": 49.30, "data_points": 22},
{"period": "2025-02", "open": 49.25, "high": 51.10, "low": 46.80, "close": 47.60, "data_points": 20}
]
}
}
Field usage:
- open/high/low/close: Compute realized volatility or ATR-like bands to scale simulated order-book depth or to choose time-varying slippage in your fills engine.
- data_points: Count of raw observations that formed the candle—handy if you want to filter candles with thin underlying data.
6) Auction-Aware Planning: GET /forecast
Many electricity markets publish day-ahead results at deterministic times. /forecast gives you the next published day-ahead price for auction-sourced symbols—essential when you simulate pre-commit hedging or scheduling logic for tomorrow’s hours. It is not a predictive model; it is a deterministic lookup for already-published results keyed by symbol.
Endpoint:
GET /forecast
Key params:
- symbol (required): One auction-sourced electricity symbol.
cURL:
curl -G https://energy-api.com/api/v1/forecast \
--data-urlencode "symbol=OMIE_ES_DA" \
--data-urlencode "api_key=YOUR_API_KEY"
Use case in the sandbox:
- Train algorithms to pre-position based on published day-ahead data, then compare to realized hourly prices the next day using /electricity/hourly to stress check your P&L swing.
7) Health-Aware Simulation: GET /status
Even the best pipelines see occasional data lags from upstream sources. /status helps your simulator decide when to hold state, switch to last-known-good values, or shade uncertainty in your synthetic quotes. In finance, this becomes your circuit breaker: if a provider shows stale status, you slow the matching engine or checkpoint positions before continuing.
Endpoint:
GET /status
cURL:
curl -G https://energy-api.com/api/v1/status \
--data-urlencode "api_key=YOUR_API_KEY"
Illustrative JSON:
{
"success": true,
"providers": [
{"name": "OMIE", "last_fetch": "2026-06-11T12:10:00Z", "status": "ok"},
{"name": "ENTSO-E", "last_fetch": "2026-06-11T12:08:00Z", "status": "ok"},
{"name": "EIA", "last_fetch": "2026-06-10T23:30:00Z", "status": "ok"},
{"name": "FRED", "last_fetch": "2026-06-10T22:05:00Z", "status": "ok"},
{"name": "ESIOS", "last_fetch": "2026-06-11T12:06:00Z", "status": "ok"}
]
}
Tip: If any provider is “degraded” or “delayed,” record that in your run metadata and restrict strategy actions in your emulator (e.g., widen simulated spreads or halt rebalancing).
From Prices To Orders: Designing The Local Sandbox
The microstructure scaffolding below gives you a practical path from raw Energy API responses to a replayable, latency-aware simulator that approximates an order-driven venue for energy-linked instruments.
- Instrument catalog. Use /symbols to bootstrap a local registry keyed by symbol with currency, category, and frequency. Add optional packaging (lot size, tick size) for your own execution rules.
- Data hydrator. Implement a loader module that can fetch /timeseries for historical backfills, /latest for recent snapshots, /electricity/hourly for intraday power curves, and /ohlc for volatility. Cache JSON responses on disk for reproducible runs.
- Clock and scheduler. Drive your simulation by symbol frequency: daily assets broadcast session-open events; hourly/15-min electricity curves broadcast per-interval events. Align multi-asset strategies by selecting a lead clock (e.g., hourly) and forward-fill daily series between session opens.
- Synthetic order book. For each symbol and time slice, build a ladder around the reference price (from /latest, /timeseries, or intraday curve). Scale ladder width using recent volatility from /ohlc: wider bands during high vol, tighter bands otherwise. Populate bid/ask depth asymmetrically when news-like moves are detected (e.g., sharp hour-on-hour jumps in electricity).
- Latency and jitter. Simulate network latency by sleeping a random number within a configured band when “publishing” updates to your matching engine. Apply additional jitter when /status indicates provider slowness, and document this in logs for audit.
- Matching and fills. When your strategy places a limit or market order, cross it against the synthetic book. For market orders, sweep multiple levels if volume requires. For limit orders, perform partial fills as the reference price trades through levels during replay.
- Risk and P&L. Translate positions into a reporting currency using currencies from responses. Revalue at each tick, roll realized/unrealized P&L, and store run artifacts (prices, orders, fills) with a run_id for reproducibility.
Implementation Examples: cURL, Python, JavaScript
Below are minimal data-ingestion snippets you can drop into your sandbox project. They focus on realistic developer ergonomics and observability.
cURL: Multi-asset latest snapshot
curl -G https://energy-api.com/api/v1/latest \
--data-urlencode "symbols=BRENT_CRUDE,TTF_GAS,EUA_CO2,COAL_ROTTERDAM" \
--data-urlencode "api_key=YOUR_API_KEY" \
--silent | jq '.'
Use this in a cron or Makefile step to hydrate nightly “warm start” snapshots.
Python: Historical backfill and intraday curves
import os
import json
import time
from datetime import datetime, timedelta
import requests
BASE = "https://energy-api.com/api/v1"
API_KEY = os.getenv("ENERGY_API_KEY")
def get_timeseries(symbols, start, end):
r = requests.get(f"{BASE}/timeseries", params={
"symbols": ",".join(symbols),
"start": start,
"end": end,
"api_key": API_KEY
}, timeout=30)
r.raise_for_status()
return r.json()
def get_hourly(symbol, date):
r = requests.get(f"{BASE}/electricity/hourly", params={
"symbol": symbol,
"date": date,
"api_key": API_KEY
}, timeout=30)
r.raise_for_status()
return r.json()
def persist(path, payload):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(payload, f, indent=2)
if __name__ == "__main__":
# Backfill gas/oil/carbon
symbols = ["TTF_GAS", "BRENT_CRUDE", "EUA_CO2"]
ts = get_timeseries(symbols, "2025-01-01", "2025-06-30")
persist("data/timeseries_gas_oil_carbon_2025H1.json", ts)
# Fetch intraday curve for OMIE day-ahead
date = "2026-06-11"
curve = get_hourly("OMIE_ES_DA", date)
persist(f"data/omie_hourly_{date}.json", curve)
# Thin jitter to emulate network delay during replay
time.sleep(0.150)
JavaScript: Lightweight fetch with provider health check
import fetch from "node-fetch";
const BASE = "https://energy-api.com/api/v1";
const API_KEY = process.env.ENERGY_API_KEY;
async function getLatest(symbols) {
const url = new URL(`${BASE}/latest`);
url.searchParams.set("symbols", symbols.join(","));
url.searchParams.set("api_key", API_KEY);
const res = await fetch(url.toString(), { timeout: 20000 });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function getStatus() {
const url = new URL(`${BASE}/status`);
url.searchParams.set("api_key", API_KEY);
const res = await fetch(url.toString(), { timeout: 10000 });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
(async () => {
const health = await getStatus();
const degraded = (health.providers || []).filter(p => p.status !== "ok");
if (degraded.length > 0) {
console.warn("Provider degradation detected:", degraded);
}
const snapshot = await getLatest(["EUA_CO2", "TTF_GAS", "BRENT_CRUDE"]);
console.log(JSON.stringify(snapshot, null, 2));
})();
Interpreting JSON Fields For Finance Scenarios
Energy API is designed to minimize glue code. Still, it pays to align each field with a finance use:
- success: Boolean gate for continuing a run. If false, stash the error and halt the strategy loop to preserve determinism.
- date, start_date, end_date: Use to align cross-asset windows and to index storage partitions for fast cold-start.
- rates (map): Numerics keyed by symbol and possibly date (in timeseries). Perfect to pump into a vectorized P&L calculator.
- frequencies: Non-UI metadata that prevents mis-sampling (daily vs hourly). Drive your scheduler with it.
- currencies: Keep with the price to avoid silent currency mix-ups in hedges and P&L.
- curve (array): Canonical representation of intraday slices. Convert each item into an order-book mid and expand to levels using vol-scaling.
- open, high, low, close (OHLC): Inputs for volatility and liquidity modeling.
Error Handling And Robustness
Trading sandboxes must be predictable. When building your ingestion and replay layers:
- Always check the success flag and validate that expected keys exist (e.g., that a requested symbol exists in the response).
- For historical requests, record the return window (start_date, end_date) and verify alignment with your backtest range. If official sources do not publish on weekends or holidays, expect gaps and decide whether to forward-fill or skip ticks.
- For electricity curves, validate all expected intervals (e.g., 24 hourly points for day-ahead) before replay; if a curve is incomplete, freeze the current simulation hour and log a diagnostic so results remain auditable.
- Use /status to adjust behavior when upstream sources are delayed. For latency-sensitive modules, widen spreads or switch to a conservative fill model during degraded health states.
Real-World Use Cases
Below are concrete projects teams ship with Energy API when building finance-grade tools.
- Cross-commodity price alerting and hedge prompts. Use /latest across BRENT_CRUDE, TTF_GAS, EUA_CO2, and COAL_ROTTERDAM to compute spreads and emit alerts when thresholds breach. When a spread trips, your sandbox triggers a simulated hedge order and measures slippage against intraday curves where relevant.
- Power portfolio P&L replay with hourly stress. Pull /electricity/hourly for OMIE_ES_DA and PVPC_ES_2TD and replay a retail portfolio’s exposure by the hour. Integrate /timeseries for correlated fuels (TTF_GAS) and /ohlc for vol-scaling. The sandbox outputs hour-by-hour realized/unrealized P&L and a margin timeline.
- ESG and carbon-cost overlays. Fetch EUA_CO2 from /latest and /timeseries, and combine with /carbon-intensity (e.g., CARBON_INT_DE) to estimate implied carbon cost per MWh for a geography. Your sandbox then marks an internal carbon price to power positions and tests enterprise reporting workflows end-to-end.
Frequently Asked Questions
How do I get the hourly curve for a specific day to test intraday execution?
Use GET /electricity/hourly with the symbol and date. The response includes a curve array with one entry per interval (hourly or 15-min). Loop through the entries to emit tick events in your simulator and match limit or market orders against a synthetic ladder around each price.
Can I query multiple commodities in one call for correlation or spread strategies?
Yes. GET /latest and GET /timeseries support comma-separated symbols across gas, oil, coal, carbon, and electricity. This makes it easy to compute cross-asset spreads and run a unified risk engine without stitching multiple provider formats.
How often does the TTF gas price update in Energy API?
Energy API normalizes official postings into a consistent daily cadence for TTF_GAS. Use /latest for the most recent value and /timeseries for historical tracking. Pair with /ohlc to compute volatility over weekly or monthly windows that inform your order book width.
What’s the difference between day-ahead power and retail PVPC hours for modeling?
Day-ahead (e.g., OMIE_ES_DA) represents wholesale auction results for the next day’s delivery hours. PVPC is a Spanish retail reference that varies hourly. For execution testing, treat day-ahead as your baseline wholesale curve and PVPC as a downstream reference to model retail-to-wholesale spreads and risk transfer.
How should I handle gaps like weekends or holidays in historical data?
Gaps are normal in official energy datasets. In a simulator, you can forward-fill last-known-good values or skip ticks entirely and advance the clock to the next published date. Record your choice in run metadata so downstream analytics interpret results consistently.
Putting It Together: A Sample Replay Flow
Below is a conceptual loop that glues Energy API data into a deterministic local replay with latency and fills. It demonstrates how to combine historical series, intraday curves, and vol-aware order book sizing.
# Pseudocode for a daily+hourly hybrid replay
load symbols: S = ["TTF_GAS", "BRENT_CRUDE", "EUA_CO2", "OMIE_ES_DA"]
# 1) Backfill daily assets for the window
daily = GET /timeseries { TTF_GAS, BRENT_CRUDE, EUA_CO2 } 2025-01-01..2025-01-31
# 2) For each day, fetch the intraday electricity curve
for date in daily.calendar:
curve = GET /electricity/hourly { OMIE_ES_DA, date }
# 3) Compute per-day volatility scalers from OHLC (monthly as proxy)
ohlc = GET /ohlc { TTF_GAS, BRENT_CRUDE } period=monthly
sigma = vol(ohlc["TTF_GAS"], ohlc["BRENT_CRUDE"]) # your function
# 4) Build synthetic order books per hour
for slice in curve.curve:
mid_power = slice.price
depth = scale_depth(mid_power, sigma) # vol-aware depth
book_power = make_book(mid_power, depth) # ladders
# 5) Replay strategy logic (hedge power with gas / carbon overlays)
signals = strategy(daily[date], mid_power, EUA_CO2_latest)
orders = route(signals)
# 6) Apply latency jitter
sleep(random(50ms..250ms))
# 7) Match orders against book, generate fills/partials
fills = match(orders, book_power)
# 8) Revalue P&L across commodities at end of slice
pnl = value(positions, [TTF_GAS[date], BRENT_CRUDE[date], mid_power])
log(slice.hour, fills, pnl)
With this structure, you can iterate quickly on strategy logic while keeping realistic mechanics for price formation and timing. Because Energy API uses one schema for all commodities, you avoid bespoke adapters and can focus on the trading math.
Additional Endpoints Worth Knowing
Complement your microstructure sandbox with category helpers and analytics:
- GET /electricity/latest: Pull all power symbols at once, optionally filtered by country, to sanity-check that your sandbox stays in sync with posted values.
- GET /gas/latest, GET /coal/latest, GET /emissions/latest: One-call snapshots for focused asset classes—useful for overnight batch risk.
- GET /fluctuation: Start/end values, absolute and percentage change across a window. Useful to triage big movers and select dates for higher-resolution replays.
- POST /cost-estimate: Quickly turn wholesale electricity prices into monthly bill cost estimates (kWh/month × latest price). Ideal for retail pricing simulations or pre-trade what-if analysis when building structured offers.
- GET /carbon-intensity: Add CARBON_INT_* overlays in gCO2eq/kWh by country, powering ESG-aware analytics and internal carbon pricing across portfolios.
Example: Fluctuation over a volatile week to pick stress days for replay.
curl -G https://energy-api.com/api/v1/fluctuation \
--data-urlencode "symbols=TTF_GAS,BRENT_CRUDE" \
--data-urlencode "start=2025-02-10" \
--data-urlencode "end=2025-02-17" \
--data-urlencode "api_key=YOUR_API_KEY"
Illustrative JSON:
{
"success": true,
"symbols": {
"TTF_GAS": {
"start_value": 49.10,
"end_value": 47.60,
"change": -1.50,
"change_pct": -3.06
},
"BRENT_CRUDE": {
"start_value": 81.90,
"end_value": 83.10,
"change": 1.20,
"change_pct": 1.47
}
}
}
Use change_pct to rank days for stress testing and widen simulated spreads proportionally during those sessions.
Field-by-Field Breakdown: Practical Use
To ensure you extract maximum value with minimal glue, here’s how to operationalize common fields from the endpoints featured above:
- symbol: The canonical identifier you should use everywhere (storage, logs, fills). Never alias symbols internally; keep them canonical to ease upgrades and audits.
- country_code: Drive region scoping (risk limits, local holidays) and policy overlays (carbon intensity).
- frequency and interval: Decide the event rate in the simulator (daily ticks vs hourly or 15-min). A mismatch here is the most common root cause of drift in P&L replays.
- currency_code / currencies: Keep this alongside prices and pass it to your risk/valuation layer. For cross-asset hedges, currency mismatches can silently erode P&L if ignored.
- curve (hourly/15-min): Stepwise updates to price. Use as mid-price seeds for each time-slice and expand them into a synthetic book using a volatility scaler and a depth model.
- ohlc open/high/low/close: Use to compute realistic slippage models per instrument and period. For monthly candles, recompute a liquidity index monthly to scale your simulator’s depth for that month.
- dates map (from /latest): Per-symbol publication dates help when consolidating mixed-frequency assets into one timeline for cross-asset strategies.
Performance And Observability Tips
To keep the sandbox fast and transparent:
- Cache responses on disk with content hashing (symbol + date + endpoint) for reproducibility and faster re-runs.
- Batch multi-asset requests with /latest and /timeseries to minimize network overhead and keep symbols aligned at the same wall-clock.
- Tag every run with a run_id and persist the raw JSON payloads you used. When a backtest looks surprising, diff payloads across runs before inspecting code changes.
- Add lightweight health gates using /status. If a provider shows delays, slow the replay and mark fills with a degraded_state=true tag to isolate their effect in analytics.
End-to-End Example: Intraday Power Hedge Against Gas
Let’s walk through a quick scenario: you run an intraday power book (OMIE_ES_DA) and hedge exposures with TTF_GAS. You want to test how your hedge performs hour by hour over a volatile week.
- Step 1: Pull TTF_GAS and BRENT_CRUDE /timeseries for the week to provide macro context and hedge reference. Persist as raw JSON.
- Step 2: For each day, fetch OMIE_ES_DA via /electricity/hourly. Build a synthetic order book per hour with a volatility scaler from /ohlc monthly candles for both TTF_GAS and BRENT_CRUDE.
- Step 3: Replay hour by hour: when OMIE mid changes, recalc your hedge (quantity derived from a fuel-switching coefficient). Route an order to your synthetic gas book and fill it with simulated slippage based on book depth and order size.
- Step 4: Log hourly P&L, including hedge cost and residual exposure. Graph it with timestamps from the curve to visually verify no hour skips occur.
This approach stress-tests a realistic flow without touching any live exchange gateways, yet remains grounded in official, normalized market data via Energy API.
Conclusion + CTA
The fastest path from a trading idea to a realistic execution test in energy markets is to remove the data drama. By standardizing across electricity, gas, oil, coal, carbon, and grid carbon intensity, Energy API lets you focus on microstructure logic—order books, latency, fills, and P&L—instead of writing one-off scrapers and reconcilers for every official source. The result is a local sandbox that behaves like a market: it replays hourly curves, aligns cross-asset quotes, and tolerates data delays with well-defined health gates.
If you build for procurement desks, trading teams, or ESG/finance platforms, you can wire up the endpoints above in hours and start validating strategies, risk rules, and reporting flows immediately. Bring in /latest for consolidated quoting, /timeseries for deterministic replays, /electricity/hourly for intraday realism, /ohlc for volatility-aware depth, and /status for circuit breakers. From there, scale to more symbols and countries without changing your integration pattern.
Build your sandbox today with Energy API and get from zero to production-grade energy data faster than ever. Ready to plug in your first strategy replay? Try Energy API for free.
Ready to get started?
Get your API key and start querying energy commodity prices in minutes.
Get API KeyRelated posts
Streamline developer onboarding with Energy API by creating a sandbox environment for rapid prototyping. Disco...
Read more →
Discover best practices for reducing trading latency with a Finance API. Learn how to optimize market data ing...
Read more →
Discover how to effectively benchmark intraday trading algorithms using Finance API market feeds and synthetic...
Read more →
Discover how to build a geo-fenced distributed energy resource orchestrator using Energy API and MQTT for low-...
Read more →
Discover how to build offline-first mobile apps for field technicians using Energy API. Enhance decision-makin...
Read more →