From 7827220b9b74066d30e66be8df66958b9f505905 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 21 Oct 2026 20:27:07 -0400 Subject: [PATCH] Extract shared calculations and preserve legacy research capabilities --- README.md | 53 +- .../ceo/actions/get-channels.action.ts | 2 +- .../handlers/ceo/actions/get-posts.action.ts | 2 +- .../handlers/ceo/actions/get-shorts.action.ts | 2 +- .../handlers/eod/actions/corporate-actions.ts | 2 +- .../src/handlers/eod/actions/fundamentals.ts | 2 +- .../src/handlers/qm/shared/config.ts | 4 +- .../te/actions/fetch-countries.action.ts | 2 +- .../te/actions/fetch-indicators.action.ts | 2 +- .../src/handlers/te/actions/spider.action.ts | 3 +- .../actions/fetch-exchanges.action.ts | 2 +- .../src/handlers/tt/actions/import.action.ts | 2 +- .../operation-manager/OperationRegistry.ts | 2 +- .../operation-manager/OperationTracker.ts | 2 +- .../docs/architecture-improvements.md | 2 +- .../orchestrator/docs/technical-indicators.md | 4 +- apps/stock/orchestrator/package.json | 3 +- .../src/analytics/PerformanceAnalyzer.ts | 10 +- .../src/backtest/MarketSimulator.ts | 2 +- .../src/backtest/report-format.ts | 2 +- .../src/indicators/TechnicalAnalysis.ts | 2 +- .../builtin/MeanReversionStrategy.ts | 2 +- .../builtin/SmaCrossoverStrategy.ts | 2 +- .../experimental/MLEnhancedStrategy.ts | 3 +- bun.lock | 23 +- docs/cleanup-audit.md | 50 + libs/calculations/README.md | 96 ++ libs/calculations/migration-audit.json | 408 +++++ libs/calculations/package.json | 30 + libs/calculations/research/README.md | 26 + .../research/correlation-analysis.md} | 12 + .../research/market-statistics.md} | 12 + .../research/options-pricing.md} | 12 + .../research/portfolio-analytics.md} | 12 + .../research/position-sizing-notes.md} | 206 +-- .../research/position-sizing.md} | 12 + .../research/technical-indicators.md} | 12 + .../research/volatility-models.md} | 12 + .../calculations}/src/analytics/equity.ts | 0 libs/calculations/src/analytics/index.ts | 6 + .../src/analytics/performance.ts | 0 .../src/analytics/return-statistics.ts | 0 .../src/analytics/trade-statistics.ts | 0 libs/calculations/src/index.ts | 31 + libs/calculations/src/indicators/index.ts | 6 + libs/calculations/src/indicators/sma.ts | 22 + .../src/indicators/window-statistics.ts | 0 .../src/legacy}/basic-calculations.ts | 1 + libs/calculations/src/legacy/index.ts | 5 + .../src/legacy}/performance-metrics.ts | 1 + .../src/legacy}/risk-metrics.ts | 1 + .../src/legacy}/technical-indicators.ts | 1 + .../src/market-data.ts} | 107 +- libs/calculations/src/returns.ts | 80 + libs/calculations/test/core.test.ts | 125 ++ .../test/market-data.test.ts} | 86 +- libs/calculations/test/preservation.test.ts | 55 + libs/calculations/tsconfig.json | 9 + .../connection-manager-tests.md} | 1096 ++++++------- .../redis-cache-tests.md} | 1402 +++++++++-------- libs/core/handlers/src/base/BaseHandler.ts | 3 +- .../src/registry/handler-registry.ts.old | 184 --- .../handlers/test/base-handler-http.test.ts | 4 +- libs/utils/README.md | 113 +- libs/utils/package.json | 11 +- libs/utils/src/assertions.ts | 1 - libs/utils/src/calculations/index.ts | 104 -- libs/utils/src/dateUtils.ts | 94 +- libs/utils/src/fetch.ts | 2 +- libs/utils/src/index.ts | 12 +- libs/utils/test/common-dates.test.ts | 117 ++ libs/utils/test/fetch.test.ts | 7 +- libs/utils/test/user-agent.test.ts | 2 +- libs/utils/tsconfig.json | 11 +- package.json | 2 + scripts/check.ts | 2 + scripts/runtime-imports.ts | 60 + scripts/test/architecture.test.ts | 75 +- scripts/test/library-boundaries.test.ts | 204 +++ test/integration/analytics-math.test.ts | 11 +- test/integration/strategy-contracts.test.ts | 2 +- tools/coverage-cli/package.json | 1 - 82 files changed, 3099 insertions(+), 1994 deletions(-) create mode 100644 docs/cleanup-audit.md create mode 100644 libs/calculations/README.md create mode 100644 libs/calculations/migration-audit.json create mode 100644 libs/calculations/package.json create mode 100644 libs/calculations/research/README.md rename libs/{utils/src/calculations/correlation-analysis.ts.disabled => calculations/research/correlation-analysis.md} (98%) rename libs/{utils/src/calculations/market-statistics.ts.disabled => calculations/research/market-statistics.md} (98%) rename libs/{utils/src/calculations/options-pricing.ts.disabled => calculations/research/options-pricing.md} (97%) rename libs/{utils/src/calculations/portfolio-analytics.ts.disabled => calculations/research/portfolio-analytics.md} (97%) rename libs/{utils/POSITION_SIZING_FIXES.md => calculations/research/position-sizing-notes.md} (90%) rename libs/{utils/src/calculations/position-sizing.ts.disabled => calculations/research/position-sizing.md} (97%) rename libs/{utils/src/calculations/technical-indicators.ts.disabled => calculations/research/technical-indicators.md} (99%) rename libs/{utils/src/calculations/volatility-models.ts.disabled => calculations/research/volatility-models.md} (97%) rename {apps/stock/orchestrator => libs/calculations}/src/analytics/equity.ts (100%) create mode 100644 libs/calculations/src/analytics/index.ts rename {apps/stock/orchestrator => libs/calculations}/src/analytics/performance.ts (100%) rename {apps/stock/orchestrator => libs/calculations}/src/analytics/return-statistics.ts (100%) rename {apps/stock/orchestrator => libs/calculations}/src/analytics/trade-statistics.ts (100%) create mode 100644 libs/calculations/src/index.ts create mode 100644 libs/calculations/src/indicators/index.ts create mode 100644 libs/calculations/src/indicators/sma.ts rename {apps/stock/orchestrator => libs/calculations}/src/indicators/window-statistics.ts (100%) rename libs/{utils/src/calculations => calculations/src/legacy}/basic-calculations.ts (99%) create mode 100644 libs/calculations/src/legacy/index.ts rename libs/{utils/src/calculations => calculations/src/legacy}/performance-metrics.ts (99%) rename libs/{utils/src/calculations => calculations/src/legacy}/risk-metrics.ts (99%) rename libs/{utils/src/calculations => calculations/src/legacy}/technical-indicators.ts (99%) rename libs/{utils/src/generic-functions.ts => calculations/src/market-data.ts} (63%) create mode 100644 libs/calculations/src/returns.ts create mode 100644 libs/calculations/test/core.test.ts rename libs/{utils/test/utils.test.ts => calculations/test/market-data.test.ts} (62%) create mode 100644 libs/calculations/test/preservation.test.ts create mode 100644 libs/calculations/tsconfig.json rename libs/core/cache/test/{connection-manager.test.ts.old => references/connection-manager-tests.md} (96%) rename libs/core/cache/test/{redis-cache.test.ts.old => references/redis-cache-tests.md} (96%) delete mode 100644 libs/core/handlers/src/registry/handler-registry.ts.old delete mode 100644 libs/utils/src/assertions.ts delete mode 100644 libs/utils/src/calculations/index.ts create mode 100644 libs/utils/test/common-dates.test.ts create mode 100644 scripts/runtime-imports.ts create mode 100644 scripts/test/library-boundaries.test.ts diff --git a/README.md b/README.md index cdf8c565..59e2abc6 100644 --- a/README.md +++ b/README.md @@ -19,16 +19,18 @@ bun run check The root build selects every buildable leaf workspace, including all stock services and the native engine. `bun run build --dry=json` shows the actual Turbo task plan. -| Command | Scope | -| -------------------------- | ------------------------------------------------------------------------------------------------------- | -| `bun run build:libs` | Build shared libraries in dependency order | -| `bun run build --clean` | Force every workspace build without cached results | -| `bun run typecheck` | Check library, stock application, and tool source directly | -| `bun run test:contracts` | Compile positive and negative service-contract assertions | -| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | -| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | -| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | -| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate | +| Command | Scope | +| --------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `bun run build:libs` | Build shared libraries in dependency order | +| `bun run build --clean` | Force every workspace build without cached results | +| `bun run typecheck` | Check library, stock application, and tool source directly | +| `bun run test:contracts` | Compile positive and negative service-contract assertions | +| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | +| `bun run test:utils` | Test HTTP/date/proxy helpers and their handler HTTP consumer without infrastructure | +| `bun run test:calculations` | Test shared math, OHLCV transforms, legacy capability preservation and research snapshots | +| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | +| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | +| `bun run check` | Run build, type checking, contracts, tooling, utilities, calculations, integration, native tests, and lint | `check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined. The larger existing `bun run test` suite is separate: @@ -40,6 +42,35 @@ changing Rust APIs. TensorFlow is loaded only when starting the optional ML stra Its TypeScript dependency is present for checking; using ML also requires installing its platform-specific native binding. Dependency install scripts were not enabled for verification. +## Shared calculation and utility boundaries + +`@stock-bot/calculations` owns pure reusable math for strategies, data processing and +feature engineering. Its supported subpaths expose reviewed returns, indicators, OHLCV +transforms and the previously tested orchestrator analytics/window math. The orchestrator +now consumes that library; no database, native binding, HTTP or application service is +required to import it. Existing strategy checkpoint versions and financial execution +behavior are unchanged by this relocation. + +All 105 formerly active financial calculation functions remain available behind the +explicit `@stock-bot/calculations/legacy` namespace, with unchanged executable bodies. +This is preservation, not a production-correctness endorsement. All seven previously +disabled prototypes, including unique additional indicators, survive as non-executable +source-verified research snapshots. See [the calculation contract](libs/calculations/README.md) +for supported units, undefined values, alignment and the review/promotion path. + +`@stock-bot/utils` retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday +helpers through explicit capability subpaths. Deprecated `dateUtils` names are aliases, +not an exchange holiday/session calendar. Assertions belong to `@stock-bot/invariants`, +and domain types to `@stock-bot/types`. The coverage CLI no longer declares an unused +utility dependency, and unused `simple-statistics` is removed. + +Only empty placeholder/redundant entry points remain removed; old numerical and Redis +test sources are retained as explicit legacy/research references rather than runnable +backups or claimed passing coverage. [The cleanup audit](docs/cleanup-audit.md) accounts +for every removal in this batch. [The utility contract](libs/utils/README.md) documents +the restored helpers and migration notes. Architecture tests enforce the ownership and +dependency boundaries without forbidding useful shared domain libraries. + ## Service contracts `@stock-bot/types` contains independent domain, job, and handler types. @@ -124,7 +155,7 @@ while native SMA uses 100 shares. Native mean reversion, momentum and pairs reta accepts configurable lookback/trend/RSI windows, entry/exit thresholds and notional-volume filter; its optional `quantity` is also shares. Do not transfer backend-only parameters blindly. -`indicators/window-statistics.ts` shares slice-free trailing mean, population deviation +`@stock-bot/calculations/indicators` shares slice-free trailing mean, population deviation and crossover calculations across TypeScript strategies. A crossover requires `slowPeriod + 1` bars, including a complete previous window; missing warm-up is not a synthetic zero average. Tests compare the scalar math with real Rust batch/incremental indicators and exercise diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts index 20e3a340..2ae0cd6f 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts @@ -1,4 +1,4 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import type { CeoHandler } from '../ceo.handler'; export async function getChannels(this: CeoHandler, payload: number | undefined): Promise { diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts index 97cd432b..c6bbbad3 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts @@ -1,4 +1,4 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import type { CeoHandler } from '../ceo.handler'; export async function getPosts( diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts index e626aa7a..aeec6255 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts @@ -1,4 +1,4 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import type { CeoHandler } from '../ceo.handler'; export async function getShorts( diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts index 89f1d6e2..a18e9c9f 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts @@ -1,4 +1,4 @@ -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import type { EodHandler } from '../eod.handler'; import { EOD_CONFIG } from '../shared'; diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts index cf8b4827..d4139440 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts @@ -1,4 +1,4 @@ -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import type { EodHandler } from '../eod.handler'; import { EOD_CONFIG } from '../shared'; diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/config.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/config.ts index 93c7b296..aa39b2b5 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/config.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/config.ts @@ -2,7 +2,7 @@ * Shared configuration for QM operations */ -import { getRandomUserAgent } from "@stock-bot/utils"; +import { getRandomUserAgent } from "@stock-bot/utils/user-agent"; // QM Session IDs for different endpoints export const QM_SESSION_IDS = { @@ -141,4 +141,4 @@ export function getWeekEnd(dateInput: Date | string): Date { // Set to end of day date.setHours(23, 59, 59, 999); return date; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts index 549d47ed..baa1e909 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts @@ -1,5 +1,5 @@ import * as cheerio from 'cheerio'; -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts index 00d8cb84..8aa8d22f 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts @@ -1,5 +1,5 @@ import * as cheerio from 'cheerio'; -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts index c8e8c5cb..993cbcea 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts @@ -1,5 +1,6 @@ import * as cheerio from 'cheerio'; -import { at, getRandomUserAgent } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; diff --git a/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts b/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts index b81ed36a..f09335b3 100644 --- a/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts +++ b/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts @@ -1,4 +1,4 @@ -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import { TRADINGVIEW_CONFIG } from '../shared/config'; import { type TradingViewExchange } from '../shared/types'; import type { TradingViewHandler } from '../tradingview.handler'; diff --git a/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts b/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts index 7d7dafbd..86d961ca 100644 --- a/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts +++ b/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'fs'; import { join } from 'path'; import * as cheerio from 'cheerio'; import { defined } from '@stock-bot/invariants'; -import { getRandomUserAgent } from '@stock-bot/utils'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; import type { TtHandler } from '../tt.handler'; const BASE_URL = 'https://www.turtletrader.com'; diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts index 1446cf3e..1c21b8ec 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts @@ -4,7 +4,7 @@ import type { Document } from 'mongodb'; */ import type { Logger, MongoDBClient } from '@stock-bot/services'; -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import { BaseOperationProvider } from './BaseOperationProvider'; import { OperationTracker } from './OperationTracker'; import type { diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts index 52258450..1a91ee35 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts @@ -4,7 +4,7 @@ import { MongoServerError, type Document, type Filter } from 'mongodb'; */ import type { Logger, MongoDBClient } from '@stock-bot/services'; -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import type { BaseOperationProvider } from './BaseOperationProvider'; import type { BulkOperationUpdate, diff --git a/apps/stock/orchestrator/docs/architecture-improvements.md b/apps/stock/orchestrator/docs/architecture-improvements.md index 9a87ba8e..825e57a0 100644 --- a/apps/stock/orchestrator/docs/architecture-improvements.md +++ b/apps/stock/orchestrator/docs/architecture-improvements.md @@ -51,7 +51,7 @@ still applies; this layout cleanup introduces no additional version change. 2. Validate configuration at construction and inactive edits. Use explicit units, finite values and bounded periods. Existing built-in contracts reject unsupported keys instead of ignoring them. 3. Implement bounded per-instrument indicator state in `updateIndicators` and return a - `Signal | null` from `generateSignal`. Reuse `indicators/window-statistics.ts` for trailing + `Signal | null` from `generateSignal`. Reuse `@stock-bot/calculations/indicators` for trailing scalar SMA/deviation/crossovers, or the documented native indicator wrapper for other math. 4. For paper execution, provide a version string and complete finite-JSON capture/restore contract for custom state. Version changes and changed configurations require deliberate diff --git a/apps/stock/orchestrator/docs/technical-indicators.md b/apps/stock/orchestrator/docs/technical-indicators.md index b504c127..b376e9c7 100644 --- a/apps/stock/orchestrator/docs/technical-indicators.md +++ b/apps/stock/orchestrator/docs/technical-indicators.md @@ -5,7 +5,7 @@ values; they do not own cash, positions, order submission, account risk or recov ## TypeScript trailing-window math -`src/indicators/window-statistics.ts` supplies the scalar operations used by the supported +`@stock-bot/calculations/indicators` supplies the scalar operations used by the supported TypeScript SMA and mean-reversion strategies: ```ts @@ -13,7 +13,7 @@ import { movingAverageCrossover, trailingMean, trailingPopulationDeviation, -} from '../src/indicators/window-statistics'; +} from '@stock-bot/calculations/indicators'; const prices = [3, 2, 1, 4]; const mean = trailingMean(prices, 3); diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 23e1c007..75edaf9d 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -15,6 +15,7 @@ "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" }, "dependencies": { + "@stock-bot/calculations": "workspace:*", "decimal.js-light": "2.5.1", "@stock-bot/engine": "*", "@stock-bot/cache": "*", @@ -25,14 +26,12 @@ "@stock-bot/queue": "*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", - "@stock-bot/utils": "*", "hono": "^4.0.0", "socket.io": "^4.7.2", "socket.io-client": "^4.7.2", "zod": "^3.22.0", "uuid": "^9.0.0", "axios": "^1.6.0", - "simple-statistics": "^7.8.3", "@stock-bot/services": "workspace:*", "@stock-bot/mongodb": "workspace:*", "@stock-bot/postgres": "workspace:*", diff --git a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts index d82cff01..2de9af68 100644 --- a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts +++ b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts @@ -1,6 +1,10 @@ -import { finite, type EquityPoint } from './equity'; -import { formatStatistic, performanceAnalysis } from './performance'; -import { factorStatistics } from './return-statistics'; +import { + factorStatistics, + finite, + formatStatistic, + performanceAnalysis, + type EquityPoint, +} from '@stock-bot/calculations/analytics'; export interface Trade { entryTime: Date; diff --git a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts index 411cb339..8437e351 100644 --- a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts +++ b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts @@ -1,5 +1,5 @@ import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; import { type Bar, type MarketData, diff --git a/apps/stock/orchestrator/src/backtest/report-format.ts b/apps/stock/orchestrator/src/backtest/report-format.ts index d8da19a3..f2401a93 100644 --- a/apps/stock/orchestrator/src/backtest/report-format.ts +++ b/apps/stock/orchestrator/src/backtest/report-format.ts @@ -1,4 +1,4 @@ -import { formatStatistic } from '../analytics/performance'; +import { formatStatistic } from '@stock-bot/calculations/analytics'; import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; import type { ClosedTrade } from './native-result'; diff --git a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts b/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts index ec25a754..c85b7f52 100644 --- a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts +++ b/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts @@ -4,7 +4,7 @@ import { IncrementalSMA, TechnicalIndicators, } from '@stock-bot/engine'; -import { at } from '@stock-bot/utils'; +import { at } from '@stock-bot/invariants'; export interface MacdResult { macd: number[]; diff --git a/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts b/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts index f5c4984f..7c3af0f0 100644 --- a/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts @@ -3,7 +3,7 @@ import { at, defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { MeanReversionParameters } from '../../contracts/strategies'; import type { ModeManager } from '../../core/ModeManager'; -import { trailingMean, trailingPopulationDeviation } from '../../indicators/window-statistics'; +import { trailingMean, trailingPopulationDeviation } from '@stock-bot/calculations/indicators'; import type { ExecutionService } from '../../services/ExecutionService'; import type { StrategyConfig } from '../../types'; import { type MarketData } from '../../types'; diff --git a/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts b/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts index 951730fe..2d27e8a8 100644 --- a/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts @@ -2,7 +2,7 @@ import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { SmaParameters } from '../../contracts/strategies'; import type { ModeManager } from '../../core/ModeManager'; -import { movingAverageCrossover } from '../../indicators/window-statistics'; +import { movingAverageCrossover } from '@stock-bot/calculations/indicators'; import type { ExecutionService, StrategyFill } from '../../services/ExecutionService'; import type { StrategyConfig } from '../../types'; import { type MarketData } from '../../types'; diff --git a/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts b/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts index c5bc7a3c..0aeca65a 100644 --- a/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts @@ -1,7 +1,6 @@ import type * as tf from '@tensorflow/tfjs-node'; -import { defined } from '@stock-bot/invariants'; +import { at, defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/utils'; import { TechnicalAnalysis } from '../../indicators/TechnicalAnalysis'; import type { StrategyConfig } from '../../types'; import { type MarketData } from '../../types'; diff --git a/bun.lock b/bun.lock index 7ff848cd..2d11c0f5 100644 --- a/bun.lock +++ b/bun.lock @@ -126,6 +126,7 @@ "version": "0.1.0", "dependencies": { "@stock-bot/cache": "*", + "@stock-bot/calculations": "workspace:*", "@stock-bot/config": "*", "@stock-bot/di": "*", "@stock-bot/engine": "*", @@ -140,11 +141,9 @@ "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", "@stock-bot/types": "workspace:*", - "@stock-bot/utils": "*", "axios": "^1.6.0", "decimal.js-light": "2.5.1", "hono": "^4.0.0", - "simple-statistics": "^7.8.3", "socket.io": "^4.7.2", "socket.io-client": "^4.7.2", "uuid": "^9.0.0", @@ -223,6 +222,18 @@ "vite": "^4.4.5", }, }, + "libs/calculations": { + "name": "@stock-bot/calculations", + "version": "1.0.0", + "dependencies": { + "@stock-bot/invariants": "workspace:*", + "@stock-bot/types": "workspace:*", + }, + "devDependencies": { + "bun-types": "^1.2.15", + "typescript": "^5.3.0", + }, + }, "libs/core/cache": { "name": "@stock-bot/cache", "version": "1.0.0", @@ -483,11 +494,8 @@ "name": "@stock-bot/utils", "version": "1.0.0", "dependencies": { - "@stock-bot/cache": "workspace:*", - "@stock-bot/config": "workspace:*", "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "workspace:*", - "@stock-bot/types": "workspace:*", }, "devDependencies": { "@types/node": "^20.11.0", @@ -503,7 +511,6 @@ }, "dependencies": { "@stock-bot/invariants": "workspace:*", - "@stock-bot/utils": "workspace:*", "chalk": "^5.3.0", "commander": "^11.1.0", "glob": "^10.3.10", @@ -953,6 +960,8 @@ "@stock-bot/cache": ["@stock-bot/cache@workspace:libs/core/cache"], + "@stock-bot/calculations": ["@stock-bot/calculations@workspace:libs/calculations"], + "@stock-bot/config": ["@stock-bot/config@workspace:libs/core/config"], "@stock-bot/coverage-cli": ["@stock-bot/coverage-cli@workspace:tools/coverage-cli"], @@ -2431,8 +2440,6 @@ "simple-oauth2": ["simple-oauth2@5.1.0", "", { "dependencies": { "@hapi/hoek": "^11.0.4", "@hapi/wreck": "^18.0.0", "debug": "^4.3.4", "joi": "^17.6.4" } }, "sha512-gWDa38Ccm4MwlG5U7AlcJxPv3lvr80dU7ARJWrGdgvOKyzSj1gr3GBPN1rABTedAYvC/LsGYoFuFxwDBPtGEbw=="], - "simple-statistics": ["simple-statistics@7.8.8", "", {}, "sha512-CUtP0+uZbcbsFpqEyvNDYjJCl+612fNgjT8GaVuvMG7tBuJg8gXGpsP5M7X658zy0IcepWOZ6nPBu1Qb9ezA1w=="], - "slash": ["slash@3.0.0", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="], "slice-ansi": ["slice-ansi@4.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", "is-fullwidth-code-point": "^3.0.0" } }, "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ=="], diff --git a/docs/cleanup-audit.md b/docs/cleanup-audit.md new file mode 100644 index 00000000..bce95cb0 --- /dev/null +++ b/docs/cleanup-audit.md @@ -0,0 +1,50 @@ +# Shared-library cleanup: preservation and removal audit + +This records the shared-library cleanup following `ccce401`. It does not +claim to audit every deletion from the earlier execution/strategy refactors. The first +pass inferred that no current imports meant no future value; that was too broad for a +trading/feature-engineering repository. This revision separates capabilities by ownership +and readiness instead of deleting them on usage alone. + +| Previously removed item | Current disposition | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Active basic calculations, technical indicators, risk and performance modules | All 105 exported functions preserved in `libs/calculations/src/legacy/`, with original executable bodies. Explicit `@stock-bot/calculations/legacy` entry; not endorsed as reviewed core. | +| Tested orchestrator equity/return/trade/performance and window math | Moved into supported `@stock-bot/calculations/analytics` and `/indicators`; report/strategy consumers migrated. No strategy checkpoint/version changes. | +| Generic OHLCV extraction, features, grouping/filtering and timestamps | All 13 helpers restored to `@stock-bot/calculations/market-data`. SMA/return formulas delegate to reviewed core; invalid-input, VWAP and grouping behavior hardened as documented. | +| Seven `.disabled` math modules | Full original sources preserved as verified Markdown research snapshots, including unique indicators and numerical prototypes. Not activated or silently labeled production-ready. | +| `POSITION_SIZING_FIXES.md` | Preserved as historical research notes with an explicit warning that its correctness/production claims were not independently verified. | +| Proxy URL and sleep helpers | Restored to `@stock-bot/utils/common` and named root exports. | +| Date helpers | Restored to `@stock-bot/utils/dates`: validated UTC weekday/date functions; old `dateUtils` names retained as deprecated aliases. Not an exchange/holiday calendar. UTC semantics replace the old environment-dependent local calendar arithmetic. | +| `utils` assertion facade | Remains removed. `at`/`defined` are unchanged in `@stock-bot/invariants`; all consumers import the actual owner. This removes a duplicate entry point, not the functionality. | +| Domain-type re-exports through the calculation barrel | Domain types remain unchanged in `@stock-bot/types`; callers import the owner, rather than maintaining another re-export layer. | +| Empty `analyzePortfolio` API | Remains removed: it returned empty objects and implemented no calculation. Real legacy/research portfolio functions are preserved above. | +| Old generic utility test file | Its 21 existing cases were split into 13 market-data tests and 8 common/date tests at the owning packages, with UTC assertions and new boundary tests. No executed behavior coverage was discarded merely for being unused by apps. | +| `connection-manager.test.ts.old` and `redis-cache.test.ts.old` | Remain removed as `.old` files; full source/scenarios preserved in cache test references. These were not run by the test runner. They contain 27 and 47 cases, respectively, and are not all equivalent to the active tests. Some target absent APIs; the connection-manager suite is skipped and has broken mock names. No passing coverage is claimed. | +| Old handler-registry singleton implementation | Remains removed. The metadata/configuration/service/scheduling registry lives in `@stock-bot/handler-registry`; no imports used the `.old` singleton. Reintroducing it would create another registry authority. | +| `simple-statistics`, unused utility dependencies/references in orchestrator/coverage CLI, and config/cache/type dependencies in general utilities | Remain removed. No live imports required them. The orchestrator now declares the actual calculation workspace; the calculation package has no infrastructure/native dependencies. | + +## Preservation evidence and readiness + +[The calculation inventory](../libs/calculations/migration-audit.json) records every +previously exported math function, source provenance, legacy AST hashes and research +source hashes. Tests verify all 105 legacy exports and their unchanged executable bodies, +and all seven research snapshots. This proves source/capability preservation, **not** +algorithmic correctness. The reviewed core is tested separately; legacy functions can +still contain zero/Infinity fallbacks, inconsistent conventions or incomplete formulas. + +[The calculation contract](../libs/calculations/README.md) specifies supported units, +warm-up/alignment, invalid-result policies and the promotion path for legacy/research +functions. [Research concerns](../libs/calculations/research/README.md) identify known +limitations before reuse. Supported stock application code cannot import the legacy +tier, and no supported math module can load it transitively. + +The retired Redis test sources are retained as +[connection-manager scenarios](../libs/core/cache/test/references/connection-manager-tests.md) +and [cache scenarios](../libs/core/cache/test/references/redis-cache-tests.md). Their +valid assertions should be ported with correct public contracts and isolated fixtures; +archived source is deliberately not counted in any test totals. + +This revision does not change cache production code, trading/execution behavior, +persisted data, environment files or WCAG. General date helpers and OHLCV edge-case +contracts are the explicit behavior corrections noted above; old legacy math remains +unchanged and opt-in. diff --git a/libs/calculations/README.md b/libs/calculations/README.md new file mode 100644 index 00000000..aaed8a38 --- /dev/null +++ b/libs/calculations/README.md @@ -0,0 +1,96 @@ +# Shared calculations + +`@stock-bot/calculations` is a private, pure TypeScript workspace for data processing, +strategy features and analytics. It requires no database, HTTP client, logger, native +binding or application service container. `@stock-bot/types` is type-only; invariants +are the only runtime workspace dependency. + +```ts +import { returnStatistics } from '@stock-bot/calculations/analytics'; +import { sma, trailingMean } from '@stock-bot/calculations/indicators'; +import { calculateVWAP, extractCloses } from '@stock-bot/calculations/market-data'; +import { simpleReturns } from '@stock-bot/calculations/returns'; + +const returns = simpleReturns([100, 110, 99]); +const movingMeans = sma([100, 110, 99], 2); +const risk = returnStatistics(returns); +``` + +## Supported core + +- `./returns`: simple/log returns, explicit percentage-point conversion, CAGR and + annualization. Inputs must be finite. Invalid price baselines throw, not return zero. + CAGR is `null` for zero elapsed time, nonpositive ending capital or unrepresentable + output. Other nonrepresentable outputs throw. Annualization requires an explicit + positive number of periods/year; return statistics below intentionally use daily data. +- `./indicators`: O(n) batch SMA plus trailing mean, population deviation and crossover + helpers shared with the supported TypeScript strategies. SMA output index 0 belongs + to source index `period - 1`; incomplete batch warm-up is `[]`, scalar warm-up is + `undefined`. No future data is read. Windows/offsets must be valid integers. +- `./market-data`: restored generic OHLCV extraction, returns, SMA, HLC/3 typical price, + true range, cumulative VWAP, filtering, grouping and timestamp conversion. SMA and + returns delegate to the same core functions. VWAP is `null` until positive cumulative + volume exists, never a fabricated price. OHLC features validate used prices/ranges; + negative volume and invalid timestamps fail explicitly. Time filters retain the old + inclusive `[start, end]` contract. `groupBySymbol` is ticker grouping, not listing + identity: partition qualified venue/instrument IDs before calculating any feature. +- `./analytics`: the existing tested fraction-based equity/drawdown, observed daily + return/factor, closed-trade and performance calculations, moved from the orchestrator. + Daily statistics use 252 periods/year, UTC grouping, sample volatility and explicit + `null` for undefined ratios. Trade holding periods are minutes. Persisted strategy + versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage + fields in `performanceAnalysis` remain compatibility heuristics, not optimizers. + +The root entry exports the supported returns, indicators and market-data helpers. +Use subpaths to avoid loading unrelated math. Shared domain types remain owned by +`@stock-bot/types`; HTTP/date/proxy helpers remain in `@stock-bot/utils`. + +The application-level `PerformanceAnalyzer` remains a reporting facade. The native +`TechnicalAnalysis` adapter still supports its existing Rust indicators; neither is a +dependency of this library. Native and legacy indicators can have different seeding, +smoothing and warm-up conventions: they are not interchangeable without parity tests. + +## Preserved legacy APIs + +All **105 previously active calculation functions** are retained, not deleted, behind +one explicit opt-in entry: + +```ts +import { basic, indicators, performance, risk } from '@stock-bot/calculations/legacy'; +``` + +The four original modules are preserved with unchanged executable bodies and their +original function names. These are migration/research APIs, **not newly validated +production APIs**. Known concerns include zero/Infinity fallbacks, incompatible ratio +units, different indicator seeding/smoothing, drawdown definitions and simplified +attribution/MWRR. Do not introduce these into supported stock execution. Prefer the +reviewed core, and promote additional functions with documented contracts and golden, +invalid-input, warm-up/alignment and batch/incremental parity tests as applicable. + +[migration-audit.json](migration-audit.json) inventories every original exported function, +its disposition and source provenance (`ccce401`). Regression tests verify the legacy +AST hashes and export lists; that proves preservation, not financial correctness. + +## Preserved research + +All seven formerly `.disabled` modules are retained as source-verified Markdown research +snapshots in [research/](research/README.md), including their unique indicators. They +were never active package exports and are not activated by this change. Some contain +placeholders, unseeded randomness or partial numerical methods. They are not compiled, +published or importable code. Extract and validate useful functions before promotion. + +The empty `analyzePortfolio` convenience placeholder was not restored. Removing a +placeholder API does not remove the real portfolio/research implementations above. + +## Verify + +```sh +bun run test:calculations +bun run test:integration +bun run check +``` + +The root gate builds/type-checks this workspace and runs its regressions. The integration +suite retains native/window parity, strategy recovery and analytics golden fixtures. +Architecture checks keep infrastructure and application adapters out of the library, +and prevent supported app code from loading the legacy/research tier. diff --git a/libs/calculations/migration-audit.json b/libs/calculations/migration-audit.json new file mode 100644 index 00000000..7175727a --- /dev/null +++ b/libs/calculations/migration-audit.json @@ -0,0 +1,408 @@ +{ + "sourceCommit": "ccce401", + "modules": [ + { + "original": "libs/utils/src/calculations/basic-calculations.ts", + "status": "legacy-api", + "destination": "src/legacy/basic-calculations.ts", + "sourceSha256": "366b46cd207316409bcb281b62cadac92792a97981b40fc31f65c59513149d7a", + "astSha256": "68b64fcb0a00367d16a92f8f39eef6f4856c04bdc2fa8f070252d3e4c002c506", + "functions": [ + "accruedInterest", + "annualizeReturn", + "annualizeVolatility", + "bondConvexity", + "bondPrice", + "bondYield", + "cagr", + "capitalAssetPricingModel", + "cleanPrice", + "compoundInterest", + "degreeOfFinancialLeverage", + "degreeOfOperatingLeverage", + "degreeOfTotalLeverage", + "dirtyPrice", + "dividendDiscountModel", + "dollarDuration", + "economicValueAdded", + "effectiveAnnualRate", + "futureValue", + "hurdleRate", + "internalRateOfReturn", + "logReturn", + "macaulayDuration", + "modifiedDuration", + "netPresentValue", + "paybackPeriod", + "percentageChange", + "presentValue", + "simpleReturn", + "weightedAverageCostOfCapital" + ] + }, + { + "original": "libs/utils/src/calculations/technical-indicators.ts", + "status": "legacy-api", + "destination": "src/legacy/technical-indicators.ts", + "sourceSha256": "7792daec5b77cc5f6c5e5f8735e1d8798f9b00090e103a837e4eb187e6a4f38e", + "astSha256": "d3e84dde74368e641e6b05df0a189e8d1451c42991e6c9e30aac638f5b8d17d9", + "functions": [ + "accumulationDistribution", + "adx", + "aroon", + "atr", + "balanceOfPower", + "bollingerBands", + "cci", + "chaikinMoneyFlow", + "chandeMomentumOscillator", + "coppockCurve", + "donchianChannels", + "easeOfMovement", + "ema", + "ichimoku", + "keltnerChannels", + "klingerVolumeOscillator", + "macd", + "massIndex", + "mfi", + "momentum", + "obv", + "parabolicSAR", + "pivotPoints", + "priceOscillator", + "roc", + "rsi", + "sma", + "stochastic", + "stochasticRSI", + "tema", + "trix", + "ultimateOscillator", + "vortexIndicator", + "vwma", + "williamsR", + "wma" + ] + }, + { + "original": "libs/utils/src/calculations/risk-metrics.ts", + "status": "legacy-api", + "destination": "src/legacy/risk-metrics.ts", + "sourceSha256": "7916a60801b0ea57b6f258d1137f41ce78b4acce91e64e54399cb5146b764220", + "astSha256": "12a636e2dd2c4768389fafedac8102967321869add25eecae2ff9271e9593139", + "functions": [ + "alpha", + "annualizedVolatility", + "beta", + "calculateRiskMetrics", + "conditionalValueAtRisk", + "downsideDeviation", + "kurtosis", + "maxDrawdown", + "parametricVaR", + "riskAdjustedReturn", + "riskContribution", + "sharpeRatio", + "skewness", + "trackingError", + "treynorRatio", + "ulcerIndex", + "valueAtRisk", + "volatility" + ] + }, + { + "original": "libs/utils/src/calculations/performance-metrics.ts", + "status": "legacy-api", + "destination": "src/legacy/performance-metrics.ts", + "sourceSha256": "3333c4a285a94ab40ca1fb537166ef8f820431cfdd7afeb3bcf74d64d40f861f", + "astSha256": "dd39e4a594d06d752263c4ecc5e90e816c87ac32b825e6da11dcc3ffb2c707ea", + "functions": [ + "analyzeDrawdowns", + "analyzeReturns", + "analyzeTradePerformance", + "calculateRollingAlpha", + "calculateRollingBeta", + "calculateRollingMetrics", + "calculateStrategyMetrics", + "calmarRatio", + "captureRatio", + "gainToPainRatio", + "informationRatio", + "jensensAlpha", + "martinRatio", + "moneyWeightedRateOfReturn", + "omegaRatio", + "sortinoRatio", + "sterlingRatio", + "strategyPerformanceAttribution", + "tailRatio", + "timeWeightedRateOfReturn", + "ulcerPerformanceIndex" + ] + }, + { + "original": "libs/utils/src/calculations/correlation-analysis.ts.disabled", + "status": "research-reference", + "destination": "research/correlation-analysis.md", + "sourceSha256": "5add7ae799098f19502a57a14682f2207fffe568d96584c28cc896439354b4df", + "functions": [ + "autocorrelation", + "correlationMatrix", + "correlationRegimeAnalysis", + "covarianceMatrix", + "crossCorrelation", + "dccModel", + "distanceCorrelation", + "grangerCausalityTest", + "kendallTau", + "mutualInformation", + "partialCorrelation", + "pearsonCorrelation", + "rollingCorrelation", + "spearmanCorrelation", + "tailCorrelation" + ] + }, + { + "original": "libs/utils/src/calculations/market-statistics.ts.disabled", + "status": "research-reference", + "destination": "research/market-statistics.md", + "sourceSha256": "4bd442052d2d2997f9f78b884b3ccb4793df4ec5eb512f824fddad013920318b", + "functions": [ + "ImplementationShortfall", + "IntradayPatterns", + "LiquidityMetrics", + "MarketImpact", + "MarketStress", + "OrderBookImbalance", + "PriceDiscovery", + "RealizedSpread", + "TWAP", + "VWAP", + "adverseSelectionComponent", + "amihudIlliquidity", + "amihudIlliquidityHFT", + "cumulativeVolumeDelta", + "deltaNeutralHedgingRatio", + "gammaScalpingRange", + "garmanKlassVolatility", + "identifyMarketRegime", + "inventoryRiskComponent", + "kyleLambda", + "marketOrderRatio", + "optimalOrderSize", + "probabilityInformedTrading", + "quoteAge", + "rollSpreadEstimator", + "tickRule", + "tradeClassification", + "volumeConcentrationHHI", + "volumeOrderImbalance", + "volumeProfile", + "yangZhangVolatility" + ] + }, + { + "original": "libs/utils/src/calculations/options-pricing.ts.disabled", + "status": "research-reference", + "destination": "research/options-pricing.md", + "sourceSha256": "199004579a57c196c87230684717a559b1c95c6ef1e6c7cda7ab33852abfcb52", + "functions": [ + "binomialOptionPricing", + "blackScholes", + "blackScholesWithGreeks", + "butterfly", + "calculateGreeks", + "calculateImpliedVolatility", + "calculateOptionPortfolioRisk", + "calculateStrategyGreeks", + "callBreakeven", + "callProbabilityOfProfit", + "condor", + "impliedVolatility", + "interpolateVolatilitySurface", + "monteCarloOptionPricing", + "putBreakeven", + "putProbabilityOfProfit", + "straddle", + "strangle" + ] + }, + { + "original": "libs/utils/src/calculations/portfolio-analytics.ts.disabled", + "status": "research-reference", + "destination": "research/portfolio-analytics.md", + "sourceSha256": "547b7df19c8fffc73736a6a5e6080f7de81bdfb6132080565b728651ae9e4bf2", + "functions": [ + "blackLittermanOptimization", + "calculateEfficientFrontier", + "calculatePortfolioMetrics", + "calculatePortfolioReturns", + "calculatePortfolioVariance", + "calculateRebalancing", + "calculateRiskContributions", + "famaFrenchAnalysis", + "findMinimumVariancePortfolio", + "markowitzOptimization", + "performanceAttribution", + "riskParityOptimization" + ] + }, + { + "original": "libs/utils/src/calculations/position-sizing.ts.disabled", + "status": "research-reference", + "destination": "research/position-sizing.md", + "sourceSha256": "23815464ab33ebed0e597e2b3c35499c59ed3d2788d9e06bcd3a4878fda540f1", + "functions": [ + "atrBasedPositionSize", + "calculatePortfolioHeat", + "correlationAdjustedPositionSize", + "dynamicPositionSize", + "equalWeightPositionSize", + "expectancyPositionSize", + "fixedFractionalPositionSize", + "fixedRiskPositionSize", + "fractionalKellyPositionSize", + "kellyPositionSize", + "liquidityConstrainedPositionSize", + "monteCarloPositionSize", + "multiTimeframePositionSize", + "optimalFPositionSize", + "riskParityPositionSize", + "secureFPositionSize", + "sharpeOptimizedPositionSize", + "validatePositionSize", + "volatilityAdjustedPositionSize", + "volatilityTargetPositionSize" + ] + }, + { + "original": "libs/utils/src/calculations/technical-indicators.ts.disabled", + "status": "research-reference", + "destination": "research/technical-indicators.md", + "sourceSha256": "603ef0b619c52e7388e1121993d628821e9c65e30e5d28cb34a1fd6f60eeeacc", + "functions": [ + "accumulationDistribution", + "adx", + "aroon", + "atr", + "atrTrailingStops", + "balanceOfPower", + "bollingerBands", + "cci", + "centerOfGravity", + "chaikinADRange", + "chaikinMoneyFlow", + "chaikinOscillator", + "chandeMomentumOscillator", + "chandelierExit", + "coppockCurve", + "coppockRange", + "correlationCoefficient", + "deMarker", + "detrendedPriceOscillator", + "directionalMovementIndex", + "donchianChannels", + "donchianWidth", + "easeOfMovement", + "elderDisk", + "elderRay", + "eldersCloud", + "eldersForceIndex", + "eldersSafeZoneStops", + "eldersThermometer", + "ema", + "forceIndex", + "fractalChaosBands", + "fractalEfficiency", + "guppyMultipleMovingAverage", + "highLowIndex", + "highLowRange", + "hilbertTransformInstantaneousTrendline", + "historicalVolatility", + "ichimokuCloud", + "intradayIntensityIndex", + "kama", + "keltnerChannels", + "klingerOscillator", + "knowSureThing", + "linearRegressionIndicator", + "macd", + "marketFacilitationIndex", + "massIndex", + "medianPrice", + "medianPriceRange", + "mfi", + "momentum", + "momentumFromCurrentPrice", + "moneyFlowChaikinOscillator", + "moneyFlowIndexRange", + "moneyFlowMultiplier", + "movingAverageEnvelope", + "negativeVolumeIndex", + "normalizedAverageTrueRange", + "obv", + "onBalanceVolumeMean", + "onBalanceVolumeOscillator", + "parabolicSAR", + "percentagePriceOscillator", + "pivotPoints", + "positiveVolumeIndex", + "prettyGoodOscillator", + "priceVolumeTrend", + "primeNumberOscillator", + "projectionBands", + "projectionOscillator", + "qStick", + "rainbowOscillator", + "rangeActionVerificationIndex", + "relativeStrength", + "relativeVigorIndex", + "relativeVolatilityIndex", + "roc", + "rocFromCurrentPrice", + "rsi", + "schaffTrendCycle", + "sma", + "standardDeviation", + "stochRSIFast", + "stochRSIFull", + "stochastic", + "stochasticRSI", + "trix", + "trueStrengthIndex", + "twiggsMoneyFlow", + "typicalPrice", + "typicalPriceRange", + "ultimateMovingAverage", + "ultimateOscillator", + "verticalHorizontalFilter", + "volumeOscillator", + "volumeRateOfChange", + "vwma", + "williamsR" + ] + }, + { + "original": "libs/utils/src/calculations/volatility-models.ts.disabled", + "status": "research-reference", + "destination": "research/volatility-models.md", + "sourceSha256": "c84b4088b9251ecbc6e8a6306d90db78b2beebd82bdcfd5b21e009225cd4e0f8", + "functions": [ + "calculateEWMAVolatility", + "calculateRealizedVolatility", + "calculateVolatilityRisk", + "calculateVolatilitySmile", + "calculateVolatilityTermStructure", + "calculateYangZhangVolatility", + "estimateGARCH", + "estimateHestonParameters", + "forecastVolatilityEWMA", + "identifyVolatilityRegimes", + "parkinsonVolatility" + ] + } + ] +} diff --git a/libs/calculations/package.json b/libs/calculations/package.json new file mode 100644 index 00000000..125f8b78 --- /dev/null +++ b/libs/calculations/package.json @@ -0,0 +1,30 @@ +{ + "name": "@stock-bot/calculations", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Pure calculations shared by strategies, processing and feature engineering", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./analytics": "./src/analytics/index.ts", + "./indicators": "./src/indicators/index.ts", + "./market-data": "./src/market-data.ts", + "./returns": "./src/returns.ts", + "./legacy": "./src/legacy/index.ts" + }, + "scripts": { + "build": "tsc", + "test": "bun test", + "clean": "rimraf dist" + }, + "dependencies": { + "@stock-bot/invariants": "workspace:*", + "@stock-bot/types": "workspace:*" + }, + "devDependencies": { + "bun-types": "^1.2.15", + "typescript": "^5.3.0" + } +} diff --git a/libs/calculations/research/README.md b/libs/calculations/research/README.md new file mode 100644 index 00000000..382e9f3f --- /dev/null +++ b/libs/calculations/research/README.md @@ -0,0 +1,26 @@ +# Research references, not runtime APIs + +These source snapshots preserve **all seven previously disabled calculation modules** +from `ccce401`, including functions not present in the active indicator module. Markdown +keeps their former non-executable status explicit. Their source hashes are verified by +the calculation preservation tests; this does not validate their algorithms. + +| Snapshot | Review concerns before promotion | +| ------------------------------------------------ | ------------------------------------------------------------------------------- | +| [Correlation analysis](correlation-analysis.md) | Random permutation tests and approximate inference/matrix methods | +| [Market statistics](market-statistics.md) | Hard-coded market cap/stress estimates and simplified microstructure outputs | +| [Options pricing](options-pricing.md) | Unseeded Monte Carlo, convergence fallbacks and logging | +| [Portfolio analytics](portfolio-analytics.md) | Equal-weight optimizer baselines, zero factor estimates, incomplete attribution | +| [Position sizing](position-sizing.md) | Unseeded simulation/search; old production-readiness claims were unsupported | +| [Additional indicators](technical-indicators.md) | Duplicates plus unique indicators and a placeholder Hilbert transform | +| [Volatility models](volatility-models.md) | Simplified Yang–Zhang/Heston estimates and random shocks | + +[Historical position-sizing notes](position-sizing-notes.md) retain the old formula and +validation discussion without endorsing its production-readiness claims. + +To promote a function: define its inputs, units, undefined-result policy and temporal +alignment; remove synthetic results, implicit clock access and unseeded randomness; +add an independently checked fixture and edge-case tests; then expose a deliberate +supported subpath. Keep approximate research explicitly labeled rather than treating +an importable function as proof of correctness. Supported code must not depend on these +references or the legacy namespace. diff --git a/libs/utils/src/calculations/correlation-analysis.ts.disabled b/libs/calculations/research/correlation-analysis.md similarity index 98% rename from libs/utils/src/calculations/correlation-analysis.ts.disabled rename to libs/calculations/research/correlation-analysis.md index 5d4eadca..70d5a95e 100644 --- a/libs/utils/src/calculations/correlation-analysis.ts.disabled +++ b/libs/calculations/research/correlation-analysis.md @@ -1,3 +1,14 @@ +# correlation-analysis research snapshot + +Source: `ccce401:libs/utils/src/calculations/correlation-analysis.ts.disabled`. + +Contains random permutation tests and simplified statistical/numerical approximations. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Correlation Analysis Module * @@ -1267,3 +1278,4 @@ function fCDF(f: number, df1: number, df2: number): number { const x = df2 / (df2 + df1 * f); return 1 - betaIncomplete(df2 / 2, df1 / 2, x); } +``` diff --git a/libs/utils/src/calculations/market-statistics.ts.disabled b/libs/calculations/research/market-statistics.md similarity index 98% rename from libs/utils/src/calculations/market-statistics.ts.disabled rename to libs/calculations/research/market-statistics.md index 7a6858fb..79352392 100644 --- a/libs/utils/src/calculations/market-statistics.ts.disabled +++ b/libs/calculations/research/market-statistics.md @@ -1,3 +1,14 @@ +# market-statistics research snapshot + +Source: `ccce401:libs/utils/src/calculations/market-statistics.ts.disabled`. + +Contains fixed correlation stress, estimated market cap, and simplified spread/impact outputs. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Market Statistics and Microstructure Analysis * Tools for analyzing market behavior, liquidity, and trading patterns @@ -1024,3 +1035,4 @@ function calculateCovariance(x: number[], y: number[]): number { return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1); } +``` diff --git a/libs/utils/src/calculations/options-pricing.ts.disabled b/libs/calculations/research/options-pricing.md similarity index 97% rename from libs/utils/src/calculations/options-pricing.ts.disabled rename to libs/calculations/research/options-pricing.md index 755affdb..fe74c591 100644 --- a/libs/utils/src/calculations/options-pricing.ts.disabled +++ b/libs/calculations/research/options-pricing.md @@ -1,3 +1,14 @@ +# options-pricing research snapshot + +Source: `ccce401:libs/utils/src/calculations/options-pricing.ts.disabled`. + +Contains unseeded Monte Carlo sampling and volatility-convergence fallbacks/logging. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Options Pricing Models * Implementation of various options pricing models and Greeks calculations @@ -808,3 +819,4 @@ export function putProbabilityOfProfit( (volatility * Math.sqrt(timeToExpiry)); return 1 - normalCDF(d1); } +``` diff --git a/libs/utils/src/calculations/portfolio-analytics.ts.disabled b/libs/calculations/research/portfolio-analytics.md similarity index 97% rename from libs/utils/src/calculations/portfolio-analytics.ts.disabled rename to libs/calculations/research/portfolio-analytics.md index 5fe17086..e19c1705 100644 --- a/libs/utils/src/calculations/portfolio-analytics.ts.disabled +++ b/libs/calculations/research/portfolio-analytics.md @@ -1,3 +1,14 @@ +# portfolio-analytics research snapshot + +Source: `ccce401:libs/utils/src/calculations/portfolio-analytics.ts.disabled`. + +Contains equal-weight optimization baselines, zero factor estimates and incomplete attribution. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Portfolio Analytics * Advanced portfolio analysis and optimization tools @@ -590,3 +601,4 @@ function findMinimumVarianceWeights( return weights; } +``` diff --git a/libs/utils/POSITION_SIZING_FIXES.md b/libs/calculations/research/position-sizing-notes.md similarity index 90% rename from libs/utils/POSITION_SIZING_FIXES.md rename to libs/calculations/research/position-sizing-notes.md index 7f1cc65d..587b0527 100644 --- a/libs/utils/POSITION_SIZING_FIXES.md +++ b/libs/calculations/research/position-sizing-notes.md @@ -1,97 +1,109 @@ -# Position Sizing Calculations - Fixed Issues Summary - -## Issues Identified and Fixed: - -### 1. **Duplicate Kelly Function** ✅ FIXED -- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures -- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface - -### 2. **Incorrect Kelly Criterion Formula** ✅ FIXED -- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)` -- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio` -- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate - -### 3. **Missing Input Validation** ✅ FIXED -- **Problem**: Functions didn't validate inputs (zero/negative values) -- **Solution**: Added comprehensive input validation to all functions -- **Examples**: - - Check for `accountSize <= 0`, `riskPercentage <= 0` - - Validate `winRate` is between 0 and 1 - - Ensure prices and volatilities are positive - -### 4. **ATR Position Sizing Units Error** ✅ FIXED -- **Problem**: Function returned risk amount instead of shares -- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares) - -### 5. **Flawed Monte Carlo Simulation** ✅ FIXED -- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns -- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio - -### 6. **Redundant Liquidity Calculations** ✅ FIXED -- **Problem**: Unnecessary conversions between shares and dollar values -- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares` - -### 7. **Risk Parity Not Using Target Risk** ✅ FIXED -- **Problem**: `targetRisk` parameter was ignored in calculations -- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)` - -### 8. **Missing Safety Constraints** ✅ FIXED -- **Problem**: No caps on leverage or volatility ratios -- **Solution**: Added reasonable caps: - - Volatility targeting: max 2x leverage - - Volatility adjustment: max 3x leverage - - Kelly fraction: max 25% with safety factor - -### 9. **Correlation Risk Calculation Error** ✅ FIXED -- **Problem**: Correlation risk calculation didn't consider relative position sizes -- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment - -### 10. **Integer Share Handling** ✅ FIXED -- **Problem**: Functions returned fractional shares -- **Solution**: Added `Math.floor()` to return whole shares where appropriate - -## Mathematical Validation Examples: - -### Fixed Risk Position Sizing: -``` -Account: $100,000, Risk: 2%, Entry: $100, Stop: $95 -Risk Amount: $100,000 × 0.02 = $2,000 -Risk Per Share: |$100 - $95| = $5 -Position Size: $2,000 ÷ $5 = 400 shares ✅ -``` - -### Kelly Criterion (Corrected): -``` -Win Rate: 60%, Avg Win: $150, Avg Loss: $100 -Win/Loss Ratio: $150 ÷ $100 = 1.5 -Kelly Fraction: (1.5 × 0.6 - 0.4) ÷ 1.5 = 0.333 -With Safety Factor (25%): 0.333 × 0.25 = 0.083 -Position: $100,000 × 0.083 = $8,333 ✅ -``` - -### Volatility Targeting: -``` -Price: $100, Asset Vol: 20%, Target Vol: 10% -Volatility Ratio: 10% ÷ 20% = 0.5 -Position Value: $100,000 × 0.5 = $50,000 -Position Size: $50,000 ÷ $100 = 500 shares ✅ -``` - -## Edge Cases Now Handled: -- ✅ Zero or negative account sizes -- ✅ Equal entry and stop loss prices -- ✅ Zero volatility assets -- ✅ Negative expectancy strategies -- ✅ Extreme correlation values -- ✅ Division by zero scenarios -- ✅ Invalid win rates (≤0 or ≥1) - -## Additional Improvements: -- ✅ Consistent return types (whole shares vs. dollar amounts) -- ✅ Proper TypeScript interfaces for all parameters -- ✅ Comprehensive JSDoc documentation -- ✅ Mathematical formulas verified against financial literature -- ✅ Safety factors to prevent over-leveraging -- ✅ Portfolio-level risk management functions - -All position sizing calculations are now mathematically correct, properly validated, and production-ready! +# Historical position-sizing notes + +Original: `ccce401:libs/utils/POSITION_SIZING_FIXES.md`. + +The following notes are retained as research context. Their claims of mathematical +correctness and production readiness were not independently established and are not +endorsements. The implementation remains in the non-executable position-sizing snapshot. +Use the package promotion checklist before adopting any formula or validation claim. + +--- + +# Position Sizing Calculations - Fixed Issues Summary + +## Issues Identified and Fixed: + +### 1. **Duplicate Kelly Function** ✅ FIXED +- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures +- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface + +### 2. **Incorrect Kelly Criterion Formula** ✅ FIXED +- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)` +- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio` +- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate + +### 3. **Missing Input Validation** ✅ FIXED +- **Problem**: Functions didn't validate inputs (zero/negative values) +- **Solution**: Added comprehensive input validation to all functions +- **Examples**: + - Check for `accountSize <= 0`, `riskPercentage <= 0` + - Validate `winRate` is between 0 and 1 + - Ensure prices and volatilities are positive + +### 4. **ATR Position Sizing Units Error** ✅ FIXED +- **Problem**: Function returned risk amount instead of shares +- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares) + +### 5. **Flawed Monte Carlo Simulation** ✅ FIXED +- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns +- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio + +### 6. **Redundant Liquidity Calculations** ✅ FIXED +- **Problem**: Unnecessary conversions between shares and dollar values +- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares` + +### 7. **Risk Parity Not Using Target Risk** ✅ FIXED +- **Problem**: `targetRisk` parameter was ignored in calculations +- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)` + +### 8. **Missing Safety Constraints** ✅ FIXED +- **Problem**: No caps on leverage or volatility ratios +- **Solution**: Added reasonable caps: + - Volatility targeting: max 2x leverage + - Volatility adjustment: max 3x leverage + - Kelly fraction: max 25% with safety factor + +### 9. **Correlation Risk Calculation Error** ✅ FIXED +- **Problem**: Correlation risk calculation didn't consider relative position sizes +- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment + +### 10. **Integer Share Handling** ✅ FIXED +- **Problem**: Functions returned fractional shares +- **Solution**: Added `Math.floor()` to return whole shares where appropriate + +## Mathematical Validation Examples: + +### Fixed Risk Position Sizing: +``` +Account: $100,000, Risk: 2%, Entry: $100, Stop: $95 +Risk Amount: $100,000 × 0.02 = $2,000 +Risk Per Share: |$100 - $95| = $5 +Position Size: $2,000 ÷ $5 = 400 shares ✅ +``` + +### Kelly Criterion (Corrected): +``` +Win Rate: 60%, Avg Win: $150, Avg Loss: $100 +Win/Loss Ratio: $150 ÷ $100 = 1.5 +Kelly Fraction: (1.5 × 0.6 - 0.4) ÷ 1.5 = 0.333 +With Safety Factor (25%): 0.333 × 0.25 = 0.083 +Position: $100,000 × 0.083 = $8,333 ✅ +``` + +### Volatility Targeting: +``` +Price: $100, Asset Vol: 20%, Target Vol: 10% +Volatility Ratio: 10% ÷ 20% = 0.5 +Position Value: $100,000 × 0.5 = $50,000 +Position Size: $50,000 ÷ $100 = 500 shares ✅ +``` + +## Edge Cases Now Handled: +- ✅ Zero or negative account sizes +- ✅ Equal entry and stop loss prices +- ✅ Zero volatility assets +- ✅ Negative expectancy strategies +- ✅ Extreme correlation values +- ✅ Division by zero scenarios +- ✅ Invalid win rates (≤0 or ≥1) + +## Additional Improvements: +- ✅ Consistent return types (whole shares vs. dollar amounts) +- ✅ Proper TypeScript interfaces for all parameters +- ✅ Comprehensive JSDoc documentation +- ✅ Mathematical formulas verified against financial literature +- ✅ Safety factors to prevent over-leveraging +- ✅ Portfolio-level risk management functions + +All position sizing calculations are now mathematically correct, properly validated, and production-ready! + diff --git a/libs/utils/src/calculations/position-sizing.ts.disabled b/libs/calculations/research/position-sizing.md similarity index 97% rename from libs/utils/src/calculations/position-sizing.ts.disabled rename to libs/calculations/research/position-sizing.md index 28348a3d..344461b4 100644 --- a/libs/utils/src/calculations/position-sizing.ts.disabled +++ b/libs/calculations/research/position-sizing.md @@ -1,3 +1,14 @@ +# position-sizing research snapshot + +Source: `ccce401:libs/utils/src/calculations/position-sizing.ts.disabled`. + +Contains unseeded Monte Carlo search and unqualified production-ready claims in its old notes. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Position Sizing Calculations * Risk-based position sizing methods for trading strategies @@ -579,3 +590,4 @@ export function secureFPositionSize( return accountSize * secureF; } +``` diff --git a/libs/utils/src/calculations/technical-indicators.ts.disabled b/libs/calculations/research/technical-indicators.md similarity index 99% rename from libs/utils/src/calculations/technical-indicators.ts.disabled rename to libs/calculations/research/technical-indicators.md index 1811e412..f4a7a39c 100644 --- a/libs/utils/src/calculations/technical-indicators.ts.disabled +++ b/libs/calculations/research/technical-indicators.md @@ -1,3 +1,14 @@ +# technical-indicators research snapshot + +Source: `ccce401:libs/utils/src/calculations/technical-indicators.ts.disabled`. + +Contains additional indicator prototypes as well as duplicate indicators and a placeholder Hilbert transform. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Technical Indicators * Comprehensive set of technical analysis indicators @@ -2506,3 +2517,4 @@ export function rocFromCurrentPrice(prices: number[], period: number = 10): numb return result; } +``` diff --git a/libs/utils/src/calculations/volatility-models.ts.disabled b/libs/calculations/research/volatility-models.md similarity index 97% rename from libs/utils/src/calculations/volatility-models.ts.disabled rename to libs/calculations/research/volatility-models.md index 74ee7e8f..5d379e38 100644 --- a/libs/utils/src/calculations/volatility-models.ts.disabled +++ b/libs/calculations/research/volatility-models.md @@ -1,3 +1,14 @@ +# volatility-models research snapshot + +Source: `ccce401:libs/utils/src/calculations/volatility-models.ts.disabled`. + +Contains simplified Yang–Zhang/Heston estimates and unseeded random shocks. + +This preserves previously disabled research, not a supported or executable package API. +Review formulas, contracts, determinism and fixtures before porting any function into `src/`. +The code below is the original source, unchanged. + +```ts /** * Volatility Models * Advanced volatility modeling and forecasting tools @@ -619,3 +630,4 @@ export function forecastVolatilityEWMA( } return forecast; } +``` diff --git a/apps/stock/orchestrator/src/analytics/equity.ts b/libs/calculations/src/analytics/equity.ts similarity index 100% rename from apps/stock/orchestrator/src/analytics/equity.ts rename to libs/calculations/src/analytics/equity.ts diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts new file mode 100644 index 00000000..736bd17b --- /dev/null +++ b/libs/calculations/src/analytics/index.ts @@ -0,0 +1,6 @@ +export { dayMs, equityAnalysis, finite, nullable, ratio } from './equity'; +export type { DrawdownPeriod, EquityPoint } from './equity'; +export { factorStatistics, mean, returnStatistics, sampleDeviation } from './return-statistics'; +export { tradeStatistics } from './trade-statistics'; +export type { TradeObservation } from './trade-statistics'; +export { formatStatistic, performanceAnalysis } from './performance'; diff --git a/apps/stock/orchestrator/src/analytics/performance.ts b/libs/calculations/src/analytics/performance.ts similarity index 100% rename from apps/stock/orchestrator/src/analytics/performance.ts rename to libs/calculations/src/analytics/performance.ts diff --git a/apps/stock/orchestrator/src/analytics/return-statistics.ts b/libs/calculations/src/analytics/return-statistics.ts similarity index 100% rename from apps/stock/orchestrator/src/analytics/return-statistics.ts rename to libs/calculations/src/analytics/return-statistics.ts diff --git a/apps/stock/orchestrator/src/analytics/trade-statistics.ts b/libs/calculations/src/analytics/trade-statistics.ts similarity index 100% rename from apps/stock/orchestrator/src/analytics/trade-statistics.ts rename to libs/calculations/src/analytics/trade-statistics.ts diff --git a/libs/calculations/src/index.ts b/libs/calculations/src/index.ts new file mode 100644 index 00000000..8ce44e2f --- /dev/null +++ b/libs/calculations/src/index.ts @@ -0,0 +1,31 @@ +export { + annualizeReturn, + annualizeVolatility, + cagr, + logReturn, + logReturns, + percentageChange, + simpleReturn, + simpleReturns, +} from './returns'; +export { + movingAverageCrossover, + sma, + trailingMean, + trailingPopulationDeviation, +} from './indicators'; +export { + calculateLogReturns, + calculateReturns, + calculateSMA, + calculateTrueRange, + calculateTypicalPrice, + calculateVWAP, + convertTimestamps, + extractCloses, + extractOHLC, + extractVolumes, + filterBySymbol, + filterByTimeRange, + groupBySymbol, +} from './market-data'; diff --git a/libs/calculations/src/indicators/index.ts b/libs/calculations/src/indicators/index.ts new file mode 100644 index 00000000..429dfe99 --- /dev/null +++ b/libs/calculations/src/indicators/index.ts @@ -0,0 +1,6 @@ +export { + movingAverageCrossover, + trailingMean, + trailingPopulationDeviation, +} from './window-statistics'; +export { sma } from './sma'; diff --git a/libs/calculations/src/indicators/sma.ts b/libs/calculations/src/indicators/sma.ts new file mode 100644 index 00000000..986304c1 --- /dev/null +++ b/libs/calculations/src/indicators/sma.ts @@ -0,0 +1,22 @@ +import { at } from '@stock-bot/invariants'; +import { finite } from '../analytics/equity'; + +/** Trailing-only SMA in O(n). Output 0 belongs to input period - 1; no warm-up zeros. */ +export function sma(values: readonly number[], period: number): number[] { + if (!Number.isSafeInteger(period) || period < 1) { + throw new RangeError('Indicator period must be a positive integer'); + } + const result: number[] = []; + let sum = 0; + for (const [index, value] of values.entries()) { + finite(value); + if (index >= period) { + sum -= finite(at(values, index - period)); + } + sum = finite(sum + value); + if (index >= period - 1) { + result.push(finite(sum / period)); + } + } + return result; +} diff --git a/apps/stock/orchestrator/src/indicators/window-statistics.ts b/libs/calculations/src/indicators/window-statistics.ts similarity index 100% rename from apps/stock/orchestrator/src/indicators/window-statistics.ts rename to libs/calculations/src/indicators/window-statistics.ts diff --git a/libs/utils/src/calculations/basic-calculations.ts b/libs/calculations/src/legacy/basic-calculations.ts similarity index 99% rename from libs/utils/src/calculations/basic-calculations.ts rename to libs/calculations/src/legacy/basic-calculations.ts index f555ca52..8cae2d52 100644 --- a/libs/utils/src/calculations/basic-calculations.ts +++ b/libs/calculations/src/legacy/basic-calculations.ts @@ -1,3 +1,4 @@ +/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ /** * Basic Financial Calculations * Core mathematical functions for financial analysis diff --git a/libs/calculations/src/legacy/index.ts b/libs/calculations/src/legacy/index.ts new file mode 100644 index 00000000..f4925f75 --- /dev/null +++ b/libs/calculations/src/legacy/index.ts @@ -0,0 +1,5 @@ +/** Opt-in historical APIs, not aliases for the reviewed core. See the package migration notes. */ +export * as basic from './basic-calculations'; +export * as indicators from './technical-indicators'; +export * as risk from './risk-metrics'; +export * as performance from './performance-metrics'; diff --git a/libs/utils/src/calculations/performance-metrics.ts b/libs/calculations/src/legacy/performance-metrics.ts similarity index 99% rename from libs/utils/src/calculations/performance-metrics.ts rename to libs/calculations/src/legacy/performance-metrics.ts index f2fe6e3b..36437ee8 100644 --- a/libs/utils/src/calculations/performance-metrics.ts +++ b/libs/calculations/src/legacy/performance-metrics.ts @@ -1,3 +1,4 @@ +/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ import { ulcerIndex } from './risk-metrics'; /** diff --git a/libs/utils/src/calculations/risk-metrics.ts b/libs/calculations/src/legacy/risk-metrics.ts similarity index 99% rename from libs/utils/src/calculations/risk-metrics.ts rename to libs/calculations/src/legacy/risk-metrics.ts index 97daf822..9987d984 100644 --- a/libs/utils/src/calculations/risk-metrics.ts +++ b/libs/calculations/src/legacy/risk-metrics.ts @@ -1,3 +1,4 @@ +/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ /** * Risk Metrics and Analysis * Comprehensive risk measurement tools for portfolio and trading analysis diff --git a/libs/utils/src/calculations/technical-indicators.ts b/libs/calculations/src/legacy/technical-indicators.ts similarity index 99% rename from libs/utils/src/calculations/technical-indicators.ts rename to libs/calculations/src/legacy/technical-indicators.ts index 7d4d2f31..1fb716dc 100644 --- a/libs/utils/src/calculations/technical-indicators.ts +++ b/libs/calculations/src/legacy/technical-indicators.ts @@ -1,3 +1,4 @@ +/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ import { defined } from '@stock-bot/invariants'; /** * Technical Indicators diff --git a/libs/utils/src/generic-functions.ts b/libs/calculations/src/market-data.ts similarity index 63% rename from libs/utils/src/generic-functions.ts rename to libs/calculations/src/market-data.ts index e5ab3820..e161ebba 100644 --- a/libs/utils/src/generic-functions.ts +++ b/libs/calculations/src/market-data.ts @@ -5,13 +5,32 @@ import { defined } from '@stock-bot/invariants'; */ import type { HasClose, HasOHLC, HasVolume, OHLCV } from '@stock-bot/types'; +import { finite } from './analytics/equity'; +import { sma } from './indicators/sma'; +import { logReturns, simpleReturns } from './returns'; + +function priceRange(item: HasOHLC): number { + const range = finite(finite(item.high) - finite(item.low)); + if (range < 0) { + throw new RangeError('High must be at least low'); + } + if (finite(item.close) < item.low || item.close > item.high) { + throw new RangeError('Close must be within high and low'); + } + return range; +} + +function typicalPrice(item: HasOHLC): number { + priceRange(item); + return finite((item.high + item.low + item.close) / 3); +} /** * Extract close prices from any data structure that has a close field * Works with OHLCV, MarketData, or any custom type with close price */ export function extractCloses(data: T[]): number[] { - return data.map(item => item.close); + return Array.from(data, item => finite(item.close)); } /** @@ -25,6 +44,10 @@ export function extractOHLC( lows: number[]; closes: number[]; } { + for (const item of data) { + priceRange(item); + finite(item.open); + } return { opens: data.map(item => item.open), highs: data.map(item => item.high), @@ -37,29 +60,21 @@ export function extractOHLC( * Extract volumes from any data structure that has a volume field */ export function extractVolumes(data: T[]): number[] { - return data.map(item => item.volume); + return Array.from(data, item => finite(item.volume)); } /** * Calculate simple moving average using close prices from any compatible data type */ export function calculateSMA(data: T[], period: number): number[] { - const closes = extractCloses(data); - const result: number[] = []; - - for (let i = period - 1; i < closes.length; i++) { - const sum = closes.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - result.push(sum / period); - } - - return result; + return sma(extractCloses(data), period); } /** * Calculate typical price (HLC/3) from any OHLC compatible data */ export function calculateTypicalPrice(data: T[]): number[] { - return data.map(item => (item.high + item.low + item.close) / 3); + return Array.from(data, typicalPrice); } /** @@ -69,6 +84,7 @@ export function calculateTrueRange(data: T[]): number[] { const result: number[] = []; for (let i = 0; i < data.length; i++) { + priceRange(defined(data[i])); if (i === 0) { result.push(defined(data[i]).high - defined(data[i]).low); } else { @@ -79,7 +95,7 @@ export function calculateTrueRange(data: T[]): number[] { Math.abs(current.high - previous.close), Math.abs(current.low - previous.close) ); - result.push(tr); + result.push(finite(tr)); } } @@ -90,59 +106,36 @@ export function calculateTrueRange(data: T[]): number[] { * Calculate returns from close prices */ export function calculateReturns(data: T[]): number[] { - const closes = extractCloses(data); - const returns: number[] = []; - - for (let i = 1; i < closes.length; i++) { - const current = defined(closes[i]); - const previous = defined(closes[i - 1]); - if (previous > 0) { - returns.push((current - previous) / previous); - } else { - returns.push(0); - } - } - - return returns; + return simpleReturns(extractCloses(data)); } /** * Calculate log returns from close prices */ export function calculateLogReturns(data: T[]): number[] { - const closes = extractCloses(data); - const logReturns: number[] = []; - - for (let i = 1; i < closes.length; i++) { - const current = defined(closes[i]); - const previous = defined(closes[i - 1]); - if (previous > 0 && current > 0) { - logReturns.push(Math.log(current / previous)); - } else { - logReturns.push(0); - } - } - - return logReturns; + return logReturns(extractCloses(data)); } /** * Calculate volume-weighted average price (VWAP) from OHLC + Volume data */ -export function calculateVWAP(data: T[]): number[] { - const result: number[] = []; +export function calculateVWAP(data: T[]): Array { + const result: Array = []; let cumulativeVolumePrice = 0; let cumulativeVolume = 0; for (const item of data) { - const typicalPrice = (item.high + item.low + item.close) / 3; - cumulativeVolumePrice += typicalPrice * item.volume; - cumulativeVolume += item.volume; + const price = typicalPrice(item); + if (finite(item.volume) < 0) { + throw new RangeError('Volume must be nonnegative'); + } + cumulativeVolumePrice = finite(cumulativeVolumePrice + price * item.volume); + cumulativeVolume = finite(cumulativeVolume + item.volume); if (cumulativeVolume > 0) { - result.push(cumulativeVolumePrice / cumulativeVolume); + result.push(finite(cumulativeVolumePrice / cumulativeVolume)); } else { - result.push(typicalPrice); + result.push(null); } } @@ -160,14 +153,17 @@ export function filterBySymbol(data: OHLCV[], symbol: string): OHLCV[] { * Filter OHLCV data by time range */ export function filterByTimeRange(data: OHLCV[], startTime: number, endTime: number): OHLCV[] { - return data.filter(item => item.timestamp >= startTime && item.timestamp <= endTime); + if (finite(startTime) > finite(endTime)) { + throw new RangeError('Invalid time range'); + } + return data.filter(item => finite(item.timestamp) >= startTime && item.timestamp <= endTime); } /** * Group OHLCV data by symbol */ export function groupBySymbol(data: OHLCV[]): Record { - const grouped: Record = {}; + const grouped: Record = Object.create(null); for (const item of data) { if (!grouped[item.symbol]) { @@ -183,8 +179,11 @@ export function groupBySymbol(data: OHLCV[]): Record { * Convert timestamp to Date for OHLCV data */ export function convertTimestamps(data: OHLCV[]): Array { - return data.map(item => ({ - ...item, - date: new Date(item.timestamp), - })); + return data.map(item => { + const date = new Date(finite(item.timestamp)); + if (!Number.isFinite(date.getTime())) { + throw new RangeError('Invalid timestamp'); + } + return { ...item, date }; + }); } diff --git a/libs/calculations/src/returns.ts b/libs/calculations/src/returns.ts new file mode 100644 index 00000000..fcbf056a --- /dev/null +++ b/libs/calculations/src/returns.ts @@ -0,0 +1,80 @@ +import { finite, nullable } from './analytics/equity'; + +/** Fractional return. A zero/negative baseline is undefined, not a zero return. */ +export function simpleReturn(initial: number, final: number): number { + if (finite(initial) <= 0) { + throw new RangeError('Return baseline must be positive'); + } + return finite(finite(final) / initial - 1); +} + +/** Percentage points, explicitly distinguished from the fraction-based functions. */ +export function percentageChange(initial: number, final: number): number { + return finite(simpleReturn(initial, final) * 100); +} + +export function logReturn(initial: number, final: number): number { + if (finite(initial) <= 0 || finite(final) <= 0) { + throw new RangeError('Log return prices must be positive'); + } + return finite(Math.log(final) - Math.log(initial)); +} + +function series(values: readonly number[], calculate: (initial: number, final: number) => number) { + const result: number[] = []; + let previous: number | undefined; + for (const value of values) { + finite(value); + if (previous !== undefined) { + result.push(calculate(previous, value)); + } + previous = value; + } + return result; +} + +/** Result i belongs to input i + 1. No observations are skipped or forward-filled. */ +export function simpleReturns(values: readonly number[]): number[] { + return series(values, simpleReturn); +} +export function logReturns(values: readonly number[]): number[] { + for (const value of values) { + if (finite(value) <= 0) { + throw new RangeError('Log return prices must be positive'); + } + } + return series(values, logReturn); +} + +export function cagr(start: number, end: number, years: number): number | null { + if (finite(start) <= 0) { + throw new RangeError('Initial capital must be positive'); + } + finite(end); + if (finite(years) < 0) { + throw new RangeError('Years must be nonnegative'); + } + return years === 0 || end <= 0 + ? null + : nullable(Math.expm1((Math.log(end) - Math.log(start)) / years)); +} + +export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number { + if (finite(periodicReturn) < -1) { + throw new RangeError('Periodic return must be at least -1'); + } + if (finite(periodsPerYear) <= 0) { + throw new RangeError('Periods per year must be positive'); + } + return finite(Math.expm1(Math.log1p(periodicReturn) * periodsPerYear)); +} + +export function annualizeVolatility(volatility: number, periodsPerYear: number): number { + if (finite(volatility) < 0) { + throw new RangeError('Volatility must be nonnegative'); + } + if (finite(periodsPerYear) <= 0) { + throw new RangeError('Periods per year must be positive'); + } + return finite(volatility * Math.sqrt(periodsPerYear)); +} diff --git a/libs/calculations/test/core.test.ts b/libs/calculations/test/core.test.ts new file mode 100644 index 00000000..7b3fa779 --- /dev/null +++ b/libs/calculations/test/core.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, test } from 'bun:test'; +import { equityAnalysis, mean, returnStatistics } from '@stock-bot/calculations/analytics'; +import { + movingAverageCrossover, + sma, + trailingMean, + trailingPopulationDeviation, +} from '@stock-bot/calculations/indicators'; +import { + calculateReturns, + calculateTrueRange, + calculateVWAP, + convertTimestamps, + extractCloses, + filterByTimeRange, + groupBySymbol, +} from '@stock-bot/calculations/market-data'; +import { + annualizeReturn, + annualizeVolatility, + cagr, + logReturn, + logReturns, + percentageChange, + simpleReturn, + simpleReturns, +} from '@stock-bot/calculations/returns'; + +const bar = { open: 10, high: 12, low: 8, close: 10, volume: 10, symbol: 'ABC.US', timestamp: 0 }; + +describe('reviewed shared calculation contracts', () => { + test('returns keep fractions distinct from percentage points and reject fabricated baselines', () => { + expect(simpleReturn(100, 110)).toBeCloseTo(0.1); + expect(percentageChange(100, 110)).toBeCloseTo(10); + expect(simpleReturn(100, -10)).toBeCloseTo(-1.1); + expect(logReturn(100, 110)).toBeCloseTo(Math.log(1.1)); + expect(simpleReturns([100, 110, 99])).toEqual([simpleReturn(100, 110), simpleReturn(110, 99)]); + expect(logReturns([100, 110])).toEqual([logReturn(100, 110)]); + expect(simpleReturns([])).toEqual([]); + expect(logReturns([100])).toEqual([]); + for (const value of [0, -1, NaN, Infinity]) { + expect(() => simpleReturn(value, 10)).toThrow(); + expect(() => logReturn(10, value)).toThrow(); + } + expect(() => simpleReturns([100, 0, 110])).toThrow('baseline'); + expect(() => calculateReturns([{ close: 100 }, { close: 0 }, { close: 110 }])).toThrow(); + expect(() => simpleReturns(Array(2))).toThrow('finite'); + expect(Number.isFinite(logReturn(Number.MIN_VALUE, Number.MAX_VALUE))).toBe(true); + }); + + test('annualization has explicit undefined CAGR and validates sampling units', () => { + expect(cagr(100, 121, 2)).toBeCloseTo(0.1); + expect(cagr(100, 110, 0)).toBeNull(); + expect(cagr(100, 0, 1)).toBeNull(); + expect(cagr(100, -10, 1)).toBeNull(); + expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull(); + expect(() => cagr(0, 10, 1)).toThrow(); + expect(() => cagr(100, 110, -1)).toThrow(); + expect(() => cagr(100, NaN, 1)).toThrow(); + expect(annualizeReturn(0.01, 12)).toBeCloseTo(1.01 ** 12 - 1); + expect(annualizeReturn(-1, 252)).toBe(-1); + expect(annualizeVolatility(0.1, 4)).toBeCloseTo(0.2); + for (const periods of [0, -1, NaN, Infinity]) { + expect(() => annualizeReturn(0.01, periods)).toThrow(); + expect(() => annualizeVolatility(0.1, periods)).toThrow(); + } + expect(() => annualizeReturn(-1.1, 12)).toThrow(); + expect(() => annualizeVolatility(-0.1, 12)).toThrow(); + const curve = equityAnalysis( + [ + { timestamp: 0, value: 100 }, + { timestamp: 365 * 86400000, value: 110 }, + ], + 100 + ); + expect(curve.annualizedReturn).toBeCloseTo(cagr(100, 110, 1)!); + }); + + test('trailing features have explicit offsets and never read future bars', () => { + const prices = [3, 2, 1, 4, 6, 5, 7, 8]; + expect(sma(prices, 3)).toEqual([2, 7 / 3, 11 / 3, 5, 6, 20 / 3]); + expect(sma([1, 2], 3)).toEqual([]); + expect(trailingMean([1, 2], 3)).toBeUndefined(); + expect(trailingPopulationDeviation([1, 2, 3], 3)).toBeCloseTo(Math.sqrt(2 / 3)); + for (let end = 1; end <= prices.length; end++) { + const prefix = prices.slice(0, end); + expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3)); + expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1)); + } + expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true); + expect(() => sma([1, 2], 0)).toThrow(); + expect(() => sma([1, NaN], 2)).toThrow('finite'); + expect(() => sma(Array(3), 2)).toThrow('finite'); + expect(() => sma([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('finite'); + expect(() => movingAverageCrossover(prices, 3, 2)).toThrow(); + }); + + test('OHLCV features preserve alignment without inventing volume or prices', () => { + expect(calculateVWAP([{ ...bar, volume: 0 }, bar])).toEqual([null, 10]); + expect(calculateVWAP([bar, { ...bar, close: 12, volume: 30 }])[1]).toBeCloseTo(10.5); + expect(calculateTrueRange([bar, { ...bar, low: 11, high: 15, close: 12 }])).toEqual([4, 5]); + expect(() => calculateVWAP([{ ...bar, volume: -1 }])).toThrow(); + expect(() => calculateVWAP([{ ...bar, high: 7 }])).toThrow(); + expect(() => calculateTrueRange([{ ...bar, close: 20 }])).toThrow(); + expect(() => extractCloses([{ close: Infinity }])).toThrow(); + expect(() => convertTimestamps([{ ...bar, timestamp: Infinity }])).toThrow(); + expect(() => convertTimestamps([{ ...bar, timestamp: 1e30 }])).toThrow(); + expect(filterByTimeRange([bar], 0, 0)).toEqual([bar]); + expect(() => filterByTimeRange([bar], 1, 0)).toThrow(); + const grouped = groupBySymbol([ + { ...bar, symbol: '__proto__' }, + { ...bar, symbol: 'constructor' }, + ]); + expect(grouped['__proto__']).toHaveLength(1); + expect(grouped['constructor']).toHaveLength(1); + expect(Object.getPrototypeOf(grouped)).toBeNull(); + }); + + test('analytics remains reusable without an application/native runtime', () => { + expect(mean([1, 2, 3])).toBe(2); + expect(mean([])).toBeNull(); + expect(returnStatistics([0, 0]).sharpeRatio).toBeNull(); + expect(() => returnStatistics([NaN])).toThrow('finite'); + }); +}); diff --git a/libs/utils/test/utils.test.ts b/libs/calculations/test/market-data.test.ts similarity index 62% rename from libs/utils/test/utils.test.ts rename to libs/calculations/test/market-data.test.ts index ec9d1c87..23ab9747 100644 --- a/libs/utils/test/utils.test.ts +++ b/libs/calculations/test/market-data.test.ts @@ -7,97 +7,15 @@ import { calculateTypicalPrice, calculateVWAP, convertTimestamps, - // Common utilities - createProxyUrl, - // Date utilities - dateUtils, - // Generic functions extractCloses, extractOHLC, extractVolumes, filterBySymbol, filterByTimeRange, groupBySymbol, - sleep, -} from '../src/index'; - -describe('Utility Functions', () => { - describe('common utilities', () => { - it('should create proxy URL with auth', () => { - const proxy = { - protocol: 'http', - host: '192.168.1.1', - port: 8080, - username: 'user', - password: 'pass', - }; - - const url = createProxyUrl(proxy); - expect(url).toBe('http://user:pass@192.168.1.1:8080'); - }); - - it('should create proxy URL without auth', () => { - const proxy = { - protocol: 'socks5', - host: '192.168.1.1', - port: 1080, - }; - - const url = createProxyUrl(proxy); - expect(url).toBe('socks5://192.168.1.1:1080'); - }); - - it('should sleep for specified milliseconds', async () => { - const start = Date.now(); - await sleep(100); - const elapsed = Date.now() - start; - - expect(elapsed).toBeGreaterThanOrEqual(90); - expect(elapsed).toBeLessThan(200); - }); - }); - - describe('date utilities', () => { - it('should check if date is trading day', () => { - const monday = new Date('2023-12-25'); // Monday - const saturday = new Date('2023-12-23'); // Saturday - const sunday = new Date('2023-12-24'); // Sunday - - expect(dateUtils.isTradingDay(monday)).toBe(true); - expect(dateUtils.isTradingDay(saturday)).toBe(false); - expect(dateUtils.isTradingDay(sunday)).toBe(false); - }); - - it('should get next trading day', () => { - const friday = new Date('2023-12-22'); // Friday - const nextDay = dateUtils.getNextTradingDay(friday); - - expect(nextDay.getDay()).toBe(1); // Monday - }); - - it('should get previous trading day', () => { - const monday = new Date('2023-12-25'); // Monday - const prevDay = dateUtils.getPreviousTradingDay(monday); - - expect(prevDay.getDay()).toBe(5); // Friday - }); - - it('should format date as YYYY-MM-DD', () => { - const date = new Date('2023-12-25T10:30:00Z'); - const formatted = dateUtils.formatDate(date); - - expect(formatted).toBe('2023-12-25'); - }); - - it('should parse date from string', () => { - const date = dateUtils.parseDate('2023-12-25'); - - expect(date.getFullYear()).toBe(2023); - expect(date.getMonth()).toBe(11); // 0-based - expect(date.getDate()).toBe(25); - }); - }); +} from '@stock-bot/calculations/market-data'; +describe('restored market-data utilities', () => { describe('generic functions', () => { const testData = [ { open: 100, high: 105, low: 98, close: 103, volume: 1000 }, diff --git a/libs/calculations/test/preservation.test.ts b/libs/calculations/test/preservation.test.ts new file mode 100644 index 00000000..08f10042 --- /dev/null +++ b/libs/calculations/test/preservation.test.ts @@ -0,0 +1,55 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, test } from 'bun:test'; +import ts from 'typescript'; +import * as legacy from '@stock-bot/calculations/legacy'; +import audit from '../migration-audit.json'; + +const root = join(import.meta.dir, '..'); +const namespaces: Record = { + 'basic-calculations.ts': legacy.basic, + 'technical-indicators.ts': legacy.indicators, + 'risk-metrics.ts': legacy.risk, + 'performance-metrics.ts': legacy.performance, +}; +const hash = (value: string) => createHash('sha256').update(value).digest('hex'); + +describe('calculation capability preservation', () => { + test('all 105 previously active functions remain available with unchanged legacy bodies', () => { + let count = 0; + for (const module of audit.modules.filter(module => module.status === 'legacy-api')) { + const name = module.original.split('/').at(-1)!; + expect(Object.keys(namespaces[name]!).sort()).toEqual(module.functions); + const source = readFileSync(join(root, module.destination), 'utf8'); + const ast = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true); + expect(hash(ts.createPrinter({ removeComments: true }).printFile(ast))).toBe( + module.astSha256! + ); + count += module.functions.length; + } + expect(count).toBe(105); + // Legacy behavior is preserved, not silently relabeled as validated core behavior. + expect(legacy.basic.simpleReturn(0, 100)).toBe(0); + expect(legacy.indicators.sma([1, 2, 3], 2)).toEqual([1.5, 2.5]); + expect(legacy.risk.maxDrawdown([100, 80, 100])).toBeCloseTo(0.2); + expect( + legacy.performance.analyzeTradePerformance([{ pnl: 1, date: new Date(0) }]).profitFactor + ).toBe(Infinity); + }); + + test('all seven disabled prototypes survive as non-executable, source-verified references', () => { + const modules = audit.modules.filter(module => module.status === 'research-reference'); + expect(modules).toHaveLength(7); + for (const module of modules) { + const reference = readFileSync(join(root, module.destination), 'utf8'); + const start = reference.indexOf('```ts\n') + 6; + const end = reference.lastIndexOf('```'); + expect(start).toBeGreaterThan(5); + expect(end).toBeGreaterThan(start); + expect(hash(reference.slice(start, end).replaceAll('\r\n', '\n').trimEnd())).toBe( + module.sourceSha256 + ); + } + }); +}); diff --git a/libs/calculations/tsconfig.json b/libs/calculations/tsconfig.json new file mode 100644 index 00000000..9e06f9c2 --- /dev/null +++ b/libs/calculations/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.lib.json", + "compilerOptions": { "rootDir": "src", "outDir": "dist", "composite": true }, + "include": ["src/**/*.ts"], + "references": [ + { "path": "../core/invariants" }, + { "path": "../core/types" } + ] +} diff --git a/libs/core/cache/test/connection-manager.test.ts.old b/libs/core/cache/test/references/connection-manager-tests.md similarity index 96% rename from libs/core/cache/test/connection-manager.test.ts.old rename to libs/core/cache/test/references/connection-manager-tests.md index 168fa52c..825b64e5 100644 --- a/libs/core/cache/test/connection-manager.test.ts.old +++ b/libs/core/cache/test/references/connection-manager-tests.md @@ -1,542 +1,554 @@ -import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test'; -import { RedisConnectionManager } from '../src/connection-manager'; -import type { RedisConfig } from '../src/types'; - -// Mock ioredis -const mockRedisInstance = { - on: mock((_event: string, _callback: Function) => { - // Store callbacks for triggering events - mockRedisInstance._eventCallbacks[event] = callback; - }), - once: mock((event: string, callback: Function) => { - mockRedisInstance._onceCallbacks[event] = callback; - }), - ping: mock(async () => 'PONG'), - quit: mock(async () => 'OK'), - status: 'ready', - _eventCallbacks: {} as Record, - _onceCallbacks: {} as Record, - // Helper to trigger events - _triggerEvent(event: string, ...args: any[]) { - if (this._eventCallbacks[event]) { - this._eventCallbacks[event](...args); - } - if (this._onceCallbacks[event]) { - this._onceCallbacks[event](...args); - delete this._onceCallbacks[event]; - } - } -}; - -mock.module('ioredis', () => ({ - default: mock(() => { - // Create a new instance for each Redis connection with event handling methods - const instance = { - ...mockRedisInstance, - _eventCallbacks: {}, - _onceCallbacks: {}, - on: function(event: string, callback: Function) { - this._eventCallbacks[event] = callback; - return this; - }, - once: function(event: string, callback: Function) { - this._onceCallbacks[event] = callback; - return this; - }, - _triggerEvent: function(event: string, ...args: any[]) { - if (this._eventCallbacks[event]) { - this._eventCallbacks[event](...args); - } - if (this._onceCallbacks[event]) { - this._onceCallbacks[event](...args); - delete this._onceCallbacks[event]; - } - } - }; - return instance; - }) -})); - -// Skip these tests when running all tests together -// Run them individually with: bun test libs/core/cache/test/connection-manager.test.ts -describe.skip('RedisConnectionManager', () => { - let manager: RedisConnectionManager; - const mockLogger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - }; - - beforeEach(() => { - // Clear static state - (RedisConnectionManager as any).instance = undefined; - if ((RedisConnectionManager as any).sharedConnections) { - (RedisConnectionManager as any).sharedConnections.clear(); - } - if ((RedisConnectionManager as any).readyConnections) { - (RedisConnectionManager as any).readyConnections.clear(); - } - - // Get new instance - manager = RedisConnectionManager.getInstance(); - - // Set mock logger on the instance - (manager as any).logger = mockLogger; - - // Reset mocks - mockLogger.info.mockClear(); - mockLogger.error.mockClear(); - mockLogger.warn.mockClear(); - mockLogger.debug.mockClear(); - }); - - afterEach(async () => { - await manager.closeAllConnections(); - }); - - describe('getInstance', () => { - it('should return singleton instance', () => { - const instance1 = RedisConnectionManager.getInstance(); - const instance2 = RedisConnectionManager.getInstance(); - expect(instance1).toBe(instance2); - }); - }); - - describe('getConnection', () => { - const baseConfig: RedisConfig = { - host: 'localhost', - port: 6379, - }; - - it('should create unique connection when singleton is false', () => { - const connection1 = manager.getConnection({ - name: 'test', - singleton: false, - redisConfig: baseConfig, - logger: mockLogger, - }); - - const connection2 = manager.getConnection({ - name: 'test', - singleton: false, - redisConfig: baseConfig, - logger: mockLogger, - }); - - expect(connection1).not.toBe(connection2); - expect(mockLogger.debug).toHaveBeenCalledTimes(2); - }); - - it('should reuse shared connection when singleton is true', () => { - const connection1 = manager.getConnection({ - name: 'shared-test', - singleton: true, - redisConfig: baseConfig, - logger: mockLogger, - }); - - const connection2 = manager.getConnection({ - name: 'shared-test', - singleton: true, - redisConfig: baseConfig, - logger: mockLogger, - }); - - expect(connection1).toBe(connection2); - expect(mockLogger.info).toHaveBeenCalledWith('Created shared Redis connection: shared-test'); - }); - - it('should apply custom db number', () => { - const connection = manager.getConnection({ - name: 'db-test', - singleton: false, - db: 5, - redisConfig: baseConfig, - logger: mockLogger, - }); - - expect(connection).toBeDefined(); - }); - - it('should handle TLS configuration', () => { - const tlsConfig: RedisConfig = { - ...baseConfig, - tls: { - cert: 'cert-content', - key: 'key-content', - ca: 'ca-content', - rejectUnauthorized: false, - }, - }; - - const connection = manager.getConnection({ - name: 'tls-test', - singleton: false, - redisConfig: tlsConfig, - logger: mockLogger, - }); - - expect(connection).toBeDefined(); - }); - - it('should use provided logger', () => { - const customLogger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - }; - - manager.getConnection({ - name: 'logger-test', - singleton: false, - redisConfig: baseConfig, - logger: customLogger, - }); - - expect(customLogger.debug).toHaveBeenCalled(); - }); - }); - - describe('connection events', () => { - it('should handle connect event', () => { - const connection = manager.getConnection({ - name: 'event-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Trigger connect event - (connection as any)._triggerEvent('connect'); - - expect(mockLogger.info).toHaveBeenCalledWith(expect.stringContaining('Redis connection established')); - }); - - it('should handle ready event', () => { - const connection = manager.getConnection({ - name: 'ready-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Trigger ready event - (connection as any)._triggerEvent('ready'); - - expect(mockLogger.info).toHaveBeenCalledWith(expect.stringContaining('Redis connection ready')); - }); - - it('should handle error event', () => { - const connection = manager.getConnection({ - name: 'error-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - const error = new Error('Connection failed'); - (connection as any)._triggerEvent('error', error); - - expect(mockLogger.error).toHaveBeenCalledWith( - expect.stringContaining('Redis connection error'), - error - ); - }); - - it('should handle close event', () => { - const connection = manager.getConnection({ - name: 'close-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - (connection as any)._triggerEvent('close'); - - expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Redis connection closed')); - }); - - it('should handle reconnecting event', () => { - const connection = manager.getConnection({ - name: 'reconnect-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - (connection as any)._triggerEvent('reconnecting'); - - expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Redis reconnecting')); - }); - }); - - describe('closeConnection', () => { - it('should close connection successfully', async () => { - const connection = manager.getConnection({ - name: 'close-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - await manager.closeConnection(connection); - - expect(connection.quit).toHaveBeenCalled(); - }); - - it('should handle close errors gracefully', async () => { - const connection = manager.getConnection({ - name: 'close-error-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Make quit throw an error - (connection.quit as any).mockImplementation(() => Promise.reject(new Error('Quit failed'))); - - await manager.closeConnection(connection); - - expect(mockLogger.warn).toHaveBeenCalledWith( - 'Error closing Redis connection:', - expect.any(Error) - ); - }); - }); - - describe('closeAllConnections', () => { - it('should close all unique connections', async () => { - const conn1 = manager.getConnection({ - name: 'unique1', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - const conn2 = manager.getConnection({ - name: 'unique2', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - await manager.closeAllConnections(); - - expect(conn1.quit).toHaveBeenCalled(); - expect(conn2.quit).toHaveBeenCalled(); - expect(mockLogger.info).toHaveBeenCalledWith('All Redis connections closed'); - }); - - it('should close shared connections', async () => { - const sharedConn = manager.getConnection({ - name: 'shared', - singleton: true, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - await manager.closeAllConnections(); - - expect(sharedConn.quit).toHaveBeenCalled(); - expect(manager.getConnectionCount()).toEqual({ shared: 0, unique: 0 }); - }); - }); - - describe('getConnectionCount', () => { - it('should return correct connection counts', () => { - manager.getConnection({ - name: 'unique1', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - manager.getConnection({ - name: 'unique2', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - manager.getConnection({ - name: 'shared1', - singleton: true, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - const counts = manager.getConnectionCount(); - expect(counts.unique).toBe(2); - expect(counts.shared).toBe(1); - }); - }); - - describe('getConnectionNames', () => { - it('should return connection names', () => { - manager.getConnection({ - name: 'test-unique', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - manager.getConnection({ - name: 'test-shared', - singleton: true, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - const names = manager.getConnectionNames(); - expect(names.shared).toContain('test-shared'); - expect(names.unique.length).toBe(1); - expect(names.unique[0]).toContain('test-unique'); - }); - }); - - describe('healthCheck', () => { - it('should report healthy connections', async () => { - manager.getConnection({ - name: 'health-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - const health = await manager.healthCheck(); - - expect(health.healthy).toBe(true); - expect(Object.keys(health.details).length).toBeGreaterThan(0); - }); - - it('should report unhealthy connections', async () => { - const connection = manager.getConnection({ - name: 'unhealthy-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - // Make ping fail - (connection.ping as any).mockImplementation(() => Promise.reject(new Error('Ping failed'))); - - const health = await manager.healthCheck(); - - expect(health.healthy).toBe(false); - expect(Object.values(health.details)).toContain(false); - }); - }); - - describe('waitForAllConnections', () => { - it('should wait for connections to be ready', async () => { - manager.getConnection({ - name: 'wait-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Connection is already ready - await RedisConnectionManager.waitForAllConnections(1000); - - expect(mockLogger.info).toHaveBeenCalledWith('All Redis connections are ready'); - }); - - it('should handle no connections', async () => { - await RedisConnectionManager.waitForAllConnections(1000); - - expect(mockLogger.debug).toHaveBeenCalledWith('No Redis connections to wait for'); - }); - - it('should timeout if connection not ready', async () => { - const connection = manager.getConnection({ - name: 'timeout-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - // Make connection not ready - (connection as any).status = 'connecting'; - - await expect(RedisConnectionManager.waitForAllConnections(100)).rejects.toThrow( - 'failed to be ready within 100ms' - ); - }); - - it('should handle connection errors during wait', async () => { - const connection = manager.getConnection({ - name: 'error-wait-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Make connection not ready - (connection as any).status = 'connecting'; - - // Trigger error after a delay - setTimeout(() => { - (connection as any)._triggerEvent('error', new Error('Connection failed')); - }, 50); - - await expect(RedisConnectionManager.waitForAllConnections(1000)).rejects.toThrow( - 'Connection failed' - ); - }); - }); - - describe('areAllConnectionsReady', () => { - it('should return false when no connections', () => { - expect(RedisConnectionManager.areAllConnectionsReady()).toBe(false); - }); - - it('should return true when all connections ready', async () => { - manager.getConnection({ - name: 'ready-check-test', - singleton: false, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - await RedisConnectionManager.waitForAllConnections(1000); - - expect(RedisConnectionManager.areAllConnectionsReady()).toBe(true); - }); - }); - - describe('edge cases', () => { - it('should handle concurrent access to shared connections', () => { - // Test that multiple requests for the same shared connection return the same instance - const conn1 = manager.getConnection({ - name: 'shared-concurrent', - singleton: true, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - const conn2 = manager.getConnection({ - name: 'shared-concurrent', - singleton: true, - redisConfig: { host: 'localhost', port: 6379 }, - }); - - expect(conn1).toBe(conn2); - expect(manager.getConnectionCount().shared).toBe(1); - }); - - it('should apply all Redis options', () => { - const fullConfig: RedisConfig = { - host: 'localhost', - port: 6379, - username: 'user', - password: 'pass', - db: 2, - maxRetriesPerRequest: 5, - retryDelayOnFailover: 200, - connectTimeout: 20000, - commandTimeout: 10000, - keepAlive: 5000, - }; - - const connection = manager.getConnection({ - name: 'full-config-test', - singleton: false, - redisConfig: fullConfig, - }); - - expect(connection).toBeDefined(); - }); - }); -}); \ No newline at end of file +# Retired connection-manager.test.ts.old reference + +Original: `ccce401:libs/core/cache/test/connection-manager.test.ts.old`. + +This preserves test scenarios, NOT passing coverage. The old files were not executable test +inputs. Some cases target obsolete APIs; the connection-manager suite was also skipped and +its mock references undeclared event/callback names. Port valid scenarios against the +current contracts with isolated mocks or real disposable infrastructure before activating. +No cache production behavior is changed by archiving this reference. + +```ts +import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test'; +import { RedisConnectionManager } from '../src/connection-manager'; +import type { RedisConfig } from '../src/types'; + +// Mock ioredis +const mockRedisInstance = { + on: mock((_event: string, _callback: Function) => { + // Store callbacks for triggering events + mockRedisInstance._eventCallbacks[event] = callback; + }), + once: mock((event: string, callback: Function) => { + mockRedisInstance._onceCallbacks[event] = callback; + }), + ping: mock(async () => 'PONG'), + quit: mock(async () => 'OK'), + status: 'ready', + _eventCallbacks: {} as Record, + _onceCallbacks: {} as Record, + // Helper to trigger events + _triggerEvent(event: string, ...args: any[]) { + if (this._eventCallbacks[event]) { + this._eventCallbacks[event](...args); + } + if (this._onceCallbacks[event]) { + this._onceCallbacks[event](...args); + delete this._onceCallbacks[event]; + } + } +}; + +mock.module('ioredis', () => ({ + default: mock(() => { + // Create a new instance for each Redis connection with event handling methods + const instance = { + ...mockRedisInstance, + _eventCallbacks: {}, + _onceCallbacks: {}, + on: function(event: string, callback: Function) { + this._eventCallbacks[event] = callback; + return this; + }, + once: function(event: string, callback: Function) { + this._onceCallbacks[event] = callback; + return this; + }, + _triggerEvent: function(event: string, ...args: any[]) { + if (this._eventCallbacks[event]) { + this._eventCallbacks[event](...args); + } + if (this._onceCallbacks[event]) { + this._onceCallbacks[event](...args); + delete this._onceCallbacks[event]; + } + } + }; + return instance; + }) +})); + +// Skip these tests when running all tests together +// Run them individually with: bun test libs/core/cache/test/connection-manager.test.ts +describe.skip('RedisConnectionManager', () => { + let manager: RedisConnectionManager; + const mockLogger = { + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + }; + + beforeEach(() => { + // Clear static state + (RedisConnectionManager as any).instance = undefined; + if ((RedisConnectionManager as any).sharedConnections) { + (RedisConnectionManager as any).sharedConnections.clear(); + } + if ((RedisConnectionManager as any).readyConnections) { + (RedisConnectionManager as any).readyConnections.clear(); + } + + // Get new instance + manager = RedisConnectionManager.getInstance(); + + // Set mock logger on the instance + (manager as any).logger = mockLogger; + + // Reset mocks + mockLogger.info.mockClear(); + mockLogger.error.mockClear(); + mockLogger.warn.mockClear(); + mockLogger.debug.mockClear(); + }); + + afterEach(async () => { + await manager.closeAllConnections(); + }); + + describe('getInstance', () => { + it('should return singleton instance', () => { + const instance1 = RedisConnectionManager.getInstance(); + const instance2 = RedisConnectionManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe('getConnection', () => { + const baseConfig: RedisConfig = { + host: 'localhost', + port: 6379, + }; + + it('should create unique connection when singleton is false', () => { + const connection1 = manager.getConnection({ + name: 'test', + singleton: false, + redisConfig: baseConfig, + logger: mockLogger, + }); + + const connection2 = manager.getConnection({ + name: 'test', + singleton: false, + redisConfig: baseConfig, + logger: mockLogger, + }); + + expect(connection1).not.toBe(connection2); + expect(mockLogger.debug).toHaveBeenCalledTimes(2); + }); + + it('should reuse shared connection when singleton is true', () => { + const connection1 = manager.getConnection({ + name: 'shared-test', + singleton: true, + redisConfig: baseConfig, + logger: mockLogger, + }); + + const connection2 = manager.getConnection({ + name: 'shared-test', + singleton: true, + redisConfig: baseConfig, + logger: mockLogger, + }); + + expect(connection1).toBe(connection2); + expect(mockLogger.info).toHaveBeenCalledWith('Created shared Redis connection: shared-test'); + }); + + it('should apply custom db number', () => { + const connection = manager.getConnection({ + name: 'db-test', + singleton: false, + db: 5, + redisConfig: baseConfig, + logger: mockLogger, + }); + + expect(connection).toBeDefined(); + }); + + it('should handle TLS configuration', () => { + const tlsConfig: RedisConfig = { + ...baseConfig, + tls: { + cert: 'cert-content', + key: 'key-content', + ca: 'ca-content', + rejectUnauthorized: false, + }, + }; + + const connection = manager.getConnection({ + name: 'tls-test', + singleton: false, + redisConfig: tlsConfig, + logger: mockLogger, + }); + + expect(connection).toBeDefined(); + }); + + it('should use provided logger', () => { + const customLogger = { + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + }; + + manager.getConnection({ + name: 'logger-test', + singleton: false, + redisConfig: baseConfig, + logger: customLogger, + }); + + expect(customLogger.debug).toHaveBeenCalled(); + }); + }); + + describe('connection events', () => { + it('should handle connect event', () => { + const connection = manager.getConnection({ + name: 'event-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Trigger connect event + (connection as any)._triggerEvent('connect'); + + expect(mockLogger.info).toHaveBeenCalledWith(expect.stringContaining('Redis connection established')); + }); + + it('should handle ready event', () => { + const connection = manager.getConnection({ + name: 'ready-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Trigger ready event + (connection as any)._triggerEvent('ready'); + + expect(mockLogger.info).toHaveBeenCalledWith(expect.stringContaining('Redis connection ready')); + }); + + it('should handle error event', () => { + const connection = manager.getConnection({ + name: 'error-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + const error = new Error('Connection failed'); + (connection as any)._triggerEvent('error', error); + + expect(mockLogger.error).toHaveBeenCalledWith( + expect.stringContaining('Redis connection error'), + error + ); + }); + + it('should handle close event', () => { + const connection = manager.getConnection({ + name: 'close-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + (connection as any)._triggerEvent('close'); + + expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Redis connection closed')); + }); + + it('should handle reconnecting event', () => { + const connection = manager.getConnection({ + name: 'reconnect-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + (connection as any)._triggerEvent('reconnecting'); + + expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Redis reconnecting')); + }); + }); + + describe('closeConnection', () => { + it('should close connection successfully', async () => { + const connection = manager.getConnection({ + name: 'close-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + await manager.closeConnection(connection); + + expect(connection.quit).toHaveBeenCalled(); + }); + + it('should handle close errors gracefully', async () => { + const connection = manager.getConnection({ + name: 'close-error-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Make quit throw an error + (connection.quit as any).mockImplementation(() => Promise.reject(new Error('Quit failed'))); + + await manager.closeConnection(connection); + + expect(mockLogger.warn).toHaveBeenCalledWith( + 'Error closing Redis connection:', + expect.any(Error) + ); + }); + }); + + describe('closeAllConnections', () => { + it('should close all unique connections', async () => { + const conn1 = manager.getConnection({ + name: 'unique1', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + const conn2 = manager.getConnection({ + name: 'unique2', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + await manager.closeAllConnections(); + + expect(conn1.quit).toHaveBeenCalled(); + expect(conn2.quit).toHaveBeenCalled(); + expect(mockLogger.info).toHaveBeenCalledWith('All Redis connections closed'); + }); + + it('should close shared connections', async () => { + const sharedConn = manager.getConnection({ + name: 'shared', + singleton: true, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + await manager.closeAllConnections(); + + expect(sharedConn.quit).toHaveBeenCalled(); + expect(manager.getConnectionCount()).toEqual({ shared: 0, unique: 0 }); + }); + }); + + describe('getConnectionCount', () => { + it('should return correct connection counts', () => { + manager.getConnection({ + name: 'unique1', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + manager.getConnection({ + name: 'unique2', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + manager.getConnection({ + name: 'shared1', + singleton: true, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + const counts = manager.getConnectionCount(); + expect(counts.unique).toBe(2); + expect(counts.shared).toBe(1); + }); + }); + + describe('getConnectionNames', () => { + it('should return connection names', () => { + manager.getConnection({ + name: 'test-unique', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + manager.getConnection({ + name: 'test-shared', + singleton: true, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + const names = manager.getConnectionNames(); + expect(names.shared).toContain('test-shared'); + expect(names.unique.length).toBe(1); + expect(names.unique[0]).toContain('test-unique'); + }); + }); + + describe('healthCheck', () => { + it('should report healthy connections', async () => { + manager.getConnection({ + name: 'health-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + const health = await manager.healthCheck(); + + expect(health.healthy).toBe(true); + expect(Object.keys(health.details).length).toBeGreaterThan(0); + }); + + it('should report unhealthy connections', async () => { + const connection = manager.getConnection({ + name: 'unhealthy-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + // Make ping fail + (connection.ping as any).mockImplementation(() => Promise.reject(new Error('Ping failed'))); + + const health = await manager.healthCheck(); + + expect(health.healthy).toBe(false); + expect(Object.values(health.details)).toContain(false); + }); + }); + + describe('waitForAllConnections', () => { + it('should wait for connections to be ready', async () => { + manager.getConnection({ + name: 'wait-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Connection is already ready + await RedisConnectionManager.waitForAllConnections(1000); + + expect(mockLogger.info).toHaveBeenCalledWith('All Redis connections are ready'); + }); + + it('should handle no connections', async () => { + await RedisConnectionManager.waitForAllConnections(1000); + + expect(mockLogger.debug).toHaveBeenCalledWith('No Redis connections to wait for'); + }); + + it('should timeout if connection not ready', async () => { + const connection = manager.getConnection({ + name: 'timeout-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + // Make connection not ready + (connection as any).status = 'connecting'; + + await expect(RedisConnectionManager.waitForAllConnections(100)).rejects.toThrow( + 'failed to be ready within 100ms' + ); + }); + + it('should handle connection errors during wait', async () => { + const connection = manager.getConnection({ + name: 'error-wait-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Make connection not ready + (connection as any).status = 'connecting'; + + // Trigger error after a delay + setTimeout(() => { + (connection as any)._triggerEvent('error', new Error('Connection failed')); + }, 50); + + await expect(RedisConnectionManager.waitForAllConnections(1000)).rejects.toThrow( + 'Connection failed' + ); + }); + }); + + describe('areAllConnectionsReady', () => { + it('should return false when no connections', () => { + expect(RedisConnectionManager.areAllConnectionsReady()).toBe(false); + }); + + it('should return true when all connections ready', async () => { + manager.getConnection({ + name: 'ready-check-test', + singleton: false, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + await RedisConnectionManager.waitForAllConnections(1000); + + expect(RedisConnectionManager.areAllConnectionsReady()).toBe(true); + }); + }); + + describe('edge cases', () => { + it('should handle concurrent access to shared connections', () => { + // Test that multiple requests for the same shared connection return the same instance + const conn1 = manager.getConnection({ + name: 'shared-concurrent', + singleton: true, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + const conn2 = manager.getConnection({ + name: 'shared-concurrent', + singleton: true, + redisConfig: { host: 'localhost', port: 6379 }, + }); + + expect(conn1).toBe(conn2); + expect(manager.getConnectionCount().shared).toBe(1); + }); + + it('should apply all Redis options', () => { + const fullConfig: RedisConfig = { + host: 'localhost', + port: 6379, + username: 'user', + password: 'pass', + db: 2, + maxRetriesPerRequest: 5, + retryDelayOnFailover: 200, + connectTimeout: 20000, + commandTimeout: 10000, + keepAlive: 5000, + }; + + const connection = manager.getConnection({ + name: 'full-config-test', + singleton: false, + redisConfig: fullConfig, + }); + + expect(connection).toBeDefined(); + }); + }); +}); +``` diff --git a/libs/core/cache/test/redis-cache.test.ts.old b/libs/core/cache/test/references/redis-cache-tests.md similarity index 96% rename from libs/core/cache/test/redis-cache.test.ts.old rename to libs/core/cache/test/references/redis-cache-tests.md index 8de18ec5..b418dd0c 100644 --- a/libs/core/cache/test/redis-cache.test.ts.old +++ b/libs/core/cache/test/references/redis-cache-tests.md @@ -1,695 +1,707 @@ -import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test'; -import { RedisCache } from '../src/redis-cache'; -import type { CacheOptions } from '../src/types'; - -// Mock Redis instance -const createMockRedis = () => ({ - status: 'ready', - on: mock(() => {}), - once: mock(() => {}), - get: mock(async () => null), - set: mock(async () => 'OK'), - setex: mock(async () => 'OK'), - del: mock(async () => 1), - exists: mock(async () => 0), - keys: mock(async () => []), - ping: mock(async () => 'PONG'), - ttl: mock(async () => -2), - eval: mock(async () => [null, -2]), - _eventCallbacks: {} as Record, - _triggerEvent(event: string, ...args: any[]) { - if (this._eventCallbacks[event]) { - this._eventCallbacks[event](...args); - } - } -}); - -// Create mock instance getter that we can control -let mockConnectionManagerInstance: any = null; - -// Mock the connection manager -mock.module('../src/connection-manager', () => ({ - RedisConnectionManager: { - getInstance: () => mockConnectionManagerInstance - } -})); - -describe('RedisCache', () => { - let cache: RedisCache; - let mockRedis: ReturnType; - let mockLogger: any; - let mockConnectionManager: any; - - beforeEach(() => { - mockLogger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - }; - - mockRedis = createMockRedis(); - mockConnectionManager = { - getConnection: mock(() => mockRedis) - }; - - // Set the mock instance for the module - mockConnectionManagerInstance = mockConnectionManager; - }); - - afterEach(() => { - // Clear mocks - mockLogger.info.mockClear(); - mockLogger.error.mockClear(); - mockLogger.warn.mockClear(); - mockLogger.debug.mockClear(); - }); - - describe('constructor', () => { - it('should create cache with default options', () => { - const options: CacheOptions = { - redisConfig: { host: 'localhost', port: 6379 }, - }; - - cache = new RedisCache(options); - - expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ - name: 'CACHE-SERVICE', - singleton: true, - redisConfig: options.redisConfig, - logger: expect.any(Object), - }); - }); - - it('should use custom name and prefix', () => { - const options: CacheOptions = { - name: 'MyCache', - keyPrefix: 'custom:', - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }; - - cache = new RedisCache(options); - - expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ - name: 'MyCache-SERVICE', - singleton: true, - redisConfig: options.redisConfig, - logger: mockLogger, - }); - }); - - it('should handle non-shared connections', () => { - const options: CacheOptions = { - shared: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }; - - cache = new RedisCache(options); - - // Should create a new connection for non-shared - expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ - name: 'CACHE-SERVICE', - singleton: false, - redisConfig: options.redisConfig, - logger: mockLogger, - }); - }); - - it('should sanitize prefix for connection name', () => { - const options: CacheOptions = { - keyPrefix: 'my-special:prefix!', - redisConfig: { host: 'localhost', port: 6379 }, - }; - - cache = new RedisCache(options); - - expect(mockConnectionManager.getConnection).toHaveBeenCalledWith( - expect.objectContaining({ - name: 'MYSPECIALPREFIX-SERVICE', - }) - ); - }); - }); - - describe('get', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should get value with prefix', async () => { - const testValue = { data: 'test' }; - (mockRedis.get as any).mockResolvedValue(JSON.stringify(testValue)); - - const result = await cache.get('mykey'); - - expect(mockRedis.get).toHaveBeenCalledWith('test:mykey'); - expect(result).toEqual(testValue); - expect(mockLogger.debug).toHaveBeenCalledWith('Cache hit', { key: 'mykey' }); - }); - - it('should handle cache miss', async () => { - (mockRedis.get as any).mockResolvedValue(null); - - const result = await cache.get('nonexistent'); - - expect(result).toBeNull(); - expect(mockLogger.debug).toHaveBeenCalledWith('Cache miss', { key: 'nonexistent' }); - }); - - it('should handle non-JSON strings', async () => { - (mockRedis.get as any).mockResolvedValue('plain string'); - - const result = await cache.get('stringkey'); - - expect(result).toBe('plain string'); - }); - - it('should handle Redis errors gracefully', async () => { - (mockRedis.get as any).mockRejectedValue(new Error('Redis error')); - - const result = await cache.get('errorkey'); - - expect(result).toBeNull(); - expect(mockLogger.error).toHaveBeenCalledWith( - 'Redis get failed', - expect.objectContaining({ error: 'Redis error' }) - ); - }); - - it('should handle not ready state', async () => { - mockRedis.status = 'connecting'; - - const result = await cache.get('key'); - - expect(result).toBeNull(); - expect(mockLogger.warn).toHaveBeenCalledWith( - 'Redis not ready for get, using fallback' - ); - }); - }); - - describe('set', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - ttl: 7200, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should set value with default TTL', async () => { - const value = { data: 'test' }; - - await cache.set('mykey', value); - - expect(mockRedis.setex).toHaveBeenCalledWith( - 'test:mykey', - 7200, - JSON.stringify(value) - ); - }); - - it('should set value with custom TTL as number', async () => { - await cache.set('mykey', 'value', 3600); - - expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 3600, 'value'); - }); - - it('should set value with options object', async () => { - await cache.set('mykey', 'value', { ttl: 1800 }); - - expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 1800, 'value'); - }); - - it('should handle preserveTTL option', async () => { - // Key exists with TTL - (mockRedis.ttl as any).mockResolvedValue(3600); - - await cache.set('mykey', 'newvalue', { preserveTTL: true }); - - expect(mockRedis.ttl).toHaveBeenCalledWith('test:mykey'); - expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 3600, 'newvalue'); - }); - - it('should handle preserveTTL with no expiry', async () => { - // Key exists with no expiry - (mockRedis.ttl as any).mockResolvedValue(-1); - - await cache.set('mykey', 'value', { preserveTTL: true }); - - expect(mockRedis.set).toHaveBeenCalledWith('test:mykey', 'value'); - }); - - it('should handle onlyIfExists option', async () => { - (mockRedis.set as any).mockResolvedValue(null); - - await cache.set('mykey', 'value', { onlyIfExists: true }); - - expect(mockRedis.set).toHaveBeenCalledWith( - 'test:mykey', - 'value', - 'EX', - 7200, - 'XX' - ); - }); - - it('should handle onlyIfNotExists option', async () => { - (mockRedis.set as any).mockResolvedValue('OK'); - - await cache.set('mykey', 'value', { onlyIfNotExists: true }); - - expect(mockRedis.set).toHaveBeenCalledWith( - 'test:mykey', - 'value', - 'EX', - 7200, - 'NX' - ); - }); - - it('should get old value when requested', async () => { - const oldValue = { old: 'data' }; - (mockRedis.get as any).mockResolvedValue(JSON.stringify(oldValue)); - - const result = await cache.set('mykey', 'newvalue', { getOldValue: true }); - - expect(mockRedis.get).toHaveBeenCalledWith('test:mykey'); - expect(result).toEqual(oldValue); - }); - - it('should throw error for conflicting options', async () => { - await expect( - cache.set('mykey', 'value', { onlyIfExists: true, onlyIfNotExists: true }) - ).rejects.toThrow('Cannot specify both onlyIfExists and onlyIfNotExists'); - }); - - it('should handle string values directly', async () => { - await cache.set('mykey', 'plain string'); - - expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 7200, 'plain string'); - }); - }); - - describe('del', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should delete key with prefix', async () => { - await cache.del('mykey'); - - expect(mockRedis.del).toHaveBeenCalledWith('test:mykey'); - expect(mockLogger.debug).toHaveBeenCalledWith('Cache delete', { key: 'mykey' }); - }); - - it('should handle delete errors gracefully', async () => { - (mockRedis.del as any).mockRejectedValue(new Error('Delete failed')); - - await cache.del('errorkey'); - - expect(mockLogger.error).toHaveBeenCalledWith( - 'Redis del failed', - expect.objectContaining({ error: 'Delete failed' }) - ); - }); - }); - - describe('exists', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - }); - }); - - it('should check key existence', async () => { - (mockRedis.exists as any).mockResolvedValue(1); - - const result = await cache.exists('mykey'); - - expect(mockRedis.exists).toHaveBeenCalledWith('test:mykey'); - expect(result).toBe(true); - }); - - it('should return false for non-existent key', async () => { - (mockRedis.exists as any).mockResolvedValue(0); - - const result = await cache.exists('nonexistent'); - - expect(result).toBe(false); - }); - }); - - describe('clear', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should clear all prefixed keys', async () => { - const keys = ['test:key1', 'test:key2', 'test:key3']; - (mockRedis.keys as any).mockResolvedValue(keys); - - await cache.clear(); - - expect(mockRedis.keys).toHaveBeenCalledWith('test:*'); - expect(mockRedis.del).toHaveBeenCalledWith(...keys); - expect(mockLogger.warn).toHaveBeenCalledWith('Cache cleared', { keysDeleted: 3 }); - }); - - it('should handle empty cache', async () => { - (mockRedis.keys as any).mockResolvedValue([]); - - await cache.clear(); - - expect(mockRedis.del).not.toHaveBeenCalled(); - }); - }); - - describe('getRaw', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should get value without prefix', async () => { - const value = { raw: 'data' }; - (mockRedis.get as any).mockResolvedValue(JSON.stringify(value)); - - const result = await cache.getRaw('raw:key'); - - expect(mockRedis.get).toHaveBeenCalledWith('raw:key'); - expect(result).toEqual(value); - }); - - it('should handle parse errors', async () => { - (mockRedis.get as any).mockResolvedValue('invalid json'); - - const result = await cache.getRaw('badkey'); - - expect(result).toBe('invalid json'); - expect(mockLogger.warn).toHaveBeenCalledWith( - 'Cache getRaw JSON parse failed', - expect.objectContaining({ - key: 'badkey', - valueLength: 12, - }) - ); - }); - }); - - describe('keys', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - }); - }); - - it('should get keys with pattern and strip prefix', async () => { - (mockRedis.keys as any).mockResolvedValue([ - 'test:user:1', - 'test:user:2', - 'test:user:3', - ]); - - const keys = await cache.keys('user:*'); - - expect(mockRedis.keys).toHaveBeenCalledWith('test:user:*'); - expect(keys).toEqual(['user:1', 'user:2', 'user:3']); - }); - }); - - describe('health', () => { - beforeEach(() => { - cache = new RedisCache({ - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - }); - - it('should return true when healthy', async () => { - const result = await cache.health(); - - expect(mockRedis.ping).toHaveBeenCalled(); - expect(result).toBe(true); - }); - - it('should return false on ping failure', async () => { - (mockRedis.ping as any).mockRejectedValue(new Error('Ping failed')); - - const result = await cache.health(); - - expect(result).toBe(false); - expect(mockLogger.error).toHaveBeenCalledWith( - 'Redis health check failed', - expect.objectContaining({ error: 'Ping failed' }) - ); - }); - }); - - describe('stats', () => { - beforeEach(() => { - cache = new RedisCache({ - redisConfig: { host: 'localhost', port: 6379 }, - enableMetrics: true, - }); - }); - - it('should track cache hits', async () => { - (mockRedis.get as any).mockResolvedValue('value'); - - await cache.get('key1'); - await cache.get('key2'); - - const stats = cache.getStats(); - expect(stats.hits).toBe(2); - expect(stats.total).toBe(2); - expect(stats.hitRate).toBe(1.0); - }); - - it('should track cache misses', async () => { - (mockRedis.get as any).mockResolvedValue(null); - - await cache.get('key1'); - await cache.get('key2'); - - const stats = cache.getStats(); - expect(stats.misses).toBe(2); - expect(stats.total).toBe(2); - expect(stats.hitRate).toBe(0); - }); - - it('should track errors', async () => { - mockRedis.status = 'connecting'; - - await cache.get('key1'); - - const stats = cache.getStats(); - expect(stats.errors).toBe(1); - }); - - it('should not track stats when disabled', async () => { - cache = new RedisCache({ - redisConfig: { host: 'localhost', port: 6379 }, - enableMetrics: false, - }); - - (mockRedis.get as any).mockResolvedValue('value'); - await cache.get('key'); - - const stats = cache.getStats(); - expect(stats.hits).toBe(0); - }); - }); - - describe('waitForReady', () => { - beforeEach(() => { - cache = new RedisCache({ - redisConfig: { host: 'localhost', port: 6379 }, - }); - }); - - it('should resolve immediately if ready', async () => { - mockRedis.status = 'ready'; - - await expect(cache.waitForReady(1000)).resolves.toBeUndefined(); - }); - - it('should wait for ready event', async () => { - mockRedis.status = 'connecting'; - mockRedis.once = mock((event: string, handler: Function) => { - if (event === 'ready') { - setTimeout(() => handler(), 10); - } - }); - - await expect(cache.waitForReady(1000)).resolves.toBeUndefined(); - }); - - it('should timeout if not ready', async () => { - mockRedis.status = 'connecting'; - mockRedis.once = mock(() => {}); // Don't trigger any events - - await expect(cache.waitForReady(100)).rejects.toThrow( - 'Redis connection timeout after 100ms' - ); - }); - - it('should reject on error', async () => { - mockRedis.status = 'connecting'; - mockRedis.once = mock((event: string, handler: Function) => { - if (event === 'error') { - setTimeout(() => handler(new Error('Connection failed')), 10); - } - }); - - await expect(cache.waitForReady(1000)).rejects.toThrow('Connection failed'); - }); - }); - - describe('isReady', () => { - beforeEach(() => { - cache = new RedisCache({ - redisConfig: { host: 'localhost', port: 6379 }, - }); - }); - - it('should return true when ready', () => { - mockRedis.status = 'ready'; - expect(cache.isReady()).toBe(true); - }); - - it('should return false when not ready', () => { - mockRedis.status = 'connecting'; - expect(cache.isReady()).toBe(false); - }); - }); - - describe('convenience methods', () => { - beforeEach(() => { - cache = new RedisCache({ - keyPrefix: 'test:', - redisConfig: { host: 'localhost', port: 6379 }, - }); - }); - - it('should update value preserving TTL', async () => { - (mockRedis.ttl as any).mockResolvedValue(3600); - (mockRedis.get as any).mockResolvedValue(JSON.stringify({ old: 'value' })); - - const result = await cache.update('key', { new: 'value' }); - - expect(mockRedis.setex).toHaveBeenCalledWith( - 'test:key', - 3600, - JSON.stringify({ new: 'value' }) - ); - expect(result).toEqual({ old: 'value' }); - }); - - it('should setIfExists', async () => { - (mockRedis.set as any).mockResolvedValue('OK'); - (mockRedis.exists as any).mockResolvedValue(1); - - const result = await cache.setIfExists('key', 'value', 1800); - - expect(mockRedis.set).toHaveBeenCalledWith('test:key', 'value', 'EX', 1800, 'XX'); - expect(result).toBe(true); - }); - - it('should setIfNotExists', async () => { - (mockRedis.set as any).mockResolvedValue('OK'); - - const result = await cache.setIfNotExists('key', 'value', 1800); - - expect(mockRedis.set).toHaveBeenCalledWith('test:key', 'value', 'EX', 1800, 'NX'); - expect(result).toBe(true); - }); - - it('should replace existing value', async () => { - (mockRedis.get as any).mockResolvedValue(JSON.stringify({ old: 'data' })); - (mockRedis.set as any).mockResolvedValue('OK'); - - const result = await cache.replace('key', { new: 'data' }, 3600); - - expect(result).toEqual({ old: 'data' }); - }); - - it('should update field atomically', async () => { - (mockRedis.eval as any).mockResolvedValue(['{"count": 5}', 3600]); - - const updater = (current: any) => ({ - ...current, - count: (current?.count || 0) + 1, - }); - - const result = await cache.updateField('key', updater); - - expect(mockRedis.eval).toHaveBeenCalled(); - expect(result).toEqual({ count: 5 }); - }); - - it('should handle updateField with new key', async () => { - (mockRedis.eval as any).mockResolvedValue([null, -2]); - - const updater = (_current: unknown) => ({ value: 'new' }); - - await cache.updateField('key', updater); - - expect(mockRedis.setex).toHaveBeenCalled(); - }); - }); - - describe('event handlers', () => { - it('should handle connection events for non-shared cache', () => { - // Create non-shared cache - mockRedis.on = mock((event: string, handler: Function) => { - mockRedis._eventCallbacks[event] = handler; - }); - - cache = new RedisCache({ - shared: false, - redisConfig: { host: 'localhost', port: 6379 }, - logger: mockLogger, - }); - - // Trigger events - mockRedis._triggerEvent('connect'); - expect(mockLogger.info).toHaveBeenCalledWith('Redis cache connected'); - - mockRedis._triggerEvent('ready'); - expect(mockLogger.info).toHaveBeenCalledWith('Redis cache ready'); - - mockRedis._triggerEvent('error', new Error('Test error')); - expect(mockLogger.error).toHaveBeenCalledWith( - 'Redis cache connection error', - expect.objectContaining({ error: 'Test error' }) - ); - - mockRedis._triggerEvent('close'); - expect(mockLogger.warn).toHaveBeenCalledWith('Redis cache connection closed'); - - mockRedis._triggerEvent('reconnecting'); - expect(mockLogger.warn).toHaveBeenCalledWith('Redis cache reconnecting...'); - }); - }); -}); \ No newline at end of file +# Retired redis-cache.test.ts.old reference + +Original: `ccce401:libs/core/cache/test/redis-cache.test.ts.old`. + +This preserves test scenarios, NOT passing coverage. The old files were not executable test +inputs. Some cases target obsolete APIs; the connection-manager suite was also skipped and +its mock references undeclared event/callback names. Port valid scenarios against the +current contracts with isolated mocks or real disposable infrastructure before activating. +No cache production behavior is changed by archiving this reference. + +```ts +import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test'; +import { RedisCache } from '../src/redis-cache'; +import type { CacheOptions } from '../src/types'; + +// Mock Redis instance +const createMockRedis = () => ({ + status: 'ready', + on: mock(() => {}), + once: mock(() => {}), + get: mock(async () => null), + set: mock(async () => 'OK'), + setex: mock(async () => 'OK'), + del: mock(async () => 1), + exists: mock(async () => 0), + keys: mock(async () => []), + ping: mock(async () => 'PONG'), + ttl: mock(async () => -2), + eval: mock(async () => [null, -2]), + _eventCallbacks: {} as Record, + _triggerEvent(event: string, ...args: any[]) { + if (this._eventCallbacks[event]) { + this._eventCallbacks[event](...args); + } + } +}); + +// Create mock instance getter that we can control +let mockConnectionManagerInstance: any = null; + +// Mock the connection manager +mock.module('../src/connection-manager', () => ({ + RedisConnectionManager: { + getInstance: () => mockConnectionManagerInstance + } +})); + +describe('RedisCache', () => { + let cache: RedisCache; + let mockRedis: ReturnType; + let mockLogger: any; + let mockConnectionManager: any; + + beforeEach(() => { + mockLogger = { + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + }; + + mockRedis = createMockRedis(); + mockConnectionManager = { + getConnection: mock(() => mockRedis) + }; + + // Set the mock instance for the module + mockConnectionManagerInstance = mockConnectionManager; + }); + + afterEach(() => { + // Clear mocks + mockLogger.info.mockClear(); + mockLogger.error.mockClear(); + mockLogger.warn.mockClear(); + mockLogger.debug.mockClear(); + }); + + describe('constructor', () => { + it('should create cache with default options', () => { + const options: CacheOptions = { + redisConfig: { host: 'localhost', port: 6379 }, + }; + + cache = new RedisCache(options); + + expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ + name: 'CACHE-SERVICE', + singleton: true, + redisConfig: options.redisConfig, + logger: expect.any(Object), + }); + }); + + it('should use custom name and prefix', () => { + const options: CacheOptions = { + name: 'MyCache', + keyPrefix: 'custom:', + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }; + + cache = new RedisCache(options); + + expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ + name: 'MyCache-SERVICE', + singleton: true, + redisConfig: options.redisConfig, + logger: mockLogger, + }); + }); + + it('should handle non-shared connections', () => { + const options: CacheOptions = { + shared: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }; + + cache = new RedisCache(options); + + // Should create a new connection for non-shared + expect(mockConnectionManager.getConnection).toHaveBeenCalledWith({ + name: 'CACHE-SERVICE', + singleton: false, + redisConfig: options.redisConfig, + logger: mockLogger, + }); + }); + + it('should sanitize prefix for connection name', () => { + const options: CacheOptions = { + keyPrefix: 'my-special:prefix!', + redisConfig: { host: 'localhost', port: 6379 }, + }; + + cache = new RedisCache(options); + + expect(mockConnectionManager.getConnection).toHaveBeenCalledWith( + expect.objectContaining({ + name: 'MYSPECIALPREFIX-SERVICE', + }) + ); + }); + }); + + describe('get', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should get value with prefix', async () => { + const testValue = { data: 'test' }; + (mockRedis.get as any).mockResolvedValue(JSON.stringify(testValue)); + + const result = await cache.get('mykey'); + + expect(mockRedis.get).toHaveBeenCalledWith('test:mykey'); + expect(result).toEqual(testValue); + expect(mockLogger.debug).toHaveBeenCalledWith('Cache hit', { key: 'mykey' }); + }); + + it('should handle cache miss', async () => { + (mockRedis.get as any).mockResolvedValue(null); + + const result = await cache.get('nonexistent'); + + expect(result).toBeNull(); + expect(mockLogger.debug).toHaveBeenCalledWith('Cache miss', { key: 'nonexistent' }); + }); + + it('should handle non-JSON strings', async () => { + (mockRedis.get as any).mockResolvedValue('plain string'); + + const result = await cache.get('stringkey'); + + expect(result).toBe('plain string'); + }); + + it('should handle Redis errors gracefully', async () => { + (mockRedis.get as any).mockRejectedValue(new Error('Redis error')); + + const result = await cache.get('errorkey'); + + expect(result).toBeNull(); + expect(mockLogger.error).toHaveBeenCalledWith( + 'Redis get failed', + expect.objectContaining({ error: 'Redis error' }) + ); + }); + + it('should handle not ready state', async () => { + mockRedis.status = 'connecting'; + + const result = await cache.get('key'); + + expect(result).toBeNull(); + expect(mockLogger.warn).toHaveBeenCalledWith( + 'Redis not ready for get, using fallback' + ); + }); + }); + + describe('set', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + ttl: 7200, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should set value with default TTL', async () => { + const value = { data: 'test' }; + + await cache.set('mykey', value); + + expect(mockRedis.setex).toHaveBeenCalledWith( + 'test:mykey', + 7200, + JSON.stringify(value) + ); + }); + + it('should set value with custom TTL as number', async () => { + await cache.set('mykey', 'value', 3600); + + expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 3600, 'value'); + }); + + it('should set value with options object', async () => { + await cache.set('mykey', 'value', { ttl: 1800 }); + + expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 1800, 'value'); + }); + + it('should handle preserveTTL option', async () => { + // Key exists with TTL + (mockRedis.ttl as any).mockResolvedValue(3600); + + await cache.set('mykey', 'newvalue', { preserveTTL: true }); + + expect(mockRedis.ttl).toHaveBeenCalledWith('test:mykey'); + expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 3600, 'newvalue'); + }); + + it('should handle preserveTTL with no expiry', async () => { + // Key exists with no expiry + (mockRedis.ttl as any).mockResolvedValue(-1); + + await cache.set('mykey', 'value', { preserveTTL: true }); + + expect(mockRedis.set).toHaveBeenCalledWith('test:mykey', 'value'); + }); + + it('should handle onlyIfExists option', async () => { + (mockRedis.set as any).mockResolvedValue(null); + + await cache.set('mykey', 'value', { onlyIfExists: true }); + + expect(mockRedis.set).toHaveBeenCalledWith( + 'test:mykey', + 'value', + 'EX', + 7200, + 'XX' + ); + }); + + it('should handle onlyIfNotExists option', async () => { + (mockRedis.set as any).mockResolvedValue('OK'); + + await cache.set('mykey', 'value', { onlyIfNotExists: true }); + + expect(mockRedis.set).toHaveBeenCalledWith( + 'test:mykey', + 'value', + 'EX', + 7200, + 'NX' + ); + }); + + it('should get old value when requested', async () => { + const oldValue = { old: 'data' }; + (mockRedis.get as any).mockResolvedValue(JSON.stringify(oldValue)); + + const result = await cache.set('mykey', 'newvalue', { getOldValue: true }); + + expect(mockRedis.get).toHaveBeenCalledWith('test:mykey'); + expect(result).toEqual(oldValue); + }); + + it('should throw error for conflicting options', async () => { + await expect( + cache.set('mykey', 'value', { onlyIfExists: true, onlyIfNotExists: true }) + ).rejects.toThrow('Cannot specify both onlyIfExists and onlyIfNotExists'); + }); + + it('should handle string values directly', async () => { + await cache.set('mykey', 'plain string'); + + expect(mockRedis.setex).toHaveBeenCalledWith('test:mykey', 7200, 'plain string'); + }); + }); + + describe('del', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should delete key with prefix', async () => { + await cache.del('mykey'); + + expect(mockRedis.del).toHaveBeenCalledWith('test:mykey'); + expect(mockLogger.debug).toHaveBeenCalledWith('Cache delete', { key: 'mykey' }); + }); + + it('should handle delete errors gracefully', async () => { + (mockRedis.del as any).mockRejectedValue(new Error('Delete failed')); + + await cache.del('errorkey'); + + expect(mockLogger.error).toHaveBeenCalledWith( + 'Redis del failed', + expect.objectContaining({ error: 'Delete failed' }) + ); + }); + }); + + describe('exists', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + }); + }); + + it('should check key existence', async () => { + (mockRedis.exists as any).mockResolvedValue(1); + + const result = await cache.exists('mykey'); + + expect(mockRedis.exists).toHaveBeenCalledWith('test:mykey'); + expect(result).toBe(true); + }); + + it('should return false for non-existent key', async () => { + (mockRedis.exists as any).mockResolvedValue(0); + + const result = await cache.exists('nonexistent'); + + expect(result).toBe(false); + }); + }); + + describe('clear', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should clear all prefixed keys', async () => { + const keys = ['test:key1', 'test:key2', 'test:key3']; + (mockRedis.keys as any).mockResolvedValue(keys); + + await cache.clear(); + + expect(mockRedis.keys).toHaveBeenCalledWith('test:*'); + expect(mockRedis.del).toHaveBeenCalledWith(...keys); + expect(mockLogger.warn).toHaveBeenCalledWith('Cache cleared', { keysDeleted: 3 }); + }); + + it('should handle empty cache', async () => { + (mockRedis.keys as any).mockResolvedValue([]); + + await cache.clear(); + + expect(mockRedis.del).not.toHaveBeenCalled(); + }); + }); + + describe('getRaw', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should get value without prefix', async () => { + const value = { raw: 'data' }; + (mockRedis.get as any).mockResolvedValue(JSON.stringify(value)); + + const result = await cache.getRaw('raw:key'); + + expect(mockRedis.get).toHaveBeenCalledWith('raw:key'); + expect(result).toEqual(value); + }); + + it('should handle parse errors', async () => { + (mockRedis.get as any).mockResolvedValue('invalid json'); + + const result = await cache.getRaw('badkey'); + + expect(result).toBe('invalid json'); + expect(mockLogger.warn).toHaveBeenCalledWith( + 'Cache getRaw JSON parse failed', + expect.objectContaining({ + key: 'badkey', + valueLength: 12, + }) + ); + }); + }); + + describe('keys', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + }); + }); + + it('should get keys with pattern and strip prefix', async () => { + (mockRedis.keys as any).mockResolvedValue([ + 'test:user:1', + 'test:user:2', + 'test:user:3', + ]); + + const keys = await cache.keys('user:*'); + + expect(mockRedis.keys).toHaveBeenCalledWith('test:user:*'); + expect(keys).toEqual(['user:1', 'user:2', 'user:3']); + }); + }); + + describe('health', () => { + beforeEach(() => { + cache = new RedisCache({ + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + }); + + it('should return true when healthy', async () => { + const result = await cache.health(); + + expect(mockRedis.ping).toHaveBeenCalled(); + expect(result).toBe(true); + }); + + it('should return false on ping failure', async () => { + (mockRedis.ping as any).mockRejectedValue(new Error('Ping failed')); + + const result = await cache.health(); + + expect(result).toBe(false); + expect(mockLogger.error).toHaveBeenCalledWith( + 'Redis health check failed', + expect.objectContaining({ error: 'Ping failed' }) + ); + }); + }); + + describe('stats', () => { + beforeEach(() => { + cache = new RedisCache({ + redisConfig: { host: 'localhost', port: 6379 }, + enableMetrics: true, + }); + }); + + it('should track cache hits', async () => { + (mockRedis.get as any).mockResolvedValue('value'); + + await cache.get('key1'); + await cache.get('key2'); + + const stats = cache.getStats(); + expect(stats.hits).toBe(2); + expect(stats.total).toBe(2); + expect(stats.hitRate).toBe(1.0); + }); + + it('should track cache misses', async () => { + (mockRedis.get as any).mockResolvedValue(null); + + await cache.get('key1'); + await cache.get('key2'); + + const stats = cache.getStats(); + expect(stats.misses).toBe(2); + expect(stats.total).toBe(2); + expect(stats.hitRate).toBe(0); + }); + + it('should track errors', async () => { + mockRedis.status = 'connecting'; + + await cache.get('key1'); + + const stats = cache.getStats(); + expect(stats.errors).toBe(1); + }); + + it('should not track stats when disabled', async () => { + cache = new RedisCache({ + redisConfig: { host: 'localhost', port: 6379 }, + enableMetrics: false, + }); + + (mockRedis.get as any).mockResolvedValue('value'); + await cache.get('key'); + + const stats = cache.getStats(); + expect(stats.hits).toBe(0); + }); + }); + + describe('waitForReady', () => { + beforeEach(() => { + cache = new RedisCache({ + redisConfig: { host: 'localhost', port: 6379 }, + }); + }); + + it('should resolve immediately if ready', async () => { + mockRedis.status = 'ready'; + + await expect(cache.waitForReady(1000)).resolves.toBeUndefined(); + }); + + it('should wait for ready event', async () => { + mockRedis.status = 'connecting'; + mockRedis.once = mock((event: string, handler: Function) => { + if (event === 'ready') { + setTimeout(() => handler(), 10); + } + }); + + await expect(cache.waitForReady(1000)).resolves.toBeUndefined(); + }); + + it('should timeout if not ready', async () => { + mockRedis.status = 'connecting'; + mockRedis.once = mock(() => {}); // Don't trigger any events + + await expect(cache.waitForReady(100)).rejects.toThrow( + 'Redis connection timeout after 100ms' + ); + }); + + it('should reject on error', async () => { + mockRedis.status = 'connecting'; + mockRedis.once = mock((event: string, handler: Function) => { + if (event === 'error') { + setTimeout(() => handler(new Error('Connection failed')), 10); + } + }); + + await expect(cache.waitForReady(1000)).rejects.toThrow('Connection failed'); + }); + }); + + describe('isReady', () => { + beforeEach(() => { + cache = new RedisCache({ + redisConfig: { host: 'localhost', port: 6379 }, + }); + }); + + it('should return true when ready', () => { + mockRedis.status = 'ready'; + expect(cache.isReady()).toBe(true); + }); + + it('should return false when not ready', () => { + mockRedis.status = 'connecting'; + expect(cache.isReady()).toBe(false); + }); + }); + + describe('convenience methods', () => { + beforeEach(() => { + cache = new RedisCache({ + keyPrefix: 'test:', + redisConfig: { host: 'localhost', port: 6379 }, + }); + }); + + it('should update value preserving TTL', async () => { + (mockRedis.ttl as any).mockResolvedValue(3600); + (mockRedis.get as any).mockResolvedValue(JSON.stringify({ old: 'value' })); + + const result = await cache.update('key', { new: 'value' }); + + expect(mockRedis.setex).toHaveBeenCalledWith( + 'test:key', + 3600, + JSON.stringify({ new: 'value' }) + ); + expect(result).toEqual({ old: 'value' }); + }); + + it('should setIfExists', async () => { + (mockRedis.set as any).mockResolvedValue('OK'); + (mockRedis.exists as any).mockResolvedValue(1); + + const result = await cache.setIfExists('key', 'value', 1800); + + expect(mockRedis.set).toHaveBeenCalledWith('test:key', 'value', 'EX', 1800, 'XX'); + expect(result).toBe(true); + }); + + it('should setIfNotExists', async () => { + (mockRedis.set as any).mockResolvedValue('OK'); + + const result = await cache.setIfNotExists('key', 'value', 1800); + + expect(mockRedis.set).toHaveBeenCalledWith('test:key', 'value', 'EX', 1800, 'NX'); + expect(result).toBe(true); + }); + + it('should replace existing value', async () => { + (mockRedis.get as any).mockResolvedValue(JSON.stringify({ old: 'data' })); + (mockRedis.set as any).mockResolvedValue('OK'); + + const result = await cache.replace('key', { new: 'data' }, 3600); + + expect(result).toEqual({ old: 'data' }); + }); + + it('should update field atomically', async () => { + (mockRedis.eval as any).mockResolvedValue(['{"count": 5}', 3600]); + + const updater = (current: any) => ({ + ...current, + count: (current?.count || 0) + 1, + }); + + const result = await cache.updateField('key', updater); + + expect(mockRedis.eval).toHaveBeenCalled(); + expect(result).toEqual({ count: 5 }); + }); + + it('should handle updateField with new key', async () => { + (mockRedis.eval as any).mockResolvedValue([null, -2]); + + const updater = (_current: unknown) => ({ value: 'new' }); + + await cache.updateField('key', updater); + + expect(mockRedis.setex).toHaveBeenCalled(); + }); + }); + + describe('event handlers', () => { + it('should handle connection events for non-shared cache', () => { + // Create non-shared cache + mockRedis.on = mock((event: string, handler: Function) => { + mockRedis._eventCallbacks[event] = handler; + }); + + cache = new RedisCache({ + shared: false, + redisConfig: { host: 'localhost', port: 6379 }, + logger: mockLogger, + }); + + // Trigger events + mockRedis._triggerEvent('connect'); + expect(mockLogger.info).toHaveBeenCalledWith('Redis cache connected'); + + mockRedis._triggerEvent('ready'); + expect(mockLogger.info).toHaveBeenCalledWith('Redis cache ready'); + + mockRedis._triggerEvent('error', new Error('Test error')); + expect(mockLogger.error).toHaveBeenCalledWith( + 'Redis cache connection error', + expect.objectContaining({ error: 'Test error' }) + ); + + mockRedis._triggerEvent('close'); + expect(mockLogger.warn).toHaveBeenCalledWith('Redis cache connection closed'); + + mockRedis._triggerEvent('reconnecting'); + expect(mockLogger.warn).toHaveBeenCalledWith('Redis cache reconnecting...'); + }); + }); +}); +``` diff --git a/libs/core/handlers/src/base/BaseHandler.ts b/libs/core/handlers/src/base/BaseHandler.ts index a5e26239..0748ad8b 100644 --- a/libs/core/handlers/src/base/BaseHandler.ts +++ b/libs/core/handlers/src/base/BaseHandler.ts @@ -10,8 +10,7 @@ import type { IHandler, JobHandler, } from '@stock-bot/types'; -import type { FetchOptions } from '@stock-bot/utils'; -import { fetch } from '@stock-bot/utils'; +import { fetch, type FetchOptions } from '@stock-bot/utils/fetch'; // Handler registry is now injected, not imported import { createJobHandler } from '../utils/create-job-handler'; diff --git a/libs/core/handlers/src/registry/handler-registry.ts.old b/libs/core/handlers/src/registry/handler-registry.ts.old deleted file mode 100644 index 19401b5a..00000000 --- a/libs/core/handlers/src/registry/handler-registry.ts.old +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Handler Registry - Runtime registry for queue handlers - * Properly located in handlers package instead of types - */ - -import type { - HandlerConfig, - HandlerConfigWithSchedule, - JobHandler, - ScheduledJob, -} from '@stock-bot/types'; -import { getLogger } from '@stock-bot/logger'; - -class HandlerRegistry { - private readonly logger = getLogger('handler-registry'); - private handlers = new Map(); - private handlerSchedules = new Map(); - private handlerServices = new Map(); // Maps handler to service name - - /** - * Register a handler with its operations (simple config) - */ - register(handlerName: string, config: HandlerConfig, serviceName?: string): void { - this.logger.info(`Registering handler: ${handlerName}`, { - operations: Object.keys(config), - service: serviceName, - }); - - this.handlers.set(handlerName, config); - - // Track service ownership if provided - if (serviceName) { - this.handlerServices.set(handlerName, serviceName); - } - } - - /** - * Register a handler with scheduled jobs (enhanced config) - */ - registerWithSchedule(config: HandlerConfigWithSchedule, serviceName?: string): void { - this.logger.info(`Registering handler with schedule: ${config.name}`, { - operations: Object.keys(config.operations), - scheduledJobs: config.scheduledJobs?.length || 0, - service: serviceName, - }); - - this.handlers.set(config.name, config.operations); - - if (config.scheduledJobs && config.scheduledJobs.length > 0) { - this.handlerSchedules.set(config.name, config.scheduledJobs); - } - - // Track service ownership if provided - if (serviceName) { - this.handlerServices.set(config.name, serviceName); - } - } - - /** - * Get a specific handler's configuration - */ - getHandler(handlerName: string): HandlerConfig | undefined { - return this.handlers.get(handlerName); - } - - /** - * Get all registered handlers - */ - getAllHandlers(): Map { - return new Map(this.handlers); - } - - /** - * Get scheduled jobs for a handler - */ - getScheduledJobs(handlerName: string): ScheduledJob[] { - return this.handlerSchedules.get(handlerName) || []; - } - - /** - * Get all handlers with their scheduled jobs - */ - getAllHandlersWithSchedule(): Map< - string, - { operations: HandlerConfig; scheduledJobs: ScheduledJob[] } - > { - const result = new Map(); - - for (const [name, operations] of this.handlers) { - result.set(name, { - operations, - scheduledJobs: this.handlerSchedules.get(name) || [], - }); - } - - return result; - } - - /** - * Get a specific operation from a handler - */ - getOperation(handlerName: string, operationName: string): JobHandler | undefined { - const handler = this.handlers.get(handlerName); - if (!handler) { - return undefined; - } - return handler[operationName]; - } - - /** - * Check if a handler is registered - */ - hasHandler(handlerName: string): boolean { - return this.handlers.has(handlerName); - } - - /** - * Get list of all registered handler names - */ - getHandlerNames(): string[] { - return Array.from(this.handlers.keys()); - } - - /** - * Get registry statistics - */ - getStats(): { handlers: number; operations: number; scheduledJobs: number } { - let operationCount = 0; - let scheduledJobCount = 0; - - for (const [_, config] of this.handlers) { - operationCount += Object.keys(config).length; - } - - for (const [_, jobs] of this.handlerSchedules) { - scheduledJobCount += jobs.length; - } - - return { - handlers: this.handlers.size, - operations: operationCount, - scheduledJobs: scheduledJobCount, - }; - } - - /** - * Get the service that owns a handler - */ - getHandlerService(handlerName: string): string | undefined { - return this.handlerServices.get(handlerName); - } - - /** - * Get all handlers for a specific service - */ - getServiceHandlers(serviceName: string): string[] { - const handlers: string[] = []; - for (const [handler, service] of this.handlerServices) { - if (service === serviceName) { - handlers.push(handler); - } - } - return handlers; - } - - /** - * Set service ownership for a handler (used during auto-discovery) - */ - setHandlerService(handlerName: string, serviceName: string): void { - this.handlerServices.set(handlerName, serviceName); - } - - /** - * Clear all registrations (useful for testing) - */ - clear(): void { - this.handlers.clear(); - this.handlerSchedules.clear(); - this.handlerServices.clear(); - } -} - -// Export singleton instance -export const handlerRegistry = new HandlerRegistry(); \ No newline at end of file diff --git a/libs/core/handlers/test/base-handler-http.test.ts b/libs/core/handlers/test/base-handler-http.test.ts index 4785c704..383b7602 100644 --- a/libs/core/handlers/test/base-handler-http.test.ts +++ b/libs/core/handlers/test/base-handler-http.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import type { IServiceContainer } from '@stock-bot/services'; -import * as utils from '@stock-bot/utils'; +import * as utils from '@stock-bot/utils/fetch'; import { BaseHandler } from '../src/base/BaseHandler'; // Mock fetch @@ -54,7 +54,7 @@ describe('BaseHandler HTTP Methods', () => { }); afterEach(() => { - // spyOn automatically restores + mock.restore(); }); describe('GET requests', () => { diff --git a/libs/utils/README.md b/libs/utils/README.md index 66639109..d685e90b 100644 --- a/libs/utils/README.md +++ b/libs/utils/README.md @@ -1,34 +1,79 @@ -# Utils Library - -Common utility functions shared across services in the stock-bot project. - -## Included Utilities - -### Date Utilities - -Helper functions for working with market dates: - -```typescript -import { dateUtils } from '@stock-bot/utils'; - -// Check if a date is a trading day -const isTradingDay = dateUtils.isTradingDay(new Date()); - -// Get the next trading day -const nextTradingDay = dateUtils.getNextTradingDay(new Date()); -``` - -### Financial Utilities - -Mathematical functions for financial calculations: - -```typescript -import { calculateCAGR, calculateSharpeRatio } from '@stock-bot/utils'; - -// Calculate compound annual growth rate -const returns = [0.05, 0.03, -0.01, 0.04, 0.02]; -const cagr = calculateCAGR(startValue, endValue, years); - -// Calculate Sharpe ratio -const sharpeRatio = calculateSharpeRatio(returns, 0.02); -``` +# General utilities + +`@stock-bot/utils` is a private workspace package for infrastructure-neutral general +helpers. Financial/feature calculations belong to `@stock-bot/calculations`, not here. + +## Supported capabilities + +- `@stock-bot/utils/fetch`: `fetch` and the type-only `FetchOptions`. +- `@stock-bot/utils/user-agent`: `getRandomUserAgent` selects from a fixed local list. +- `@stock-bot/utils/common`: `createProxyUrl` encodes proxy credentials; `sleep` + returns a timer-backed promise. +- `@stock-bot/utils/dates`: `utcDates` supplies `isWeekday`, `nextWeekday`, + `previousWeekday`, strict `parseDate` (`YYYY-MM-DD`) and `formatDate`. + +The root explicitly exports these six runtime values (`fetch`, `getRandomUserAgent`, +`createProxyUrl`, `sleep`, `utcDates`, `dateUtils`) plus the `FetchOptions` type. +Capability subpaths avoid loading unrelated helpers. There are no wildcard/deep exports. + +```ts +import { utcDates } from '@stock-bot/utils/dates'; +import { fetch, type FetchOptions } from '@stock-bot/utils/fetch'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; + +const options: FetchOptions = { + headers: { 'User-Agent': getRandomUserAgent() }, + timeout: 5_000, +}; +const response = await fetch('https://example.com/data', options); +const next = utcDates.nextWeekday(utcDates.parseDate('2024-03-08')); +``` + +Fetch keeps its existing logging, Bun proxy, timeout and original-`Response` behavior. +Non-OK statuses are returned, not thrown. Timeout cancellation and caller cancellation +are not composed: a configured timeout currently replaces the supplied signal. The +user-agent list is not fingerprinting or a guarantee of provider access. + +Date arithmetic is explicitly UTC, validates inputs and does not mutate the supplied +date. Weekdays are **not** exchange sessions: holidays, exchange time zones and trading +hours are not modeled. The deprecated `dateUtils` names (`isTradingDay`, +`getNextTradingDay`, `getPreviousTradingDay`, `formatDate`, `parseDate`) remain +as aliases for migration, not as verified trading-calendar APIs. This replaces the old +environment-dependent local weekday arithmetic; use `utcDates` in new code. + +`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike` +from `@stock-bot/logger` is type-only. No databases, configuration initialization, +application service containers or mandatory native bindings may be added here. + +## Calculation migration and removals + +The financial modules and OHLCV helpers were **relocated/preserved**, not discarded: + +- Reviewed returns/analytics/window math and OHLCV processing: + `@stock-bot/calculations` and its explicit capability subpaths. +- All 105 formerly active calculation functions with their original bodies: + `@stock-bot/calculations/legacy`, an opt-in historical API, not reviewed core. +- All seven disabled numerical/indicator prototypes: + non-executable source-verified snapshots in `libs/calculations/research/`. + +See [the calculation contract](../calculations/README.md) and +[the complete cleanup audit](../../docs/cleanup-audit.md) for readiness, preserved test +scenarios and deliberate removals. The empty `analyzePortfolio` placeholder remains +removed because it calculated nothing. + +Import assertions directly from `@stock-bot/invariants`; the redundant utility assertion +facade was removed, not its functionality. Import domain types from `@stock-bot/types`. +No finance compatibility re-export is added to the general utility package. + +## Verify + +From the repository root: + +```sh +bun run test:utils +bun run test:calculations +bun run check +``` + +The root gate includes general-utility and handler HTTP-consumer tests, calculation +regressions and architecture checks for the explicit APIs and dependency boundaries. diff --git a/libs/utils/package.json b/libs/utils/package.json index 49d16036..d8d3dfd9 100644 --- a/libs/utils/package.json +++ b/libs/utils/package.json @@ -1,7 +1,8 @@ { "name": "@stock-bot/utils", "version": "1.0.0", - "description": "Common utility functions for stock-bot services", + "private": true, + "description": "General HTTP, date and asynchronous helpers for stock-bot services", "main": "./src/index.ts", "types": "./src/index.ts", "scripts": { @@ -10,10 +11,7 @@ "test": "bun test" }, "dependencies": { - "@stock-bot/config": "workspace:*", "@stock-bot/logger": "workspace:*", - "@stock-bot/cache": "workspace:*", - "@stock-bot/types": "workspace:*", "@stock-bot/invariants": "workspace:*" }, "devDependencies": { @@ -23,6 +21,9 @@ }, "exports": { ".": "./src/index.ts", - "./assertions": "./src/assertions.ts" + "./fetch": "./src/fetch.ts", + "./user-agent": "./src/user-agent.ts", + "./common": "./src/common.ts", + "./dates": "./src/dateUtils.ts" } } diff --git a/libs/utils/src/assertions.ts b/libs/utils/src/assertions.ts deleted file mode 100644 index 9b8b7105..00000000 --- a/libs/utils/src/assertions.ts +++ /dev/null @@ -1 +0,0 @@ -export { at, defined } from '@stock-bot/invariants'; diff --git a/libs/utils/src/calculations/index.ts b/libs/utils/src/calculations/index.ts deleted file mode 100644 index 7ee646a0..00000000 --- a/libs/utils/src/calculations/index.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Financial Calculations Library - * - * This module provides a core set of financial calculations for trading and investment analysis. - * Focuses on basic calculations and standardized type exports. - */ - -// Re-export all standardized types from @stock-bot/types -export type { - OHLCV, - OHLCVWithMetadata, - PortfolioPosition, - PortfolioAnalysis, - AssetAllocation, - TradeExecution, - TradePerformance, - RiskMetrics, - DrawdownAnalysis, - ReturnAnalysis, - OptionParameters, - OptionPricing, - GreeksCalculation, - MarketData, - LiquidityMetrics, - MarketRegime, - PositionSizeParams, - KellyParams, - BalanceSheet, - IncomeStatement, - CashFlowStatement, - TechnicalIndicators, - CorrelationResult, - CorrelationMatrix, - VolatilityEstimates, - GARCHParameters, - BacktestResults, - HasClose, - HasOHLC, - HasVolume, - HasTimestamp, -} from '@stock-bot/types'; - -// Export working calculation functions -export * from './basic-calculations'; - -// Export working technical indicators (building one by one) -export { - sma, - ema, - rsi, - macd, - bollingerBands, - atr, - obv, - stochastic, - williamsR, - cci, - mfi, - vwma, - momentum, - roc, - accumulationDistribution, - aroon, - adx, - parabolicSAR, - chaikinMoneyFlow, - pivotPoints, - ichimoku, - ultimateOscillator, - easeOfMovement, - tema, - wma, - keltnerChannels, - donchianChannels, - klingerVolumeOscillator, - priceOscillator, - chandeMomentumOscillator, - stochasticRSI, - vortexIndicator, - balanceOfPower, - trix, - massIndex, - coppockCurve, -} from './technical-indicators'; -export * from './risk-metrics'; -export * from './performance-metrics'; - -// Convenience function for comprehensive portfolio analysis -export function analyzePortfolio( - _returns: number[], - _equityCurve: Array<{ value: number; date: Date }>, - _benchmarkReturns?: number[], - _riskFreeRate: number = 0.02 -): { - performance: Record; - risk: Record; -} { - // Note: Implementation depends on performance-metrics and risk-metrics - // This is a placeholder for the full implementation - return { - performance: {}, - risk: {}, - }; -} diff --git a/libs/utils/src/dateUtils.ts b/libs/utils/src/dateUtils.ts index 7495d321..d7e5e008 100644 --- a/libs/utils/src/dateUtils.ts +++ b/libs/utils/src/dateUtils.ts @@ -1,56 +1,48 @@ -/** - * Date and time utilities for working with market data - */ -export const dateUtils = { - /** - * Check if a date is a trading day (Monday-Friday, non-holiday) - * This is a simplified implementation - a real version would check market holidays - */ - isTradingDay(date: Date): boolean { - const day = date.getDay(); - return day > 0 && day < 6; // Mon-Fri - }, +function valid(date: Date): Date { + if (!Number.isFinite(date.getTime())) { + throw new RangeError('Invalid UTC date'); + } + return date; +} - /** - * Get the next trading day from a given date - */ - getNextTradingDay(date: Date): Date { - const nextDay = new Date(date); - nextDay.setDate(nextDay.getDate() + 1); +/** Weekdays in UTC, NOT an exchange calendar: holidays and venue sessions are not modeled. */ +function isWeekday(date: Date): boolean { + const day = valid(date).getUTCDay(); + return day > 0 && day < 6; +} - while (!this.isTradingDay(nextDay)) { - nextDay.setDate(nextDay.getDate() + 1); - } +function shiftWeekday(date: Date, direction: 1 | -1): Date { + const result = new Date(valid(date).getTime()); + do { + result.setUTCDate(result.getUTCDate() + direction); + } while (!isWeekday(result)); + return result; +} - return nextDay; - }, +function parseDate(value: string): Date { + if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) { + throw new RangeError('Expected YYYY-MM-DD'); + } + const date = valid(new Date(`${value}T00:00:00.000Z`)); + if (date.toISOString().slice(0, 10) !== value) { + throw new RangeError('Invalid calendar date'); + } + return date; +} - /** - * Get the previous trading day from a given date - */ - getPreviousTradingDay(date: Date): Date { - const prevDay = new Date(date); - prevDay.setDate(prevDay.getDate() - 1); - - while (!this.isTradingDay(prevDay)) { - prevDay.setDate(prevDay.getDate() - 1); - } - - return prevDay; - }, - - /** - * Format a date as YYYY-MM-DD - */ - formatDate(date: Date): string { - const parts = date.toISOString().split('T'); - return parts[0] ?? ''; - }, - - /** - * Parse a date string in YYYY-MM-DD format - */ - parseDate(dateStr: string): Date { - return new Date(dateStr); - }, +export const utcDates = { + isWeekday, + nextWeekday: (date: Date): Date => shiftWeekday(date, 1), + previousWeekday: (date: Date): Date => shiftWeekday(date, -1), + formatDate: (date: Date): string => valid(date).toISOString().slice(0, 10), + parseDate, +}; + +/** @deprecated Compatibility names only. These are UTC weekdays, never verified trading sessions. */ +export const dateUtils = { + isTradingDay: utcDates.isWeekday, + getNextTradingDay: utcDates.nextWeekday, + getPreviousTradingDay: utcDates.previousWeekday, + formatDate: utcDates.formatDate, + parseDate: utcDates.parseDate, }; diff --git a/libs/utils/src/fetch.ts b/libs/utils/src/fetch.ts index cc5147a3..a13bcd56 100644 --- a/libs/utils/src/fetch.ts +++ b/libs/utils/src/fetch.ts @@ -5,7 +5,7 @@ import type { LoggerLike } from '@stock-bot/logger'; * Drop-in replacement for native fetch with additional features */ -export interface BunRequestInit extends RequestInit { +interface BunRequestInit extends RequestInit { proxy?: string; } diff --git a/libs/utils/src/index.ts b/libs/utils/src/index.ts index 67758170..08241eed 100644 --- a/libs/utils/src/index.ts +++ b/libs/utils/src/index.ts @@ -1,7 +1,5 @@ -export * from './calculations/index'; -export * from './assertions'; -export * from './common'; -export * from './dateUtils'; -export * from './generic-functions'; -export * from './fetch'; -export * from './user-agent'; +export { fetch } from './fetch'; +export type { FetchOptions } from './fetch'; +export { getRandomUserAgent } from './user-agent'; +export { createProxyUrl, sleep } from './common'; +export { dateUtils, utcDates } from './dateUtils'; diff --git a/libs/utils/test/common-dates.test.ts b/libs/utils/test/common-dates.test.ts new file mode 100644 index 00000000..e1accce7 --- /dev/null +++ b/libs/utils/test/common-dates.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'bun:test'; +import { createProxyUrl, sleep } from '@stock-bot/utils/common'; +import { dateUtils, utcDates } from '@stock-bot/utils/dates'; + +describe('restored general utilities', () => { + describe('common utilities', () => { + it('should create proxy URL with auth', () => { + const proxy = { + protocol: 'http', + host: '192.168.1.1', + port: 8080, + username: 'user', + password: 'pass', + }; + + const url = createProxyUrl(proxy); + expect(url).toBe('http://user:pass@192.168.1.1:8080'); + }); + + it('should create proxy URL without auth', () => { + const proxy = { + protocol: 'socks5', + host: '192.168.1.1', + port: 1080, + }; + + const url = createProxyUrl(proxy); + expect(url).toBe('socks5://192.168.1.1:1080'); + }); + + it('should sleep for specified milliseconds', async () => { + const start = Date.now(); + await sleep(100); + const elapsed = Date.now() - start; + + expect(elapsed).toBeGreaterThanOrEqual(90); + }); + + it('UTC weekday helpers preserve the supplied instant time and never mutate inputs', () => { + const friday = new Date('2024-03-08T23:30:00.000Z'); + expect(utcDates.nextWeekday(friday).toISOString()).toBe('2024-03-11T23:30:00.000Z'); + expect(friday.toISOString()).toBe('2024-03-08T23:30:00.000Z'); + expect(utcDates.previousWeekday(new Date('2024-03-11T23:30:00Z')).toISOString()).toBe( + '2024-03-08T23:30:00.000Z' + ); + // Christmas is a weekday, not a promise that any particular exchange is open. + expect(utcDates.isWeekday(new Date('2023-12-25T00:00:00Z'))).toBe(true); + const detached = utcDates.nextWeekday; + expect(detached(friday).getUTCDay()).toBe(1); + }); + + it('strict UTC dates reject invalid inputs and impossible calendar dates', () => { + expect(utcDates.parseDate('2024-02-29').toISOString()).toBe('2024-02-29T00:00:00.000Z'); + for (const value of ['2023-02-29', '2024-02-30', '2024-13-01', '2024-01-01T00:00:00Z', '']) { + expect(() => utcDates.parseDate(value)).toThrow(); + } + expect(() => utcDates.nextWeekday(new Date(NaN))).toThrow(); + expect(() => utcDates.formatDate(new Date(NaN))).toThrow(); + }); + + it('proxy credentials remain encoded and sleep remains asynchronous', async () => { + expect( + createProxyUrl({ + protocol: 'http', + host: 'localhost', + port: 8080, + username: 'a@b', + password: 'p:/?', + }) + ).toBe('http://a%40b:p%3A%2F%3F@localhost:8080'); + const wait = sleep(0); + expect(wait).toBeInstanceOf(Promise); + await wait; + }); + }); + + describe('date utilities', () => { + it('should check if date is trading day', () => { + const monday = new Date('2023-12-25'); // Monday + const saturday = new Date('2023-12-23'); // Saturday + const sunday = new Date('2023-12-24'); // Sunday + + expect(dateUtils.isTradingDay(monday)).toBe(true); + expect(dateUtils.isTradingDay(saturday)).toBe(false); + expect(dateUtils.isTradingDay(sunday)).toBe(false); + }); + + it('should get next trading day', () => { + const friday = new Date('2023-12-22'); // Friday + const nextDay = dateUtils.getNextTradingDay(friday); + + expect(nextDay.getUTCDay()).toBe(1); // Monday + }); + + it('should get previous trading day', () => { + const monday = new Date('2023-12-25'); // Monday + const prevDay = dateUtils.getPreviousTradingDay(monday); + + expect(prevDay.getUTCDay()).toBe(5); // Friday + }); + + it('should format date as YYYY-MM-DD', () => { + const date = new Date('2023-12-25T10:30:00Z'); + const formatted = dateUtils.formatDate(date); + + expect(formatted).toBe('2023-12-25'); + }); + + it('should parse date from string', () => { + const date = dateUtils.parseDate('2023-12-25'); + + expect(date.getUTCFullYear()).toBe(2023); + expect(date.getUTCMonth()).toBe(11); // 0-based + expect(date.getUTCDate()).toBe(25); + }); + }); +}); diff --git a/libs/utils/test/fetch.test.ts b/libs/utils/test/fetch.test.ts index 2ab3b4a3..5a641f12 100644 --- a/libs/utils/test/fetch.test.ts +++ b/libs/utils/test/fetch.test.ts @@ -1,13 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; -import { fetch } from '../src/fetch'; +import { fetch } from '@stock-bot/utils/fetch'; describe('Enhanced Fetch', () => { let originalFetch: typeof globalThis.fetch; + let originalDebug: typeof console.debug; let mockFetch: any; let mockLogger: any; beforeEach(() => { originalFetch = globalThis.fetch; + originalDebug = console.debug; mockFetch = mock(() => Promise.resolve(new Response('test'))); globalThis.fetch = mockFetch; @@ -20,6 +22,7 @@ describe('Enhanced Fetch', () => { afterEach(() => { globalThis.fetch = originalFetch; + console.debug = originalDebug; }); describe('basic fetch', () => { @@ -209,8 +212,6 @@ describe('Enhanced Fetch', () => { await fetch('https://api.example.com/data'); expect(consoleSpy).toHaveBeenCalledTimes(2); // Request and response - - console.debug = originalFetch as any; }); }); diff --git a/libs/utils/test/user-agent.test.ts b/libs/utils/test/user-agent.test.ts index f85fc144..7fbb478f 100644 --- a/libs/utils/test/user-agent.test.ts +++ b/libs/utils/test/user-agent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'bun:test'; -import { getRandomUserAgent } from '../src/user-agent'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; describe('User Agent', () => { describe('getRandomUserAgent', () => { diff --git a/libs/utils/tsconfig.json b/libs/utils/tsconfig.json index 8e4792ca..7b4eec8c 100644 --- a/libs/utils/tsconfig.json +++ b/libs/utils/tsconfig.json @@ -10,20 +10,11 @@ "include": ["src/**/*"], "exclude": ["node_modules", "dist"], "references": [ - { - "path": "../core/types" - }, - { - "path": "../core/cache" - }, - { - "path": "../core/config" - }, { "path": "../core/logger" }, { - "path": "../../libs/core/invariants" + "path": "../core/invariants" } ] } diff --git a/package.json b/package.json index 34e3c78c..bd2eee7e 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,8 @@ "typecheck": "tsc --project tsconfig.check.json --noEmit", "check": "bun run scripts/check.ts", "test:tooling": "bun test scripts/test/", + "test:utils": "bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts", + "test:calculations": "bun test libs/calculations/test/", "test:contracts": "tsc --project tsconfig.contracts.json --noEmit", "test": "turbo run test --filter=!@stock-bot/stock-app", "test:watch": "bun test --watch", diff --git a/scripts/check.ts b/scripts/check.ts index d1d0c4f5..ff4b4016 100644 --- a/scripts/check.ts +++ b/scripts/check.ts @@ -7,6 +7,8 @@ export const checks = [ 'typecheck', 'test:contracts', 'test:tooling', + 'test:utils', + 'test:calculations', 'test:integration', 'test:native', 'lint:check', diff --git a/scripts/runtime-imports.ts b/scripts/runtime-imports.ts new file mode 100644 index 00000000..03ccd50e --- /dev/null +++ b/scripts/runtime-imports.ts @@ -0,0 +1,60 @@ +import { readFileSync } from 'node:fs'; +import ts from 'typescript'; + +/** Runtime edges only: type imports and type re-exports cannot initialize a module. */ +export function runtimeImports(file: string, sourceText = readFileSync(file, 'utf8')): string[] { + const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true); + const imports = new Set(); + function visit(node: ts.Node) { + if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { + const clause = node.importClause; + const bindings = clause?.namedBindings; + const typesOnly = + clause?.isTypeOnly || + (clause && + !clause.name && + bindings && + ts.isNamedImports(bindings) && + bindings.elements.length > 0 && + bindings.elements.every(item => item.isTypeOnly)); + if (!typesOnly) imports.add(node.moduleSpecifier.text); + } + if ( + ts.isExportDeclaration(node) && + !node.isTypeOnly && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) + ) { + const clause = node.exportClause; + if ( + !clause || + !ts.isNamedExports(clause) || + !clause.elements.length || + clause.elements.some(item => !item.isTypeOnly) + ) { + imports.add(node.moduleSpecifier.text); + } + } + if ( + ts.isCallExpression(node) && + (node.expression.kind === ts.SyntaxKind.ImportKeyword || + (ts.isIdentifier(node.expression) && node.expression.text === 'require')) && + node.arguments[0] && + ts.isStringLiteral(node.arguments[0]) + ) { + imports.add(node.arguments[0].text); + } + if ( + ts.isImportEqualsDeclaration(node) && + !node.isTypeOnly && + ts.isExternalModuleReference(node.moduleReference) && + node.moduleReference.expression && + ts.isStringLiteral(node.moduleReference.expression) + ) { + imports.add(node.moduleReference.expression.text); + } + ts.forEachChild(node, visit); + } + visit(source); + return [...imports]; +} diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 50b0df8a..6b69cdb8 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -3,63 +3,11 @@ import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'bun:test'; import ts from 'typescript'; +import { runtimeImports } from '../runtime-imports'; const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url)); const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file)); -/** Include static imports/re-exports and lazy imports; type-only edges do not load code. */ -function runtimeImports(file: string): string[] { - const source = ts.createSourceFile( - file, - readFileSync(file, 'utf8'), - ts.ScriptTarget.Latest, - true - ); - const imports = new Set(); - function visit(node: ts.Node) { - if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { - const clause = node.importClause; - const bindings = clause?.namedBindings; - const typesOnly = - clause?.isTypeOnly || - (clause && - !clause.name && - bindings && - ts.isNamedImports(bindings) && - bindings.elements.length > 0 && - bindings.elements.every(item => item.isTypeOnly)); - if (!typesOnly) imports.add(node.moduleSpecifier.text); - } - if ( - ts.isExportDeclaration(node) && - !node.isTypeOnly && - node.moduleSpecifier && - ts.isStringLiteral(node.moduleSpecifier) - ) { - const clause = node.exportClause; - if ( - !clause || - !ts.isNamedExports(clause) || - !clause.elements.length || - clause.elements.some(item => !item.isTypeOnly) - ) { - imports.add(node.moduleSpecifier.text); - } - } - if ( - ts.isCallExpression(node) && - node.expression.kind === ts.SyntaxKind.ImportKeyword && - node.arguments[0] && - ts.isStringLiteral(node.arguments[0]) - ) { - imports.add(node.arguments[0].text); - } - ts.forEachChild(node, visit); - } - visit(source); - return [...imports]; -} - const imports = new Map(files.map(file => [file, runtimeImports(file)])); function localFile(from: string, specifier: string): string | undefined { if (!specifier.startsWith('.')) return undefined; @@ -256,14 +204,14 @@ describe('orchestrator architecture boundaries', () => { expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']); }); - it('shared analytics math is pure and cannot load report facades or application adapters', () => { + it('reviewed analytics and window math live in the shared calculations library', () => { for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) { - for (const file of reachable(join(root, 'analytics/' + entry + '.ts'))) { - expect(relative(root, file)).toMatch(/^analytics\//); - expect(relative(root, file)).not.toBe('analytics/PerformanceAnalyzer.ts'); - expect((imports.get(file) ?? []).every(specifier => specifier.startsWith('.'))).toBe(true); - } + expect(existsSync(join(root, 'analytics/' + entry + '.ts'))).toBe(false); } + expect(existsSync(join(root, 'indicators/window-statistics.ts'))).toBe(false); + expect(imports.get(join(root, 'analytics/PerformanceAnalyzer.ts'))).toEqual([ + '@stock-bot/calculations/analytics', + ]); }); it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => { @@ -276,9 +224,12 @@ describe('orchestrator architecture boundaries', () => { for (const specifier of imports.get(file) ?? []) { expect( specifier.startsWith('.') || - ['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes( - specifier - ) + [ + 'zod', + '@stock-bot/invariants', + '@stock-bot/logger', + '@stock-bot/calculations/analytics', + ].includes(specifier) ).toBe(true); } } diff --git a/scripts/test/library-boundaries.test.ts b/scripts/test/library-boundaries.test.ts new file mode 100644 index 00000000..a998afc3 --- /dev/null +++ b/scripts/test/library-boundaries.test.ts @@ -0,0 +1,204 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'bun:test'; +import * as utils from '@stock-bot/utils'; +import { fetch } from '@stock-bot/utils/fetch'; +import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; +import { checks } from '../check'; +import { runtimeImports } from '../runtime-imports'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const utilsRoot = join(root, 'libs/utils'); +const manifest = JSON.parse(readFileSync(join(utilsRoot, 'package.json'), 'utf8')); +const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot })].map(file => + join(utilsRoot, file) +); + +describe('shared library boundaries', () => { + it('utils exposes general helpers without a financial framework', () => { + expect(Object.keys(utils).sort()).toEqual([ + 'createProxyUrl', + 'dateUtils', + 'fetch', + 'getRandomUserAgent', + 'sleep', + 'utcDates', + ]); + expect(utils.fetch).toBe(fetch); + expect(utils.getRandomUserAgent).toBe(getRandomUserAgent); + expect(manifest.private).toBe(true); + expect(manifest.exports).toEqual({ + '.': './src/index.ts', + './fetch': './src/fetch.ts', + './user-agent': './src/user-agent.ts', + './common': './src/common.ts', + './dates': './src/dateUtils.ts', + }); + for (const retired of ['assertions', 'calculations', 'src/fetch', 'dateUtils']) { + expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow(); + } + }); + + it('utils cannot load infrastructure adapters or grow another domain-math API', () => { + expect(Object.keys(manifest.dependencies).sort()).toEqual([ + '@stock-bot/invariants', + '@stock-bot/logger', + ]); + const config = JSON.parse(readFileSync(join(utilsRoot, 'tsconfig.json'), 'utf8')); + expect(config.references.map((ref: { path: string }) => ref.path).sort()).toEqual([ + '../core/invariants', + '../core/logger', + ]); + for (const file of sourceFiles) { + expect(file).not.toContain('/calculations/'); + for (const specifier of runtimeImports(file)) { + if (specifier.startsWith('.')) { + const local = resolve(dirname(file), specifier); + expect( + sourceFiles.some( + target => target === `${local}.ts` || target === join(local, 'index.ts') + ) + ).toBe(true); + } else { + // Logger is a type-only capability; only invariants may be loaded at runtime. + expect(specifier).toBe('@stock-bot/invariants'); + } + } + } + }); + + it('calculations is a portable pure library, with legacy code isolated from supported exports', () => { + const directory = join(root, 'libs/calculations'); + const pkg = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')); + expect(Object.keys(pkg.dependencies).sort()).toEqual([ + '@stock-bot/invariants', + '@stock-bot/types', + ]); + expect(pkg.private).toBe(true); + const sources = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: directory })].map(file => + join(directory, file) + ); + for (const file of sources) { + for (const specifier of runtimeImports(file)) { + if (!specifier.startsWith('.')) { + expect(specifier).toBe('@stock-bot/invariants'); + continue; + } + const target = resolve(dirname(file), specifier); + const dependency = sources.find( + source => source === `${target}.ts` || source === join(target, 'index.ts') + ); + expect(dependency).toBeDefined(); + if (!file.includes('/legacy/')) expect(dependency).not.toContain('/legacy/'); + } + } + expect(Object.keys(pkg.exports).sort()).toEqual([ + '.', + './analytics', + './indicators', + './legacy', + './market-data', + './returns', + ]); + for (const path of [ + 'research', + 'src/legacy/basic-calculations', + 'legacy/technical-indicators', + ]) { + expect(() => Bun.resolveSync(`@stock-bot/calculations/${path}`, root)).toThrow(); + } + expect(runtimeImports(join(root, 'libs/core/invariants/src/index.ts'))).toEqual([]); + }); + + it('stock applications use reviewed calculation contracts, not archived prototypes or legacy math', () => { + const directory = join(root, 'apps/stock'); + const files = [...new Bun.Glob('*/src/**/*.ts').scanSync({ cwd: directory })]; + for (const file of files) { + for (const specifier of runtimeImports(join(directory, file))) { + expect(specifier).not.toMatch(/^@stock-bot\/calculations\/(legacy|research)/); + if (specifier.startsWith('.')) { + const target = resolve(dirname(join(directory, file)), specifier); + expect(target).not.toContain('/libs/calculations/src/legacy/'); + expect(target).not.toContain('/libs/calculations/research/'); + } + } + } + }); + + it('library source and tests contain no disabled or backup copies', () => { + const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })]; + const backups = files.filter( + file => + !file.split('/').some(part => ['node_modules', 'dist'].includes(part)) && + /\.(old|disabled|bak|orig)$/.test(file) + ); + expect(backups).toEqual([]); + }); + + it('the root gate runs utility and HTTP-consumer regressions', () => { + expect(checks).toContain('test:utils'); + expect(checks).toContain('test:calculations'); + const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); + expect(pkg.scripts['test:utils']).toBe( + 'bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts' + ); + for (const path of ['apps/stock/orchestrator', 'tools/coverage-cli']) { + const consumer = JSON.parse(readFileSync(join(root, path, 'package.json'), 'utf8')); + expect(consumer.dependencies).not.toHaveProperty('@stock-bot/utils'); + expect(consumer.dependencies).not.toHaveProperty('simple-statistics'); + } + }); +}); + +describe('runtime dependency inspection', () => { + it('ignores erased type-only imports and re-exports', () => { + expect( + runtimeImports( + 'fixture.ts', + ` + import type { Logger } from 'logger'; + import { type Cache } from 'cache'; + import type * as DB from 'database'; + export type { Portfolio } from 'finance'; + export { type Model } from 'models'; + type Lazy = typeof import('type-query'); + import type Legacy = require('legacy-type'); + ` + ) + ).toEqual([]); + }); + + it('detects static, mixed, side-effect, lazy and CommonJS runtime edges', () => { + expect( + runtimeImports( + 'fixture.ts', + ` + import { run, type Options } from 'mixed'; + import fallback, { type Shape } from 'default'; + import 'side-effect'; + export { execute, type Input } from 're-export'; + export * from 'star'; + export * as ns from 'namespace'; + import {} from 'empty-import'; + export {} from 'empty-export'; + const module = await import('lazy'); + const cjs = require('commonjs'); + import legacy = require('import-equals'); + ` + ) + ).toEqual([ + 'mixed', + 'default', + 'side-effect', + 're-export', + 'star', + 'namespace', + 'empty-import', + 'empty-export', + 'lazy', + 'commonjs', + 'import-equals', + ]); + }); +}); diff --git a/test/integration/analytics-math.test.ts b/test/integration/analytics-math.test.ts index f88c70e4..5bf861f2 100644 --- a/test/integration/analytics-math.test.ts +++ b/test/integration/analytics-math.test.ts @@ -1,12 +1,13 @@ import { describe, expect, test } from 'bun:test'; -import { dayMs, equityAnalysis } from '../../apps/stock/orchestrator/src/analytics/equity'; -import { performanceAnalysis } from '../../apps/stock/orchestrator/src/analytics/performance'; -import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer'; import { + dayMs, + equityAnalysis, factorStatistics, + performanceAnalysis, returnStatistics, -} from '../../apps/stock/orchestrator/src/analytics/return-statistics'; -import { tradeStatistics } from '../../apps/stock/orchestrator/src/analytics/trade-statistics'; + tradeStatistics, +} from '@stock-bot/calculations/analytics'; +import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer'; import golden from '../fixtures/analytics-golden.json'; const start = Date.parse('2024-01-01T00:00:00Z'); diff --git a/test/integration/strategy-contracts.test.ts b/test/integration/strategy-contracts.test.ts index 493067ef..358bf26d 100644 --- a/test/integration/strategy-contracts.test.ts +++ b/test/integration/strategy-contracts.test.ts @@ -24,7 +24,7 @@ import { movingAverageCrossover, trailingMean, trailingPopulationDeviation, -} from '../../apps/stock/orchestrator/src/indicators/window-statistics'; +} from '@stock-bot/calculations/indicators'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; diff --git a/tools/coverage-cli/package.json b/tools/coverage-cli/package.json index 4a054f27..1bba9908 100644 --- a/tools/coverage-cli/package.json +++ b/tools/coverage-cli/package.json @@ -18,7 +18,6 @@ "handlebars": "^4.7.8", "lcov-parse": "^1.0.0", "table": "^6.8.1", - "@stock-bot/utils": "workspace:*", "@stock-bot/invariants": "workspace:*" }, "devDependencies": {