@qtsurfer/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +160 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +17 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +20 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +39 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/workflows/backtest.d.ts +36 -0
- package/dist/workflows/backtest.d.ts.map +1 -0
- package/dist/workflows/backtest.js +168 -0
- package/dist/workflows/backtest.js.map +1 -0
- package/package.json +56 -0
- package/src/client.ts +34 -0
- package/src/errors.ts +41 -0
- package/src/index.ts +16 -0
- package/src/workflows/backtest.ts +276 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing the Work or
|
|
166
|
+
Derivative Works thereof, You may choose to offer, and charge a
|
|
167
|
+
fee for, acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 QTSurfer
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
200
|
+
implied. See the License for the specific language governing
|
|
201
|
+
permissions and limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# @qtsurfer/sdk
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://github.com/QTSurfer/sdk-ts/actions/workflows/ci.yml"><img src="https://github.com/QTSurfer/sdk-ts/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
5
|
+
<a href="https://www.npmjs.com/package/@qtsurfer/sdk"><img src="https://img.shields.io/npm/v/@qtsurfer/sdk" alt="npm"></a>
|
|
6
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License"></a>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
Opinionated TypeScript SDK for [QTSurfer](https://qtsurfer.com), built on top of [`@qtsurfer/api-client`](https://github.com/QTSurfer/api-client-ts).
|
|
10
|
+
|
|
11
|
+
Where `@qtsurfer/api-client` gives you one typed function per API endpoint, `@qtsurfer/sdk` adds **workflow orchestration**, **normalized errors**, and **cancellation** — run a backtest with a single `await`.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @qtsurfer/sdk
|
|
17
|
+
# or
|
|
18
|
+
pnpm add @qtsurfer/sdk
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { QTSurfer } from '@qtsurfer/sdk';
|
|
25
|
+
import { readFileSync } from 'node:fs';
|
|
26
|
+
|
|
27
|
+
const qts = new QTSurfer({
|
|
28
|
+
baseUrl: 'https://api.qtsurfer.com/v1',
|
|
29
|
+
token: process.env.QTSURFER_TOKEN,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
|
|
34
|
+
const result = await qts.backtest(
|
|
35
|
+
{
|
|
36
|
+
strategy: readFileSync('./MyStrategy.java', 'utf8'),
|
|
37
|
+
exchangeId: 'binance',
|
|
38
|
+
instrument: 'BTCUSDT',
|
|
39
|
+
from: '2024-01-01',
|
|
40
|
+
to: '2024-12-31',
|
|
41
|
+
storeSignals: true,
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
signal: controller.signal,
|
|
45
|
+
onProgress: (p) => console.log(`[${p.stage}] ${p.percent?.toFixed(1) ?? '-'}%`),
|
|
46
|
+
pollIntervalMs: 500,
|
|
47
|
+
maxPollIntervalMs: 5000,
|
|
48
|
+
timeoutMs: 10 * 60 * 1000,
|
|
49
|
+
},
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
console.log('PnL:', result.pnlTotal);
|
|
53
|
+
console.log('Trades:', result.totalTrades);
|
|
54
|
+
console.log('Signals:', result.signalsUrl);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## What `backtest()` does
|
|
58
|
+
|
|
59
|
+
Orchestrates the full four-step workflow that the raw API exposes:
|
|
60
|
+
|
|
61
|
+
1. **Compile** the strategy (`POST /strategy` in async mode) and poll `GET /strategy/{id}` until `Completed`.
|
|
62
|
+
2. **Prepare** the data range (`POST /backtest/{exchange}/ticker/prepare`) and poll until `Completed`.
|
|
63
|
+
3. **Execute** the backtest (`POST /backtest/{exchange}/ticker/execute`) and poll `GET /backtest/.../execute/{jobId}` until `Completed`.
|
|
64
|
+
4. Return the `ResultMap` (`pnlTotal`, `totalTrades`, `sharpeRatio`, `signalsUrl`, …).
|
|
65
|
+
|
|
66
|
+
Polling uses exponential backoff (`intervalMs * 1.5`, capped at `maxIntervalMs`) with per-stage timeout.
|
|
67
|
+
|
|
68
|
+
Progress is emitted on every stage transition and after each poll whose `size > 0`.
|
|
69
|
+
|
|
70
|
+
## Error hierarchy
|
|
71
|
+
|
|
72
|
+
All SDK errors extend `QTSError` so you can catch them generically or match by subclass.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import {
|
|
76
|
+
QTSError,
|
|
77
|
+
QTSStrategyCompileError,
|
|
78
|
+
QTSPreparationError,
|
|
79
|
+
QTSExecutionError,
|
|
80
|
+
QTSTimeoutError,
|
|
81
|
+
QTSCanceledError,
|
|
82
|
+
} from '@qtsurfer/sdk';
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
await qts.backtest(req);
|
|
86
|
+
} catch (e) {
|
|
87
|
+
if (e instanceof QTSStrategyCompileError) {
|
|
88
|
+
console.error('Compile failed:', e.message);
|
|
89
|
+
} else if (e instanceof QTSPreparationError) {
|
|
90
|
+
console.error('Data prep failed:', e.message);
|
|
91
|
+
} else if (e instanceof QTSExecutionError) {
|
|
92
|
+
console.error('Execution failed:', e.message);
|
|
93
|
+
} else if (e instanceof QTSTimeoutError) {
|
|
94
|
+
console.error('Stage timed out');
|
|
95
|
+
} else if (e instanceof QTSCanceledError) {
|
|
96
|
+
console.error('Canceled by signal');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Cancellation
|
|
102
|
+
|
|
103
|
+
Pass an `AbortSignal`. The SDK stops polling immediately and, if execution has already started server-side, best-effort calls `cancelExecution` on the QTSurfer API.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
setTimeout(() => controller.abort(), 60_000);
|
|
108
|
+
await qts.backtest(req, { signal: controller.signal });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Under the hood
|
|
112
|
+
|
|
113
|
+
Polling, retry, backoff, timeout, and cancellation are delegated to [`cockatiel`](https://github.com/connor4312/cockatiel). Each workflow stage composes a `retry` policy (exponential backoff on in-progress statuses) with an optional `timeout` policy. If you need advanced resilience primitives (circuit breakers, bulkheads, fallbacks), import them directly from `cockatiel`.
|
|
114
|
+
|
|
115
|
+
## Roadmap
|
|
116
|
+
|
|
117
|
+
### v0.1 — Core workflow ✅
|
|
118
|
+
|
|
119
|
+
- [x] `QTSurfer` client over `@qtsurfer/api-client`
|
|
120
|
+
- [x] `qts.backtest()` orchestrating compile → prepare → execute
|
|
121
|
+
- [x] Backoff, timeout, and `AbortSignal` cancellation via `cockatiel` policies
|
|
122
|
+
- [x] Error hierarchy: `QTSError`, `QTSStrategyCompileError`, `QTSPreparationError`, `QTSExecutionError`, `QTSTimeoutError`, `QTSCanceledError`
|
|
123
|
+
|
|
124
|
+
### v0.2 — Domain objects
|
|
125
|
+
|
|
126
|
+
- [ ] `Strategy` class with `.backtest()`, `.status()`
|
|
127
|
+
- [ ] `BacktestJob` class with `.wait()`, `.cancel()`, `.stream()`
|
|
128
|
+
- [ ] TTL cache for `exchanges` / `instruments`
|
|
129
|
+
|
|
130
|
+
### v0.3 — Streaming progress
|
|
131
|
+
|
|
132
|
+
- [ ] `job.stream()` returns `AsyncIterator<BacktestProgress>`
|
|
133
|
+
- [ ] Server-side hooks (when the backend exposes SSE/WebSocket)
|
|
134
|
+
|
|
135
|
+
### v0.4 — Ecosystem integration
|
|
136
|
+
|
|
137
|
+
- [ ] Helpers to load `signalsUrl` Parquet into DuckDB / Lastra
|
|
138
|
+
- [ ] Framework adapters (`@qtsurfer/sdk-react`, `@qtsurfer/sdk-svelte`)
|
|
139
|
+
|
|
140
|
+
## Project layout
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
src/
|
|
144
|
+
├── index.ts # public exports
|
|
145
|
+
├── client.ts # QTSurfer class
|
|
146
|
+
├── errors.ts # QTSError hierarchy
|
|
147
|
+
└── workflows/
|
|
148
|
+
└── backtest.ts # compile → prepare → execute (cockatiel policies)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Development
|
|
152
|
+
|
|
153
|
+
| Script | Description |
|
|
154
|
+
| ------ | ----------- |
|
|
155
|
+
| `npm run lint` | Type-check without emitting |
|
|
156
|
+
| `npm run build` | Compile to `dist/` |
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type BacktestOptions, type BacktestRequest, type BacktestResult } from './workflows/backtest';
|
|
2
|
+
export interface QTSurferOptions {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
token?: string;
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
}
|
|
7
|
+
export declare class QTSurfer {
|
|
8
|
+
constructor(options: QTSurferOptions);
|
|
9
|
+
backtest(req: BacktestRequest, opts?: BacktestOptions): Promise<BacktestResult>;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,cAAc,EACpB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,qBAAa,QAAQ;gBACP,OAAO,EAAE,eAAe;IAUpC,QAAQ,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;CAQhF"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { client as apiClient } from '@qtsurfer/api-client';
|
|
2
|
+
import { backtest, } from './workflows/backtest';
|
|
3
|
+
export class QTSurfer {
|
|
4
|
+
constructor(options) {
|
|
5
|
+
apiClient.setConfig({
|
|
6
|
+
baseUrl: options.baseUrl,
|
|
7
|
+
...(options.token
|
|
8
|
+
? { headers: { Authorization: `Bearer ${options.token}` } }
|
|
9
|
+
: {}),
|
|
10
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
backtest(req, opts) {
|
|
14
|
+
return backtest(req, opts);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EACL,QAAQ,GAIT,MAAM,sBAAsB,CAAC;AAQ9B,MAAM,OAAO,QAAQ;IACnB,YAAY,OAAwB;QAClC,SAAS,CAAC,SAAS,CAAC;YAClB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,CAAC,OAAO,CAAC,KAAK;gBACf,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE;gBAC3D,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACnD,CAAC,CAAC;IACL,CAAC;IAED,QAAQ,CAAC,GAAoB,EAAE,IAAsB;QACnD,OAAO,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC7B,CAAC;CAMF"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare class QTSError extends Error {
|
|
2
|
+
readonly cause?: unknown | undefined;
|
|
3
|
+
constructor(message: string, cause?: unknown | undefined);
|
|
4
|
+
}
|
|
5
|
+
export declare class QTSStrategyCompileError extends QTSError {
|
|
6
|
+
constructor(message: string, cause?: unknown);
|
|
7
|
+
}
|
|
8
|
+
export declare class QTSPreparationError extends QTSError {
|
|
9
|
+
constructor(message: string, cause?: unknown);
|
|
10
|
+
}
|
|
11
|
+
export declare class QTSExecutionError extends QTSError {
|
|
12
|
+
constructor(message: string, cause?: unknown);
|
|
13
|
+
}
|
|
14
|
+
export declare class QTSTimeoutError extends QTSError {
|
|
15
|
+
constructor(message: string, cause?: unknown);
|
|
16
|
+
}
|
|
17
|
+
export declare class QTSCanceledError extends QTSError {
|
|
18
|
+
constructor(message: string, cause?: unknown);
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,QAAS,SAAQ,KAAK;IACJ,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO;gBAAzC,OAAO,EAAE,MAAM,EAAW,KAAK,CAAC,EAAE,OAAO,YAAA;CAItD;AAED,qBAAa,uBAAwB,SAAQ,QAAQ;gBACvC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;gBACnC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,iBAAkB,SAAQ,QAAQ;gBACjC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,eAAgB,SAAQ,QAAQ;gBAC/B,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,gBAAiB,SAAQ,QAAQ;gBAChC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export class QTSError extends Error {
|
|
2
|
+
cause;
|
|
3
|
+
constructor(message, cause) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.cause = cause;
|
|
6
|
+
this.name = 'QTSError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export class QTSStrategyCompileError extends QTSError {
|
|
10
|
+
constructor(message, cause) {
|
|
11
|
+
super(message, cause);
|
|
12
|
+
this.name = 'QTSStrategyCompileError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class QTSPreparationError extends QTSError {
|
|
16
|
+
constructor(message, cause) {
|
|
17
|
+
super(message, cause);
|
|
18
|
+
this.name = 'QTSPreparationError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class QTSExecutionError extends QTSError {
|
|
22
|
+
constructor(message, cause) {
|
|
23
|
+
super(message, cause);
|
|
24
|
+
this.name = 'QTSExecutionError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export class QTSTimeoutError extends QTSError {
|
|
28
|
+
constructor(message, cause) {
|
|
29
|
+
super(message, cause);
|
|
30
|
+
this.name = 'QTSTimeoutError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class QTSCanceledError extends QTSError {
|
|
34
|
+
constructor(message, cause) {
|
|
35
|
+
super(message, cause);
|
|
36
|
+
this.name = 'QTSCanceledError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,QAAS,SAAQ,KAAK;IACK;IAAtC,YAAY,OAAe,EAAW,KAAe;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QADqB,UAAK,GAAL,KAAK,CAAU;QAEnD,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED,MAAM,OAAO,uBAAwB,SAAQ,QAAQ;IACnD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,QAAQ;IAC/C,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AAED,MAAM,OAAO,iBAAkB,SAAQ,QAAQ;IAC7C,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF;AAED,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IAC3C,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AAED,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAC5C,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { QTSurfer, type QTSurferOptions } from './client';
|
|
2
|
+
export { QTSError, QTSStrategyCompileError, QTSPreparationError, QTSExecutionError, QTSTimeoutError, QTSCanceledError, } from './errors';
|
|
3
|
+
export type { BacktestRequest, BacktestResult, BacktestProgress, BacktestStage, BacktestOptions, } from './workflows/backtest';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EACL,QAAQ,EACR,uBAAuB,EACvB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,YAAY,EACV,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,eAAe,GAChB,MAAM,sBAAsB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwB,MAAM,UAAU,CAAC;AAC1D,OAAO,EACL,QAAQ,EACR,uBAAuB,EACvB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,GACjB,MAAM,UAAU,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type ResultMap } from '@qtsurfer/api-client';
|
|
2
|
+
export interface BacktestRequest {
|
|
3
|
+
/** Strategy source code (Java) */
|
|
4
|
+
strategy: string;
|
|
5
|
+
/** Exchange id, e.g. `binance` */
|
|
6
|
+
exchangeId: string;
|
|
7
|
+
/** Instrument symbol, e.g. `BTCUSDT` */
|
|
8
|
+
instrument: string;
|
|
9
|
+
/** Date range start (ISO-8601, ISO DATE or BASIC ISO DATE) */
|
|
10
|
+
from: string;
|
|
11
|
+
/** Date range end (same formats as `from`) */
|
|
12
|
+
to: string;
|
|
13
|
+
/** When true, the worker uploads emitted signals to object storage. */
|
|
14
|
+
storeSignals?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export type BacktestResult = ResultMap;
|
|
17
|
+
export type BacktestStage = 'compiling' | 'preparing' | 'executing';
|
|
18
|
+
export interface BacktestProgress {
|
|
19
|
+
stage: BacktestStage;
|
|
20
|
+
/** 0-100 when size is known. Undefined during stage start. */
|
|
21
|
+
percent?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface BacktestOptions {
|
|
24
|
+
/** Abort the workflow. Cancels the current poll and calls `cancelExecution` server-side if execution has started. */
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
/** Called on stage transitions and after each poll with updated progress. */
|
|
27
|
+
onProgress?: (p: BacktestProgress) => void;
|
|
28
|
+
/** Initial interval between polls. Default 500ms, backed off up to `maxPollIntervalMs`. */
|
|
29
|
+
pollIntervalMs?: number;
|
|
30
|
+
/** Upper bound for exponential backoff. Default 5000ms. */
|
|
31
|
+
maxPollIntervalMs?: number;
|
|
32
|
+
/** Per-stage timeout. Default none. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
}
|
|
35
|
+
export declare function backtest(req: BacktestRequest, opts?: BacktestOptions): Promise<BacktestResult>;
|
|
36
|
+
//# sourceMappingURL=backtest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backtest.d.ts","sourceRoot":"","sources":["../../src/workflows/backtest.ts"],"names":[],"mappings":"AAAA,OAAO,EASL,KAAK,SAAS,EACf,MAAM,sBAAsB,CAAC;AAoB9B,MAAM,WAAW,eAAe;IAC9B,kCAAkC;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,wCAAwC;IACxC,UAAU,EAAE,MAAM,CAAC;IACnB,8DAA8D;IAC9D,IAAI,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,EAAE,EAAE,MAAM,CAAC;IACX,uEAAuE;IACvE,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,MAAM,cAAc,GAAG,SAAS,CAAC;AAEvC,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,WAAW,GAAG,WAAW,CAAC;AAEpE,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,aAAa,CAAC;IACrB,8DAA8D;IAC9D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,qHAAqH;IACrH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC3C,2FAA2F;IAC3F,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,2DAA2D;IAC3D,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,uCAAuC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAMD,wBAAsB,QAAQ,CAC5B,GAAG,EAAE,eAAe,EACpB,IAAI,GAAE,eAAoB,GACzB,OAAO,CAAC,cAAc,CAAC,CAczB"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { cancelExecution, executeBacktesting, getExecutionResult, getPreparationStatus, getStrategyStatus, postStrategy, prepareBacktesting, } from '@qtsurfer/api-client';
|
|
2
|
+
import { ExponentialBackoff, TaskCancelledError, TimeoutStrategy, handleWhenResult, retry, timeout, wrap, } from 'cockatiel';
|
|
3
|
+
import { QTSCanceledError, QTSExecutionError, QTSPreparationError, QTSStrategyCompileError, QTSTimeoutError, } from '../errors';
|
|
4
|
+
const TICKER = 'ticker';
|
|
5
|
+
export async function backtest(req, opts = {}) {
|
|
6
|
+
const policy = buildStagePolicy(opts);
|
|
7
|
+
// 1. Compile strategy (async mode)
|
|
8
|
+
opts.onProgress?.({ stage: 'compiling' });
|
|
9
|
+
const strategyId = await compileStrategy(req.strategy, policy, opts);
|
|
10
|
+
// 2. Prepare data
|
|
11
|
+
opts.onProgress?.({ stage: 'preparing' });
|
|
12
|
+
const prepareJobId = await prepareData(req, policy, opts);
|
|
13
|
+
// 3. Execute
|
|
14
|
+
opts.onProgress?.({ stage: 'executing' });
|
|
15
|
+
return executeStrategy(req, prepareJobId, strategyId, policy, opts);
|
|
16
|
+
}
|
|
17
|
+
function buildStagePolicy(opts) {
|
|
18
|
+
const retryPolicy = retry(handleWhenResult((r) => {
|
|
19
|
+
const status = r?.status;
|
|
20
|
+
return status === 'New' || status === 'Started';
|
|
21
|
+
}), {
|
|
22
|
+
maxAttempts: Number.MAX_SAFE_INTEGER,
|
|
23
|
+
backoff: new ExponentialBackoff({
|
|
24
|
+
initialDelay: opts.pollIntervalMs ?? 500,
|
|
25
|
+
maxDelay: opts.maxPollIntervalMs ?? 5000,
|
|
26
|
+
}),
|
|
27
|
+
});
|
|
28
|
+
return opts.timeoutMs
|
|
29
|
+
? wrap(timeout(opts.timeoutMs, TimeoutStrategy.Cooperative), retryPolicy)
|
|
30
|
+
: retryPolicy;
|
|
31
|
+
}
|
|
32
|
+
async function compileStrategy(source, policy, opts) {
|
|
33
|
+
const { data, error } = await postStrategy({
|
|
34
|
+
body: source,
|
|
35
|
+
headers: { 'X-Compile-Async': true },
|
|
36
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
37
|
+
});
|
|
38
|
+
if (error)
|
|
39
|
+
throw new QTSStrategyCompileError('Strategy submission failed', error);
|
|
40
|
+
if (!data)
|
|
41
|
+
throw new QTSStrategyCompileError('Empty response from strategy endpoint');
|
|
42
|
+
// Sync mode returns { strategyId }; async mode returns { jobId }.
|
|
43
|
+
if ('strategyId' in data && data.strategyId) {
|
|
44
|
+
return data.strategyId;
|
|
45
|
+
}
|
|
46
|
+
if (!('jobId' in data) || !data.jobId) {
|
|
47
|
+
throw new QTSStrategyCompileError('Missing jobId/strategyId in compile response');
|
|
48
|
+
}
|
|
49
|
+
const compileJobId = data.jobId;
|
|
50
|
+
const status = await runStage(policy, opts, async ({ signal }) => {
|
|
51
|
+
const res = await getStrategyStatus({ path: { strategyId: compileJobId }, signal });
|
|
52
|
+
if (res.error)
|
|
53
|
+
throw new QTSStrategyCompileError('Compile status request failed', res.error);
|
|
54
|
+
if (!res.data)
|
|
55
|
+
throw new QTSStrategyCompileError('Empty compile status response');
|
|
56
|
+
return res.data;
|
|
57
|
+
});
|
|
58
|
+
if (status.status === 'Failed') {
|
|
59
|
+
throw new QTSStrategyCompileError(status.statusDetail ?? 'Strategy compilation failed');
|
|
60
|
+
}
|
|
61
|
+
if (status.status === 'Aborted') {
|
|
62
|
+
throw new QTSCanceledError('Strategy compilation aborted');
|
|
63
|
+
}
|
|
64
|
+
if (!status.strategyId) {
|
|
65
|
+
throw new QTSStrategyCompileError('Compile completed without a strategyId');
|
|
66
|
+
}
|
|
67
|
+
return status.strategyId;
|
|
68
|
+
}
|
|
69
|
+
async function prepareData(req, policy, opts) {
|
|
70
|
+
const { data, error } = await prepareBacktesting({
|
|
71
|
+
path: { exchangeId: req.exchangeId, type: TICKER },
|
|
72
|
+
body: { instrument: req.instrument, from: req.from, to: req.to },
|
|
73
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
74
|
+
});
|
|
75
|
+
if (error)
|
|
76
|
+
throw new QTSPreparationError('Prepare submission failed', error);
|
|
77
|
+
if (!data?.jobId)
|
|
78
|
+
throw new QTSPreparationError('Missing jobId in prepare response');
|
|
79
|
+
const prepareJobId = data.jobId;
|
|
80
|
+
const state = await runStage(policy, opts, async ({ signal }) => {
|
|
81
|
+
const res = await getPreparationStatus({
|
|
82
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: prepareJobId },
|
|
83
|
+
signal,
|
|
84
|
+
});
|
|
85
|
+
if (res.error)
|
|
86
|
+
throw new QTSPreparationError('Preparation status request failed', res.error);
|
|
87
|
+
if (!res.data)
|
|
88
|
+
throw new QTSPreparationError('Empty preparation status response');
|
|
89
|
+
return res.data;
|
|
90
|
+
}, (r) => {
|
|
91
|
+
if (r.size > 0) {
|
|
92
|
+
opts.onProgress?.({ stage: 'preparing', percent: (r.completed / r.size) * 100 });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
if (state.status === 'Failed') {
|
|
96
|
+
throw new QTSPreparationError(state.statusDetail ?? 'Data preparation failed');
|
|
97
|
+
}
|
|
98
|
+
if (state.status === 'Aborted') {
|
|
99
|
+
throw new QTSCanceledError('Data preparation aborted');
|
|
100
|
+
}
|
|
101
|
+
return prepareJobId;
|
|
102
|
+
}
|
|
103
|
+
async function executeStrategy(req, prepareJobId, strategyId, policy, opts) {
|
|
104
|
+
const { data, error } = await executeBacktesting({
|
|
105
|
+
path: { exchangeId: req.exchangeId, type: TICKER },
|
|
106
|
+
body: {
|
|
107
|
+
prepareJobId,
|
|
108
|
+
strategyId,
|
|
109
|
+
...(req.storeSignals !== undefined ? { storeSignals: req.storeSignals } : {}),
|
|
110
|
+
},
|
|
111
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
112
|
+
});
|
|
113
|
+
if (error)
|
|
114
|
+
throw new QTSExecutionError('Execute submission failed', error);
|
|
115
|
+
if (!data?.jobId)
|
|
116
|
+
throw new QTSExecutionError('Missing jobId in execute response');
|
|
117
|
+
const executeJobId = data.jobId;
|
|
118
|
+
try {
|
|
119
|
+
const finalResult = await runStage(policy, opts, async ({ signal }) => {
|
|
120
|
+
const res = await getExecutionResult({
|
|
121
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: executeJobId },
|
|
122
|
+
signal,
|
|
123
|
+
});
|
|
124
|
+
if (res.error)
|
|
125
|
+
throw new QTSExecutionError('Execution result request failed', res.error);
|
|
126
|
+
if (!res.data)
|
|
127
|
+
throw new QTSExecutionError('Empty execution result response');
|
|
128
|
+
return { ...res.data.state, __result: res.data.results };
|
|
129
|
+
}, (r) => {
|
|
130
|
+
if (r.size > 0) {
|
|
131
|
+
opts.onProgress?.({ stage: 'executing', percent: (r.completed / r.size) * 100 });
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
if (finalResult.status === 'Failed') {
|
|
135
|
+
throw new QTSExecutionError(finalResult.statusDetail ?? 'Execution failed');
|
|
136
|
+
}
|
|
137
|
+
if (finalResult.status === 'Aborted') {
|
|
138
|
+
throw new QTSCanceledError('Execution aborted');
|
|
139
|
+
}
|
|
140
|
+
return finalResult.__result;
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
if (err instanceof QTSCanceledError) {
|
|
144
|
+
await cancelExecution({
|
|
145
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: executeJobId },
|
|
146
|
+
}).catch(() => undefined);
|
|
147
|
+
}
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function runStage(policy, opts, fetchFn, onEachAttempt) {
|
|
152
|
+
try {
|
|
153
|
+
return await policy.execute(async (ctx) => {
|
|
154
|
+
const result = await fetchFn(ctx);
|
|
155
|
+
onEachAttempt?.(result);
|
|
156
|
+
return result;
|
|
157
|
+
}, opts.signal);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
if (err instanceof TaskCancelledError) {
|
|
161
|
+
if (opts.signal?.aborted)
|
|
162
|
+
throw new QTSCanceledError('Workflow aborted', err);
|
|
163
|
+
throw new QTSTimeoutError(`Stage exceeded ${opts.timeoutMs}ms`, err);
|
|
164
|
+
}
|
|
165
|
+
throw err;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=backtest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backtest.js","sourceRoot":"","sources":["../../src/workflows/backtest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,kBAAkB,EAClB,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,GAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,gBAAgB,EAChB,KAAK,EACL,OAAO,EACP,IAAI,GAGL,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,uBAAuB,EACvB,eAAe,GAChB,MAAM,WAAW,CAAC;AAwCnB,MAAM,MAAM,GAAmB,QAAQ,CAAC;AAIxC,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,GAAoB,EACpB,OAAwB,EAAE;IAE1B,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,mCAAmC;IACnC,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1C,MAAM,UAAU,GAAG,MAAM,eAAe,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAErE,kBAAkB;IAClB,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1C,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAE1D,aAAa;IACb,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1C,OAAO,eAAe,CAAC,GAAG,EAAE,YAAY,EAAE,UAAU,EAAE,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version": "0.1.0",
|
|
4
|
+
"description": "Opinionated TypeScript SDK for QTSurfer: workflow orchestration, domain objects, normalized errors",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc",
|
|
22
|
+
"lint": "tsc --noEmit",
|
|
23
|
+
"prepublishOnly": "npm run build"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/QTSurfer/sdk-ts.git"
|
|
28
|
+
},
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/QTSurfer/sdk-ts/issues"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/QTSurfer/sdk-ts#readme",
|
|
33
|
+
"author": "QTSurfer (https://github.com/QTSurfer)",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"keywords": [
|
|
36
|
+
"qtsurfer",
|
|
37
|
+
"sdk",
|
|
38
|
+
"typescript",
|
|
39
|
+
"backtesting",
|
|
40
|
+
"trading",
|
|
41
|
+
"workflow"
|
|
42
|
+
],
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@qtsurfer/api-client": "^0.1.0",
|
|
48
|
+
"cockatiel": "^3.2.1"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"typescript": "^5.8.0"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": ">=20"
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { client as apiClient } from '@qtsurfer/api-client';
|
|
2
|
+
import {
|
|
3
|
+
backtest,
|
|
4
|
+
type BacktestOptions,
|
|
5
|
+
type BacktestRequest,
|
|
6
|
+
type BacktestResult,
|
|
7
|
+
} from './workflows/backtest';
|
|
8
|
+
|
|
9
|
+
export interface QTSurferOptions {
|
|
10
|
+
baseUrl: string;
|
|
11
|
+
token?: string;
|
|
12
|
+
fetch?: typeof fetch;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class QTSurfer {
|
|
16
|
+
constructor(options: QTSurferOptions) {
|
|
17
|
+
apiClient.setConfig({
|
|
18
|
+
baseUrl: options.baseUrl,
|
|
19
|
+
...(options.token
|
|
20
|
+
? { headers: { Authorization: `Bearer ${options.token}` } }
|
|
21
|
+
: {}),
|
|
22
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
backtest(req: BacktestRequest, opts?: BacktestOptions): Promise<BacktestResult> {
|
|
27
|
+
return backtest(req, opts);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Future surface:
|
|
31
|
+
// strategies: { compile, status, list }
|
|
32
|
+
// instruments: { list, get } with TTL cache
|
|
33
|
+
// jobs: { cancel, stream, result }
|
|
34
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export class QTSError extends Error {
|
|
2
|
+
constructor(message: string, readonly cause?: unknown) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = 'QTSError';
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export class QTSStrategyCompileError extends QTSError {
|
|
9
|
+
constructor(message: string, cause?: unknown) {
|
|
10
|
+
super(message, cause);
|
|
11
|
+
this.name = 'QTSStrategyCompileError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class QTSPreparationError extends QTSError {
|
|
16
|
+
constructor(message: string, cause?: unknown) {
|
|
17
|
+
super(message, cause);
|
|
18
|
+
this.name = 'QTSPreparationError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class QTSExecutionError extends QTSError {
|
|
23
|
+
constructor(message: string, cause?: unknown) {
|
|
24
|
+
super(message, cause);
|
|
25
|
+
this.name = 'QTSExecutionError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class QTSTimeoutError extends QTSError {
|
|
30
|
+
constructor(message: string, cause?: unknown) {
|
|
31
|
+
super(message, cause);
|
|
32
|
+
this.name = 'QTSTimeoutError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class QTSCanceledError extends QTSError {
|
|
37
|
+
constructor(message: string, cause?: unknown) {
|
|
38
|
+
super(message, cause);
|
|
39
|
+
this.name = 'QTSCanceledError';
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { QTSurfer, type QTSurferOptions } from './client';
|
|
2
|
+
export {
|
|
3
|
+
QTSError,
|
|
4
|
+
QTSStrategyCompileError,
|
|
5
|
+
QTSPreparationError,
|
|
6
|
+
QTSExecutionError,
|
|
7
|
+
QTSTimeoutError,
|
|
8
|
+
QTSCanceledError,
|
|
9
|
+
} from './errors';
|
|
10
|
+
export type {
|
|
11
|
+
BacktestRequest,
|
|
12
|
+
BacktestResult,
|
|
13
|
+
BacktestProgress,
|
|
14
|
+
BacktestStage,
|
|
15
|
+
BacktestOptions,
|
|
16
|
+
} from './workflows/backtest';
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cancelExecution,
|
|
3
|
+
executeBacktesting,
|
|
4
|
+
getExecutionResult,
|
|
5
|
+
getPreparationStatus,
|
|
6
|
+
getStrategyStatus,
|
|
7
|
+
postStrategy,
|
|
8
|
+
prepareBacktesting,
|
|
9
|
+
type DataSourceType,
|
|
10
|
+
type ResultMap,
|
|
11
|
+
} from '@qtsurfer/api-client';
|
|
12
|
+
import {
|
|
13
|
+
ExponentialBackoff,
|
|
14
|
+
TaskCancelledError,
|
|
15
|
+
TimeoutStrategy,
|
|
16
|
+
handleWhenResult,
|
|
17
|
+
retry,
|
|
18
|
+
timeout,
|
|
19
|
+
wrap,
|
|
20
|
+
type IPolicy,
|
|
21
|
+
type ICancellationContext,
|
|
22
|
+
} from 'cockatiel';
|
|
23
|
+
import {
|
|
24
|
+
QTSCanceledError,
|
|
25
|
+
QTSExecutionError,
|
|
26
|
+
QTSPreparationError,
|
|
27
|
+
QTSStrategyCompileError,
|
|
28
|
+
QTSTimeoutError,
|
|
29
|
+
} from '../errors';
|
|
30
|
+
|
|
31
|
+
export interface BacktestRequest {
|
|
32
|
+
/** Strategy source code (Java) */
|
|
33
|
+
strategy: string;
|
|
34
|
+
/** Exchange id, e.g. `binance` */
|
|
35
|
+
exchangeId: string;
|
|
36
|
+
/** Instrument symbol, e.g. `BTCUSDT` */
|
|
37
|
+
instrument: string;
|
|
38
|
+
/** Date range start (ISO-8601, ISO DATE or BASIC ISO DATE) */
|
|
39
|
+
from: string;
|
|
40
|
+
/** Date range end (same formats as `from`) */
|
|
41
|
+
to: string;
|
|
42
|
+
/** When true, the worker uploads emitted signals to object storage. */
|
|
43
|
+
storeSignals?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type BacktestResult = ResultMap;
|
|
47
|
+
|
|
48
|
+
export type BacktestStage = 'compiling' | 'preparing' | 'executing';
|
|
49
|
+
|
|
50
|
+
export interface BacktestProgress {
|
|
51
|
+
stage: BacktestStage;
|
|
52
|
+
/** 0-100 when size is known. Undefined during stage start. */
|
|
53
|
+
percent?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface BacktestOptions {
|
|
57
|
+
/** Abort the workflow. Cancels the current poll and calls `cancelExecution` server-side if execution has started. */
|
|
58
|
+
signal?: AbortSignal;
|
|
59
|
+
/** Called on stage transitions and after each poll with updated progress. */
|
|
60
|
+
onProgress?: (p: BacktestProgress) => void;
|
|
61
|
+
/** Initial interval between polls. Default 500ms, backed off up to `maxPollIntervalMs`. */
|
|
62
|
+
pollIntervalMs?: number;
|
|
63
|
+
/** Upper bound for exponential backoff. Default 5000ms. */
|
|
64
|
+
maxPollIntervalMs?: number;
|
|
65
|
+
/** Per-stage timeout. Default none. */
|
|
66
|
+
timeoutMs?: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const TICKER: DataSourceType = 'ticker';
|
|
70
|
+
|
|
71
|
+
type JobStatus = 'New' | 'Started' | 'Completed' | 'Aborted' | 'Failed';
|
|
72
|
+
|
|
73
|
+
export async function backtest(
|
|
74
|
+
req: BacktestRequest,
|
|
75
|
+
opts: BacktestOptions = {},
|
|
76
|
+
): Promise<BacktestResult> {
|
|
77
|
+
const policy = buildStagePolicy(opts);
|
|
78
|
+
|
|
79
|
+
// 1. Compile strategy (async mode)
|
|
80
|
+
opts.onProgress?.({ stage: 'compiling' });
|
|
81
|
+
const strategyId = await compileStrategy(req.strategy, policy, opts);
|
|
82
|
+
|
|
83
|
+
// 2. Prepare data
|
|
84
|
+
opts.onProgress?.({ stage: 'preparing' });
|
|
85
|
+
const prepareJobId = await prepareData(req, policy, opts);
|
|
86
|
+
|
|
87
|
+
// 3. Execute
|
|
88
|
+
opts.onProgress?.({ stage: 'executing' });
|
|
89
|
+
return executeStrategy(req, prepareJobId, strategyId, policy, opts);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function buildStagePolicy(opts: BacktestOptions): IPolicy<ICancellationContext, never> {
|
|
93
|
+
const retryPolicy = retry(
|
|
94
|
+
handleWhenResult((r) => {
|
|
95
|
+
const status = (r as { status?: JobStatus } | undefined)?.status;
|
|
96
|
+
return status === 'New' || status === 'Started';
|
|
97
|
+
}),
|
|
98
|
+
{
|
|
99
|
+
maxAttempts: Number.MAX_SAFE_INTEGER,
|
|
100
|
+
backoff: new ExponentialBackoff({
|
|
101
|
+
initialDelay: opts.pollIntervalMs ?? 500,
|
|
102
|
+
maxDelay: opts.maxPollIntervalMs ?? 5000,
|
|
103
|
+
}),
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
return opts.timeoutMs
|
|
108
|
+
? wrap(timeout(opts.timeoutMs, TimeoutStrategy.Cooperative), retryPolicy)
|
|
109
|
+
: retryPolicy;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function compileStrategy(
|
|
113
|
+
source: string,
|
|
114
|
+
policy: IPolicy<ICancellationContext, never>,
|
|
115
|
+
opts: BacktestOptions,
|
|
116
|
+
): Promise<string> {
|
|
117
|
+
const { data, error } = await postStrategy({
|
|
118
|
+
body: source,
|
|
119
|
+
headers: { 'X-Compile-Async': true },
|
|
120
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
121
|
+
});
|
|
122
|
+
if (error) throw new QTSStrategyCompileError('Strategy submission failed', error);
|
|
123
|
+
if (!data) throw new QTSStrategyCompileError('Empty response from strategy endpoint');
|
|
124
|
+
|
|
125
|
+
// Sync mode returns { strategyId }; async mode returns { jobId }.
|
|
126
|
+
if ('strategyId' in data && data.strategyId) {
|
|
127
|
+
return data.strategyId;
|
|
128
|
+
}
|
|
129
|
+
if (!('jobId' in data) || !data.jobId) {
|
|
130
|
+
throw new QTSStrategyCompileError('Missing jobId/strategyId in compile response');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const compileJobId = data.jobId;
|
|
134
|
+
const status = await runStage(
|
|
135
|
+
policy,
|
|
136
|
+
opts,
|
|
137
|
+
async ({ signal }) => {
|
|
138
|
+
const res = await getStrategyStatus({ path: { strategyId: compileJobId }, signal });
|
|
139
|
+
if (res.error) throw new QTSStrategyCompileError('Compile status request failed', res.error);
|
|
140
|
+
if (!res.data) throw new QTSStrategyCompileError('Empty compile status response');
|
|
141
|
+
return res.data;
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
if (status.status === 'Failed') {
|
|
146
|
+
throw new QTSStrategyCompileError(status.statusDetail ?? 'Strategy compilation failed');
|
|
147
|
+
}
|
|
148
|
+
if (status.status === 'Aborted') {
|
|
149
|
+
throw new QTSCanceledError('Strategy compilation aborted');
|
|
150
|
+
}
|
|
151
|
+
if (!status.strategyId) {
|
|
152
|
+
throw new QTSStrategyCompileError('Compile completed without a strategyId');
|
|
153
|
+
}
|
|
154
|
+
return status.strategyId;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function prepareData(
|
|
158
|
+
req: BacktestRequest,
|
|
159
|
+
policy: IPolicy<ICancellationContext, never>,
|
|
160
|
+
opts: BacktestOptions,
|
|
161
|
+
): Promise<string> {
|
|
162
|
+
const { data, error } = await prepareBacktesting({
|
|
163
|
+
path: { exchangeId: req.exchangeId, type: TICKER },
|
|
164
|
+
body: { instrument: req.instrument, from: req.from, to: req.to },
|
|
165
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
166
|
+
});
|
|
167
|
+
if (error) throw new QTSPreparationError('Prepare submission failed', error);
|
|
168
|
+
if (!data?.jobId) throw new QTSPreparationError('Missing jobId in prepare response');
|
|
169
|
+
|
|
170
|
+
const prepareJobId = data.jobId;
|
|
171
|
+
const state = await runStage(
|
|
172
|
+
policy,
|
|
173
|
+
opts,
|
|
174
|
+
async ({ signal }) => {
|
|
175
|
+
const res = await getPreparationStatus({
|
|
176
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: prepareJobId },
|
|
177
|
+
signal,
|
|
178
|
+
});
|
|
179
|
+
if (res.error) throw new QTSPreparationError('Preparation status request failed', res.error);
|
|
180
|
+
if (!res.data) throw new QTSPreparationError('Empty preparation status response');
|
|
181
|
+
return res.data;
|
|
182
|
+
},
|
|
183
|
+
(r) => {
|
|
184
|
+
if (r.size > 0) {
|
|
185
|
+
opts.onProgress?.({ stage: 'preparing', percent: (r.completed / r.size) * 100 });
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
if (state.status === 'Failed') {
|
|
191
|
+
throw new QTSPreparationError(state.statusDetail ?? 'Data preparation failed');
|
|
192
|
+
}
|
|
193
|
+
if (state.status === 'Aborted') {
|
|
194
|
+
throw new QTSCanceledError('Data preparation aborted');
|
|
195
|
+
}
|
|
196
|
+
return prepareJobId;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function executeStrategy(
|
|
200
|
+
req: BacktestRequest,
|
|
201
|
+
prepareJobId: string,
|
|
202
|
+
strategyId: string,
|
|
203
|
+
policy: IPolicy<ICancellationContext, never>,
|
|
204
|
+
opts: BacktestOptions,
|
|
205
|
+
): Promise<BacktestResult> {
|
|
206
|
+
const { data, error } = await executeBacktesting({
|
|
207
|
+
path: { exchangeId: req.exchangeId, type: TICKER },
|
|
208
|
+
body: {
|
|
209
|
+
prepareJobId,
|
|
210
|
+
strategyId,
|
|
211
|
+
...(req.storeSignals !== undefined ? { storeSignals: req.storeSignals } : {}),
|
|
212
|
+
},
|
|
213
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
214
|
+
});
|
|
215
|
+
if (error) throw new QTSExecutionError('Execute submission failed', error);
|
|
216
|
+
if (!data?.jobId) throw new QTSExecutionError('Missing jobId in execute response');
|
|
217
|
+
|
|
218
|
+
const executeJobId = data.jobId;
|
|
219
|
+
|
|
220
|
+
try {
|
|
221
|
+
const finalResult = await runStage(
|
|
222
|
+
policy,
|
|
223
|
+
opts,
|
|
224
|
+
async ({ signal }) => {
|
|
225
|
+
const res = await getExecutionResult({
|
|
226
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: executeJobId },
|
|
227
|
+
signal,
|
|
228
|
+
});
|
|
229
|
+
if (res.error) throw new QTSExecutionError('Execution result request failed', res.error);
|
|
230
|
+
if (!res.data) throw new QTSExecutionError('Empty execution result response');
|
|
231
|
+
return { ...res.data.state, __result: res.data.results };
|
|
232
|
+
},
|
|
233
|
+
(r) => {
|
|
234
|
+
if (r.size > 0) {
|
|
235
|
+
opts.onProgress?.({ stage: 'executing', percent: (r.completed / r.size) * 100 });
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
if (finalResult.status === 'Failed') {
|
|
241
|
+
throw new QTSExecutionError(finalResult.statusDetail ?? 'Execution failed');
|
|
242
|
+
}
|
|
243
|
+
if (finalResult.status === 'Aborted') {
|
|
244
|
+
throw new QTSCanceledError('Execution aborted');
|
|
245
|
+
}
|
|
246
|
+
return finalResult.__result;
|
|
247
|
+
} catch (err) {
|
|
248
|
+
if (err instanceof QTSCanceledError) {
|
|
249
|
+
await cancelExecution({
|
|
250
|
+
path: { exchangeId: req.exchangeId, type: TICKER, jobId: executeJobId },
|
|
251
|
+
}).catch(() => undefined);
|
|
252
|
+
}
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function runStage<T extends { status: JobStatus }>(
|
|
258
|
+
policy: IPolicy<ICancellationContext, never>,
|
|
259
|
+
opts: BacktestOptions,
|
|
260
|
+
fetchFn: (ctx: ICancellationContext) => Promise<T>,
|
|
261
|
+
onEachAttempt?: (r: T) => void,
|
|
262
|
+
): Promise<T> {
|
|
263
|
+
try {
|
|
264
|
+
return await policy.execute(async (ctx) => {
|
|
265
|
+
const result = await fetchFn(ctx);
|
|
266
|
+
onEachAttempt?.(result);
|
|
267
|
+
return result;
|
|
268
|
+
}, opts.signal);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
if (err instanceof TaskCancelledError) {
|
|
271
|
+
if (opts.signal?.aborted) throw new QTSCanceledError('Workflow aborted', err);
|
|
272
|
+
throw new QTSTimeoutError(`Stage exceeded ${opts.timeoutMs}ms`, err);
|
|
273
|
+
}
|
|
274
|
+
throw err;
|
|
275
|
+
}
|
|
276
|
+
}
|