The Easiest Way to Get Mild Steel Plate China Spot (MSP-CH) - Per Ton Historical Rates using a REST API in Python
If you need Mild Steel Plate China Spot (MSP-CH) — priced per ton — historical rates inside a Python or JavaScript workflow, the fastest path is a simple REST call to Metals-API and a few lines of code to normalize units, invert the “base currency” where needed, and cache results. In this guide, we’ll walk through pulling MSP-CH history for backfilling dashboards, pricing BOMs in ERP, and running time-based analytics in research pipelines. We’ll use just the 2–3 endpoints you actually need for historical analysis, explain the JSON you’ll get back, and share production tips for timestamps, per-ton units, weekend handling, and performance. Along the way, we’ll show one complete curl request plus a JavaScript snippet you can drop into a script or service. When you’re ready to build, get a free API key at the Metals-API Website.
What we’re building: pull MSP-CH per-ton historical prices for analysis and pricing
Typical use cases for MSP-CH historical rates include:
- Backfilling a multi-year chart for China spot mild steel plate pricing (per metric ton), aligned to your preferred currency and timezone.
- Computing rolling averages and volatility to drive a dynamic safety margin in procurement or BOM pricing.
- Generating alerts when daily close deviates from a trailing window (e.g., 5% above 30-day SMA).
- Exporting normalized per-ton values into data lakes or research notebooks for cost modeling and stress tests.
We’ll accomplish all of these using Metals-API’s historical and time-series endpoints and, where needed, daily OHLC (open, high, low, close) data. You can find endpoint details in the Metals-API Documentation and confirm symbol availability on Metals-API Supported Symbols. For this article, we’ll focus on MSP-CH specifically and keep everything else as minimal context.
Key concept: base currency and how to read “rates” for MSP-CH
Metals-API returns rates by default with base set to USD. That means each rate value tells you “how many units of the metal (or commodity) one USD buys” for the unit reported by the API. For precious metals, examples are often per troy ounce; for MSP-CH we care about per metric ton. Because most pricing and analytics require “USD per ton,” you’ll typically invert the rate:
- rate = units per USD (as returned by the API)
- price_per_ton_usd = 1.0 / rate
We’ll show how to do this safely and consistently, including sanity checks in code.
Which endpoints to use for MSP-CH historical analysis
We’ll use only the endpoints relevant to the title’s task:
- Historical Rates Endpoint: retrieve MSP-CH for a single past date.
- Time-Series Endpoint: retrieve MSP-CH for a date range.
- OHLC Endpoint: retrieve daily OHLC for MSP-CH when you need open/high/low/close series.
For everything else (latest rates, bids/asks, conversion, intraday, or specialized endpoints), see the Metals-API Documentation.
Authentication and symbol verification
Before you start:
- Get your API key at the Metals-API Website. You’ll pass it via the access_key parameter.
- Verify that MSP-CH appears on the Metals-API Supported Symbols page. This ensures correct symbol spelling and confirms the unit (per ton), which is critical for downstream math and labeling.
Historical Rates endpoint: single-day MSP-CH lookup
Use this when you want MSP-CH for a specific date, e.g., to fill a missing value in a daily table or to fetch “yesterday’s close.”
Purpose and functionality
The Historical Rates endpoint returns exchange rates for a given YYYY-MM-DD. For MSP-CH, it provides the per-ton rate expressed in units-per-USD (by default base=USD) for that date.
Parameters
- date (path): a date formatted as YYYY-MM-DD.
- access_key (query): your API key from Metals-API.
- base (optional): typically “USD” by default. Keep default unless you have a strong reason to change your base currency. If you choose another base, remember all math must follow that base.
- symbols (optional but recommended): set to MSP-CH to limit the payload to the required symbol.
Example curl request
curl "https://metals-api.com/api/2026-09-19?access_key=YOUR_API_KEY&symbols=MSP-CH&base=USD"
Sample JSON response (illustrative)
The following is a structurally accurate example response to help you integrate and test. Values are for demonstration only.
{
"success": true,
"timestamp": 1789777035,
"base": "USD",
"date": "2026-09-19",
"rates": {
"MSP-CH": 0.0005
},
"unit": "per metric ton"
}
Field-by-field explanation
- success: boolean indicator for request success.
- timestamp: Unix timestamp (UTC). Use it for ordering and caching. Convert to your display timezone as needed.
- base: currency denominator for rates; by default USD. That means the rate shows “tons per USD.”
- date: the historical date of the rates, formatted YYYY-MM-DD.
- rates: key-value mapping where the key is the symbol (“MSP-CH”) and the value is “per metric ton units per USD” for that date.
- unit: the unit of the symbol’s quantity. For MSP-CH you should expect something like “per metric ton.” Always display this in your UI to prevent unit confusion.
How to compute a price per ton in USD
- ton_per_usd = rates["MSP-CH"]
- usd_per_ton = 1.0 / ton_per_usd
Include guards for zero/None/NaN before inverting, and decide how to handle missing data (e.g., fallback to previous business day).
Common pitfalls and troubleshooting
- Zero or null rates: treat as missing data; fall back to nearest prior business day, or flag for manual review.
- Timezone drift: the date is in UTC context. If your local day changes earlier than UTC, you may see “yesterday” until the UTC roll. Align business logic accordingly.
- Weekends/holidays: some markets don’t print prices daily. Your historical series may naturally skip. Use previous-close carry-forward or an explicit market-calendar if your model requires continuity.
Performance and rate usage
- Cache historical dates aggressively; those values don’t change once published.
- Batch requests with the Time-Series endpoint when you need multiple days instead of one-by-one daily calls.
Time-Series endpoint: multi-day MSP-CH history
For charts, rolling windows, and backtesting, query a contiguous range with the Time-Series endpoint.
Purpose and functionality
Returns daily historical rates between start_date and end_date inclusive, with the same base and unit conventions. Responses are grouped by date keys.
Parameters
- start_date: YYYY-MM-DD (inclusive).
- end_date: YYYY-MM-DD (inclusive). Adhere to date range limits based on your plan.
- access_key: your API key.
- base (optional): typically “USD.”
- symbols (optional): set to MSP-CH to keep payload compact.
Example curl request
curl "https://metals-api.com/api/timeseries?access_key=YOUR_API_KEY&start_date=2026-09-13&end_date=2026-09-20&symbols=MSP-CH&base=USD"
Sample JSON response (illustrative)
Values are examples for demonstration purposes only; integrate the structure as shown.
{
"success": true,
"timeseries": true,
"start_date": "2026-09-13",
"end_date": "2026-09-20",
"base": "USD",
"rates": {
"2026-09-13": { "MSP-CH": 0.000505 },
"2026-09-15": { "MSP-CH": 0.000498 },
"2026-09-20": { "MSP-CH": 0.0005 }
},
"unit": "per metric ton"
}
Field-by-field explanation and usage
- timeseries: confirms you requested a range.
- start_date/end_date: useful for validating that your requested window was honored and for logging.
- rates: dictionary keyed by date; each date has MSP-CH rate in tons per USD.
- unit: confirm “per metric ton” to align axis labels and calculations.
Transformations for analytics
- Invert to USD per ton: 1.0 / rate.
- Compute SMA/EMA: run windowed averages on USD per ton values.
- Volatility: daily pct_change on USD per ton, then annualize if needed.
- Resampling: fill weekends or holidays forward only if your model requires continuity; otherwise keep market-day granularity.
Error handling and edge cases
- Missing dates: not all days print data; don’t assume weekends will appear. Your code should not rely on contiguous calendar dates.
- Partial windows: if end_date is in the future or a market holiday, the last date may be older than end_date. Detect by inspecting the keys returned.
- Validation: ensure all returned keys are within your requested window and parse ISO-format dates reliably.
Performance and scaling
- Prefer one time-series call per symbol per window instead of many daily historical calls.
- Persist normalized USD-per-ton values in a local store or cache. On app restart, only request incremental days you’re missing.
- For multi-tenant dashboards, decouple data-fetch from page load; update on a schedule and serve from cache to reduce API usage.
OHLC endpoint: open/high/low/close for MSP-CH
When you need daily bar data (e.g., to draw candlesticks or to compute range-based indicators), use the OHLC endpoint for MSP-CH.
Purpose and functionality
Returns a daily OHLC set for MSP-CH keyed under rates[“MSP-CH”] with open, high, low, close values. Units and base follow the same conventions as other endpoints.
Parameters
- date (path): YYYY-MM-DD for the OHLC day.
- access_key: API key.
- base (optional): typically “USD.”
- symbols (optional): set to MSP-CH.
Example curl request
curl "https://metals-api.com/api/open-high-low-close/2026-09-20?access_key=YOUR_API_KEY&symbols=MSP-CH&base=USD"
Sample JSON response (illustrative)
Values below are structural examples only for integration testing.
{
"success": true,
"timestamp": 1789863435,
"base": "USD",
"date": "2026-09-20",
"rates": {
"MSP-CH": {
"open": 0.000502,
"high": 0.000507,
"low": 0.000497,
"close":0.000500
}
},
"unit": "per metric ton"
}
How to use OHLC in analytics
- Invert each value to USD per ton for charts and indicators.
- True range and ATR: compute off inverted high/low/close values.
- Signal generation: use close or VWAP-equivalent logic if you blend OHLC data with other sources.
Validation and consistency checks
- Check that low ≤ open/close ≤ high after inversion. Due to floating precision, allow a small epsilon.
- Confirm unit matches expectations before rendering a chart.
End-to-end JavaScript example: fetch MSP-CH, invert to USD per ton, and compute day-over-day change
This snippet demonstrates a simple fetch from the Historical Rates endpoint, conversion to USD per ton, and a basic comparison against the previous business day. You can paste this into Node.js or adapt it for the browser (respecting key security best practices for client-side apps).
/**
* Example: Fetch MSP-CH for two dates and compute USD/ton and day-over-day pct change.
* Note: Replace YOUR_API_KEY with your actual key. Consider storing it securely (env var or vault).
*/
import fetch from "node-fetch";
const API_BASE = "https://metals-api.com/api";
const ACCESS_KEY = process.env.METALS_API_KEY || "YOUR_API_KEY";
const SYMBOL = "MSP-CH";
function invertToUsdPerTon(rate) {
if (rate === null || rate === 0 || Number.isNaN(rate)) {
throw new Error("Invalid MSP-CH rate for inversion");
}
return 1.0 / rate;
}
async function getHistorical(symbol, date, base = "USD") {
const url = `${API_BASE}/${date}?access_key=${ACCESS_KEY}&symbols=${encodeURIComponent(symbol)}&base=${base}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
const json = await res.json();
if (!json.success) {
const msg = json.error?.info || "Unknown Metals-API error";
throw new Error(`Metals-API error: ${msg}`);
}
const rate = json.rates?.[symbol];
if (rate == null) throw new Error(`No rate for ${symbol} on ${date}`);
const unit = json.unit; // e.g., "per metric ton"
return { date: json.date, rate, unit, base: json.base, timestamp: json.timestamp };
}
(async () => {
try {
const d1 = "2026-09-19";
const d0 = "2026-09-18"; // prior business day (ensure it's a valid market day in production)
const [r1, r0] = await Promise.all([
getHistorical(SYMBOL, d1),
getHistorical(SYMBOL, d0)
]);
const usdPerTon1 = invertToUsdPerTon(r1.rate);
const usdPerTon0 = invertToUsdPerTon(r0.rate);
const pctChange = ((usdPerTon1 - usdPerTon0) / usdPerTon0) * 100.0;
console.log({
symbol: SYMBOL,
date: r1.date,
base: r1.base,
unit: r1.unit,
usdPerTon: usdPerTon1,
dayOverDayPct: pctChange
});
} catch (err) {
console.error("Failed to fetch MSP-CH history:", err.message);
}
})();
What to look for in the response
- json.success: always check before accessing rates.
- json.base: confirm expected currency; change your math or labeling if you change base.
- json.rates["MSP-CH"]: the per-ton units-per-USD rate for the date.
- json.unit: display it to avoid confusion between “per troy ounce” and “per metric ton.”
- json.timestamp: use for logging, sorting, and caching keys.
Practical guidance you shouldn’t skip
Units: metric ton vs. troy ounce
Metals-API covers many instruments with different default units. MSP-CH should report per metric ton. Always read the unit field in the response and propagate it to your UI labels, data exports, and column metadata. Never hardcode unit assumptions.
Base currency and inversion
- Default base is USD and rate is “tons per USD.” Invert to compute USD per ton.
- If you set base to, say, EUR, then rate becomes “tons per EUR,” and your inversion yields EUR per ton.
- When displaying multiple currencies, maintain separate series to avoid mixing units unintentionally.
Timestamps and timezone
- timestamp is Unix time in UTC. Convert for UI display, but keep UTC for storage and joins.
- Daily cutovers reflect UTC. For regional dashboards, consider a market calendar or clearly indicate data “as of UTC.”
Weekends and market closures
- Not every calendar day yields a new rate. Expect missing keys in time-series for weekends and holidays.
- Decide on a carry-forward policy or maintain sparse daily indexing and compute indicators on observed days only.
Caching to save requests
- Historical values are stable. Cache them by date and symbol. If you do nightly jobs, only fetch the latest day.
- For web apps, separate a background data fetcher from the request path and serve from an internal cache or DB.
End-to-end curl workflow examples for MSP-CH
1) Fetch a single historical day and print the raw JSON
curl "https://metals-api.com/api/2026-09-19?access_key=YOUR_API_KEY&symbols=MSP-CH&base=USD"
2) Fetch a week of MSP-CH history
curl "https://metals-api.com/api/timeseries?access_key=YOUR_API_KEY&start_date=2026-09-13&end_date=2026-09-20&symbols=MSP-CH&base=USD"
3) Fetch daily OHLC for a specific date
curl "https://metals-api.com/api/open-high-low-close/2026-09-20?access_key=YOUR_API_KEY&symbols=MSP-CH&base=USD"
Integrating MSP-CH into pricing, ERP, and research pipelines
ERP and e-commerce pricing
- Nightly task: pull yesterday’s MSP-CH, invert to USD per ton, and recompute price lists or surcharges.
- Rounding and min increments: align with your commercial rules. Keep the raw USD-per-ton in a pricing facts table for audit.
- Currency localization: if your store runs in EUR, request base=EUR to avoid double conversion, or convert downstream with your FX layer.
Trading and risk tools
- Use time-series for return distributions, drawdowns, and correlation with freight, scrap, or energy indexes (if you maintain those separately).
- Integrate OHLC for range analysis or to calibrate slippage assumptions when you model procurement timing.
R&D notebooks and analytics
- Load MSP-CH series, invert, resample to business days, and annotate with economic calendars to explain gaps in data.
- Persist transforms (e.g., log-returns) for modeling to avoid recomputation during each analysis run.
Security and key management
- Never hardcode your API key in client-side code for public sites. Use a backend proxy or server-side fetch.
- Store keys in environment variables or a secret manager (e.g., Vault, AWS Secrets Manager).
- Implement request signing or IP allowlists if available in your environment.
Error handling and recovery strategies
- Transport errors: retry with backoff; distinguish transient timeouts from hard 4xx failures.
- API-level errors: check success=false; inspect error info field when present; log context (symbol, date range) for triage.
- Data gaps: for historical series, if a date is missing, either backfill from the prior available date or mark null and let the visualization handle sparse series.
Data validation and sanitization
- Type-check all parsed fields. Rates should be finite positive numbers before inversion.
- Clamp implausible spikes with alerts rather than silently discarding; keep raw payloads in a quarantine table for audits.
- Unit consistency: assert that unit contains “ton” for MSP-CH. If unexpected, stop the pipeline and notify maintainers.
Performance optimization and scaling
- Batch time-series calls by symbol and window. Avoid repeated single-day calls in loops.
- Introduce a materialized view (e.g., in Postgres) that stores USD-per-ton for MSP-CH with a date primary key and derived columns (SMA, EMA, pct_change). Regenerate on new data arrival only.
- Separate high-frequency frontends from your data fetch cadence. For dashboards, request from your own cache every few seconds, not the upstream API.
Monitoring and observability
- Log request IDs, symbol, window, and timing for each API call.
- Alert on a spike in failed fetches, missing days beyond tolerance, or a sudden change in unit/base.
- Include checksums for response bodies in stored artifacts to detect accidental mutations.
Versioning and schema evolution
- Encapsulate Metals-API parsing behind a small adapter module so that any schema or unit changes can be handled in one place.
- Write automated tests that validate MSP-CH parsing logic using saved fixtures representing success, error, and edge responses.
Compliance and auditability
- Archive original JSON responses for a minimum retention period relevant to your business audits.
- Record derived computations (e.g., inversion to USD per ton) with the version of code and algorithm used at the time.
Where to go next
- Read the Metals-API Documentation for endpoint limits, optional parameters, and additional features you might need later.
- Confirm symbol conventions on Metals-API Supported Symbols whenever you add a new commodity to your stack.
- Get a free API key at the Metals-API Website and start testing MSP-CH calls in your environment today.
A note on innovation: from static spreadsheets to API-first steel analytics
As steel procurement, manufacturing, and fintech converge, API-first data pipelines let teams replace manual updates with automated, reliable feeds. With metals data wired directly into pricing engines, manufacturing execution systems, and research sandboxes, your product teams can experiment with smart surcharges, dynamic safety stocks, and on-the-fly quotes that reflect real market conditions. Metals-API’s consistent schema and unit metadata help shift from brittle, ad-hoc data prep to repeatable analytics. This is the foundation for smarter tools—integrated dashboards, alerts, and decision support—that adapt quickly as markets evolve.
Conclusion
For Mild Steel Plate China Spot (MSP-CH) — priced per ton — the most direct way to obtain historical rates is to call Metals-API’s Historical Rates, Time-Series, and (if you need bar data) OHLC endpoints. Keep your logic simple and robust: verify the unit field, confirm the base currency, invert the rate to USD per ton, and cache aggressively. Handle weekends and closures by design, validate inputs and outputs, and separate fetch from render for scale and reliability. With those practices, you can backfill charts, power ERP pricing, and run research pipelines in minutes.
Start now: visit the Metals-API Website to get your free API key, scan the Metals-API Supported Symbols to confirm MSP-CH details, and integrate with confidence using the Metals-API Documentation.
Helpful links
- Metals-API Website — get your API key and explore features
- Metals-API Documentation — full endpoint reference
- Metals-API Supported Symbols — confirm MSP-CH and units
- World Steel Association — background research and reports
- Shanghai Futures Exchange — market context and announcements
FAQ
What does MSP-CH represent?
It stands for Mild Steel Plate China Spot, typically quoted per metric ton. Always confirm symbol definitions and units on the Metals-API Supported Symbols page.
Are rates returned as USD per ton?
By default, base=USD means the API returns “tons per USD.” Invert the rate (1/rate) to compute USD per ton.
How far back does MSP-CH history go?
Historical availability depends on the symbol and your plan. Use the Time-Series endpoint to request an early range; if earlier dates are unavailable, the result simply won’t include them. See the Metals-API Documentation for historical limits.
Why is a certain date missing?
Weekends, holidays, or data pauses can mean no print for that day. Handle missing dates by carrying forward the previous close if your analytics require a continuous series, or treat the series as irregularly spaced.
Can I get OHLC for MSP-CH?
Yes, via the OHLC endpoint for a given date. You’ll receive open, high, low, and close in the same units-per-base convention. Invert to USD per ton if needed.
What’s the best way to lower API request volume?
Cache historical responses indefinitely, fetch new days only once, and batch ranges with the Time-Series endpoint. For frontends, serve from your cache or database rather than calling the API on each view.
How do I secure my API key in the browser?
Prefer server-side calls or a backend proxy. If you must call from the browser, consider short-lived tokens or strict rate limits, but server-side remains best practice.
Can I request MSP-CH in EUR per ton directly?
Yes. Set base=EUR and invert the returned rate to get EUR per ton. Keep separate series per base currency to avoid confusion.