37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.
C avx2ccpu-inferenceggufinference-enginelinuxllmlocal-llmmixture-of-expertsmoenvmequantizationqwen3simdspeculative-decodingvulkan
Release 2026-10-02: janas-prices - prices and finance for information; the system message read ahead kept on disk again
camauri55014c02e9a8
diff --git a/ChangeLog.md b/ChangeLog.mdindex 9ae883e..5e5e126 100644--- a/ChangeLog.md+++ b/ChangeLog.md@@ -2,6 +2,13 @@> Curated, user-facing summary of completed work, newest first.+## [2026-10-02] - janas-prices: prices and finance, for information++- **janas-prices**, an MCP service for information only: an amount in other currencies at the ECB's reference rates (Frankfurter; the ECB's file when it does not answer), a crypto-asset's price (CoinGecko's keyless API; Coinbase when it does not answer), a share's (Alpha Vantage, with a free key of the user's: the only tool that needs one), inflation (Eurostat monthly for the EU, Iceland and Norway, the World Bank yearly for every other country), the rates of the ECB, the Fed, the Bank of England and the SNB, the wholesale price of electricity hour by hour (energy-charts, only the bidding zones it gives under CC BY: northern Italy yes, Sicily no), the cheapest fuel near a place (Italy's MIMIT, France's live flow, Spain's ministry, Austria's E-Control; another country is said not to be covered; a price not told for over eight days is left out and counted: a station's of two months before had come first in Palermo). Every answer says its source, its date, and "for information only, not advice". Layouts for every answer; `tests/test_prices_parse.c` on answers of 2 October.+- **The system message read ahead is kept on disk again**: since the services' tools are given when needed it is under a thousand tokens (767 with seven services), and copies under 1024 tokens were never written, so every start read it anew; a recurrent model's (Qwen3.6-35B-A3B) cannot be cut back from a longer conversation either. A read-ahead copy is now written from 64 tokens. Two starts in a row of `janas-chat` with a "Ciao", on a machine busy with other work: Qwen3.6-35B-A3B 21.6 s then 4.4 s, the second reading nothing again; Qwen3-4B 11.6 then 2.1 s; Qwen3.5-2B 6.3 then 1.4 s. `tests/llm_keep.c` checks a short system message too, and no longer leaves its cache directory behind.+- **Spain's fuel at the ministry's newer address**: the older one offers only TLS 1.2 with RSA's key exchange, which Mbed TLS 4 no longer has.+- **Places by Nominatim**: Open-Meteo's geocoding matches one language only ("Wien" was a place in the United States, "Milano" Milanówek in Poland).+## [2026-10-02] - janas-github and janas-git- **janas-github**, GitHub as an MCP service that only reads: a repository's issues and pull requests (`new`: those opened since the last time asked, kept in `~/.config/janas/github-seen.txt`), its latest releases (its tags when it has none), a branch's recent commits, what it is. A name alone is looked for among the user's repositories, else the one with the most stars, and the answer says which. The token of `GH_TOKEN`, `GITHUB_TOKEN` or `gh auth token`, kept in memory only; without one, 60 requests an hour. Layouts for every answer; `tests/test_github_parse.c` on answers of 2 October.diff --git a/README.md b/README.mdindex 6d06720..e413bf3 100644--- a/README.md+++ b/README.md@@ -55,6 +55,7 @@ Everything the engine does is chosen from what it measures, so another machine w- **`janas-flights`:** where a flight is and what flies over a sea or a place, as MCP tools, from the ADS-B receivers of the community, and today's schedules with a free AviationStack key: the first of Janas's services ([docs/services](docs/services/README.md)).- **`janas-weather`:** the weather now, with what the nearest station measured, the forecast, the sea and its waves, and the warnings in force (in Italy the Civil Protection's levels), from free sources with no key ([docs/services/weather.md](docs/services/weather.md)).- **`janas-maps`:** roads and places: a route by car, bike or on foot, step by step in your language, journeys by public transport, what is near (fuel, a pharmacy, a cash machine...), where an address is; OpenStreetMap's data through free services with no key ([docs/services/maps.md](docs/services/maps.md)).+- **`janas-prices`:** prices and finance, for information: currencies at the ECB's rates, crypto-assets, shares (with a free key of yours), inflation, central banks' rates, electricity where it is open data, the cheapest fuel near a place in Italy, France, Spain and Austria ([docs/services/prices.md](docs/services/prices.md)).- **`janas-github`:** a project on GitHub: its issues and pull requests (the new ones since you last asked), its latest releases, its recent commits, what it is; it only reads, with the gh command's token when you have one ([docs/services/github.md](docs/services/github.md)).- **`janas-git`:** the git repositories of your computer: what has changed, the commits, the branches, a diff; and a commit, pull, push or switch of branch, each shown whole and asked of you first; nothing that throws work away ([docs/services/git.md](docs/services/git.md)).- **`janas-wiki`:** Wikipedia when you ask for it: its search, a page shown to you as it is (the introduction, then the section asked for) while the model reads only a note of it, and the pages about what lies around a place ([docs/services/wiki.md](docs/services/wiki.md)).@@ -297,7 +298,7 @@ printf 'Explain mixture of experts in one paragraph.\n/quit\n' \### Janas's services-The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).+The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-prices`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?", "where is diesel cheapest near here?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).**The services' tools are given when they are needed.** Written into the system message, the tools of three services made it four thousand tokens, over a minute of a large model before the first message, and every service more made it longer. The system message now holds a catalog, a line a service, and the model opens a service when a question needs it: that service's instructions and tools come back as the answer of the call, its tools can be called from then on, and the next reply is held to be a call (a small model told to call one made the answer up instead). With Qwen3.6-35B-A3B the system message went from 4,057 tokens to 616, and opening the weather costs about a thousand tokens, once in a conversation, when the first question about the weather comes. `--all-tools` writes them all into the system message as before.@@ -599,6 +600,7 @@ It stands on the work of others, and says so:- **`janas-flights`** reads the positions of aircraft from [adsb.lol](https://adsb.lol) (data under the Open Database License) and [adsb.fi](https://adsb.fi), routes from [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's, schedules from [AviationStack](https://aviationstack.com); its tables of places are built from [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0) and [Natural Earth](https://www.naturalearthdata.com) (public domain).- **`janas-weather`** reads forecasts and the sea from [Open-Meteo](https://open-meteo.com) (CC BY 4.0) and [MET Norway](https://api.met.no) (CC BY 4.0), the stations' reports from [aviationweather.gov](https://aviationweather.gov) (NOAA), warnings from [MeteoAlarm](https://meteoalarm.org) (EUMETNET) and the Italian alert levels from the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica) (CC BY 4.0). With no place named, the services ask [GeoJS](https://www.geojs.io) or [ipwho.is](https://ipwho.is) where the internet connection is.- **`janas-maps`** reads [OpenStreetMap](https://www.openstreetmap.org)'s data (© OpenStreetMap contributors, ODbL) through [Nominatim](https://nominatim.org), [Photon](https://photon.komoot.io), [Valhalla](https://github.com/valhalla/valhalla) and [OSRM](https://project-osrm.org) on the servers of [FOSSGIS](https://fossgis.de), and the [Overpass API](https://overpass-api.de) (with [Private.coffee's instance](https://overpass.private.coffee) when it is busy), and journeys by public transport from [Transitous](https://transitous.org), over the operators' open timetables.+- **`janas-prices`** reads the [European Central Bank](https://www.ecb.europa.eu) (through [Frankfurter](https://frankfurter.dev)), [CoinGecko](https://www.coingecko.com/en/api) (data provided by CoinGecko) and [Coinbase](https://www.coinbase.com), [Alpha Vantage](https://www.alphavantage.co) with the user's key, [Eurostat](https://ec.europa.eu/eurostat) and the [World Bank](https://data.worldbank.org) (CC BY 4.0), the [New York Fed](https://www.newyorkfed.org), the [Bank of England](https://www.bankofengland.co.uk) and the [Swiss National Bank](https://data.snb.ch), [energy-charts.info](https://www.energy-charts.info) (Fraunhofer ISE; the zones under CC BY 4.0, from the Bundesnetzagentur's SMARD), and the fuel prices of Italy's [MIMIT](https://www.mimit.gov.it) (IODL 2.0), France's [prix-carburants](https://data.economie.gouv.fr), Spain's [ministry](https://energia.serviciosmin.gob.es) and Austria's [E-Control](https://www.e-control.at); places through [Nominatim](https://nominatim.org).- **`janas-github`** reads [GitHub](https://github.com)'s REST API; **`janas-git`** runs [git](https://git-scm.com).- **`janas-wiki`** reads [Wikipedia](https://www.wikipedia.org) through its API; the text is Wikipedia's, under CC BY-SA 4.0, and every answer gives the page's address.- **The people who tried it on their own machines** and reported what they saw, in the issues of this repository: their reports changed the engine more than once (the threads it picks, the prompt's progress, the GPU's diagnosis).diff --git a/docs/services/README.md b/docs/services/README.mdindex c10a903..04a8398 100644--- a/docs/services/README.md+++ b/docs/services/README.md@@ -1,6 +1,6 @@# Janas's services-A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, GitHub's projects, the git repositories of your computer - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.+A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, prices and finance, GitHub's projects, the git repositories of your computer - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.| Service | What it answers | Key ||---|---|---|@@ -8,6 +8,7 @@ A service of Janas is a program that brings data of the world - flights, the wea| [`janas-git`](git.md) | the git repositories of this computer: what has changed, the commits, the branches, a diff; a commit, pull, push or switch of branch, each asked of you first | none || [`janas-github`](github.md) | a project's issues and pull requests (the new ones), its latest releases, its recent commits, what it is | none; the gh command's token when you have one || [`janas-maps`](maps.md) | a route by car, bike or on foot, step by step; journeys by public transport; what is near a place; where an address is | none |+| [`janas-prices`](prices.md) | for information: currencies, crypto-assets, shares, inflation, central banks' rates, electricity, the cheapest fuel near a place | none; a free one of your own for shares || [`janas-weather`](weather.md) | the weather now (a model's and a station's), the forecast, the sea and its waves, the warnings in force | none || [`janas-wiki`](wiki.md) | Wikipedia's search, its pages as text, the pages about what lies around a place | none |diff --git a/docs/services/prices.md b/docs/services/prices.mdnew file mode 100644index 0000000..0cb718a--- /dev/null+++ b/docs/services/prices.md@@ -0,0 +1,67 @@+# janas-prices++Prices and finance for `janas-chat` or any other MCP client (see [the services](README.md)), for information only: what a currency is worth, a crypto-asset, a share, inflation, a central bank's rates, the wholesale price of electricity, the cheapest fuel near a place. Open data without a key, for as many countries as each kind of data covers; only shares need a free key of yours.++## The tools++- **`prices_currency`** - an amount (`amount`, 1 unless asked) from a currency (`from`, EUR unless asked) into others (`to`: USD,GBP,CHF,JPY unless asked), at the ECB's reference rates of the latest working day or of a day (`date`).+- **`prices_crypto`** - a crypto-asset's price (`coin`: a name or a symbol), in a currency (`currency`, EUR unless asked), its change in 24 hours and its market value.+- **`prices_stock`** - a share's last price (`share`: a symbol, AAPL or TSCO.LON, or a company's name), its change, the day's open, high and low, the previous close; with a key of Alpha Vantage only.+- **`prices_inflation`** - a country's inflation (`country`: an ISO code, EA for the euro area; the user's country unless asked): the last thirteen months for the European Union, Iceland and Norway, the last years for every other country.+- **`prices_rates`** - a central bank's rates (`bank`: `ecb`, `fed`, `boe`, `snb`; the user's country's unless asked): the ECB's deposit facility, main refinancing operations, marginal lending facility and €STR, the Fed's effective federal funds rate and target range, the Bank of England's Bank Rate, the Swiss National Bank's policy rate.+- **`prices_electricity`** - the wholesale price of electricity for the next day, hour by hour, for a place's bidding zone (`place`, where the user is unless asked), today or tomorrow (`day`): the price on the exchange, before taxes and charges.+- **`prices_fuel`** - the cheapest stations within a radius of a place (`radius`, 5 km unless asked, 20 at most) for a fuel (`fuel`: petrol, diesel, lpg, cng), their prices, how far and which way, when the price was told; how many stations there are and the area's average.++## The answers++Every answer is data with a layout (see [the services](README.md)): `janas-chat` shows the user the whole of it in the user's language - every rate, month, hour or station - and gives the model only a brief, from which it answers in a line or two. Every answer says where its figures come from, their date, and that they are for information only, not advice to buy or sell.++## Where the data comes from++| Data | Source | Countries | Key |+|---|---|---|---|+| currencies | the [European Central Bank](https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html)'s reference rates, through [Frankfurter](https://frankfurter.dev); the ECB's own file when Frankfurter does not answer | the thirty or so currencies the ECB quotes | none |+| crypto-assets | [CoinGecko](https://www.coingecko.com/en/api)'s keyless API (data provided by CoinGecko); [Coinbase](https://www.coinbase.com)'s spot price when it does not answer | - | none |+| shares | [Alpha Vantage](https://www.alphavantage.co) | the exchanges it covers | a free one of yours |+| inflation | [Eurostat](https://ec.europa.eu/eurostat)'s harmonised index of consumer prices (monthly), the [World Bank](https://data.worldbank.org) (yearly, CC BY 4.0) | Eurostat: the EU, Iceland, Norway, the euro area; the World Bank: every other | none |+| central banks | the [ECB](https://data.ecb.europa.eu), the [New York Fed](https://www.newyorkfed.org/markets/reference-rates/effr), the [Bank of England](https://www.bankofengland.co.uk/boeapps/database/), the [Swiss National Bank](https://data.snb.ch) | euro area, United States, United Kingdom, Switzerland | none |+| electricity | [energy-charts.info](https://www.energy-charts.info) (Fraunhofer ISE) | the bidding zones it gives under CC BY 4.0 | none |+| fuel | Italy: the [Ministry of Enterprises (MIMIT)](https://www.mimit.gov.it/it/open-data/elenco-dataset/carburanti-prezzi-praticati-e-anagrafica-degli-impianti) (IODL 2.0), a day's prices; France: [prix-carburants](https://data.economie.gouv.fr/explore/dataset/prix-des-carburants-en-france-flux-instantane-v2/), live; Spain: the [Ministry for the Ecological Transition](https://energia.serviciosmin.gob.es/ServiciosRestCarburantes/PreciosCarburantes/help); Austria: [E-Control](https://www.e-control.at)'s fuel price calculator | Italy, France, Spain, Austria | none |+| places | [Nominatim](https://nominatim.org) (OpenStreetMap), the built-in tables when it does not answer | - | none |++- **Electricity only where it is open data.** energy-charts gives with each zone's prices their licence: the zones whose prices come from the Bundesnetzagentur's SMARD under CC BY 4.0 are given (on 2 October 2026: Germany-Luxembourg, Austria, Belgium, France, the Netherlands, northern Italy, among those tried); the others' are for private and internal use only, and the answer says they are not open data (Sicily, Spain, among those tried). The zone of an Italian place is its region's; that of a Nordic country's place is guessed from the point.+- **Fuel is as the stations tell it.** Italy's prices are those of the morning file, each with the time the station told it; France's are live, and some are weeks old (their date says so); Spain's are the ministry's of the moment; Austria's are those E-Control gives for a point: some of the stations near it, the cheapest. The stations' addresses are as their operators gave them. No other country publishes every station's prices as open data that `janas-prices` reads: the answer says so.+- **The sources' rules are kept.** A User-Agent naming the program, a pause between two requests to a server (three seconds for energy-charts, which refuses more), answers kept a while (rates an hour, crypto-assets two minutes, Italy's files three hours). CoinGecko asks to be credited: every answer of it says "Data provided by CoinGecko". The licence of E-Control's interface is not stated on its pages; it is called a public interface.+- **No source run from Russia or China.**++## Shares: the key++Alpha Vantage gives a free key ("it takes fewer than 20 seconds", it says): <https://www.alphavantage.co/support/#api-key>. Put it in `~/.config/janas/prices.conf`:++```+alphavantage_key = YOUR_KEY+```++or in `JANAS_ALPHAVANTAGE_KEY`. The free key allows 25 requests a day (Alpha Vantage lifts the limit for verified open-source projects); a question costs one or two. Without a key, `prices_stock` answers how to get one. The prices may be delayed.++## Running it++```sh+janas-prices [--config FILE]+```++It speaks MCP over its standard input and output and writes what it does on its standard error. In other clients:++```sh+claude mcp add prices -- /path/to/janas-prices+```++```json+{"mcpServers": {"prices": {"command": "/path/to/janas-prices"}}}+```++## What has been run++2 October 2026, over the protocol, in the release and AddressSanitizer builds, without a key of Alpha Vantage: 100 euros in dollars, pounds and francs, dollars into euros and yen on 15 January 2026, pounds into euros and dollars; Bitcoin, Solana in dollars, Dogecoin, a crypto-asset that does not exist; inflation in Italy, Greece, the euro area (Eurostat), the United States and Japan (the World Bank); the rates of the ECB, the Fed, the Bank of England and the SNB; electricity in Milan, Berlin (tomorrow) and Paris, refused for Palermo (not open data); diesel in Trapani, Madrid and Vienna, petrol in Paris, Barcelona and where the user is (Palermo), LPG in Milan and Lyon, methane near Trapani (none within 15 km) and in Paris (not in France's data), LPG in Graz (not in Austria's), diesel in London (not covered); a share without a key (the answer says how to get one). The quotes of Alpha Vantage have been read only with its public demo key (IBM).++In `janas-chat` with Qwen3.6-35B-A3B, the same day, in Italian: 100 euros in dollars and pounds, Bitcoin now, inflation in Italy, the cheapest diesel near the user (Palermo, by GeoJS), electricity in Milan today, the ECB's rates, Apple's share without a key (the model told how to get one). The first run showed a station's price of two months before as the cheapest (prices older than eight days are now left out, and counted), "rates" translated as speeds, and the sources' names left in English; run again, the answers came whole in Italian.diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.cindex f9bf456..d894a9c 100644--- a/src/chat/mcp_chat.c+++ b/src/chat/mcp_chat.c@@ -47,6 +47,9 @@ static const struct {{"maps", "roads and places: a route by car, bike or on foot, public ""transport between places, what is near (fuel, a pharmacy...), ""where an address is"},+ {"prices", "prices and finance, for information: currencies, "+ "crypto-assets, shares, inflation, central banks' rates, "+ "electricity, the cheapest fuel near a place"},{"weather", "the weather now and the forecast, the sea and its waves, ""weather warnings"},{"wiki", "Wikipedia, when the user asks for it: a page shown to the "diff --git a/src/llm/api_keep_disk.c b/src/llm/api_keep_disk.cindex c781784..dbb7115 100644--- a/src/llm/api_keep_disk.c+++ b/src/llm/api_keep_disk.c@@ -30,8 +30,14 @@#include "llm/jns.h"#include "llm/chat.h"-/* shorter copies are not worth a file: reading them again is quick */+/* shorter copies are not worth a file: reading them again is quick. Not+ so the system message read ahead (a prefix), read again at every start:+ since the services' tools are given when needed it is under a thousand+ tokens (767 with seven services), and kept by DISK_MIN it was never+ written - 14 s of Qwen3.6-35B-A3B at each start, and a conversation of+ a recurrent model cannot be cut back to it. */#define DISK_MIN 1024+#define DISK_MIN_PREFIX 64static int path_of(const janas_llm_chat *c, const char *name, char *buf,size_t len)@@ -232,7 +238,7 @@ void janas_api_disk_put(janas_llm_chat *c, const struct janas_llm_saved *sv,{const int32_t *tok;uint32_t n_kv, n = janas_llm_saved_tokens(sv, &tok, &n_kv);- if (!c->disk_dir || n_kv < DISK_MIN)+ if (!c->disk_dir || n_kv < (prefix ? DISK_MIN_PREFIX : DISK_MIN))return;uint64_t h = janas_fnv1a(tok, n * sizeof(int32_t), JANAS_FNV_INIT);h = janas_fnv1a(&n_kv, sizeof(n_kv), h);diff --git a/src/prices/data.c b/src/prices/data.cnew file mode 100644index 0000000..1bb1737--- /dev/null+++ b/src/prices/data.c@@ -0,0 +1,246 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * data.c - what janas-prices read, as the data of its layouts (see+ * prices.h, layouts.c and common/template.h). Every field is written,+ * even empty: a layout looks a name up in the item, then in what holds it.+ * Numbers keep the decimals a price of their size needs.+ */+#include <math.h>+#include <stdio.h>+#include <string.h>+#include <time.h>++#include "common/geo.h"+#include "prices.h"++void pr_jstr(struct janas_buf *b, const char *key, const char *v)+{+ if (!v)+ v = "";+ janas_buf_printf(b, ", \"%s\": ", key);+ janas_json_write_str(b, v, strlen(v));+}++/* NAN as 0 with "has_<key>": false, so that a layout can leave it out */+void pr_jnum(struct janas_buf *b, const char *key, double v, int decimals)+{+ janas_buf_printf(b, ", \"%s\": %.*f, \"has_%s\": %s", key, decimals,+ isnan(v) ? 0 : v, key, isnan(v) ? "false" : "true");+}++int pr_decimals(double v)+{+ v = fabs(v);+ return v >= 1 ? 2 : v >= 0.01 ? 4 : 6;+}++void pr_jplace(struct janas_buf *b, const char *key, const struct pr_place *p)+{+ janas_buf_printf(b, ", \"%s\": {\"name\": ", key);+ janas_json_write_str(b, p->name, strlen(p->name));+ pr_jstr(b, "country", p->country);+ pr_jstr(b, "how", p->how);+ janas_buf_puts(b, "}");+}++/* a moment in the computer's zone: "2 October, 14:05" in parts */+static void jtime(struct janas_buf *b, const char *key, time_t t)+{+ struct tm lt;+ if (t <= 0) {+ janas_buf_printf(b, ", \"%s\": {\"day\": 0, \"mon\": 0, \"at\": \"\"}",+ key);+ return;+ }+ localtime_r(&t, <);+ janas_buf_printf(b,+ ", \"%s\": {\"day\": %d, \"mon\": %d, \"at\": "+ "\"%02d:%02d\"}",+ key, lt.tm_mday, lt.tm_mon + 1, lt.tm_hour, lt.tm_min);+}++/* "2026-10-02" as day and month; "2026-08" as month and year */+static void jdate(struct janas_buf *b, const char *key, const char *d)+{+ int y = 0, m = 0, day = 0;+ int k = d ? sscanf(d, "%d-%d-%d", &y, &m, &day) : 0;+ janas_buf_printf(b, ", \"%s\": {\"day\": %d, \"mon\": %d, \"year\": %d}",+ key, k == 3 ? day : 0, k >= 2 ? m : 0, k >= 1 ? y : 0);+}++void pr_fx_data(struct janas_buf *b, double amount, const char *from,+ const struct pr_fx *fx, const char *source)+{+ janas_buf_puts(b, "{\"from\": ");+ janas_json_write_str(b, from, strlen(from));+ pr_jnum(b, "amount", amount, 2);+ jdate(b, "date", fx->date);+ pr_jstr(b, "source", source);+ janas_buf_puts(b, ", \"items\": [");+ for (int i = 0; i < fx->n; i++) {+ janas_buf_printf(b, "%s{\"code\": ", i ? ", " : "");+ janas_json_write_str(b, fx->r[i].code, strlen(fx->r[i].code));+ pr_jnum(b, "rate", fx->r[i].rate,+ fx->r[i].rate >= 100 ? 2+ : fx->r[i].rate < 0.1 ? 6+ : 4);+ pr_jnum(b, "value", amount * fx->r[i].rate, 2);+ janas_buf_puts(b, "}");+ }+ janas_buf_puts(b, "]}");+}++void pr_coin_data(struct janas_buf *b, const struct pr_coin *c,+ const char *source)+{+ janas_buf_puts(b, "{\"name\": ");+ janas_json_write_str(b, c->name, strlen(c->name));+ pr_jstr(b, "symbol", c->symbol);+ pr_jstr(b, "cur", c->cur);+ pr_jnum(b, "price", c->price,+ pr_decimals(c->price) > 2 ? pr_decimals(c->price) : 2);+ pr_jnum(b, "change", c->change_24h, 2);+ janas_buf_printf(b, ", \"up\": %s",+ !isnan(c->change_24h) && c->change_24h >= 0 ? "true"+ : "false");+ pr_jnum(b, "cap_bn", isnan(c->cap) ? NAN : c->cap / 1e9, 1);+ jtime(b, "at", c->at);+ pr_jstr(b, "source", source);+ janas_buf_puts(b, "}");+}++void pr_quote_data(struct janas_buf *b, const struct pr_quote *q)+{+ janas_buf_puts(b, "{\"symbol\": ");+ janas_json_write_str(b, q->symbol, strlen(q->symbol));+ pr_jstr(b, "name", q->name);+ pr_jstr(b, "region", q->region);+ pr_jstr(b, "currency", q->currency);+ int dec = pr_decimals(q->price) > 2 ? 3 : 2;+ pr_jnum(b, "price", q->price, dec);+ pr_jnum(b, "open", q->open, dec);+ pr_jnum(b, "high", q->high, dec);+ pr_jnum(b, "low", q->low, dec);+ pr_jnum(b, "prev", q->prev, dec);+ pr_jnum(b, "change", q->change, dec);+ pr_jnum(b, "pct", q->change_pct, 2);+ janas_buf_printf(b, ", \"up\": %s, \"volume\": %ld",+ !isnan(q->change) && q->change >= 0 ? "true" : "false",+ q->volume < 0 ? 0 : q->volume);+ jdate(b, "day", q->day);+ janas_buf_puts(b, "}");+}++void pr_series_data(struct janas_buf *b, const char *what, const char *who,+ const struct pr_series *s, int last, const char *source,+ const char *note, const char *licence)+{+ janas_buf_puts(b, "{\"what\": ");+ janas_json_write_str(b, what, strlen(what));+ pr_jstr(b, "who", who);+ pr_jstr(b, "label", s->label);+ pr_jstr(b, "unit", s->unit);+ pr_jstr(b, "source", source);+ pr_jstr(b, "note", note);+ pr_jstr(b, "licence", licence);+ int from = s->n > last ? s->n - last : 0;+ double lo = NAN, hi = NAN, sum = 0;+ int ilo = -1, ihi = -1, k = 0;+ for (int i = from; i < s->n; i++) {+ if (isnan(lo) || s->p[i].v < lo)+ lo = s->p[i].v, ilo = i;+ if (isnan(hi) || s->p[i].v > hi)+ hi = s->p[i].v, ihi = i;+ sum += s->p[i].v;+ k++;+ }+ int dec = 1;+ for (int i = from; i < s->n; i++) /* as many as the values need */+ if (fabs(s->p[i].v * 100 - round(s->p[i].v * 100)) > 1e-6)+ dec = 3;+ else if (dec < 2 && fabs(s->p[i].v * 10 - round(s->p[i].v * 10)) > 1e-6)+ dec = 2;+ if (s->n) {+ janas_buf_puts(b, ", \"last\": {\"when\": ");+ janas_json_write_str(b, s->p[s->n - 1].when,+ strlen(s->p[s->n - 1].when));+ pr_jnum(b, "v", s->p[s->n - 1].v, dec);+ janas_buf_puts(b, "}");+ }+ pr_jnum(b, "min", lo, dec);+ pr_jstr(b, "min_when", ilo >= 0 ? s->p[ilo].when : "");+ pr_jnum(b, "max", hi, dec);+ pr_jstr(b, "max_when", ihi >= 0 ? s->p[ihi].when : "");+ pr_jnum(b, "avg", k ? sum / k : NAN, dec);+ janas_buf_puts(b, ", \"items\": [");+ for (int i = from; i < s->n; i++) {+ janas_buf_printf(b, "%s{\"when\": ", i > from ? ", " : "");+ janas_json_write_str(b, s->p[i].when, strlen(s->p[i].when));+ pr_jnum(b, "v", s->p[i].v, dec);+ janas_buf_puts(b, "}");+ }+ janas_buf_puts(b, "]}");+}++void pr_rates_data(struct janas_buf *b, const char *bank,+ const struct pr_rate *r, int n, double lo, double hi,+ const char *source)+{+ janas_buf_puts(b, "{\"bank\": ");+ janas_json_write_str(b, bank, strlen(bank));+ pr_jstr(b, "source", source);+ janas_buf_printf(b, ", \"range\": %s",+ isnan(lo) || isnan(hi) ? "false" : "true");+ pr_jnum(b, "lo", lo, 2);+ pr_jnum(b, "hi", hi, 2);+ janas_buf_puts(b, ", \"items\": [");+ for (int i = 0; i < n; i++) {+ janas_buf_printf(b, "%s{\"name\": ", i ? ", " : "");+ janas_json_write_str(b, r[i].name, strlen(r[i].name));+ pr_jnum(b, "v", r[i].v, r[i].v * 100 == round(r[i].v * 100) ? 2 : 3);+ jdate(b, "when", r[i].when);+ janas_buf_puts(b, "}");+ }+ janas_buf_puts(b, "]}");+}++void pr_fuel_data(struct janas_buf *b, const struct pr_place *p,+ const char *kind, double radius, const struct pr_fuel *f,+ const char *source)+{+ janas_buf_puts(b, "{\"kind\": ");+ janas_json_write_str(b, kind, strlen(kind));+ pr_jplace(b, "place", p);+ pr_jstr(b, "fuel", f->fuel);+ pr_jstr(b, "unit", strcmp(kind, "cng") == 0 ? "€/kg" : "€/l");+ pr_jstr(b, "source", source);+ janas_buf_printf(b,+ ", \"radius\": %g, \"found\": %d, \"shown\": %d, "+ "\"stale\": %d, \"stale_days\": %d",+ radius, f->found, f->n, f->stale, PR_STALE_DAYS);+ pr_jnum(b, "cheapest", f->cheapest, 3);+ pr_jnum(b, "average", f->average, 3);+ janas_buf_puts(b, ", \"items\": [");+ for (int i = 0; i < f->n; i++) {+ const struct pr_station *s = &f->s[i];+ janas_buf_printf(b, "%s{\"name\": ", i ? ", " : "");+ janas_json_write_str(b, s->name, strlen(s->name));+ pr_jstr(b, "address", s->address);+ pr_jstr(b, "city", s->city);+ pr_jnum(b, "price", s->price, 3);+ if (s->km >= 1)+ janas_buf_printf(b, ", \"km\": %.1f, \"m\": 0", s->km);+ else+ janas_buf_printf(b, ", \"km\": 0, \"m\": %.0f",+ fmax(10, round(s->km * 100) * 10));+ pr_jstr(b, "dir",+ geo_compass(geo_bearing(p->lat, p->lon, s->lat, s->lon)));+ janas_buf_printf(b, ", \"self\": %s, \"served\": %s",+ s->self == 1 ? "true" : "false",+ s->self == 0 ? "true" : "false");+ pr_jstr(b, "updated", s->updated);+ janas_buf_puts(b, "}");+ }+ janas_buf_puts(b, "]}");+}diff --git a/src/prices/fetch.c b/src/prices/fetch.cnew file mode 100644index 0000000..5c6a106--- /dev/null+++ b/src/prices/fetch.c@@ -0,0 +1,173 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * fetch.c - janas-prices asks its sources (see prices.h): a User-Agent+ * naming the program, a pause between two requests to the same server,+ * the answers kept a while (a day's rates, an hour's prices, two minutes+ * of a crypto-asset's), so that a question asked again costs the sources+ * nothing. The key of Alpha Vantage, when the user has one, is read here+ * and never written anywhere.+ */+#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "common/https_get.h"+#include "prices.h"++#ifndef JANAS_VERSION+#define JANAS_VERSION "unknown"+#endif++#define N_KEPT 32+#define N_HOSTS 12++static struct {+ char *url;+ time_t at;+ int keep_s;+ struct janas_buf body;+} kept[N_KEPT];++static struct {+ char host[96];+ struct timespec last;+} hosts[N_HOSTS];++static char key[128];++static double since(const struct timespec *t)+{+ struct timespec now;+ clock_gettime(CLOCK_MONOTONIC, &now);+ return (double)(now.tv_sec - t->tv_sec) ++ (double)(now.tv_nsec - t->tv_nsec) * 1e-9;+}++static void pace(const char *url, double pause_s)+{+ const char *h = strstr(url, "://");+ h = h ? h + 3 : url;+ size_t n = strcspn(h, "/?:");+ int slot = -1, empty = -1;+ for (int i = 0; i < N_HOSTS && slot < 0; i++) {+ if (strlen(hosts[i].host) == n && strncmp(hosts[i].host, h, n) == 0)+ slot = i;+ else if (empty < 0 && !hosts[i].host[0])+ empty = i;+ }+ if (slot >= 0) {+ double wait = pause_s - since(&hosts[slot].last);+ if (wait > 0 && wait <= pause_s) {+ struct timespec ts = {.tv_sec = (time_t)wait};+ ts.tv_nsec = (long)((wait - (double)ts.tv_sec) * 1e9);+ nanosleep(&ts, NULL);+ }+ } else {+ slot = empty >= 0 ? empty : 0;+ snprintf(hosts[slot].host, sizeof hosts[slot].host, "%.*s", (int)n, h);+ }+ clock_gettime(CLOCK_MONOTONIC, &hosts[slot].last);+}++int pr_fetch(const char *url, int keep_s, int timeout_ms, double pause_s,+ struct janas_buf *out, char *err, size_t err_len)+{+ time_t now = time(NULL);+ int slot = 0;+ for (int i = 0; i < N_KEPT; i++) {+ if (kept[i].url && strcmp(kept[i].url, url) == 0 &&+ now - kept[i].at < kept[i].keep_s) {+ out->n = 0;+ janas_buf_put(out, kept[i].body.p, kept[i].body.n);+ janas_buf_put(out, "", 1);+ out->n--;+ return out->oom ? -1 : 200;+ }+ if (kept[i].at < kept[slot].at)+ slot = i;+ }+ static const char *const agent[] = {+ "User-Agent: janas-prices/" JANAS_VERSION+ " (+https://github.com/prabanta-dev/janas)"};+ pace(url, pause_s);+ int status =+ janas_https_get_ms(url, agent, 1, timeout_ms, out, err, err_len);+ if (status == 200 && !out->oom && keep_s > 0) {+ free(kept[slot].url);+ janas_buf_free(&kept[slot].body);+ kept[slot].url = strdup(url);+ kept[slot].at = now;+ kept[slot].keep_s = keep_s;+ janas_buf_put(&kept[slot].body, out->p, out->n);+ }+ return status;+}++void pr_fetch_free(void)+{+ for (int i = 0; i < N_KEPT; i++) {+ free(kept[i].url);+ janas_buf_free(&kept[i].body);+ }+ memset(kept, 0, sizeof kept);+ memset(key, 0, sizeof key);+}++void pr_url_put(struct janas_buf *b, const char *s)+{+ static const char hex[] = "0123456789ABCDEF";+ for (; *s; s++) {+ unsigned char c = (unsigned char)*s;+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')+ janas_buf_put(b, (const char *)&c, 1);+ else {+ char e[3] = {'%', hex[c >> 4], hex[c & 15]};+ janas_buf_put(b, e, 3);+ }+ }+}++/* A key is letters and digits: anything else is not one */+static void take(const char *s)+{+ size_t n = 0;+ while (s && isalnum((unsigned char)s[n]) && n + 1 < sizeof key)+ n++;+ if (n >= 8) {+ memcpy(key, s, n);+ key[n] = 0;+ }+}++void pr_key_config(const char *path)+{+ key[0] = 0;+ take(getenv("JANAS_ALPHAVANTAGE_KEY"));+ if (key[0] || !path)+ return;+ FILE *f = fopen(path, "r");+ if (!f)+ return;+ char line[512];+ while (!key[0] && fgets(line, sizeof line, f)) {+ if (strncmp(line, "alphavantage_key", 16) != 0)+ continue;+ const char *v = strchr(line, '=');+ if (v) {+ v++;+ while (*v == ' ' || *v == '\t')+ v++;+ take(v);+ }+ }+ memset(line, 0, sizeof line);+ fclose(f);+}++const char *pr_key(void)+{+ return key[0] ? key : NULL;+}diff --git a/src/prices/fuel.c b/src/prices/fuel.cnew file mode 100644index 0000000..770f13d--- /dev/null+++ b/src/prices/fuel.c@@ -0,0 +1,164 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * fuel.c - janas-prices' fuel stations near a place (see prices.h), from+ * the open data of the countries that publish their stations' prices:+ * Italy (MIMIT, a day's prices, IODL 2.0), France (the instant flow,+ * Licence Ouverte), Spain (the ministry's stations, by province) and+ * Austria (E-Control's fuel price calculator). The place's country picks+ * the source; another country is said to be not covered.+ */+#include <stdio.h>+#include <string.h>+#include <time.h>++#include "prices.h"++#define MS 60000+#define IT_KEEP_S (3 * 3600) /* the files change once a day */+#define FR_KEEP_S 600+#define ES_KEEP_S 1800+#define AT_KEEP_S 600++static int italy(const struct pr_fuel_ask *a, struct pr_fuel *f, char *err,+ size_t err_len)+{+ struct janas_buf reg = {0}, pri = {0};+ int ok =+ pr_fetch("https://www.mimit.gov.it/images/exportCSV/"+ "anagrafica_impianti_attivi.csv",+ IT_KEEP_S, MS, 1, ®, err, err_len) == 200 &&+ pr_fetch("https://www.mimit.gov.it/images/exportCSV/"+ "prezzo_alle_8.csv",+ IT_KEEP_S, MS, 1, &pri, err, err_len) == 200 &&+ pr_read_fuel_it(reg.p, reg.n, pri.p, pri.n, a, f, err, err_len) == 0;+ janas_buf_free(®);+ janas_buf_free(&pri);+ return ok ? 0 : -1;+}++static int france(const struct pr_fuel_ask *a, struct pr_fuel *f, char *err,+ size_t err_len)+{+ static const char *const field[] = {"e10_prix", "gazole_prix", "gplc_prix",+ NULL};+ if (!field[a->kind]) {+ snprintf(err, err_len, "France's open data has no price of methane");+ return -1;+ }+ char where[300];+ snprintf(where, sizeof where,+ "within_distance(geom, geom'POINT(%.5f %.5f)', %.1fkm) and %s "+ "is not null",+ a->lon, a->lat, a->radius_km, field[a->kind]);+ struct janas_buf url = {0}, body = {0};+ janas_buf_puts(&url, "https://data.economie.gouv.fr/api/explore/v2.1/"+ "catalog/datasets/"+ "prix-des-carburants-en-france-flux-instantane-v2/"+ "records?where=");+ pr_url_put(&url, where);+ janas_buf_printf(&url, "&order_by=%s&limit=100", field[a->kind]);+ int ok = !url.oom &&+ pr_fetch(url.p, FR_KEEP_S, MS, 1, &body, err, err_len) == 200 &&+ pr_read_fuel_fr(body.p, body.n, a, f, err, err_len) == 0;+ janas_buf_free(&url);+ janas_buf_free(&body);+ return ok ? 0 : -1;+}++/* energia.serviciosmin.gob.es: the ministry's older address,+ sedeaplicaciones.minetur.gob.es, offers only TLS 1.2 with RSA's key+ exchange, which Mbed TLS 4 no longer has */+static int spain(const struct pr_place *p, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len)+{+ /* the province: a postcode's first two digits */+ if (strlen(p->postcode) < 2 || p->postcode[0] < '0' ||+ p->postcode[0] > '5') {+ snprintf(err, err_len, "the province of %s is not known: name a town",+ p->name);+ return -1;+ }+ char url[200];+ snprintf(url, sizeof url,+ "https://energia.serviciosmin.gob.es/ServiciosRestCarburantes/"+ "PreciosCarburantes/EstacionesTerrestres/FiltroProvincia/%.2s",+ p->postcode);+ struct janas_buf body = {0};+ int ok = pr_fetch(url, ES_KEEP_S, MS, 1, &body, err, err_len) == 200 &&+ pr_read_fuel_es(body.p, body.n, a, f, err, err_len) == 0;+ janas_buf_free(&body);+ return ok ? 0 : -1;+}++static int austria(const struct pr_fuel_ask *a, struct pr_fuel *f, char *err,+ size_t err_len)+{+ static const char *const code[] = {"SUP", "DIE", NULL, "GAS"};+ if (!code[a->kind]) {+ snprintf(err, err_len, "E-Control has no price of LPG");+ return -1;+ }+ char url[300];+ snprintf(url, sizeof url,+ "https://api.e-control.at/sprit/1.0/search/gas-stations/"+ "by-address?latitude=%.5f&longitude=%.5f&fuelType=%s"+ "&includeClosed=false",+ a->lat, a->lon, code[a->kind]);+ struct janas_buf body = {0};+ int ok = pr_fetch(url, AT_KEEP_S, MS, 1, &body, err, err_len) == 200 &&+ pr_read_fuel_at(body.p, body.n, a, f, err, err_len) == 0;+ janas_buf_free(&body);+ return ok ? 0 : -1;+}++int pr_tool_fuel(const struct janas_json *args, struct janas_buf *b)+{+ static const char *const kinds[] = {"petrol", "diesel", "lpg", "cng"};+ const char *k = pr_arg_str(args, "fuel");+ int kind = -1;+ for (int i = 0; k && i < 4; i++)+ if (!strcmp(k, kinds[i]))+ kind = i;+ if (kind < 0)+ return pr_fail(b, "The fuel: petrol, diesel, lpg or cng.");+ struct pr_place p;+ char err[400] = "";+ if (pr_place_find(pr_arg_str(args, "place"), &p, err, sizeof err) != 0)+ return pr_fail(b, "%s. Ask the user which place.", err);+ double r = pr_arg_num(args, "radius", 5);+ r = r < 1 ? 1 : r > 20 ? 20 : r;+ struct pr_fuel_ask a = {.now = time(NULL),+ .lat = p.lat,+ .lon = p.lon,+ .radius_km = r,+ .kind = (enum pr_fuel_kind)kind};+ struct pr_fuel f;+ const char *source;+ int rc;+ if (!strcmp(p.cc, "IT")) {+ rc = italy(&a, &f, err, sizeof err);+ source = "mimit";+ } else if (!strcmp(p.cc, "FR")) {+ rc = france(&a, &f, err, sizeof err);+ source = "fr";+ } else if (!strcmp(p.cc, "ES")) {+ rc = spain(&p, &a, &f, err, sizeof err);+ source = "es";+ } else if (!strcmp(p.cc, "AT")) {+ rc = austria(&a, &f, err, sizeof err);+ source = "at";+ } else {+ return pr_fail(b,+ "The fuel prices of %s are not covered: open data of "+ "every station is published, and read here, for "+ "Italy, France, Spain and Austria. Tell the user so.",+ p.country[0] ? p.country : p.name);+ }+ if (rc != 0)+ return pr_fail(b, "The fuel prices near %s could not be read: %s.",+ p.name, err);+ struct janas_buf d = {0};+ pr_fuel_data(&d, &p, kinds[kind], r, &f, source);+ return pr_answer(b, "prices_fuel", &d, PR_FUEL_LAYOUT, PR_FUEL_BRIEF);+}diff --git a/src/prices/layouts.c b/src/prices/layouts.cnew file mode 100644index 0000000..a1873ce--- /dev/null+++ b/src/prices/layouts.c@@ -0,0 +1,209 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * layouts.c - the layouts of janas-prices' answers (see prices.h and+ * common/template.h): the text the user reads, filled with the data in+ * English here and in the user's language by a client that translates the+ * layout once (janas-chat), and the brief, all the model reads of it.+ * Every answer says where its figures come from, how old they are, and+ * that they are for information only.+ */+#include "prices.h"++#define MON_WORDS \+ "mon.1 = January\n" \+ "mon.2 = February\n" \+ "mon.3 = March\n" \+ "mon.4 = April\n" \+ "mon.5 = May\n" \+ "mon.6 = June\n" \+ "mon.7 = July\n" \+ "mon.8 = August\n" \+ "mon.9 = September\n" \+ "mon.10 = October\n" \+ "mon.11 = November\n" \+ "mon.12 = December\n"++#define DIR_WORDS \+ "dir.N = N\n" \+ "dir.NNE = NNE\n" \+ "dir.NE = NE\n" \+ "dir.ENE = ENE\n" \+ "dir.E = E\n" \+ "dir.ESE = ESE\n" \+ "dir.SE = SE\n" \+ "dir.SSE = SSE\n" \+ "dir.S = S\n" \+ "dir.SSW = SSW\n" \+ "dir.SW = SW\n" \+ "dir.WSW = WSW\n" \+ "dir.W = W\n" \+ "dir.WNW = WNW\n" \+ "dir.NW = NW\n" \+ "dir.NNW = NNW\n"++#define HOW_WORDS \+ "how.as set on the computer (JANAS_LOCATION) = as set on the computer " \+ "(JANAS_LOCATION)\n" \+ "how.estimated from the internet connection (GeoJS) = estimated from " \+ "the internet connection (GeoJS)\n" \+ "how.estimated from the internet connection (ipwho.is) = estimated from " \+ "the internet connection (ipwho.is)\n" \+ "how.a rough guess, the city of the computer's time zone = a rough " \+ "guess, the city of the computer's time zone\n"++#define INFO "For information only, not advice to buy or sell."++const char PR_FX_LAYOUT[] =+ "{{amount}} {{from}}, at the exchange rates of {{date.day}} "+ "{{date.mon|mon}} {{date.year}}:\n"+ "{{#items}}\n"+ " {{value}} {{code}} (1 {{from}} = {{rate}} {{code}})\n"+ "{{/items}}\n"+ "Reference exchange rates: {{source|src}}, set once a working day: "+ "a bank or an exchange office applies its own. " INFO "\n"+ "---\n" MON_WORDS+ "src.ecb_frankfurter = European Central Bank, through Frankfurter\n"+ "src.ecb = European Central Bank\n";++const char PR_FX_BRIEF[] =+ "{{amount}} {{from}} = {{#items}}{{value}} {{code}} (exchange rate "+ "{{rate}}); {{/items}}reference exchange rates of "+ "{{date.day}}/{{date.mon}}/{{date.year}} ({{source}}). Shown to "+ "the user: answer in a line, in the user's language.";++const char PR_COIN_LAYOUT[] =+ "{{name}} ({{symbol}}): {{price}} {{cur}}{{#has_change}}, "+ "{{#up}}+{{/up}}{{change}}% in 24 "+ "hours{{/has_change}}{{#has_cap_bn}}; market value {{cap_bn}} "+ "billion {{cur}}{{/has_cap_bn}}{{#at.day}}; at {{at.at}} of "+ "{{at.day}} {{at.mon|mon}}{{/at.day}}.\n"+ "Data provided by {{source|src}}. The prices of crypto-assets "+ "swing widely. " INFO "\n"+ "---\n" MON_WORDS+ "src.coingecko = CoinGecko (https://www.coingecko.com/en/api)\n"+ "src.coinbase = Coinbase\n";++const char PR_COIN_BRIEF[] =+ "{{name}} ({{symbol}}): {{price}} {{cur}}{{#has_change}}, "+ "{{change}}% in 24 hours{{/has_change}}; source {{source}}. Shown "+ "to the user: answer in a line, in the user's language.";++const char PR_QUOTE_LAYOUT[] =+ "{{name}} ({{symbol}}{{#region}}, {{region}}{{/region}}): "+ "{{price}} {{currency}}{{#has_change}}, {{#up}}+{{/up}}{{change}} "+ "({{#up}}+{{/up}}{{pct}}%){{/has_change}}; the trading day of "+ "{{day.day}} {{day.mon|mon}} {{day.year}}\n"+ "open {{open}}, high {{high}}, low {{low}}, previous close "+ "{{prev}}{{#volume}}, shares traded {{volume}}{{/volume}}\n"+ "From Alpha Vantage: the prices may be delayed. " INFO "\n"+ "---\n" MON_WORDS;++const char PR_QUOTE_BRIEF[] =+ "{{name}} ({{symbol}}{{#region}}, {{region}}{{/region}}): "+ "{{price}} {{currency}}, {{change}} ({{pct}}%), trading day "+ "{{day.day}}/{{day.mon}}/{{day.year}}. Shown to the user: answer "+ "in a line, in the user's language.";++const char PR_SERIES_LAYOUT[] =+ "{{what|what}}{{#who}}, {{who}}{{/who}}:\n"+ "{{#items}}\n"+ " {{when}}: {{v}}{{unit}}\n"+ "{{/items}}\n"+ "{{#has_min}}minimum {{min}}{{unit}} ({{min_when}}), maximum "+ "{{max}}{{unit}} ({{max_when}}), average {{avg}}{{unit}}\n"+ "{{/has_min}}{{#note}}{{note|note}}\n"+ "{{/note}}Source: {{source|src}}{{#licence}}, "+ "{{licence}}{{/licence}}. " INFO "\n"+ "---\n"+ "what.inflation = Inflation, the yearly change of consumer prices\n"+ "what.power = Electricity, the wholesale price on the day-ahead "+ "market\n"+ "src.eurostat = Eurostat, the harmonised index of consumer prices "+ "(HICP)\n"+ "src.worldbank = World Bank (CC BY 4.0), consumer prices\n"+ "src.energy_charts = energy-charts.info (Fraunhofer ISE)\n"+ "note.flash = The last month may be a first estimate.\n"+ "note.yearly = Yearly figures: the latest may be one or two years "+ "back.\n"+ "note.exchange = The price on the power exchange, before taxes, "+ "charges and the seller's margin: not what a household pays.\n";++const char PR_SERIES_BRIEF[] =+ "{{what}}{{#who}}, {{who}}{{/who}}: last {{last.v}}{{unit}} "+ "({{last.when}}); minimum {{min}} ({{min_when}}), maximum {{max}} "+ "({{max_when}}), average {{avg}}. {{#note}}Note: {{note}}. "+ "{{/note}}Shown to the user with every value: answer in a line or "+ "two, in the user's language.";++const char PR_RATES_LAYOUT[] =+ "{{bank|bank}}:\n"+ "{{#items}}\n"+ " {{name|rate}}: {{v}}% ({{when.day}} {{when.mon|mon}} "+ "{{when.year}})\n"+ "{{/items}}\n"+ "{{#range}} the target range of the federal funds: "+ "{{lo}}-{{hi}}%\n"+ "{{/range}}Source: {{source|src}}. " INFO "\n"+ "---\n" MON_WORDS "rate.deposit = deposit facility rate\n"+ "rate.mro = main refinancing operations\n"+ "rate.mlf = marginal lending facility\n"+ "rate.estr = euro short-term rate (€STR)\n"+ "rate.bank = Bank Rate\n"+ "rate.policy = policy rate\n"+ "rate.effr = effective federal funds rate\n"+ "bank.ecb = European Central Bank\n"+ "bank.fed = Federal Reserve\n"+ "bank.boe = Bank of England\n"+ "bank.snb = Swiss National Bank\n"+ "src.ecb_portal = ECB data portal\n"+ "src.nyfed = Federal Reserve Bank of New York\n"+ "src.boe = Bank of England database\n"+ "src.snb = Swiss National Bank data portal\n";++const char PR_RATES_BRIEF[] =+ "{{bank}}: {{#items}}{{name}} {{v}}% "+ "({{when.day}}/{{when.mon}}/{{when.year}}); "+ "{{/items}}{{#range}}target range {{lo}}-{{hi}}%. {{/range}}Shown "+ "to the user: answer in a line, in the user's language.";++const char PR_FUEL_LAYOUT[] =+ "{{kind|kind}} near {{place.name}}{{#place.how}} (where the user "+ "is, {{place.how|how}}){{/place.how}}{{#place.country}}, "+ "{{place.country}}{{/place.country}}: {{#found}}stations within "+ "{{radius}} km, {{found}}; the cheapest {{cheapest}} "+ "{{unit}}{{#has_average}}, the average {{average}} "+ "{{unit}}{{/has_average}}{{/found}}{{^found}}no station within "+ "{{radius}} km sells it{{/found}}{{#stale}}; left out, as their "+ "price was not told in the last {{stale_days}} days: "+ "{{stale}}{{/stale}}\n"+ "{{#items}}\n"+ "{{@n}}. {{price}} {{unit}}{{#self}} "+ "(self-service){{/self}}{{#served}} (served){{/served}}: "+ "{{#name}}{{name}}, {{/name}}{{address}}{{#city}}, "+ "{{city}}{{/city}} ({{#km}}{{km}} km{{/km}}{{#m}}{{m}} m{{/m}} "+ "{{dir|dir}}{{#updated}}; price of {{updated}}{{/updated}})\n"+ "{{/items}}\n"+ "Source: {{source|src}} ({{fuel}}); the prices as each station "+ "told them. " INFO "\n"+ "---\n" DIR_WORDS HOW_WORDS "kind.petrol = Petrol\n"+ "kind.diesel = Diesel\n"+ "kind.lpg = LPG\n"+ "kind.cng = Methane (CNG)\n"+ "src.mimit = Italian Ministry of Enterprises (MIMIT), the day's "+ "file\n"+ "src.fr = French government (prix-carburants), as they come\n"+ "src.es = Spanish Ministry for the Ecological Transition\n"+ "src.at = E-Control, Austria's fuel price calculator, which gives "+ "some stations, the cheapest\n";++const char PR_FUEL_BRIEF[] =+ "{{kind}} near {{place.name}}{{#place.how}} (where the user is, "+ "{{place.how}}: say which place, and that it may be "+ "off){{/place.how}}: {{found}} stations within {{radius}} km, the "+ "cheapest {{cheapest}} {{unit}}{{#has_average}}, average "+ "{{average}}{{/has_average}}{{#stale}}; {{stale}} left out, their "+ "price older than {{stale_days}} days{{/stale}}. "+ "{{#items}}{{price}} {{name}} {{address}} ({{#km}}{{km}} "+ "km{{/km}}{{#m}}{{m}} m{{/m}}); {{/items}}The list is shown to the "+ "user: answer in a line or two, in the user's language.";diff --git a/src/prices/macro.c b/src/prices/macro.cnew file mode 100644index 0000000..c1bee2f--- /dev/null+++ b/src/prices/macro.c@@ -0,0 +1,346 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * macro.c - janas-prices' inflation, central banks' rates and electricity+ * (see prices.h). Inflation from Eurostat for Europe, monthly, and from the+ * World Bank for every other country, yearly; the rates of the ECB, the+ * Fed (through the New York Fed), the Bank of England and the Swiss+ * National Bank; electricity from energy-charts (Fraunhofer ISE), only for+ * the bidding zones whose prices it gives under an open licence.+ */+#define _GNU_SOURCE /* strcasestr */+#include <ctype.h>+#include <math.h>+#include <stdio.h>+#include <string.h>+#include <time.h>++#include "common/geo.h"+#include "common/locate.h"+#include "prices.h"++#define DAY_KEEP_S 3600+#define MS 30000++/* The countries of Eurostat's consumer prices: the EU's, Iceland's,+ Norway's, the euro area (EA) and the Union (EU). Greece is EL there. */+static const char EUROSTAT[] = " AT BE BG CY CZ DE DK EE EL ES FI FR HR HU "+ "IE IS IT LT LU LV MT NL NO PL PT RO SE SI "+ "SK EA EU ";++static int in_eurostat(const char *cc)+{+ char k[6];+ snprintf(k, sizeof k, " %s ", cc);+ return strstr(EUROSTAT, k) != NULL;+}++/* A country's name from its ISO code, the code itself when unknown */+static const char *country_name(const char *cc)+{+ for (uint16_t i = 0; *geo_country_iso2(i); i++)+ if (!strcmp(geo_country_iso2(i), cc))+ return geo_country_name(i);+ return cc;+}++/* The user's country's code, "" when not known */+static void user_cc(char *cc)+{+ struct janas_where w;+ char err[200];+ cc[0] = 0;+ if (janas_where(&w, err, sizeof err) == 0)+ snprintf(cc, 3, "%s", w.cc);+}++int pr_tool_inflation(const struct janas_json *args, struct janas_buf *b)+{+ char cc[4] = "", err[400] = "", url[512];+ const char *c = pr_arg_str(args, "country");+ if (c) {+ if (strlen(c) != 2 || !isalpha((unsigned char)c[0]) ||+ !isalpha((unsigned char)c[1]))+ return pr_fail(b,+ "\"%s\" is not a country's ISO code (IT, US, "+ "EA for the euro area).",+ c);+ cc[0] = (char)toupper((unsigned char)c[0]);+ cc[1] = (char)toupper((unsigned char)c[1]);+ } else {+ user_cc(cc);+ if (!cc[0])+ return pr_fail(b, "No country given, and where the user is is "+ "not known: ask which country.");+ }+ if (!strcmp(cc, "GR"))+ snprintf(cc, sizeof cc, "EL");+ struct janas_buf body = {0}, d = {0};+ struct pr_series s;+ if (in_eurostat(cc)) {+ snprintf(url, sizeof url,+ "https://ec.europa.eu/eurostat/api/dissemination/statistics/"+ "1.0/data/prc_hicp_minr?geo=%s&coicop18=TOTAL&unit=RCH_A"+ "&lastTimePeriod=13",+ cc);+ int ok =+ pr_fetch(url, DAY_KEEP_S, MS, 1, &body, err, sizeof err) == 200 &&+ pr_read_eurostat(body.p, body.n, &s, err, sizeof err) == 0;+ janas_buf_free(&body);+ if (!ok)+ return pr_fail(b,+ "Eurostat's inflation of %s could not be read: "+ "%s.",+ cc, err);+ snprintf(s.unit, sizeof s.unit, "%%");+ const char *who = !strcmp(cc, "EA") ? "the euro area"+ : !strcmp(cc, "EU") ? "the European Union"+ : !strcmp(cc, "EL") ? country_name("GR")+ : country_name(cc);+ pr_series_data(&d, "inflation", who, &s, 13, "eurostat", "flash", "");+ } else {+ snprintf(url, sizeof url,+ "https://api.worldbank.org/v2/country/%s/indicator/"+ "FP.CPI.TOTL.ZG?format=json&mrv=6",+ cc);+ char country[64] = "";+ int ok =+ pr_fetch(url, DAY_KEEP_S, MS, 1, &body, err, sizeof err) == 200 &&+ pr_read_worldbank(body.p, body.n, &s, country, sizeof country, err,+ sizeof err) == 0;+ janas_buf_free(&body);+ if (!ok)+ return pr_fail(b,+ "The World Bank's inflation of %s could not be "+ "read: %s.",+ cc, err);+ snprintf(s.unit, sizeof s.unit, "%%");+ for (int i = 0; i < s.n; i++) /* as Eurostat gives them */+ s.p[i].v = round(s.p[i].v * 10) / 10;+ pr_series_data(&d, "inflation", country, &s, 6, "worldbank", "yearly",+ "");+ }+ return pr_answer(b, "prices_inflation", &d, PR_SERIES_LAYOUT,+ PR_SERIES_BRIEF);+}++/* ---- central banks ---- */++static int ecb_series(const char *key, struct pr_rate *r, const char *name,+ char *err, size_t err_len)+{+ char url[300];+ snprintf(url, sizeof url,+ "https://data-api.ecb.europa.eu/service/data/%s"+ "?lastNObservations=1&format=csvdata",+ key);+ struct janas_buf body = {0};+ struct pr_series s;+ int ok = pr_fetch(url, DAY_KEEP_S, MS, 0.5, &body, err, err_len) == 200 &&+ pr_read_ecb_csv(body.p, body.n, &s, err, err_len) == 0;+ janas_buf_free(&body);+ if (ok) {+ snprintf(r->name, sizeof r->name, "%s", name);+ snprintf(r->when, sizeof r->when, "%s", s.p[s.n - 1].when);+ r->v = s.p[s.n - 1].v;+ }+ return ok ? 0 : -1;+}++int pr_tool_rates(const struct janas_json *args, struct janas_buf *b)+{+ const char *bank = pr_arg_str(args, "bank");+ char cc[3] = "", err[400] = "";+ if (!bank) {+ user_cc(cc);+ bank = !strcmp(cc, "US") ? "fed"+ : !strcmp(cc, "GB") ? "boe"+ : !strcmp(cc, "CH") ? "snb"+ : "ecb";+ }+ struct pr_rate r[4];+ int n = 0;+ double lo = NAN, hi = NAN;+ const char *name, *source;+ struct janas_buf body = {0};+ struct pr_series s;+ if (!strcmp(bank, "ecb")) {+ static const struct {+ const char *key, *name;+ } E[] = {{"FM/D.U2.EUR.4F.KR.DFR.LEV", "deposit"},+ {"FM/D.U2.EUR.4F.KR.MRR_FR.LEV", "mro"},+ {"FM/D.U2.EUR.4F.KR.MLFR.LEV", "mlf"},+ {"EST/B.EU000A2X2A25.WT", "estr"}};+ for (int i = 0; i < 4; i++)+ if (ecb_series(E[i].key, &r[n], E[i].name, err, sizeof err) == 0)+ n++;+ name = "ecb";+ source = "ecb_portal";+ } else if (!strcmp(bank, "fed")) {+ if (pr_fetch("https://markets.newyorkfed.org/api/rates/unsecured/effr/"+ "last/1.json",+ DAY_KEEP_S, MS, 0.5, &body, err, sizeof err) == 200 &&+ pr_read_nyfed(body.p, body.n, &s, &lo, &hi, err, sizeof err) == 0) {+ snprintf(r[0].name, sizeof r[0].name, "effr");+ snprintf(r[0].when, sizeof r[0].when, "%s", s.p[s.n - 1].when);+ r[0].v = s.p[s.n - 1].v;+ n = 1;+ }+ name = "fed";+ source = "nyfed";+ } else if (!strcmp(bank, "boe")) {+ char url[400], from[16];+ time_t t = time(NULL) - 40 * 86400;+ struct tm g;+ gmtime_r(&t, &g);+ strftime(from, sizeof from, "%d/%b/%Y", &g);+ snprintf(url, sizeof url,+ "https://www.bankofengland.co.uk/boeapps/database/"+ "_iadb-fromshowcolumns.asp?csv.x=yes&Datefrom=%s&Dateto=now"+ "&SeriesCodes=IUDBEDR&CSVF=TN&UsingCodes=Y",+ from);+ if (pr_fetch(url, DAY_KEEP_S, MS, 0.5, &body, err, sizeof err) == 200 &&+ pr_read_boe_csv(body.p, body.n, &s, err, sizeof err) == 0) {+ snprintf(r[0].name, sizeof r[0].name, "bank");+ snprintf(r[0].when, sizeof r[0].when, "%s", s.p[s.n - 1].when);+ r[0].v = s.p[s.n - 1].v;+ n = 1;+ }+ name = "boe";+ source = "boe";+ } else if (!strcmp(bank, "snb")) {+ char url[300], from[16];+ time_t t = time(NULL) - 40 * 86400;+ struct tm g;+ gmtime_r(&t, &g);+ strftime(from, sizeof from, "%Y-%m", &g);+ snprintf(url, sizeof url,+ "https://data.snb.ch/api/cube/snbgwdzid/data/json/en"+ "?fromDate=%s",+ from);+ if (pr_fetch(url, DAY_KEEP_S, MS, 0.5, &body, err, sizeof err) == 200 &&+ pr_read_snb(body.p, body.n, &s, err, sizeof err) == 0) {+ snprintf(r[0].name, sizeof r[0].name, "policy");+ snprintf(r[0].when, sizeof r[0].when, "%s", s.p[s.n - 1].when);+ r[0].v = s.p[s.n - 1].v;+ n = 1;+ }+ name = "snb";+ source = "snb";+ } else {+ return pr_fail(b, "No such bank: ecb, fed, boe or snb.");+ }+ janas_buf_free(&body);+ if (!n)+ return pr_fail(b, "The rates of %s could not be read: %s.", name, err);+ struct janas_buf d = {0};+ pr_rates_data(&d, name, r, n, lo, hi, source);+ return pr_answer(b, "prices_rates", &d, PR_RATES_LAYOUT, PR_RATES_BRIEF);+}++/* ---- electricity ---- */++/* The bidding zone of a place: Italy's by its region, the Nordic+ countries' roughly by the point, the others' the country */+static void zone_of(const struct pr_place *p, char *z, size_t cap)+{+ static const struct {+ const char *word, *zone;+ } IT[] = {{"sicil", "IT-Sicily"}, {"sardegna", "IT-Sardinia"},+ {"sardinia", "IT-Sardinia"}, {"calabr", "IT-Calabria"},+ {"apulia", "IT-South"}, {"puglia", "IT-South"},+ {"basilicata", "IT-South"}, {"molise", "IT-South"},+ {"lazio", "IT-Centre-South"}, {"campania", "IT-Centre-South"},+ {"abruzz", "IT-Centre-South"}, {"tuscan", "IT-Centre-North"},+ {"toscana", "IT-Centre-North"}, {"umbria", "IT-Centre-North"},+ {"marche", "IT-Centre-North"}};+ if (!strcmp(p->cc, "IT")) {+ snprintf(z, cap, "IT-North");+ for (size_t i = 0; i < sizeof IT / sizeof *IT; i++)+ if (strcasestr(p->region, IT[i].word))+ snprintf(z, cap, "%s", IT[i].zone);+ } else if (!strcmp(p->cc, "DE") || !strcmp(p->cc, "LU")) {+ snprintf(z, cap, "DE-LU");+ } else if (!strcmp(p->cc, "DK")) {+ snprintf(z, cap, p->lon < 11 ? "DK1" : "DK2");+ } else if (!strcmp(p->cc, "SE")) {+ snprintf(z, cap,+ p->lat > 65.5 ? "SE1"+ : p->lat > 61.5 ? "SE2"+ : p->lat > 57.5 ? "SE3"+ : "SE4");+ } else if (!strcmp(p->cc, "NO")) {+ snprintf(z, cap,+ p->lat > 66 ? "NO4"+ : p->lat > 62 ? "NO3"+ : p->lon < 7.5 ? "NO5"+ : p->lat < 59.5 && p->lon < 9 ? "NO2"+ : "NO1");+ } else {+ snprintf(z, cap, "%s", p->cc);+ }+}++int pr_tool_power(const struct janas_json *args, struct janas_buf *b)+{+ struct pr_place p;+ char err[400] = "", zone[24], url[300], day[11], licence[600];+ if (pr_place_find(pr_arg_str(args, "place"), &p, err, sizeof err) != 0)+ return pr_fail(b, "%s. Ask the user which place.", err);+ if (!p.cc[0])+ return pr_fail(b, "The country of %s is not known.", p.name);+ zone_of(&p, zone, sizeof zone);+ int tomorrow = janas_json_is(janas_json_get(args, "day"), "tomorrow");+ time_t t = time(NULL) + (tomorrow ? 86400 : 0);+ struct tm lt;+ localtime_r(&t, <);+ strftime(day, sizeof day, "%Y-%m-%d", <);+ snprintf(url, sizeof url,+ "https://api.energy-charts.info/price?bzn=%s&start=%s&end=%s",+ zone, day, day);+ struct janas_buf body = {0};+ struct pr_series s;+ int st = pr_fetch(url, DAY_KEEP_S, MS, 3, &body, err, sizeof err);+ int open = st == 200 ? pr_read_power(body.p, body.n, p.tz, &s, licence,+ sizeof licence, err, sizeof err)+ : -1;+ janas_buf_free(&body);+ if (st == 404 || (st == 200 && open < 0 && !licence[0]))+ return pr_fail(b,+ "energy-charts has no prices for the zone %s (%s) "+ "%s.",+ zone, p.name, tomorrow ? "for tomorrow yet" : "today");+ if (open < 0)+ return pr_fail(b, "The prices of electricity could not be read: %s.",+ st > 0 && st != 200 ? "energy-charts is busy" : err);+ if (!open)+ return pr_fail(b,+ "The wholesale prices of the zone %s (%s) are not "+ "open data: their source allows only private and "+ "internal use, so they are not given. Tell the "+ "user so.",+ zone, p.name);+ /* the hours: quarters of an hour averaged */+ struct pr_series h;+ memset(&h, 0, sizeof h);+ snprintf(h.unit, sizeof h.unit, " €/MWh");+ for (int i = 0; i < s.n;) {+ char hour[24];+ snprintf(hour, sizeof hour, "%.13s:00", s.p[i].when);+ double sum = 0;+ int k = 0;+ for (; i < s.n && !strncmp(s.p[i].when, hour, 13); i++, k++)+ sum += s.p[i].v;+ if (h.n < PR_POINTS) {+ snprintf(h.p[h.n].when, sizeof h.p[h.n].when, "%s", hour + 11);+ h.p[h.n++].v = round(sum / k * 100) / 100;+ }+ }+ char who[160];+ snprintf(who, sizeof who, "%s, %s, %s", p.name, zone, day);+ struct janas_buf d = {0};+ pr_series_data(&d, "power", who, &h, 24, "energy_charts", "exchange",+ licence);+ return pr_answer(b, "prices_electricity", &d, PR_SERIES_LAYOUT,+ PR_SERIES_BRIEF);+}diff --git a/src/prices/main.c b/src/prices/main.cnew file mode 100644index 0000000..3dccc72--- /dev/null+++ b/src/prices/main.c@@ -0,0 +1,89 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * main.c - janas-prices: prices and finance as an MCP server over stdio,+ * for information only, for janas-chat (which starts it by itself) and any+ * other MCP client: currencies, crypto-assets, shares, inflation, central+ * banks' rates, electricity, fuel. Open data without a key, but for+ * shares, which need a free key of the user's.+ */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/mcp_server.h"+#include "prices.h"++#ifndef JANAS_VERSION+#define JANAS_VERSION "unknown"+#endif++static const char INSTRUCTIONS[] =+ "Use these tools by yourself when the user asks about a price or a "+ "figure of money: what a currency is worth, a crypto-asset, a share, "+ "inflation, a central bank's rates, electricity, the cheapest fuel near "+ "a place; never name them. The figures are for information only: never "+ "advise buying or selling. With no place or country named, leave it "+ "out: the tool takes where the user is; say which place.";++static void usage(void)+{+ fprintf(stderr,+ "usage: janas-prices [--config FILE]\n"+ "An MCP server over stdio: a client starts it and calls its\n"+ "tools - prices_currency, prices_crypto, prices_stock,\n"+ "prices_inflation, prices_rates, prices_electricity and\n"+ "prices_fuel. For information only.\n"+ "Open data without a key: the ECB (through Frankfurter),\n"+ "CoinGecko and Coinbase, Eurostat and the World Bank, the ECB,\n"+ "the New York Fed, the Bank of England and the SNB,\n"+ "energy-charts.info (only the zones it gives under CC BY), the\n"+ "fuel prices of Italy (MIMIT), France, Spain and Austria.\n"+ "Shares need a free key of Alpha Vantage\n"+ "(https://www.alphavantage.co/support/#api-key): the line\n"+ "alphavantage_key = KEY in FILE (by default\n"+ "~/.config/janas/prices.conf), or JANAS_ALPHAVANTAGE_KEY.\n"+ "janas-chat starts it by itself when it is beside it.\n"+ "Configured in a client as, for instance:\n"+ " {\"mcpServers\": {\"prices\": {\"command\": "+ "\"janas-prices\"}}}\n");+}++int main(int argc, char **argv)+{+ const char *config = NULL;+ for (int i = 1; i < argc; i++) {+ if (strcmp(argv[i], "--config") == 0 && i + 1 < argc) {+ config = argv[++i];+ continue;+ }+ usage();+ return strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 ? 0+ : 2;+ }+ char path[4096];+ if (!config) {+ const char *xdg = getenv("XDG_CONFIG_HOME"), *home = getenv("HOME");+ if (xdg && *xdg)+ snprintf(path, sizeof path, "%s/janas/prices.conf", xdg);+ else+ snprintf(path, sizeof path, "%s/.config/janas/prices.conf",+ home ? home : ".");+ config = path;+ }+ pr_key_config(config);+ struct janas_mcps srv = {.name = "janas-prices",+ .version = JANAS_VERSION,+ .instructions = INSTRUCTIONS,+ .tools_list = pr_tools_list,+ .tools_call = pr_tools_call};+ if (janas_mcps_open(&srv) != 0) {+ fprintf(stderr, "janas-prices: cannot set its output aside\n");+ return 1;+ }+ fprintf(stderr, "janas-prices %s: ready, 7 tools; shares: %s\n",+ JANAS_VERSION, pr_key() ? "Alpha Vantage" : "none (no key)");+ janas_mcps_run(&srv);+ pr_fetch_free();+ return 0;+}diff --git a/src/prices/money.c b/src/prices/money.cnew file mode 100644index 0000000..695e731--- /dev/null+++ b/src/prices/money.c@@ -0,0 +1,252 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * money.c - janas-prices' currencies, crypto-assets and shares (see+ * prices.h). Currencies at the ECB's reference rates through Frankfurter+ * (any base, any day), the ECB's own file when it does not answer;+ * crypto-assets from CoinGecko's keyless API, Coinbase's spot price when+ * it does not answer; shares from Alpha Vantage with a free key of the+ * user's, the only tool that needs one.+ */+#include <ctype.h>+#include <math.h>+#include <stdio.h>+#include <string.h>++#include "prices.h"++#define FX_KEEP_S 3600+#define COIN_KEEP_S 120+#define SEARCH_KEEP_S 86400+#define QUOTE_KEEP_S 300+#define MS 20000++/* "usd" -> "USD"; 0 when not three letters */+static int code3(const char *s, char *out)+{+ for (int i = 0; i < 3; i++) {+ if (!s || !isalpha((unsigned char)s[i]))+ return 0;+ out[i] = (char)toupper((unsigned char)s[i]);+ }+ out[3] = 0;+ return !isalnum((unsigned char)s[3]);+}++int pr_tool_currency(const struct janas_json *args, struct janas_buf *b)+{+ char from[4] = "EUR", err[400] = "";+ const char *f = pr_arg_str(args, "from");+ if (f && !code3(f, from))+ return pr_fail(b, "\"%s\" is not a currency's ISO code (EUR, USD).", f);+ /* the codes asked, else the most asked */+ const char *to = pr_arg_str(args, "to");+ char list[160] = "";+ size_t k = 0;+ for (const char *p = to ? to : "USD,GBP,CHF,JPY"; *p;) {+ char c[4];+ while (*p == ',' || *p == ' ')+ p++;+ if (!*p)+ break;+ if (!code3(p, c))+ return pr_fail(b, "\"%s\" is not a list of ISO codes.", to);+ if (strcmp(c, from) && k + 5 < sizeof list)+ k += (size_t)snprintf(list + k, sizeof list - k, "%s%s",+ k ? "," : "", c);+ p += 3;+ }+ if (!k)+ return pr_fail(b, "No currency to convert to.");+ double amount = pr_arg_num(args, "amount", 1);+ const char *date = pr_arg_str(args, "date");+ int y, m, d;+ if (date && sscanf(date, "%4d-%2d-%2d", &y, &m, &d) != 3)+ return pr_fail(b, "\"%s\" is not a date (YYYY-MM-DD).", date);+ char url[512];+ snprintf(url, sizeof url,+ "https://api.frankfurter.dev/v1/%s?base=%s&symbols=%s",+ date ? date : "latest", from, list);+ struct janas_buf body = {0};+ struct pr_fx fx;+ const char *source = "ecb_frankfurter";+ int ok = pr_fetch(url, FX_KEEP_S, MS, 0.5, &body, err, sizeof err) == 200 &&+ pr_read_frankfurter(body.p, body.n, &fx, err, sizeof err) == 0;+ if (!ok && !date) { /* the ECB's file, in euro: crossed */+ char e2[300];+ struct pr_fx eu;+ if (pr_fetch("https://www.ecb.europa.eu/stats/eurofxref/"+ "eurofxref-daily.xml",+ FX_KEEP_S, MS, 0.5, &body, e2, sizeof e2) == 200 &&+ pr_read_ecb_xml(body.p, body.n, &eu, e2, sizeof e2) == 0) {+ double base = strcmp(from, "EUR") ? NAN : 1;+ for (int i = 0; i < eu.n; i++)+ if (!strcmp(eu.r[i].code, from))+ base = eu.r[i].rate;+ memset(&fx, 0, sizeof fx);+ snprintf(fx.base, sizeof fx.base, "%s", from);+ snprintf(fx.date, sizeof fx.date, "%s", eu.date);+ for (int i = 0; i < eu.n && !isnan(base); i++)+ if (strstr(list, eu.r[i].code)) {+ fx.r[fx.n] = eu.r[i];+ fx.r[fx.n++].rate = eu.r[i].rate / base;+ }+ if (!strcmp(from, "EUR") || !isnan(base)) {+ if (strstr(list, "EUR") && strcmp(from, "EUR")) {+ snprintf(fx.r[fx.n].code, 4, "EUR");+ fx.r[fx.n++].rate = 1 / base;+ }+ ok = fx.n > 0;+ source = "ecb";+ }+ }+ }+ janas_buf_free(&body);+ if (!ok)+ return pr_fail(b, "The rates could not be read: %s.", err);+ struct janas_buf data = {0};+ pr_fx_data(&data, amount, from, &fx, source);+ return pr_answer(b, "prices_currency", &data, PR_FX_LAYOUT, PR_FX_BRIEF);+}++int pr_tool_crypto(const struct janas_json *args, struct janas_buf *b)+{+ const char *q = pr_arg_str(args, "coin");+ if (!q)+ return pr_fail(b, "No crypto-asset named.");+ char cur[4] = "EUR", err[400] = "";+ const char *c = pr_arg_str(args, "currency");+ if (c && !code3(c, cur))+ return pr_fail(b, "\"%s\" is not a currency's ISO code.", c);+ struct pr_coin coin;+ struct janas_buf url = {0}, body = {0};+ janas_buf_puts(&url, "https://api.coingecko.com/api/v3/search?query=");+ pr_url_put(&url, q);+ int found =+ !url.oom &&+ pr_fetch(url.p, SEARCH_KEEP_S, MS, 2.5, &body, err, sizeof err) ==+ 200 &&+ pr_read_coin_search(body.p, body.n, q, &coin, err, sizeof err) == 0;+ janas_buf_free(&url);+ int ok = 0;+ const char *source = "coingecko";+ if (found) {+ snprintf(coin.cur, sizeof coin.cur, "%s", cur);+ janas_buf_printf(&url,+ "https://api.coingecko.com/api/v3/simple/price?ids=%s"+ "&vs_currencies=%c%c%c&include_24hr_change=true"+ "&include_market_cap=true&include_last_updated_at="+ "true",+ coin.id, cur[0] | 0x20, cur[1] | 0x20, cur[2] | 0x20);+ ok = !url.oom &&+ pr_fetch(url.p, COIN_KEEP_S, MS, 2.5, &body, err, sizeof err) ==+ 200 &&+ pr_read_coin_price(body.p, body.n, &coin, err, sizeof err) == 0;+ janas_buf_free(&url);+ }+ if (!ok) { /* Coinbase, by the symbol */+ char e2[300], sym[16];+ snprintf(sym, sizeof sym, "%s", found ? coin.symbol : q);+ for (char *s = sym; *s; s++)+ *s = (char)toupper((unsigned char)*s);+ if (!found) {+ memset(&coin, 0, sizeof coin);+ snprintf(coin.name, sizeof coin.name, "%s", sym);+ }+ snprintf(coin.symbol, sizeof coin.symbol, "%s", sym);+ snprintf(coin.cur, sizeof coin.cur, "%s", cur);+ janas_buf_printf(&url, "https://api.coinbase.com/v2/prices/%s-%s/spot",+ sym, cur);+ ok = strspn(sym, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") ==+ strlen(sym) &&+ !url.oom &&+ pr_fetch(url.p, COIN_KEEP_S, MS, 1, &body, e2, sizeof e2) == 200 &&+ pr_read_coinbase(body.p, body.n, &coin, e2, sizeof e2) == 0;+ janas_buf_free(&url);+ source = "coinbase";+ }+ janas_buf_free(&body);+ if (!ok)+ return pr_fail(b, "The price of %s could not be read: %s.", q, err);+ for (char *s = coin.symbol; *s; s++)+ *s = (char)toupper((unsigned char)*s);+ struct janas_buf data = {0};+ pr_coin_data(&data, &coin, source);+ return pr_answer(b, "prices_crypto", &data, PR_COIN_LAYOUT, PR_COIN_BRIEF);+}++/* A symbol as Alpha Vantage writes them: "IBM", "TSCO.LON", "BRK-B" */+static int symbol_like(const char *s)+{+ size_t n = strlen(s);+ if (!n || n > 16)+ return 0;+ for (size_t i = 0; i < n; i++)+ if (!isupper((unsigned char)s[i]) && !isdigit((unsigned char)s[i]) &&+ s[i] != '.' && s[i] != '-')+ return 0;+ return 1;+}++static int quote(const char *symbol, struct pr_quote *q, char *err,+ size_t err_len)+{+ struct janas_buf url = {0}, body = {0};+ janas_buf_puts(&url,+ "https://www.alphavantage.co/query?function=GLOBAL_QUOTE"+ "&symbol=");+ pr_url_put(&url, symbol);+ janas_buf_printf(&url, "&apikey=%s", pr_key());+ int ok =+ !url.oom &&+ pr_fetch(url.p, QUOTE_KEEP_S, MS, 1.5, &body, err, err_len) == 200 &&+ pr_read_av_quote(body.p, body.n, q, err, err_len) == 0;+ janas_buf_free(&url);+ janas_buf_free(&body);+ return ok ? 0 : -1;+}++int pr_tool_stock(const struct janas_json *args, struct janas_buf *b)+{+ const char *s = pr_arg_str(args, "share");+ if (!s)+ return pr_fail(b, "No share named.");+ if (!pr_key())+ return pr_fail(+ b, "Share prices need a free key of Alpha Vantage, which the user "+ "has not given: it is had at "+ "https://www.alphavantage.co/support/#api-key and goes in "+ "~/.config/janas/prices.conf as the line alphavantage_key = "+ "KEY (or in JANAS_ALPHAVANTAGE_KEY). Tell the user so.");+ struct pr_quote q;+ char err[400] = "";+ memset(&q, 0, sizeof q);+ int ok = symbol_like(s) && quote(s, &q, err, sizeof err) == 0;+ if (!ok) { /* by the company's name */+ struct janas_buf url = {0}, body = {0};+ janas_buf_puts(&url, "https://www.alphavantage.co/query?function="+ "SYMBOL_SEARCH&keywords=");+ pr_url_put(&url, s);+ janas_buf_printf(&url, "&apikey=%s", pr_key());+ struct pr_quote found;+ ok = !url.oom &&+ pr_fetch(url.p, SEARCH_KEEP_S, MS, 1.5, &body, err, sizeof err) ==+ 200 &&+ pr_read_av_search(body.p, body.n, &found, err, sizeof err) == 0 &&+ quote(found.symbol, &q, err, sizeof err) == 0;+ if (ok) {+ snprintf(q.name, sizeof q.name, "%s", found.name);+ snprintf(q.region, sizeof q.region, "%s", found.region);+ snprintf(q.currency, sizeof q.currency, "%s", found.currency);+ }+ janas_buf_free(&url);+ janas_buf_free(&body);+ }+ if (!ok)+ return pr_fail(b, "The price of %s could not be read: %s.", s, err);+ if (!q.name[0])+ snprintf(q.name, sizeof q.name, "%s", q.symbol);+ struct janas_buf data = {0};+ pr_quote_data(&data, &q);+ return pr_answer(b, "prices_stock", &data, PR_QUOTE_LAYOUT, PR_QUOTE_BRIEF);+}diff --git a/src/prices/place.c b/src/prices/place.cnew file mode 100644index 0000000..51442c7--- /dev/null+++ b/src/prices/place.c@@ -0,0 +1,182 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * place.c - a place and its country (see prices.h), for the prices that+ * depend on where one is: fuel, electricity. A name through Nominatim+ * (OpenStreetMap: names in every language, at most a request a second),+ * the built-in tables when it does not answer, "lat,lon" through the+ * tables, where the user is through the locator. Spain's fuel goes by+ * province: a postcode's first two digits.+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/geo.h"+#include "common/locate.h"+#include "prices.h"++#define GEO_KEEP_S (7 * 86400)++static void copy(char *to, size_t cap, const char *s)+{+ snprintf(to, cap, "%s", s ? s : "");+}++static void from_tables(double lat, double lon, struct pr_place *p)+{+ double km;+ const struct geo_city *c = geo_city_near(lat, lon, &km);+ if (!c)+ return;+ if (!p->name[0])+ copy(p->name, sizeof p->name, c->name);+ if (!p->cc[0])+ copy(p->cc, sizeof p->cc, geo_country_iso2(c->country));+ if (!p->country[0])+ copy(p->country, sizeof p->country, geo_country_name(c->country));+ if (!p->region[0] && c->region != 0xFFFF)+ copy(p->region, sizeof p->region, geo_region_name(c->region));+ if (!p->tz[0])+ copy(p->tz, sizeof p->tz, geo_tz_name(c->tz));+}++/* The computer's language, for the names Nominatim gives ("Italia") */+static const char *lang(void)+{+ static char l[8];+ const char *v = getenv("LC_ALL");+ if (!v || !*v)+ v = getenv("LC_MESSAGES");+ if (!v || !*v)+ v = getenv("LANG");+ if (!v || strlen(v) < 2 || !strncmp(v, "C", 1) || !strncmp(v, "POSIX", 5))+ return "en";+ snprintf(l, sizeof l, "%.2s", v);+ return l;+}++/* A place of Nominatim's answer: an array (search) or an object+ (reverse). 0 when there is one. */+static int nominatim_read(const struct janas_buf *body, int search,+ struct pr_place *p)+{+ char why[128];+ struct janas_json_doc *d =+ janas_json_parse(body->p, body->n, why, sizeof why);+ const struct janas_json *x = d ? janas_json_root(d) : NULL;+ if (x && search)+ x = x->type == JANAS_JSON_ARRAY ? x->child : NULL;+ const struct janas_json *a = janas_json_get(x, "address");+ int ok = 0;+ if (a) {+ if (search) {+ const char *nm = janas_json_str(janas_json_get(x, "name"));+ copy(p->name, sizeof p->name, nm);+ const char *la = janas_json_str(janas_json_get(x, "lat"));+ const char *lo = janas_json_str(janas_json_get(x, "lon"));+ p->lat = la ? strtod(la, NULL) : NAN;+ p->lon = lo ? strtod(lo, NULL) : NAN;+ const char *cc = janas_json_str(janas_json_get(a, "country_code"));+ for (int i = 0; cc && i < 2 && cc[i]; i++)+ p->cc[i] = (char)(cc[i] & ~0x20); /* "it" -> "IT" */+ copy(p->country, sizeof p->country,+ janas_json_str(janas_json_get(a, "country")));+ copy(p->region, sizeof p->region,+ janas_json_str(janas_json_get(a, "state")));+ }+ const char *pc = janas_json_str(janas_json_get(a, "postcode"));+ if (pc)+ copy(p->postcode, sizeof p->postcode, pc);+ ok = !isnan(p->lat) && !isnan(p->lon);+ }+ janas_json_free(d);+ return ok ? 0 : -1;+}++/* Nominatim's place of name (any language: "Wien", "Milano"), and in+ Spain its postcode (its province) from the point when the place has+ none. 0 when found. */+static int geocode(const char *name, struct pr_place *p, char *err,+ size_t err_len)+{+ struct janas_buf url = {0}, body = {0};+ janas_buf_puts(&url, "https://nominatim.openstreetmap.org/search?q=");+ pr_url_put(&url, name);+ janas_buf_printf(&url,+ "&format=jsonv2&limit=1&addressdetails=1"+ "&accept-language=%s",+ lang());+ int st = url.oom+ ? -1+ : pr_fetch(url.p, GEO_KEEP_S, 15000, 1.1, &body, err, err_len);+ janas_buf_free(&url);+ int ok = st == 200 && nominatim_read(&body, 1, p) == 0;+ if (st == 200 && !ok)+ snprintf(err, err_len, "no place named %s", name);+ else if (st > 0 && st != 200)+ snprintf(err, err_len, "Nominatim: HTTP %d", st);+ if (ok && !strcmp(p->cc, "ES") && !p->postcode[0]) {+ char e[200];+ janas_buf_printf(&url,+ "https://nominatim.openstreetmap.org/reverse?lat=%.6f"+ "&lon=%.6f&format=jsonv2&zoom=18&addressdetails=1",+ p->lat, p->lon);+ if (!url.oom &&+ pr_fetch(url.p, GEO_KEEP_S, 15000, 1.1, &body, e, sizeof e) == 200)+ nominatim_read(&body, 0, p);+ janas_buf_free(&url);+ }+ janas_buf_free(&body);+ return ok ? 0 : -1;+}++int pr_place_find(const char *q, struct pr_place *p, char *err, size_t err_len)+{+ memset(p, 0, sizeof *p);+ p->lat = p->lon = NAN;+ if (!q) {+ struct janas_where w;+ if (janas_where(&w, err, err_len) != 0)+ return -1;+ p->lat = w.lat;+ p->lon = w.lon;+ copy(p->name, sizeof p->name, w.city);+ copy(p->cc, sizeof p->cc, w.cc);+ copy(p->country, sizeof p->country, w.country);+ copy(p->region, sizeof p->region, w.region);+ copy(p->how, sizeof p->how, w.how);+ copy(p->tz, sizeof p->tz, w.tz);+ from_tables(p->lat, p->lon, p);+ if (p->name[0] && !strcmp(p->cc, "ES")) { /* its province */+ struct pr_place g;+ char e[200];+ memset(&g, 0, sizeof g);+ if (geocode(p->name, &g, e, sizeof e) == 0)+ copy(p->postcode, sizeof p->postcode, g.postcode);+ }+ return 0;+ }+ double lat, lon;+ char tail;+ if (sscanf(q, "%lf , %lf %c", &lat, &lon, &tail) == 2 && fabs(lat) <= 90 &&+ fabs(lon) <= 180) {+ p->lat = lat;+ p->lon = lon;+ from_tables(lat, lon, p);+ return 0;+ }+ if (geocode(q, p, err, err_len) == 0) {+ from_tables(p->lat, p->lon, p); /* its time zone */+ return 0;+ }+ const struct geo_city *c = geo_city_find(q); /* the tables, offline */+ if (!c)+ return -1;+ p->lat = c->lat / 1e5;+ p->lon = c->lon / 1e5;+ copy(p->name, sizeof p->name, c->name);+ from_tables(p->lat, p->lon, p);+ return 0;+}diff --git a/src/prices/prices.h b/src/prices/prices.hnew file mode 100644index 0000000..2a2c46c--- /dev/null+++ b/src/prices/prices.h@@ -0,0 +1,236 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * prices.h - janas-prices, prices and finance as an MCP service, for+ * information only: what its parts share. fetch.c asks the sources+ * (answers kept a while, a pause between two requests to a server),+ * place.c finds a place and its country, read.c reads the answers,+ * money.c offers currencies, crypto-assets and shares, macro.c inflation,+ * central banks' rates and electricity, fuel.c the fuel prices of the+ * countries that publish them, data.c and layouts.c write the answers as+ * data with a layout, tools.c offers the tools.+ */+#ifndef JANAS_PRICES_H+#define JANAS_PRICES_H++#include <stddef.h>+#include <time.h>++#include "llm/json.h"++/* ---- fetch.c ---- */++/* GET of url, the body into out; answers of status 200 kept keep_s+ seconds; at most timeout_ms for each part of the answer; pause_s+ between two requests to the same host. The HTTP status, or -1 with the+ reason in err. */+int pr_fetch(const char *url, int keep_s, int timeout_ms, double pause_s,+ struct janas_buf *out, char *err, size_t err_len);+void pr_fetch_free(void);+void pr_url_put(struct janas_buf *b, const char *s);+/* The Alpha Vantage key (JANAS_ALPHAVANTAGE_KEY, else the line+ "alphavantage_key = KEY" of the file); NULL when none. */+void pr_key_config(const char *path);+const char *pr_key(void);++/* ---- place.c ---- */++struct pr_place {+ char name[96], country[64], cc[3], region[64];+ char postcode[12]; /* one of its postcodes, when known (Spain's+ province is its first two digits) */+ double lat, lon;+ char tz[48]; /* its time zone, when known */+ char how[96]; /* where the user is, when no place was named */+};++/* A place by name ("Trapani", "Madrid"), "lat,lon", or, with q NULL,+ where the user is. 0, or -1 with the reason in err. */+int pr_place_find(const char *q, struct pr_place *p, char *err, size_t err_len);++/* ---- read.c: the answers (no network: the tests read kept ones) ---- */++#define PR_RATES 40++struct pr_fx {+ char base[4], date[11];+ struct {+ char code[4];+ double rate;+ } r[PR_RATES];+ int n;+};++struct pr_coin {+ char id[64], name[64], symbol[16], cur[8];+ double price, change_24h, cap;+ time_t at;+};++struct pr_quote {+ char symbol[32], name[96], region[48], currency[8], day[11];+ double price, open, high, low, prev, change, change_pct;+ long volume;+};++#define PR_POINTS 400++struct pr_series { /* a value over time: inflation, a rate, a price */+ char label[96], unit[32];+ struct {+ char when[24]; /* "2026-08", "2026-10-01", "14:00" */+ double v;+ } p[PR_POINTS];+ int n;+};++#define PR_STATIONS 12++struct pr_station {+ char name[96], address[160], city[64];+ double lat, lon, km, price;+ int self; /* 1 self-service, 0 served, -1 not said */+ char updated[24];+};++struct pr_fuel {+ char fuel[24]; /* what the source calls it: "Gasolio", "Gazole" */+ int found; /* stations within the radius selling it */+ int stale; /* left out: a price not told for over STALE_DAYS */+ double cheapest, average;+ struct pr_station s[PR_STATIONS];+ int n;+};++/* The fuels asked for, as the tools name them */+enum pr_fuel_kind { PR_PETROL, PR_DIESEL, PR_LPG, PR_CNG };++int pr_read_frankfurter(const char *t, size_t n, struct pr_fx *fx, char *err,+ size_t err_len);+int pr_read_ecb_xml(const char *t, size_t n, struct pr_fx *fx, char *err,+ size_t err_len);+/* CoinGecko's search: the id of the coin named (by id, symbol or name,+ the best ranked); 0, or -1 */+int pr_read_coin_search(const char *t, size_t n, const char *q,+ struct pr_coin *c, char *err, size_t err_len);+/* CoinGecko's simple price for c->id in cur */+int pr_read_coin_price(const char *t, size_t n, struct pr_coin *c, char *err,+ size_t err_len);+/* Coinbase's spot price */+int pr_read_coinbase(const char *t, size_t n, struct pr_coin *c, char *err,+ size_t err_len);+/* Alpha Vantage: the best match of a search, a quote */+int pr_read_av_search(const char *t, size_t n, struct pr_quote *q, char *err,+ size_t err_len);+int pr_read_av_quote(const char *t, size_t n, struct pr_quote *q, char *err,+ size_t err_len);+/* Eurostat's JSON-stat with one series over time (the last points) */+int pr_read_eurostat(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len);+/* The World Bank's indicator for one country, oldest first */+int pr_read_worldbank(const char *t, size_t n, struct pr_series *s,+ char *country, size_t cap, char *err, size_t err_len);+/* The ECB's data API in CSV (TIME_PERIOD, OBS_VALUE) */+int pr_read_ecb_csv(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len);+/* The Bank of England's database in CSV (DATE,CODE) */+int pr_read_boe_csv(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len);+/* The Swiss National Bank's cube in JSON */+int pr_read_snb(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len);+/* The New York Fed's EFFR, with the FOMC's target range */+int pr_read_nyfed(const char *t, size_t n, struct pr_series *s, double *lo,+ double *hi, char *err, size_t err_len);+/* energy-charts' day-ahead prices: 1 when open data (licence CC BY), 0+ when not (its licence into licence), -1 on error */+int pr_read_power(const char *t, size_t n, const char *tz, struct pr_series *s,+ char *licence, size_t cap, char *err, size_t err_len);++/* ---- fuel.c: the stations of each country, nearest the place ---- */++struct pr_fuel_ask {+ double lat, lon, radius_km;+ enum pr_fuel_kind kind;+ time_t now; /* for the prices' age */+};++/* A price told longer ago is left out: a station's of two months before+ came first in Palermo */+#define PR_STALE_DAYS 8++/* Italy (MIMIT): the registry and the prices, both '|'-separated */+int pr_read_fuel_it(const char *registry, size_t rn, const char *prices,+ size_t pn, const struct pr_fuel_ask *a, struct pr_fuel *f,+ char *err, size_t err_len);+/* France: the records of the instant flow */+int pr_read_fuel_fr(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len);+/* Spain: a province's stations */+int pr_read_fuel_es(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len);+/* Austria: E-Control's stations by address */+int pr_read_fuel_at(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len);+/* The stations kept: those whose price is not stale, the cheapest+ first, the nearest of equal price */+void pr_fuel_rank(struct pr_fuel *f, struct pr_station *all, int n, time_t now);++/* ---- data.c ---- */++void pr_jstr(struct janas_buf *b, const char *key, const char *v);+void pr_jnum(struct janas_buf *b, const char *key, double v, int decimals);+/* A number with its decimals for a price: 2, 4 or 6 as it is small */+int pr_decimals(double v);+void pr_jplace(struct janas_buf *b, const char *key, const struct pr_place *p);+void pr_fx_data(struct janas_buf *b, double amount, const char *from,+ const struct pr_fx *fx, const char *source);+void pr_coin_data(struct janas_buf *b, const struct pr_coin *c,+ const char *source);+void pr_quote_data(struct janas_buf *b, const struct pr_quote *q);+/* source and note: words of the layout (src.*, note.*); licence as the+ source gives it */+void pr_series_data(struct janas_buf *b, const char *what, const char *who,+ const struct pr_series *s, int last, const char *source,+ const char *note, const char *licence);+/* A central bank's rates: name, value and date of each */+struct pr_rate {+ char name[64], when[24];+ double v;+};+void pr_rates_data(struct janas_buf *b, const char *bank,+ const struct pr_rate *r, int n, double lo, double hi,+ const char *source);+void pr_fuel_data(struct janas_buf *b, const struct pr_place *p,+ const char *kind, double radius, const struct pr_fuel *f,+ const char *source);++/* ---- layouts.c ---- */++extern const char PR_FX_LAYOUT[], PR_FX_BRIEF[];+extern const char PR_COIN_LAYOUT[], PR_COIN_BRIEF[];+extern const char PR_QUOTE_LAYOUT[], PR_QUOTE_BRIEF[];+extern const char PR_SERIES_LAYOUT[], PR_SERIES_BRIEF[];+extern const char PR_RATES_LAYOUT[], PR_RATES_BRIEF[];+extern const char PR_FUEL_LAYOUT[], PR_FUEL_BRIEF[];++/* ---- tools.c, money.c, macro.c, fuel.c ---- */++void pr_tools_list(void *ctx, struct janas_buf *b);+int pr_tools_call(void *ctx, const struct janas_json *params,+ struct janas_buf *b);+const char *pr_arg_str(const struct janas_json *args, const char *name);+double pr_arg_num(const struct janas_json *args, const char *name, double def);+int pr_fail(struct janas_buf *b, const char *fmt, ...)+ __attribute__((format(printf, 2, 3)));+int pr_answer(struct janas_buf *b, const char *name, struct janas_buf *d,+ const char *layout, const char *brief);+int pr_tool_currency(const struct janas_json *args, struct janas_buf *b);+int pr_tool_crypto(const struct janas_json *args, struct janas_buf *b);+int pr_tool_stock(const struct janas_json *args, struct janas_buf *b);+int pr_tool_inflation(const struct janas_json *args, struct janas_buf *b);+int pr_tool_rates(const struct janas_json *args, struct janas_buf *b);+int pr_tool_power(const struct janas_json *args, struct janas_buf *b);+int pr_tool_fuel(const struct janas_json *args, struct janas_buf *b);++#endifdiff --git a/src/prices/read.c b/src/prices/read.cnew file mode 100644index 0000000..04b96d5--- /dev/null+++ b/src/prices/read.c@@ -0,0 +1,571 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * read.c - janas-prices reads its sources' answers (see prices.h): the+ * rates of currencies (Frankfurter, the ECB), the prices of crypto-assets+ * (CoinGecko, Coinbase), shares (Alpha Vantage), inflation (Eurostat, the+ * World Bank), central banks' rates (the ECB, the Bank of England, the+ * Swiss National Bank, the New York Fed) and electricity (energy-charts).+ * The fuels are in read_fuel.c. No network here, so that the tests can+ * read answers kept as they came.+ */+#define _GNU_SOURCE /* strcasecmp, timegm */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include <time.h>++#include "prices.h"++static void copy(char *to, size_t cap, const char *s)+{+ snprintf(to, cap, "%s", s ? s : "");+}++static const char *str(const struct janas_json *o, const char *key)+{+ const char *s = janas_json_str(janas_json_get(o, key));+ return s && *s ? s : NULL;+}++/* a number given as a number or as a text ("225.6200", "2.5872%") */+static double num(const struct janas_json *o, const char *key)+{+ const struct janas_json *v = janas_json_get(o, key);+ if (v && v->type == JANAS_JSON_STRING) {+ char *end;+ double d = strtod(v->s, &end);+ return end > v->s ? d : NAN;+ }+ return janas_json_num(v, NAN);+}++static struct janas_json_doc *parse(const char *t, size_t n, const char *who,+ char *err, size_t err_len)+{+ char why[128];+ struct janas_json_doc *d = janas_json_parse(t, n, why, sizeof why);+ if (!d)+ snprintf(err, err_len, "%s: an answer it could not read (%s)", who,+ why);+ return d;+}++static void add(struct pr_series *s, const char *when, double v)+{+ if (s->n < PR_POINTS && !isnan(v)) {+ copy(s->p[s->n].when, sizeof s->p[s->n].when, when);+ s->p[s->n++].v = v;+ }+}++/* ---- currencies ---- */++int pr_read_frankfurter(const char *t, size_t n, struct pr_fx *fx, char *err,+ size_t err_len)+{+ memset(fx, 0, sizeof *fx);+ struct janas_json_doc *d = parse(t, n, "Frankfurter", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_root(d);+ copy(fx->base, sizeof fx->base, str(o, "base"));+ copy(fx->date, sizeof fx->date, str(o, "date"));+ const struct janas_json *r = janas_json_get(o, "rates");+ for (const struct janas_json *x = r ? r->child : NULL;+ x && fx->n < PR_RATES; x = x->next) {+ snprintf(fx->r[fx->n].code, sizeof fx->r[fx->n].code, "%.*s",+ (int)x->key_n, x->key);+ fx->r[fx->n++].rate = janas_json_num(x, NAN);+ }+ const char *m = str(o, "message");+ janas_json_free(d);+ if (!fx->base[0] || !fx->n) {+ snprintf(err, err_len, "Frankfurter: %s", m ? m : "no rates");+ return -1;+ }+ return 0;+}++/* <Cube time='2026-10-02'> ... <Cube currency='USD' rate='1.1225'/> */+int pr_read_ecb_xml(const char *t, size_t n, struct pr_fx *fx, char *err,+ size_t err_len)+{+ memset(fx, 0, sizeof *fx);+ snprintf(fx->base, sizeof fx->base, "EUR");+ const char *e = t + n, *p = t;+ const char *tm = memmem(t, n, "time='", 6);+ if (tm && tm + 16 <= e)+ snprintf(fx->date, sizeof fx->date, "%.10s", tm + 6);+ while ((p = memmem(p, (size_t)(e - p), "currency='", 10)) &&+ fx->n < PR_RATES) {+ p += 10;+ const char *q = memchr(p, '\'', (size_t)(e - p));+ const char *r = q ? memmem(q, (size_t)(e - q), "rate='", 6) : NULL;+ if (!q || !r || q - p != 3)+ break;+ memcpy(fx->r[fx->n].code, p, 3);+ fx->r[fx->n].code[3] = 0;+ fx->r[fx->n++].rate = strtod(r + 6, NULL);+ p = r + 6;+ }+ if (!fx->n || !fx->date[0]) {+ snprintf(err, err_len, "the ECB: no rates in its answer");+ return -1;+ }+ return 0;+}++/* ---- crypto-assets ---- */++int pr_read_coin_search(const char *t, size_t n, const char *q,+ struct pr_coin *c, char *err, size_t err_len)+{+ memset(c, 0, sizeof *c);+ struct janas_json_doc *d = parse(t, n, "CoinGecko", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *coins =+ janas_json_get(janas_json_root(d), "coins");+ /* the id itself, else the symbol or the name of the best ranked (a+ symbol is taken by many tokens: "SOL" by a hundred) */+ const struct janas_json *best = NULL;+ int best_score = 0;+ double best_rank = 1e9;+ for (const struct janas_json *x = coins ? coins->child : NULL; x;+ x = x->next) {+ const char *id = str(x, "id"), *sym = str(x, "symbol"),+ *name = str(x, "name");+ int score = id && !strcasecmp(id, q) ? 3+ : sym && !strcasecmp(sym, q) ? 2+ : name && !strcasecmp(name, q) ? 2+ : 0;+ double rank = num(x, "market_cap_rank");+ if (isnan(rank))+ rank = 1e8;+ if (score > best_score ||+ (score == best_score && score && rank < best_rank)) {+ best = x;+ best_score = score;+ best_rank = rank;+ }+ }+ if (!best && coins && coins->child)+ best = coins->child;+ if (best) {+ copy(c->id, sizeof c->id, str(best, "id"));+ copy(c->name, sizeof c->name, str(best, "name"));+ copy(c->symbol, sizeof c->symbol, str(best, "symbol"));+ } else {+ snprintf(err, err_len, "CoinGecko knows no crypto-asset named %s", q);+ }+ janas_json_free(d);+ return best ? 0 : -1;+}++int pr_read_coin_price(const char *t, size_t n, struct pr_coin *c, char *err,+ size_t err_len)+{+ struct janas_json_doc *d = parse(t, n, "CoinGecko", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_get(janas_json_root(d), c->id);+ char k[48], lc[8];+ size_t i = 0;+ for (; c->cur[i] && i + 1 < sizeof lc; i++)+ lc[i] = (char)(c->cur[i] | 0x20);+ lc[i] = 0;+ c->price = num(o, lc);+ snprintf(k, sizeof k, "%s_24h_change", lc);+ c->change_24h = num(o, k);+ snprintf(k, sizeof k, "%s_market_cap", lc);+ c->cap = num(o, k);+ double at = num(o, "last_updated_at");+ c->at = isnan(at) ? -1 : (time_t)at;+ janas_json_free(d);+ if (isnan(c->price)) {+ snprintf(err, err_len, "CoinGecko gave no price of %s in %s", c->id,+ c->cur);+ return -1;+ }+ return 0;+}++int pr_read_coinbase(const char *t, size_t n, struct pr_coin *c, char *err,+ size_t err_len)+{+ struct janas_json_doc *d = parse(t, n, "Coinbase", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_get(janas_json_root(d), "data");+ c->price = num(o, "amount");+ c->change_24h = c->cap = NAN;+ c->at = time(NULL);+ janas_json_free(d);+ if (isnan(c->price)) {+ snprintf(err, err_len, "Coinbase gave no price");+ return -1;+ }+ return 0;+}++/* ---- shares ---- */++/* Alpha Vantage says what went wrong in a member of its own */+static int av_error(const struct janas_json *o, char *err, size_t err_len)+{+ const char *m = str(o, "Error Message");+ if (!m)+ m = str(o, "Note");+ if (!m)+ m = str(o, "Information");+ if (m)+ snprintf(err, err_len, "Alpha Vantage: %.300s", m);+ return m != NULL;+}++int pr_read_av_search(const char *t, size_t n, struct pr_quote *q, char *err,+ size_t err_len)+{+ memset(q, 0, sizeof *q);+ struct janas_json_doc *d = parse(t, n, "Alpha Vantage", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_root(d);+ const struct janas_json *m = janas_json_get(o, "bestMatches");+ const struct janas_json *x = m ? m->child : NULL;+ int r = -1;+ if (x) {+ copy(q->symbol, sizeof q->symbol, str(x, "1. symbol"));+ copy(q->name, sizeof q->name, str(x, "2. name"));+ copy(q->region, sizeof q->region, str(x, "4. region"));+ copy(q->currency, sizeof q->currency, str(x, "8. currency"));+ r = q->symbol[0] ? 0 : -1;+ } else if (!av_error(o, err, err_len)) {+ snprintf(err, err_len, "Alpha Vantage found no share of that name");+ }+ janas_json_free(d);+ return r;+}++int pr_read_av_quote(const char *t, size_t n, struct pr_quote *q, char *err,+ size_t err_len)+{+ struct janas_json_doc *d = parse(t, n, "Alpha Vantage", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_root(d);+ const struct janas_json *g = janas_json_get(o, "Global Quote");+ int r = -1;+ if (g && str(g, "01. symbol")) {+ copy(q->symbol, sizeof q->symbol, str(g, "01. symbol"));+ q->open = num(g, "02. open");+ q->high = num(g, "03. high");+ q->low = num(g, "04. low");+ q->price = num(g, "05. price");+ double v = num(g, "06. volume");+ q->volume = isnan(v) ? -1 : (long)v;+ copy(q->day, sizeof q->day, str(g, "07. latest trading day"));+ q->prev = num(g, "08. previous close");+ q->change = num(g, "09. change");+ q->change_pct = num(g, "10. change percent");+ r = isnan(q->price) ? -1 : 0;+ if (r)+ snprintf(err, err_len, "Alpha Vantage gave no price");+ } else if (!av_error(o, err, err_len)) {+ snprintf(err, err_len, "Alpha Vantage has no quote of that symbol");+ }+ janas_json_free(d);+ return r;+}++/* ---- inflation ---- */++/* JSON-stat: one series, the time its only dimension of more than one+ value; "value" maps the positions to the numbers */+int pr_read_eurostat(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len)+{+ memset(s, 0, sizeof *s);+ struct janas_json_doc *d = parse(t, n, "Eurostat", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_root(d);+ copy(s->label, sizeof s->label, str(o, "label"));+ const struct janas_json *tm = janas_json_get(+ janas_json_get(janas_json_get(janas_json_get(o, "dimension"), "time"),+ "category"),+ "index");+ const struct janas_json *val = janas_json_get(o, "value");+ for (const struct janas_json *x = tm ? tm->child : NULL; x; x = x->next) {+ char k[16], when[24];+ snprintf(k, sizeof k, "%.0f", janas_json_num(x, -1));+ snprintf(when, sizeof when, "%.*s", (int)x->key_n, x->key);+ add(s, when, janas_json_num(janas_json_get(val, k), NAN));+ }+ const struct janas_json *e = janas_json_get(o, "error");+ const char *m = e ? str(e, "label") : NULL;+ janas_json_free(d);+ if (!s->n) {+ snprintf(err, err_len, "Eurostat: %s", m ? m : "no values");+ return -1;+ }+ return 0;+}++int pr_read_worldbank(const char *t, size_t n, struct pr_series *s,+ char *country, size_t cap, char *err, size_t err_len)+{+ memset(s, 0, sizeof *s);+ struct janas_json_doc *d = parse(t, n, "the World Bank", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *a = janas_json_root(d);+ const struct janas_json *rows = a && a->child ? a->child->next : NULL;+ /* newest first: kept, then turned */+ const char *first = NULL; /* one country's rows: the first's */+ for (const struct janas_json *x = rows ? rows->child : NULL; x;+ x = x->next) {+ const char *cn = str(janas_json_get(x, "country"), "value");+ if (!first)+ first = cn;+ if (!cn || !first || strcmp(cn, first) != 0)+ continue;+ if (!country[0])+ copy(country, cap, cn);+ if (!s->label[0])+ copy(s->label, sizeof s->label,+ str(janas_json_get(x, "indicator"), "value"));+ add(s, str(x, "date"), num(x, "value"));+ }+ for (int i = 0; i < s->n / 2; i++) {+ __typeof__(s->p[0]) tmp = s->p[i];+ s->p[i] = s->p[s->n - 1 - i];+ s->p[s->n - 1 - i] = tmp;+ }+ janas_json_free(d);+ if (!s->n) {+ snprintf(err, err_len, "the World Bank has no values for it");+ return -1;+ }+ return 0;+}++/* ---- central banks ---- */++/* The fields of a CSV line, quotes taken into account: field k into+ out. 0, or -1 when there are fewer. */+static int csv_field(const char *line, size_t len, int k, char *out, size_t cap)+{+ int f = 0, q = 0;+ size_t o = 0;+ for (size_t i = 0; i <= len; i++) {+ char c = i < len ? line[i] : ',';+ if (c == '"') {+ q = !q;+ continue;+ }+ if (c == ',' && !q) {+ if (f == k) {+ out[o < cap ? o : cap - 1] = 0;+ return 0;+ }+ f++;+ o = 0;+ continue;+ }+ if (f == k && o + 1 < cap)+ out[o++] = c;+ }+ return -1;+}++static int csv_column(const char *head, size_t len, const char *name)+{+ char f[64];+ for (int k = 0; csv_field(head, len, k, f, sizeof f) == 0; k++)+ if (strcmp(f, name) == 0)+ return k;+ return -1;+}++int pr_read_ecb_csv(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len)+{+ memset(s, 0, sizeof *s);+ const char *p = t, *e = t + n;+ const char *nl = memchr(p, '\n', n);+ if (!nl) {+ snprintf(err, err_len, "the ECB: no data");+ return -1;+ }+ size_t hl = (size_t)(nl - p);+ int ct = csv_column(p, hl, "TIME_PERIOD"),+ cv = csv_column(p, hl, "OBS_VALUE"), cl = csv_column(p, hl, "TITLE");+ if (ct < 0 || cv < 0) {+ snprintf(err, err_len, "the ECB: not its CSV");+ return -1;+ }+ for (p = nl + 1; p < e;) {+ nl = memchr(p, '\n', (size_t)(e - p));+ size_t len = nl ? (size_t)(nl - p) : (size_t)(e - p);+ char when[24], v[32];+ if (len && csv_field(p, len, ct, when, sizeof when) == 0 &&+ csv_field(p, len, cv, v, sizeof v) == 0 && v[0]) {+ add(s, when, strtod(v, NULL));+ if (!s->label[0] && cl >= 0)+ csv_field(p, len, cl, s->label, sizeof s->label);+ }+ p = nl ? nl + 1 : e;+ }+ if (!s->n) {+ snprintf(err, err_len, "the ECB: no values");+ return -1;+ }+ return 0;+}++/* "01 Sep 2026" -> "2026-09-01" */+static void boe_date(const char *d, char *out, size_t cap)+{+ static const char mon[] = "JanFebMarAprMayJunJulAugSepOctNovDec";+ int day, year;+ char m[4];+ if (sscanf(d, "%d %3s %d", &day, m, &year) == 3) {+ const char *at = strstr(mon, m);+ if (at && (at - mon) % 3 == 0) {+ snprintf(out, cap, "%04d-%02d-%02d", year, (int)(at - mon) / 3 + 1,+ day);+ return;+ }+ }+ copy(out, cap, d);+}++int pr_read_boe_csv(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len)+{+ memset(s, 0, sizeof *s);+ const char *p = t, *e = t + n;+ const char *nl = memchr(p, '\n', n);+ if (!nl || strncmp(p, "DATE,", 5) != 0) {+ snprintf(err, err_len, "the Bank of England: not its CSV");+ return -1;+ }+ for (p = nl + 1; p < e;) {+ nl = memchr(p, '\n', (size_t)(e - p));+ size_t len = nl ? (size_t)(nl - p) : (size_t)(e - p);+ char d[24], v[32], when[24];+ if (csv_field(p, len, 0, d, sizeof d) == 0 &&+ csv_field(p, len, 1, v, sizeof v) == 0 && v[0] && v[0] != '\r') {+ boe_date(d, when, sizeof when);+ add(s, when, strtod(v, NULL));+ }+ p = nl ? nl + 1 : e;+ }+ if (!s->n) {+ snprintf(err, err_len, "the Bank of England: no values");+ return -1;+ }+ return 0;+}++int pr_read_snb(const char *t, size_t n, struct pr_series *s, char *err,+ size_t err_len)+{+ memset(s, 0, sizeof *s);+ struct janas_json_doc *d = parse(t, n, "the SNB", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *ts =+ janas_json_get(janas_json_root(d), "timeseries");+ const struct janas_json *x = ts ? ts->child : NULL;+ const struct janas_json *v = janas_json_get(x, "values");+ for (const struct janas_json *p = v ? v->child : NULL; p; p = p->next)+ add(s, str(p, "date"), num(p, "value"));+ janas_json_free(d);+ if (!s->n) {+ snprintf(err, err_len, "the SNB: no values");+ return -1;+ }+ return 0;+}++int pr_read_nyfed(const char *t, size_t n, struct pr_series *s, double *lo,+ double *hi, char *err, size_t err_len)+{+ memset(s, 0, sizeof *s);+ *lo = *hi = NAN;+ struct janas_json_doc *d = parse(t, n, "the New York Fed", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *r = janas_json_get(janas_json_root(d), "refRates");+ /* newest first */+ int k = 0;+ for (const struct janas_json *x = r ? r->child : NULL; x; x = x->next)+ k++;+ for (int i = k - 1; i >= 0; i--) {+ const struct janas_json *x = r->child;+ for (int j = 0; j < i; j++)+ x = x->next;+ add(s, str(x, "effectiveDate"), num(x, "percentRate"));+ if (i == 0) {+ *lo = num(x, "targetRateFrom");+ *hi = num(x, "targetRateTo");+ }+ }+ janas_json_free(d);+ if (!s->n) {+ snprintf(err, err_len, "the New York Fed: no values");+ return -1;+ }+ return 0;+}++/* ---- electricity ---- */++int pr_read_power(const char *t, size_t n, const char *tz, struct pr_series *s,+ char *licence, size_t cap, char *err, size_t err_len)+{+ memset(s, 0, sizeof *s);+ licence[0] = 0;+ struct janas_json_doc *d = parse(t, n, "energy-charts", err, err_len);+ if (!d)+ return -1;+ const struct janas_json *o = janas_json_root(d);+ copy(licence, cap, str(o, "license_info"));+ copy(s->unit, sizeof s->unit, str(o, "unit"));+ int open = strstr(licence, "CC BY") != NULL;+ const struct janas_json *ts = janas_json_get(o, "unix_seconds");+ const struct janas_json *pr = janas_json_get(o, "price");+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;+ if (tz && *tz)+ setenv("TZ", tz, 1);+ tzset();+ const struct janas_json *x = ts ? ts->child : NULL;+ const struct janas_json *y = pr ? pr->child : NULL;+ for (; open && x && y; x = x->next, y = y->next) {+ time_t at = (time_t)janas_json_num(x, 0);+ struct tm lt;+ localtime_r(&at, <);+ char when[24];+ strftime(when, sizeof when, "%Y-%m-%d %H:%M", <);+ add(s, when, janas_json_num(y, NAN));+ }+ if (tz && *tz) {+ if (old)+ setenv("TZ", old, 1);+ else+ unsetenv("TZ");+ tzset();+ }+ free(old);+ janas_json_free(d);+ if (!licence[0] || (open && !s->n)) {+ snprintf(err, err_len, "energy-charts: no prices");+ return -1;+ }+ return open;+}diff --git a/src/prices/read_fuel.c b/src/prices/read_fuel.cnew file mode 100644index 0000000..f4b48d0--- /dev/null+++ b/src/prices/read_fuel.c@@ -0,0 +1,416 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * read_fuel.c - the fuel prices of the countries that publish them as open+ * data (see prices.h), each source as it gives them: Italy's ministry+ * (MIMIT) a registry of the stations and their prices, two files+ * '|'-separated, France's instant flow, Spain's stations of a province,+ * Austria's E-Control the stations near a point. Then the same list: the+ * stations within the radius selling the fuel, the cheapest first. No+ * network here, so that the tests can read answers kept as they came.+ */+#define _GNU_SOURCE /* strcasecmp, timegm */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include <time.h>++#include "common/geo.h"+#include "prices.h"++#define ALL_MAX 4096 /* stations within a radius, at most */++static void fcopy(char *to, size_t cap, const char *s, size_t n)+{+ snprintf(to, cap, "%.*s", (int)(n < cap ? n : cap - 1), s ? s : "");+}++static const char *fstr(const struct janas_json *o, const char *key)+{+ const char *s = janas_json_str(janas_json_get(o, key));+ return s && *s ? s : NULL;+}++/* "1,559" or "1.559" or a number */+static double num_any(const struct janas_json *o, const char *key)+{+ const struct janas_json *v = janas_json_get(o, key);+ if (v && v->type == JANAS_JSON_STRING) {+ char b[32];+ snprintf(b, sizeof b, "%s", v->s);+ for (char *c = b; *c; c++)+ if (*c == ',')+ *c = '.';+ char *end;+ double d = strtod(b, &end);+ return end > b ? d : NAN;+ }+ return janas_json_num(v, NAN);+}++static int cmp_station(const void *a, const void *b)+{+ const struct pr_station *x = a, *y = b;+ if (x->price != y->price)+ return x->price < y->price ? -1 : 1;+ return x->km < y->km ? -1 : x->km > y->km;+}++/* "29/09/2026 08:29:00" or "2026-10-02 09:21": when; -1 when neither */+static time_t told(const char *s)+{+ struct tm tm = {0};+ if (sscanf(s, "%d/%d/%d %d:%d", &tm.tm_mday, &tm.tm_mon, &tm.tm_year,+ &tm.tm_hour, &tm.tm_min) != 5 &&+ sscanf(s, "%d-%d-%d %d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday,+ &tm.tm_hour, &tm.tm_min) != 5)+ return -1;+ tm.tm_year -= 1900;+ tm.tm_mon -= 1;+ return timegm(&tm);+}++void pr_fuel_rank(struct pr_fuel *f, struct pr_station *all, int n, time_t now)+{+ int k = 0;+ f->stale = 0;+ for (int i = 0; i < n; i++) {+ time_t t = told(all[i].updated);+ if (t > 0 && now - t > PR_STALE_DAYS * 86400)+ f->stale++;+ else+ all[k++] = all[i];+ }+ n = k;+ qsort(all, (size_t)n, sizeof *all, cmp_station);+ f->found = n;+ f->cheapest = n ? all[0].price : NAN;+ double sum = 0;+ for (int i = 0; i < n; i++)+ sum += all[i].price;+ f->average = n ? sum / n : NAN;+ f->n = n < PR_STATIONS ? n : PR_STATIONS;+ memcpy(f->s, all, (size_t)f->n * sizeof *all);+}++/* ---- Italy ---- */++/* The fields of a line '|'-separated: up to max, pointers and lengths */+static int fields(const char *p, const char *e, const char **f, size_t *fl,+ int max)+{+ int k = 0;+ while (k < max) {+ const char *bar = memchr(p, '|', (size_t)(e - p));+ f[k] = p;+ fl[k] = (size_t)((bar ? bar : e) - p);+ k++;+ if (!bar)+ break;+ p = bar + 1;+ }+ return k;+}++struct near_it {+ long id;+ struct pr_station s;+};++static int cmp_id(const void *a, const void *b)+{+ const struct near_it *x = a, *y = b;+ return x->id < y->id ? -1 : x->id > y->id;+}++static void trim(char *s)+{+ size_t n = strlen(s);+ while (n && (s[n - 1] == ' ' || s[n - 1] == '\r'))+ s[--n] = 0;+}++int pr_read_fuel_it(const char *registry, size_t rn, const char *prices,+ size_t pn, const struct pr_fuel_ask *a, struct pr_fuel *f,+ char *err, size_t err_len)+{+ static const char *const names[] = {"Benzina", "Gasolio", "GPL", "Metano"};+ memset(f, 0, sizeof *f);+ snprintf(f->fuel, sizeof f->fuel, "%s", names[a->kind]);+ struct near_it *near = malloc(ALL_MAX * sizeof *near);+ if (!near) {+ snprintf(err, err_len, "out of memory");+ return -1;+ }+ int nn = 0;+ /* idImpianto|Gestore|Bandiera|Tipo Impianto|Nome Impianto|Indirizzo|+ Comune|Provincia|Latitudine|Longitudine, after two lines */+ const char *p = registry, *e = registry + rn;+ for (int line = 0; p < e; line++) {+ const char *nl = memchr(p, '\n', (size_t)(e - p));+ const char *le = nl ? nl : e;+ const char *fv[10];+ size_t fl[10];+ if (line >= 2 && fields(p, le, fv, fl, 10) == 10 && nn < ALL_MAX) {+ double lat = strtod(fv[8], NULL), lon = strtod(fv[9], NULL);+ double km = geo_km(a->lat, a->lon, lat, lon);+ if (lat != 0 && km <= a->radius_km) {+ struct near_it *x = &near[nn++];+ memset(x, 0, sizeof *x);+ x->id = strtol(fv[0], NULL, 10);+ /* the brand, or the operator of an unbranded one */+ int white = fl[2] == 13 && !strncmp(fv[2], "Pompe Bianche", 13);+ fcopy(x->s.name, sizeof x->s.name, white ? fv[1] : fv[2],+ white ? fl[1] : fl[2]);+ fcopy(x->s.address, sizeof x->s.address, fv[5], fl[5]);+ fcopy(x->s.city, sizeof x->s.city, fv[6], fl[6]);+ trim(x->s.name);+ trim(x->s.address);+ trim(x->s.city);+ x->s.lat = lat;+ x->s.lon = lon;+ x->s.km = km;+ x->s.price = NAN;+ x->s.self = -1;+ }+ }+ p = nl ? nl + 1 : e;+ }+ qsort(near, (size_t)nn, sizeof *near, cmp_id);+ /* idImpianto|descCarburante|prezzo|isSelf|dtComu: the self-service+ price where there is one, else the served one */+ size_t want = strlen(names[a->kind]);+ p = prices;+ e = prices + pn;+ for (int line = 0; p < e; line++) {+ const char *nl = memchr(p, '\n', (size_t)(e - p));+ const char *le = nl ? nl : e;+ const char *fv[5];+ size_t fl[5];+ if (line >= 2 && fields(p, le, fv, fl, 5) == 5 && fl[1] == want &&+ !strncasecmp(fv[1], names[a->kind], want)) {+ struct near_it key = {.id = strtol(fv[0], NULL, 10)};+ struct near_it *x =+ bsearch(&key, near, (size_t)nn, sizeof *near, cmp_id);+ int self = fv[3][0] == '1';+ if (x && (x->s.self != 1 || self)) {+ x->s.price = strtod(fv[2], NULL);+ x->s.self = self;+ fcopy(x->s.updated, sizeof x->s.updated, fv[4], fl[4]);+ trim(x->s.updated);+ }+ }+ p = nl ? nl + 1 : e;+ }+ struct pr_station *all = malloc((size_t)(nn ? nn : 1) * sizeof *all);+ int k = 0;+ for (int i = 0; all && i < nn; i++)+ if (!isnan(near[i].s.price) && near[i].s.price > 0)+ all[k++] = near[i].s;+ free(near);+ if (!all) {+ snprintf(err, err_len, "out of memory");+ return -1;+ }+ pr_fuel_rank(f, all, k, a->now);+ free(all);+ return 0;+}++/* ---- France ---- */++int pr_read_fuel_fr(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len)+{+ static const char *const field[][2] = {{"e10_prix", "sp95_prix"},+ {"gazole_prix", NULL},+ {"gplc_prix", NULL},+ {NULL, NULL}};+ static const char *const names[] = {"SP95-E10", "Gazole", "GPLc", "GNV"};+ memset(f, 0, sizeof *f);+ snprintf(f->fuel, sizeof f->fuel, "%s", names[a->kind]);+ if (!field[a->kind][0]) {+ snprintf(err, err_len, "France's open data has no price of %s",+ names[a->kind]);+ return -1;+ }+ char why[128];+ struct janas_json_doc *d = janas_json_parse(t, n, why, sizeof why);+ if (!d) {+ snprintf(err, err_len,+ "France's fuel prices: an answer it could "+ "not read (%s)",+ why);+ return -1;+ }+ const struct janas_json *o = janas_json_root(d);+ const struct janas_json *r = janas_json_get(o, "results");+ struct pr_station all[100];+ int k = 0;+ for (const struct janas_json *x = r ? r->child : NULL; x && k < 100;+ x = x->next) {+ const char *fld = field[a->kind][0];+ double price = num_any(x, fld);+ if (isnan(price) && field[a->kind][1]) {+ fld = field[a->kind][1];+ price = num_any(x, fld);+ }+ const struct janas_json *g = janas_json_get(x, "geom");+ double lat = num_any(g, "lat"), lon = num_any(g, "lon");+ if (isnan(price) || isnan(lat))+ continue;+ struct pr_station *s = &all[k++];+ memset(s, 0, sizeof *s);+ const char *ad = fstr(x, "adresse"), *ci = fstr(x, "ville");+ fcopy(s->address, sizeof s->address, ad, ad ? strlen(ad) : 0);+ fcopy(s->city, sizeof s->city, ci, ci ? strlen(ci) : 0);+ s->lat = lat;+ s->lon = lon;+ s->km = geo_km(a->lat, a->lon, lat, lon);+ s->price = price;+ s->self = -1;+ char maj[32];+ snprintf(maj, sizeof maj, "%.*s_maj", (int)(strlen(fld) - 5), fld);+ const char *m = fstr(x, maj);+ fcopy(s->updated, sizeof s->updated, m, m ? 16 : 0); /* to minutes */+ if (s->updated[10] == 'T')+ s->updated[10] = ' ';+ }+ double total = num_any(o, "total_count");+ janas_json_free(d);+ pr_fuel_rank(f, all, k, a->now);+ /* the stations asked for were the cheapest of them all: the average+ of those is not the area's */+ if (!isnan(total) && total > k) {+ f->found = (int)total;+ f->average = NAN;+ }+ return 0;+}++/* ---- Spain ---- */++int pr_read_fuel_es(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len)+{+ static const char *const field[] = {+ "Precio Gasolina 95 E5", "Precio Gasoleo A",+ "Precio Gases licuados del petróleo", "Precio Gas Natural Comprimido"};+ static const char *const names[] = {"Gasolina 95 E5", "Gasóleo A", "GLP",+ "GNC"};+ memset(f, 0, sizeof *f);+ snprintf(f->fuel, sizeof f->fuel, "%s", names[a->kind]);+ char why[128];+ struct janas_json_doc *d = janas_json_parse(t, n, why, sizeof why);+ if (!d) {+ snprintf(err, err_len,+ "Spain's fuel prices: an answer it could not "+ "read (%s)",+ why);+ return -1;+ }+ const struct janas_json *o = janas_json_root(d);+ const char *when = fstr(o, "Fecha"); /* "02/10/2026 16:48:00" */+ char upd[24] = "";+ int dd, mm, yy, hh, mi;+ if (when && sscanf(when, "%d/%d/%d %d:%d", &dd, &mm, &yy, &hh, &mi) == 5)+ snprintf(upd, sizeof upd, "%04d-%02d-%02d %02d:%02d", yy, mm, dd, hh,+ mi);+ const struct janas_json *r = janas_json_get(o, "ListaEESSPrecio");+ struct pr_station *all = malloc(ALL_MAX * sizeof *all);+ int k = 0;+ for (const struct janas_json *x = r ? r->child : NULL; all && x;+ x = x->next) {+ double price = num_any(x, field[a->kind]);+ double lat = num_any(x, "Latitud"),+ lon = num_any(x, "Longitud (WGS84)");+ if (isnan(price) || isnan(lat) || isnan(lon) || k >= ALL_MAX)+ continue;+ double km = geo_km(a->lat, a->lon, lat, lon);+ if (km > a->radius_km)+ continue;+ struct pr_station *s = &all[k++];+ memset(s, 0, sizeof *s);+ const char *nm = fstr(x, "Rótulo"), *ad = fstr(x, "Dirección"),+ *ci = fstr(x, "Localidad");+ fcopy(s->name, sizeof s->name, nm, nm ? strlen(nm) : 0);+ fcopy(s->address, sizeof s->address, ad, ad ? strlen(ad) : 0);+ fcopy(s->city, sizeof s->city, ci, ci ? strlen(ci) : 0);+ s->lat = lat;+ s->lon = lon;+ s->km = km;+ s->price = price;+ s->self = -1;+ snprintf(s->updated, sizeof s->updated, "%s", upd);+ }+ janas_json_free(d);+ if (!all) {+ snprintf(err, err_len, "out of memory");+ return -1;+ }+ pr_fuel_rank(f, all, k, a->now);+ free(all);+ return 0;+}++/* ---- Austria ---- */++int pr_read_fuel_at(const char *t, size_t n, const struct pr_fuel_ask *a,+ struct pr_fuel *f, char *err, size_t err_len)+{+ static const char *const code[] = {"SUP", "DIE", NULL, "GAS"};+ static const char *const names[] = {"Super 95", "Diesel", "LPG", "CNG"};+ memset(f, 0, sizeof *f);+ snprintf(f->fuel, sizeof f->fuel, "%s", names[a->kind]);+ if (!code[a->kind]) {+ snprintf(err, err_len, "E-Control has no price of %s", names[a->kind]);+ return -1;+ }+ char why[128];+ struct janas_json_doc *d = janas_json_parse(t, n, why, sizeof why);+ if (!d) {+ snprintf(err, err_len, "E-Control: an answer it could not read (%s)",+ why);+ return -1;+ }+ struct pr_station all[64];+ int k = 0;+ const struct janas_json *r = janas_json_root(d);+ for (const struct janas_json *x =+ r && r->type == JANAS_JSON_ARRAY ? r->child : NULL;+ x && k < 64; x = x->next) {+ const struct janas_json *ps = janas_json_get(x, "prices");+ double price = NAN;+ for (const struct janas_json *y = ps ? ps->child : NULL; y; y = y->next)+ if (janas_json_is(janas_json_get(y, "fuelType"), code[a->kind]))+ price = num_any(y, "amount");+ const struct janas_json *l = janas_json_get(x, "location");+ double lat = num_any(l, "latitude"), lon = num_any(l, "longitude");+ if (isnan(price) || isnan(lat))+ continue;+ double km = geo_km(a->lat, a->lon, lat, lon);+ if (km > a->radius_km)+ continue;+ struct pr_station *s = &all[k++];+ memset(s, 0, sizeof *s);+ const char *nm = fstr(x, "name"), *ad = fstr(l, "address"),+ *ci = fstr(l, "city");+ fcopy(s->name, sizeof s->name, nm, nm ? strlen(nm) : 0);+ fcopy(s->address, sizeof s->address, ad, ad ? strlen(ad) : 0);+ fcopy(s->city, sizeof s->city, ci, ci ? strlen(ci) : 0);+ s->lat = lat;+ s->lon = lon;+ s->km = km;+ s->price = price;+ const struct janas_json *of = janas_json_get(x, "offerInformation");+ const struct janas_json *sv = janas_json_get(of, "selfService");+ s->self = sv && sv->type == JANAS_JSON_TRUE ? 1+ : sv && sv->type == JANAS_JSON_FALSE ? 0+ : -1;+ }+ janas_json_free(d);+ pr_fuel_rank(f, all, k, a->now);+ return 0;+}diff --git a/src/prices/tools.c b/src/prices/tools.cnew file mode 100644index 0000000..e67cc74--- /dev/null+++ b/src/prices/tools.c@@ -0,0 +1,140 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * tools.c - janas-prices' tools (see prices.h) and what they share. They+ * only read, and say so (readOnlyHint): currencies, crypto-assets, shares+ * (with a free key of the user's), inflation, central banks' rates,+ * electricity and fuel, each for as many countries as open data covers.+ */+#include <stdarg.h>+#include <stdio.h>+#include <string.h>++#include "common/mcp_server.h"+#include "common/template.h"+#include "prices.h"++#define READS \+ "\"annotations\": {\"readOnlyHint\": true, \"openWorldHint\": true}"+#define PLACE_ARG \+ "\"place\": {\"type\": \"string\", \"description\": \"a town or an " \+ "address with its town; leave it out for where the user is\"}"++void pr_tools_list(void *ctx, struct janas_buf *b)+{+ (void)ctx;+ janas_buf_puts(+ b,+ "\"tools\": [{\"name\": \"prices_currency\", \"title\": "+ "\"Currencies\", \"description\": \"An amount in other currencies "+ "at the ECB's reference rates, of today or of a day.\", "+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {\"from\": "+ "{\"type\": \"string\", \"description\": \"ISO code, EUR by "+ "default\"}, \"to\": {\"type\": \"string\", \"description\": \"ISO "+ "codes, comma-separated\"}, \"amount\": {\"type\": \"number\"}, "+ "\"date\": {\"type\": \"string\", \"description\": \"YYYY-MM-DD; "+ "leave it out for the latest\"}}, \"additionalProperties\": false}, " READS+ "}, "+ "{\"name\": \"prices_crypto\", \"title\": \"Crypto-assets\", "+ "\"description\": \"The price of a crypto-asset now, and its change "+ "in 24 hours.\", \"inputSchema\": {\"type\": \"object\", "+ "\"properties\": {\"coin\": {\"type\": \"string\", \"description\": "+ "\"name or symbol: bitcoin, ETH\"}, \"currency\": {\"type\": "+ "\"string\", \"description\": \"EUR by default\"}}, \"required\": "+ "[\"coin\"], \"additionalProperties\": false}, " READS "}, "+ "{\"name\": \"prices_stock\", \"title\": \"Shares\", "+ "\"description\": \"A share's last price and its day, from its "+ "symbol (AAPL, TSCO.LON) or its company's name.\", \"inputSchema\": "+ "{\"type\": \"object\", \"properties\": {\"share\": {\"type\": "+ "\"string\"}}, \"required\": [\"share\"], \"additionalProperties\": "+ "false}, " READS "}, "+ "{\"name\": \"prices_inflation\", \"title\": \"Inflation\", "+ "\"description\": \"A country's inflation: monthly in Europe, yearly "+ "elsewhere.\", \"inputSchema\": {\"type\": \"object\", "+ "\"properties\": {\"country\": {\"type\": \"string\", "+ "\"description\": \"ISO code (IT, US) or EA for the euro area; "+ "leave it out for the user's\"}}, \"additionalProperties\": false}, " READS+ "}, "+ "{\"name\": \"prices_rates\", \"title\": \"Central banks' rates\", "+ "\"description\": \"The rates of a central bank.\", "+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {\"bank\": "+ "{\"type\": \"string\", \"enum\": [\"ecb\", \"fed\", \"boe\", "+ "\"snb\"], \"description\": \"leave it out for the user's\"}}, "+ "\"additionalProperties\": false}, " READS "}, "+ "{\"name\": \"prices_electricity\", \"title\": \"Electricity\", "+ "\"description\": \"The wholesale price of electricity hour by hour, "+ "where it is open data.\", \"inputSchema\": {\"type\": \"object\", "+ "\"properties\": {" PLACE_ARG ", \"day\": {\"type\": \"string\", "+ "\"enum\": [\"today\", \"tomorrow\"]}}, \"additionalProperties\": "+ "false}, " READS "}, "+ "{\"name\": \"prices_fuel\", \"title\": \"Fuel\", \"description\": "+ "\"The cheapest fuel stations near a place, with their prices.\", "+ "\"inputSchema\": {\"type\": \"object\", \"properties\": "+ "{" PLACE_ARG ", \"fuel\": {\"type\": \"string\", \"enum\": "+ "[\"petrol\", \"diesel\", \"lpg\", \"cng\"]}, \"radius\": {\"type\": "+ "\"number\", \"description\": \"km, 5 by default, at most 20\"}}, "+ "\"required\": [\"fuel\"], \"additionalProperties\": false}, " READS+ "}]");+}++const char *pr_arg_str(const struct janas_json *args, const char *name)+{+ const char *s = janas_json_str(janas_json_get(args, name));+ return s && *s ? s : NULL;+}++double pr_arg_num(const struct janas_json *args, const char *name, double def)+{+ const struct janas_json *v = janas_json_get(args, name);+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, def) : def;+}++int pr_fail(struct janas_buf *b, const char *fmt, ...)+{+ char line[2048];+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(line, sizeof line, fmt, ap);+ va_end(ap);+ janas_mcps_text_result(b, line, strlen(line), 1);+ return 0;+}++int pr_answer(struct janas_buf *b, const char *name, struct janas_buf *d,+ const char *layout, const char *brief)+{+ char err[300];+ int oom = d->oom;+ int r = oom ? -1+ : janas_tpl_result(b, name, d->p, d->n, layout, brief, err,+ sizeof err);+ janas_buf_free(d);+ if (r != 0)+ return pr_fail(b, "The answer could not be written: %s.",+ oom ? "out of memory" : err);+ return 0;+}++int pr_tools_call(void *ctx, const struct janas_json *params,+ struct janas_buf *b)+{+ (void)ctx;+ const struct janas_json *name = janas_json_get(params, "name");+ const struct janas_json *args = janas_json_get(params, "arguments");+ if (args && args->type != JANAS_JSON_OBJECT)+ args = NULL;+ static const struct {+ const char *name;+ int (*fn)(const struct janas_json *, struct janas_buf *);+ } T[] = {{"prices_currency", pr_tool_currency},+ {"prices_crypto", pr_tool_crypto},+ {"prices_stock", pr_tool_stock},+ {"prices_inflation", pr_tool_inflation},+ {"prices_rates", pr_tool_rates},+ {"prices_electricity", pr_tool_power},+ {"prices_fuel", pr_tool_fuel}};+ for (size_t i = 0; i < sizeof T / sizeof *T; i++)+ if (janas_json_is(name, T[i].name))+ return T[i].fn(args, b);+ return -1;+}diff --git a/tests/llm_keep.c b/tests/llm_keep.cindex 18b68dc..2953667 100644--- a/tests/llm_keep.c+++ b/tests/llm_keep.c@@ -17,7 +17,8 @@* (janas_llm_chat_prepare), as janas-chat does while its user writes: the* reply to the first message is the same as without it, the message* finds the system message computed, a new chat finds it on the disk at- * once, and a new system message set after it drops it. The disk is a+ * once, and a new system message set after it drops it - with a system+ * message over 1024 tokens and with one under. The disk is a* directory of the test's own (XDG_CACHE_HOME), removed at the end.** Usage: llm_keep <model.jns> [mtp=<file>] [draft=<file>]@@ -240,11 +241,17 @@ static int prepare_all(janas_llm_chat *c, int *first, int *steps, int32_t *done,return rc;}-static int run_prepare(janas_llm *llm)+/* rules: how long the system message is - 90 rules are over 1024 tokens,+ 25 under (janas-chat's with its services' catalog is 767: the disk kept+ none so short until 2 Oct 2026); min: the tokens it must have at least */+static int run_prepare(janas_llm *llm, int rules, int32_t min){static char sys[32768];- size_t n = (size_t)snprintf(sys, sizeof(sys), "Read ahead.\n");- for (int i = 1; i <= 90; i++)+ /* a start of its own: a dense model would take the other's from the+ disk, the first rules being the same */+ size_t n =+ (size_t)snprintf(sys, sizeof(sys), "Read ahead, %d rules.\n", rules);+ for (int i = 1; i <= rules; i++)n += (size_t)snprintf(sys + n, sizeof(sys) - n,"Rule %d: answer briefly, in English, and ""never mention the number %d.\n",@@ -278,13 +285,14 @@ static int run_prepare(janas_llm *llm)send_reply(c, A1, &other) == 0;if (c)janas_llm_chat_destroy(c);- printf("prepare: %d steps, %d of %d tokens; prompt/cached %u/%u (without "- "it %u/%u); a new chat: %d steps (first %d), %d of %d, %u/%u; "- "another system message: %u/%u\n",- steps, done, total, ahead.prompt, ahead.cached, plain.prompt,- plain.cached, steps2, first2, done2, total2, again.prompt,- again.cached, other.prompt, other.cached);- if (done != total || total < 1024 || steps < 1) {+ printf(+ "prepare (%d rules): %d steps, %d of %d tokens; prompt/cached %u/%u (without "+ "it %u/%u); a new chat: %d steps (first %d), %d of %d, %u/%u; "+ "another system message: %u/%u\n",+ rules, steps, done, total, ahead.prompt, ahead.cached, plain.prompt,+ plain.cached, steps2, first2, done2, total2, again.prompt, again.cached,+ other.prompt, other.cached);+ if (done != total || total < min || steps < 1) {printf("FAIL: prepare: not read to the end\n");fail = 1;}@@ -375,10 +383,12 @@ int main(int argc, char **argv)tmp && *tmp ? tmp : "/tmp", (int)getpid());if (!fail) {setenv("XDG_CACHE_HOME", dir, 1);- fail = run_disk(llm) != 0 || run_prepare(llm) != 0;- nftw(dir, rm_one, 16, FTW_DEPTH | FTW_PHYS);+ fail = run_disk(llm) != 0 || run_prepare(llm, 90, 1024) != 0 ||+ run_prepare(llm, 25, 256) != 0;}- janas_llm_close(llm);+ janas_llm_close(llm); /* it writes its tuning into the cache too */+ if (getenv("XDG_CACHE_HOME") && !strcmp(getenv("XDG_CACHE_HOME"), dir))+ nftw(dir, rm_one, 16, FTW_DEPTH | FTW_PHYS);printf("%s\n", fail ? "FAIL": "OK: same replies, first turns kept, system ""message read ahead");diff --git a/tests/test_prices_parse.c b/tests/test_prices_parse.cnew file mode 100644index 0000000..eed248f--- /dev/null+++ b/tests/test_prices_parse.c@@ -0,0 +1,563 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * test_prices_parse.c - janas-prices' reading of its sources' answers,+ * without the network, and the layouts filled with what was read: the+ * ECB's rates (Frankfurter's and its own file), CoinGecko's search and+ * price, Coinbase's, Alpha Vantage's quote, search and limit, Eurostat's+ * and the World Bank's inflation, the rates of the ECB, the Bank of+ * England, the SNB and the New York Fed, energy-charts' prices (open and+ * not), and the fuel of Italy, France, Spain and Austria, as they came+ * on 2 October 2026 (cut to a few items).+ * The sources belong to the program, so they are compiled in here.+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/template.h"+#include "prices/data.c"+#include "prices/layouts.c"+#include "prices/read.c"+#include "prices/read_fuel.c"++static int failures;++#define CHECK(c, ...) \+ do { \+ if (!(c)) { \+ printf(__VA_ARGS__); \+ printf("\n"); \+ failures++; \+ } \+ } while (0)++static const char S_FRANKFURTER[] =+ "{\"amount\":1.0,\"base\":\"EUR\",\"date\":\"2026-10-02\",\"rates\":{\""+ "CHF\":0.9279,\"GBP\":0.85033,\"USD\":1.1225}}";+static const char S_ECB_XML[] =+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<gesmes:Envelope xmlns:ges"+ "mes=\"http://www.gesmes.org/xml/2002-08-01\" xmlns=\"http://www.ecb.in"+ "t/vocabulary/2002-08-01/eurofxref\">\n\t<gesmes:subject>Reference rate"+ "s</gesmes:subject>\n\t<gesmes:Sender>\n\t\t<gesmes:name>European Centr"+ "al Bank</gesmes:name>\n\t</gesmes:Sender>\n\t<Cube>\n\t\t<Cube time='2"+ "026-10-02'>\n\t\t\t<Cube currency='USD' rate='1.1225'/>\n\t\t\t</Cube>"+ "</Cube></gesmes:Envelope>";+static const char S_CG_SEARCH[] =+ "{\"coins\": [{\"id\": \"solana\", \"name\": \"Solana\", \"api_symbol\""+ ": \"solana\", \"symbol\": \"SOL\", \"market_cap_rank\": 7}, {\"id\": "+ "\"solana-name-service\", \"name\": \"Solana Name Service\", \"api_symb"+ "ol\": \"solana-name-service\", \"symbol\": \"SNS\", \"market_cap_rank"+ "\": 2510}, {\"id\": \"green-satoshi-token\", \"name\": \"STEPN Green S"+ "atoshi Token on Solana\", \"api_symbol\": \"green-satoshi-token\", \"s"+ "ymbol\": \"GST-SOL\", \"market_cap_rank\": 2833}]}";+static const char S_CG_PRICE[] =+ "{\"solana\":{\"eur\":107.62,\"eur_market_cap\":63316909208.14257,\"eur"+ "_24h_change\":3.607680380747676,\"last_updated_at\":1790952650}}";+static const char S_COINBASE[] =+ "{\"data\":{\"amount\":\"76832.01\",\"base\":\"BTC\",\"currency\":\"EUR"+ "\"}}";+static const char S_AV_QUOTE[] =+ "{\"Global Quote\": {\"01. symbol\": \"IBM\", \"02. open\": \"230.7600"+ "\", \"03. high\": \"234.2700\", \"04. low\": \"224.5000\", \"05. price"+ "\": \"225.6200\", \"06. volume\": \"8884106\", \"07. latest trading da"+ "y\": \"2026-10-01\", \"08. previous close\": \"219.9300\", \"09. chang"+ "e\": \"5.6900\", \"10. change percent\": \"2.5872%\"}}";+static const char S_AV_SEARCH[] =+ "{\"bestMatches\": [{\"1. symbol\": \"TSCO.LON\", \"2. name\": \"Tesco "+ "PLC\", \"3. type\": \"Equity\", \"4. region\": \"United Kingdom\", \"5"+ ". marketOpen\": \"08:00\", \"6. marketClose\": \"16:30\", \"7. timezon"+ "e\": \"UTC+01\", \"8. currency\": \"GBX\", \"9. matchScore\": \"0.7273"+ "\"}, {\"1. symbol\": \"TSCDF\", \"2. name\": \"Tesco plc\", \"3. type"+ "\": \"Equity\", \"4. region\": \"United States\", \"5. marketOpen\": "+ "\"09:30\", \"6. marketClose\": \"16:00\", \"7. timezone\": \"UTC-04\","+ " \"8. currency\": \"USD\", \"9. matchScore\": \"0.7143\"}]}";+static const char S_AV_LIMIT[] =+ "{\"Information\": \"The **demo** API key is for demo purposes only. Pl"+ "ease claim your free API key at (https://www.alphavantage.co/support/#"+ "api-key) to explore our full API offerings. It takes fewer than 20 sec"+ "onds.\"}";+static const char S_EUROSTAT[] =+ "{\"version\": \"2.0\", \"class\": \"dataset\", \"label\": \"Harmonised"+ " index of consumer prices (HICP) - ECOICOP ver.2 - indices and rates o"+ "f change, monthly data\", \"source\": \"ESTAT\", \"updated\": \"2026-1"+ "0-02T11:00:00+0200\", \"value\": {\"0\": 2.2, \"1\": 2.1, \"2\": 2.1, "+ "\"3\": 2.0, \"4\": 1.7, \"5\": 1.9, \"6\": 2.6, \"7\": 3.0, \"8\": 3.2"+ ", \"9\": 2.8, \"10\": 2.9, \"11\": 3.2, \"12\": 3.8}, \"status\": {\"1"+ "2\": \"e\"}, \"id\": [\"freq\", \"unit\", \"coicop18\", \"geo\", \"tim"+ "e\"], \"size\": [1, 1, 1, 1, 13], \"dimension\": {\"freq\": {\"label\""+ ": \"Time frequency\", \"category\": {\"index\": {\"M\": 0}, \"label\":"+ " {\"M\": \"Monthly\"}}}, \"unit\": {\"label\": \"Unit of measure\", \""+ "category\": {\"index\": {\"RCH_A\": 0}, \"label\": {\"RCH_A\": \"Annua"+ "l rate of change\"}}}, \"coicop18\": {\"label\": \"Classification of i"+ "ndividual consumption by purpose (COICOP) - 2018\", \"category\": {\"i"+ "ndex\": {\"TOTAL\": 0}, \"label\": {\"TOTAL\": \"Total\"}}}, \"geo\": "+ "{\"label\": \"Geopolitical entity (reporting)\", \"category\": {\"inde"+ "x\": {\"EA\": 0}, \"label\": {\"EA\": \"Euro area (EA11-1999, EA12-200"+ "1, EA13-2007, EA15-2008, EA16-2009, EA17-2011, EA18-2014, EA19-2015, E"+ "A20-2023, EA21-2026)\"}}}, \"time\": {\"label\": \"Time\", \"category"+ "\": {\"index\": {\"2025-09\": 0, \"2025-10\": 1, \"2025-11\": 2, \"202"+ "5-12\": 3, \"2026-01\": 4, \"2026-02\": 5, \"2026-03\": 6, \"2026-04\""+ ": 7, \"2026-05\": 8, \"2026-06\": 9, \"2026-07\": 10, \"2026-08\": 11,"+ " \"2026-09\": 12}, \"label\": {\"2025-09\": \"2025-09\", \"2025-10\": "+ "\"2025-10\", \"2025-11\": \"2025-11\", \"2025-12\": \"2025-12\", \"202"+ "6-01\": \"2026-01\", \"2026-02\": \"2026-02\", \"2026-03\": \"2026-03"+ "\", \"2026-04\": \"2026-04\", \"2026-05\": \"2026-05\", \"2026-06\": "+ "\"2026-06\", \"2026-07\": \"2026-07\", \"2026-08\": \"2026-08\", \"202"+ "6-09\": \"2026-09\"}}}}}";+static const char S_WORLDBANK[] =+ "[{\"page\":1,\"pages\":1,\"per_page\":50,\"total\":3,\"sourceid\":\"2"+ "\",\"lastupdated\":\"2026-07-13\"},[{\"indicator\":{\"id\":\"FP.CPI.TO"+ "TL.ZG\",\"value\":\"Inflation, consumer prices (annual %)\"},\"country"+ "\":{\"id\":\"GB\",\"value\":\"United Kingdom\"},\"countryiso3code\":\""+ "GBR\",\"date\":\"2025\",\"value\":3.88306881626,\"unit\":\"\",\"obs_st"+ "atus\":\"\",\"decimal\":1},{\"indicator\":{\"id\":\"FP.CPI.TOTL.ZG\","+ "\"value\":\"Inflation, consumer prices (annual %)\"},\"country\":{\"id"+ "\":\"JP\",\"value\":\"Japan\"},\"countryiso3code\":\"JPN\",\"date\":\""+ "2025\",\"value\":3.17253034260248,\"unit\":\"\",\"obs_status\":\"\",\""+ "decimal\":1},{\"indicator\":{\"id\":\"FP.CPI.TOTL.ZG\",\"value\":\"Inf"+ "lation, consumer prices (annual %)\"},\"country\":{\"id\":\"US\",\"val"+ "ue\":\"United States\"},\"countryiso3code\":\"USA\",\"date\":\"2025\","+ "\"value\":null,\"unit\":\"\",\"obs_status\":\"\",\"decimal\":1}]]";+static const char S_ECB_CSV[] =+ "KEY,FREQ,REF_AREA,CURRENCY,PROVIDER_FM,INSTRUMENT_FM,PROVIDER_FM_ID,DA"+ "TA_TYPE_FM,TIME_PERIOD,OBS_VALUE,OBS_STATUS,OBS_CONF,OBS_PRE_BREAK,OBS"+ "_COM,TIME_FORMAT,BREAKS,COLLECTION,COMPILING_ORG,DISS_ORG,DOM_SER_IDS,"+ "FM_CONTRACT_TIME,FM_COUPON_RATE,FM_IDENTIFIER,FM_LOT_SIZE,FM_MATURITY,"+ "FM_OUTS_AMOUNT,FM_PUT_CALL,FM_STRIKE_PRICE,PUBL_MU,PUBL_PUBLIC,UNIT_IN"+ "DEX_BASE,COMPILATION,COVERAGE,DECIMALS,SOURCE_AGENCY,SOURCE_PUB,TITLE,"+ "TITLE_COMPL,UNIT,UNIT_MULT\nFM.D.U2.EUR.4F.KR.DFR.LEV,D,U2,EUR,4F,KR,D"+ "FR,LEV,2026-10-02,2.5,A,F,,,P1D,,E,4F0,,,,,,,,,,,,,,,,7,,,Deposit faci"+ "lity - date of changes (raw data) - Level,\"Euro area (changing compos"+ "ition) - Key interest rate - Deposit facility - date of changes (raw d"+ "ata) - Level - Euro, provided by ECB\",PCPA,0\n";+static const char S_BOE[] =+ "DATE,IUDBEDR\n01 Sep 2026,3.75\n02 Sep 2026,3.75\n03 Sep 2026,3.75\n04"+ " Sep 2026,3.75\n07 Sep 2026,3.75\n08 Sep 2026,3.75\n09 Sep 2026,3.75\n"+ "10 Sep 2026,3.75\n11 Sep 2026,3.75\n14 Sep 2026,3.75\n15 Sep 2026,3.75"+ "\n16 Sep 2026,3.75\n17 Sep 2026,3.75\n18 Sep 2026,3.75\n21 Sep 2026,3."+ "75\n22 Sep 2026,3.75\n23 Sep 2026,3.75\n24 Sep 2026,3.75\n25 Sep 2026,"+ "3.75\n28 Sep 2026,3.75\n29 Sep 2026,3.75\n30 Sep 2026,3.75\n01 Oct 202"+ "6,3.75\n";+static const char S_SNB[] =+ "{\"timeseries\": [{\"header\": [{\"dim\": \"Overview\", \"dimItem\": "+ "\"SNB policy rate\"}], \"metadata\": {\"key\": \"[email protected]{LZ}"+ "\", \"frequency\": \"P1D_L\", \"scale\": \"\", \"unit\": \"In percent"+ "\"}, \"values\": [{\"date\": \"2026-09-23\", \"value\": 0.0}, {\"date"+ "\": \"2026-09-24\", \"value\": 0.0}, {\"date\": \"2026-09-25\", \"valu"+ "e\": 0.0}]}]}";+static const char S_NYFED[] =+ "{ \"refRates\": [ { \"effectiveDate\": \"2026-10-01\", \"type\": \"EFF"+ "R\" ,\"percentRate\": 3.88 ,\"percentPercentile1\": 3.85 ,\"percentPer"+ "centile25\": 3.87 ,\"percentPercentile75\": 3.88 ,\"percentPercentile9"+ "9\": 3.89 ,\"targetRateFrom\": 3.75 ,\"targetRateTo\": 4.00 ,\"volumeI"+ "nBillions\": 120 ,\"revisionIndicator\": \"\" } ] }";+static const char S_POWER[] =+ "{\"license_info\": \"CC BY 4.0 (creativecommons.org/licenses/by/4.0) f"+ "rom Bundesnetzagentur | SMARD.de\", \"unix_seconds\": [1790892000, 179"+ "0892900, 1790893800, 1790894700, 1790895600, 1790896500, 1790897400, 1"+ "790898300], \"price\": [185.11, 208.09, 208.09, 196.89, 203.55, 185.0,"+ " 181.75, 183.9], \"unit\": \"EUR / MWh\", \"deprecated\": false}";+static const char S_POWER_CLOSED[] =+ "{\"license_info\": \"The data provided herein is for private and inter"+ "nal use only.\", \"unix_seconds\": [1790892000], \"price\": [100.0], "+ "\"unit\": \"EUR / MWh\"}";+static const char S_IT_REG[] =+ "Estrazione del 2026-10-01\nidImpianto|Gestore|Bandiera|Tipo Impianto|N"+ "ome Impianto|Indirizzo|Comune|Provincia|Latitudine|Longitudine\n18062|"+ "SCHIFANO ALESSANDRO & TAGLIAVIA DAVIDE - SOCIETA' IN NOME COLLE TTIVO|"+ "Api-Ip|Stradale|STAZIONE IP SCHIFANO & TAGLIAVIA|LUNGOMARE DANTE ALIGH"+ "IERI 91100|TRAPANI|TP|38.021958273519594|12.519967354355135\n29846|MA"+ "GGIO GIACOMA|Pompe Bianche|Stradale|pompa bianca|VIA MARSALA 72 91100|"+ "TRAPANI|TP|38.018249806100236|12.532137080426082\n38672|PROTEC S.R.L.|"+ "Nobile Oil|Stradale|PROTEC TP|PIAZZA STAZIONE SNC 91100|TRAPANI|TP|38."+ "01674157298534|12.518189017888517\n45503|EOS SERVICES S.R.L. A SOCIO U"+ "NICO|Q8|Stradale|TP063|VIA MARSALA ANGOLO VIA VESPRI SNC 91100|TRAPANI"+ "|TP|38.01920496451889|12.530868220888578\n41498|GP SERVICE DI PECORELL"+ "A GASPARE & C. SAS|Pompe Bianche|Stradale|GP PETROLI|PIAZZALE LAZZARET"+ "TO SNC 91100|TRAPANI|TP|38.015526026835126|12.49569296836853\n";+static const char S_IT_PRICES[] =+ "Estrazione del 2026-10-01\nidImpianto|descCarburante|prezzo|isSelf|dtC"+ "omu\n18062|Gasolio|2.460|0|30/09/2026 17:10:38\n18062|Gasolio|2.230|1|"+ "30/09/2026 17:10:38\n29846|Gasolio|2.369|1|29/09/2026 18:42:12\n38672|"+ "Gasolio|2.099|0|29/09/2026 08:29:00\n45503|Gasolio|2.699|0|29/09/2026 "+ "07:48:05\n45503|Gasolio|2.399|1|29/09/2026 07:48:05\n41498|Gasolio|2.4"+ "00|0|30/09/2026 21:31:09\n18062|Benzina|2.260|0|30/09/2026 17:10:37\n";+static const char S_FR[] =+ "{\"total_count\": 7, \"results\": [{\"id\": 75013025, \"latitude\": \""+ "4883200\", \"longitude\": \"235900\", \"cp\": \"75013\", \"pop\": \"R"+ "\", \"adresse\": \"181, BOULEVARD VINCENT AURIOL\", \"ville\": \"Paris"+ "\", \"rupture\": \"[{\\\"@nom\\\": \\\"SP95\\\", \\\"@id\\\": \\\"2\\"+ "\", \\\"@debut\\\": \\\"2023-01-30 13:35:10\\\", \\\"@fin\\\": \\\"\\"+ "\", \\\"@type\\\": \\\"definitive\\\"}, {\\\"@nom\\\": \\\"E85\\\", \\"+ "\"@id\\\": \\\"3\\\", \\\"@debut\\\": \\\"2023-01-30 13:35:10\\\", \\"+ "\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"definitive\\\"}]\", \"geom\":"+ " {\"lon\": 2.359, \"lat\": 48.832}, \"gazole_maj\": \"2026-10-02T09:21"+ ":33+00:00\", \"gazole_prix\": 2.25, \"sp95_maj\": null, \"sp95_prix\":"+ " null, \"e85_maj\": null, \"e85_prix\": null, \"gplc_maj\": \"2026-10-"+ "02T09:21:33+00:00\", \"gplc_prix\": 0.984, \"e10_maj\": \"2026-10-02T0"+ "9:21:33+00:00\", \"e10_prix\": 1.99, \"sp98_maj\": \"2026-10-02T09:21:"+ "33+00:00\", \"sp98_prix\": 1.99, \"e10_rupture_debut\": null, \"e10_ru"+ "pture_type\": null, \"sp98_rupture_debut\": null, \"sp98_rupture_type"+ "\": null, \"sp95_rupture_debut\": \"2023-01-30T13:35:10+00:00\", \"sp9"+ "5_rupture_type\": \"definitive\", \"e85_rupture_debut\": \"2023-01-30T"+ "13:35:10+00:00\", \"e85_rupture_type\": \"definitive\", \"gplc_rupture"+ "_debut\": null, \"gplc_rupture_type\": null, \"gazole_rupture_debut\":"+ " null, \"gazole_rupture_type\": null, \"carburants_rupture_temporaire"+ "\": null, \"carburants_rupture_definitive\": \"SP95;E85\", \"horaires_"+ "automate_24_24\": \"Non\", \"departement\": \"Paris\", \"code_departem"+ "ent\": \"75\", \"region\": \"Île-de-France\", \"code_region\": \"11\""+ "}, {\"id\": 75013024, \"latitude\": \"4883500\", \"longitude\": \"2358"+ "00\", \"cp\": \"75013\", \"pop\": \"R\", \"adresse\": \"114 BD DE L HO"+ "PITAL\", \"ville\": \"Paris\", \"rupture\": \"[{\\\"@nom\\\": \\\"GPLc"+ "\\\", \\\"@id\\\": \\\"4\\\", \\\"@debut\\\": \\\"2020-03-04 19:45:31"+ "\\\", \\\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"definitive\\\"}, {\\"+ "\"@nom\\\": \\\"SP95\\\", \\\"@id\\\": \\\"2\\\", \\\"@debut\\\": \\\""+ "2025-10-28 06:11:04\\\", \\\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"de"+ "finitive\\\"}, {\\\"@nom\\\": \\\"SP98\\\", \\\"@id\\\": \\\"6\\\", \\"+ "\"@debut\\\": \\\"2026-10-02 14:03:40\\\", \\\"@fin\\\": \\\"\\\", \\"+ "\"@type\\\": \\\"temporaire\\\"}]\", \"geom\": {\"lon\": 2.358, \"lat"+ "\": 48.835}, \"gazole_maj\": \"2026-10-02T00:01:00+00:00\", \"gazole_p"+ "rix\": 2.25, \"sp95_maj\": null, \"sp95_prix\": null, \"e85_maj\": \"2"+ "026-10-02T00:01:00+00:00\", \"e85_prix\": 0.919, \"gplc_maj\": null, "+ "\"gplc_prix\": null, \"e10_maj\": \"2026-10-02T00:01:00+00:00\", \"e10"+ "_prix\": 1.99, \"sp98_maj\": null, \"sp98_prix\": null, \"e10_rupture_"+ "debut\": null, \"e10_rupture_type\": null, \"sp98_rupture_debut\": \"2"+ "026-10-02T14:03:40+00:00\", \"sp98_rupture_type\": \"temporaire\", \"s"+ "p95_rupture_debut\": \"2025-10-28T06:11:04+00:00\", \"sp95_rupture_typ"+ "e\": \"definitive\", \"e85_rupture_debut\": null, \"e85_rupture_type\""+ ": null, \"gplc_rupture_debut\": \"2020-03-04T19:45:31+00:00\", \"gplc_"+ "rupture_type\": \"definitive\", \"gazole_rupture_debut\": null, \"gazo"+ "le_rupture_type\": null, \"carburants_rupture_temporaire\": \"SP98\", "+ "\"carburants_rupture_definitive\": \"SP95;GPLc\", \"horaires_automate_"+ "24_24\": \"Non\", \"departement\": \"Paris\", \"code_departement\": \""+ "75\", \"region\": \"Île-de-France\", \"code_region\": \"11\"}, {\"id"+ "\": 75012010, \"latitude\": \"4884200\", \"longitude\": \"237300\", \""+ "cp\": \"75012\", \"pop\": \"R\", \"adresse\": \"36 Quai de la Rapée\""+ ", \"ville\": \"Paris\", \"rupture\": \"[{\\\"@nom\\\": \\\"SP95\\\", "+ "\\\"@id\\\": \\\"2\\\", \\\"@debut\\\": \\\"2009-07-02 03:27:00\\\", "+ "\\\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"\\\"}, {\\\"@nom\\\": \\\"E"+ "85\\\", \\\"@id\\\": \\\"3\\\", \\\"@debut\\\": \\\"2023-06-28 10:21:1"+ "8\\\", \\\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"temporaire\\\"}, {\\"+ "\"@nom\\\": \\\"GPLc\\\", \\\"@id\\\": \\\"4\\\", \\\"@debut\\\": \\\""+ "2023-06-28 10:21:18\\\", \\\"@fin\\\": \\\"\\\", \\\"@type\\\": \\\"te"+ "mporaire\\\"}]\", \"geom\": {\"lon\": 2.373, \"lat\": 48.842}, \"gazol"+ "e_maj\": \"2026-10-02T07:31:00+00:00\", \"gazole_prix\": 2.391, \"sp95"+ "_maj\": null, \"sp95_prix\": null, \"e85_maj\": null, \"e85_prix\": nu"+ "ll, \"gplc_maj\": null, \"gplc_prix\": null, \"e10_maj\": \"2026-10-02"+ "T07:31:00+00:00\", \"e10_prix\": 2.152, \"sp98_maj\": \"2026-10-02T07:"+ "31:00+00:00\", \"sp98_prix\": 2.286, \"e10_rupture_debut\": null, \"e1"+ "0_rupture_type\": null, \"sp98_rupture_debut\": null, \"sp98_rupture_t"+ "ype\": null, \"sp95_rupture_debut\": null, \"sp95_rupture_type\": null"+ ", \"e85_rupture_debut\": \"2023-06-28T10:21:18+00:00\", \"e85_rupture_"+ "type\": \"temporaire\", \"gplc_rupture_debut\": \"2023-06-28T10:21:18+"+ "00:00\", \"gplc_rupture_type\": \"temporaire\", \"gazole_rupture_debut"+ "\": null, \"gazole_rupture_type\": null, \"carburants_rupture_temporai"+ "re\": \"E85;GPLc\", \"carburants_rupture_definitive\": null, \"horaire"+ "s_automate_24_24\": \"Non\", \"departement\": \"Paris\", \"code_depart"+ "ement\": \"75\", \"region\": \"Île-de-France\", \"code_region\": \"11"+ "\"}]}";+static const char S_ES[] =+ "{\"Fecha\": \"02/10/2026 16:48:00\", \"ListaEESSPrecio\": [{\"Direcci"+ "ón\": \"RONDA SEGOVIA, 37\", \"Latitud\": \"40,410250\", \"Localidad"+ "\": \"MADRID\", \"Longitud (WGS84)\": \"-3,717528\", \"Precio Gasoleo "+ "A\": \"1,899\", \"Precio Gasolina 95 E5\": \"1,748\", \"Rótulo\": \"B"+ "ALLENOIL\"}, {\"Dirección\": \"CL PASEO ACACIAS, 8\", \"Latitud\": \""+ "40,404417\", \"Localidad\": \"MADRID\", \"Longitud (WGS84)\": \"-3,705"+ "389\", \"Precio Gasoleo A\": \"2,005\", \"Precio Gasolina 95 E5\": \"1"+ ",845\", \"Rótulo\": \"REPSOL\"}, {\"Dirección\": \"CALLE ALBERTO AGU"+ "ILERA, 9\", \"Latitud\": \"40,429694\", \"Localidad\": \"MADRID\", \"L"+ "ongitud (WGS84)\": \"-3,708389\", \"Precio Gasoleo A\": \"1,979\", \"P"+ "recio Gasolina 95 E5\": \"1,899\", \"Rótulo\": \"REPSOL\"}, {\"Direcc"+ "ión\": \"GLORIETA EMBAJADORES, 0\", \"Latitud\": \"40,405278\", \"Loc"+ "alidad\": \"MADRID\", \"Longitud (WGS84)\": \"-3,703139\", \"Precio Ga"+ "soleo A\": \"1,969\", \"Precio Gasolina 95 E5\": \"1,849\", \"Rótulo"+ "\": \"BLANCA\"}], \"ResultadoConsulta\": \"OK\"}";+static const char S_AT[] =+ "[{\"id\": 1494440, \"name\": \"TMC Werkstatt & Tankstelle\", \"locatio"+ "n\": {\"address\": \"Rechte Wienzeile 43\", \"postalCode\": \"1050\", "+ "\"city\": \"Wien\", \"latitude\": 48.1963966, \"longitude\": 16.358812"+ "}, \"offerInformation\": {\"service\": true, \"selfService\": false, "+ "\"unattended\": false}, \"position\": 1, \"open\": true, \"distance\":"+ " 0.9219608420880954, \"prices\": [{\"fuelType\": \"DIE\", \"amount\": "+ "2.109, \"label\": \"Diesel\"}]}, {\"id\": 34026, \"name\": \"leodiskon"+ "ttankstelle GmbH\", \"location\": {\"address\": \"Seidengasse 12\", \""+ "postalCode\": \"1070\", \"city\": \"Wien\", \"latitude\": 48.2004272, "+ "\"longitude\": 16.3445982}, \"offerInformation\": {\"service\": true, "+ "\"selfService\": false, \"unattended\": false}, \"position\": 2, \"ope"+ "n\": true, \"distance\": 1.8853604072204895, \"prices\": [{\"fuelType"+ "\": \"DIE\", \"amount\": 2.119, \"label\": \"Diesel\"}]}, {\"id\": 147"+ "6471, \"name\": \"Turmöl\", \"location\": {\"address\": \"Margaretens"+ "traße 28\", \"postalCode\": \"1040\", \"city\": \"Wien\", \"latitude"+ "\": 48.19633, \"longitude\": 16.36464}, \"offerInformation\": {\"servi"+ "ce\": false, \"selfService\": true, \"unattended\": false}, \"position"+ "\": 3, \"open\": true, \"distance\": 0.5701115453999446, \"prices\": ["+ "{\"fuelType\": \"DIE\", \"amount\": 2.124, \"label\": \"Diesel\"}]}, {"+ "\"id\": 6441, \"name\": \"Torrefina Gmbh.\", \"location\": {\"address"+ "\": \"Schottenfeldgasse 94\", \"postalCode\": \"1070\", \"city\": \"Wi"+ "en\", \"latitude\": 48.2071479, \"longitude\": 16.343487}, \"offerInfo"+ "rmation\": {\"service\": true, \"selfService\": false, \"unattended\":"+ " false}, \"position\": 4, \"open\": true, \"distance\": 2.121867918313"+ "451, \"prices\": [{\"fuelType\": \"DIE\", \"amount\": 2.157, \"label\""+ ": \"Diesel\"}]}]";++/* The layout filled with the data: the text, or "" when it failed. */+static char text[16384];++static const char *fill(const char *layout, const struct janas_buf *d)+{+ text[0] = 0;+ struct janas_json_doc *doc =+ janas_json_parse(d->p ? d->p : "", d->n, NULL, 0);+ CHECK(doc != NULL, "the data is not JSON:\n%.*s", (int)d->n, d->p);+ if (!doc)+ return text;+ struct janas_buf out = {0};+ char err[200];+ if (janas_tpl_render(layout, strlen(layout), janas_json_root(doc), &out,+ err, sizeof err) == 0)+ snprintf(text, sizeof text, "%.*s", (int)out.n, out.p);+ else+ CHECK(0, "a layout not filled: %s", err);+ janas_buf_free(&out);+ janas_json_free(doc);+ return text;+}++static void money(void)+{+ struct pr_fx fx;+ char err[300] = "";+ CHECK(pr_read_frankfurter(S_FRANKFURTER, strlen(S_FRANKFURTER), &fx, err,+ sizeof err) == 0 &&+ !strcmp(fx.base, "EUR") && !strcmp(fx.date, "2026-10-02") &&+ fx.n == 3,+ "Frankfurter: %s", err);+ struct janas_buf d = {0};+ pr_fx_data(&d, 100, "EUR", &fx, "ecb");+ const char *t = fill(PR_FX_LAYOUT, &d);+ CHECK(strstr(t, "100.00 EUR, at the exchange rates of 2 October 2026:\n") &&+ strstr(t, " 112.25 USD (1 EUR = 1.1225 USD)\n") &&+ strstr(t, "For information only"),+ "the rates' layout:\n%s", t);+ janas_buf_free(&d);+ CHECK(pr_read_ecb_xml(S_ECB_XML, strlen(S_ECB_XML), &fx, err, sizeof err) ==+ 0 &&+ fx.n == 1 && !strcmp(fx.r[0].code, "USD") &&+ fabs(fx.r[0].rate - 1.1225) < 1e-9 &&+ !strcmp(fx.date, "2026-10-02"),+ "the ECB's file: %s %d", err, fx.n);++ struct pr_coin c;+ CHECK(pr_read_coin_search(S_CG_SEARCH, strlen(S_CG_SEARCH), "SOL", &c, err,+ sizeof err) == 0 &&+ !strcmp(c.id, "solana"),+ "CoinGecko's search: %s %s", err, c.id);+ snprintf(c.cur, sizeof c.cur, "EUR");+ CHECK(pr_read_coin_price(S_CG_PRICE, strlen(S_CG_PRICE), &c, err,+ sizeof err) == 0 &&+ fabs(c.price - 107.62) < 1e-9 && c.change_24h > 3.6 &&+ c.at == 1790952650,+ "CoinGecko's price: %s", err);+ snprintf(c.symbol, sizeof c.symbol, "SOL");+ pr_coin_data(&d, &c, "coingecko");+ t = fill(PR_COIN_LAYOUT, &d);+ CHECK(+ strstr(t, "Solana (SOL): 107.62 EUR, +3.61% in 24 hours; market "+ "value 63.3 billion EUR") &&+ strstr(+ t,+ "Data provided by CoinGecko (https://www.coingecko.com/en/api)."),+ "the coin's layout:\n%s", t);+ janas_buf_free(&d);+ CHECK(pr_read_coinbase(S_COINBASE, strlen(S_COINBASE), &c, err,+ sizeof err) == 0 &&+ fabs(c.price - 76832.01) < 1e-6,+ "Coinbase: %s", err);++ struct pr_quote q;+ memset(&q, 0, sizeof q);+ CHECK(pr_read_av_quote(S_AV_QUOTE, strlen(S_AV_QUOTE), &q, err,+ sizeof err) == 0 &&+ !strcmp(q.symbol, "IBM") && fabs(q.price - 225.62) < 1e-9 &&+ fabs(q.change_pct - 2.5872) < 1e-9 && q.volume == 8884106 &&+ !strcmp(q.day, "2026-10-01"),+ "Alpha Vantage's quote: %s", err);+ snprintf(q.name, sizeof q.name, "IBM");+ pr_quote_data(&d, &q);+ t = fill(PR_QUOTE_LAYOUT, &d);+ CHECK(strstr(t, "IBM (IBM): 225.62 , +5.69 (+2.59%); the trading day of 1 "+ "October 2026\nopen 230.76, high 234.27, low 224.50, "+ "previous close 219.93, shares traded 8884106\n"),+ "the quote's layout:\n%s", t);+ janas_buf_free(&d);+ struct pr_quote s;+ CHECK(pr_read_av_search(S_AV_SEARCH, strlen(S_AV_SEARCH), &s, err,+ sizeof err) == 0 &&+ !strcmp(s.symbol, "TSCO.LON") && !strcmp(s.currency, "GBX"),+ "Alpha Vantage's search: %s", err);+ CHECK(pr_read_av_quote(S_AV_LIMIT, strlen(S_AV_LIMIT), &q, err,+ sizeof err) != 0 &&+ strstr(err, "Alpha Vantage: The **demo** API key"),+ "Alpha Vantage's refusal said: %s", err);+}++static void macro(void)+{+ struct pr_series s;+ char err[300] = "", country[64] = "";+ CHECK(pr_read_eurostat(S_EUROSTAT, strlen(S_EUROSTAT), &s, err,+ sizeof err) == 0 &&+ s.n == 13 && !strcmp(s.p[0].when, "2025-09") &&+ fabs(s.p[12].v - 3.8) < 1e-9,+ "Eurostat: %s %d", err, s.n);+ snprintf(s.unit, sizeof s.unit, "%%");+ struct janas_buf d = {0};+ pr_series_data(&d, "inflation", "the euro area", &s, 13, "eurostat",+ "flash", "");+ const char *t = fill(PR_SERIES_LAYOUT, &d);+ CHECK(strstr(t, "Inflation, the yearly change of consumer prices, the "+ "euro area:\n 2025-09: 2.2%\n") &&+ strstr(t, " 2026-09: 3.8%\n") &&+ strstr(t, "minimum 1.7% (2026-01), maximum 3.8% (2026-09)"),+ "the inflation's layout:\n%s", t);+ t = fill(PR_SERIES_BRIEF, &d);+ CHECK(strstr(t, "last 3.8% (2026-09)"), "the inflation's brief:\n%s", t);+ janas_buf_free(&d);+ CHECK(pr_read_worldbank(S_WORLDBANK, strlen(S_WORLDBANK), &s, country,+ sizeof country, err, sizeof err) == 0 &&+ s.n == 1 && !strcmp(country, "United Kingdom"),+ "the World Bank: %s %d %s", err, s.n, country);+ CHECK(pr_read_ecb_csv(S_ECB_CSV, strlen(S_ECB_CSV), &s, err, sizeof err) ==+ 0 &&+ s.n == 1 && !strcmp(s.p[0].when, "2026-10-02") &&+ fabs(s.p[0].v - 2.5) < 1e-9,+ "the ECB's CSV: %s", err);+ CHECK(pr_read_boe_csv(S_BOE, strlen(S_BOE), &s, err, sizeof err) == 0 &&+ !strcmp(s.p[0].when, "2026-09-01") &&+ fabs(s.p[s.n - 1].v - 3.75) < 1e-9,+ "the Bank of England: %s %s", err, s.n ? s.p[0].when : "");+ CHECK(pr_read_snb(S_SNB, strlen(S_SNB), &s, err, sizeof err) == 0 &&+ s.n == 3 && s.p[2].v == 0,+ "the SNB: %s", err);+ double lo, hi;+ CHECK(pr_read_nyfed(S_NYFED, strlen(S_NYFED), &s, &lo, &hi, err,+ sizeof err) == 0 &&+ fabs(s.p[0].v - 3.88) < 1e-9 && lo == 3.75 && hi == 4.0,+ "the New York Fed: %s", err);+ struct pr_rate r[2] = {{.name = "effr", .when = "2026-10-01", .v = 3.88}};+ pr_rates_data(&d, "fed", r, 1, lo, hi, "nyfed");+ t = fill(PR_RATES_LAYOUT, &d);+ CHECK(strstr(t, "Federal Reserve:\n effective federal funds rate: 3.88% "+ "(1 October 2026)\n the target range of the federal "+ "funds: 3.75-4.00%\n"),+ "the rates' layout:\n%s", t);+ janas_buf_free(&d);+ char licence[300];+ CHECK(pr_read_power(S_POWER, strlen(S_POWER), "Europe/Rome", &s, licence,+ sizeof licence, err, sizeof err) == 1 &&+ s.n == 8 && !strcmp(s.p[0].when, "2026-10-02 00:00") &&+ strstr(licence, "CC BY 4.0"),+ "energy-charts, open: %s %d %s", err, s.n, s.n ? s.p[0].when : "");+ CHECK(pr_read_power(S_POWER_CLOSED, strlen(S_POWER_CLOSED), "", &s, licence,+ sizeof licence, err, sizeof err) == 0 &&+ s.n == 0,+ "energy-charts, not open: no prices kept");+}++static void fuel(void)+{+ struct pr_fuel f;+ char err[300] = "";+ struct pr_fuel_ask a = {.now = 1790942400,+ .lat = 38.0174,+ .lon = 12.5160,+ .radius_km = 2,+ .kind = PR_DIESEL};+ CHECK(pr_read_fuel_it(S_IT_REG, strlen(S_IT_REG), S_IT_PRICES,+ strlen(S_IT_PRICES), &a, &f, err, sizeof err) == 0 &&+ f.found == 5 && f.n == 5,+ "Italy: %s %d", err, f.found);+ CHECK(f.s[0].price == 2.099 && f.s[0].self == 0 &&+ !strcmp(f.s[0].name, "Nobile Oil") && f.s[1].price == 2.230 &&+ f.s[1].self == 1 && !strcmp(f.s[1].name, "Api-Ip") &&+ !strcmp(f.s[2].name, "MAGGIO GIACOMA") &&+ fabs(f.average - 2.2994) < 1e-9,+ "Italy's stations: %s %.3f %d, %s, %s, %.4f", f.s[0].name,+ f.s[1].price, f.s[1].self, f.s[1].name, f.s[2].name, f.average);+ struct pr_place p = {+ .name = "Trapani", .country = "Italia", .lat = 38.0174, .lon = 12.5160};+ struct janas_buf d = {0};+ pr_fuel_data(&d, &p, "diesel", 2, &f, "mimit");+ const char *t = fill(PR_FUEL_LAYOUT, &d);+ CHECK(strstr(t, "Diesel near Trapani, Italia: stations within 2 km, 5; "+ "the cheapest 2.099 €/l, the average 2.299 €/l\n") &&+ strstr(t, "1. 2.099 €/l (served): Nobile Oil, PIAZZA STAZIONE "+ "SNC 91100, TRAPANI (") &&+ strstr(t, "2. 2.230 €/l (self-service): Api-Ip,"),+ "the fuel's layout:\n%s", t);+ janas_buf_free(&d);++ a = (struct pr_fuel_ask){.now = 1790942400,+ .lat = 48.8566,+ .lon = 2.3522,+ .radius_km = 3,+ .kind = PR_DIESEL};+ CHECK(pr_read_fuel_fr(S_FR, strlen(S_FR), &a, &f, err, sizeof err) == 0 &&+ f.n >= 1 && f.found == 7 && isnan(f.average) &&+ !strncmp(f.s[0].updated, "2026-10-02 ", 11),+ "France: %s %d %d %s", err, f.n, f.found, f.s[0].updated);+ a.kind = PR_CNG;+ CHECK(pr_read_fuel_fr(S_FR, strlen(S_FR), &a, &f, err, sizeof err) != 0,+ "France has no methane");+ a = (struct pr_fuel_ask){.now = 1790942400,+ .lat = 40.4168,+ .lon = -3.7038,+ .radius_km = 2,+ .kind = PR_DIESEL};+ CHECK(pr_read_fuel_es(S_ES, strlen(S_ES), &a, &f, err, sizeof err) == 0 &&+ f.n >= 1 && f.s[0].price > 1 && f.s[0].price < 3 &&+ !strncmp(f.s[0].updated, "2026-10-02 ", 11),+ "Spain: %s %d", err, f.n);+ a = (struct pr_fuel_ask){.now = 1790942400,+ .lat = 48.2,+ .lon = 16.37,+ .radius_km = 5,+ .kind = PR_DIESEL};+ CHECK(pr_read_fuel_at(S_AT, strlen(S_AT), &a, &f, err, sizeof err) == 0 &&+ f.n >= 1 && fabs(f.s[0].price - 2.109) < 1e-9 && f.s[0].self == 0,+ "Austria: %s %d", err, f.n);+}++/* a price told over PR_STALE_DAYS days before is left out, in both+ ways the sources write a time */+static void stale(void)+{+ struct pr_station st[3] = {+ {.name = "old", .price = 1.5, .updated = "16/09/2026 08:00:00"},+ {.name = "new", .price = 1.9, .updated = "2026-10-01 10:00"},+ {.name = "undated", .price = 1.8}};+ struct pr_fuel f;+ memset(&f, 0, sizeof f);+ pr_fuel_rank(&f, st, 3, 1790942400);+ CHECK(f.found == 2 && f.stale == 1 && !strcmp(f.s[0].name, "undated") &&+ f.cheapest == 1.8,+ "stale prices: %d found, %d left out, first %s", f.found, f.stale,+ f.s[0].name);+}++int main(void)+{+ setenv("TZ", "UTC", 1);+ money();+ macro();+ fuel();+ stale();+ if (failures) {+ printf("test_prices_parse: %d failures\n", failures);+ return 1;+ }+ printf("test_prices_parse: ok\n");+ return 0;+}