Skip to Content
Symmio Trading-SDK — the SDK surface for builders on Arbitrum
CoreCandlesgetCandlesQueryOptions

getCandlesQueryOptions

Build TanStack Query options for a CandleSource’s historical bars.

Unlike the chain-scoped factories elsewhere in the SDK, this takes a source rather than a Config: which venue to chart is the consumer’s choice, not a property of the SYMMIO deployment. The source’s id is folded into the query key so switching venues does not read another venue’s cached bars.

import { createBinanceCandleSource, getCandlesQueryOptions } from "@symmio/trading-core"; const source = createBinanceCandleSource(); const options = getCandlesQueryOptions(source, { marketName: "BTCUSDT", resolution: "1m", from: rangeStart, to: rangeEnd, }); // queryClient.fetchQuery(options) / useQuery(options)

Parameters

marketNamestring

Market name as SYMMIO names it (e.g. "BTCUSDT").

resolutionCandleResolution

Bar size to fetch. Must be listed in the source’s supportedResolutions. See Resolutions.

fromnumber

Range start, unix milliseconds, inclusive.

tonumber

Range end, unix milliseconds, exclusive.

limitnumberoptional

Maximum bars to return. A source pages internally to satisfy this, so it may exceed the venue’s own per-request cap.

queryQueryParameteroptional

TanStack overrides (staleTime, enabled, …).

Returns

GetCandlesQueryOptions

Options to pass to useQuery / queryClient.fetchQuery. The resolved data is GetCandlesData — candles in ascending time order, de-duplicated and clipped to the requested range, plus a noMoreData flag.

noMoreData is true when the source confirms there is no earlier history to page into. A chart paging backwards should stop when it sees this. The result can still contain candles, including the instrument’s earliest available bar.

from/to are part of the query key. Passing a live Date.now() mints a new cache entry on every call — derive the range from state that only changes when the user actually pans or changes resolution.

For providers without history-boundary metadata, noMoreData: false means exhaustion is unknown. Empty windows can be gaps. See the lowcap source compatibility note. Use staleTime: 0 for mutable history and refetch on the stream’s onReset; do not mark recent OHLCV immutable.

Query key

getCandlesQueryKey builds the key on its own — its options take a sourceId in place of the source object:

