Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@ All notable changes to `com.qtsurfer:mcp-java` are documented here.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed 🐛

- Native binary: register the types it could not deserialize. The API's `segments` and
`liveSegments` are sets, which Jackson fills with a `HashSet` the native image had no
registration for, so `list_exchanges` failed with a bare `HTTP 0`. The `version` a finished
dataset import carries was missing too, so `get_dataset_import` answered "Dataset import not
found". The enums of `Dataset` and `DatasetVersion` and the equity-curve request types were
missing as well.
- `get_dataset_import` reports why a read failed instead of answering "Dataset import not found"
for every error.
- `get_job_status` no longer reports a failed or cancelled run as `COMPLETED`. The status now
reads the failure the run ended with and shows the platform's reason as `Detail`, for runs
submitted by this server and for runs read off the platform by `exchangeId`.
- `submit_backtest` says it prepares ticker data and cannot request a kline run; a strategy that
reads kline data ends `FAILED` with the platform's reason.

## [0.21.0] — 2026-10-23

### Added ✨
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,9 +345,11 @@ docker run -i --rm -e QTSURFER_APIKEY \

Once `get_dataset_upload` returns `READY`, inspect `type` with `get_dataset`, then submit a run with
`datasetId`; omit `exchangeId` and `instrument`, because MCP derives the reserved `exchangeId=user`.
`datasetVersionId` pins a prior ready version. User-data kline backtests require the selected ready
version to have `type=klines`; ticker backtests accept either type. An uploaded version's type is
inferred from its rows when ingest completes. `equityCurve` is accepted by both run tools and is
`datasetVersionId` pins a prior ready version. A run is prepared as ticker data, which accepts a
dataset of either type; this tool cannot yet request a kline run, so a strategy that reads kline
data ends `FAILED` with the platform's reason (the API itself runs kline backtests only over a
version with `type=klines`). An uploaded version's type is inferred from its rows when ingest
completes. `equityCurve` is accepted by both run tools and is
passed through to the API.

