@backtest-kit/signals 0.0.1 → 0.0.3
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/README.md +1 -0
- package/build/index.cjs +2055 -5
- package/build/index.mjs +2055 -5
- package/package.json +16 -11
- package/types.d.ts +1512 -0
package/build/index.cjs
CHANGED
|
@@ -5,31 +5,97 @@ var backtestKit = require('backtest-kit');
|
|
|
5
5
|
var diKit = require('di-kit');
|
|
6
6
|
var functoolsKit = require('functools-kit');
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* Dependency injection container for signals library.
|
|
10
|
+
*
|
|
11
|
+
* Creates an isolated DI container using di-kit for managing service instances.
|
|
12
|
+
* Provides methods for dependency registration, injection, and initialization.
|
|
13
|
+
*
|
|
14
|
+
* @module lib/core/di
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* DI container exports for signals library.
|
|
18
|
+
*
|
|
19
|
+
* - provide: Register service factory in DI container
|
|
20
|
+
* - inject: Retrieve service instance from container
|
|
21
|
+
* - init: Initialize all registered services
|
|
22
|
+
* - override: Replace existing service registration
|
|
23
|
+
*/
|
|
8
24
|
const { provide, inject, init, override } = diKit.createActivator("signal");
|
|
9
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Dependency injection type symbols for signals library.
|
|
28
|
+
*
|
|
29
|
+
* Defines unique symbols for service registration and retrieval in the DI container.
|
|
30
|
+
* Organized by service category: common, math, and history services.
|
|
31
|
+
*
|
|
32
|
+
* @module lib/core/types
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* Common service symbols.
|
|
36
|
+
*/
|
|
10
37
|
const commonServices$1 = {
|
|
38
|
+
/** Logger service for diagnostic output */
|
|
11
39
|
loggerService: Symbol("loggerService"),
|
|
12
40
|
};
|
|
41
|
+
/**
|
|
42
|
+
* Technical analysis service symbols.
|
|
43
|
+
*/
|
|
13
44
|
const mathServices$1 = {
|
|
45
|
+
/** 1-hour (LongTerm) technical analysis service */
|
|
14
46
|
longTermMathService: Symbol('longTermMathService'),
|
|
47
|
+
/** 30-minute (SwingTerm) technical analysis service */
|
|
15
48
|
swingTermMathService: Symbol('swingTermMathService'),
|
|
49
|
+
/** 15-minute (ShortTerm) technical analysis service */
|
|
16
50
|
shortTermMathService: Symbol('shortTermMathService'),
|
|
51
|
+
/** 1-minute (MicroTerm) technical analysis service */
|
|
17
52
|
microTermMathService: Symbol('microTermMathService'),
|
|
53
|
+
/** Order book analysis service */
|
|
18
54
|
bookDataMathService: Symbol('bookDataMathService'),
|
|
19
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* Candle history service symbols.
|
|
58
|
+
*/
|
|
20
59
|
const historyServices$1 = {
|
|
60
|
+
/** 15-minute candle history service */
|
|
21
61
|
fifteenMinuteCandleHistoryService: Symbol('fifteenMinuteCandleHistoryService'),
|
|
62
|
+
/** 1-hour candle history service */
|
|
22
63
|
hourCandleHistoryService: Symbol('hourCandleHistoryService'),
|
|
64
|
+
/** 1-minute candle history service */
|
|
23
65
|
oneMinuteCandleHistoryService: Symbol('oneMinuteCandleHistoryService'),
|
|
66
|
+
/** 30-minute candle history service */
|
|
24
67
|
thirtyMinuteCandleHistoryService: Symbol('thirtyMinuteCandleHistoryService'),
|
|
25
68
|
};
|
|
69
|
+
/**
|
|
70
|
+
* All service type symbols combined.
|
|
71
|
+
*/
|
|
26
72
|
const TYPES = {
|
|
27
73
|
...commonServices$1,
|
|
28
74
|
...mathServices$1,
|
|
29
75
|
...historyServices$1,
|
|
30
76
|
};
|
|
31
77
|
|
|
78
|
+
/**
|
|
79
|
+
* LongTerm (1-hour) technical analysis service for trend trading.
|
|
80
|
+
*
|
|
81
|
+
* Generates 30+ indicators on 1-hour candles with 48-candle lookback (48 hours).
|
|
82
|
+
* Optimized for multi-day trend trading and position management.
|
|
83
|
+
*
|
|
84
|
+
* Indicators: RSI(14), StochRSI(14), MACD(12,26,9), Bollinger(20,2), Stochastic(14,3,3),
|
|
85
|
+
* ADX(14), ATR(14,20), CCI(20), Momentum(10), SMA(50), EMA(20,34), DEMA(21), WMA(20),
|
|
86
|
+
* Support/Resistance, Fibonacci levels, Volume trends.
|
|
87
|
+
*
|
|
88
|
+
* Used by commitLongTermMath().
|
|
89
|
+
*/
|
|
90
|
+
/**
|
|
91
|
+
* Maximum number of historical rows to return in analysis results.
|
|
92
|
+
* Limits memory usage and table size for markdown reports.
|
|
93
|
+
*/
|
|
32
94
|
const TABLE_ROWS_LIMIT$3 = 48;
|
|
95
|
+
/**
|
|
96
|
+
* Minimum number of candles required before generating analysis rows.
|
|
97
|
+
* Ensures all technical indicators (especially SMA(50)) have sufficient data.
|
|
98
|
+
*/
|
|
33
99
|
const WARMUP_PERIOD$3 = 50;
|
|
34
100
|
const columns$3 = [
|
|
35
101
|
{
|
|
@@ -214,6 +280,23 @@ const columns$3 = [
|
|
|
214
280
|
format: (v) => new Date(v).toISOString(),
|
|
215
281
|
},
|
|
216
282
|
];
|
|
283
|
+
/**
|
|
284
|
+
* Validates whether a numeric value is safe for calculations.
|
|
285
|
+
*
|
|
286
|
+
* Checks if value is a valid finite number. Returns true if value is null,
|
|
287
|
+
* NaN, Infinity, or not a number type.
|
|
288
|
+
*
|
|
289
|
+
* @param value - Value to validate
|
|
290
|
+
* @returns True if value is unsafe (null/NaN/Infinity), false if valid number
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```typescript
|
|
294
|
+
* isUnsafe(42) // false - valid number
|
|
295
|
+
* isUnsafe(null) // true - null value
|
|
296
|
+
* isUnsafe(NaN) // true - not a number
|
|
297
|
+
* isUnsafe(Infinity) // true - infinite value
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
217
300
|
function isUnsafe$4(value) {
|
|
218
301
|
if (typeof value !== "number") {
|
|
219
302
|
return true;
|
|
@@ -226,6 +309,25 @@ function isUnsafe$4(value) {
|
|
|
226
309
|
}
|
|
227
310
|
return false;
|
|
228
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Calculates Fibonacci retracement levels and finds nearest level to current price.
|
|
314
|
+
*
|
|
315
|
+
* Computes standard Fibonacci levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%)
|
|
316
|
+
* plus extension levels (127.2%, 161.8%) based on high-low range over lookback period.
|
|
317
|
+
* Returns the level closest to current price with distance in USD.
|
|
318
|
+
*
|
|
319
|
+
* @param candles - Array of candle data
|
|
320
|
+
* @param endIndex - Index of current candle in array
|
|
321
|
+
* @returns Object with nearest level name, price, and distance in USD
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* ```typescript
|
|
325
|
+
* const candles = await getCandles('BTCUSDT', '1h', 100);
|
|
326
|
+
* const fib = calculateFibonacciLevels(candles, 99);
|
|
327
|
+
* console.log(fib);
|
|
328
|
+
* // { level: "61.8%", price: 42500.50, distance: 125.30 }
|
|
329
|
+
* ```
|
|
330
|
+
*/
|
|
229
331
|
function calculateFibonacciLevels$2(candles, endIndex) {
|
|
230
332
|
const lookbackPeriod = Math.min(24, endIndex + 1);
|
|
231
333
|
const startIndex = endIndex + 1 - lookbackPeriod;
|
|
@@ -258,6 +360,31 @@ function calculateFibonacciLevels$2(candles, endIndex) {
|
|
|
258
360
|
});
|
|
259
361
|
return nearestLevel;
|
|
260
362
|
}
|
|
363
|
+
/**
|
|
364
|
+
* Generates comprehensive technical analysis for 1-hour candles (long-term trading).
|
|
365
|
+
*
|
|
366
|
+
* Calculates 30+ technical indicators per candle including:
|
|
367
|
+
* - Momentum: RSI(14), Stochastic RSI(14), MACD(12,26,9), Momentum(10)
|
|
368
|
+
* - Trend: SMA(50), EMA(20,34), DEMA(21), WMA(20), ADX(14), +DI/-DI
|
|
369
|
+
* - Volatility: ATR(14,20), Bollinger Bands(20,2.0), CCI(20)
|
|
370
|
+
* - Volume: Volume trend analysis
|
|
371
|
+
* - Support/Resistance: Pivot points, Fibonacci levels
|
|
372
|
+
*
|
|
373
|
+
* Skips first WARMUP_PERIOD (50) candles to ensure indicator stability.
|
|
374
|
+
* Returns last TABLE_ROWS_LIMIT (48) rows for memory efficiency.
|
|
375
|
+
*
|
|
376
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
377
|
+
* @param candles - Array of 1-hour candle data
|
|
378
|
+
* @returns Array of technical analysis rows with all indicators
|
|
379
|
+
*
|
|
380
|
+
* @example
|
|
381
|
+
* ```typescript
|
|
382
|
+
* const candles = await getCandles('BTCUSDT', '1h', 100);
|
|
383
|
+
* const analysis = generateAnalysis('BTCUSDT', candles);
|
|
384
|
+
* console.log(analysis[0].rsi14); // 52.45
|
|
385
|
+
* console.log(analysis[0].support); // 42000.50
|
|
386
|
+
* ```
|
|
387
|
+
*/
|
|
261
388
|
function generateAnalysis$3(symbol, candles) {
|
|
262
389
|
const closes = candles.map((candle) => Number(candle.close));
|
|
263
390
|
const highs = candles.map((candle) => Number(candle.high));
|
|
@@ -439,6 +566,32 @@ function generateAnalysis$3(symbol, candles) {
|
|
|
439
566
|
});
|
|
440
567
|
return results;
|
|
441
568
|
}
|
|
569
|
+
/**
|
|
570
|
+
* Generates markdown table with long-term technical analysis history.
|
|
571
|
+
*
|
|
572
|
+
* Creates comprehensive markdown report with:
|
|
573
|
+
* - Formatted table of all technical indicators
|
|
574
|
+
* - Column headers with indicator names and parameters
|
|
575
|
+
* - Formatted values (prices in USD, percentages, decimals)
|
|
576
|
+
* - Data sources section explaining each indicator's calculation
|
|
577
|
+
* - Timeframe and lookback period documentation (1h candles, 48h lookback)
|
|
578
|
+
*
|
|
579
|
+
* Output is optimized for LLM consumption in long-term trading signal generation.
|
|
580
|
+
*
|
|
581
|
+
* @param indicators - Array of analysis rows from generateAnalysis()
|
|
582
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
583
|
+
* @returns Markdown-formatted technical analysis report
|
|
584
|
+
*
|
|
585
|
+
* @example
|
|
586
|
+
* ```typescript
|
|
587
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
588
|
+
* const markdown = await generateHistoryTable(rows, 'BTCUSDT');
|
|
589
|
+
* console.log(markdown);
|
|
590
|
+
* // # 1-Hour Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
591
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
592
|
+
* // | RSI(14) | MACD(12,26,9) | Support Level | ... |
|
|
593
|
+
* ```
|
|
594
|
+
*/
|
|
442
595
|
async function generateHistoryTable$3(indicators, symbol) {
|
|
443
596
|
let markdown = "";
|
|
444
597
|
const currentData = await backtestKit.getDate();
|
|
@@ -519,9 +672,61 @@ async function generateHistoryTable$3(indicators, symbol) {
|
|
|
519
672
|
"- **Close Price**: close price at row timestamp (Min: 0 USD, Max: +∞ USD)\n";
|
|
520
673
|
return markdown;
|
|
521
674
|
}
|
|
675
|
+
/**
|
|
676
|
+
* Service for long-term (1-hour) technical analysis and markdown report generation.
|
|
677
|
+
*
|
|
678
|
+
* Provides comprehensive technical analysis for 1-hour candles with 30+ indicators
|
|
679
|
+
* including momentum (RSI, MACD), trend (EMA, SMA), volatility (ATR, Bollinger Bands),
|
|
680
|
+
* support/resistance levels, and Fibonacci retracements.
|
|
681
|
+
*
|
|
682
|
+
* Key features:
|
|
683
|
+
* - 30+ technical indicators (RSI, MACD, Bollinger Bands, Stochastic, ADX, etc.)
|
|
684
|
+
* - Support/resistance level detection
|
|
685
|
+
* - Fibonacci retracement analysis
|
|
686
|
+
* - Volume trend analysis
|
|
687
|
+
* - Markdown table generation for LLM consumption
|
|
688
|
+
* - Intelligent indicator warmup (skips first 50 candles)
|
|
689
|
+
* - Memory-efficient output (last 48 rows only)
|
|
690
|
+
* - Dependency injection support
|
|
691
|
+
*
|
|
692
|
+
* @example
|
|
693
|
+
* ```typescript
|
|
694
|
+
* import { LongTermHistoryService } from '@backtest-kit/signals';
|
|
695
|
+
*
|
|
696
|
+
* const service = new LongTermHistoryService();
|
|
697
|
+
*
|
|
698
|
+
* // Get markdown report for symbol (fetches candles internally)
|
|
699
|
+
* const report = await service.getReport('BTCUSDT');
|
|
700
|
+
* console.log(report); // Markdown table with all indicators
|
|
701
|
+
*
|
|
702
|
+
* // Or analyze custom candles
|
|
703
|
+
* const candles = await getCandles('ETHUSDT', '1h', 100);
|
|
704
|
+
* const rows = await service.getData('ETHUSDT', candles);
|
|
705
|
+
* console.log(rows[0].rsi14); // 52.45
|
|
706
|
+
* ```
|
|
707
|
+
*/
|
|
522
708
|
class LongTermHistoryService {
|
|
523
709
|
constructor() {
|
|
524
710
|
this.loggerService = inject(TYPES.loggerService);
|
|
711
|
+
/**
|
|
712
|
+
* Analyzes candle data and returns technical indicator rows.
|
|
713
|
+
*
|
|
714
|
+
* Calculates all technical indicators for provided candles, skips first WARMUP_PERIOD
|
|
715
|
+
* rows to ensure stability, and returns last TABLE_ROWS_LIMIT rows.
|
|
716
|
+
*
|
|
717
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
718
|
+
* @param candles - Array of 1-hour candle data
|
|
719
|
+
* @returns Array of technical analysis rows with all indicators
|
|
720
|
+
*
|
|
721
|
+
* @example
|
|
722
|
+
* ```typescript
|
|
723
|
+
* const candles = await getCandles('BTCUSDT', '1h', 100);
|
|
724
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
725
|
+
* console.log(rows.length); // Up to 48 rows
|
|
726
|
+
* console.log(rows[0].rsi14); // 52.45
|
|
727
|
+
* console.log(rows[0].support); // 42000.50
|
|
728
|
+
* ```
|
|
729
|
+
*/
|
|
525
730
|
this.getData = async (symbol, candles) => {
|
|
526
731
|
this.loggerService.log("longTermHistoryService getData", {
|
|
527
732
|
symbol,
|
|
@@ -529,6 +734,26 @@ class LongTermHistoryService {
|
|
|
529
734
|
});
|
|
530
735
|
return generateAnalysis$3(symbol, candles);
|
|
531
736
|
};
|
|
737
|
+
/**
|
|
738
|
+
* Generates complete markdown technical analysis report for a symbol.
|
|
739
|
+
*
|
|
740
|
+
* Fetches 100 1-hour candles (100 hours) from exchange, calculates all indicators,
|
|
741
|
+
* and formats last 48 rows as markdown table optimized for LLM consumption.
|
|
742
|
+
*
|
|
743
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
744
|
+
* @returns Markdown-formatted technical analysis report with table and explanations
|
|
745
|
+
*
|
|
746
|
+
* @example
|
|
747
|
+
* ```typescript
|
|
748
|
+
* const report = await service.getReport('BTCUSDT');
|
|
749
|
+
* console.log(report);
|
|
750
|
+
* // # 1-Hour Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
751
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
752
|
+
* //
|
|
753
|
+
* // | RSI(14) | MACD(12,26,9) | Support Level | ...
|
|
754
|
+
* // | 52.45 | 0.0023 | 42000.50 USD | ...
|
|
755
|
+
* ```
|
|
756
|
+
*/
|
|
532
757
|
this.getReport = async (symbol) => {
|
|
533
758
|
this.loggerService.log("longTermHistoryService getReport", { symbol });
|
|
534
759
|
const fullCandles = await backtestKit.getCandles(symbol, "1h", 100);
|
|
@@ -537,6 +762,24 @@ class LongTermHistoryService {
|
|
|
537
762
|
const rows = allRows.slice(-TABLE_ROWS_LIMIT$3);
|
|
538
763
|
return generateHistoryTable$3(rows, symbol);
|
|
539
764
|
};
|
|
765
|
+
/**
|
|
766
|
+
* Converts analysis rows into markdown table format.
|
|
767
|
+
*
|
|
768
|
+
* Takes pre-calculated indicator rows and formats them as markdown table
|
|
769
|
+
* with column headers, formatted values, and data source explanations.
|
|
770
|
+
*
|
|
771
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
772
|
+
* @param rows - Array of technical analysis rows from getData()
|
|
773
|
+
* @returns Markdown-formatted table with all indicators
|
|
774
|
+
*
|
|
775
|
+
* @example
|
|
776
|
+
* ```typescript
|
|
777
|
+
* const candles = await getCandles('BTCUSDT', '1h', 100);
|
|
778
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
779
|
+
* const markdown = await service.generateHistoryTable('BTCUSDT', rows);
|
|
780
|
+
* console.log(markdown); // Markdown table
|
|
781
|
+
* ```
|
|
782
|
+
*/
|
|
540
783
|
this.generateHistoryTable = async (symbol, rows) => {
|
|
541
784
|
this.loggerService.log("longTermHistoryService generateHistoryTable", {
|
|
542
785
|
symbol,
|
|
@@ -547,7 +790,27 @@ class LongTermHistoryService {
|
|
|
547
790
|
}
|
|
548
791
|
}
|
|
549
792
|
|
|
793
|
+
/**
|
|
794
|
+
* MicroTerm (1-minute) technical analysis service for scalping strategies.
|
|
795
|
+
*
|
|
796
|
+
* Generates 40+ indicators on 1-minute candles with 60-candle lookback.
|
|
797
|
+
* Optimized for high-frequency trading and sub-5 minute positions.
|
|
798
|
+
*
|
|
799
|
+
* Indicators: RSI(9,14), StochRSI(9,14), MACD(8,21,5), Bollinger(8,2), Stochastic(3,5),
|
|
800
|
+
* ADX(9), ATR(5,9), CCI(9), Momentum(5,10), ROC(1,3,5), EMA(3,8,13,21), SMA(8), DEMA(8),
|
|
801
|
+
* WMA(5), Support/Resistance, Volume analysis, Squeeze momentum.
|
|
802
|
+
*
|
|
803
|
+
* Used by commitMicroTermMath().
|
|
804
|
+
*/
|
|
805
|
+
/**
|
|
806
|
+
* Minimum number of candles required before generating analysis rows.
|
|
807
|
+
* Ensures all technical indicators (especially EMA(21)) have sufficient data.
|
|
808
|
+
*/
|
|
550
809
|
const WARMUP_PERIOD$2 = 21;
|
|
810
|
+
/**
|
|
811
|
+
* Maximum number of historical rows to return in analysis results.
|
|
812
|
+
* Limits memory usage and table size for markdown reports.
|
|
813
|
+
*/
|
|
551
814
|
const TABLE_ROWS_LIMIT$2 = 40;
|
|
552
815
|
const columns$2 = [
|
|
553
816
|
{
|
|
@@ -825,6 +1088,23 @@ const columns$2 = [
|
|
|
825
1088
|
format: (v) => new Date(v).toISOString(),
|
|
826
1089
|
},
|
|
827
1090
|
];
|
|
1091
|
+
/**
|
|
1092
|
+
* Validates whether a numeric value is safe for calculations.
|
|
1093
|
+
*
|
|
1094
|
+
* Checks if value is a valid finite number. Returns true if value is null,
|
|
1095
|
+
* NaN, Infinity, or not a number type.
|
|
1096
|
+
*
|
|
1097
|
+
* @param value - Value to validate
|
|
1098
|
+
* @returns True if value is unsafe (null/NaN/Infinity), false if valid number
|
|
1099
|
+
*
|
|
1100
|
+
* @example
|
|
1101
|
+
* ```typescript
|
|
1102
|
+
* isUnsafe(42) // false - valid number
|
|
1103
|
+
* isUnsafe(null) // true - null value
|
|
1104
|
+
* isUnsafe(NaN) // true - not a number
|
|
1105
|
+
* isUnsafe(Infinity) // true - infinite value
|
|
1106
|
+
* ```
|
|
1107
|
+
*/
|
|
828
1108
|
function isUnsafe$3(value) {
|
|
829
1109
|
if (typeof value !== "number") {
|
|
830
1110
|
return true;
|
|
@@ -837,6 +1117,25 @@ function isUnsafe$3(value) {
|
|
|
837
1117
|
}
|
|
838
1118
|
return false;
|
|
839
1119
|
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Calculates volume metrics including SMA, ratio, and trend.
|
|
1122
|
+
*
|
|
1123
|
+
* Computes volume SMA(5), current volume to average ratio, and volume trend
|
|
1124
|
+
* by comparing recent 3 candles to previous 3 candles. Returns "increasing"
|
|
1125
|
+
* if recent average > 120% of previous, "decreasing" if < 80%, else "stable".
|
|
1126
|
+
*
|
|
1127
|
+
* @param candles - Array of candle data
|
|
1128
|
+
* @param endIndex - Index of current candle in array
|
|
1129
|
+
* @returns Object with volumeSma5, volumeRatio, and volumeTrend
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
* ```typescript
|
|
1133
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1134
|
+
* const metrics = calculateVolumeMetrics(candles, 59);
|
|
1135
|
+
* console.log(metrics);
|
|
1136
|
+
* // { volumeSma5: 1500000, volumeRatio: 1.25, volumeTrend: "increasing" }
|
|
1137
|
+
* ```
|
|
1138
|
+
*/
|
|
840
1139
|
function calculateVolumeMetrics(candles, endIndex) {
|
|
841
1140
|
const volumes = candles.slice(0, endIndex + 1).map((c) => Number(c.volume));
|
|
842
1141
|
if (volumes.length < 5) {
|
|
@@ -863,6 +1162,24 @@ function calculateVolumeMetrics(candles, endIndex) {
|
|
|
863
1162
|
}
|
|
864
1163
|
return { volumeSma5: avgVolume, volumeRatio, volumeTrend };
|
|
865
1164
|
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Calculates price change percentages over 1, 3, and 5 minute periods.
|
|
1167
|
+
*
|
|
1168
|
+
* Computes percentage price changes from current price to prices at
|
|
1169
|
+
* 1, 3, and 5 candles ago. Returns null for periods with insufficient data.
|
|
1170
|
+
*
|
|
1171
|
+
* @param candles - Array of candle data
|
|
1172
|
+
* @param endIndex - Index of current candle in array
|
|
1173
|
+
* @returns Object with priceChange1m, priceChange3m, and priceChange5m percentages
|
|
1174
|
+
*
|
|
1175
|
+
* @example
|
|
1176
|
+
* ```typescript
|
|
1177
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1178
|
+
* const changes = calculatePriceChanges(candles, 59);
|
|
1179
|
+
* console.log(changes);
|
|
1180
|
+
* // { priceChange1m: 0.05, priceChange3m: 0.12, priceChange5m: -0.08 }
|
|
1181
|
+
* ```
|
|
1182
|
+
*/
|
|
866
1183
|
function calculatePriceChanges(candles, endIndex) {
|
|
867
1184
|
const closes = candles.slice(0, endIndex + 1).map((c) => Number(c.close));
|
|
868
1185
|
if (closes.length < 2) {
|
|
@@ -883,6 +1200,26 @@ function calculatePriceChanges(candles, endIndex) {
|
|
|
883
1200
|
: null;
|
|
884
1201
|
return { priceChange1m, priceChange3m, priceChange5m };
|
|
885
1202
|
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Calculates support and resistance levels from recent high/low prices.
|
|
1205
|
+
*
|
|
1206
|
+
* Identifies support (minimum low) and resistance (maximum high) levels
|
|
1207
|
+
* over last 30 candles. Uses minimum distance threshold (0.3% of current price)
|
|
1208
|
+
* to filter significant levels. Falls back to current price if insufficient data.
|
|
1209
|
+
*
|
|
1210
|
+
* @param candles - Array of candle data
|
|
1211
|
+
* @param endIndex - Index of current candle in array
|
|
1212
|
+
* @param currentPrice - Current price for distance calculations
|
|
1213
|
+
* @returns Object with support and resistance price levels
|
|
1214
|
+
*
|
|
1215
|
+
* @example
|
|
1216
|
+
* ```typescript
|
|
1217
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1218
|
+
* const levels = calculateSupportResistance(candles, 59, 42500);
|
|
1219
|
+
* console.log(levels);
|
|
1220
|
+
* // { support: 42400.50, resistance: 42600.75 }
|
|
1221
|
+
* ```
|
|
1222
|
+
*/
|
|
886
1223
|
function calculateSupportResistance$1(candles, endIndex, currentPrice) {
|
|
887
1224
|
const recentPeriod = Math.min(30, endIndex + 1);
|
|
888
1225
|
const startIdx = endIndex + 1 - recentPeriod;
|
|
@@ -913,6 +1250,32 @@ function calculateSupportResistance$1(candles, endIndex, currentPrice) {
|
|
|
913
1250
|
: currentPrice;
|
|
914
1251
|
return { support, resistance };
|
|
915
1252
|
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Generates comprehensive technical analysis for 1-minute candles (scalping).
|
|
1255
|
+
*
|
|
1256
|
+
* Calculates 40+ technical indicators per candle including:
|
|
1257
|
+
* - Momentum: RSI(9,14), Stochastic RSI(9,14), MACD(8,21,5), Momentum(5,10), ROC(1,3,5)
|
|
1258
|
+
* - Trend: EMA(3,8,13,21), SMA(8), DEMA(8), WMA(5), ADX(9), +DI/-DI
|
|
1259
|
+
* - Volatility: ATR(5,9), Bollinger Bands(8,2.0), volatility(5), true range
|
|
1260
|
+
* - Volume: Volume SMA(5), volume ratio, volume trend
|
|
1261
|
+
* - Support/Resistance: Pivot points over 30 candles
|
|
1262
|
+
* - Special: Squeeze momentum, pressure index, Bollinger position
|
|
1263
|
+
*
|
|
1264
|
+
* Skips first WARMUP_PERIOD (21) candles to ensure indicator stability.
|
|
1265
|
+
* Returns last TABLE_ROWS_LIMIT (40) rows for memory efficiency.
|
|
1266
|
+
*
|
|
1267
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1268
|
+
* @param candles - Array of 1-minute candle data
|
|
1269
|
+
* @returns Array of technical analysis rows with all indicators
|
|
1270
|
+
*
|
|
1271
|
+
* @example
|
|
1272
|
+
* ```typescript
|
|
1273
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1274
|
+
* const analysis = generateAnalysis('BTCUSDT', candles);
|
|
1275
|
+
* console.log(analysis[0].rsi9); // 45.23
|
|
1276
|
+
* console.log(analysis[0].squeezeMomentum); // 1.25
|
|
1277
|
+
* ```
|
|
1278
|
+
*/
|
|
916
1279
|
function generateAnalysis$2(symbol, candles) {
|
|
917
1280
|
const closes = candles.map((candle) => Number(candle.close));
|
|
918
1281
|
const highs = candles.map((candle) => Number(candle.high));
|
|
@@ -1157,6 +1520,32 @@ function generateAnalysis$2(symbol, candles) {
|
|
|
1157
1520
|
// Return only the last TABLE_ROWS_LIMIT rows
|
|
1158
1521
|
return results.slice(-TABLE_ROWS_LIMIT$2);
|
|
1159
1522
|
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Generates markdown table with micro-term technical analysis history.
|
|
1525
|
+
*
|
|
1526
|
+
* Creates comprehensive markdown report with:
|
|
1527
|
+
* - Formatted table of all 40+ technical indicators
|
|
1528
|
+
* - Column headers with indicator names and parameters
|
|
1529
|
+
* - Formatted values (prices in USD, percentages, decimals)
|
|
1530
|
+
* - Data sources section explaining each indicator's calculation
|
|
1531
|
+
* - Timeframe and lookback period documentation (1m candles, 60m lookback)
|
|
1532
|
+
*
|
|
1533
|
+
* Output is optimized for LLM consumption in scalping signal generation.
|
|
1534
|
+
*
|
|
1535
|
+
* @param indicators - Array of analysis rows from generateAnalysis()
|
|
1536
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
1537
|
+
* @returns Markdown-formatted technical analysis report
|
|
1538
|
+
*
|
|
1539
|
+
* @example
|
|
1540
|
+
* ```typescript
|
|
1541
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
1542
|
+
* const markdown = await generateHistoryTable(rows, 'BTCUSDT');
|
|
1543
|
+
* console.log(markdown);
|
|
1544
|
+
* // # 1-Minute Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
1545
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
1546
|
+
* // | RSI(9) | MACD(8,21,5) | Squeeze Momentum | ... |
|
|
1547
|
+
* ```
|
|
1548
|
+
*/
|
|
1160
1549
|
async function generateHistoryTable$2(indicators, symbol) {
|
|
1161
1550
|
let markdown = "";
|
|
1162
1551
|
const currentData = await backtestKit.getDate();
|
|
@@ -1271,9 +1660,64 @@ async function generateHistoryTable$2(indicators, symbol) {
|
|
|
1271
1660
|
"- **Close Price**: close price at row timestamp (Min: 0 USD, Max: +∞ USD)\n";
|
|
1272
1661
|
return markdown;
|
|
1273
1662
|
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Service for micro-term (1-minute) technical analysis and markdown report generation.
|
|
1665
|
+
*
|
|
1666
|
+
* Provides comprehensive technical analysis for 1-minute candles with 40+ indicators
|
|
1667
|
+
* including momentum (RSI, MACD), trend (EMA, SMA), volatility (ATR, Bollinger Bands),
|
|
1668
|
+
* support/resistance levels, volume analysis, and specialized scalping indicators.
|
|
1669
|
+
*
|
|
1670
|
+
* Key features:
|
|
1671
|
+
* - 40+ technical indicators (RSI, MACD, Bollinger Bands, Stochastic, ADX, etc.)
|
|
1672
|
+
* - Support/resistance level detection (30-candle lookback)
|
|
1673
|
+
* - Volume analysis (SMA, ratio, trend)
|
|
1674
|
+
* - Price change tracking (1m, 3m, 5m)
|
|
1675
|
+
* - Specialized scalping indicators (squeeze momentum, pressure index, Bollinger position)
|
|
1676
|
+
* - Volatility and true range calculations
|
|
1677
|
+
* - Markdown table generation for LLM consumption
|
|
1678
|
+
* - Intelligent indicator warmup (skips first 21 candles)
|
|
1679
|
+
* - Memory-efficient output (last 40 rows only)
|
|
1680
|
+
* - Dependency injection support
|
|
1681
|
+
*
|
|
1682
|
+
* @example
|
|
1683
|
+
* ```typescript
|
|
1684
|
+
* import { MicroTermHistoryService } from '@backtest-kit/signals';
|
|
1685
|
+
*
|
|
1686
|
+
* const service = new MicroTermHistoryService();
|
|
1687
|
+
*
|
|
1688
|
+
* // Get markdown report for symbol (fetches candles internally)
|
|
1689
|
+
* const report = await service.getReport('BTCUSDT');
|
|
1690
|
+
* console.log(report); // Markdown table with all indicators
|
|
1691
|
+
*
|
|
1692
|
+
* // Or analyze custom candles
|
|
1693
|
+
* const candles = await getCandles('ETHUSDT', '1m', 60);
|
|
1694
|
+
* const rows = await service.getData('ETHUSDT', candles);
|
|
1695
|
+
* console.log(rows[0].rsi9); // 45.23
|
|
1696
|
+
* console.log(rows[0].squeezeMomentum); // 1.25
|
|
1697
|
+
* ```
|
|
1698
|
+
*/
|
|
1274
1699
|
class MicroTermHistoryService {
|
|
1275
1700
|
constructor() {
|
|
1276
1701
|
this.loggerService = inject(TYPES.loggerService);
|
|
1702
|
+
/**
|
|
1703
|
+
* Analyzes candle data and returns technical indicator rows.
|
|
1704
|
+
*
|
|
1705
|
+
* Calculates all technical indicators for provided candles, skips first WARMUP_PERIOD
|
|
1706
|
+
* rows to ensure stability, and returns last TABLE_ROWS_LIMIT rows.
|
|
1707
|
+
*
|
|
1708
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1709
|
+
* @param candles - Array of 1-minute candle data
|
|
1710
|
+
* @returns Array of technical analysis rows with all indicators
|
|
1711
|
+
*
|
|
1712
|
+
* @example
|
|
1713
|
+
* ```typescript
|
|
1714
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1715
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
1716
|
+
* console.log(rows.length); // Up to 40 rows
|
|
1717
|
+
* console.log(rows[0].rsi9); // 45.23
|
|
1718
|
+
* console.log(rows[0].volumeRatio); // 1.25
|
|
1719
|
+
* ```
|
|
1720
|
+
*/
|
|
1277
1721
|
this.getData = async (symbol, candles) => {
|
|
1278
1722
|
this.loggerService.log("microTermHistoryService getData", {
|
|
1279
1723
|
symbol,
|
|
@@ -1281,12 +1725,50 @@ class MicroTermHistoryService {
|
|
|
1281
1725
|
});
|
|
1282
1726
|
return generateAnalysis$2(symbol, candles);
|
|
1283
1727
|
};
|
|
1728
|
+
/**
|
|
1729
|
+
* Generates complete markdown technical analysis report for a symbol.
|
|
1730
|
+
*
|
|
1731
|
+
* Fetches 60 1-minute candles (60 minutes) from exchange, calculates all indicators,
|
|
1732
|
+
* and formats results as markdown table optimized for LLM consumption.
|
|
1733
|
+
*
|
|
1734
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1735
|
+
* @returns Markdown-formatted technical analysis report with table and explanations
|
|
1736
|
+
*
|
|
1737
|
+
* @example
|
|
1738
|
+
* ```typescript
|
|
1739
|
+
* const report = await service.getReport('BTCUSDT');
|
|
1740
|
+
* console.log(report);
|
|
1741
|
+
* // # 1-Minute Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
1742
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
1743
|
+
* //
|
|
1744
|
+
* // | RSI(9) | MACD(8,21,5) | Squeeze Momentum | ...
|
|
1745
|
+
* // | 45.23 | 0.0012 | 1.25 | ...
|
|
1746
|
+
* ```
|
|
1747
|
+
*/
|
|
1284
1748
|
this.getReport = async (symbol) => {
|
|
1285
1749
|
this.loggerService.log("microTermHistoryService getReport", { symbol });
|
|
1286
1750
|
const candles = await backtestKit.getCandles(symbol, "1m", 60);
|
|
1287
1751
|
const rows = await this.getData(symbol, candles);
|
|
1288
1752
|
return generateHistoryTable$2(rows, symbol);
|
|
1289
1753
|
};
|
|
1754
|
+
/**
|
|
1755
|
+
* Converts analysis rows into markdown table format.
|
|
1756
|
+
*
|
|
1757
|
+
* Takes pre-calculated indicator rows and formats them as markdown table
|
|
1758
|
+
* with column headers, formatted values, and data source explanations.
|
|
1759
|
+
*
|
|
1760
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
1761
|
+
* @param rows - Array of technical analysis rows from getData()
|
|
1762
|
+
* @returns Markdown-formatted table with all indicators
|
|
1763
|
+
*
|
|
1764
|
+
* @example
|
|
1765
|
+
* ```typescript
|
|
1766
|
+
* const candles = await getCandles('BTCUSDT', '1m', 60);
|
|
1767
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
1768
|
+
* const markdown = await service.generateHistoryTable('BTCUSDT', rows);
|
|
1769
|
+
* console.log(markdown); // Markdown table
|
|
1770
|
+
* ```
|
|
1771
|
+
*/
|
|
1290
1772
|
this.generateHistoryTable = async (symbol, rows) => {
|
|
1291
1773
|
this.loggerService.log("microTermHistoryService generateHistoryTable", {
|
|
1292
1774
|
symbol,
|
|
@@ -1297,7 +1779,15 @@ class MicroTermHistoryService {
|
|
|
1297
1779
|
}
|
|
1298
1780
|
}
|
|
1299
1781
|
|
|
1782
|
+
/**
|
|
1783
|
+
* Maximum number of historical rows to return in analysis results.
|
|
1784
|
+
* Limits memory usage and table size for markdown reports.
|
|
1785
|
+
*/
|
|
1300
1786
|
const TABLE_ROWS_LIMIT$1 = 48;
|
|
1787
|
+
/**
|
|
1788
|
+
* Minimum number of candles required before generating analysis rows.
|
|
1789
|
+
* Ensures all technical indicators (especially SMA(50)) have sufficient data.
|
|
1790
|
+
*/
|
|
1301
1791
|
const WARMUP_PERIOD$1 = 50;
|
|
1302
1792
|
const columns$1 = [
|
|
1303
1793
|
{
|
|
@@ -1485,6 +1975,23 @@ const columns$1 = [
|
|
|
1485
1975
|
format: (v) => new Date(v).toISOString(),
|
|
1486
1976
|
},
|
|
1487
1977
|
];
|
|
1978
|
+
/**
|
|
1979
|
+
* Validates whether a numeric value is safe for calculations.
|
|
1980
|
+
*
|
|
1981
|
+
* Checks if value is a valid finite number. Returns true if value is null,
|
|
1982
|
+
* NaN, Infinity, or not a number type.
|
|
1983
|
+
*
|
|
1984
|
+
* @param value - Value to validate
|
|
1985
|
+
* @returns True if value is unsafe (null/NaN/Infinity), false if valid number
|
|
1986
|
+
*
|
|
1987
|
+
* @example
|
|
1988
|
+
* ```typescript
|
|
1989
|
+
* isUnsafe(42) // false - valid number
|
|
1990
|
+
* isUnsafe(null) // true - null value
|
|
1991
|
+
* isUnsafe(NaN) // true - not a number
|
|
1992
|
+
* isUnsafe(Infinity) // true - infinite value
|
|
1993
|
+
* ```
|
|
1994
|
+
*/
|
|
1488
1995
|
function isUnsafe$2(value) {
|
|
1489
1996
|
if (typeof value !== "number") {
|
|
1490
1997
|
return true;
|
|
@@ -1497,6 +2004,25 @@ function isUnsafe$2(value) {
|
|
|
1497
2004
|
}
|
|
1498
2005
|
return false;
|
|
1499
2006
|
}
|
|
2007
|
+
/**
|
|
2008
|
+
* Calculates Fibonacci retracement levels and finds nearest level to current price.
|
|
2009
|
+
*
|
|
2010
|
+
* Computes standard Fibonacci levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%)
|
|
2011
|
+
* plus extension levels (127.2%, 161.8%) based on high-low range over lookback period.
|
|
2012
|
+
* Returns the level closest to current price with distance in USD.
|
|
2013
|
+
*
|
|
2014
|
+
* @param candles - Array of candle data
|
|
2015
|
+
* @param endIndex - Index of current candle in array
|
|
2016
|
+
* @returns Object with nearest level name, price, and distance in USD
|
|
2017
|
+
*
|
|
2018
|
+
* @example
|
|
2019
|
+
* ```typescript
|
|
2020
|
+
* const candles = await getCandles('BTCUSDT', '15m', 300);
|
|
2021
|
+
* const fib = calculateFibonacciLevels(candles, 299);
|
|
2022
|
+
* console.log(fib);
|
|
2023
|
+
* // { level: "61.8%", price: 42500.50, distance: 125.30 }
|
|
2024
|
+
* ```
|
|
2025
|
+
*/
|
|
1500
2026
|
function calculateFibonacciLevels$1(candles, endIndex) {
|
|
1501
2027
|
const lookbackPeriod = Math.min(288, endIndex + 1);
|
|
1502
2028
|
const startIndex = endIndex + 1 - lookbackPeriod;
|
|
@@ -1529,6 +2055,24 @@ function calculateFibonacciLevels$1(candles, endIndex) {
|
|
|
1529
2055
|
});
|
|
1530
2056
|
return nearestLevel;
|
|
1531
2057
|
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Analyzes volume trend by comparing recent vs older volume averages.
|
|
2060
|
+
*
|
|
2061
|
+
* Compares average volume of last 8 candles against previous 8 candles.
|
|
2062
|
+
* Returns "increasing" if recent volume > 120% of older volume,
|
|
2063
|
+
* "decreasing" if recent < 80% of older volume, otherwise "stable".
|
|
2064
|
+
*
|
|
2065
|
+
* @param candles - Array of candle data
|
|
2066
|
+
* @param endIndex - Index of current candle in array
|
|
2067
|
+
* @returns Volume trend: "increasing", "decreasing", or "stable"
|
|
2068
|
+
*
|
|
2069
|
+
* @example
|
|
2070
|
+
* ```typescript
|
|
2071
|
+
* const candles = await getCandles('ETHUSDT', '15m', 100);
|
|
2072
|
+
* const trend = calculateVolumeTrend(candles, 99);
|
|
2073
|
+
* console.log(trend); // "increasing" | "decreasing" | "stable"
|
|
2074
|
+
* ```
|
|
2075
|
+
*/
|
|
1532
2076
|
function calculateVolumeTrend(candles, endIndex) {
|
|
1533
2077
|
const volumes = candles.slice(0, endIndex + 1).map((c) => Number(c.volume));
|
|
1534
2078
|
if (volumes.length < 16)
|
|
@@ -1545,6 +2089,31 @@ function calculateVolumeTrend(candles, endIndex) {
|
|
|
1545
2089
|
return "decreasing";
|
|
1546
2090
|
return "stable";
|
|
1547
2091
|
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Generates comprehensive technical analysis for 15-minute candles.
|
|
2094
|
+
*
|
|
2095
|
+
* Calculates 30+ technical indicators per candle including:
|
|
2096
|
+
* - Momentum: RSI(9), Stochastic RSI(9), MACD(8,21,5), Momentum(8), ROC(5,10)
|
|
2097
|
+
* - Trend: SMA(50), EMA(8,21), DEMA(21), WMA(20), ADX(14), +DI/-DI
|
|
2098
|
+
* - Volatility: ATR(9), Bollinger Bands(10,2.0)
|
|
2099
|
+
* - Volume: Volume trend analysis
|
|
2100
|
+
* - Support/Resistance: Pivot points, Fibonacci levels
|
|
2101
|
+
*
|
|
2102
|
+
* Skips first WARMUP_PERIOD (50) candles to ensure indicator stability.
|
|
2103
|
+
* Returns last TABLE_ROWS_LIMIT (48) rows for memory efficiency.
|
|
2104
|
+
*
|
|
2105
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
2106
|
+
* @param candles - Array of 15-minute candle data
|
|
2107
|
+
* @returns Array of technical analysis rows with all indicators
|
|
2108
|
+
*
|
|
2109
|
+
* @example
|
|
2110
|
+
* ```typescript
|
|
2111
|
+
* const candles = await getCandles('BTCUSDT', '15m', 144);
|
|
2112
|
+
* const analysis = generateAnalysis('BTCUSDT', candles);
|
|
2113
|
+
* console.log(analysis[0].rsi9); // 45.23
|
|
2114
|
+
* console.log(analysis[0].support); // 42000.50
|
|
2115
|
+
* ```
|
|
2116
|
+
*/
|
|
1548
2117
|
function generateAnalysis$1(symbol, candles) {
|
|
1549
2118
|
const closes = candles.map((candle) => Number(candle.close));
|
|
1550
2119
|
const highs = candles.map((candle) => Number(candle.high));
|
|
@@ -1722,6 +2291,32 @@ function generateAnalysis$1(symbol, candles) {
|
|
|
1722
2291
|
// Return only the last TABLE_ROWS_LIMIT rows
|
|
1723
2292
|
return results.slice(-TABLE_ROWS_LIMIT$1);
|
|
1724
2293
|
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Generates markdown table with technical analysis history.
|
|
2296
|
+
*
|
|
2297
|
+
* Creates comprehensive markdown report with:
|
|
2298
|
+
* - Formatted table of all technical indicators
|
|
2299
|
+
* - Column headers with indicator names and parameters
|
|
2300
|
+
* - Formatted values (prices in USD, percentages, decimals)
|
|
2301
|
+
* - Data sources section explaining each indicator's calculation
|
|
2302
|
+
* - Timeframe and lookback period documentation
|
|
2303
|
+
*
|
|
2304
|
+
* Output is optimized for LLM consumption in trading signal generation.
|
|
2305
|
+
*
|
|
2306
|
+
* @param indicators - Array of analysis rows from generateAnalysis()
|
|
2307
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
2308
|
+
* @returns Markdown-formatted technical analysis report
|
|
2309
|
+
*
|
|
2310
|
+
* @example
|
|
2311
|
+
* ```typescript
|
|
2312
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
2313
|
+
* const markdown = await generateHistoryTable(rows, 'BTCUSDT');
|
|
2314
|
+
* console.log(markdown);
|
|
2315
|
+
* // # 15-Minute Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
2316
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
2317
|
+
* // | RSI(9) | MACD(8,21,5) | ... |
|
|
2318
|
+
* ```
|
|
2319
|
+
*/
|
|
1725
2320
|
async function generateHistoryTable$1(indicators, symbol) {
|
|
1726
2321
|
let markdown = "";
|
|
1727
2322
|
const currentData = await backtestKit.getDate();
|
|
@@ -1804,9 +2399,61 @@ async function generateHistoryTable$1(indicators, symbol) {
|
|
|
1804
2399
|
"- **Close Price**: close price at row timestamp (Min: 0 USD, Max: +∞ USD)\n";
|
|
1805
2400
|
return markdown;
|
|
1806
2401
|
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Service for short-term (15-minute) technical analysis and markdown report generation.
|
|
2404
|
+
*
|
|
2405
|
+
* Provides comprehensive technical analysis for 15-minute candles with 30+ indicators
|
|
2406
|
+
* including momentum (RSI, MACD), trend (EMA, SMA), volatility (ATR, Bollinger Bands),
|
|
2407
|
+
* support/resistance levels, and Fibonacci retracements.
|
|
2408
|
+
*
|
|
2409
|
+
* Key features:
|
|
2410
|
+
* - 30+ technical indicators (RSI, MACD, Bollinger Bands, Stochastic, ADX, etc.)
|
|
2411
|
+
* - Support/resistance level detection
|
|
2412
|
+
* - Fibonacci retracement analysis
|
|
2413
|
+
* - Volume trend analysis
|
|
2414
|
+
* - Markdown table generation for LLM consumption
|
|
2415
|
+
* - Intelligent indicator warmup (skips first 50 candles)
|
|
2416
|
+
* - Memory-efficient output (last 48 rows only)
|
|
2417
|
+
* - Dependency injection support
|
|
2418
|
+
*
|
|
2419
|
+
* @example
|
|
2420
|
+
* ```typescript
|
|
2421
|
+
* import { ShortTermHistoryService } from '@backtest-kit/signals';
|
|
2422
|
+
*
|
|
2423
|
+
* const service = new ShortTermHistoryService();
|
|
2424
|
+
*
|
|
2425
|
+
* // Get markdown report for symbol (fetches candles internally)
|
|
2426
|
+
* const report = await service.getReport('BTCUSDT');
|
|
2427
|
+
* console.log(report); // Markdown table with all indicators
|
|
2428
|
+
*
|
|
2429
|
+
* // Or analyze custom candles
|
|
2430
|
+
* const candles = await getCandles('ETHUSDT', '15m', 144);
|
|
2431
|
+
* const rows = await service.getData('ETHUSDT', candles);
|
|
2432
|
+
* console.log(rows[0].rsi9); // 45.23
|
|
2433
|
+
* ```
|
|
2434
|
+
*/
|
|
1807
2435
|
class ShortTermHistoryService {
|
|
1808
2436
|
constructor() {
|
|
1809
2437
|
this.loggerService = inject(TYPES.loggerService);
|
|
2438
|
+
/**
|
|
2439
|
+
* Analyzes candle data and returns technical indicator rows.
|
|
2440
|
+
*
|
|
2441
|
+
* Calculates all technical indicators for provided candles, skips first WARMUP_PERIOD
|
|
2442
|
+
* rows to ensure stability, and returns last TABLE_ROWS_LIMIT rows.
|
|
2443
|
+
*
|
|
2444
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
2445
|
+
* @param candles - Array of 15-minute candle data
|
|
2446
|
+
* @returns Array of technical analysis rows with all indicators
|
|
2447
|
+
*
|
|
2448
|
+
* @example
|
|
2449
|
+
* ```typescript
|
|
2450
|
+
* const candles = await getCandles('BTCUSDT', '15m', 144);
|
|
2451
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
2452
|
+
* console.log(rows.length); // Up to 48 rows
|
|
2453
|
+
* console.log(rows[0].rsi9); // 45.23
|
|
2454
|
+
* console.log(rows[0].support); // 42000.50
|
|
2455
|
+
* ```
|
|
2456
|
+
*/
|
|
1810
2457
|
this.getData = async (symbol, candles) => {
|
|
1811
2458
|
this.loggerService.log("shortTermHistoryService getData", {
|
|
1812
2459
|
symbol,
|
|
@@ -1814,12 +2461,50 @@ class ShortTermHistoryService {
|
|
|
1814
2461
|
});
|
|
1815
2462
|
return generateAnalysis$1(symbol, candles);
|
|
1816
2463
|
};
|
|
2464
|
+
/**
|
|
2465
|
+
* Generates complete markdown technical analysis report for a symbol.
|
|
2466
|
+
*
|
|
2467
|
+
* Fetches 144 15-minute candles (36 hours) from exchange, calculates all indicators,
|
|
2468
|
+
* and formats results as markdown table optimized for LLM consumption.
|
|
2469
|
+
*
|
|
2470
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
2471
|
+
* @returns Markdown-formatted technical analysis report with table and explanations
|
|
2472
|
+
*
|
|
2473
|
+
* @example
|
|
2474
|
+
* ```typescript
|
|
2475
|
+
* const report = await service.getReport('BTCUSDT');
|
|
2476
|
+
* console.log(report);
|
|
2477
|
+
* // # 15-Minute Candles Trading Analysis for BTCUSDT (Historical Data)
|
|
2478
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
2479
|
+
* //
|
|
2480
|
+
* // | RSI(9) | MACD(8,21,5) | Support Level | ...
|
|
2481
|
+
* // | 45.23 | 0.0012 | 42000.50 USD | ...
|
|
2482
|
+
* ```
|
|
2483
|
+
*/
|
|
1817
2484
|
this.getReport = async (symbol) => {
|
|
1818
2485
|
this.loggerService.log("shortTermHistoryService getReport", { symbol });
|
|
1819
2486
|
const candles = await backtestKit.getCandles(symbol, "15m", 144);
|
|
1820
2487
|
const rows = await this.getData(symbol, candles);
|
|
1821
2488
|
return generateHistoryTable$1(rows, symbol);
|
|
1822
2489
|
};
|
|
2490
|
+
/**
|
|
2491
|
+
* Converts analysis rows into markdown table format.
|
|
2492
|
+
*
|
|
2493
|
+
* Takes pre-calculated indicator rows and formats them as markdown table
|
|
2494
|
+
* with column headers, formatted values, and data source explanations.
|
|
2495
|
+
*
|
|
2496
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
2497
|
+
* @param rows - Array of technical analysis rows from getData()
|
|
2498
|
+
* @returns Markdown-formatted table with all indicators
|
|
2499
|
+
*
|
|
2500
|
+
* @example
|
|
2501
|
+
* ```typescript
|
|
2502
|
+
* const candles = await getCandles('BTCUSDT', '15m', 144);
|
|
2503
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
2504
|
+
* const markdown = await service.generateHistoryTable('BTCUSDT', rows);
|
|
2505
|
+
* console.log(markdown); // Markdown table
|
|
2506
|
+
* ```
|
|
2507
|
+
*/
|
|
1823
2508
|
this.generateHistoryTable = async (symbol, rows) => {
|
|
1824
2509
|
this.loggerService.log("shortTermHistoryService generateHistoryTable", {
|
|
1825
2510
|
symbol,
|
|
@@ -1830,7 +2515,15 @@ class ShortTermHistoryService {
|
|
|
1830
2515
|
}
|
|
1831
2516
|
}
|
|
1832
2517
|
|
|
2518
|
+
/**
|
|
2519
|
+
* Maximum number of historical rows to return in analysis results.
|
|
2520
|
+
* Limits memory usage and table size for markdown reports.
|
|
2521
|
+
*/
|
|
1833
2522
|
const TABLE_ROWS_LIMIT = 30;
|
|
2523
|
+
/**
|
|
2524
|
+
* Minimum number of candles required before generating analysis rows.
|
|
2525
|
+
* Ensures all technical indicators (especially EMA(34)) have sufficient data.
|
|
2526
|
+
*/
|
|
1834
2527
|
const WARMUP_PERIOD = 34;
|
|
1835
2528
|
const columns = [
|
|
1836
2529
|
{
|
|
@@ -2029,6 +2722,23 @@ const columns = [
|
|
|
2029
2722
|
format: (v) => new Date(v).toISOString(),
|
|
2030
2723
|
},
|
|
2031
2724
|
];
|
|
2725
|
+
/**
|
|
2726
|
+
* Validates whether a numeric value is safe for calculations.
|
|
2727
|
+
*
|
|
2728
|
+
* Checks if value is a valid finite number. Returns true if value is null,
|
|
2729
|
+
* NaN, Infinity, or not a number type.
|
|
2730
|
+
*
|
|
2731
|
+
* @param value - Value to validate
|
|
2732
|
+
* @returns True if value is unsafe (null/NaN/Infinity), false if valid number
|
|
2733
|
+
*
|
|
2734
|
+
* @example
|
|
2735
|
+
* ```typescript
|
|
2736
|
+
* isUnsafe(42) // false - valid number
|
|
2737
|
+
* isUnsafe(null) // true - null value
|
|
2738
|
+
* isUnsafe(NaN) // true - not a number
|
|
2739
|
+
* isUnsafe(Infinity) // true - infinite value
|
|
2740
|
+
* ```
|
|
2741
|
+
*/
|
|
2032
2742
|
function isUnsafe$1(value) {
|
|
2033
2743
|
if (typeof value !== "number") {
|
|
2034
2744
|
return true;
|
|
@@ -2041,6 +2751,31 @@ function isUnsafe$1(value) {
|
|
|
2041
2751
|
}
|
|
2042
2752
|
return false;
|
|
2043
2753
|
}
|
|
2754
|
+
/**
|
|
2755
|
+
* Calculates Fibonacci levels and determines nearest support/resistance levels.
|
|
2756
|
+
*
|
|
2757
|
+
* Computes Fibonacci retracement levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%)
|
|
2758
|
+
* and extension levels (127.2%, 161.8%, 261.8%) over specified lookback period.
|
|
2759
|
+
* Identifies current price position relative to Fibonacci levels and finds
|
|
2760
|
+
* nearest support/resistance levels.
|
|
2761
|
+
*
|
|
2762
|
+
* @param candles - Array of candle data
|
|
2763
|
+
* @param endIndex - Index of current candle in array
|
|
2764
|
+
* @param period - Lookback period in candles (default: 48)
|
|
2765
|
+
* @returns Object with nearest support/resistance prices and current level description
|
|
2766
|
+
*
|
|
2767
|
+
* @example
|
|
2768
|
+
* ```typescript
|
|
2769
|
+
* const candles = await getCandles('BTCUSDT', '30m', 96);
|
|
2770
|
+
* const fib = calculateFibonacciLevels(candles, 95, 48);
|
|
2771
|
+
* console.log(fib);
|
|
2772
|
+
* // {
|
|
2773
|
+
* // nearestSupport: 42000.50,
|
|
2774
|
+
* // nearestResistance: 43500.25,
|
|
2775
|
+
* // currentLevel: "50.0% Retracement"
|
|
2776
|
+
* // }
|
|
2777
|
+
* ```
|
|
2778
|
+
*/
|
|
2044
2779
|
function calculateFibonacciLevels(candles, endIndex, period = 48) {
|
|
2045
2780
|
if (endIndex + 1 < period) {
|
|
2046
2781
|
return {
|
|
@@ -2127,6 +2862,25 @@ function calculateFibonacciLevels(candles, endIndex, period = 48) {
|
|
|
2127
2862
|
currentLevel,
|
|
2128
2863
|
};
|
|
2129
2864
|
}
|
|
2865
|
+
/**
|
|
2866
|
+
* Calculates support and resistance levels from recent high/low prices.
|
|
2867
|
+
*
|
|
2868
|
+
* Identifies support (minimum low) and resistance (maximum high) levels
|
|
2869
|
+
* over specified window period. Falls back to current price if insufficient data.
|
|
2870
|
+
*
|
|
2871
|
+
* @param candles - Array of candle data
|
|
2872
|
+
* @param endIndex - Index of current candle in array
|
|
2873
|
+
* @param window - Lookback window in candles (default: 20)
|
|
2874
|
+
* @returns Object with support and resistance price levels
|
|
2875
|
+
*
|
|
2876
|
+
* @example
|
|
2877
|
+
* ```typescript
|
|
2878
|
+
* const candles = await getCandles('ETHUSDT', '30m', 96);
|
|
2879
|
+
* const levels = calculateSupportResistance(candles, 95, 20);
|
|
2880
|
+
* console.log(levels);
|
|
2881
|
+
* // { support: 2200.50, resistance: 2350.75 }
|
|
2882
|
+
* ```
|
|
2883
|
+
*/
|
|
2130
2884
|
function calculateSupportResistance(candles, endIndex, window = 20) {
|
|
2131
2885
|
const startIdx = Math.max(0, endIndex + 1 - window);
|
|
2132
2886
|
const recentHighs = candles
|
|
@@ -2142,6 +2896,31 @@ function calculateSupportResistance(candles, endIndex, window = 20) {
|
|
|
2142
2896
|
const resistance = recentHighs.length > 0 ? Math.max(...recentHighs) : currentPrice;
|
|
2143
2897
|
return { support, resistance };
|
|
2144
2898
|
}
|
|
2899
|
+
/**
|
|
2900
|
+
* Generates comprehensive technical analysis for 30-minute candles (swing trading).
|
|
2901
|
+
*
|
|
2902
|
+
* Calculates 25+ technical indicators per candle including:
|
|
2903
|
+
* - Momentum: RSI(14), Stochastic RSI(14), MACD(12,26,9), Momentum(8), Price Momentum(6)
|
|
2904
|
+
* - Trend: SMA(20), EMA(13,34), DEMA(21), WMA(20), ADX(14), +DI/-DI
|
|
2905
|
+
* - Volatility: ATR(14), Bollinger Bands(20,2.0), calculated volatility
|
|
2906
|
+
* - Support/Resistance: Pivot points, Fibonacci levels with nearest support/resistance
|
|
2907
|
+
* - Volume analysis
|
|
2908
|
+
*
|
|
2909
|
+
* Skips first WARMUP_PERIOD (34) candles to ensure indicator stability.
|
|
2910
|
+
* Returns last TABLE_ROWS_LIMIT (30) rows for memory efficiency.
|
|
2911
|
+
*
|
|
2912
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
2913
|
+
* @param candles - Array of 30-minute candle data
|
|
2914
|
+
* @returns Array of technical analysis rows with all indicators
|
|
2915
|
+
*
|
|
2916
|
+
* @example
|
|
2917
|
+
* ```typescript
|
|
2918
|
+
* const candles = await getCandles('BTCUSDT', '30m', 96);
|
|
2919
|
+
* const analysis = generateAnalysis('BTCUSDT', candles);
|
|
2920
|
+
* console.log(analysis[0].rsi14); // 52.45
|
|
2921
|
+
* console.log(analysis[0].fibonacciCurrentLevel); // "50.0% Retracement"
|
|
2922
|
+
* ```
|
|
2923
|
+
*/
|
|
2145
2924
|
function generateAnalysis(symbol, candles) {
|
|
2146
2925
|
const closes = candles.map((candle) => Number(candle.close));
|
|
2147
2926
|
const highs = candles.map((candle) => Number(candle.high));
|
|
@@ -2318,6 +3097,32 @@ function generateAnalysis(symbol, candles) {
|
|
|
2318
3097
|
// Return only the last TABLE_ROWS_LIMIT rows
|
|
2319
3098
|
return results.slice(-TABLE_ROWS_LIMIT);
|
|
2320
3099
|
}
|
|
3100
|
+
/**
|
|
3101
|
+
* Generates markdown table with swing trading technical analysis history.
|
|
3102
|
+
*
|
|
3103
|
+
* Creates comprehensive markdown report with:
|
|
3104
|
+
* - Formatted table of all technical indicators
|
|
3105
|
+
* - Column headers with indicator names and parameters
|
|
3106
|
+
* - Formatted values (prices in USD, percentages, decimals)
|
|
3107
|
+
* - Data sources section explaining each indicator's calculation
|
|
3108
|
+
* - Timeframe and lookback period documentation (30m candles, 48h lookback)
|
|
3109
|
+
*
|
|
3110
|
+
* Output is optimized for LLM consumption in swing trading signal generation.
|
|
3111
|
+
*
|
|
3112
|
+
* @param indicators - Array of analysis rows from generateAnalysis()
|
|
3113
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3114
|
+
* @returns Markdown-formatted technical analysis report
|
|
3115
|
+
*
|
|
3116
|
+
* @example
|
|
3117
|
+
* ```typescript
|
|
3118
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
3119
|
+
* const markdown = await generateHistoryTable(rows, 'BTCUSDT');
|
|
3120
|
+
* console.log(markdown);
|
|
3121
|
+
* // # 30-Min Candles Analysis for BTCUSDT (Historical Data)
|
|
3122
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3123
|
+
* // | RSI(14) | MACD(12,26,9) | Fibonacci Current Level | ... |
|
|
3124
|
+
* ```
|
|
3125
|
+
*/
|
|
2321
3126
|
async function generateHistoryTable(indicators, symbol) {
|
|
2322
3127
|
let markdown = "";
|
|
2323
3128
|
const currentData = await backtestKit.getDate();
|
|
@@ -2402,9 +3207,63 @@ async function generateHistoryTable(indicators, symbol) {
|
|
|
2402
3207
|
"- **Volatility**: volatility percentage at row timestamp (Min: 0%, Max: +∞)\n";
|
|
2403
3208
|
return markdown;
|
|
2404
3209
|
}
|
|
3210
|
+
/**
|
|
3211
|
+
* Service for swing-term (30-minute) technical analysis and markdown report generation.
|
|
3212
|
+
*
|
|
3213
|
+
* Provides comprehensive technical analysis for 30-minute candles with 25+ indicators
|
|
3214
|
+
* including momentum (RSI, MACD), trend (EMA, SMA), volatility (ATR, Bollinger Bands),
|
|
3215
|
+
* support/resistance levels, and Fibonacci analysis with nearest support/resistance.
|
|
3216
|
+
*
|
|
3217
|
+
* Key features:
|
|
3218
|
+
* - 25+ technical indicators (RSI, MACD, Bollinger Bands, Stochastic, ADX, etc.)
|
|
3219
|
+
* - Support/resistance level detection
|
|
3220
|
+
* - Fibonacci retracement and extension analysis with nearest levels
|
|
3221
|
+
* - Volume and volatility analysis
|
|
3222
|
+
* - Price momentum tracking
|
|
3223
|
+
* - Markdown table generation for LLM consumption
|
|
3224
|
+
* - Intelligent indicator warmup (skips first 34 candles)
|
|
3225
|
+
* - Memory-efficient output (last 30 rows only)
|
|
3226
|
+
* - Dependency injection support
|
|
3227
|
+
*
|
|
3228
|
+
* @example
|
|
3229
|
+
* ```typescript
|
|
3230
|
+
* import { SwingTermHistoryService } from '@backtest-kit/signals';
|
|
3231
|
+
*
|
|
3232
|
+
* const service = new SwingTermHistoryService();
|
|
3233
|
+
*
|
|
3234
|
+
* // Get markdown report for symbol (fetches candles internally)
|
|
3235
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3236
|
+
* console.log(report); // Markdown table with all indicators
|
|
3237
|
+
*
|
|
3238
|
+
* // Or analyze custom candles
|
|
3239
|
+
* const candles = await getCandles('ETHUSDT', '30m', 96);
|
|
3240
|
+
* const rows = await service.getData('ETHUSDT', candles);
|
|
3241
|
+
* console.log(rows[0].rsi14); // 52.45
|
|
3242
|
+
* console.log(rows[0].fibonacciCurrentLevel); // "50.0% Retracement"
|
|
3243
|
+
* ```
|
|
3244
|
+
*/
|
|
2405
3245
|
class SwingTermHistoryService {
|
|
2406
3246
|
constructor() {
|
|
2407
3247
|
this.loggerService = inject(TYPES.loggerService);
|
|
3248
|
+
/**
|
|
3249
|
+
* Analyzes candle data and returns technical indicator rows.
|
|
3250
|
+
*
|
|
3251
|
+
* Calculates all technical indicators for provided candles, skips first WARMUP_PERIOD
|
|
3252
|
+
* rows to ensure stability, and returns last TABLE_ROWS_LIMIT rows.
|
|
3253
|
+
*
|
|
3254
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3255
|
+
* @param candles - Array of 30-minute candle data
|
|
3256
|
+
* @returns Array of technical analysis rows with all indicators
|
|
3257
|
+
*
|
|
3258
|
+
* @example
|
|
3259
|
+
* ```typescript
|
|
3260
|
+
* const candles = await getCandles('BTCUSDT', '30m', 96);
|
|
3261
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
3262
|
+
* console.log(rows.length); // Up to 30 rows
|
|
3263
|
+
* console.log(rows[0].rsi14); // 52.45
|
|
3264
|
+
* console.log(rows[0].fibonacciNearestSupport); // 42000.50
|
|
3265
|
+
* ```
|
|
3266
|
+
*/
|
|
2408
3267
|
this.getData = async (symbol, candles) => {
|
|
2409
3268
|
this.loggerService.log("swingTermHistoryService getData", {
|
|
2410
3269
|
symbol,
|
|
@@ -2412,12 +3271,50 @@ class SwingTermHistoryService {
|
|
|
2412
3271
|
});
|
|
2413
3272
|
return generateAnalysis(symbol, candles);
|
|
2414
3273
|
};
|
|
3274
|
+
/**
|
|
3275
|
+
* Generates complete markdown technical analysis report for a symbol.
|
|
3276
|
+
*
|
|
3277
|
+
* Fetches 96 30-minute candles (48 hours) from exchange, calculates all indicators,
|
|
3278
|
+
* and formats results as markdown table optimized for LLM consumption.
|
|
3279
|
+
*
|
|
3280
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3281
|
+
* @returns Markdown-formatted technical analysis report with table and explanations
|
|
3282
|
+
*
|
|
3283
|
+
* @example
|
|
3284
|
+
* ```typescript
|
|
3285
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3286
|
+
* console.log(report);
|
|
3287
|
+
* // # 30-Min Candles Analysis for BTCUSDT (Historical Data)
|
|
3288
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3289
|
+
* //
|
|
3290
|
+
* // | RSI(14) | MACD(12,26,9) | Fibonacci Current Level | ...
|
|
3291
|
+
* // | 52.45 | 0.0023 | 50.0% Retracement | ...
|
|
3292
|
+
* ```
|
|
3293
|
+
*/
|
|
2415
3294
|
this.getReport = async (symbol) => {
|
|
2416
3295
|
this.loggerService.log("swingTermHistoryService getReport", { symbol });
|
|
2417
3296
|
const candles = await backtestKit.getCandles(symbol, "30m", 96);
|
|
2418
3297
|
const rows = await this.getData(symbol, candles);
|
|
2419
3298
|
return generateHistoryTable(rows, symbol);
|
|
2420
3299
|
};
|
|
3300
|
+
/**
|
|
3301
|
+
* Converts analysis rows into markdown table format.
|
|
3302
|
+
*
|
|
3303
|
+
* Takes pre-calculated indicator rows and formats them as markdown table
|
|
3304
|
+
* with column headers, formatted values, and data source explanations.
|
|
3305
|
+
*
|
|
3306
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3307
|
+
* @param rows - Array of technical analysis rows from getData()
|
|
3308
|
+
* @returns Markdown-formatted table with all indicators
|
|
3309
|
+
*
|
|
3310
|
+
* @example
|
|
3311
|
+
* ```typescript
|
|
3312
|
+
* const candles = await getCandles('BTCUSDT', '30m', 96);
|
|
3313
|
+
* const rows = await service.getData('BTCUSDT', candles);
|
|
3314
|
+
* const markdown = await service.generateHistoryTable('BTCUSDT', rows);
|
|
3315
|
+
* console.log(markdown); // Markdown table
|
|
3316
|
+
* ```
|
|
3317
|
+
*/
|
|
2421
3318
|
this.generateHistoryTable = async (symbol, rows) => {
|
|
2422
3319
|
this.loggerService.log("swingTermHistoryService generateHistoryTable", {
|
|
2423
3320
|
symbol,
|
|
@@ -2428,14 +3325,102 @@ class SwingTermHistoryService {
|
|
|
2428
3325
|
}
|
|
2429
3326
|
}
|
|
2430
3327
|
|
|
3328
|
+
/**
|
|
3329
|
+
* Fifteen-minute candle history service for day trading analysis.
|
|
3330
|
+
*
|
|
3331
|
+
* Generates markdown reports of the last 8 fifteen-minute candles including:
|
|
3332
|
+
* - OHLCV data with high-volatility detection
|
|
3333
|
+
* - Candle type (Green/Red/Doji)
|
|
3334
|
+
* - Volatility percentage (flagged if >1.5x average)
|
|
3335
|
+
* - Body size percentage
|
|
3336
|
+
* - Timestamp
|
|
3337
|
+
*
|
|
3338
|
+
* Used by commitFifteenMinuteHistory() for LLM context injection.
|
|
3339
|
+
*/
|
|
3340
|
+
/**
|
|
3341
|
+
* Number of recent candles to include in history report.
|
|
3342
|
+
* Provides 2-hour price action context for day trading decisions.
|
|
3343
|
+
*/
|
|
2431
3344
|
const RECENT_CANDLES$3 = 8;
|
|
3345
|
+
/**
|
|
3346
|
+
* Service for generating 15-minute candle history reports for day trading analysis.
|
|
3347
|
+
*
|
|
3348
|
+
* Provides detailed OHLCV analysis for the last 8 fifteen-minute candles with
|
|
3349
|
+
* candle pattern identification, volatility metrics, high-volatility detection,
|
|
3350
|
+
* and body size calculations.
|
|
3351
|
+
*
|
|
3352
|
+
* Key features:
|
|
3353
|
+
* - Last 8 fifteen-minute candles (2 hours of price action)
|
|
3354
|
+
* - OHLCV data with formatted prices and volumes
|
|
3355
|
+
* - Candle type identification (Green/Red/Doji)
|
|
3356
|
+
* - Volatility percentage calculations
|
|
3357
|
+
* - High-volatility detection (>1.5x average volatility)
|
|
3358
|
+
* - Body size percentage relative to candle range
|
|
3359
|
+
* - ISO timestamp formatting
|
|
3360
|
+
* - Dependency injection support
|
|
3361
|
+
*
|
|
3362
|
+
* @example
|
|
3363
|
+
* ```typescript
|
|
3364
|
+
* import { FifteenMinuteCandleHistoryService } from '@backtest-kit/signals';
|
|
3365
|
+
*
|
|
3366
|
+
* const service = new FifteenMinuteCandleHistoryService();
|
|
3367
|
+
*
|
|
3368
|
+
* // Get markdown report
|
|
3369
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3370
|
+
* console.log(report);
|
|
3371
|
+
* // ## 15-Minute Candles History (Last 8)
|
|
3372
|
+
* // ### 15m Candle 1 (Green) HIGH-VOLATILITY
|
|
3373
|
+
* // - **Open**: 42000.50 USD
|
|
3374
|
+
* // - **15m Volatility**: 0.85%
|
|
3375
|
+
*
|
|
3376
|
+
* // Or get raw candle data
|
|
3377
|
+
* const candles = await service.getData('ETHUSDT');
|
|
3378
|
+
* console.log(candles.length); // 8
|
|
3379
|
+
* ```
|
|
3380
|
+
*/
|
|
2432
3381
|
class FifteenMinuteCandleHistoryService {
|
|
2433
3382
|
constructor() {
|
|
2434
3383
|
this.loggerService = inject(TYPES.loggerService);
|
|
3384
|
+
/**
|
|
3385
|
+
* Fetches last 8 fifteen-minute candles for a symbol.
|
|
3386
|
+
*
|
|
3387
|
+
* Retrieves recent 15-minute candles from exchange for day trading analysis.
|
|
3388
|
+
*
|
|
3389
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3390
|
+
* @returns Array of 8 fifteen-minute candles
|
|
3391
|
+
*
|
|
3392
|
+
* @example
|
|
3393
|
+
* ```typescript
|
|
3394
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3395
|
+
* console.log(candles.length); // 8
|
|
3396
|
+
* console.log(candles[0].close); // Latest candle close price
|
|
3397
|
+
* ```
|
|
3398
|
+
*/
|
|
2435
3399
|
this.getData = async (symbol) => {
|
|
2436
3400
|
this.loggerService.log("fifteenMinuteCandleHistoryService getData", { symbol });
|
|
2437
3401
|
return backtestKit.getCandles(symbol, "15m", RECENT_CANDLES$3);
|
|
2438
3402
|
};
|
|
3403
|
+
/**
|
|
3404
|
+
* Generates markdown report from candle data with volatility detection.
|
|
3405
|
+
*
|
|
3406
|
+
* Creates detailed markdown report with OHLCV data, candle patterns,
|
|
3407
|
+
* volatility metrics, and HIGH-VOLATILITY flags for candles exceeding
|
|
3408
|
+
* 1.5x the average volatility of all candles.
|
|
3409
|
+
*
|
|
3410
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3411
|
+
* @param candles - Array of candle data to analyze
|
|
3412
|
+
* @returns Markdown-formatted candle history report with volatility flags
|
|
3413
|
+
*
|
|
3414
|
+
* @example
|
|
3415
|
+
* ```typescript
|
|
3416
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3417
|
+
* const report = await service.generateReport('BTCUSDT', candles);
|
|
3418
|
+
* console.log(report);
|
|
3419
|
+
* // ## 15-Minute Candles History (Last 8)
|
|
3420
|
+
* // ### 15m Candle 1 (Green) HIGH-VOLATILITY
|
|
3421
|
+
* // - **Open**: 42000.50 USD
|
|
3422
|
+
* ```
|
|
3423
|
+
*/
|
|
2439
3424
|
this.generateReport = async (symbol, candles) => {
|
|
2440
3425
|
this.loggerService.log("fifteenMinuteCandleHistoryService generateReport", { symbol });
|
|
2441
3426
|
const averageVolatility = candles.reduce((sum, candle) => sum + ((candle.high - candle.low) / candle.close) * 100, 0) / candles.length;
|
|
@@ -2468,6 +3453,28 @@ class FifteenMinuteCandleHistoryService {
|
|
|
2468
3453
|
}
|
|
2469
3454
|
return report;
|
|
2470
3455
|
};
|
|
3456
|
+
/**
|
|
3457
|
+
* Generates complete markdown candle history report for a symbol.
|
|
3458
|
+
*
|
|
3459
|
+
* Fetches last 8 fifteen-minute candles and formats them as markdown report
|
|
3460
|
+
* with OHLCV data, patterns, volatility flags, and metrics.
|
|
3461
|
+
*
|
|
3462
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3463
|
+
* @returns Markdown-formatted candle history report with high-volatility detection
|
|
3464
|
+
*
|
|
3465
|
+
* @example
|
|
3466
|
+
* ```typescript
|
|
3467
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3468
|
+
* console.log(report);
|
|
3469
|
+
* // ## 15-Minute Candles History (Last 8)
|
|
3470
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3471
|
+
* //
|
|
3472
|
+
* // ### 15m Candle 1 (Green) HIGH-VOLATILITY
|
|
3473
|
+
* // - **Time**: 2025-01-14T10:15:00.000Z
|
|
3474
|
+
* // - **Open**: 42000.50 USD
|
|
3475
|
+
* // - **15m Volatility**: 0.85%
|
|
3476
|
+
* ```
|
|
3477
|
+
*/
|
|
2471
3478
|
this.getReport = async (symbol) => {
|
|
2472
3479
|
this.loggerService.log("fifteenMinuteCandleHistoryService getReport", { symbol });
|
|
2473
3480
|
const candles = await this.getData(symbol);
|
|
@@ -2476,14 +3483,99 @@ class FifteenMinuteCandleHistoryService {
|
|
|
2476
3483
|
}
|
|
2477
3484
|
}
|
|
2478
3485
|
|
|
3486
|
+
/**
|
|
3487
|
+
* Hourly candle history service for trend analysis.
|
|
3488
|
+
*
|
|
3489
|
+
* Generates markdown reports of the last 6 hourly candles including:
|
|
3490
|
+
* - OHLCV data
|
|
3491
|
+
* - Candle type (Green/Red/Doji)
|
|
3492
|
+
* - Volatility percentage
|
|
3493
|
+
* - Body size percentage
|
|
3494
|
+
* - Timestamp
|
|
3495
|
+
*
|
|
3496
|
+
* Used by commitHourHistory() for LLM context injection.
|
|
3497
|
+
*/
|
|
3498
|
+
/**
|
|
3499
|
+
* Number of recent candles to include in history report.
|
|
3500
|
+
* Provides 6-hour price action context for long-term trading decisions.
|
|
3501
|
+
*/
|
|
2479
3502
|
const RECENT_CANDLES$2 = 6;
|
|
3503
|
+
/**
|
|
3504
|
+
* Service for generating 1-hour candle history reports for trend analysis.
|
|
3505
|
+
*
|
|
3506
|
+
* Provides detailed OHLCV analysis for the last 6 hourly candles with
|
|
3507
|
+
* candle pattern identification, volatility metrics, and body size calculations.
|
|
3508
|
+
*
|
|
3509
|
+
* Key features:
|
|
3510
|
+
* - Last 6 hourly candles (6 hours of price action)
|
|
3511
|
+
* - OHLCV data with formatted prices and volumes
|
|
3512
|
+
* - Candle type identification (Green/Red/Doji)
|
|
3513
|
+
* - Volatility percentage calculations
|
|
3514
|
+
* - Body size percentage relative to candle range
|
|
3515
|
+
* - ISO timestamp formatting
|
|
3516
|
+
* - Dependency injection support
|
|
3517
|
+
*
|
|
3518
|
+
* @example
|
|
3519
|
+
* ```typescript
|
|
3520
|
+
* import { HourCandleHistoryService } from '@backtest-kit/signals';
|
|
3521
|
+
*
|
|
3522
|
+
* const service = new HourCandleHistoryService();
|
|
3523
|
+
*
|
|
3524
|
+
* // Get markdown report
|
|
3525
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3526
|
+
* console.log(report);
|
|
3527
|
+
* // ## Hourly Candles History (Last 6)
|
|
3528
|
+
* // ### 1h Candle 1 (Green)
|
|
3529
|
+
* // - **Open**: 42000.50 USD
|
|
3530
|
+
* // - **1h Volatility**: 2.15%
|
|
3531
|
+
*
|
|
3532
|
+
* // Or get raw candle data
|
|
3533
|
+
* const candles = await service.getData('ETHUSDT');
|
|
3534
|
+
* console.log(candles.length); // 6
|
|
3535
|
+
* ```
|
|
3536
|
+
*/
|
|
2480
3537
|
class HourCandleHistoryService {
|
|
2481
3538
|
constructor() {
|
|
2482
3539
|
this.loggerService = inject(TYPES.loggerService);
|
|
3540
|
+
/**
|
|
3541
|
+
* Fetches last 6 hourly candles for a symbol.
|
|
3542
|
+
*
|
|
3543
|
+
* Retrieves recent 1-hour candles from exchange for trend analysis.
|
|
3544
|
+
*
|
|
3545
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3546
|
+
* @returns Array of 6 hourly candles
|
|
3547
|
+
*
|
|
3548
|
+
* @example
|
|
3549
|
+
* ```typescript
|
|
3550
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3551
|
+
* console.log(candles.length); // 6
|
|
3552
|
+
* console.log(candles[0].close); // Latest candle close price
|
|
3553
|
+
* ```
|
|
3554
|
+
*/
|
|
2483
3555
|
this.getData = async (symbol) => {
|
|
2484
3556
|
this.loggerService.log("hourCandleHistoryService getData", { symbol });
|
|
2485
3557
|
return backtestKit.getCandles(symbol, "1h", RECENT_CANDLES$2);
|
|
2486
3558
|
};
|
|
3559
|
+
/**
|
|
3560
|
+
* Generates markdown report from candle data.
|
|
3561
|
+
*
|
|
3562
|
+
* Creates detailed markdown report with OHLCV data, candle patterns,
|
|
3563
|
+
* volatility metrics, and body size percentages for each candle.
|
|
3564
|
+
*
|
|
3565
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3566
|
+
* @param candles - Array of candle data to analyze
|
|
3567
|
+
* @returns Markdown-formatted candle history report
|
|
3568
|
+
*
|
|
3569
|
+
* @example
|
|
3570
|
+
* ```typescript
|
|
3571
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3572
|
+
* const report = await service.generateReport('BTCUSDT', candles);
|
|
3573
|
+
* console.log(report);
|
|
3574
|
+
* // ## Hourly Candles History (Last 6)
|
|
3575
|
+
* // ### 1h Candle 1 (Green)
|
|
3576
|
+
* // - **Open**: 42000.50 USD
|
|
3577
|
+
* ```
|
|
3578
|
+
*/
|
|
2487
3579
|
this.generateReport = async (symbol, candles) => {
|
|
2488
3580
|
this.loggerService.log("hourCandleHistoryService generateReport", { symbol });
|
|
2489
3581
|
let markdown = "";
|
|
@@ -2514,6 +3606,28 @@ class HourCandleHistoryService {
|
|
|
2514
3606
|
}
|
|
2515
3607
|
return markdown;
|
|
2516
3608
|
};
|
|
3609
|
+
/**
|
|
3610
|
+
* Generates complete markdown candle history report for a symbol.
|
|
3611
|
+
*
|
|
3612
|
+
* Fetches last 6 hourly candles and formats them as markdown report
|
|
3613
|
+
* with OHLCV data, patterns, and metrics.
|
|
3614
|
+
*
|
|
3615
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3616
|
+
* @returns Markdown-formatted candle history report
|
|
3617
|
+
*
|
|
3618
|
+
* @example
|
|
3619
|
+
* ```typescript
|
|
3620
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3621
|
+
* console.log(report);
|
|
3622
|
+
* // ## Hourly Candles History (Last 6)
|
|
3623
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3624
|
+
* //
|
|
3625
|
+
* // ### 1h Candle 1 (Green)
|
|
3626
|
+
* // - **Time**: 2025-01-14T10:00:00.000Z
|
|
3627
|
+
* // - **Open**: 42000.50 USD
|
|
3628
|
+
* // - **1h Volatility**: 2.15%
|
|
3629
|
+
* ```
|
|
3630
|
+
*/
|
|
2517
3631
|
this.getReport = async (symbol) => {
|
|
2518
3632
|
this.loggerService.log("hourCandleHistoryService getReport", { symbol });
|
|
2519
3633
|
const candles = await this.getData(symbol);
|
|
@@ -2522,14 +3636,99 @@ class HourCandleHistoryService {
|
|
|
2522
3636
|
}
|
|
2523
3637
|
}
|
|
2524
3638
|
|
|
3639
|
+
/**
|
|
3640
|
+
* One-minute candle history service for ultra-short term analysis.
|
|
3641
|
+
*
|
|
3642
|
+
* Generates markdown reports of the last 15 one-minute candles including:
|
|
3643
|
+
* - OHLCV data (Open, High, Low, Close, Volume)
|
|
3644
|
+
* - Candle type (Green/Red/Doji)
|
|
3645
|
+
* - Volatility percentage
|
|
3646
|
+
* - Body size percentage
|
|
3647
|
+
* - Timestamp
|
|
3648
|
+
*
|
|
3649
|
+
* Used by commitOneMinuteHistory() for LLM context injection.
|
|
3650
|
+
*/
|
|
3651
|
+
/**
|
|
3652
|
+
* Number of recent candles to include in history report.
|
|
3653
|
+
* Provides 15-minute price action context for scalping decisions.
|
|
3654
|
+
*/
|
|
2525
3655
|
const RECENT_CANDLES$1 = 15;
|
|
3656
|
+
/**
|
|
3657
|
+
* Service for generating 1-minute candle history reports for scalping analysis.
|
|
3658
|
+
*
|
|
3659
|
+
* Provides detailed OHLCV analysis for the last 15 one-minute candles with
|
|
3660
|
+
* candle pattern identification, volatility metrics, and body size calculations.
|
|
3661
|
+
*
|
|
3662
|
+
* Key features:
|
|
3663
|
+
* - Last 15 one-minute candles (15 minutes of price action)
|
|
3664
|
+
* - OHLCV data with formatted prices and volumes
|
|
3665
|
+
* - Candle type identification (Green/Red/Doji)
|
|
3666
|
+
* - Volatility percentage calculations
|
|
3667
|
+
* - Body size percentage relative to candle range
|
|
3668
|
+
* - ISO timestamp formatting
|
|
3669
|
+
* - Dependency injection support
|
|
3670
|
+
*
|
|
3671
|
+
* @example
|
|
3672
|
+
* ```typescript
|
|
3673
|
+
* import { OneMinuteCandleHistoryService } from '@backtest-kit/signals';
|
|
3674
|
+
*
|
|
3675
|
+
* const service = new OneMinuteCandleHistoryService();
|
|
3676
|
+
*
|
|
3677
|
+
* // Get markdown report
|
|
3678
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3679
|
+
* console.log(report);
|
|
3680
|
+
* // ## One-Minute Candles History (Last 15)
|
|
3681
|
+
* // ### 1m Candle 1 (Green)
|
|
3682
|
+
* // - **Open**: 42000.50 USD
|
|
3683
|
+
* // - **1m Volatility**: 0.15%
|
|
3684
|
+
*
|
|
3685
|
+
* // Or get raw candle data
|
|
3686
|
+
* const candles = await service.getData('ETHUSDT');
|
|
3687
|
+
* console.log(candles.length); // 15
|
|
3688
|
+
* ```
|
|
3689
|
+
*/
|
|
2526
3690
|
class OneMinuteCandleHistoryService {
|
|
2527
3691
|
constructor() {
|
|
2528
3692
|
this.loggerService = inject(TYPES.loggerService);
|
|
3693
|
+
/**
|
|
3694
|
+
* Fetches last 15 one-minute candles for a symbol.
|
|
3695
|
+
*
|
|
3696
|
+
* Retrieves recent 1-minute candles from exchange for scalping analysis.
|
|
3697
|
+
*
|
|
3698
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3699
|
+
* @returns Array of 15 one-minute candles
|
|
3700
|
+
*
|
|
3701
|
+
* @example
|
|
3702
|
+
* ```typescript
|
|
3703
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3704
|
+
* console.log(candles.length); // 15
|
|
3705
|
+
* console.log(candles[0].close); // Latest candle close price
|
|
3706
|
+
* ```
|
|
3707
|
+
*/
|
|
2529
3708
|
this.getData = async (symbol) => {
|
|
2530
3709
|
this.loggerService.log("oneMinuteCandleHistoryService getData", { symbol });
|
|
2531
3710
|
return backtestKit.getCandles(symbol, "1m", RECENT_CANDLES$1);
|
|
2532
3711
|
};
|
|
3712
|
+
/**
|
|
3713
|
+
* Generates markdown report from candle data.
|
|
3714
|
+
*
|
|
3715
|
+
* Creates detailed markdown report with OHLCV data, candle patterns,
|
|
3716
|
+
* volatility metrics, and body size percentages for each candle.
|
|
3717
|
+
*
|
|
3718
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3719
|
+
* @param candles - Array of candle data to analyze
|
|
3720
|
+
* @returns Markdown-formatted candle history report
|
|
3721
|
+
*
|
|
3722
|
+
* @example
|
|
3723
|
+
* ```typescript
|
|
3724
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3725
|
+
* const report = await service.generateReport('BTCUSDT', candles);
|
|
3726
|
+
* console.log(report);
|
|
3727
|
+
* // ## One-Minute Candles History (Last 15)
|
|
3728
|
+
* // ### 1m Candle 1 (Green)
|
|
3729
|
+
* // - **Open**: 42000.50 USD
|
|
3730
|
+
* ```
|
|
3731
|
+
*/
|
|
2533
3732
|
this.generateReport = async (symbol, candles) => {
|
|
2534
3733
|
this.loggerService.log("oneMinuteCandleHistoryService generateReport", { symbol });
|
|
2535
3734
|
let markdown = "";
|
|
@@ -2556,6 +3755,28 @@ class OneMinuteCandleHistoryService {
|
|
|
2556
3755
|
}
|
|
2557
3756
|
return markdown;
|
|
2558
3757
|
};
|
|
3758
|
+
/**
|
|
3759
|
+
* Generates complete markdown candle history report for a symbol.
|
|
3760
|
+
*
|
|
3761
|
+
* Fetches last 15 one-minute candles and formats them as markdown report
|
|
3762
|
+
* with OHLCV data, patterns, and metrics.
|
|
3763
|
+
*
|
|
3764
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3765
|
+
* @returns Markdown-formatted candle history report
|
|
3766
|
+
*
|
|
3767
|
+
* @example
|
|
3768
|
+
* ```typescript
|
|
3769
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3770
|
+
* console.log(report);
|
|
3771
|
+
* // ## One-Minute Candles History (Last 15)
|
|
3772
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3773
|
+
* //
|
|
3774
|
+
* // ### 1m Candle 1 (Green)
|
|
3775
|
+
* // - **Time**: 2025-01-14T10:29:00.000Z
|
|
3776
|
+
* // - **Open**: 42000.50 USD
|
|
3777
|
+
* // - **1m Volatility**: 0.15%
|
|
3778
|
+
* ```
|
|
3779
|
+
*/
|
|
2559
3780
|
this.getReport = async (symbol) => {
|
|
2560
3781
|
this.loggerService.log("oneMinuteCandleHistoryService getReport", { symbol });
|
|
2561
3782
|
const candles = await this.getData(symbol);
|
|
@@ -2564,14 +3785,99 @@ class OneMinuteCandleHistoryService {
|
|
|
2564
3785
|
}
|
|
2565
3786
|
}
|
|
2566
3787
|
|
|
3788
|
+
/**
|
|
3789
|
+
* Thirty-minute candle history service for swing trading analysis.
|
|
3790
|
+
*
|
|
3791
|
+
* Generates markdown reports of the last 6 thirty-minute candles including:
|
|
3792
|
+
* - OHLCV data
|
|
3793
|
+
* - Candle type (Green/Red/Doji)
|
|
3794
|
+
* - Volatility percentage
|
|
3795
|
+
* - Body size percentage
|
|
3796
|
+
* - Timestamp
|
|
3797
|
+
*
|
|
3798
|
+
* Used by commitThirtyMinuteHistory() for LLM context injection.
|
|
3799
|
+
*/
|
|
3800
|
+
/**
|
|
3801
|
+
* Number of recent candles to include in history report.
|
|
3802
|
+
* Provides 3-hour price action context for swing trading decisions.
|
|
3803
|
+
*/
|
|
2567
3804
|
const RECENT_CANDLES = 6;
|
|
3805
|
+
/**
|
|
3806
|
+
* Service for generating 30-minute candle history reports for swing trading analysis.
|
|
3807
|
+
*
|
|
3808
|
+
* Provides detailed OHLCV analysis for the last 6 thirty-minute candles with
|
|
3809
|
+
* candle pattern identification, volatility metrics, and body size calculations.
|
|
3810
|
+
*
|
|
3811
|
+
* Key features:
|
|
3812
|
+
* - Last 6 thirty-minute candles (3 hours of price action)
|
|
3813
|
+
* - OHLCV data with formatted prices and volumes
|
|
3814
|
+
* - Candle type identification (Green/Red/Doji)
|
|
3815
|
+
* - Volatility percentage calculations
|
|
3816
|
+
* - Body size percentage relative to candle range
|
|
3817
|
+
* - ISO timestamp formatting
|
|
3818
|
+
* - Dependency injection support
|
|
3819
|
+
*
|
|
3820
|
+
* @example
|
|
3821
|
+
* ```typescript
|
|
3822
|
+
* import { ThirtyMinuteCandleHistoryService } from '@backtest-kit/signals';
|
|
3823
|
+
*
|
|
3824
|
+
* const service = new ThirtyMinuteCandleHistoryService();
|
|
3825
|
+
*
|
|
3826
|
+
* // Get markdown report
|
|
3827
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3828
|
+
* console.log(report);
|
|
3829
|
+
* // ## 30-Min Candles History (Last 6)
|
|
3830
|
+
* // ### 30m Candle 1 (Green)
|
|
3831
|
+
* // - **Open**: 42000.50 USD
|
|
3832
|
+
* // - **30m Volatility**: 1.25%
|
|
3833
|
+
*
|
|
3834
|
+
* // Or get raw candle data
|
|
3835
|
+
* const candles = await service.getData('ETHUSDT');
|
|
3836
|
+
* console.log(candles.length); // 6
|
|
3837
|
+
* ```
|
|
3838
|
+
*/
|
|
2568
3839
|
class ThirtyMinuteCandleHistoryService {
|
|
2569
3840
|
constructor() {
|
|
2570
3841
|
this.loggerService = inject(TYPES.loggerService);
|
|
3842
|
+
/**
|
|
3843
|
+
* Fetches last 6 thirty-minute candles for a symbol.
|
|
3844
|
+
*
|
|
3845
|
+
* Retrieves recent 30-minute candles from exchange for analysis.
|
|
3846
|
+
*
|
|
3847
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3848
|
+
* @returns Array of 6 thirty-minute candles
|
|
3849
|
+
*
|
|
3850
|
+
* @example
|
|
3851
|
+
* ```typescript
|
|
3852
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3853
|
+
* console.log(candles.length); // 6
|
|
3854
|
+
* console.log(candles[0].close); // Latest candle close price
|
|
3855
|
+
* ```
|
|
3856
|
+
*/
|
|
2571
3857
|
this.getData = async (symbol) => {
|
|
2572
3858
|
this.loggerService.log("thirtyMinuteCandleHistoryService getData", { symbol });
|
|
2573
3859
|
return backtestKit.getCandles(symbol, "30m", RECENT_CANDLES);
|
|
2574
3860
|
};
|
|
3861
|
+
/**
|
|
3862
|
+
* Generates markdown report from candle data.
|
|
3863
|
+
*
|
|
3864
|
+
* Creates detailed markdown report with OHLCV data, candle patterns,
|
|
3865
|
+
* volatility metrics, and body size percentages for each candle.
|
|
3866
|
+
*
|
|
3867
|
+
* @param symbol - Trading pair symbol for price formatting
|
|
3868
|
+
* @param candles - Array of candle data to analyze
|
|
3869
|
+
* @returns Markdown-formatted candle history report
|
|
3870
|
+
*
|
|
3871
|
+
* @example
|
|
3872
|
+
* ```typescript
|
|
3873
|
+
* const candles = await service.getData('BTCUSDT');
|
|
3874
|
+
* const report = await service.generateReport('BTCUSDT', candles);
|
|
3875
|
+
* console.log(report);
|
|
3876
|
+
* // ## 30-Min Candles History (Last 6)
|
|
3877
|
+
* // ### 30m Candle 1 (Green)
|
|
3878
|
+
* // - **Open**: 42000.50 USD
|
|
3879
|
+
* ```
|
|
3880
|
+
*/
|
|
2575
3881
|
this.generateReport = async (symbol, candles) => {
|
|
2576
3882
|
this.loggerService.log("thirtyMinuteCandleHistoryService generateReport", { symbol });
|
|
2577
3883
|
let report = "";
|
|
@@ -2602,6 +3908,28 @@ class ThirtyMinuteCandleHistoryService {
|
|
|
2602
3908
|
}
|
|
2603
3909
|
return report;
|
|
2604
3910
|
};
|
|
3911
|
+
/**
|
|
3912
|
+
* Generates complete markdown candle history report for a symbol.
|
|
3913
|
+
*
|
|
3914
|
+
* Fetches last 6 thirty-minute candles and formats them as markdown report
|
|
3915
|
+
* with OHLCV data, patterns, and metrics.
|
|
3916
|
+
*
|
|
3917
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
3918
|
+
* @returns Markdown-formatted candle history report
|
|
3919
|
+
*
|
|
3920
|
+
* @example
|
|
3921
|
+
* ```typescript
|
|
3922
|
+
* const report = await service.getReport('BTCUSDT');
|
|
3923
|
+
* console.log(report);
|
|
3924
|
+
* // ## 30-Min Candles History (Last 6)
|
|
3925
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
3926
|
+
* //
|
|
3927
|
+
* // ### 30m Candle 1 (Green)
|
|
3928
|
+
* // - **Time**: 2025-01-14T10:00:00.000Z
|
|
3929
|
+
* // - **Open**: 42000.50 USD
|
|
3930
|
+
* // - **30m Volatility**: 1.25%
|
|
3931
|
+
* ```
|
|
3932
|
+
*/
|
|
2605
3933
|
this.getReport = async (symbol) => {
|
|
2606
3934
|
this.loggerService.log("thirtyMinuteCandleHistoryService getReport", { symbol });
|
|
2607
3935
|
const candles = await this.getData(symbol);
|
|
@@ -2610,6 +3938,46 @@ class ThirtyMinuteCandleHistoryService {
|
|
|
2610
3938
|
}
|
|
2611
3939
|
}
|
|
2612
3940
|
|
|
3941
|
+
/**
|
|
3942
|
+
* Order book analysis service for real-time market depth and liquidity assessment.
|
|
3943
|
+
*
|
|
3944
|
+
* Generates comprehensive order book reports including:
|
|
3945
|
+
* - Top 20 bid/ask levels sorted by volume percentage
|
|
3946
|
+
* - Best bid/ask prices
|
|
3947
|
+
* - Mid price and spread
|
|
3948
|
+
* - Depth imbalance (buy vs sell pressure indicator)
|
|
3949
|
+
*
|
|
3950
|
+
* Depth Imbalance Formula:
|
|
3951
|
+
* (Total Bid Volume - Total Ask Volume) / (Total Bid Volume + Total Ask Volume)
|
|
3952
|
+
* - Positive: Buy pressure (more bids)
|
|
3953
|
+
* - Negative: Sell pressure (more asks)
|
|
3954
|
+
* - Zero: Balanced market
|
|
3955
|
+
*
|
|
3956
|
+
* Used by commitBookDataReport() for LLM context injection.
|
|
3957
|
+
* Only available in live mode (skipped in backtest mode).
|
|
3958
|
+
*/
|
|
3959
|
+
/**
|
|
3960
|
+
* Maximum order book depth levels to fetch for accurate metrics.
|
|
3961
|
+
* Provides comprehensive liquidity view for depth imbalance calculation.
|
|
3962
|
+
*/
|
|
3963
|
+
const MAX_DEPTH_LEVELS = 1000;
|
|
3964
|
+
/**
|
|
3965
|
+
* Validates whether a numeric value is safe for calculations.
|
|
3966
|
+
*
|
|
3967
|
+
* Checks if value is a valid finite number. Returns true if value is null,
|
|
3968
|
+
* NaN, Infinity, or not a number type.
|
|
3969
|
+
*
|
|
3970
|
+
* @param value - Value to validate
|
|
3971
|
+
* @returns True if value is unsafe (null/NaN/Infinity), false if valid number
|
|
3972
|
+
*
|
|
3973
|
+
* @example
|
|
3974
|
+
* ```typescript
|
|
3975
|
+
* isUnsafe(42) // false - valid number
|
|
3976
|
+
* isUnsafe(null) // true - null value
|
|
3977
|
+
* isUnsafe(NaN) // true - not a number
|
|
3978
|
+
* isUnsafe(Infinity) // true - infinite value
|
|
3979
|
+
* ```
|
|
3980
|
+
*/
|
|
2613
3981
|
function isUnsafe(value) {
|
|
2614
3982
|
if (typeof value !== "number") {
|
|
2615
3983
|
return true;
|
|
@@ -2622,7 +3990,28 @@ function isUnsafe(value) {
|
|
|
2622
3990
|
}
|
|
2623
3991
|
return false;
|
|
2624
3992
|
}
|
|
2625
|
-
|
|
3993
|
+
/**
|
|
3994
|
+
* Processes one side of order book (bids or asks) and calculates volume percentages.
|
|
3995
|
+
*
|
|
3996
|
+
* Converts raw bid/ask data to structured entries with volume percentage calculations.
|
|
3997
|
+
* Each entry's percentage represents its share of total side volume.
|
|
3998
|
+
*
|
|
3999
|
+
* @param orders - Raw order book entries from exchange API
|
|
4000
|
+
* @returns Processed entries with price, quantity, and volume percentage
|
|
4001
|
+
*
|
|
4002
|
+
* @example
|
|
4003
|
+
* ```typescript
|
|
4004
|
+
* const rawBids = [
|
|
4005
|
+
* { price: "42000", quantity: "1.5" },
|
|
4006
|
+
* { price: "41999", quantity: "0.5" }
|
|
4007
|
+
* ];
|
|
4008
|
+
* const processed = processOrderBookSide(rawBids);
|
|
4009
|
+
* // [
|
|
4010
|
+
* // { price: 42000, quantity: 1.5, percentage: 75.0 },
|
|
4011
|
+
* // { price: 41999, quantity: 0.5, percentage: 25.0 }
|
|
4012
|
+
* // ]
|
|
4013
|
+
* ```
|
|
4014
|
+
*/
|
|
2626
4015
|
function processOrderBookSide(orders) {
|
|
2627
4016
|
const entries = orders.map((order) => ({
|
|
2628
4017
|
price: parseFloat(order.price),
|
|
@@ -2637,7 +4026,34 @@ function processOrderBookSide(orders) {
|
|
|
2637
4026
|
});
|
|
2638
4027
|
return entries;
|
|
2639
4028
|
}
|
|
2640
|
-
|
|
4029
|
+
/**
|
|
4030
|
+
* Generates markdown-formatted order book report with depth analysis.
|
|
4031
|
+
*
|
|
4032
|
+
* Creates comprehensive markdown report including:
|
|
4033
|
+
* - Order book summary (best bid/ask, mid price, spread, depth imbalance)
|
|
4034
|
+
* - Top 20 bid levels sorted by volume percentage
|
|
4035
|
+
* - Top 20 ask levels sorted by volume percentage
|
|
4036
|
+
* - Formatted prices and quantities with proper USD notation
|
|
4037
|
+
*
|
|
4038
|
+
* Output is optimized for LLM consumption in trading signal generation.
|
|
4039
|
+
*
|
|
4040
|
+
* @param self - Service instance for logging context
|
|
4041
|
+
* @param result - Order book analysis data with calculated metrics
|
|
4042
|
+
* @returns Markdown-formatted order book report
|
|
4043
|
+
*
|
|
4044
|
+
* @example
|
|
4045
|
+
* ```typescript
|
|
4046
|
+
* const analysis = await service.getData('BTCUSDT');
|
|
4047
|
+
* const report = await generateBookDataReport(service, analysis);
|
|
4048
|
+
* console.log(report);
|
|
4049
|
+
* // # Order Book Analysis for BTCUSDT
|
|
4050
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
4051
|
+
* // ## Order Book Summary
|
|
4052
|
+
* // - **Best Bid**: 42000.50 USD
|
|
4053
|
+
* // - **Best Ask**: 42001.25 USD
|
|
4054
|
+
* // - **Depth Imbalance**: 12.5%
|
|
4055
|
+
* ```
|
|
4056
|
+
*/
|
|
2641
4057
|
const generateBookDataReport = async (self, result) => {
|
|
2642
4058
|
const currentData = await backtestKit.getDate();
|
|
2643
4059
|
let markdown = `# Order Book Analysis for ${result.symbol}\n`;
|
|
@@ -2702,15 +4118,88 @@ const generateBookDataReport = async (self, result) => {
|
|
|
2702
4118
|
markdown += `\n`;
|
|
2703
4119
|
return markdown;
|
|
2704
4120
|
};
|
|
4121
|
+
/**
|
|
4122
|
+
* Service for order book analysis and markdown report generation.
|
|
4123
|
+
*
|
|
4124
|
+
* Provides real-time order book depth analysis with market liquidity metrics
|
|
4125
|
+
* including bid/ask levels, depth imbalance, spread, and volume distribution.
|
|
4126
|
+
*
|
|
4127
|
+
* Key features:
|
|
4128
|
+
* - Fetches up to 1000 order book depth levels
|
|
4129
|
+
* - Calculates best bid/ask, mid price, and spread
|
|
4130
|
+
* - Computes depth imbalance (buy vs sell pressure)
|
|
4131
|
+
* - Analyzes volume distribution with percentage calculations
|
|
4132
|
+
* - Generates markdown reports with top 20 levels
|
|
4133
|
+
* - Only available in live mode (skipped in backtest)
|
|
4134
|
+
* - Dependency injection support
|
|
4135
|
+
*
|
|
4136
|
+
* @example
|
|
4137
|
+
* ```typescript
|
|
4138
|
+
* import { BookDataMathService } from '@backtest-kit/signals';
|
|
4139
|
+
*
|
|
4140
|
+
* const service = new BookDataMathService();
|
|
4141
|
+
*
|
|
4142
|
+
* // Get markdown report (fetches order book internally)
|
|
4143
|
+
* const report = await service.getReport('BTCUSDT');
|
|
4144
|
+
* console.log(report); // Markdown with top 20 bid/ask levels
|
|
4145
|
+
*
|
|
4146
|
+
* // Or analyze custom order book data
|
|
4147
|
+
* const analysis = await service.getData('ETHUSDT');
|
|
4148
|
+
* console.log(analysis.depthImbalance); // 0.125 (12.5% buy pressure)
|
|
4149
|
+
* console.log(analysis.bestBid); // 2300.50
|
|
4150
|
+
* ```
|
|
4151
|
+
*/
|
|
2705
4152
|
class BookDataMathService {
|
|
2706
4153
|
constructor() {
|
|
2707
4154
|
this.loggerService = inject(TYPES.loggerService);
|
|
4155
|
+
/**
|
|
4156
|
+
* Converts order book analysis into markdown report format.
|
|
4157
|
+
*
|
|
4158
|
+
* Takes pre-calculated order book analysis and formats it as markdown
|
|
4159
|
+
* with summary metrics and top 20 bid/ask levels sorted by volume.
|
|
4160
|
+
*
|
|
4161
|
+
* @param symbol - Trading pair symbol for header
|
|
4162
|
+
* @param bookData - Order book analysis from getData()
|
|
4163
|
+
* @returns Markdown-formatted order book report
|
|
4164
|
+
*
|
|
4165
|
+
* @example
|
|
4166
|
+
* ```typescript
|
|
4167
|
+
* const analysis = await service.getData('BTCUSDT');
|
|
4168
|
+
* const report = await service.generateReport('BTCUSDT', analysis);
|
|
4169
|
+
* console.log(report); // Markdown table with order book data
|
|
4170
|
+
* ```
|
|
4171
|
+
*/
|
|
2708
4172
|
this.generateReport = async (symbol, bookData) => {
|
|
2709
4173
|
this.loggerService.log("bookDataMathService generateReport", {
|
|
2710
4174
|
symbol,
|
|
2711
4175
|
});
|
|
2712
4176
|
return await generateBookDataReport(this, bookData);
|
|
2713
4177
|
};
|
|
4178
|
+
/**
|
|
4179
|
+
* Generates complete markdown order book report for a symbol.
|
|
4180
|
+
*
|
|
4181
|
+
* Fetches order book depth (up to 1000 levels) from exchange, calculates all metrics,
|
|
4182
|
+
* and formats results as markdown report optimized for LLM consumption.
|
|
4183
|
+
*
|
|
4184
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
4185
|
+
* @returns Markdown-formatted order book report with depth analysis
|
|
4186
|
+
*
|
|
4187
|
+
* @example
|
|
4188
|
+
* ```typescript
|
|
4189
|
+
* const report = await service.getReport('BTCUSDT');
|
|
4190
|
+
* console.log(report);
|
|
4191
|
+
* // # Order Book Analysis for BTCUSDT
|
|
4192
|
+
* // > Current time: 2025-01-14T10:30:00.000Z
|
|
4193
|
+
* //
|
|
4194
|
+
* // ## Order Book Summary
|
|
4195
|
+
* // - **Best Bid**: 42000.50 USD
|
|
4196
|
+
* // - **Depth Imbalance**: 12.5%
|
|
4197
|
+
* //
|
|
4198
|
+
* // ## Top 20 Order Book Levels
|
|
4199
|
+
* // ### Bids (Buy Orders)
|
|
4200
|
+
* // | Price | Quantity | % of Total |
|
|
4201
|
+
* ```
|
|
4202
|
+
*/
|
|
2714
4203
|
this.getReport = async (symbol) => {
|
|
2715
4204
|
this.loggerService.log("bookDataMathService getReport", {
|
|
2716
4205
|
symbol,
|
|
@@ -2718,6 +4207,26 @@ class BookDataMathService {
|
|
|
2718
4207
|
const bookData = await this.getData(symbol);
|
|
2719
4208
|
return await this.generateReport(symbol, bookData);
|
|
2720
4209
|
};
|
|
4210
|
+
/**
|
|
4211
|
+
* Fetches and analyzes order book data with depth metrics.
|
|
4212
|
+
*
|
|
4213
|
+
* Retrieves up to 1000 depth levels from exchange, processes bid/ask data,
|
|
4214
|
+
* calculates volume percentages, and computes market depth metrics including
|
|
4215
|
+
* best bid/ask, mid price, spread, and depth imbalance.
|
|
4216
|
+
*
|
|
4217
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
4218
|
+
* @returns Order book analysis with all calculated metrics
|
|
4219
|
+
*
|
|
4220
|
+
* @example
|
|
4221
|
+
* ```typescript
|
|
4222
|
+
* const analysis = await service.getData('BTCUSDT');
|
|
4223
|
+
* console.log(analysis.bestBid); // 42000.50
|
|
4224
|
+
* console.log(analysis.bestAsk); // 42001.25
|
|
4225
|
+
* console.log(analysis.spread); // 0.75
|
|
4226
|
+
* console.log(analysis.depthImbalance); // 0.125 (12.5% buy pressure)
|
|
4227
|
+
* console.log(analysis.bids.length); // Up to 1000 levels
|
|
4228
|
+
* ```
|
|
4229
|
+
*/
|
|
2721
4230
|
this.getData = async (symbol) => {
|
|
2722
4231
|
this.loggerService.log("bookDataMathService getBookDataAnalysis", {
|
|
2723
4232
|
symbol,
|
|
@@ -2751,6 +4260,28 @@ class BookDataMathService {
|
|
|
2751
4260
|
}
|
|
2752
4261
|
}
|
|
2753
4262
|
|
|
4263
|
+
/**
|
|
4264
|
+
* Logger service for signals library diagnostic output.
|
|
4265
|
+
*
|
|
4266
|
+
* Provides logging capabilities with a no-op default implementation.
|
|
4267
|
+
* Use setLogger() from the public API to enable actual logging output.
|
|
4268
|
+
*
|
|
4269
|
+
* @example
|
|
4270
|
+
* ```typescript
|
|
4271
|
+
* import { setLogger } from '@backtest-kit/signals';
|
|
4272
|
+
*
|
|
4273
|
+
* setLogger({
|
|
4274
|
+
* log: console.log,
|
|
4275
|
+
* debug: console.debug,
|
|
4276
|
+
* info: console.info,
|
|
4277
|
+
* warn: console.warn,
|
|
4278
|
+
* });
|
|
4279
|
+
* ```
|
|
4280
|
+
*/
|
|
4281
|
+
/**
|
|
4282
|
+
* No-op logger implementation that discards all log calls.
|
|
4283
|
+
* Used as default to avoid polluting console output.
|
|
4284
|
+
*/
|
|
2754
4285
|
const NOOP_LOGGER = {
|
|
2755
4286
|
log() {
|
|
2756
4287
|
},
|
|
@@ -2761,30 +4292,133 @@ const NOOP_LOGGER = {
|
|
|
2761
4292
|
warn() {
|
|
2762
4293
|
},
|
|
2763
4294
|
};
|
|
4295
|
+
/**
|
|
4296
|
+
* Logger service implementation with configurable backend.
|
|
4297
|
+
*
|
|
4298
|
+
* Delegates all logging calls to the configured logger implementation.
|
|
4299
|
+
* Defaults to NOOP_LOGGER which discards all output.
|
|
4300
|
+
*/
|
|
2764
4301
|
class LoggerService {
|
|
2765
4302
|
constructor() {
|
|
2766
4303
|
this._commonLogger = NOOP_LOGGER;
|
|
4304
|
+
/**
|
|
4305
|
+
* Logs general messages with topic and optional arguments.
|
|
4306
|
+
*
|
|
4307
|
+
* Delegates to configured logger implementation. Uses no-op logger by default
|
|
4308
|
+
* until setLogger() is called with custom implementation.
|
|
4309
|
+
*
|
|
4310
|
+
* @param topic - Log topic or category identifier
|
|
4311
|
+
* @param args - Additional arguments to log
|
|
4312
|
+
*
|
|
4313
|
+
* @example
|
|
4314
|
+
* ```typescript
|
|
4315
|
+
* const logger = new LoggerService();
|
|
4316
|
+
* await logger.log('user-action', { userId: '123', action: 'login' });
|
|
4317
|
+
* // Output depends on configured logger implementation
|
|
4318
|
+
* ```
|
|
4319
|
+
*/
|
|
2767
4320
|
this.log = async (topic, ...args) => {
|
|
2768
4321
|
await this._commonLogger.log(topic, ...args);
|
|
2769
4322
|
};
|
|
4323
|
+
/**
|
|
4324
|
+
* Logs debug-level messages with topic and optional arguments.
|
|
4325
|
+
*
|
|
4326
|
+
* Typically used for detailed diagnostic information during development.
|
|
4327
|
+
* Delegates to configured logger implementation.
|
|
4328
|
+
*
|
|
4329
|
+
* @param topic - Debug topic or category identifier
|
|
4330
|
+
* @param args - Additional arguments to log
|
|
4331
|
+
*
|
|
4332
|
+
* @example
|
|
4333
|
+
* ```typescript
|
|
4334
|
+
* const logger = new LoggerService();
|
|
4335
|
+
* await logger.debug('api-call', { endpoint: '/data', params: { limit: 10 } });
|
|
4336
|
+
* ```
|
|
4337
|
+
*/
|
|
2770
4338
|
this.debug = async (topic, ...args) => {
|
|
2771
4339
|
await this._commonLogger.debug(topic, ...args);
|
|
2772
4340
|
};
|
|
4341
|
+
/**
|
|
4342
|
+
* Logs informational messages with topic and optional arguments.
|
|
4343
|
+
*
|
|
4344
|
+
* Used for general informational messages about application state or progress.
|
|
4345
|
+
* Delegates to configured logger implementation.
|
|
4346
|
+
*
|
|
4347
|
+
* @param topic - Info topic or category identifier
|
|
4348
|
+
* @param args - Additional arguments to log
|
|
4349
|
+
*
|
|
4350
|
+
* @example
|
|
4351
|
+
* ```typescript
|
|
4352
|
+
* const logger = new LoggerService();
|
|
4353
|
+
* await logger.info('server-start', { port: 3000, env: 'production' });
|
|
4354
|
+
* ```
|
|
4355
|
+
*/
|
|
2773
4356
|
this.info = async (topic, ...args) => {
|
|
2774
4357
|
await this._commonLogger.info(topic, ...args);
|
|
2775
4358
|
};
|
|
4359
|
+
/**
|
|
4360
|
+
* Logs warning messages with topic and optional arguments.
|
|
4361
|
+
*
|
|
4362
|
+
* Used for potentially harmful situations that don't prevent execution.
|
|
4363
|
+
* Delegates to configured logger implementation.
|
|
4364
|
+
*
|
|
4365
|
+
* @param topic - Warning topic or category identifier
|
|
4366
|
+
* @param args - Additional arguments to log
|
|
4367
|
+
*
|
|
4368
|
+
* @example
|
|
4369
|
+
* ```typescript
|
|
4370
|
+
* const logger = new LoggerService();
|
|
4371
|
+
* await logger.warn('rate-limit', { limit: 100, current: 95 });
|
|
4372
|
+
* ```
|
|
4373
|
+
*/
|
|
2776
4374
|
this.warn = async (topic, ...args) => {
|
|
2777
4375
|
await this._commonLogger.warn(topic, ...args);
|
|
2778
4376
|
};
|
|
4377
|
+
/**
|
|
4378
|
+
* Sets custom logger implementation.
|
|
4379
|
+
*
|
|
4380
|
+
* Replaces the default no-op logger with a custom implementation that
|
|
4381
|
+
* conforms to the ILogger interface. Call this during application initialization
|
|
4382
|
+
* to enable actual logging output.
|
|
4383
|
+
*
|
|
4384
|
+
* @param logger - Custom logger conforming to ILogger interface
|
|
4385
|
+
*
|
|
4386
|
+
* @example
|
|
4387
|
+
* ```typescript
|
|
4388
|
+
* const logger = new LoggerService();
|
|
4389
|
+
* logger.setLogger({
|
|
4390
|
+
* log: console.log,
|
|
4391
|
+
* debug: console.debug,
|
|
4392
|
+
* info: console.info,
|
|
4393
|
+
* warn: console.warn,
|
|
4394
|
+
* });
|
|
4395
|
+
* await logger.log('test', 'now logging to console');
|
|
4396
|
+
* ```
|
|
4397
|
+
*/
|
|
2779
4398
|
this.setLogger = (logger) => {
|
|
2780
4399
|
this._commonLogger = logger;
|
|
2781
4400
|
};
|
|
2782
4401
|
}
|
|
2783
4402
|
}
|
|
2784
4403
|
|
|
4404
|
+
/**
|
|
4405
|
+
* Service registration for signals library DI container.
|
|
4406
|
+
*
|
|
4407
|
+
* Registers all service factories with the dependency injection container.
|
|
4408
|
+
* Services are lazily instantiated on first injection.
|
|
4409
|
+
*
|
|
4410
|
+
* Service categories:
|
|
4411
|
+
* - Common: Logger service
|
|
4412
|
+
* - Math: Technical analysis services (MicroTerm, ShortTerm, SwingTerm, LongTerm, OrderBook)
|
|
4413
|
+
* - History: Candle history services (1m, 15m, 30m, 1h)
|
|
4414
|
+
*
|
|
4415
|
+
* @module lib/core/provide
|
|
4416
|
+
*/
|
|
4417
|
+
// Register common services
|
|
2785
4418
|
{
|
|
2786
4419
|
provide(TYPES.loggerService, () => new LoggerService());
|
|
2787
4420
|
}
|
|
4421
|
+
// Register technical analysis services
|
|
2788
4422
|
{
|
|
2789
4423
|
provide(TYPES.swingTermMathService, () => new SwingTermHistoryService());
|
|
2790
4424
|
provide(TYPES.longTermMathService, () => new LongTermHistoryService());
|
|
@@ -2792,6 +4426,7 @@ class LoggerService {
|
|
|
2792
4426
|
provide(TYPES.microTermMathService, () => new MicroTermHistoryService());
|
|
2793
4427
|
provide(TYPES.bookDataMathService, () => new BookDataMathService());
|
|
2794
4428
|
}
|
|
4429
|
+
// Register candle history services
|
|
2795
4430
|
{
|
|
2796
4431
|
provide(TYPES.fifteenMinuteCandleHistoryService, () => new FifteenMinuteCandleHistoryService());
|
|
2797
4432
|
provide(TYPES.hourCandleHistoryService, () => new HourCandleHistoryService());
|
|
@@ -2799,9 +4434,30 @@ class LoggerService {
|
|
|
2799
4434
|
provide(TYPES.thirtyMinuteCandleHistoryService, () => new ThirtyMinuteCandleHistoryService());
|
|
2800
4435
|
}
|
|
2801
4436
|
|
|
4437
|
+
/**
|
|
4438
|
+
* Service container initialization and export for signals library.
|
|
4439
|
+
*
|
|
4440
|
+
* Initializes the DI container, injects all registered services,
|
|
4441
|
+
* and exports them as a unified 'signal' object for internal use.
|
|
4442
|
+
*
|
|
4443
|
+
* This module:
|
|
4444
|
+
* 1. Imports service registrations from './core/provide'
|
|
4445
|
+
* 2. Injects all services from DI container
|
|
4446
|
+
* 3. Initializes DI container
|
|
4447
|
+
* 4. Exports combined service object
|
|
4448
|
+
* 5. Attaches to globalThis for debugging (non-production only)
|
|
4449
|
+
*
|
|
4450
|
+
* @module lib/index
|
|
4451
|
+
*/
|
|
4452
|
+
/**
|
|
4453
|
+
* Common services.
|
|
4454
|
+
*/
|
|
2802
4455
|
const commonServices = {
|
|
2803
4456
|
loggerService: inject(TYPES.loggerService),
|
|
2804
4457
|
};
|
|
4458
|
+
/**
|
|
4459
|
+
* Technical analysis services.
|
|
4460
|
+
*/
|
|
2805
4461
|
const mathServices = {
|
|
2806
4462
|
swingTermMathService: inject(TYPES.swingTermMathService),
|
|
2807
4463
|
longTermMathService: inject(TYPES.longTermMathService),
|
|
@@ -2809,32 +4465,97 @@ const mathServices = {
|
|
|
2809
4465
|
microTermMathService: inject(TYPES.microTermMathService),
|
|
2810
4466
|
bookDataMathService: inject(TYPES.bookDataMathService),
|
|
2811
4467
|
};
|
|
4468
|
+
/**
|
|
4469
|
+
* Candle history services.
|
|
4470
|
+
*/
|
|
2812
4471
|
const historyServices = {
|
|
2813
4472
|
fifteenMinuteCandleHistoryService: inject(TYPES.fifteenMinuteCandleHistoryService),
|
|
2814
4473
|
hourCandleHistoryService: inject(TYPES.hourCandleHistoryService),
|
|
2815
4474
|
oneMinuteCandleHistoryService: inject(TYPES.oneMinuteCandleHistoryService),
|
|
2816
4475
|
thirtyMinuteCandleHistoryService: inject(TYPES.thirtyMinuteCandleHistoryService),
|
|
2817
4476
|
};
|
|
4477
|
+
/**
|
|
4478
|
+
* Combined service container for internal library use.
|
|
4479
|
+
* Contains all registered services: common, math, and history.
|
|
4480
|
+
*/
|
|
2818
4481
|
const signal = {
|
|
2819
4482
|
...commonServices,
|
|
2820
4483
|
...mathServices,
|
|
2821
4484
|
...historyServices,
|
|
2822
4485
|
};
|
|
4486
|
+
// Initialize DI container
|
|
2823
4487
|
init();
|
|
4488
|
+
// Attach to global for debugging (non-production)
|
|
2824
4489
|
Object.assign(globalThis, { signal });
|
|
2825
4490
|
|
|
4491
|
+
/**
|
|
4492
|
+
* Candle history report generation functions for multi-timeframe analysis.
|
|
4493
|
+
*
|
|
4494
|
+
* Provides cached functions to fetch and commit OHLCV candle history reports
|
|
4495
|
+
* across 4 timeframes (1m, 15m, 30m, 1h) formatted as markdown for LLM consumption.
|
|
4496
|
+
* Each function automatically handles caching, error recovery, and report formatting.
|
|
4497
|
+
*
|
|
4498
|
+
* Key features:
|
|
4499
|
+
* - Intelligent caching with timeframe-specific TTL (1m: 1min, 15m: 5min, 30m: 15min, 1h: 30min)
|
|
4500
|
+
* - Automatic cache clearing on errors for data freshness
|
|
4501
|
+
* - Formatted markdown tables with candle details (OHLCV, volatility, body size, candle type)
|
|
4502
|
+
* - User/assistant message pair format for LLM context
|
|
4503
|
+
*
|
|
4504
|
+
* @module function/history
|
|
4505
|
+
*/
|
|
4506
|
+
/**
|
|
4507
|
+
* Cached function to fetch 1-hour candle history report.
|
|
4508
|
+
* Cache TTL: 30 minutes
|
|
4509
|
+
*/
|
|
2826
4510
|
const fetchHourHistory = backtestKit.Cache.fn(signal.hourCandleHistoryService.getReport, {
|
|
2827
4511
|
interval: "30m",
|
|
2828
4512
|
});
|
|
4513
|
+
/**
|
|
4514
|
+
* Cached function to fetch 30-minute candle history report.
|
|
4515
|
+
* Cache TTL: 15 minutes
|
|
4516
|
+
*/
|
|
2829
4517
|
const fetchThirtyMinuteHistory = backtestKit.Cache.fn(signal.thirtyMinuteCandleHistoryService.getReport, {
|
|
2830
4518
|
interval: "15m",
|
|
2831
4519
|
});
|
|
4520
|
+
/**
|
|
4521
|
+
* Cached function to fetch 15-minute candle history report.
|
|
4522
|
+
* Cache TTL: 5 minutes
|
|
4523
|
+
*/
|
|
2832
4524
|
const fetchFifteenMinuteHistory = backtestKit.Cache.fn(signal.fifteenMinuteCandleHistoryService.getReport, {
|
|
2833
4525
|
interval: "5m",
|
|
2834
4526
|
});
|
|
4527
|
+
/**
|
|
4528
|
+
* Cached function to fetch 1-minute candle history report.
|
|
4529
|
+
* Cache TTL: 1 minute
|
|
4530
|
+
*/
|
|
2835
4531
|
const fetchOneMinuteHistory = backtestKit.Cache.fn(signal.oneMinuteCandleHistoryService.getReport, {
|
|
2836
4532
|
interval: "1m",
|
|
2837
4533
|
});
|
|
4534
|
+
/**
|
|
4535
|
+
* Commits 1-hour candle history report to history container.
|
|
4536
|
+
*
|
|
4537
|
+
* Fetches and appends a markdown-formatted report of the last 6 hourly candles
|
|
4538
|
+
* including OHLCV data, volatility, body size, and candle type (Green/Red/Doji).
|
|
4539
|
+
* Automatically clears cache on errors to ensure data freshness.
|
|
4540
|
+
*
|
|
4541
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4542
|
+
* @param history - History container to append report to
|
|
4543
|
+
* @returns Promise that resolves when report is committed
|
|
4544
|
+
*
|
|
4545
|
+
* @example
|
|
4546
|
+
* ```typescript
|
|
4547
|
+
* import { commitHourHistory } from '@backtest-kit/signals';
|
|
4548
|
+
*
|
|
4549
|
+
* const messages = [];
|
|
4550
|
+
* await commitHourHistory('BTCUSDT', messages);
|
|
4551
|
+
*
|
|
4552
|
+
* // messages now contains:
|
|
4553
|
+
* // [
|
|
4554
|
+
* // { role: 'user', content: '=== HOURLY CANDLES HISTORY (LAST 6) ===\n\n...' },
|
|
4555
|
+
* // { role: 'assistant', content: 'Hourly candles history received.' }
|
|
4556
|
+
* // ]
|
|
4557
|
+
* ```
|
|
4558
|
+
*/
|
|
2838
4559
|
const commitHourHistory = functoolsKit.trycatch(async (symbol, history) => {
|
|
2839
4560
|
const hourHistory = await fetchHourHistory(symbol);
|
|
2840
4561
|
await history.push({
|
|
@@ -2847,6 +4568,25 @@ const commitHourHistory = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2847
4568
|
}, {
|
|
2848
4569
|
fallback: () => backtestKit.Cache.clear(fetchHourHistory),
|
|
2849
4570
|
});
|
|
4571
|
+
/**
|
|
4572
|
+
* Commits 30-minute candle history report to history container.
|
|
4573
|
+
*
|
|
4574
|
+
* Fetches and appends a markdown-formatted report of the last 6 thirty-minute candles
|
|
4575
|
+
* including OHLCV data, volatility, body size, and candle type (Green/Red/Doji).
|
|
4576
|
+
* Automatically clears cache on errors to ensure data freshness.
|
|
4577
|
+
*
|
|
4578
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4579
|
+
* @param history - History container to append report to
|
|
4580
|
+
* @returns Promise that resolves when report is committed
|
|
4581
|
+
*
|
|
4582
|
+
* @example
|
|
4583
|
+
* ```typescript
|
|
4584
|
+
* import { commitThirtyMinuteHistory } from '@backtest-kit/signals';
|
|
4585
|
+
*
|
|
4586
|
+
* const messages = [];
|
|
4587
|
+
* await commitThirtyMinuteHistory('ETHUSDT', messages);
|
|
4588
|
+
* ```
|
|
4589
|
+
*/
|
|
2850
4590
|
const commitThirtyMinuteHistory = functoolsKit.trycatch(async (symbol, history) => {
|
|
2851
4591
|
const thirtyMinuteHistory = await fetchThirtyMinuteHistory(symbol);
|
|
2852
4592
|
await history.push({
|
|
@@ -2859,6 +4599,25 @@ const commitThirtyMinuteHistory = functoolsKit.trycatch(async (symbol, history)
|
|
|
2859
4599
|
}, {
|
|
2860
4600
|
fallback: () => backtestKit.Cache.clear(fetchThirtyMinuteHistory),
|
|
2861
4601
|
});
|
|
4602
|
+
/**
|
|
4603
|
+
* Commits 15-minute candle history report to history container.
|
|
4604
|
+
*
|
|
4605
|
+
* Fetches and appends a markdown-formatted report of the last 8 fifteen-minute candles
|
|
4606
|
+
* including OHLCV data, volatility, body size, and candle type (Green/Red/Doji).
|
|
4607
|
+
* Automatically clears cache on errors to ensure data freshness.
|
|
4608
|
+
*
|
|
4609
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4610
|
+
* @param history - History container to append report to
|
|
4611
|
+
* @returns Promise that resolves when report is committed
|
|
4612
|
+
*
|
|
4613
|
+
* @example
|
|
4614
|
+
* ```typescript
|
|
4615
|
+
* import { commitFifteenMinuteHistory } from '@backtest-kit/signals';
|
|
4616
|
+
*
|
|
4617
|
+
* const messages = [];
|
|
4618
|
+
* await commitFifteenMinuteHistory('BTCUSDT', messages);
|
|
4619
|
+
* ```
|
|
4620
|
+
*/
|
|
2862
4621
|
const commitFifteenMinuteHistory = functoolsKit.trycatch(async (symbol, history) => {
|
|
2863
4622
|
const fifteenMinuteHistory = await fetchFifteenMinuteHistory(symbol);
|
|
2864
4623
|
await history.push({
|
|
@@ -2871,6 +4630,25 @@ const commitFifteenMinuteHistory = functoolsKit.trycatch(async (symbol, history)
|
|
|
2871
4630
|
}, {
|
|
2872
4631
|
fallback: () => backtestKit.Cache.clear(fetchFifteenMinuteHistory),
|
|
2873
4632
|
});
|
|
4633
|
+
/**
|
|
4634
|
+
* Commits 1-minute candle history report to history container.
|
|
4635
|
+
*
|
|
4636
|
+
* Fetches and appends a markdown-formatted report of the last 15 one-minute candles
|
|
4637
|
+
* including OHLCV data, volatility, body size, and candle type (Green/Red/Doji).
|
|
4638
|
+
* Automatically clears cache on errors to ensure data freshness.
|
|
4639
|
+
*
|
|
4640
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4641
|
+
* @param history - History container to append report to
|
|
4642
|
+
* @returns Promise that resolves when report is committed
|
|
4643
|
+
*
|
|
4644
|
+
* @example
|
|
4645
|
+
* ```typescript
|
|
4646
|
+
* import { commitOneMinuteHistory } from '@backtest-kit/signals';
|
|
4647
|
+
*
|
|
4648
|
+
* const messages = [];
|
|
4649
|
+
* await commitOneMinuteHistory('BTCUSDT', messages);
|
|
4650
|
+
* ```
|
|
4651
|
+
*/
|
|
2874
4652
|
const commitOneMinuteHistory = functoolsKit.trycatch(async (symbol, history) => {
|
|
2875
4653
|
const oneMinuteHistory = await fetchOneMinuteHistory(symbol);
|
|
2876
4654
|
await history.push({
|
|
@@ -2884,18 +4662,83 @@ const commitOneMinuteHistory = functoolsKit.trycatch(async (symbol, history) =>
|
|
|
2884
4662
|
fallback: () => backtestKit.Cache.clear(fetchOneMinuteHistory),
|
|
2885
4663
|
});
|
|
2886
4664
|
|
|
4665
|
+
/**
|
|
4666
|
+
* Technical indicator report generation functions for multi-timeframe trading analysis.
|
|
4667
|
+
*
|
|
4668
|
+
* Provides cached functions to fetch and commit comprehensive technical indicator reports
|
|
4669
|
+
* across 4 trading timeframes (MicroTerm: 1m, ShortTerm: 15m, SwingTerm: 30m, LongTerm: 1h).
|
|
4670
|
+
* Each report includes 50+ indicators formatted as markdown tables for LLM consumption.
|
|
4671
|
+
*
|
|
4672
|
+
* Key features:
|
|
4673
|
+
* - MicroTerm (1m): RSI(9,14), MACD(8,21,5), Stochastic, ADX(9), Bollinger(8,2), ATR, CCI, Volume analysis, Squeeze momentum
|
|
4674
|
+
* - ShortTerm (15m): RSI(9), MACD(8,21,5), Stochastic(5,3,3), ADX(14), Bollinger(10,2), Fibonacci levels
|
|
4675
|
+
* - SwingTerm (30m): RSI(14), MACD(12,26,9), Stochastic(14,3,3), Bollinger(20,2), Support/Resistance, Fibonacci
|
|
4676
|
+
* - LongTerm (1h): RSI(14), MACD(12,26,9), ADX(14), Bollinger(20,2), SMA(50), DEMA, WMA, Volume trends
|
|
4677
|
+
* - Intelligent caching with timeframe-specific TTL
|
|
4678
|
+
* - Automatic cache clearing on errors
|
|
4679
|
+
*
|
|
4680
|
+
* @module function/math
|
|
4681
|
+
*/
|
|
4682
|
+
/**
|
|
4683
|
+
* Cached function to fetch MicroTerm (1-minute) technical analysis report.
|
|
4684
|
+
* Cache TTL: 1 minute
|
|
4685
|
+
*/
|
|
2887
4686
|
const fetchMicroTermMath = backtestKit.Cache.fn(signal.microTermMathService.getReport, {
|
|
2888
4687
|
interval: "1m",
|
|
2889
4688
|
});
|
|
4689
|
+
/**
|
|
4690
|
+
* Cached function to fetch ShortTerm (15-minute) technical analysis report.
|
|
4691
|
+
* Cache TTL: 5 minutes
|
|
4692
|
+
*/
|
|
2890
4693
|
const fetchShortTermMath = backtestKit.Cache.fn(signal.shortTermMathService.getReport, {
|
|
2891
4694
|
interval: "5m",
|
|
2892
4695
|
});
|
|
4696
|
+
/**
|
|
4697
|
+
* Cached function to fetch SwingTerm (30-minute) technical analysis report.
|
|
4698
|
+
* Cache TTL: 15 minutes
|
|
4699
|
+
*/
|
|
2893
4700
|
const fetchSwingTermMath = backtestKit.Cache.fn(signal.swingTermMathService.getReport, {
|
|
2894
4701
|
interval: "15m",
|
|
2895
4702
|
});
|
|
4703
|
+
/**
|
|
4704
|
+
* Cached function to fetch LongTerm (1-hour) technical analysis report.
|
|
4705
|
+
* Cache TTL: 30 minutes
|
|
4706
|
+
*/
|
|
2896
4707
|
const fetchLongTermMath = backtestKit.Cache.fn(signal.longTermMathService.getReport, {
|
|
2897
4708
|
interval: "30m",
|
|
2898
4709
|
});
|
|
4710
|
+
/**
|
|
4711
|
+
* Commits MicroTerm (1-minute) technical analysis report to history container.
|
|
4712
|
+
*
|
|
4713
|
+
* Generates comprehensive technical analysis for scalping and ultra-short term trading.
|
|
4714
|
+
* Includes 40+ indicators optimized for 1-minute timeframe with 60-candle lookback.
|
|
4715
|
+
*
|
|
4716
|
+
* Indicators included:
|
|
4717
|
+
* - Momentum: RSI(9,14), Stochastic RSI(9,14), MACD(8,21,5), Momentum(5,10), ROC(1,3,5)
|
|
4718
|
+
* - Trend: ADX(9), +DI/-DI(9), EMA(3,8,13,21), SMA(8), DEMA(8), WMA(5)
|
|
4719
|
+
* - Volatility: ATR(5,9), Bollinger Bands(8,2) with width/position, Squeeze momentum
|
|
4720
|
+
* - Volume: SMA(5), volume ratio, volume trend (increasing/decreasing/stable)
|
|
4721
|
+
* - Support/Resistance: Dynamic levels from 30-candle window
|
|
4722
|
+
* - Price Analysis: 1m/3m/5m price changes, volatility, true range, pressure index
|
|
4723
|
+
*
|
|
4724
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4725
|
+
* @param history - History container to append report to
|
|
4726
|
+
* @returns Promise that resolves when report is committed
|
|
4727
|
+
*
|
|
4728
|
+
* @example
|
|
4729
|
+
* ```typescript
|
|
4730
|
+
* import { commitMicroTermMath } from '@backtest-kit/signals';
|
|
4731
|
+
*
|
|
4732
|
+
* const messages = [];
|
|
4733
|
+
* await commitMicroTermMath('BTCUSDT', messages);
|
|
4734
|
+
*
|
|
4735
|
+
* // Use in LLM strategy for scalping signals
|
|
4736
|
+
* const signal = await llm([
|
|
4737
|
+
* { role: 'system', content: 'Analyze for scalping opportunities' },
|
|
4738
|
+
* ...messages
|
|
4739
|
+
* ]);
|
|
4740
|
+
* ```
|
|
4741
|
+
*/
|
|
2899
4742
|
const commitMicroTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
2900
4743
|
const microTermMath = await fetchMicroTermMath(symbol);
|
|
2901
4744
|
await history.push({
|
|
@@ -2908,6 +4751,32 @@ const commitMicroTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2908
4751
|
}, {
|
|
2909
4752
|
fallback: () => backtestKit.Cache.clear(fetchMicroTermMath),
|
|
2910
4753
|
});
|
|
4754
|
+
/**
|
|
4755
|
+
* Commits LongTerm (1-hour) technical analysis report to history container.
|
|
4756
|
+
*
|
|
4757
|
+
* Generates comprehensive technical analysis for trend identification and position management.
|
|
4758
|
+
* Includes 30+ indicators optimized for 1-hour timeframe with 48-candle lookback (48 hours).
|
|
4759
|
+
*
|
|
4760
|
+
* Indicators included:
|
|
4761
|
+
* - Momentum: RSI(14), Stochastic RSI(14), MACD(12,26,9), Stochastic(14,3,3), Momentum(10)
|
|
4762
|
+
* - Trend: ADX(14), +DI/-DI(14), SMA(50), EMA(20,34), DEMA(21), WMA(20)
|
|
4763
|
+
* - Volatility: ATR(14,20), Bollinger Bands(20,2), CCI(20)
|
|
4764
|
+
* - Support/Resistance: 4-candle pivot detection
|
|
4765
|
+
* - Fibonacci: Retracement levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%) with nearest level
|
|
4766
|
+
* - Volume: Trend analysis (increasing/decreasing/stable)
|
|
4767
|
+
*
|
|
4768
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4769
|
+
* @param history - History container to append report to
|
|
4770
|
+
* @returns Promise that resolves when report is committed
|
|
4771
|
+
*
|
|
4772
|
+
* @example
|
|
4773
|
+
* ```typescript
|
|
4774
|
+
* import { commitLongTermMath } from '@backtest-kit/signals';
|
|
4775
|
+
*
|
|
4776
|
+
* const messages = [];
|
|
4777
|
+
* await commitLongTermMath('ETHUSDT', messages);
|
|
4778
|
+
* ```
|
|
4779
|
+
*/
|
|
2911
4780
|
const commitLongTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
2912
4781
|
const longTermMath = await fetchLongTermMath(symbol);
|
|
2913
4782
|
await history.push({
|
|
@@ -2920,6 +4789,32 @@ const commitLongTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2920
4789
|
}, {
|
|
2921
4790
|
fallback: () => backtestKit.Cache.clear(fetchLongTermMath),
|
|
2922
4791
|
});
|
|
4792
|
+
/**
|
|
4793
|
+
* Commits ShortTerm (15-minute) technical analysis report to history container.
|
|
4794
|
+
*
|
|
4795
|
+
* Generates comprehensive technical analysis for day trading strategies.
|
|
4796
|
+
* Includes 30+ indicators optimized for 15-minute timeframe with 144-candle lookback (36 hours).
|
|
4797
|
+
*
|
|
4798
|
+
* Indicators included:
|
|
4799
|
+
* - Momentum: RSI(9), Stochastic RSI(9), MACD(8,21,5), Stochastic(5,3,3), Momentum(8), ROC(5,10)
|
|
4800
|
+
* - Trend: ADX(14), +DI/-DI(14), SMA(50), EMA(8,21), DEMA(21), WMA(20)
|
|
4801
|
+
* - Volatility: ATR(9), Bollinger Bands(10,2) with width, CCI(14)
|
|
4802
|
+
* - Support/Resistance: 48-candle window with 0.3% threshold
|
|
4803
|
+
* - Fibonacci: Retracement levels over 288-candle lookback (72 hours)
|
|
4804
|
+
* - Volume: Trend analysis over 16-candle window
|
|
4805
|
+
*
|
|
4806
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4807
|
+
* @param history - History container to append report to
|
|
4808
|
+
* @returns Promise that resolves when report is committed
|
|
4809
|
+
*
|
|
4810
|
+
* @example
|
|
4811
|
+
* ```typescript
|
|
4812
|
+
* import { commitShortTermMath } from '@backtest-kit/signals';
|
|
4813
|
+
*
|
|
4814
|
+
* const messages = [];
|
|
4815
|
+
* await commitShortTermMath('BTCUSDT', messages);
|
|
4816
|
+
* ```
|
|
4817
|
+
*/
|
|
2923
4818
|
const commitShortTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
2924
4819
|
const shortTermMath = await fetchShortTermMath(symbol);
|
|
2925
4820
|
await history.push({
|
|
@@ -2932,6 +4827,33 @@ const commitShortTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2932
4827
|
}, {
|
|
2933
4828
|
fallback: () => backtestKit.Cache.clear(fetchShortTermMath),
|
|
2934
4829
|
});
|
|
4830
|
+
/**
|
|
4831
|
+
* Commits SwingTerm (30-minute) technical analysis report to history container.
|
|
4832
|
+
*
|
|
4833
|
+
* Generates comprehensive technical analysis for swing trading strategies.
|
|
4834
|
+
* Includes 30+ indicators optimized for 30-minute timeframe with 96-candle lookback (48 hours).
|
|
4835
|
+
*
|
|
4836
|
+
* Indicators included:
|
|
4837
|
+
* - Momentum: RSI(14), Stochastic RSI(14), MACD(12,26,9), Stochastic(14,3,3), Momentum(8)
|
|
4838
|
+
* - Trend: ADX(14), +DI/-DI(14), SMA(20), EMA(13,34), DEMA(21), WMA(20)
|
|
4839
|
+
* - Volatility: ATR(14), Bollinger Bands(20,2) with width, CCI(20), Basic volatility
|
|
4840
|
+
* - Support/Resistance: 20-candle window detection
|
|
4841
|
+
* - Fibonacci: Support/resistance levels with current level identification
|
|
4842
|
+
* - Volume: Trading volume analysis
|
|
4843
|
+
* - Price Momentum: 6-period momentum indicator
|
|
4844
|
+
*
|
|
4845
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4846
|
+
* @param history - History container to append report to
|
|
4847
|
+
* @returns Promise that resolves when report is committed
|
|
4848
|
+
*
|
|
4849
|
+
* @example
|
|
4850
|
+
* ```typescript
|
|
4851
|
+
* import { commitSwingTermMath } from '@backtest-kit/signals';
|
|
4852
|
+
*
|
|
4853
|
+
* const messages = [];
|
|
4854
|
+
* await commitSwingTermMath('BTCUSDT', messages);
|
|
4855
|
+
* ```
|
|
4856
|
+
*/
|
|
2935
4857
|
const commitSwingTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
2936
4858
|
const swingTermMath = await fetchSwingTermMath(symbol);
|
|
2937
4859
|
await history.push({
|
|
@@ -2945,9 +4867,59 @@ const commitSwingTermMath = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2945
4867
|
fallback: () => backtestKit.Cache.clear(fetchSwingTermMath),
|
|
2946
4868
|
});
|
|
2947
4869
|
|
|
4870
|
+
/**
|
|
4871
|
+
* Orchestrator functions for complete market analysis setup.
|
|
4872
|
+
*
|
|
4873
|
+
* Provides high-level functions that combine multiple analysis types
|
|
4874
|
+
* (order book, candle history, technical indicators) into comprehensive
|
|
4875
|
+
* market reports for LLM-based trading strategies.
|
|
4876
|
+
*
|
|
4877
|
+
* Key features:
|
|
4878
|
+
* - commitBookDataReport: Order book analysis with top 20 levels by volume
|
|
4879
|
+
* - commitHistorySetup: All-in-one setup with full multi-timeframe analysis
|
|
4880
|
+
* - Automatic mode detection (skips order book in backtest mode)
|
|
4881
|
+
* - System context injection (symbol, price, timestamp)
|
|
4882
|
+
*
|
|
4883
|
+
* @module function/other
|
|
4884
|
+
*/
|
|
4885
|
+
/**
|
|
4886
|
+
* Cached function to fetch order book analysis report.
|
|
4887
|
+
* Cache TTL: 5 minutes
|
|
4888
|
+
*/
|
|
2948
4889
|
const fetchBookData = backtestKit.Cache.fn(signal.bookDataMathService.getReport, {
|
|
2949
4890
|
interval: "5m",
|
|
2950
4891
|
});
|
|
4892
|
+
/**
|
|
4893
|
+
* Commits order book analysis report to history container.
|
|
4894
|
+
*
|
|
4895
|
+
* Fetches and appends real-time order book data including top 20 price levels
|
|
4896
|
+
* by volume percentage, best bid/ask, mid price, spread, and depth imbalance.
|
|
4897
|
+
* Automatically skipped in backtest mode (order book data unavailable).
|
|
4898
|
+
*
|
|
4899
|
+
* Order book metrics:
|
|
4900
|
+
* - Best Bid/Ask: Top buy and sell prices
|
|
4901
|
+
* - Mid Price: (Best Bid + Best Ask) / 2
|
|
4902
|
+
* - Spread: Best Ask - Best Bid
|
|
4903
|
+
* - Depth Imbalance: (Bid Volume - Ask Volume) / (Bid Volume + Ask Volume)
|
|
4904
|
+
* - Positive = buying pressure
|
|
4905
|
+
* - Negative = selling pressure
|
|
4906
|
+
* - Top 20 Levels: Sorted by volume percentage on each side
|
|
4907
|
+
*
|
|
4908
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4909
|
+
* @param history - History container to append report to
|
|
4910
|
+
* @returns Promise that resolves when report is committed (or immediately in backtest mode)
|
|
4911
|
+
*
|
|
4912
|
+
* @example
|
|
4913
|
+
* ```typescript
|
|
4914
|
+
* import { commitBookDataReport } from '@backtest-kit/signals';
|
|
4915
|
+
*
|
|
4916
|
+
* const messages = [];
|
|
4917
|
+
* await commitBookDataReport('BTCUSDT', messages);
|
|
4918
|
+
*
|
|
4919
|
+
* // In live mode: messages contains order book analysis
|
|
4920
|
+
* // In backtest mode: messages unchanged (order book skipped)
|
|
4921
|
+
* ```
|
|
4922
|
+
*/
|
|
2951
4923
|
const commitBookDataReport = functoolsKit.trycatch(async (symbol, history) => {
|
|
2952
4924
|
const mode = await backtestKit.getMode();
|
|
2953
4925
|
if (mode === "backtest") {
|
|
@@ -2964,15 +4936,56 @@ const commitBookDataReport = functoolsKit.trycatch(async (symbol, history) => {
|
|
|
2964
4936
|
}, {
|
|
2965
4937
|
fallback: () => backtestKit.Cache.clear(fetchBookData),
|
|
2966
4938
|
});
|
|
4939
|
+
/**
|
|
4940
|
+
* Commits complete multi-timeframe market analysis setup to history container.
|
|
4941
|
+
*
|
|
4942
|
+
* All-in-one function that orchestrates the full technical analysis pipeline.
|
|
4943
|
+
* Sequentially commits order book data, candle histories, technical indicators,
|
|
4944
|
+
* and system context for comprehensive LLM-based trading analysis.
|
|
4945
|
+
*
|
|
4946
|
+
* Analysis pipeline:
|
|
4947
|
+
* 1. Order Book: Top 20 levels, bid/ask depth, spread, imbalance (live mode only)
|
|
4948
|
+
* 2. Candle Histories: 1m (15 candles), 15m (8 candles), 30m (6 candles), 1h (6 candles)
|
|
4949
|
+
* 3. Technical Indicators:
|
|
4950
|
+
* - MicroTerm (1m): 40+ scalping indicators
|
|
4951
|
+
* - ShortTerm (15m): 30+ day trading indicators
|
|
4952
|
+
* - SwingTerm (30m): 30+ swing trading indicators
|
|
4953
|
+
* - LongTerm (1h): 30+ trend indicators
|
|
4954
|
+
* 4. System Context: Symbol, current price (VWAP), timestamp
|
|
4955
|
+
*
|
|
4956
|
+
* Total output: 150+ indicators across 4 timeframes + order book + candle data
|
|
4957
|
+
*
|
|
4958
|
+
* @param symbol - Trading pair symbol (e.g., 'BTCUSDT')
|
|
4959
|
+
* @param history - History container to append all reports to
|
|
4960
|
+
* @returns Promise that resolves when all reports are committed
|
|
4961
|
+
*
|
|
4962
|
+
* @example
|
|
4963
|
+
* ```typescript
|
|
4964
|
+
* import { commitHistorySetup } from '@backtest-kit/signals';
|
|
4965
|
+
* import { json } from './llm-wrapper';
|
|
4966
|
+
*
|
|
4967
|
+
* // Complete LLM strategy setup
|
|
4968
|
+
* const messages = [
|
|
4969
|
+
* { role: 'system', content: 'You are a trading bot. Analyze and generate signals.' }
|
|
4970
|
+
* ];
|
|
4971
|
+
*
|
|
4972
|
+
* // Inject all technical analysis
|
|
4973
|
+
* await commitHistorySetup('BTCUSDT', messages);
|
|
4974
|
+
*
|
|
4975
|
+
* // Generate trading signal
|
|
4976
|
+
* const signal = await json(messages);
|
|
4977
|
+
* console.log(signal); // { position: 'long', priceTakeProfit: 50500, priceStopLoss: 49500 }
|
|
4978
|
+
* ```
|
|
4979
|
+
*/
|
|
2967
4980
|
const commitHistorySetup = async (symbol, history) => {
|
|
2968
|
-
//
|
|
4981
|
+
// Order book analysis
|
|
2969
4982
|
await commitBookDataReport(symbol, history);
|
|
2970
|
-
//
|
|
4983
|
+
// Candle histories across timeframes
|
|
2971
4984
|
await commitOneMinuteHistory(symbol, history);
|
|
2972
4985
|
await commitFifteenMinuteHistory(symbol, history);
|
|
2973
4986
|
await commitThirtyMinuteHistory(symbol, history);
|
|
2974
4987
|
await commitHourHistory(symbol, history);
|
|
2975
|
-
//
|
|
4988
|
+
// Technical indicators across timeframes
|
|
2976
4989
|
await commitMicroTermMath(symbol, history);
|
|
2977
4990
|
await commitShortTermMath(symbol, history);
|
|
2978
4991
|
await commitSwingTermMath(symbol, history);
|
|
@@ -2986,6 +4999,43 @@ const commitHistorySetup = async (symbol, history) => {
|
|
|
2986
4999
|
});
|
|
2987
5000
|
};
|
|
2988
5001
|
|
|
5002
|
+
/**
|
|
5003
|
+
* Configuration utilities for signals library.
|
|
5004
|
+
*
|
|
5005
|
+
* Provides functions to customize library behavior, primarily logging configuration.
|
|
5006
|
+
*
|
|
5007
|
+
* @module tools/setup
|
|
5008
|
+
*/
|
|
5009
|
+
/**
|
|
5010
|
+
* Sets custom logger implementation for signals library.
|
|
5011
|
+
*
|
|
5012
|
+
* By default, signals uses a no-op logger (no output).
|
|
5013
|
+
* Use this function to enable logging for debugging and monitoring.
|
|
5014
|
+
*
|
|
5015
|
+
* @param logger - Custom logger implementation conforming to ILogger interface
|
|
5016
|
+
*
|
|
5017
|
+
* @example
|
|
5018
|
+
* ```typescript
|
|
5019
|
+
* import { setLogger } from '@backtest-kit/signals';
|
|
5020
|
+
*
|
|
5021
|
+
* // Enable console logging
|
|
5022
|
+
* setLogger({
|
|
5023
|
+
* log: console.log,
|
|
5024
|
+
* debug: console.debug,
|
|
5025
|
+
* info: console.info,
|
|
5026
|
+
* warn: console.warn,
|
|
5027
|
+
* });
|
|
5028
|
+
*
|
|
5029
|
+
* // Or use custom logger
|
|
5030
|
+
* import winston from 'winston';
|
|
5031
|
+
* setLogger({
|
|
5032
|
+
* log: (topic, ...args) => winston.log('info', topic, args),
|
|
5033
|
+
* debug: (topic, ...args) => winston.debug(topic, args),
|
|
5034
|
+
* info: (topic, ...args) => winston.info(topic, args),
|
|
5035
|
+
* warn: (topic, ...args) => winston.warn(topic, args),
|
|
5036
|
+
* });
|
|
5037
|
+
* ```
|
|
5038
|
+
*/
|
|
2989
5039
|
const setLogger = (logger) => {
|
|
2990
5040
|
signal.loggerService.setLogger(logger);
|
|
2991
5041
|
};
|