How to Test a US Stock Historical Data API for Stop-Loss and Take-Profit Backtests

TickDB Research ·

How to Test a US Stock Historical Data API for Stop-Loss and Take-Profit Backtests

Before buying minute data for a US stock strategy with stop-loss and take-profit exits, test whether the two levels first appear in separate bars. We reran the same check on one unadjusted session each for AAPL and NVDA. AAPL’s upper and lower levels first fell within the ranges at 09:30 and 09:41. Both NVDA levels fell inside the 09:30 bar. The worksheet and script help you identify which windows are worth checking at a finer resolution.

Suppose a long position is already open. The next minute’s range contains both the take-profit and stop-loss levels. Your code can record a profit if it evaluates that exit first, or a loss if it checks the other one first. Find cases that depend on that assumption before deciding what data to buy.

Check the minute labels before testing your exit logic

We requested unadjusted one-minute bars from TickDB’s historical candlestick endpoint for AAPL on October 27, 2026, and NVDA on October 26 (interval=1m, adjust=none) [1]. We retrieved and saved both responses on November 21 [2]. Using New York’s 09:30 to 16:00 regular session as the window [3], we checked that each response had all 390 minute labels from 09:30 through 15:59, with no duplicates [2].

Separate the checks. First establish a consistent session, price adjustment, and set of minute labels. Then test the question your strategy depends on. Can you order the first bars whose ranges contain each exit level?

AAPL separates the levels. NVDA leaves the order unresolved

To make the check reproducible, we set the example levels 0.25 US dollars above and below the opening price of each symbol’s first bar. Starting at 09:30, we found the first bar whose high-low range contained each level. AAPL’s levels appeared in separate minute bars. The upper was at 09:30 and the lower at 09:41. Both NVDA levels fell in the same minute bar, at 09:30 [2].

AAPL’s upper and lower levels fall within the 09:30 and 09:41 ranges. NVDA’s first bar contains both, with the order unresolved

The same range check on two saved responses. Times are local to New York [2].

Sample and example levelsFirst bar containing each level
AAPL, October 27. USD 343.415 upper and 342.915 lower09:30 upper and 09:41 lower. The first qualifying bars are in different minutes.
NVDA, October 26. USD 213.355 upper and 212.855 lowerBoth at 09:30. The order within the minute is unresolved.

NVDA’s first bar had a high of 213.640 and a low of 212.610 [2]. A path that visits the high first and one that visits the low first can have the same extrema. The open and close give the endpoints. A backtest engine needs an additional assumption to assign a single exit order inside that bar. TradingView’s broker emulator, for example, documents the price-path assumptions it uses by default [4].

The saved NVDA response opened directly in a browser, showing a first-bar high of 213.640 and low of 212.610

Original response in the browser. The first timestamp labels 09:30 New York time on October 26, 2026 [2].

The output identifies the first qualifying minute for each level. Your strategy still needs rules for gaps, entry timing, and order triggers. With finer data, whether an order fills and at what price still depends on execution conditions [5].

How much can the exit assumption change the result?

Take the original NVDA bar and make a hypothetical trade. Assume a one-share long entry at the 09:30 bar’s opening price of USD 213.105. Assume the first level reached is also the exit price. Set slippage and fees aside for this illustration [2].

AssumptionAssumed exit priceResult per share
Upper level firstUSD 213.355+USD 0.25
Lower level firstUSD 212.855−USD 0.25

The difference is USD 0.50 per share with the same OHLC bar. The original data shows that both levels lie within the bar’s range. The exits and results in the table follow from the two assumptions and require finer data and execution rules to verify for a real trade.

Request finer data for the windows that could change your conclusion

Choose trades whose exit order could change your assessment. Substitute your strategy’s actual entry time and exit levels. Mark same-bar cases as unresolved. Then rerun the samples twice with the other assumptions held fixed, once giving the upper exit priority and once giving the lower exit priority. The two runs show how sensitive your conclusion is to that choice.