### Import market history
Expand Down
25 changes: 17 additions & 8 deletions src/main/java/com/qtsurfer/mcp/model/JobSummary.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,24 @@
/**
* Lightweight view of a backtest job returned by status / list queries.
*
* @param jobId server-assigned execution identifier
* @param instrument CCXT-style instrument (e.g. {@code BTC/USDT})
* @param exchangeId exchange (e.g. {@code binance})
* @param status current lifecycle state
* @param submittedAt ISO-8601 submission timestamp
* @param result execution metrics, non-null only when {@code status} is COMPLETED
* @param jobId server-assigned execution identifier
* @param instrument CCXT-style instrument (e.g. {@code BTC/USDT})
* @param exchangeId exchange (e.g. {@code binance})
* @param status current lifecycle state
* @param submittedAt ISO-8601 submission timestamp
* @param result execution metrics, non-null only when {@code status} is COMPLETED
* @param retryable whether the same request can succeed on retry, when the API says so
* @param statusDetail why the run ended without a result, when it did and the platform said why
*/
public record JobSummary(
String jobId, String instrument, String exchangeId, JobStatus status,
String submittedAt, JobResult result, Boolean retryable) {
String submittedAt, JobResult result, Boolean retryable, String statusDetail) {

/** Preserve the constructor that predates {@code statusDetail}. */
public JobSummary(String jobId, String instrument, String exchangeId, JobStatus status,
String submittedAt, JobResult result, Boolean retryable) {
this(jobId, instrument, exchangeId, status, submittedAt, result, retryable, null);
}

/** Preserve the original completed-job constructor. */
public JobSummary(String jobId, String instrument, String exchangeId, JobStatus status,
Expand All @@ -33,6 +41,7 @@ public String toString() {
+ " exchange=" + exchangeId
+ " status=" + status
+ " submitted=" + submittedAt
+ (retryable == null ? "" : " retryable=" + retryable);
+ (retryable == null ? "" : " retryable=" + retryable)
+ (statusDetail == null ? "" : " detail=" + statusDetail);
}
}
98 changes: 76 additions & 22 deletions src/main/java/com/qtsurfer/mcp/service/SdkBacktestingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import com.qtsurfer.api.sdk.UpdateLiveParamsRequestBuilder;
import com.qtsurfer.api.sdk.ValidationOutcome;
import com.qtsurfer.api.sdk.auth.AuthenticatedClient;
import com.qtsurfer.api.sdk.errors.QTSCanceledError;
import com.qtsurfer.mcp.model.EquityPoint;
import com.qtsurfer.mcp.model.DatasetSummary;
import com.qtsurfer.mcp.model.DatasetUploadResult;
Expand Down Expand Up @@ -80,6 +81,7 @@
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
Expand Down Expand Up @@ -197,19 +199,59 @@ private record SessionJob(
String submittedAt,
CompletableFuture<Void> future,
Backtest backtest,
AtomicReference<ResultMap> resultRef) {
AtomicReference<ResultMap> resultRef,
AtomicReference<Failure> failure) {

JobStatus status() {
if (future.isCompletedExceptionally()) return JobStatus.FAILED;
if (future.isDone()) return JobStatus.COMPLETED;
if (backtest == null) return JobStatus.COMPILING;
return switch (backtest.state()) {
case EXECUTING -> JobStatus.EXECUTING;
case COMPLETED -> JobStatus.COMPLETED;
case FAILED -> JobStatus.FAILED;
case CANCELED -> JobStatus.CANCELED;
};
return resolveStatus(failure.get(), future.isCompletedExceptionally(), future.isDone(),
backtest == null ? null : backtest.state());
}

/** The platform's reason when the run ended badly, otherwise {@code null}. */
String failureDetail() {
Failure f = failure.get();
return f == null ? null : f.detail();
}
}

/** How a submitted run ended when it did not complete, and the reason the platform gave. */
record Failure(JobStatus status, String detail) {}

/**
* The lifecycle state of a submitted run.
*
* <p>The await future is not a reliable signal on its own: the failure is observed and recorded
* as a {@link Failure} so the future itself can complete normally, which made a run whose
* preparation was rejected read as {@link JobStatus#COMPLETED}. A recorded failure therefore
* decides first, then a cancellation the SDK has already marked, and only a future that is done
* with neither is a completed run.
*
* @param failure the failure recorded when the await future ended badly, or {@code null}
* @param exceptional whether the future itself completed exceptionally
* @param done whether the future is done
* @param state the SDK's local snapshot, or {@code null} while the strategy compiles
*/
static JobStatus resolveStatus(
Failure failure, boolean exceptional, boolean done, Backtest.State state) {
if (failure != null) return failure.status();
if (exceptional) return JobStatus.FAILED;
if (state == Backtest.State.CANCELED) return JobStatus.CANCELED;
if (done) return JobStatus.COMPLETED;
if (state == null) return JobStatus.COMPILING;
return switch (state) {
case EXECUTING -> JobStatus.EXECUTING;
case COMPLETED -> JobStatus.COMPLETED;
case FAILED -> JobStatus.FAILED;
case CANCELED -> JobStatus.CANCELED;
};
}

/** Whether an await failure is the run being cancelled rather than failing. */
static boolean isCancellation(Throwable error) {
for (Throwable t = error; t != null; t = t.getCause()) {
if (t instanceof QTSCanceledError || t instanceof CancellationException) return true;
}
return false;
}

/** Session provenance required to address a retained curve through the SDK. */
Expand Down Expand Up @@ -336,13 +378,12 @@ public DatasetImportResult importDataset(DatasetImportRequest request) {

@Override
public Optional<DatasetImportStatus> getDatasetImport(String datasetId, String importId) {
try {
DatasetImportState state = qts.getDatasetImport(datasetId, importId);
return Optional.of(new DatasetImportStatus(datasetId, state.getImportId(), String.valueOf(state.getStatus()),
state.getJobId(), state.getError(), state.getVersion() == null ? null : state.getVersion().getId()));
} catch (RuntimeException e) {
return Optional.empty();
}
// A failed read propagates: the tool reports its cause. Swallowing it here read every error,
// a body the client could not parse included, as an import that does not exist.
DatasetImportState state = qts.getDatasetImport(datasetId, importId);
if (state == null) return Optional.empty();
return Optional.of(new DatasetImportStatus(datasetId, state.getImportId(), String.valueOf(state.getStatus()),
state.getJobId(), state.getError(), state.getVersion() == null ? null : state.getVersion().getId()));
}

private Path guardedUploadFile(String filePath) {
Expand Down Expand Up @@ -481,20 +522,29 @@ public String submitBacktest(BacktestRequest sdkRequest) {
String submittedAt = Instant.now().toString();
String finalJobId = jobId;
AtomicReference<ResultMap> resultRef = new AtomicReference<>();
AtomicReference<Failure> failureRef = new AtomicReference<>();

// Track the await future; capture ResultMap when execution completes
// Track the await future; capture ResultMap when execution completes. A failure is kept, not
// just logged: this future completes normally either way, so the job's status reads it back.
CompletableFuture<Void> future = backtest.await()
.thenAccept(sdkResult -> {
resultRef.set(sdkResult);
log.info("Job {} completed — pnl={} trades={}", finalJobId,
sdkResult.getPnlTotal(), sdkResult.getTotalTrades());
})
.exceptionally(err -> { log.warn("Job {} failed: {}", finalJobId, rootMessage(err)); return null; });
.exceptionally(err -> {
String detail = rootMessage(err);
failureRef.set(new Failure(
isCancellation(err) ? JobStatus.CANCELED : JobStatus.FAILED, detail));
log.warn("Job {} ended without a result: {}", finalJobId, detail);
return null;
});

String source = sdkRequest.datasetId() == null ? sdkRequest.instrument()
: "dataset:" + sdkRequest.datasetId()
+ (sdkRequest.datasetVersionId() == null ? "" : ":" + sdkRequest.datasetVersionId());
jobs.put(jobId, new SessionJob(jobId, source, sdkRequest.exchangeId(), submittedAt, future, backtest, resultRef));
jobs.put(jobId, new SessionJob(
jobId, source, sdkRequest.exchangeId(), submittedAt, future, backtest, resultRef, failureRef));
log.info("Submitted backtest {} ({} {} {} → {})", jobId, sdkRequest.exchangeId(), source,
sdkRequest.from(), sdkRequest.to());
return jobId;
Expand All @@ -510,7 +560,7 @@ public Optional<JobSummary> getJobStatus(String jobId, String exchangeId) {
ResultMap sdkResult = job.resultRef().get();
JobResult result = sdkResult != null ? toJobResult(sdkResult) : null;
return Optional.of(new JobSummary(job.jobId(), job.instrument(), job.exchangeId(),
job.status(), job.submittedAt(), result));
job.status(), job.submittedAt(), result, null, job.failureDetail()));
}

/**
Expand Down Expand Up @@ -560,9 +610,13 @@ private Optional<JobSummary> fromPlatform(String jobId, String exchangeId) {
? results.getInstrument() : "unknown";
String startedAt = state != null && state.getStartTime() != null
? state.getStartTime().toString() : "unknown";
// The platform's reason only means something for a run that ended without a result; a
// completed one can carry an informational detail that would read as an error.
String detail = state != null && (status == JobStatus.FAILED || status == JobStatus.CANCELED)
? state.getStatusDetail() : null;
return Optional.of(
new JobSummary(jobId, instrument, exchangeId, status, startedAt, result,
state == null ? null : state.getRetryable()));
state == null ? null : state.getRetryable(), detail));
}

private static JobResult toJobResult(ResultMap r) {
Expand Down
11 changes: 7 additions & 4 deletions src/main/java/com/qtsurfer/mcp/tool/McpTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,8 @@ private static SyncToolSpecification submitBacktest(BacktestingService service)
.description("Compile a Java strategy and queue a backtesting run on QTSurfer. "
+ "Returns the job ID immediately — poll with get_job_status. "
+ "Provide either exchangeId plus instrument, or datasetId (the server derives exchangeId=user). "
+ "For a user-data kline run, the selected ready dataset version must have type=klines; ticker runs accept either type. "
+ "A run is prepared as ticker data and a dataset of either type is accepted for it; this tool "
+ "cannot request a kline run, so a strategy that reads kline data ends FAILED with the platform's reason. "
+ "Set storeSignals only for selected runs that need emitted signals: it is disabled by default "
+ "and retained signals consume the account's storage quota. "
+ "To try the same strategy at many parameter settings, use submit_sweep instead of "
Expand Down Expand Up @@ -701,7 +702,8 @@ private static SyncToolSpecification getJobStatus(BacktestingService service) {
Tool tool = Tool.builder()
.name("get_job_status")
.description("Get the current status of a backtesting job. "
+ "A failed job may include retryable, indicating whether the same request can succeed on retry. "
+ "A failed job may include retryable, indicating whether the same request can succeed on retry, "
+ "and Detail, the reason the platform gave for ending the run without a result. "
+ "A job submitted by this server in this session is answered from its own state and "
+ "needs nothing but the jobId. Any other job id — from the web app, another session, "
+ "or this server before a restart — is read straight off the platform, which "
Expand Down Expand Up @@ -729,7 +731,7 @@ private static SyncToolSpecification getJobStatus(BacktestingService service) {
return service.getJobStatus(jobId, exchangeId)
.map(j -> {
String body = formatJobStatus(j.jobId(), j.instrument(), j.exchangeId(),
j.status(), j.submittedAt(), j.result(), j.retryable());
j.status(), j.submittedAt(), j.result(), j.retryable(), j.statusDetail());
if (includeCurve && j.result() != null
&& j.result().equityCurve() != null && !j.result().equityCurve().isEmpty()) {
body += "\n\nEquity curve:\n"
Expand Down Expand Up @@ -2064,12 +2066,13 @@ private static WalkForwardSpec parseWalkForward(Object raw) {

private static String formatJobStatus(String jobId, String instrument, String exchangeId,
JobStatus status, String submittedAt, JobResult result,
Boolean retryable) {
Boolean retryable, String statusDetail) {
StringBuilder sb = new StringBuilder();
sb.append("Job ").append(jobId).append(": ").append(status).append('\n');
sb.append("Exchange: ").append(exchangeId).append(" | Instrument: ").append(instrument).append('\n');
sb.append("Submitted: ").append(submittedAt);
if (retryable != null) sb.append("\nRetryable: ").append(retryable);
if (statusDetail != null && !statusDetail.isBlank()) sb.append("\nDetail: ").append(statusDetail);

if (result != null) {
sb.append("\n\n=== Results ===\n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1000,7 +1000,16 @@
{ "name": "com.qtsurfer.api.client.model.DatasetImportCreated$StatusEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.DatasetImportState", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.DatasetImportState$StatusEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.DatasetVersion", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.DatasetVersion$DataFormatEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.DatasetVersion$TimestampUnitEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.Dataset", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.Dataset$StatusEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.Dataset$TimestampUnitEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.Dataset$TypeEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.EquityCurveOptions", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.EquityCurveRequest", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.EquityCurveRequest$ModeEnum", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{ "name": "com.qtsurfer.api.client.model.ListDatasets200Response", "allDeclaredConstructors": true, "allDeclaredMethods": true, "allDeclaredFields": true },
{
"name": "com.qtsurfer.api.client.model.ResponseError",
Expand Down Expand Up @@ -2293,6 +2302,15 @@
{
"name": "java.util.Collection"
},
{
"name": "java.util.HashSet",
"methods": [
{
"name": "<init>",
"parameterTypes": []
}
]
},
{
"name": "java.util.ImmutableCollections$AbstractImmutableCollection"
},
Expand All @@ -2314,6 +2332,15 @@
{
"name": "java.util.ImmutableCollections$MapN"
},
{
"name": "java.util.LinkedHashSet",
"methods": [
{
"name": "<init>",
"parameterTypes": []
}
]
},
{
"name": "java.util.List"
},
Expand Down
Loading
Loading