@tradejs/strategies 1.0.8 → 1.0.10

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,209 +0,0 @@
1
- import {
2
- config,
3
- maStrategyManifest
4
- } from "./chunk-H4MHFD4B.mjs";
5
- import "./chunk-HEBXNMVQ.mjs";
6
-
7
- // src/MaStrategy/strategy.ts
8
- import { createStrategyRuntime } from "@tradejs/node/strategies";
9
-
10
- // src/MaStrategy/core.ts
11
- import { round } from "@tradejs/core/math";
12
-
13
- // src/MaStrategy/figures.ts
14
- var toLinePoints = (candles, values, limit = 120) => {
15
- const points = [];
16
- const seriesOffset = Math.max(0, candles.length - values.length);
17
- const start = Math.max(0, values.length - limit);
18
- for (let i = start; i < values.length; i += 1) {
19
- const candle = candles[seriesOffset + i];
20
- const value = values[i];
21
- if (!candle || !Number.isFinite(value)) continue;
22
- points.push({
23
- timestamp: candle.timestamp,
24
- value
25
- });
26
- }
27
- return points;
28
- };
29
- var buildMaStrategyFigures = ({
30
- fullData,
31
- maFast,
32
- maSlow,
33
- crossTimestamp,
34
- crossPrice,
35
- crossKind
36
- }) => ({
37
- lines: [
38
- {
39
- id: "ma-fast",
40
- kind: "ma_fast",
41
- points: toLinePoints(fullData, maFast),
42
- color: "#22d3ee",
43
- width: 2,
44
- style: "solid"
45
- },
46
- {
47
- id: "ma-slow",
48
- kind: "ma_slow",
49
- points: toLinePoints(fullData, maSlow),
50
- color: "#f59e0b",
51
- width: 2,
52
- style: "solid"
53
- }
54
- ],
55
- points: [
56
- {
57
- id: `ma-cross-${crossTimestamp}`,
58
- kind: "ma_cross",
59
- points: [
60
- {
61
- timestamp: crossTimestamp,
62
- value: crossPrice
63
- }
64
- ],
65
- color: crossKind === "bullish" ? "#22c55e" : "#ef4444",
66
- radius: 4
67
- }
68
- ]
69
- });
70
-
71
- // src/MaStrategy/core.ts
72
- var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
73
- var detectCross = (maFast, maSlow) => {
74
- if (maFast.length < 2 || maSlow.length < 2) {
75
- return null;
76
- }
77
- const maFastPrev = maFast[maFast.length - 2];
78
- const maFastCurrent = maFast[maFast.length - 1];
79
- const maSlowPrev = maSlow[maSlow.length - 2];
80
- const maSlowCurrent = maSlow[maSlow.length - 1];
81
- if (!isFiniteNumber(maFastPrev) || !isFiniteNumber(maFastCurrent) || !isFiniteNumber(maSlowPrev) || !isFiniteNumber(maSlowCurrent)) {
82
- return null;
83
- }
84
- if (maFastPrev <= maSlowPrev && maFastCurrent > maSlowCurrent) {
85
- return {
86
- kind: "bullish",
87
- maFastPrev,
88
- maFastCurrent,
89
- maSlowPrev,
90
- maSlowCurrent
91
- };
92
- }
93
- if (maFastPrev >= maSlowPrev && maFastCurrent < maSlowCurrent) {
94
- return {
95
- kind: "bearish",
96
- maFastPrev,
97
- maFastCurrent,
98
- maSlowPrev,
99
- maSlowCurrent
100
- };
101
- }
102
- return null;
103
- };
104
- var createMaStrategyCore = async ({ config: config2, strategyApi, indicatorsState }) => {
105
- const { FEE_PERCENT, MAX_LOSS_VALUE, TRADE_COOLDOWN_MS, LONG, SHORT } = config2;
106
- const lastTradeController = strategyApi.createLastTradeController({
107
- enabled: Number(TRADE_COOLDOWN_MS ?? 0) > 0,
108
- cooldownMs: Number(TRADE_COOLDOWN_MS ?? 0)
109
- });
110
- return async () => {
111
- indicatorsState.onBar();
112
- const indicators = indicatorsState.snapshot();
113
- if (!indicators) {
114
- return strategyApi.skip("NO_INDICATORS");
115
- }
116
- const maFast = Array.isArray(indicators.maFast) ? indicators.maFast : [];
117
- const maSlow = Array.isArray(indicators.maSlow) ? indicators.maSlow : [];
118
- if (maFast.length < 2 || maSlow.length < 2) {
119
- return strategyApi.skip("WAIT_MA_DATA");
120
- }
121
- const cross = detectCross(maFast, maSlow);
122
- const position = await strategyApi.getCurrentPosition();
123
- const positionExists = Boolean(
124
- position && typeof position.qty === "number" && position.qty > 0
125
- );
126
- if (positionExists && position) {
127
- if (position.direction === "LONG" && cross?.kind === "bearish" || position.direction === "SHORT" && cross?.kind === "bullish") {
128
- const { currentPrice: currentPrice2, timestamp: timestamp2 } = await strategyApi.getMarketData();
129
- return {
130
- kind: "exit",
131
- code: "CLOSE_BY_OPPOSITE_MA_CROSS",
132
- closePlan: {
133
- price: currentPrice2,
134
- timestamp: timestamp2,
135
- direction: position.direction
136
- }
137
- };
138
- }
139
- return strategyApi.skip("POSITION_HELD");
140
- }
141
- if (!cross) {
142
- return strategyApi.skip("NO_CROSS");
143
- }
144
- const modeConfig = cross.kind === "bullish" ? LONG : SHORT;
145
- if (!modeConfig.enable) {
146
- return strategyApi.skip("STRATEGY_DISABLED");
147
- }
148
- const { fullData, timestamp, currentPrice } = await strategyApi.getMarketData();
149
- if (lastTradeController.isInCooldown(timestamp)) {
150
- return strategyApi.skip("TRADE_COOLDOWN");
151
- }
152
- const { stopLossPrice, takeProfitPrice, riskRatio, qty } = strategyApi.getDirectionalTpSlPrices({
153
- price: currentPrice,
154
- direction: modeConfig.direction,
155
- takeProfitDelta: modeConfig.TP,
156
- stopLossDelta: modeConfig.SL,
157
- unit: "percent",
158
- maxLossValue: MAX_LOSS_VALUE,
159
- feePercent: Number(FEE_PERCENT ?? 0)
160
- });
161
- if (!qty || !Number.isFinite(qty) || qty <= 0) {
162
- return strategyApi.skip("INVALID_QTY");
163
- }
164
- if (riskRatio <= modeConfig.minRiskRatio) {
165
- return strategyApi.skip(`RISK_RATIO:${round(riskRatio)}`);
166
- }
167
- const correlation = indicatorsState.latestNumber("correlation");
168
- lastTradeController.markTrade(timestamp);
169
- return strategyApi.entry({
170
- code: cross.kind === "bullish" ? "MA_BULLISH_CROSS" : "MA_BEARISH_CROSS",
171
- direction: modeConfig.direction,
172
- figures: buildMaStrategyFigures({
173
- fullData,
174
- maFast,
175
- maSlow,
176
- crossTimestamp: timestamp,
177
- crossPrice: currentPrice,
178
- crossKind: cross.kind
179
- }),
180
- indicators,
181
- additionalIndicators: {
182
- crossKind: cross.kind,
183
- maFastPrev: cross.maFastPrev,
184
- maFastCurrent: cross.maFastCurrent,
185
- maSlowPrev: cross.maSlowPrev,
186
- maSlowCurrent: cross.maSlowCurrent,
187
- maGap: cross.maFastCurrent - cross.maSlowCurrent,
188
- correlation
189
- },
190
- orderPlan: {
191
- qty,
192
- stopLossPrice,
193
- takeProfits: [{ rate: 1, price: takeProfitPrice }]
194
- }
195
- });
196
- };
197
- };
198
-
199
- // src/MaStrategy/strategy.ts
200
- var MaStrategyCreator = createStrategyRuntime({
201
- strategyName: "MaStrategy",
202
- defaults: config,
203
- createCore: createMaStrategyCore,
204
- manifest: maStrategyManifest,
205
- strategyDirectory: __dirname
206
- });
207
- export {
208
- MaStrategyCreator
209
- };
@@ -1,348 +0,0 @@
1
- import {
2
- buildTrendlineStructuralContext,
3
- buildTrendlineTimingContext,
4
- config,
5
- trendLineManifest
6
- } from "./chunk-TDUTYEGH.mjs";
7
- import "./chunk-HEBXNMVQ.mjs";
8
-
9
- // src/TrendLine/strategy.ts
10
- import { createStrategyRuntime } from "@tradejs/node/strategies";
11
-
12
- // src/TrendLine/core.ts
13
- import { round as round2 } from "@tradejs/core/math";
14
- import { createTrendlineEngine } from "@tradejs/core/indicators";
15
-
16
- // src/TrendLine/filters.ts
17
- import { diffRel } from "@tradejs/core/math";
18
- import { ATR_PCT } from "@tradejs/indicators";
19
- var MAX_CANDLE_VOLATILITY = 0.025;
20
- var filterByVeryVolatility = (data) => {
21
- const lastCandle = data[data.length - 1];
22
- const prevCandle = data[data.length - 2];
23
- const isVeryVolatility = diffRel(lastCandle.low, lastCandle.high) > MAX_CANDLE_VOLATILITY || diffRel(prevCandle.low, prevCandle.high) > MAX_CANDLE_VOLATILITY;
24
- if (isVeryVolatility) {
25
- return false;
26
- }
27
- return true;
28
- };
29
-
30
- // src/TrendLine/figures.ts
31
- var buildTrendLineFigures = (bestLine) => ({
32
- lines: [
33
- {
34
- id: bestLine.id,
35
- kind: "trendline",
36
- points: [...bestLine.points ?? []].sort(
37
- (left, right) => left.timestamp - right.timestamp
38
- ),
39
- color: bestLine.mode === "lows" ? "#facc15" : "#fb923c",
40
- width: 2,
41
- style: "solid"
42
- }
43
- ],
44
- points: [
45
- {
46
- id: `${bestLine.id}-points`,
47
- kind: "trendline_points",
48
- points: [...bestLine.points ?? [], ...bestLine.touches ?? []].sort(
49
- (left, right) => left.timestamp - right.timestamp
50
- ),
51
- color: "#ef4444",
52
- radius: 4
53
- }
54
- ]
55
- });
56
-
57
- // src/TrendLine/risk.ts
58
- import { round } from "@tradejs/core/math";
59
- var MIN_STOP_BUFFER_PCT = 0.15;
60
- var LINE_BUFFER_ATR_FACTOR = 0.35;
61
- var LINE_BUFFER_BASE_SL_FACTOR = 0.15;
62
- var ATR_STOP_FLOOR_FACTOR = 0.8;
63
- var MIN_STOP_LOSS_FACTOR = 0.75;
64
- var MAX_STOP_LOSS_FACTOR = 2.25;
65
- var clampNumber = (value, min, max) => Math.min(Math.max(value, min), max);
66
- var getTimingStopFactor = (entryTiming) => {
67
- if (entryTiming === "ready_retest") {
68
- return 0.9;
69
- }
70
- if (entryTiming === "ready_follow_through") {
71
- return 1.05;
72
- }
73
- return 1;
74
- };
75
- var getTimingTargetRiskRatio = ({
76
- direction,
77
- entryTiming
78
- }) => {
79
- if (direction === "LONG") {
80
- if (entryTiming === "ready_retest") {
81
- return 2.45;
82
- }
83
- if (entryTiming === "ready_follow_through") {
84
- return 2.3;
85
- }
86
- return 2.6;
87
- }
88
- if (entryTiming === "ready_retest") {
89
- return 2.3;
90
- }
91
- if (entryTiming === "ready_follow_through") {
92
- return 2.15;
93
- }
94
- return 2.45;
95
- };
96
- var buildTrendlineRiskPlan = ({
97
- direction,
98
- modeConfig,
99
- structuralContext,
100
- timingContext
101
- }) => {
102
- const baseStopLossDelta = modeConfig.SL;
103
- const atrPct = structuralContext.atrPct ?? baseStopLossDelta;
104
- const priceVsLinePctAbs = structuralContext.priceVsLinePctAbs ?? 0;
105
- const breakVsAtrRatio = structuralContext.breakVsAtrRatio ?? 0;
106
- const touches = structuralContext.touches ?? 0;
107
- const distance = structuralContext.distance ?? null;
108
- const lineBufferPct = Math.max(
109
- atrPct * LINE_BUFFER_ATR_FACTOR,
110
- baseStopLossDelta * LINE_BUFFER_BASE_SL_FACTOR,
111
- MIN_STOP_BUFFER_PCT
112
- );
113
- const lineInvalidationPct = priceVsLinePctAbs + lineBufferPct;
114
- const volatilityFloorPct = Math.max(
115
- atrPct * ATR_STOP_FLOOR_FACTOR,
116
- baseStopLossDelta * MIN_STOP_LOSS_FACTOR
117
- );
118
- let stopLossDelta = Math.max(lineInvalidationPct, volatilityFloorPct);
119
- if (touches >= 6) {
120
- stopLossDelta *= 0.95;
121
- } else if (touches > 0 && touches <= 4) {
122
- stopLossDelta *= 1.05;
123
- }
124
- if (distance != null && distance >= 250) {
125
- stopLossDelta *= 1.08;
126
- } else if (distance != null && distance <= 120) {
127
- stopLossDelta *= 0.95;
128
- }
129
- stopLossDelta *= getTimingStopFactor(timingContext.entryTiming);
130
- if (direction === "SHORT") {
131
- stopLossDelta *= 1.08;
132
- }
133
- if (breakVsAtrRatio >= 1.5) {
134
- stopLossDelta *= 0.95;
135
- }
136
- stopLossDelta = clampNumber(
137
- stopLossDelta,
138
- baseStopLossDelta * MIN_STOP_LOSS_FACTOR,
139
- baseStopLossDelta * MAX_STOP_LOSS_FACTOR
140
- );
141
- let targetRiskRatio = getTimingTargetRiskRatio({
142
- direction,
143
- entryTiming: timingContext.entryTiming
144
- });
145
- if (breakVsAtrRatio >= 1.25) {
146
- targetRiskRatio += 0.2;
147
- } else if (breakVsAtrRatio > 0 && breakVsAtrRatio < 0.75) {
148
- targetRiskRatio -= 0.15;
149
- }
150
- if (touches >= 6) {
151
- targetRiskRatio += 0.1;
152
- }
153
- if (distance != null && distance >= 120 && distance <= 350) {
154
- targetRiskRatio += 0.1;
155
- }
156
- if (direction === "SHORT" && distance != null && distance > 450) {
157
- targetRiskRatio -= 0.25;
158
- }
159
- if (direction === "LONG" && distance != null && distance > 500) {
160
- targetRiskRatio -= 0.15;
161
- }
162
- const minTargetRiskRatio = modeConfig.minRiskRatio + 0.05;
163
- const maxTargetRiskRatio = Math.max(modeConfig.TP / modeConfig.SL, minTargetRiskRatio) + 0.4;
164
- targetRiskRatio = clampNumber(
165
- targetRiskRatio,
166
- minTargetRiskRatio,
167
- maxTargetRiskRatio
168
- );
169
- return {
170
- stopLossDelta: round(stopLossDelta, 3),
171
- targetRiskRatio: round(targetRiskRatio, 2),
172
- takeProfitDelta: round(stopLossDelta * targetRiskRatio, 3)
173
- };
174
- };
175
-
176
- // src/TrendLine/core.ts
177
- var buildTrendlineSignalSeed = ({
178
- direction,
179
- currentPrice,
180
- indicators,
181
- bestLine,
182
- trendlineTiming
183
- }) => ({
184
- direction,
185
- prices: { currentPrice },
186
- indicators,
187
- additionalIndicators: {
188
- touches: bestLine.touches.length + 2,
189
- distance: bestLine.distance,
190
- trendLine: bestLine,
191
- ...trendlineTiming ? { trendlineTiming } : {}
192
- },
193
- figures: {
194
- trendLine: bestLine
195
- }
196
- });
197
- var isOpenPosition = (position) => Boolean(
198
- position && typeof position.price === "number" && Number.isFinite(position.price) && typeof position.qty === "number" && Number.isFinite(position.qty) && position.qty > 0 && (position.direction === "LONG" || position.direction === "SHORT")
199
- );
200
- var isFailedBreakout = ({
201
- direction,
202
- priceVsLinePct
203
- }) => {
204
- if (priceVsLinePct == null) {
205
- return false;
206
- }
207
- return direction === "LONG" ? priceVsLinePct < 0 : priceVsLinePct > 0;
208
- };
209
- var createTrendLineCore = async ({ config: config2, data: cachedData, strategyApi, indicatorsState }) => {
210
- const { TRENDLINE, FEE_PERCENT, MAX_LOSS_VALUE, HIGHS, LOWS } = config2;
211
- const lastTradeController = strategyApi.createLastTradeController();
212
- const trendlineOptions = {
213
- bestLines: 1,
214
- capture: true,
215
- ...TRENDLINE
216
- };
217
- const getLowsTrendlines = createTrendlineEngine(cachedData, {
218
- mode: "lows",
219
- ...trendlineOptions
220
- });
221
- const getHighsTrendlines = createTrendlineEngine(cachedData, {
222
- mode: "highs",
223
- ...trendlineOptions
224
- });
225
- return async (candle) => {
226
- const lowsTrendlines = getLowsTrendlines.next(candle);
227
- const highsTrendlines = getHighsTrendlines.next(candle);
228
- indicatorsState.onBar();
229
- const currentPosition = await strategyApi.getCurrentPosition();
230
- if (isOpenPosition(currentPosition)) {
231
- const { currentPrice: currentPrice2 } = await strategyApi.getMarketData();
232
- const activeLine = currentPosition.direction === "LONG" ? highsTrendlines[0] : lowsTrendlines[0];
233
- const activeModeConfig = currentPosition.direction === "LONG" ? HIGHS : LOWS;
234
- if (activeLine) {
235
- const indicators2 = indicatorsState.snapshot();
236
- const manageSignalSeed = buildTrendlineSignalSeed({
237
- direction: activeModeConfig.direction,
238
- currentPrice: currentPrice2,
239
- indicators: indicators2,
240
- bestLine: activeLine
241
- });
242
- const structuralContext2 = buildTrendlineStructuralContext(manageSignalSeed);
243
- if (isFailedBreakout({
244
- direction: currentPosition.direction,
245
- priceVsLinePct: structuralContext2.priceVsLinePct
246
- })) {
247
- return strategyApi.exit({
248
- code: "TRENDLINE_FAILED_BREAKOUT_EXIT",
249
- direction: currentPosition.direction
250
- });
251
- }
252
- }
253
- return strategyApi.skip("POSITION_EXISTS");
254
- }
255
- const bestLine = lowsTrendlines.length > 0 ? lowsTrendlines[0] : highsTrendlines[0];
256
- if (!bestLine) {
257
- return strategyApi.skip("NO_TRENDLINE");
258
- }
259
- if (lastTradeController.isInCooldown(candle.timestamp)) {
260
- return strategyApi.skip("DEV_TRADE_COOLDOWN");
261
- }
262
- const modeConfig = bestLine.mode === "highs" ? HIGHS : LOWS;
263
- const { direction, minRiskRatio, enable } = modeConfig;
264
- if (!enable) {
265
- return strategyApi.skip("STRATEGY_DISABLED");
266
- }
267
- const { fullData, timestamp, currentPrice } = await strategyApi.getMarketData();
268
- if (!filterByVeryVolatility(fullData)) {
269
- return strategyApi.skip("VERY_VOLATILITY");
270
- }
271
- const indicators = indicatorsState.snapshot();
272
- const signalSeed = buildTrendlineSignalSeed({
273
- direction,
274
- currentPrice,
275
- indicators,
276
- bestLine
277
- });
278
- const structuralContext = buildTrendlineStructuralContext(signalSeed);
279
- if (structuralContext.structuralHardBlockReasons.length > 0) {
280
- return strategyApi.skip(
281
- `TRENDLINE_STRUCTURE:${structuralContext.structuralHardBlockReasons[0]}`
282
- );
283
- }
284
- const timingContext = buildTrendlineTimingContext({
285
- signal: signalSeed,
286
- candles: fullData,
287
- structuralContext
288
- });
289
- if (!timingContext.entryReadyNow) {
290
- const timingCode = timingContext.entryTiming === "stale_breakout" ? "STALE_BREAKOUT" : timingContext.entryTiming === "wait_retest_confirmation" ? "WAIT_RETEST_CONFIRMATION" : "WAIT_RETEST";
291
- return strategyApi.skip(`TRENDLINE_TIMING:${timingCode}`);
292
- }
293
- const riskPlan = buildTrendlineRiskPlan({
294
- direction,
295
- modeConfig,
296
- structuralContext,
297
- timingContext
298
- });
299
- const { stopLossPrice, takeProfitPrice, riskRatio, qty } = strategyApi.getDirectionalTpSlPrices({
300
- price: currentPrice,
301
- direction,
302
- takeProfitDelta: riskPlan.takeProfitDelta,
303
- stopLossDelta: riskPlan.stopLossDelta,
304
- unit: "percent",
305
- maxLossValue: MAX_LOSS_VALUE,
306
- feePercent: Number(FEE_PERCENT ?? 0)
307
- });
308
- if (!qty || !Number.isFinite(qty) || qty <= 0) {
309
- return strategyApi.skip("INVALID_QTY");
310
- }
311
- if (riskRatio <= minRiskRatio) {
312
- return strategyApi.skip(`RISK_RATIO:${round2(riskRatio)}`);
313
- }
314
- lastTradeController.markTrade(timestamp);
315
- return strategyApi.entry({
316
- code: "TRENDLINE_SIGNAL",
317
- figures: {
318
- ...buildTrendLineFigures(bestLine)
319
- },
320
- direction,
321
- indicators,
322
- additionalIndicators: buildTrendlineSignalSeed({
323
- direction,
324
- currentPrice,
325
- indicators,
326
- bestLine,
327
- trendlineTiming: timingContext
328
- }).additionalIndicators,
329
- orderPlan: {
330
- qty,
331
- stopLossPrice,
332
- takeProfits: [{ rate: 1, price: takeProfitPrice }]
333
- }
334
- });
335
- };
336
- };
337
-
338
- // src/TrendLine/strategy.ts
339
- var TrendlineStrategyCreator = createStrategyRuntime({
340
- strategyName: "TrendLine",
341
- defaults: config,
342
- createCore: createTrendLineCore,
343
- manifest: trendLineManifest,
344
- strategyDirectory: __dirname
345
- });
346
- export {
347
- TrendlineStrategyCreator
348
- };