diff --git a/CHANGELOG.md b/CHANGELOG.md index fc7ecef..6e74012 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added ✨ + +- `type` on `BacktestRequest` and `SweepRequest` (`DataSourceType.TICKER`, the default, or `KLINE`). A strategy + that reads candles can now be backtested and swept from Java: preparation, execution, polling, cancellation + and the sweep reads use the requested route. Until now every Java run was prepared as ticker data, so a kline + strategy over a klines dataset ended `Failed`. The TypeScript and Python SDKs already took this option. +- `getBacktestResult(exchangeId, type, jobId)`, `getSweepRunEquityCurve(exchangeId, type, ...)` and + `getBoundedSweepRunEquityCurve(exchangeId, type, ...)` on `QTSurfer` and `AuthenticatedClient`: a run is + addressed by its exchange, its type and its id, so reading a kline run needs its type. The forms without a + type keep reading the ticker route. + ## [0.34.1] — 2026-10-25 ### Fixed 🐛 diff --git a/docs/backtesting.md b/docs/backtesting.md index a80cbd5..8831195 100644 --- a/docs/backtesting.md +++ b/docs/backtesting.md @@ -15,6 +15,23 @@ A kline backtest over `exchangeId: user` requires the selected ready dataset ver types with `400` before queueing. Upload datasets are classified from their rows when ingest reaches `READY`, so inspect the resulting `Dataset.type` rather than assuming every upload is a ticker. +A request is a ticker run unless it says otherwise. A strategy that reads candles needs `type(DataSourceType.KLINE)` +on its `BacktestRequest` (or `SweepRequest`); the type then applies to every stage of the run, preparation, +execution, polling, cancellation, and the sweep reads. A kline strategy submitted as a ticker run ends `Failed` +with the platform's reason. To read or cancel a run from another process, address it by its type too: +`getBacktestResult(exchangeId, DataSourceType.KLINE, jobId)`; the two-argument form reads the ticker route. + +```java +ResultMap result = qts.executeBacktest(BacktestRequest.builder() + .strategy(candleStrategy) + .exchangeId("user") + .datasetId("ds_candles") + .from("2026-08-01T00:00:00Z") + .to("2026-08-01T03:00:00Z") + .type(DataSourceType.KLINE) + .build()).join(); +``` + `executeBacktest(request)` compiles the source, prepares the requested window, submits execution, polls both asynchronous stages, and completes with `ResultMap`. Polling uses Failsafe exponential backoff and optional stage timeouts. diff --git a/src/main/java/com/qtsurfer/api/sdk/BacktestRequest.java b/src/main/java/com/qtsurfer/api/sdk/BacktestRequest.java index 16bbf95..e8d6af1 100644 --- a/src/main/java/com/qtsurfer/api/sdk/BacktestRequest.java +++ b/src/main/java/com/qtsurfer/api/sdk/BacktestRequest.java @@ -1,5 +1,6 @@ package com.qtsurfer.api.sdk; +import com.qtsurfer.api.client.model.DataSourceType; import com.qtsurfer.api.client.model.EquityCurveOptions; import com.qtsurfer.api.client.model.SweepBaseConfig; import java.util.LinkedHashMap; @@ -57,6 +58,10 @@ * keeps the platform defaults * @param params scalar strategy properties for this run; an empty map keeps every * declared property at its default + * @param type the kind of data the strategy reads, {@link DataSourceType#TICKER} (trades) or + * {@link DataSourceType#KLINE} (candles); {@code null} means + * {@code TICKER}. A strategy that reads candles needs {@code KLINE}, and over a + * user dataset that dataset's version must hold candles */ public record BacktestRequest( String strategy, @@ -69,8 +74,16 @@ public record BacktestRequest( String datasetVersionId, EquityCurveOptions equityCurve, SweepBaseConfig baseConfig, - Map params + Map params, + DataSourceType type ) { + /** Compatibility constructor for callers that predate {@code type}: a ticker run. */ + public BacktestRequest(String strategy, String exchangeId, String instrument, String from, String to, + Boolean storeSignals, String datasetId, String datasetVersionId, + EquityCurveOptions equityCurve, SweepBaseConfig baseConfig, Map params) { + this(strategy, exchangeId, instrument, from, to, storeSignals, datasetId, datasetVersionId, + equityCurve, baseConfig, params, null); + } public BacktestRequest(String strategy, String exchangeId, String instrument, String from, String to, Boolean storeSignals, String datasetId, String datasetVersionId) { this(strategy, exchangeId, instrument, from, to, storeSignals, datasetId, datasetVersionId, @@ -99,6 +112,7 @@ public BacktestRequest(String strategy, String exchangeId, String instrument, St Objects.requireNonNull(from, "from"); Objects.requireNonNull(to, "to"); params = params == null ? Map.of() : Map.copyOf(params); + type = type == null ? DataSourceType.TICKER : type; if (params.size() > 64) { throw new IllegalArgumentException("params may hold at most 64 properties"); } @@ -127,6 +141,7 @@ public static final class Builder { private EquityCurveOptions equityCurve; private SweepBaseConfig baseConfig; private final Map params = new LinkedHashMap<>(); + private DataSourceType type; public Builder strategy(String strategy) { this.strategy = strategy; return this; } public Builder exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } @@ -146,6 +161,11 @@ public static final class Builder { * @return this builder */ public Builder baseConfig(SweepBaseConfig baseConfig) { this.baseConfig = baseConfig; return this; } + /** + * @param type the kind of data the strategy reads: {@code TICKER} (the default) or {@code KLINE} + * @return this builder + */ + public Builder type(DataSourceType type) { this.type = type; return this; } /** Add or replace one scalar strategy property for this run. */ public Builder param(String name, Object value) { this.params.put(Objects.requireNonNull(name, "name"), Objects.requireNonNull(value, "value")); @@ -161,7 +181,7 @@ public Builder params(Map params) { public BacktestRequest build() { return new BacktestRequest( strategy, exchangeId, instrument, from, to, storeSignals, datasetId, datasetVersionId, - equityCurve, baseConfig, params); + equityCurve, baseConfig, params, type); } } } diff --git a/src/main/java/com/qtsurfer/api/sdk/QTSurfer.java b/src/main/java/com/qtsurfer/api/sdk/QTSurfer.java index d2507de..3024a53 100644 --- a/src/main/java/com/qtsurfer/api/sdk/QTSurfer.java +++ b/src/main/java/com/qtsurfer/api/sdk/QTSurfer.java @@ -16,6 +16,7 @@ import com.qtsurfer.api.client.model.Account; import com.qtsurfer.api.client.model.AccountUsage; import com.qtsurfer.api.client.model.Dataset; +import com.qtsurfer.api.client.model.DataSourceType; import com.qtsurfer.api.client.model.DatasetCreated; import com.qtsurfer.api.client.model.DatasetImportCreated; import com.qtsurfer.api.client.model.DatasetImportRequest; @@ -463,6 +464,22 @@ public BacktestOutcome getBacktestResult(String exchangeId, String jobId) { return backtestWorkflow.readResult(exchangeId, jobId); } + /** + * {@link #getBacktestResult(String, String)} for a run of the given data type. A run is addressed + * by its exchange, its type and its job id, so a kline run is not found under the ticker route + * the two-argument form reads. + * + * @param exchangeId exchange the run was submitted against + * @param type {@link DataSourceType#TICKER} or {@link DataSourceType#KLINE}, as the run was submitted + * @param jobId id of the execute job + */ + public BacktestOutcome getBacktestResult(String exchangeId, DataSourceType type, String jobId) { + Objects.requireNonNull(exchangeId, "exchangeId"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(jobId, "jobId"); + return backtestWorkflow.readResult(exchangeId, type, jobId); + } + /** @deprecated Use {@link #getBacktestResult(String, String)}. */ @Deprecated(forRemoval = false) public BacktestOutcome backtestResult(String exchangeId, String jobId) { @@ -546,6 +563,27 @@ public EquityCurveResult getSweepRunEquityCurve( exchangeId, requestId, sweepId, runIx, outMode, resample, differential); } + /** {@link #getSweepRunEquityCurve(String, String, String, int, EquityCurveOutMode, Integer, Boolean)} for a sweep of the given data type. */ + public EquityCurveResult getSweepRunEquityCurve( + String exchangeId, DataSourceType type, String requestId, String sweepId, int runIx, + EquityCurveOutMode outMode, Integer resample, Boolean differential) { + Objects.requireNonNull(exchangeId, "exchangeId"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(sweepId, "sweepId"); + return backtestWorkflow.getSweepRunEquityCurve( + exchangeId, type, requestId, sweepId, runIx, outMode, resample, differential); + } + + /** {@link #getBoundedSweepRunEquityCurve(String, String, String, int, Integer)} for a sweep of the given data type. */ + public BoundedEquityCurve getBoundedSweepRunEquityCurve( + String exchangeId, DataSourceType type, String requestId, String sweepId, int runIx, Integer maxResample) { + int limit = maxResample == null ? BoundedEquityCurve.DEFAULT_MAX_RESAMPLE : maxResample; + BoundedEquityCurve.validateMaxResample(limit); + return BoundedEquityCurve.decode(getSweepRunEquityCurve( + exchangeId, type, requestId, sweepId, runIx, EquityCurveOutMode.SHORT, limit, true), limit); + } + /** Read a retained sweep curve as normalized absolute points with a bounded server request. */ public BoundedEquityCurve getBoundedSweepRunEquityCurve( String exchangeId, String requestId, String sweepId, int runIx, Integer maxResample) { diff --git a/src/main/java/com/qtsurfer/api/sdk/SweepRequest.java b/src/main/java/com/qtsurfer/api/sdk/SweepRequest.java index 2430988..93a3f48 100644 --- a/src/main/java/com/qtsurfer/api/sdk/SweepRequest.java +++ b/src/main/java/com/qtsurfer/api/sdk/SweepRequest.java @@ -1,6 +1,7 @@ package com.qtsurfer.api.sdk; import com.qtsurfer.api.client.model.ExecuteSweepAccepted; +import com.qtsurfer.api.client.model.DataSourceType; import com.qtsurfer.api.client.model.EquityCurveRequest; import java.util.LinkedHashMap; @@ -67,6 +68,8 @@ * {@code null} keeps the platform defaults * @param storeSignals when {@code Boolean.TRUE}, retain emitted signals for every trial; * {@code null} keeps the platform default + * @param type the kind of data the strategy reads, {@link DataSourceType#TICKER} (trades) or + * {@link DataSourceType#KLINE} (candles); {@code null} means {@code TICKER} */ public record SweepRequest( String strategy, @@ -83,14 +86,23 @@ public record SweepRequest( String datasetId, String datasetVersionId, EquityCurveRequest equityCurve, - Boolean storeSignals + Boolean storeSignals, + DataSourceType type ) { + /** Compatibility constructor for callers that predate {@code type}: a ticker sweep. */ + public SweepRequest(String strategy, String exchangeId, String instrument, String from, String to, + Map params, SweepSampler sampler, Integer samples, Long seed, + SweepObjective objective, WalkForwardSpec walkForward, String datasetId, + String datasetVersionId, EquityCurveRequest equityCurve, Boolean storeSignals) { + this(strategy, exchangeId, instrument, from, to, params, sampler, samples, seed, objective, + walkForward, datasetId, datasetVersionId, equityCurve, storeSignals, null); + } public SweepRequest(String strategy, String exchangeId, String instrument, String from, String to, Map params, SweepSampler sampler, Integer samples, Long seed, SweepObjective objective, WalkForwardSpec walkForward, String datasetId, String datasetVersionId) { this(strategy, exchangeId, instrument, from, to, params, sampler, samples, seed, objective, - walkForward, datasetId, datasetVersionId, null, null); + walkForward, datasetId, datasetVersionId, null, null, null); } /** * @throws NullPointerException when a required field is missing, or when neither @@ -118,6 +130,7 @@ public SweepRequest(String strategy, String exchangeId, String instrument, Strin throw new IllegalArgumentException("params must hold at least one axis"); } params = Map.copyOf(params); + type = type == null ? DataSourceType.TICKER : type; } /** @@ -144,6 +157,7 @@ public static final class Builder { private String datasetVersionId; private EquityCurveRequest equityCurve; private Boolean storeSignals; + private DataSourceType type; /** * @param strategy strategy source code (Java) @@ -268,6 +282,9 @@ public Builder params(Map params) { /** Request storage of emitted signals for every sweep trial. */ public Builder storeSignals(boolean storeSignals) { this.storeSignals = storeSignals; return this; } + /** The kind of data the strategy reads: {@code TICKER} (the default) or {@code KLINE}. */ + public Builder type(DataSourceType type) { this.type = type; return this; } + /** * Build the request. * @@ -277,7 +294,7 @@ public SweepRequest build() { return new SweepRequest( strategy, exchangeId, instrument, from, to, params, sampler, samples, seed, objective, walkForward, - datasetId, datasetVersionId, equityCurve, storeSignals); + datasetId, datasetVersionId, equityCurve, storeSignals, type); } } } diff --git a/src/main/java/com/qtsurfer/api/sdk/auth/AuthenticatedClient.java b/src/main/java/com/qtsurfer/api/sdk/auth/AuthenticatedClient.java index 188d248..abd2c25 100644 --- a/src/main/java/com/qtsurfer/api/sdk/auth/AuthenticatedClient.java +++ b/src/main/java/com/qtsurfer/api/sdk/auth/AuthenticatedClient.java @@ -18,6 +18,7 @@ import com.qtsurfer.api.client.model.AuthTokenResponse; import com.qtsurfer.api.client.model.CreateDatasetRequest; import com.qtsurfer.api.client.model.Dataset; +import com.qtsurfer.api.client.model.DataSourceType; import com.qtsurfer.api.client.model.DatasetCreated; import com.qtsurfer.api.client.model.DatasetImportCreated; import com.qtsurfer.api.client.model.DatasetImportRequest; @@ -640,6 +641,22 @@ public BacktestOutcome getBacktestResult(String exchangeId, String jobId) { return withRefreshOn401(() -> backtestWorkflow.readResult(exchangeId, jobId)); } + /** + * {@link #getBacktestResult(String, String)} for a run of the given data type. A run is addressed + * by its exchange, its type and its job id, so a kline run is not found under the ticker route + * the two-argument form reads. + * + * @param exchangeId exchange the run was submitted against + * @param type {@link DataSourceType#TICKER} or {@link DataSourceType#KLINE}, as the run was submitted + * @param jobId id of the execute job + */ + public BacktestOutcome getBacktestResult(String exchangeId, DataSourceType type, String jobId) { + Objects.requireNonNull(exchangeId, "exchangeId"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(jobId, "jobId"); + return withRefreshOn401(() -> backtestWorkflow.readResult(exchangeId, type, jobId)); + } + /** @deprecated Use {@link #getBacktestResult(String, String)}. */ @Deprecated(forRemoval = false) public BacktestOutcome backtestResult(String exchangeId, String jobId) { @@ -716,6 +733,27 @@ public EquityCurveResult getSweepRunEquityCurve( exchangeId, requestId, sweepId, runIx, outMode, resample, differential)); } + /** {@link #getSweepRunEquityCurve(String, String, String, int, EquityCurveOutMode, Integer, Boolean)} for a sweep of the given data type. */ + public EquityCurveResult getSweepRunEquityCurve( + String exchangeId, DataSourceType type, String requestId, String sweepId, int runIx, + EquityCurveOutMode outMode, Integer resample, Boolean differential) { + Objects.requireNonNull(exchangeId, "exchangeId"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(sweepId, "sweepId"); + return withRefreshOn401(() -> backtestWorkflow.getSweepRunEquityCurve( + exchangeId, type, requestId, sweepId, runIx, outMode, resample, differential)); + } + + /** {@link #getBoundedSweepRunEquityCurve(String, String, String, int, Integer)} for a sweep of the given data type. */ + public BoundedEquityCurve getBoundedSweepRunEquityCurve( + String exchangeId, DataSourceType type, String requestId, String sweepId, int runIx, Integer maxResample) { + int limit = maxResample == null ? BoundedEquityCurve.DEFAULT_MAX_RESAMPLE : maxResample; + BoundedEquityCurve.validateMaxResample(limit); + return BoundedEquityCurve.decode(getSweepRunEquityCurve( + exchangeId, type, requestId, sweepId, runIx, EquityCurveOutMode.SHORT, limit, true), limit); + } + /** Read a retained sweep curve as normalized absolute points with a bounded server request. */ public BoundedEquityCurve getBoundedSweepRunEquityCurve( String exchangeId, String requestId, String sweepId, int runIx, Integer maxResample) { diff --git a/src/main/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflow.java b/src/main/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflow.java index 0a0f990..37f1851 100644 --- a/src/main/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflow.java +++ b/src/main/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflow.java @@ -95,7 +95,7 @@ public CompletableFuture submitExecution( emit(safeOpts.onProgress(), new BacktestProgress(BacktestStage.EXECUTING, null)); AcceptedJob accepted = call( - () -> backtestingApi.executeBacktest(req.exchangeId(), TICKER, buildExecuteBody(req, strategy, prepareJobId)), + () -> backtestingApi.executeBacktest(req.exchangeId(), req.type(), buildExecuteBody(req, strategy, prepareJobId)), "Execute submission failed", QTSExecutionError::new); if (accepted == null || accepted.getJobId() == null) { @@ -136,16 +136,32 @@ public CompletableFuture runFull(BacktestRequest req, BacktestOptions * about an execution any more */ public BacktestOutcome readResult(String exchangeId, String jobId) { - return BacktestOutcomes.of(readJobResult(exchangeId, jobId, QTSError::new)); + return readResult(exchangeId, TICKER, jobId); + } + + /** + * {@link #readResult(String, String)} for a run of the given data type: a run is addressed by + * its exchange, its type and its job id, and a kline run is not found under the ticker route. + */ + public BacktestOutcome readResult(String exchangeId, DataSourceType type, String jobId) { + return BacktestOutcomes.of(readJobResult(exchangeId, type, jobId, QTSError::new)); } /** Read a retained sweep trial curve without starting or polling a sweep. */ public EquityCurveResult getSweepRunEquityCurve( String exchangeId, String requestId, String sweepId, int runIx, EquityCurveOutMode outMode, Integer resample, Boolean differential) { + return getSweepRunEquityCurve( + exchangeId, TICKER, requestId, sweepId, runIx, outMode, resample, differential); + } + + /** {@link #getSweepRunEquityCurve(String, String, String, int, EquityCurveOutMode, Integer, Boolean)} for a sweep of the given data type. */ + public EquityCurveResult getSweepRunEquityCurve( + String exchangeId, DataSourceType type, String requestId, String sweepId, int runIx, + EquityCurveOutMode outMode, Integer resample, Boolean differential) { return call( () -> backtestingApi.getSweepRunEquityCurve( - exchangeId, TICKER, requestId, sweepId, runIx, + exchangeId, type, requestId, sweepId, runIx, outMode, resample, differential), "Sweep equity curve request failed", QTSError::new); @@ -165,10 +181,11 @@ public EquityCurveResult getSweepRunEquityCurve( */ private BacktestJobResult readJobResult( String exchangeId, + DataSourceType type, String jobId, java.util.function.BiFunction errorCtor) { return call( - () -> backtestingApi.getBacktestResult(exchangeId, TICKER, jobId), + () -> backtestingApi.getBacktestResult(exchangeId, type, jobId), "Execution result request failed", errorCtor); } @@ -229,7 +246,7 @@ private Backtest buildJob( Runnable cancelHook = () -> { resultFuture.cancel(true); try { - backtestingApi.cancelBacktest(req.exchangeId(), TICKER, executeJobId); + backtestingApi.cancelBacktest(req.exchangeId(), req.type(), executeJobId); } catch (Exception ignore) { // Best effort } @@ -273,7 +290,7 @@ private ResultMap pollExecution( BacktestStage.EXECUTING, opts, percent -> progressSink.accept(new BacktestProgress(BacktestStage.EXECUTING, percent)), - () -> readJobResult(req.exchangeId(), executeJobId, QTSExecutionError::new), + () -> readJobResult(req.exchangeId(), req.type(), executeJobId, QTSExecutionError::new), r -> StatusNormalizer.normalize(statusOf(r)) == Normalized.IN_PROGRESS); Normalized norm = StatusNormalizer.normalize(statusOf(finalResult)); @@ -322,7 +339,7 @@ private String prepareData(BacktestRequest req, BacktestOptions opts) { body.datasetVersionId(req.datasetVersionId()); } return Preparation.prepare( - backtestingApi, req.exchangeId(), TICKER, body, + backtestingApi, req.exchangeId(), req.type(), body, opts.pollInterval(), opts.maxPollInterval(), opts.timeout(), percent -> emit(opts.onProgress(), new BacktestProgress(BacktestStage.PREPARING, percent)), // Surface the backend's coverage ratio for the prepared window (spec 0.98.0) on the diff --git a/src/main/java/com/qtsurfer/api/sdk/workflows/SweepWorkflow.java b/src/main/java/com/qtsurfer/api/sdk/workflows/SweepWorkflow.java index da68b59..6529a9a 100644 --- a/src/main/java/com/qtsurfer/api/sdk/workflows/SweepWorkflow.java +++ b/src/main/java/com/qtsurfer/api/sdk/workflows/SweepWorkflow.java @@ -58,7 +58,6 @@ public final class SweepWorkflow { private static final Logger log = LoggerFactory.getLogger(Sweep.class); - private static final DataSourceType TICKER = DataSourceType.TICKER; private final StrategyCompileClient strategyClient; private final BacktestingApi backtestingApi; @@ -102,7 +101,7 @@ public CompletableFuture submit(SweepRequest req, SweepOptions opts) { emit(safeOpts.onProgress(), new SweepProgressEvent(BacktestStage.EXECUTING, null)); ExecuteSweepAccepted accepted = ApiCalls.call( () -> backtestingApi.executeSweep( - req.exchangeId(), TICKER, requestId, buildSweepBody(req, strategyId)), + req.exchangeId(), req.type(), requestId, buildSweepBody(req, strategyId)), "Sweep submission failed", QTSExecutionError::new); if (accepted == null || accepted.getSweepId() == null) { @@ -128,7 +127,7 @@ private String prepareData(SweepRequest req, SweepOptions opts) { body.datasetVersionId(req.datasetVersionId()); } return Preparation.prepare( - backtestingApi, req.exchangeId(), TICKER, body, + backtestingApi, req.exchangeId(), req.type(), body, opts.pollInterval(), opts.maxPollInterval(), opts.timeout(), percent -> emit(opts.onProgress(), new SweepProgressEvent(BacktestStage.PREPARING, percent)), // A thinly covered window is about to be scored once per parameter vector, so the @@ -187,7 +186,7 @@ private Sweep buildSweep( // polling until the platform reports CANCELLED with no shards still in flight. Runnable cancelHook = () -> { try { - backtestingApi.cancelSweep(req.exchangeId(), TICKER, requestId, sweepId); + backtestingApi.cancelSweep(req.exchangeId(), req.type(), requestId, sweepId); } catch (Exception ignore) { // Best effort } @@ -218,8 +217,8 @@ private Sweep buildSweep( return new Sweep( accepted, requestId, strategyId, resultFuture, publisher, state, cancelHook, (order, ranking) -> readResults( - req.exchangeId(), requestId, sweepId, order, ranking, QTSError::new), - objective -> readSensitivity(req.exchangeId(), requestId, sweepId, objective)); + req.exchangeId(), req.type(), requestId, sweepId, order, ranking, QTSError::new), + objective -> readSensitivity(req.exchangeId(), req.type(), requestId, sweepId, objective)); } private ExecuteSweepResult pollSweep( @@ -232,7 +231,7 @@ private ExecuteSweepResult pollSweep( ExecuteSweepResult finalResult = Polling.poll( BacktestStage.EXECUTING.toString(), opts.pollInterval(), opts.maxPollInterval(), opts.timeout(), - () -> readResults(req.exchangeId(), requestId, sweepId, + () -> readResults(req.exchangeId(), req.type(), requestId, sweepId, opts.order(), opts.ranking(), QTSExecutionError::new), SweepWorkflow::stillRunning, r -> progressSink.accept(new SweepProgressEvent( @@ -261,12 +260,12 @@ private ExecuteSweepResult pollSweep( * {@link #readSensitivity} has always used for the sibling read. */ private ExecuteSweepResult readResults( - String exchangeId, String requestId, String sweepId, + String exchangeId, DataSourceType type, String requestId, String sweepId, SweepOrder order, SweepRanking ranking, java.util.function.BiFunction errorCtor) { return ApiCalls.call( () -> backtestingApi.getSweepResult( - exchangeId, TICKER, requestId, sweepId, null, + exchangeId, type, requestId, sweepId, null, order != null ? order.wire() : null, ranking != null ? ranking.wire() : null), "Sweep result request failed", @@ -274,10 +273,10 @@ private ExecuteSweepResult readResults( } private SweepSensitivity readSensitivity( - String exchangeId, String requestId, String sweepId, SweepObjective objective) { + String exchangeId, DataSourceType type, String requestId, String sweepId, SweepObjective objective) { return ApiCalls.call( () -> backtestingApi.getSweepSensitivity( - exchangeId, TICKER, requestId, sweepId, + exchangeId, type, requestId, sweepId, objective != null ? objective.wire() : null), "Sweep sensitivity request failed", QTSError::new); diff --git a/src/test/java/com/qtsurfer/api/sdk/BacktestResultTest.java b/src/test/java/com/qtsurfer/api/sdk/BacktestResultTest.java index b49ab7b..3f59681 100644 --- a/src/test/java/com/qtsurfer/api/sdk/BacktestResultTest.java +++ b/src/test/java/com/qtsurfer/api/sdk/BacktestResultTest.java @@ -85,6 +85,19 @@ void backtestResultGetsTheExecuteJobResource() { assertEquals(7L, result.getTotalTrades()); } + @Test + void getBacktestResultOfAKlineRunReadsTheKlineRoute() { + responseStatus.set(200); + responseBody.set(""" + {"state":{"status":"Completed"},"results":{"instrument":"BTC/USDT","totalTrades":20}}"""); + + BacktestOutcome outcome = qts.getBacktestResult( + "user", com.qtsurfer.api.client.model.DataSourceType.KLINE, "exec-k"); + + assertEquals("/backtest/user/kline/execute/exec-k", exchanges.get(0).getRequestURI().getPath()); + assertEquals(20L, assertInstanceOf(BacktestOutcome.Completed.class, outcome).results().getTotalTrades()); + } + /** * A run started with per-run {@code params} comes back with them echoed. A number or a boolean * among them used to make the whole result unreadable ("N classes match result, expected 1"). diff --git a/src/test/java/com/qtsurfer/api/sdk/DataSourceTypeRequestTest.java b/src/test/java/com/qtsurfer/api/sdk/DataSourceTypeRequestTest.java new file mode 100644 index 0000000..3cd43fb --- /dev/null +++ b/src/test/java/com/qtsurfer/api/sdk/DataSourceTypeRequestTest.java @@ -0,0 +1,61 @@ +package com.qtsurfer.api.sdk; + +import com.qtsurfer.api.client.model.DataSourceType; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** The data type a run reads: ticker unless a request says otherwise. */ +class DataSourceTypeRequestTest { + + private static BacktestRequest.Builder backtest() { + return BacktestRequest.builder().strategy("class S {}").exchangeId("binance") + .instrument("BTC/USDT").from("2026-01-01").to("2026-01-02"); + } + + private static SweepRequest.Builder sweep() { + return SweepRequest.builder().strategy("class S {}").exchangeId("binance") + .instrument("BTC/USDT").from("2026-01-01").to("2026-01-02") + .param("rsiPeriod", ParamAxis.range(7, 28, 1)); + } + + @Test + void aBacktestWithoutATypeIsATickerRun() { + assertEquals(DataSourceType.TICKER, backtest().build().type()); + } + + @Test + void aBacktestKeepsTheTypeItIsGiven() { + assertEquals(DataSourceType.KLINE, backtest().type(DataSourceType.KLINE).build().type()); + } + + @Test + void aSweepWithoutATypeIsATickerSweep() { + assertEquals(DataSourceType.TICKER, sweep().build().type()); + } + + @Test + void aSweepKeepsTheTypeItIsGiven() { + assertEquals(DataSourceType.KLINE, sweep().type(DataSourceType.KLINE).build().type()); + } + + @Test + void theConstructorsThatPredateTheTypeStayTickerRuns() { + BacktestRequest viaEleven = new BacktestRequest("class S {}", "binance", "BTC/USDT", "2026-01-01", "2026-01-02", + null, null, null, null, null, Map.of()); + assertEquals(DataSourceType.TICKER, viaEleven.type()); + + SweepRequest viaFifteen = new SweepRequest("class S {}", "binance", "BTC/USDT", "2026-01-01", "2026-01-02", + Map.of("rsiPeriod", ParamAxis.range(7, 28, 1)), null, null, null, null, null, null, null, null, null); + assertEquals(DataSourceType.TICKER, viaFifteen.type()); + } + + @Test + void aNullTypeInTheCanonicalConstructorMeansTicker() { + BacktestRequest request = new BacktestRequest("class S {}", "binance", "BTC/USDT", "2026-01-01", "2026-01-02", + null, null, null, null, null, Map.of(), null); + assertEquals(DataSourceType.TICKER, request.type()); + } +} diff --git a/src/test/java/com/qtsurfer/api/sdk/SweepTest.java b/src/test/java/com/qtsurfer/api/sdk/SweepTest.java index 641cb4a..468ded9 100644 --- a/src/test/java/com/qtsurfer/api/sdk/SweepTest.java +++ b/src/test/java/com/qtsurfer/api/sdk/SweepTest.java @@ -212,6 +212,26 @@ void sendsTheGridAsTheApiSpellsIt() throws Exception { assertFalse(values.get("values").get(1).asBoolean()); } + /** A kline sweep is prepared, submitted and read on the kline route, never on the ticker one. */ + @Test + void aKlineSweepUsesTheKlineRouteEverywhere() throws Exception { + sweepResults.add(completed()); + + qts.sweep(request().type(com.qtsurfer.api.client.model.DataSourceType.KLINE).build(), fastOpts().build()) + .get(10, TimeUnit.SECONDS) + .await().get(10, TimeUnit.SECONDS); + + assertEquals("/backtest/binance/kline/prepare", call("POST", "/prepare").path()); + assertEquals("/backtest/binance/kline/executeSweep/prep-1", call("POST", "/executeSweep/prep-1").path()); + synchronized (recorded) { + for (Recorded r : recorded) { + if (r.path().startsWith("/backtest/")) { + assertTrue(r.path().startsWith("/backtest/binance/kline/"), "off the kline route: " + r.path()); + } + } + } + } + /** Preparation runs first, and the sweep is addressed by the dataset it produced. */ @Test void preparesTheDatasetBeforeSubmitting() throws Exception { diff --git a/src/test/java/com/qtsurfer/api/sdk/auth/AuthenticatedClientTest.java b/src/test/java/com/qtsurfer/api/sdk/auth/AuthenticatedClientTest.java index a724311..6cded18 100644 --- a/src/test/java/com/qtsurfer/api/sdk/auth/AuthenticatedClientTest.java +++ b/src/test/java/com/qtsurfer/api/sdk/auth/AuthenticatedClientTest.java @@ -532,6 +532,20 @@ void backtestResultParticipatesInRefreshOn401() { assertEquals("Bearer jwt-2", retried.authorization()); } + @Test + void backtestResultOfAKlineRunReadsTheKlineRoute() { + tokenResponses.add(jwt("jwt-1", "free")); + resultStatuses.add(200); + + AuthenticatedClient session = QTSurfer.authenticate("ak", opts()); + BacktestOutcome outcome = session.getBacktestResult( + "user", com.qtsurfer.api.client.model.DataSourceType.KLINE, "exec-k"); + + assertInstanceOf(BacktestOutcome.Completed.class, outcome); + RequestRecord read = requests.stream().filter(r -> r.path().contains("/execute/")).findFirst().orElseThrow(); + assertEquals("/v1/backtest/user/kline/execute/exec-k", read.path()); + } + /** The session the MCP server uses must read a result whose echoed params hold a number or a boolean. */ @Test void backtestResultReadsNumericAndBooleanParamsEchoedBack() { diff --git a/src/test/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflowTest.java b/src/test/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflowTest.java index 27afbeb..c4af127 100644 --- a/src/test/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflowTest.java +++ b/src/test/java/com/qtsurfer/api/sdk/workflows/BacktestWorkflowTest.java @@ -44,6 +44,7 @@ import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -115,6 +116,47 @@ void runsHappyPathAndReturnsResultMap() throws Exception { assertEquals("strategy-abc", execBody.getValue().getStrategyId()); } + /** A kline run is prepared, executed, polled and read on the kline route, and never on the ticker one. */ + @Test + void aKlineRequestPreparesExecutesAndReadsOnTheKlineRoute() throws Exception { + when(strategyClient.compile("class S {}")).thenReturn("strategy-abc"); + when(backtestingApi.prepareBacktest(eq("user"), eq(DataSourceType.KLINE), any(PrepareRequest.class))) + .thenReturn(new AcceptedJob().jobId("prep-1")); + when(backtestingApi.getPrepareStatus("user", DataSourceType.KLINE, "prep-1")) + .thenReturn(new PrepareJobState().status(PrepareJobState.StatusEnum.COMPLETED)); + when(backtestingApi.executeBacktest(eq("user"), eq(DataSourceType.KLINE), any(ExecuteBacktestRequest.class))) + .thenReturn(new AcceptedJob().jobId("exec-1")); + when(backtestingApi.getBacktestResult("user", DataSourceType.KLINE, "exec-1")) + .thenReturn(new BacktestJobResult().state(new JobState().status(JobState.StatusEnum.COMPLETED)) + .results(new ResultMap().strategyId("strategy-abc"))); + + BacktestRequest request = BacktestRequest.builder() + .strategy("class S {}").exchangeId("user").datasetId("ds_1") + .from("2026-08-01T00:00:00Z").to("2026-08-01T03:00:00Z") + .type(DataSourceType.KLINE).build(); + ResultMap result = workflow.runFull(request, fastOpts()).get(10, TimeUnit.SECONDS); + + assertEquals("strategy-abc", result.getStrategyId()); + verify(backtestingApi, never()).prepareBacktest(anyString(), eq(DataSourceType.TICKER), any(PrepareRequest.class)); + verify(backtestingApi, never()).executeBacktest(anyString(), eq(DataSourceType.TICKER), any(ExecuteBacktestRequest.class)); + verify(backtestingApi, never()).getBacktestResult(anyString(), eq(DataSourceType.TICKER), anyString()); + } + + /** A run is addressed by its exchange, its type and its job id. */ + @Test + void readResultAddressesARunByItsType() throws Exception { + BacktestJobResult done = new BacktestJobResult() + .state(new JobState().status(JobState.StatusEnum.COMPLETED)).results(new ResultMap()); + when(backtestingApi.getBacktestResult("user", DataSourceType.KLINE, "exec-k")).thenReturn(done); + when(backtestingApi.getBacktestResult("binance", DataSourceType.TICKER, "exec-t")).thenReturn(done); + + assertInstanceOf(com.qtsurfer.api.sdk.BacktestOutcome.Completed.class, + workflow.readResult("user", DataSourceType.KLINE, "exec-k")); + // The form without a type is a ticker read. + assertInstanceOf(com.qtsurfer.api.sdk.BacktestOutcome.Completed.class, + workflow.readResult("binance", "exec-t")); + } + @Test void sendsScalarParamsWithTheExecuteRequest() throws Exception { when(strategyClient.compile("class S {}")).thenReturn("strategy-abc");