import { getCandlesQueryKey } from "@symmio/trading-core"; const key = getCandlesQueryKey({ sourceId: source.id, // e.g. "binance:usd-m-futures" marketName: "BTCUSDT", resolution: "1m", from, to, }); // → ["getCandles", { sourceId, marketName, resolution, from, to }]

signal is excluded from the key. The query function forwards TanStack’s abort signal to the source, including through useCandles, so obsolete pages can be cancelled. Direct queryFn() calls remain supported without a signal.

Types

TypeShape
GetCandlesOptionsThe parameters above.
GetCandlesData{ candles: Candle[]; noMoreData: boolean }
GetCandlesQueryKey["getCandles", { sourceId, marketName, resolution, from, to }]
GetCandlesQueryOptionsThe TanStack options bag this factory returns.

getCandleHistoryQueryOptions

Build an incremental history query for any CandleSource. This factory is framework-neutral: use it with TanStack’s InfiniteQueryObserver or a framework infinite-query hook. React consumers can use useCandleHistory.

import { getCandleHistoryQueryOptions } from "@symmio/trading-core"; const options = getCandleHistoryQueryOptions(source, { marketName, resolution: "1h", from: rangeStart, to: rangeEnd, followLatest: true, query: { staleTime: 0, retry: false }, }); // useInfiniteQuery(options) / new InfiniteQueryObserver(queryClient, options)
function getCandleHistoryQueryOptions( source: CandleSource, options: GetCandleHistoryOptions, ): GetCandleHistoryQueryOptions; function getCandleHistoryQueryKey(parameters: GetCandleHistoryQueryKeyParameters): GetCandleHistoryQueryKey;

The required inputs are marketName, resolution, from, and to. Bounds are integer milliseconds and must satisfy from < to. Optional followLatest defaults to false; when enabled, only the newest window’s end advances through the current time when fetched. query accepts TanStack observer overrides except the SDK-owned key, function, selection, page cursors, and page eviction settings.

Calling fetchNextPage requests [oldestRequestedFrom - (to - from), oldestRequestedFrom). It does not download loaded windows again. Cursors come from requested dates, including empty windows, rather than candle counts or the first returned candle. The source owns bucket alignment, internal HTTP limits, and flat-candle filtering. No consumer bar limit is passed, so a page cannot silently discard part of its requested range.

Guard calls with !isFetching && hasNextPage and pass { cancelRefetch: false } to deduplicate concurrent page requests. A normal refetch revalidates every retained window, including removals and corrections, following TanStack’s infinite-query behavior . For a source correction with known bounds, use refreshCandleHistory to fetch only corrected intervals. Do not treat retained data as final or disable correction-triggered refreshes.

The selector retains TanStack’s pages and pageParams and adds ascending, duplicate-free candles and noMoreData from the oldest requested window. It preserves the source’s candles, including any first-candle exception per separately requested window. Query identity includes the source id, market, resolution, initial range, and follow policy; keep the initial range stable during paging.

TypeShape / purpose
CandleHistoryRange{ from: number; to: number } in milliseconds.
CandleHistoryPageA requested range plus { candles, noMoreData }.
CandleHistoryData{ pages, pageParams, candles, noMoreData }; pages newest first, candles oldest first.
GetCandleHistoryParametersMarket, resolution, initial range, and optional followLatest.
GetCandleHistoryOptionsParameters plus query overrides.
GetCandleHistoryQueryKeyParametersParameters plus sourceId.
GetCandleHistoryQueryKey["getCandleHistory", { sourceId, marketName, resolution, from, to, followLatest }].
GetCandleHistoryQueryOptionsInfinite-query observer options returned by the factory.

The returned options include fetchRange(range, signal): Promise<CandleHistoryPage> for exact-range reads. It uses the same source, market, resolution, and cancellation rules as queryFn, but never extends the range for followLatest. refreshCandleHistory uses it for corrections. If you wrap errors for a framework, wrap both queryFn and fetchRange consistently; the React hook does this for you.

refreshCandleHistory

Revalidate an incremental history query using the same QueryClient and options that own its retained pages. Pass the optional range from watchCandles.onReset to fetch only corrected intervals. Omit it for a full refresh. React consumers use history.refresh(range).

function refreshCandleHistory(queryClient: QueryClient, parameters: RefreshCandleHistoryParameters): Promise<void>; interface RefreshCandleHistoryParameters { queryOptions: GetCandleHistoryQueryOptions; range?: CandleHistoryRange; signal?: AbortSignal; }
ParameterMeaning
queryClientTanStack client owning this history query.
queryOptionsThe original getCandleHistoryQueryOptions result, including any query-function error wrapper.
range?Corrected candle starts, in integer milliseconds: inclusive from, exclusive to. Requires from < to.
signal?Cancels a scheduled refresh before it starts. An existing shared query owns cancellation of its transport.

A bounded refresh waits for pending full refreshes and active or offline-paused paging to finish, then fetches the corrected intervals within retained windows. It replaces candles in those intervals, including removals, and preserves the others. The original paging boundaries stay intact; exhaustion is updated only when the beginning of a page is fetched again. Flat-candle filtering is evaluated by the source for each requested interval. A correction outside a fixed retained range makes no request. With followLatest: true, any missing tail is also fetched through the current time, including when the correction targets an older page or falls outside retained history. This read overlaps one interval before the previous cutoff so a candle that was still forming is revalidated, even if it was previously absent. Monthly resolutions use a 31-day overlap; each source retains ownership of bucket alignment. Adjacent or overlapping intervals share a request; separated corrections and tails are fetched independently, so a small correction does not redownload an entire growing page. If no history is retained, the initial window is fetched.

A full refresh takes priority over bounded corrections, cancels active work for this query, and revalidates all retained windows. A correction arriving while the full refresh starts cannot reduce its coverage. Both modes expose loading and errors through the original query; existing data remains available during refresh and after a failure. The promise rejects on a request failure or cancellation; invalid bounds throw INVALID_CANDLE_RANGE. A source can split each window into multiple HTTP requests.

import { getCandleHistoryQueryOptions, refreshCandleHistory } from "@symmio/trading-core"; const queryOptions = getCandleHistoryQueryOptions(source, { marketName, resolution: "1h", from: rangeStart, to: rangeEnd, followLatest: true, }); await queryClient.fetchInfiniteQuery(queryOptions); await refreshCandleHistory(queryClient, { queryOptions, range: { from: correctedCandleStart, to: correctedCandleStart + 3_600_000 }, });

Observer refetch policies still apply independently. For a chart that refreshes through source resets and an explicit Refresh control, set query.refetchOnWindowFocus: false to avoid a full refetch on every return to the tab. This does not make history immutable or disable explicit corrections.

Last updated on