@tradejs/node 2.0.18 → 2.0.20

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.
@@ -1,137 +0,0 @@
1
- import {
2
- __require
3
- } from "./chunk-UV2HVMKZ.mjs";
4
-
5
- // src/pine.ts
6
- import fs from "fs";
7
- import path from "path";
8
- var getPinePlotSeries = (context, plotName) => {
9
- const name = String(plotName || "").trim();
10
- if (!name) return [];
11
- const data = context?.plots?.[name]?.data;
12
- return Array.isArray(data) ? data : [];
13
- };
14
- var getLatestPineRawPlotValue = (context, plotName) => {
15
- const series = getPinePlotSeries(context, plotName);
16
- if (!series.length) return void 0;
17
- return series[series.length - 1]?.value;
18
- };
19
- var getLatestPineNumberPlotValue = (context, plotName) => toFiniteNumber(getLatestPineRawPlotValue(context, plotName)) ?? null;
20
- var getLatestPineBooleanPlotValue = (context, plotName) => toPineBoolean(getLatestPineRawPlotValue(context, plotName));
21
- var getLatestPineNumberPlotValues = (context, plotNames) => Object.fromEntries(
22
- plotNames.map((plotName) => [
23
- plotName,
24
- getLatestPineNumberPlotValue(context, plotName)
25
- ])
26
- );
27
- var getLatestPineBooleanPlotValues = (context, plotNames) => Object.fromEntries(
28
- plotNames.map((plotName) => [
29
- plotName,
30
- getLatestPineBooleanPlotValue(context, plotName)
31
- ])
32
- );
33
- var toFiniteNumber = (value) => {
34
- if (typeof value !== "number" || !Number.isFinite(value)) {
35
- return void 0;
36
- }
37
- return value;
38
- };
39
- var toPineBoolean = (value) => {
40
- if (typeof value === "boolean") return value;
41
- if (typeof value === "number") return Number.isFinite(value) && value !== 0;
42
- return false;
43
- };
44
- var loadPinets = () => {
45
- const resolvedPath = __require.resolve("pinets");
46
- const cjsPath = resolvedPath.includes("pinets.min.browser") ? resolvedPath.replace(/pinets\.min\.browser(\.es)?\.js$/, "pinets.min.cjs") : resolvedPath;
47
- return __require(cjsPath);
48
- };
49
- var loadPineScriptFile = (filePath, fallback = "") => {
50
- const resolvedPath = String(filePath || "").trim();
51
- if (!resolvedPath) {
52
- return fallback;
53
- }
54
- try {
55
- return fs.readFileSync(resolvedPath, "utf8").trim();
56
- } catch {
57
- return fallback;
58
- }
59
- };
60
- var createPineScriptLoader = (baseDir) => {
61
- const resolvedBaseDir = path.resolve(baseDir);
62
- return (fileNameOrPath, fallback = "") => {
63
- const rawPath = String(fileNameOrPath || "").trim();
64
- if (!rawPath) {
65
- return fallback;
66
- }
67
- const resolvedPath = path.isAbsolute(rawPath) ? rawPath : path.resolve(resolvedBaseDir, rawPath);
68
- return loadPineScriptFile(resolvedPath, fallback);
69
- };
70
- };
71
- var MINUTE_MS = 6e4;
72
- var normalizeTimestampMs = (timestamp) => timestamp < 1e12 ? timestamp * 1e3 : timestamp;
73
- var resolveCandleDuration = (candles) => {
74
- if (candles.length < 2) {
75
- return MINUTE_MS;
76
- }
77
- const first = normalizeTimestampMs(candles[0].timestamp);
78
- const second = normalizeTimestampMs(candles[1].timestamp);
79
- const duration = Math.max(second - first, MINUTE_MS);
80
- return Number.isFinite(duration) && duration > 0 ? duration : MINUTE_MS;
81
- };
82
- var toPineRuntimeCandles = (candles) => {
83
- const candleDuration = resolveCandleDuration(candles);
84
- return candles.map((candle) => {
85
- const openTime = normalizeTimestampMs(candle.timestamp);
86
- return {
87
- open: Number(candle.open),
88
- high: Number(candle.high),
89
- low: Number(candle.low),
90
- close: Number(candle.close),
91
- volume: Number(candle.volume ?? 0),
92
- openTime,
93
- closeTime: openTime + candleDuration
94
- };
95
- });
96
- };
97
- var runPineScript = async ({
98
- candles,
99
- script,
100
- symbol = "SYMBOL",
101
- timeframe = "15",
102
- inputs = {},
103
- limit
104
- }) => {
105
- const { PineTS, Indicator } = loadPinets();
106
- const trimmedScript = String(script || "").trim();
107
- if (!trimmedScript) {
108
- throw new Error("Pine script is empty");
109
- }
110
- if (!Array.isArray(candles) || candles.length === 0) {
111
- throw new Error("No candles provided for Pine script execution");
112
- }
113
- const pineCandles = toPineRuntimeCandles(candles);
114
- const pine = new PineTS(
115
- pineCandles,
116
- symbol,
117
- timeframe,
118
- Math.max(1, limit ?? pineCandles.length)
119
- );
120
- const indicator = new Indicator(trimmedScript, inputs);
121
- const context = await pine.run(indicator);
122
- return context;
123
- };
124
-
125
- export {
126
- getPinePlotSeries,
127
- getLatestPineRawPlotValue,
128
- getLatestPineNumberPlotValue,
129
- getLatestPineBooleanPlotValue,
130
- getLatestPineNumberPlotValues,
131
- getLatestPineBooleanPlotValues,
132
- toFiniteNumber,
133
- toPineBoolean,
134
- loadPineScriptFile,
135
- createPineScriptLoader,
136
- runPineScript
137
- };
@@ -1,246 +0,0 @@
1
- import {
2
- getTradejsProjectCwd,
3
- importTradejsModule,
4
- loadTradejsConfig,
5
- resolvePluginModuleSpecifier
6
- } from "./chunk-WS5DYEVZ.mjs";
7
-
8
- // src/strategy/manifests.ts
9
- import {
10
- registerIndicatorEntries,
11
- resetIndicatorRegistryCache
12
- } from "@tradejs/core/indicators";
13
- import { logger } from "@tradejs/infra/logger";
14
- var createStrategyRegistryState = () => ({
15
- strategyCreators: /* @__PURE__ */ new Map(),
16
- strategyManifestsMap: /* @__PURE__ */ new Map(),
17
- pluginsLoadPromise: null
18
- });
19
- var registryStateByProjectRoot = /* @__PURE__ */ new Map();
20
- var getStrategyRegistryState = (cwd = getTradejsProjectCwd()) => {
21
- const projectRoot = getTradejsProjectCwd(cwd);
22
- let state = registryStateByProjectRoot.get(projectRoot);
23
- if (!state) {
24
- state = createStrategyRegistryState();
25
- registryStateByProjectRoot.set(projectRoot, state);
26
- }
27
- return {
28
- projectRoot,
29
- state
30
- };
31
- };
32
- var toUniqueModules = (modules = []) => [
33
- ...new Set(modules.map((moduleName) => moduleName.trim()).filter(Boolean))
34
- ];
35
- var getConfiguredPluginModuleNames = async (cwd = getTradejsProjectCwd()) => {
36
- const config = await loadTradejsConfig(cwd);
37
- return {
38
- strategyModules: toUniqueModules(config.strategies),
39
- indicatorModules: toUniqueModules(config.indicators)
40
- };
41
- };
42
- var extractModuleEntries = (moduleExport, key) => {
43
- if (!moduleExport || typeof moduleExport !== "object") {
44
- return null;
45
- }
46
- const candidate = moduleExport;
47
- if (Array.isArray(candidate[key])) {
48
- return candidate[key];
49
- }
50
- const defaultExport = candidate.default;
51
- if (defaultExport && Array.isArray(defaultExport[key])) {
52
- return defaultExport[key];
53
- }
54
- return null;
55
- };
56
- var extractStrategyPluginDefinition = (moduleExport) => {
57
- const strategyEntries = extractModuleEntries(
58
- moduleExport,
59
- "strategyEntries"
60
- );
61
- return strategyEntries ? { strategyEntries } : null;
62
- };
63
- var extractIndicatorPluginDefinition = (moduleExport) => {
64
- const indicatorEntries = extractModuleEntries(
65
- moduleExport,
66
- "indicatorEntries"
67
- );
68
- return indicatorEntries ? { indicatorEntries } : null;
69
- };
70
- var registerEntries = (entries, source, state) => {
71
- for (const entry of entries) {
72
- const strategyName = entry.manifest?.name;
73
- if (!strategyName) {
74
- logger.warn("Skip strategy entry without name from %s", source);
75
- continue;
76
- }
77
- if (state.strategyCreators.has(strategyName)) {
78
- logger.warn(
79
- 'Skip duplicate strategy "%s" from %s: already registered',
80
- strategyName,
81
- source
82
- );
83
- continue;
84
- }
85
- state.strategyCreators.set(strategyName, entry.creator);
86
- state.strategyManifestsMap.set(strategyName, entry.manifest);
87
- }
88
- };
89
- var importStrategyPluginModule = async (moduleName, cwd = getTradejsProjectCwd()) => {
90
- if (typeof importTradejsModule === "function") {
91
- return importTradejsModule(moduleName, cwd);
92
- }
93
- return import(
94
- /* webpackIgnore: true */
95
- moduleName
96
- );
97
- };
98
- var ensureStrategyPluginsLoaded = async (cwd = getTradejsProjectCwd()) => {
99
- const { projectRoot, state } = getStrategyRegistryState(cwd);
100
- if (!state.pluginsLoadPromise) {
101
- resetIndicatorRegistryCache(projectRoot);
102
- state.pluginsLoadPromise = (async () => {
103
- const { strategyModules, indicatorModules } = await getConfiguredPluginModuleNames(projectRoot);
104
- const strategySet = new Set(strategyModules);
105
- const indicatorSet = new Set(indicatorModules);
106
- const pluginModuleNames = [
107
- .../* @__PURE__ */ new Set([...strategyModules, ...indicatorModules])
108
- ];
109
- if (!pluginModuleNames.length) {
110
- return;
111
- }
112
- for (const moduleName of pluginModuleNames) {
113
- try {
114
- const resolvedModuleName = resolvePluginModuleSpecifier(
115
- moduleName,
116
- projectRoot
117
- );
118
- const moduleExport = await importStrategyPluginModule(
119
- resolvedModuleName,
120
- projectRoot
121
- );
122
- if (strategySet.has(moduleName)) {
123
- const pluginDefinition = extractStrategyPluginDefinition(moduleExport);
124
- if (!pluginDefinition) {
125
- logger.warn(
126
- 'Skip strategy plugin "%s": export { strategyEntries } is missing',
127
- moduleName
128
- );
129
- } else {
130
- registerEntries(
131
- pluginDefinition.strategyEntries,
132
- moduleName,
133
- state
134
- );
135
- }
136
- }
137
- if (indicatorSet.has(moduleName)) {
138
- const indicatorPluginDefinition = extractIndicatorPluginDefinition(moduleExport);
139
- if (!indicatorPluginDefinition) {
140
- logger.warn(
141
- 'Skip indicator plugin "%s": export { indicatorEntries } is missing',
142
- moduleName
143
- );
144
- } else {
145
- registerIndicatorEntries(
146
- indicatorPluginDefinition.indicatorEntries,
147
- moduleName,
148
- projectRoot
149
- );
150
- }
151
- }
152
- if (!strategySet.has(moduleName) && !indicatorSet.has(moduleName)) {
153
- logger.warn(
154
- 'Skip plugin "%s": no strategy/indicator sections requested in config',
155
- moduleName
156
- );
157
- }
158
- } catch (error) {
159
- logger.warn(
160
- 'Failed to load plugin "%s": %s',
161
- moduleName,
162
- String(error)
163
- );
164
- }
165
- }
166
- })();
167
- }
168
- await state.pluginsLoadPromise;
169
- };
170
- var ensureIndicatorPluginsLoaded = async (cwd = getTradejsProjectCwd()) => ensureStrategyPluginsLoaded(cwd);
171
- var getStrategyCreator = async (name, cwd = getTradejsProjectCwd()) => {
172
- await ensureStrategyPluginsLoaded(cwd);
173
- const { state } = getStrategyRegistryState(cwd);
174
- return state.strategyCreators.get(name);
175
- };
176
- var getAvailableStrategyNames = async (cwd = getTradejsProjectCwd()) => {
177
- await ensureStrategyPluginsLoaded(cwd);
178
- const { state } = getStrategyRegistryState(cwd);
179
- return [...state.strategyCreators.keys()].sort((a, b) => a.localeCompare(b));
180
- };
181
- var getRegisteredStrategies = (cwd = getTradejsProjectCwd()) => {
182
- const { state } = getStrategyRegistryState(cwd);
183
- return Object.fromEntries(state.strategyCreators.entries());
184
- };
185
- var getRegisteredManifests = (cwd = getTradejsProjectCwd()) => {
186
- const { state } = getStrategyRegistryState(cwd);
187
- return [...state.strategyManifestsMap.values()];
188
- };
189
- var getStrategyManifest = (name, cwd = getTradejsProjectCwd()) => {
190
- if (!name) {
191
- return void 0;
192
- }
193
- const { state } = getStrategyRegistryState(cwd);
194
- return state.strategyManifestsMap.get(name);
195
- };
196
- var isKnownStrategy = (name, cwd = getTradejsProjectCwd()) => {
197
- const { state } = getStrategyRegistryState(cwd);
198
- return state.strategyCreators.has(name);
199
- };
200
- var registerStrategyEntries = (entries, cwd = getTradejsProjectCwd()) => {
201
- const { state } = getStrategyRegistryState(cwd);
202
- registerEntries(entries, "runtime", state);
203
- };
204
- var resetStrategyRegistryCache = (cwd) => {
205
- const normalizedCwd = String(cwd ?? "").trim();
206
- if (!normalizedCwd) {
207
- registryStateByProjectRoot.clear();
208
- resetIndicatorRegistryCache();
209
- return;
210
- }
211
- const projectRoot = getTradejsProjectCwd(normalizedCwd);
212
- registryStateByProjectRoot.delete(projectRoot);
213
- resetIndicatorRegistryCache(projectRoot);
214
- };
215
- var strategies = new Proxy(
216
- {},
217
- {
218
- get: (_target, property) => {
219
- if (typeof property !== "string") {
220
- return void 0;
221
- }
222
- return getStrategyRegistryState().state.strategyCreators.get(property);
223
- },
224
- ownKeys: () => {
225
- return [...getStrategyRegistryState().state.strategyCreators.keys()];
226
- },
227
- getOwnPropertyDescriptor: () => ({
228
- enumerable: true,
229
- configurable: true
230
- })
231
- }
232
- );
233
-
234
- export {
235
- ensureStrategyPluginsLoaded,
236
- ensureIndicatorPluginsLoaded,
237
- getStrategyCreator,
238
- getAvailableStrategyNames,
239
- getRegisteredStrategies,
240
- getRegisteredManifests,
241
- getStrategyManifest,
242
- isKnownStrategy,
243
- registerStrategyEntries,
244
- resetStrategyRegistryCache,
245
- strategies
246
- };
@@ -1,41 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __commonJS = (cb, mod) => function __require2() {
14
- try {
15
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
- } catch (e) {
17
- throw mod = 0, e;
18
- }
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") {
22
- for (let key of __getOwnPropNames(from))
23
- if (!__hasOwnProp.call(to, key) && key !== except)
24
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
-
37
- export {
38
- __require,
39
- __commonJS,
40
- __toESM
41
- };