If both runs support the same research decision, keep using minute bars and retain the two conditional results and the unresolved label. If one run passes your predefined strategy acceptance threshold and the other fails, ask for finer data for the affected window first. If it is unavailable, report both conditional results and leave the window unresolved. For NVDA here, the starting point would be October 26 at 09:30 New York time. Ask what finer historical sample exists, which price and timestamp fields it contains, and whether its resolution can support your actual trigger rule. We tested the minute bars here. Test a finer sample separately if you need it. The TickDB US Stock Market Data API page is the starting point for checking available minute data and its settings.

Record the trial and rerun the check

What to recordHow to use it
Symbol, trading date, session, and price adjustmentsMatch the scope across feeds and keep the input samples.
Entry time and both exit levelsUse your actual strategy settings. If the position opened in the same bar, check the price path relative to entry.
First qualifying bars and check statusDistinguish separate bars, unresolved same-bar cases, one level seen, and neither level seen. Investigate missing or duplicate bars and invalid price ranges first.
Upper-first and lower-first run results, and any window to requestRecord whether the assumption changed your assessment. Include the symbol, date, time zone, and exact window in the request.

Save the script as check_minute_order.py and run it with Python 3.9 or newer. It takes one stock’s unadjusted 1m JSON response for a full regular session, the date, and both price levels. It requires adjust=none, validates the 390 minute labels, and finds each level’s first qualifying bar. If the adjustment field is absent or differs, retrieve the data again on the same adjustment basis. An after-entry window, an early close, or extended hours needs different session boundaries. Here is the actual output from both frozen responses [2].

python check_minute_order.py aapl-20261027.json 2026-10-27 343.415 342.915
AAPL.US upper=09:30 lower=09:41 upper_first
python check_minute_order.py nvda-20261026.json 2026-10-26 213.355 212.855
NVDA.US upper=09:30 lower=09:30 same_bar_unresolved
import json
import sys
from datetime import datetime, timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo

file_name, trading_day, upper, lower = sys.argv[1:]
upper, lower = Decimal(upper), Decimal(lower)
if not (upper.is_finite() and lower.is_finite() and upper > lower):
    raise SystemExit("Expected finite thresholds with upper > lower")

with open(file_name, encoding="utf-8") as file:
    envelope = json.load(file)
reply = envelope.get("reply", envelope)
code = reply.get("code")
if type(code) is not int or code != 0:
    raise SystemExit("Expected integer business code 0")

data = reply.get("data")
if not isinstance(data, dict) or data.get("interval") != "1m":
    raise SystemExit("Expected a one-minute response")
if data.get("adjust") != "none":
    raise SystemExit("Expected unadjusted data: adjust=none")
ny = ZoneInfo("America/New_York")
start = datetime.fromisoformat(f"{trading_day}T09:30").replace(tzinfo=ny)
rows = sorted(data["klines"], key=lambda bar: bar["time"])
expected = [int((start + timedelta(minutes=i)).timestamp() * 1000)
            for i in range(390)]
if [bar["time"] for bar in rows] != expected:
    raise SystemExit("Review: missing, duplicate or out-of-session minute labels")

bounds = [(Decimal(bar["low"]), Decimal(bar["high"])) for bar in rows]
if any(not lo.is_finite() or not hi.is_finite() or lo > hi for lo, hi in bounds):
    raise SystemExit("Review: invalid price ranges")

def first_covering(level):
    return next((start + timedelta(minutes=i) for i, (lo, hi) in enumerate(bounds)
                 if lo <= level <= hi), None)

def label(value):
    return value.strftime("%H:%M") if value is not None else "not_seen"

hi, lo = first_covering(upper), first_covering(lower)
if hi is None or lo is None:
    result = "neither_seen" if hi is None and lo is None else "one_side_seen"
elif hi == lo:
    result = "same_bar_unresolved"
else:
    result = "upper_first" if hi < lo else "lower_first"
print(f"{data['symbol']} upper={label(hi)} lower={label(lo)} {result}")

