
Forex API Integration Tutorial: How to Get Real-Time Forex Quotes and Historical K-Line Data
Learn how to retrieve historical forex candlestick data with REST APIs and stream live quotes through WebSocket. Using EUR/USD as an example, this guide covers Python integration, key parameters, and timestamp handling.
When developing a forex market dashboard or quantitative trading system, two problems usually need to be solved: how to continuously obtain the latest quotes for currency pairs such as EUR/USD and USD/JPY, and how to retrieve historical prices for candlestick charts and trading strategy validation.
Although these requirements seem similar, they do not necessarily call for the same API approach. Integrating a forex API is not just about retrieving data successfully. It also involves choosing the right data delivery method, handling timestamps correctly, and ensuring that real-time quotes can be connected with historical data.
Should You Use a REST API or WebSocket for Real-Time Quotes?
If an application only needs to retrieve a quote when a user opens a page, a REST API is usually more straightforward. The program sends an HTTP request, retrieves the current data, and ends the request. This approach is suitable for quote queries, page initialization, and periodic refreshes.
However, if you need to update forex quotes continuously—for example, displaying the latest bid and ask prices for EUR/USD in a trading terminal—repeated REST API calls require ongoing requests and may not capture every market update between requests.
In this case, WebSocket is better suited to continuous market data subscriptions. Once the client establishes a connection and subscribes to the required currency pairs, the server can continuously push updates, reducing the overhead of repeatedly initiating HTTP requests.
| Development requirement | More suitable approach |
|---|---|
| Retrieving current quotes or initializing a page | REST API |
| Continuously updating real-time forex quotes | WebSocket |
| Retrieving historical K-lines for backtesting | REST API |
| Displaying historical charts alongside real-time prices | REST API + WebSocket |
When choosing a forex market data API, you should also confirm which currency pairs are supported, which quote fields are provided, and what request-rate and subscription limits apply to your plan. Different APIs may return prices that look similar but have different meanings.
Retrieving Historical Forex K-Line Data with AllTick
For example, if you need historical EUR/USD data, AllTick provides a forex data API that allows you to retrieve K-line data through an HTTP GET request.
The historical K-line endpoint for forex, precious metals, cryptocurrencies, and certain commodities uses the path /quote-b-api/kline. The request passes the API token through the token parameter and submits URL-encoded JSON parameters through query.
The following Python example requests the latest 100 EUR/USD K-lines, with each candle representing five minutes:
import json
import os
import uuid
import requests
BASE_URL = "https://quote.alltick.co/quote-b-api"
TOKEN = os.environ["ALLTICK_API_TOKEN"]
query = {
"trace": str(uuid.uuid4()),
"data": {
"code": "EURUSD",
"kline_type": 2,
"kline_timestamp_end": 0,
"query_kline_num": 100,
"adjust_type": 0
}
}
response = requests.get(
f"{BASE_URL}/kline",
params={
"token": TOKEN,
"query": json.dumps(query)
},
timeout=15
)
response.raise_for_status()
result = response.json()
if result.get("ret") != 200:
raise RuntimeError(f"API error: {result}")
candles = result.get("data", {}).get("kline_list", [])
print(f"Retrieved {len(candles)} candles")
Before running the code, install requests and set a valid API token in the ALLTICK_API_TOKEN environment variable. This example demonstrates the request and basic error-handling logic. The actual response structure and call results should still be verified against the current documentation and your account.
Several parameters deserve particular attention:
code: Specifies the currency pair. Use a code format supported by the product.kline_type: Specifies the K-line interval. In this example,2corresponds to five-minute candles.kline_timestamp_end: Sets the query's time boundary. A value of0indicates a query starting from the latest available market data range.query_kline_num: Specifies the number of K-lines to return. A maximum of 500 candles can be requested in a single call.
If you need more historical data, do not assume that a single request will return the entire dataset. Retrieve data in segments using supported time boundaries, then check for duplicate timestamps, expected ordering, and completeness.
Why Should You Check Timestamps After Integrating Real-Time Quotes?
Receiving data from an API does not mean that the data can be used directly in calculations or business logic.
For example, a WebSocket connection may deliver multiple EUR/USD updates. If the program simply overwrites the current price in message-arrival order, network delays may cause an older quote to arrive after a newer one. The interface could then display a stale price.
A more reliable approach is to record the event time of each quote and distinguish between the time the market data was generated and the time it was received locally. When updating a cache, determine whether a new record should replace the current one based on the data type and the timestamp fields provided by the API, rather than relying solely on message-arrival order.
Historical K-lines require similar checks. When merging data from different batches, use fields such as the currency pair and K-line interval to identify the relevant data, then deduplicate and sort records by timestamp. If a time gap appears, first determine whether it falls within a normal market closure or data-availability period. Do not automatically fill every gap by carrying forward the previous candle's closing price.
Real-time quotes and historical K-lines may also update at different rates. If your application needs to update the end of a historical chart continuously, determine whether the latest candle is complete or still forming. Otherwise, an unfinished candle may be incorrectly treated as a final closing price.
What Else Should You Check Before Choosing a Forex Market Data API?
Before integration, confirm three things: whether the required currency pairs are covered, whether the available historical data range and K-line intervals meet your needs, and whether your plan supports the required request rate and number of WebSocket connections.
AllTick's forex API page lists representative currency pairs such as EUR/USD, GBP/USD, and USD/JPY. It also describes data types including real-time bid and ask quotes, Tick data, OHLC K-lines, and historical time series. The actual coverage and available permissions should be confirmed against the current product catalog, plan details, and API documentation.
If you are developing a forex market dashboard, quantitative strategy, or market data service, start by reviewing the AllTick Forex Market Data API, then consult the AllTick API documentation to confirm the parameters, authentication method, and data limitations before integration.
Reliable forex API integration involves more than retrieving real-time prices. It requires ensuring that historical data, timestamps, and update logic meet the application's actual requirements. Before deploying to production, validate requests using your target currency pairs, then test WebSocket reconnection, data deduplication, and historical K-line recovery.