
What to Check When Backtesting with Historical Data from a Free Forex API
Learn how to use free FX API historical data for backtesting. Discover how missing data, timestamps, OHLC accuracy, and trading costs can affect your results.
A developer might use a free forex API to download historical USD/JPY prices and test a moving average or breakout strategy in Python. The backtest looks profitable, but once the strategy runs in a live environment, its performance is noticeably different.
The trading logic is not always the problem. Missing candles, inconsistent timestamps, or ignored trading costs can all make historical test results less representative of actual market conditions.
When choosing a free forex API, developers should look beyond how much historical data they can retrieve. They also need to understand whether that data is suitable for the strategy they want to test.
Check Data Continuity, Not Just Historical Coverage
When evaluating a forex historical data API, check the supported currency pairs, candle intervals, request limits, and timestamp format.
For example, the AllTick REST API supports up to 500 candles in a single request to its single-instrument K-line endpoint. For forex instruments such as USD/JPY, kline_timestamp_end can be used to specify the historical query boundary.
The following Python example retrieves one-hour USD/JPY candles:
import json, uuid, requests, pandas as pd
from urllib.parse import quote
query = {
"trace": str(uuid.uuid4()),
"data": {
"code": "USDJPY",
"kline_type": 5,
"kline_timestamp_end": 0,
"query_kline_num": 500,
"adjust_type": 0
}
}
url = "https://quote.alltick.co/quote-b-api/v1/kline/" + quote(
json.dumps(query, separators=(",", ":")), safe=""
)
r = requests.get(
url, headers={"X-API-Key": "YOUR_API_KEY"}, timeout=20
)
r.raise_for_status()
result = r.json()
if result.get("ret") != 200:
raise RuntimeError(result)
df = pd.DataFrame(result["data"]["kline_list"])
df["timestamp"] = pd.to_datetime(
pd.to_numeric(df["timestamp"]), unit="s", utc=True
)
cols = ["open_price", "high_price", "low_price", "close_price"]
df[cols] = df[cols].apply(pd.to_numeric, errors="coerce")
df = df.sort_values("timestamp")
print("重複:", df["timestamp"].duplicated().sum())
invalid = (
(df.high_price < df[["open_price", "close_price"]].max(axis=1)) |
(df.low_price > df[["open_price", "close_price"]].min(axis=1)) |
(df.high_price < df.low_price)
)
print("OHLC异常:", invalid.sum())
Here, kline_type: 5 specifies one-hour candles, query_kline_num: 500 requests 500 bars, and kline_timestamp_end: 0 retrieves data backward from the latest available market period.
If the strategy requires more than 500 candles, retrieve the data in multiple batches. Sort the records by timestamp and remove duplicates before combining them into a single dataset.
A Time Gap Does Not Always Mean Missing Data
After downloading historical forex data, inspect the timestamps for unexpected gaps.
For example, if an hourly series is expected to be continuous but one or more candles are missing, the gap may affect moving averages, RSI calculations, and ultimately the timing of strategy signals.
However, not every gap indicates an API problem.
The forex market closes over the weekend, and some currency pairs have daily trading breaks. Daylight saving time can also change the scheduled trading hours. AllTick's instrument catalog provides trading sessions based on GMT 0, which can help developers distinguish normal market closures from potential data issues.
Avoid automatically filling every gap with a zero price or the previous candle's closing price. First determine whether the interval represents a scheduled market closure or missing records. The appropriate handling depends on the strategy and data requirements.
OHLC Data Cannot Fully Reproduce Actual Execution
Trading costs are another factor that can significantly affect backtest results.
When using OHLC candles alone, it may not be possible to reconstruct the Bid and Ask prices at every point in time or simulate actual order execution accurately.
For example, buying EUR/USD involves the Ask price, while selling involves the Bid price. The difference between these two prices is the spread.
This matters particularly for short-term strategies. Even a relatively small spread can affect overall profitability when a strategy trades frequently.
There is another limitation: if a candle's high reaches a take-profit level while its low also reaches a stop-loss level, OHLC data alone cannot establish which level was reached first.
For short-term strategies, consider using finer time intervals or Tick data where appropriate. Include spread, commission, and slippage assumptions in the backtest instead of evaluating performance using price movements alone.
Choosing a Free Forex API: Check the Actual Access Conditions
When comparing free forex APIs, do not focus only on the number of supported currency pairs. Data types, historical access, and API request limits matter just as much.
AllTick Forex API supports more than 50 currency pairs and provides Bid/Ask quotes, Tick data, OHLC candles, and historical time series. Its Free plan includes demo instruments such as USD/JPY and allows up to 10 API requests per minute.
However, the availability of a demo instrument does not automatically mean that every currency pair has identical historical data access. Before running a backtest, verify the permitted instruments, candle intervals, and actual historical query range using your own API key.
A practical starting point is to retrieve a small USD/JPY dataset, validate its timestamps and OHLC values, and then connect the validated data to your backtesting program.
For developers building forex analytics tools or automated trading systems, visit the AllTick API portal to review the API access conditions and integration options.
Reliable backtesting depends on more than a well-designed strategy. It also depends on whether the historical data accurately supports the assumptions behind that strategy.
Note: AllTick market data is provided for informational purposes only and is not intended for trading or investment purposes.