Frequently asked questions about testing minute data

The levels appeared in different minutes. Can I record a fill?

Record the order of the qualifying minutes. Use your order type and trigger rules to model fills. Check the specific window if a gap crossed a level or entry and exit fall in the same bar [5].

What should I do with same_bar_unresolved?

Keep the order unresolved. Try both exit priorities on the same strategy sample. If your conclusion changes, ask for finer data for that symbol, date, New York time, and pair of levels.

What if I get fewer than 390 bars or one level is absent?

Check the session before interpreting the result. Verify whether the session closed early, included extended hours, or had gaps in the response. If the chosen window is complete, record one level seen or neither seen and check for price gaps that skipped over a level.

References

  1. TickDB official OpenAPI specification, Candlestick Data, GET /v1/market/kline. Used for the interval, query window, and price adjustment settings.
  2. This article’s test record. Unadjusted minute responses for AAPL on October 27, 2026, and NVDA on October 26, saved November 21, with the script output and original screenshot.
  3. Nasdaq, US & Nordic Stock Market Schedule, US regular market hours. Used to define the regular-session window for the test.
  4. TradingView Pine Script documentation, Strategies, Broker emulator. Used for the documented price-path assumptions in a simulator.
  5. U.S. Securities and Exchange Commission, Investor.gov, Stop, Stop-Limit, and Trailing Stop Orders – Investor Bulletin, published July 13, 2017, updated August 18, 2026. Used for the distinction between order triggers and execution.

7 markets · 42,687 symbols

US stocks
14,386
Hong Kong market
3,353
China stocks, ETFs & bonds
7,576
Forex & metals
1,228
Indices
13,960
Futures
1,172
Crypto
1,012
11/23/2026

Related articles

Did Your Watchlist Follow the Index? A Midday Review with a Real-Time China A-Share Stock API

On November 23, the ChiNext Index opened lower and was up 1.22% by midday. Yet 209 stocks in our example watchlist were still below their previous close. Use opening prices, previous closes, and midday quotes from a real-time China A-share stock API to see which stocks rebounded, which turned positive, and whether your watchlist still warrants a risk flag.

TickDB Research ·

Moving a Hong Kong stock data API into Docker? Check the first quote after restart

Before moving a Hong Kong stock dashboard, alerting service, or risk monitor to Docker, what should count as recovery? In our local Tencent test, the first quote request returned HTTP 403. A later run returned a valid snapshot. The controlled restart command returned after 0.223 seconds, and the first quote passed validation after 1.580 seconds. It was still the previous session's quote. This article shows what to check on a weekend and what to verify again during trading.

TickDB Research ·

How to Trial a China A-Share Market Data API Before Switching Your Intraday Screener

Before switching an intraday A-share screener to a new feed, start with your own stock list. All 300 CSI 300 constituents matched in our weekend snapshot and carried the expected quote date. Seven stocks outside the list had earlier quotes. Use the worksheet below to take the same check into a parallel intraday trial.

TickDB Research ·

How to Track Hong Kong Stock Buybacks with a Market Data API and Filings

How do you check a Hong Kong stock buyback announcement and calculate the change in shares in issue? Tencent's FY2025 disclosures show how to reconcile a buyback plan, actual repurchases, share cancellations and new issuance. Compare the market data API aggregate with HKEX filings, then use the share count reconciliation to explain why Tencent bought back 153.4 million shares but ended the year with 1.13% fewer issued shares.

TickDB Research ·

Trailing P/E (TTM): Financial Data API Guide to Adjusted Earnings and Peer Valuation

How do you calculate trailing P/E (TTM) for peer valuation without mixing earnings definitions? This financial data API research example combines dated market prices with official Cambricon and Hygon reports to compare reported and adjusted earnings—specifically, parent-attributable income excluding the reports' non-recurring items. The relative reference-multiple gap narrows from 10.33% to 6.34%. Includes a revenue-to-shareholder-earnings decomposition, an earnings sensitivity table and runnable Python.

TickDB Research ·