refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -1,157 +0,0 @@
# Library Standards and Patterns
This document defines the standardized patterns for all libraries in the @stock-bot ecosystem.
## Export Patterns
### Standard: Named Exports Only
All libraries should use **named exports only**. Default exports have been removed for consistency and better tree-shaking.
**Example:**
```typescript
// ✅ Good - Named exports
export { createCache } from './cache';
export type { CacheOptions } from './types';
// ❌ Bad - Default export
export default createCache;
```
## Initialization Patterns
Libraries follow different initialization patterns based on their purpose:
### 1. Singleton with Global State
**Use for:** Global services that should have only one instance (config, logger)
**Example:** Config library
```typescript
let configInstance: ConfigManager | null = null;
export function initializeConfig(): AppConfig {
if (!configInstance) {
configInstance = new ConfigManager();
}
return configInstance.initialize();
}
export function getConfig(): AppConfig {
if (!configInstance) {
throw new Error('Config not initialized');
}
return configInstance.get();
}
```
### 2. Factory with Registry
**Use for:** Services that need instance reuse based on configuration (cache, logger instances)
**Example:** Cache library
```typescript
const cacheInstances = new Map<string, CacheProvider>();
export function createCache(options: CacheOptions): CacheProvider {
if (options.shared) {
const key = generateKey(options);
if (cacheInstances.has(key)) {
return cacheInstances.get(key)!;
}
const cache = new RedisCache(options);
cacheInstances.set(key, cache);
return cache;
}
return new RedisCache(options);
}
```
### 3. Pure Factory Functions
**Use for:** Services that need creation logic beyond simple instantiation
**Example:** Event bus with configuration processing
```typescript
export function createEventBus(config: EventBusConfig): EventBus {
// Process config, set defaults, etc.
const processedConfig = { ...defaultConfig, ...config };
return new EventBus(processedConfig);
}
```
**Note:** Simple instantiation doesn't need factories - use direct class instantiation or DI container.
### 4. Direct Class Exports
**Use for:** Simple utilities or services managed by DI container
**Example:** MongoDB library
```typescript
export { MongoDBClient } from './client';
// No factory function - let DI container handle instantiation
```
### 5. Singleton Classes
**Use for:** Manager classes that coordinate multiple instances
**Example:** QueueManager
```typescript
export class QueueManager {
private static instance: QueueManager | null = null;
static initialize(config: QueueConfig): QueueManager {
if (!QueueManager.instance) {
QueueManager.instance = new QueueManager(config);
}
return QueueManager.instance;
}
static getInstance(): QueueManager {
if (!QueueManager.instance) {
throw new Error('QueueManager not initialized');
}
return QueueManager.instance;
}
}
```
## Pattern Selection Guide
Choose the initialization pattern based on these criteria:
| Pattern | When to Use | Examples |
|---------|-------------|----------|
| **Singleton with Global State** | - One instance per process<br>- Stateful configuration<br>- Process-wide settings | config, logger setup |
| **Factory with Registry** | - Multiple instances with same config should share<br>- Connection pooling<br>- Resource optimization | cache, logger instances |
| **Pure Factory** | - Complex initialization logic<br>- Configuration processing needed<br>- Defaults to apply | event bus (if needed) |
| **Direct Class Export** | - DI container manages lifecycle<br>- Simple initialization<br>- No special setup needed | database clients (MongoDB, PostgreSQL, QuestDB), utilities |
| **Singleton Class** | - Coordinates multiple resources<br>- Central management point<br>- Graceful shutdown needed | QueueManager, ConnectionManager |
## Additional Standards
### Error Handling
- All libraries should throw descriptive errors
- Consider creating custom error classes for domain-specific errors
- Always include context in error messages
### Configuration
- Accept configuration through constructor/factory parameters
- Validate configuration using Zod schemas
- Provide sensible defaults where appropriate
### Testing
- All libraries must have unit tests
- Use consistent test file naming: `*.test.ts`
- Mock external dependencies
### Documentation
- Every library must have a README.md
- Include usage examples
- Document all public APIs with JSDoc
### TypeScript
- Export all public types
- Use strict TypeScript settings
- Avoid `any` types
### Dependencies
- Minimize external dependencies
- Use exact versions for critical dependencies
- Document peer dependencies clearly

View file

@ -62,38 +62,6 @@ The application-level `PerformanceAnalyzer` remains a reporting facade. The nati
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
@ -104,5 +72,4 @@ 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.
Architecture checks keep infrastructure and application adapters out of the library.

View file

@ -1,408 +0,0 @@
{
"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"
]
}
]
}

View file

@ -11,8 +11,7 @@
"./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"
"./returns": "./src/returns.ts"
},
"scripts": {
"build": "tsc",

View file

@ -1,26 +0,0 @@
# 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.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,822 +0,0 @@
# 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
*/
export interface OptionParameters {
spotPrice: number;
strikePrice: number;
timeToExpiry: number; // in years
riskFreeRate: number;
volatility: number;
dividendYield?: number;
}
export interface OptionPricing {
callPrice: number;
putPrice: number;
intrinsicValueCall: number;
intrinsicValuePut: number;
timeValueCall: number;
timeValuePut: number;
}
export interface GreeksCalculation {
delta: number;
gamma: number;
theta: number;
vega: number;
rho: number;
}
export interface ImpliedVolatilityResult {
impliedVolatility: number;
iterations: number;
converged: boolean;
}
/**
* Black-Scholes option pricing model
*/
export function blackScholes(params: OptionParameters): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
if (timeToExpiry <= 0) {
const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0);
const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0);
return {
callPrice: intrinsicValueCall,
putPrice: intrinsicValuePut,
intrinsicValueCall,
intrinsicValuePut,
timeValueCall: 0,
timeValuePut: 0,
};
}
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
const nd1 = normalCDF(d1);
const nd2 = normalCDF(d2);
const nMinusd1 = normalCDF(-d1);
const nMinusd2 = normalCDF(-d2);
const callPrice =
spotPrice * Math.exp(-dividendYield * timeToExpiry) * nd1 -
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2;
const putPrice =
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nMinusd2 -
spotPrice * Math.exp(-dividendYield * timeToExpiry) * nMinusd1;
const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0);
const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0);
const timeValueCall = callPrice - intrinsicValueCall;
const timeValuePut = putPrice - intrinsicValuePut;
return {
callPrice,
putPrice,
intrinsicValueCall,
intrinsicValuePut,
timeValueCall,
timeValuePut,
};
}
export function impliedVolatility(
price: number,
S: number,
K: number,
T: number,
r: number,
isCall = true
): number {
// …Newton–Raphson on σ to match blackScholesPrice
let sigma = 0.2; // Initial guess for volatility
const tolerance = 1e-6;
const maxIterations = 100;
let iteration = 0;
let priceDiff = 1; // Initialize to a non-zero value
while (Math.abs(priceDiff) > tolerance && iteration < maxIterations) {
const params: OptionParameters = {
spotPrice: S,
strikePrice: K,
timeToExpiry: T,
riskFreeRate: r,
volatility: sigma,
};
const calculatedPrice = isCall ? blackScholes(params).callPrice : blackScholes(params).putPrice;
priceDiff = calculatedPrice - price;
// Calculate Vega
const greeks = calculateGreeks(params, isCall ? 'call' : 'put');
const vega = greeks.vega * 100; // Convert from percentage to absolute
if (vega === 0) {
break; // Avoid division by zero
}
sigma -= priceDiff / vega; // Update volatility estimate
iteration++;
}
if (iteration === maxIterations) {
console.warn('Implied volatility calculation did not converge');
}
if (sigma < 0) {
console.warn('Calculated implied volatility is negative, returning 0');
return 0;
}
if (sigma > 10) {
console.warn('Calculated implied volatility is too high, returning 10');
return 10; // Cap at a reasonable maximum
}
if (isNaN(sigma)) {
console.warn('Calculated implied volatility is NaN, returning 0');
return 0;
}
return sigma;
}
/**
* Calculate option Greeks using Black-Scholes model
*/
export function calculateGreeks(
params: OptionParameters,
optionType: 'call' | 'put' = 'call'
): GreeksCalculation {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
if (timeToExpiry <= 0) {
return {
delta:
optionType === 'call'
? spotPrice > strikePrice
? 1
: 0
: spotPrice < strikePrice
? -1
: 0,
gamma: 0,
theta: 0,
vega: 0,
rho: 0,
};
}
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
const nd1 = normalCDF(d1);
const nd2 = normalCDF(d2);
const npd1 = normalPDF(d1);
// Delta
const callDelta = Math.exp(-dividendYield * timeToExpiry) * nd1;
const putDelta = Math.exp(-dividendYield * timeToExpiry) * (nd1 - 1);
const delta = optionType === 'call' ? callDelta : putDelta;
// Gamma (same for calls and puts)
const gamma =
(Math.exp(-dividendYield * timeToExpiry) * npd1) /
(spotPrice * volatility * Math.sqrt(timeToExpiry));
// Theta
const term1 =
-(spotPrice * npd1 * volatility * Math.exp(-dividendYield * timeToExpiry)) /
(2 * Math.sqrt(timeToExpiry));
const term2Call = riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2;
const term2Put =
-riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2);
const term3 =
dividendYield *
spotPrice *
Math.exp(-dividendYield * timeToExpiry) *
(optionType === 'call' ? nd1 : normalCDF(-d1));
const theta =
optionType === 'call' ? (term1 - term2Call + term3) / 365 : (term1 + term2Put + term3) / 365;
// Vega (same for calls and puts)
const vega =
(spotPrice * Math.exp(-dividendYield * timeToExpiry) * npd1 * Math.sqrt(timeToExpiry)) / 100;
// Rho
const callRho = (strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * nd2) / 100;
const putRho =
(-strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2)) / 100;
const rho = optionType === 'call' ? callRho : putRho;
return {
delta,
gamma,
theta,
vega,
rho,
};
}
/**
* Calculate implied volatility using Newton-Raphson method
*/
export function calculateImpliedVolatility(
marketPrice: number,
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
optionType: 'call' | 'put' = 'call',
dividendYield: number = 0,
initialGuess: number = 0.2,
tolerance: number = 1e-6,
maxIterations: number = 100
): ImpliedVolatilityResult {
let volatility = initialGuess;
let iterations = 0;
let converged = false;
for (let i = 0; i < maxIterations; i++) {
iterations = i + 1;
const params: OptionParameters = {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield,
};
const pricing = blackScholes(params);
const theoreticalPrice = optionType === 'call' ? pricing.callPrice : pricing.putPrice;
const priceDiff = theoreticalPrice - marketPrice;
if (Math.abs(priceDiff) < tolerance) {
converged = true;
break;
}
// Calculate vega for Newton-Raphson
const greeks = calculateGreeks(params, optionType);
const vega = greeks.vega * 100; // Convert back from percentage
if (Math.abs(vega) < 1e-10) {
break; // Avoid division by zero
}
volatility = volatility - priceDiff / vega;
// Keep volatility within reasonable bounds
volatility = Math.max(0.001, Math.min(volatility, 10));
}
return {
impliedVolatility: volatility,
iterations,
converged,
};
}
/**
* Binomial option pricing model
*/
export function binomialOptionPricing(
params: OptionParameters,
optionType: 'call' | 'put' = 'call',
americanStyle: boolean = false,
steps: number = 100
): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
const dt = timeToExpiry / steps;
const u = Math.exp(volatility * Math.sqrt(dt));
const d = 1 / u;
const p = (Math.exp((riskFreeRate - dividendYield) * dt) - d) / (u - d);
const discount = Math.exp(-riskFreeRate * dt);
// Create price tree
const stockPrices: number[][] = [];
for (let i = 0; i <= steps; i++) {
stockPrices[i] = [];
for (let j = 0; j <= i; j++) {
stockPrices[i][j] = spotPrice * Math.pow(u, i - j) * Math.pow(d, j);
}
}
// Calculate option values at expiration
const optionValues: number[][] = [];
for (let i = 0; i <= steps; i++) {
optionValues[i] = [];
}
for (let j = 0; j <= steps; j++) {
if (optionType === 'call') {
optionValues[steps][j] = Math.max(stockPrices[steps][j] - strikePrice, 0);
} else {
optionValues[steps][j] = Math.max(strikePrice - stockPrices[steps][j], 0);
}
}
// Work backwards through the tree
for (let i = steps - 1; i >= 0; i--) {
for (let j = 0; j <= i; j++) {
// European option value
const holdValue =
discount * (p * optionValues[i + 1][j] + (1 - p) * optionValues[i + 1][j + 1]);
if (americanStyle) {
// American option - can exercise early
const exerciseValue =
optionType === 'call'
? Math.max(stockPrices[i][j] - strikePrice, 0)
: Math.max(strikePrice - stockPrices[i][j], 0);
optionValues[i][j] = Math.max(holdValue, exerciseValue);
} else {
optionValues[i][j] = holdValue;
}
}
}
const price = optionValues[0][0];
const intrinsicValue =
optionType === 'call'
? Math.max(spotPrice - strikePrice, 0)
: Math.max(strikePrice - spotPrice, 0);
const timeValue = price - intrinsicValue;
if (optionType === 'call') {
return {
callPrice: price,
putPrice: 0, // Not calculated
intrinsicValueCall: intrinsicValue,
intrinsicValuePut: 0,
timeValueCall: timeValue,
timeValuePut: 0,
};
} else {
return {
callPrice: 0, // Not calculated
putPrice: price,
intrinsicValueCall: 0,
intrinsicValuePut: intrinsicValue,
timeValueCall: 0,
timeValuePut: timeValue,
};
}
}
/**
* Monte Carlo option pricing
*/
export function monteCarloOptionPricing(
params: OptionParameters,
optionType: 'call' | 'put' = 'call',
numSimulations: number = 100000
): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
let totalPayoff = 0;
for (let i = 0; i < numSimulations; i++) {
// Generate random price path
const z = boxMullerTransform();
const finalPrice =
spotPrice *
Math.exp(
(riskFreeRate - dividendYield - 0.5 * volatility * volatility) * timeToExpiry +
volatility * Math.sqrt(timeToExpiry) * z
);
// Calculate payoff
const payoff =
optionType === 'call'
? Math.max(finalPrice - strikePrice, 0)
: Math.max(strikePrice - finalPrice, 0);
totalPayoff += payoff;
}
const averagePayoff = totalPayoff / numSimulations;
const price = averagePayoff * Math.exp(-riskFreeRate * timeToExpiry);
const intrinsicValue =
optionType === 'call'
? Math.max(spotPrice - strikePrice, 0)
: Math.max(strikePrice - spotPrice, 0);
const timeValue = price - intrinsicValue;
if (optionType === 'call') {
return {
callPrice: price,
putPrice: 0,
intrinsicValueCall: intrinsicValue,
intrinsicValuePut: 0,
timeValueCall: timeValue,
timeValuePut: 0,
};
} else {
return {
callPrice: 0,
putPrice: price,
intrinsicValueCall: 0,
intrinsicValuePut: intrinsicValue,
timeValueCall: 0,
timeValuePut: timeValue,
};
}
}
/**
* Calculate option portfolio risk metrics
*/
export function calculateOptionPortfolioRisk(
positions: Array<{
optionType: 'call' | 'put';
quantity: number;
params: OptionParameters;
}>
): {
totalDelta: number;
totalGamma: number;
totalTheta: number;
totalVega: number;
totalRho: number;
portfolioValue: number;
} {
let totalDelta = 0;
let totalGamma = 0;
let totalTheta = 0;
let totalVega = 0;
let totalRho = 0;
let portfolioValue = 0;
for (const position of positions) {
const greeks = calculateGreeks(position.params, position.optionType);
const pricing = blackScholes(position.params);
const optionPrice = position.optionType === 'call' ? pricing.callPrice : pricing.putPrice;
totalDelta += greeks.delta * position.quantity;
totalGamma += greeks.gamma * position.quantity;
totalTheta += greeks.theta * position.quantity;
totalVega += greeks.vega * position.quantity;
totalRho += greeks.rho * position.quantity;
portfolioValue += optionPrice * position.quantity;
}
return {
totalDelta,
totalGamma,
totalTheta,
totalVega,
totalRho,
portfolioValue,
};
}
/**
* Volatility surface interpolation
*/
export function interpolateVolatilitySurface(
strikes: number[],
expiries: number[],
volatilities: number[][],
targetStrike: number,
targetExpiry: number
): number {
// Simplified bilinear interpolation
// In production, use more sophisticated interpolation methods
// Find surrounding points
let strikeIndex = 0;
let expiryIndex = 0;
for (let i = 0; i < strikes.length - 1; i++) {
if (targetStrike >= strikes[i] && targetStrike <= strikes[i + 1]) {
strikeIndex = i;
break;
}
}
for (let i = 0; i < expiries.length - 1; i++) {
if (targetExpiry >= expiries[i] && targetExpiry <= expiries[i + 1]) {
expiryIndex = i;
break;
}
}
// Bilinear interpolation
const x1 = strikes[strikeIndex];
const x2 = strikes[strikeIndex + 1];
const y1 = expiries[expiryIndex];
const y2 = expiries[expiryIndex + 1];
const q11 = volatilities[expiryIndex][strikeIndex];
const q12 = volatilities[expiryIndex + 1][strikeIndex];
const q21 = volatilities[expiryIndex][strikeIndex + 1];
const q22 = volatilities[expiryIndex + 1][strikeIndex + 1];
const wx = (targetStrike - x1) / (x2 - x1);
const wy = (targetExpiry - y1) / (y2 - y1);
return q11 * (1 - wx) * (1 - wy) + q21 * wx * (1 - wy) + q12 * (1 - wx) * wy + q22 * wx * wy;
}
// Helper functions
/**
* Normal cumulative distribution function
*/
function normalCDF(x: number): number {
return 0.5 * (1 + erf(x / Math.sqrt(2)));
}
/**
* Normal probability density function
*/
function normalPDF(x: number): number {
return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);
}
/**
* Error function approximation
*/
function erf(x: number): number {
// Abramowitz and Stegun approximation
const a1 = 0.254829592;
const a2 = -0.284496736;
const a3 = 1.421413741;
const a4 = -1.453152027;
const a5 = 1.061405429;
const p = 0.3275911;
const sign = x >= 0 ? 1 : -1;
x = Math.abs(x);
const t = 1.0 / (1.0 + p * x);
const y = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x);
return sign * y;
}
/**
* Box-Muller transformation for normal random numbers
*/
function boxMullerTransform(): number {
let u1 = Math.random();
const u2 = Math.random();
// Ensure u1 is not zero
while (u1 === 0) {
u1 = Math.random();
}
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
}
/**
* Prices a straddle option strategy
*/
export function straddle(params: OptionParameters): {
callPrice: number;
putPrice: number;
strategyCost: number;
} {
const callOption = blackScholes(params);
const putOption = blackScholes(params);
const strategyCost = callOption.callPrice + putOption.putPrice;
return {
callPrice: callOption.callPrice,
putPrice: putOption.putPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a strangle option strategy
*/
export function strangle(
callParams: OptionParameters,
putParams: OptionParameters
): { callPrice: number; putPrice: number; strategyCost: number } {
const callOption = blackScholes(callParams);
const putOption = blackScholes(putParams);
const strategyCost = callOption.callPrice + putOption.putPrice;
return {
callPrice: callOption.callPrice,
putPrice: putOption.putPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a butterfly option strategy
*/
export function butterfly(
lowerStrikeParams: OptionParameters,
middleStrikeParams: OptionParameters,
upperStrikeParams: OptionParameters
): {
lowerCallPrice: number;
middleCallPrice: number;
upperCallPrice: number;
strategyCost: number;
} {
const lowerCall = blackScholes(lowerStrikeParams);
const middleCall = blackScholes(middleStrikeParams);
const upperCall = blackScholes(upperStrikeParams);
const strategyCost = lowerCall.callPrice - 2 * middleCall.callPrice + upperCall.callPrice;
return {
lowerCallPrice: lowerCall.callPrice,
middleCallPrice: middleCall.callPrice,
upperCallPrice: upperCall.callPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a condor option strategy
*/
export function condor(
lowerStrikeParams: OptionParameters,
middleLowerStrikeParams: OptionParameters,
middleUpperStrikeParams: OptionParameters,
upperStrikeParams: OptionParameters
): {
lowerCallPrice: number;
middleLowerCallPrice: number;
middleUpperCallPrice: number;
upperCallPrice: number;
strategyCost: number;
} {
const lowerCall = blackScholes(lowerStrikeParams);
const middleLowerCall = blackScholes(middleLowerStrikeParams);
const middleUpperCall = blackScholes(middleUpperStrikeParams);
const upperCall = blackScholes(upperStrikeParams);
const strategyCost =
lowerCall.callPrice -
middleLowerCall.callPrice -
middleUpperCall.callPrice +
upperCall.callPrice;
return {
lowerCallPrice: lowerCall.callPrice,
middleLowerCallPrice: middleLowerCall.callPrice,
middleUpperCallPrice: middleUpperCall.callPrice,
upperCallPrice: upperCall.callPrice,
strategyCost: strategyCost,
};
}
/**
* Calculates combined Greeks for an option strategy
*/
export function calculateStrategyGreeks(
positions: Array<{
optionType: 'call' | 'put';
quantity: number;
params: OptionParameters;
}>
): GreeksCalculation {
let totalDelta = 0;
let totalGamma = 0;
let totalTheta = 0;
let totalVega = 0;
let totalRho = 0;
for (const position of positions) {
const greeks = calculateGreeks(position.params, position.optionType);
totalDelta += greeks.delta * position.quantity;
totalGamma += greeks.gamma * position.quantity;
totalTheta += greeks.theta * position.quantity;
totalVega += greeks.vega * position.quantity;
totalRho += greeks.rho * position.quantity;
}
return {
delta: totalDelta,
gamma: totalGamma,
theta: totalTheta,
vega: totalVega,
rho: totalRho,
};
}
/**
* Black-Scholes option pricing model with greeks
*/
export function blackScholesWithGreeks(
params: OptionParameters,
optionType: 'call' | 'put' = 'call'
): { pricing: OptionPricing; greeks: GreeksCalculation } {
const pricing = blackScholes(params);
const greeks = calculateGreeks(params, optionType);
return { pricing, greeks };
}
/**
* Calculates the breakeven point for a call option at expiration
*/
export function callBreakeven(strikePrice: number, callPrice: number): number {
return strikePrice + callPrice;
}
/**
* Calculates the breakeven point for a put option at expiration
*/
export function putBreakeven(strikePrice: number, putPrice: number): number {
return strikePrice - putPrice;
}
/**
* Estimates the probability of profit for a call option at expiration
*/
export function callProbabilityOfProfit(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
volatility: number
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
return normalCDF(d1);
}
/**
* Estimates the probability of profit for a put option at expiration
*/
export function putProbabilityOfProfit(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
volatility: number
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
return 1 - normalCDF(d1);
}
```

View file

@ -1,604 +0,0 @@
# 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
*/
import { OHLCVData, PriceData } from './index';
export interface PortfolioPosition {
symbol: string;
shares: number;
price: number;
value: number;
weight: number;
}
export interface PortfolioAnalysis {
totalValue: number;
totalReturn: number;
volatility: number;
sharpeRatio: number;
maxDrawdown: number;
var95: number;
beta: number;
alpha: number;
treynorRatio: number;
informationRatio: number;
trackingError: number;
}
export interface AssetAllocation {
symbol: string;
targetWeight: number;
currentWeight: number;
difference: number;
rebalanceAmount: number;
}
export interface PortfolioOptimizationResult {
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
symbols: string[];
}
/**
* Calculate portfolio value and weights
*/
export function calculatePortfolioMetrics(positions: PortfolioPosition[]): {
totalValue: number;
weights: number[];
concentrationRisk: number;
} {
const totalValue = positions.reduce((sum, pos) => sum + pos.value, 0);
const weights = positions.map(pos => pos.value / totalValue);
// Calculate Herfindahl-Hirschman Index for concentration risk
const concentrationRisk = weights.reduce((sum, weight) => sum + weight * weight, 0);
return {
totalValue,
weights,
concentrationRisk,
};
}
/**
* Calculate portfolio returns from position returns
*/
export function calculatePortfolioReturns(assetReturns: number[][], weights: number[]): number[] {
if (assetReturns.length === 0 || weights.length !== assetReturns[0].length) {
return [];
}
const portfolioReturns: number[] = [];
for (let i = 0; i < assetReturns.length; i++) {
let portfolioReturn = 0;
for (let j = 0; j < weights.length; j++) {
portfolioReturn += weights[j] * assetReturns[i][j];
}
portfolioReturns.push(portfolioReturn);
}
return portfolioReturns;
}
/**
* Mean-Variance Optimization (Markowitz)
*/
export function markowitzOptimization(
expectedReturns: number[],
covarianceMatrix: number[][],
riskFreeRate: number = 0.02,
riskAversion: number = 1
): PortfolioOptimizationResult {
const n = expectedReturns.length;
// Simplified optimization using equal weights as baseline
// In production, use proper quadratic programming solver
const weights = new Array(n).fill(1 / n);
const expectedReturn = weights.reduce((sum, weight, i) => sum + weight * expectedReturns[i], 0);
// Calculate portfolio variance
let portfolioVariance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
const volatility = Math.sqrt(portfolioVariance);
const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0;
return {
weights,
expectedReturn,
volatility,
sharpeRatio,
symbols: [], // Would be filled with actual symbols
};
}
/**
* Black-Litterman Model
*/
export function blackLittermanOptimization(
marketCaps: number[],
covarianceMatrix: number[][],
views: Array<{ assets: number[]; expectedReturn: number; confidence: number }>,
riskAversion: number = 3,
riskFreeRate: number = 0.02
): PortfolioOptimizationResult {
const n = marketCaps.length;
// Calculate market weights
const totalMarketCap = marketCaps.reduce((sum, cap) => sum + cap, 0);
const marketWeights = marketCaps.map(cap => cap / totalMarketCap);
// Implied equilibrium returns
const equilibriumReturns: number[] = [];
for (let i = 0; i < n; i++) {
let equilibriumReturn = 0;
for (let j = 0; j < n; j++) {
equilibriumReturn += riskAversion * covarianceMatrix[i][j] * marketWeights[j];
}
equilibriumReturns.push(equilibriumReturn);
}
// Simplified BL implementation - in production use proper matrix operations
const weights = [...marketWeights]; // Start with market weights
const expectedReturn = weights.reduce(
(sum, weight, i) => sum + weight * equilibriumReturns[i],
0
);
let portfolioVariance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
const volatility = Math.sqrt(portfolioVariance);
const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0;
return {
weights,
expectedReturn,
volatility,
sharpeRatio,
symbols: [],
};
}
/**
* Risk Parity Portfolio
*/
export function riskParityOptimization(covarianceMatrix: number[][]): PortfolioOptimizationResult {
const n = covarianceMatrix.length;
// Start with equal weights
let weights = new Array(n).fill(1 / n);
// Iterative optimization for equal risk contribution
const maxIterations = 100;
const tolerance = 1e-8;
for (let iter = 0; iter < maxIterations; iter++) {
const riskContributions = calculateRiskContributions(weights, covarianceMatrix);
const totalRisk = Math.sqrt(calculatePortfolioVariance(weights, covarianceMatrix));
const targetRiskContribution = totalRisk / n;
let converged = true;
const newWeights = [...weights];
for (let i = 0; i < n; i++) {
const diff = riskContributions[i] - targetRiskContribution;
if (Math.abs(diff) > tolerance) {
converged = false;
// Simple adjustment - in production use proper optimization
newWeights[i] *= 1 - (diff / totalRisk) * 0.1;
}
}
// Normalize weights
const sum = newWeights.reduce((s, w) => s + w, 0);
weights = newWeights.map(w => w / sum);
if (converged) {
break;
}
}
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const volatility = Math.sqrt(portfolioVariance);
return {
weights,
expectedReturn: 0, // Not calculated for risk parity
volatility,
sharpeRatio: 0,
symbols: [],
};
}
/**
* Calculate risk contributions for each asset
*/
export function calculateRiskContributions(
weights: number[],
covarianceMatrix: number[][]
): number[] {
const n = weights.length;
const riskContributions: number[] = [];
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
for (let i = 0; i < n; i++) {
let marginalContribution = 0;
for (let j = 0; j < n; j++) {
marginalContribution += weights[j] * covarianceMatrix[i][j];
}
const riskContribution = (weights[i] * marginalContribution) / portfolioVolatility;
riskContributions.push(riskContribution);
}
return riskContributions;
}
/**
* Calculate portfolio variance
*/
export function calculatePortfolioVariance(
weights: number[],
covarianceMatrix: number[][]
): number {
const n = weights.length;
let variance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
variance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
return variance;
}
/**
* Portfolio rebalancing analysis
*/
export function calculateRebalancing(
currentPositions: PortfolioPosition[],
targetWeights: number[],
totalValue: number
): AssetAllocation[] {
if (currentPositions.length !== targetWeights.length) {
throw new Error('Number of positions must match number of target weights');
}
return currentPositions.map((position, index) => {
const currentWeight = position.value / totalValue;
const targetWeight = targetWeights[index];
const difference = targetWeight - currentWeight;
const rebalanceAmount = difference * totalValue;
return {
symbol: position.symbol,
targetWeight,
currentWeight,
difference,
rebalanceAmount,
};
});
}
/**
* Factor model analysis (Fama-French)
*/
export function famaFrenchAnalysis(
portfolioReturns: number[],
marketReturns: number[],
smbReturns: number[], // Small minus Big
hmlReturns: number[], // High minus Low
riskFreeRate: number = 0.02
): {
alpha: number;
marketBeta: number;
sizeBeta: number;
valueBeta: number;
rSquared: number;
} {
const n = portfolioReturns.length;
// Excess returns
const excessPortfolioReturns = portfolioReturns.map(r => r - riskFreeRate);
const excessMarketReturns = marketReturns.map(r => r - riskFreeRate);
// Simple linear regression (in production, use proper multiple regression)
const meanExcessPortfolio = excessPortfolioReturns.reduce((sum, r) => sum + r, 0) / n;
const meanExcessMarket = excessMarketReturns.reduce((sum, r) => sum + r, 0) / n;
const meanSMB = smbReturns.reduce((sum, r) => sum + r, 0) / n;
const meanHML = hmlReturns.reduce((sum, r) => sum + r, 0) / n;
// Calculate market beta
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < n; i++) {
const portfolioDiff = excessPortfolioReturns[i] - meanExcessPortfolio;
const marketDiff = excessMarketReturns[i] - meanExcessMarket;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
const marketBeta = marketVariance > 0 ? covariance / marketVariance : 0;
const alpha = meanExcessPortfolio - marketBeta * meanExcessMarket;
return {
alpha,
marketBeta,
sizeBeta: 0, // Simplified - would need proper regression
valueBeta: 0, // Simplified - would need proper regression
rSquared: 0, // Simplified - would need proper regression
};
}
/**
* Portfolio performance attribution
*/
export function performanceAttribution(
portfolioReturns: number[],
benchmarkReturns: number[],
sectorWeights: number[][],
sectorReturns: number[][]
): {
totalActiveReturn: number;
allocationEffect: number;
selectionEffect: number;
interactionEffect: number;
} {
const n = portfolioReturns.length;
const portfolioReturn = portfolioReturns.reduce((sum, r) => sum + r, 0) / n;
const benchmarkReturn = benchmarkReturns.reduce((sum, r) => sum + r, 0) / n;
const totalActiveReturn = portfolioReturn - benchmarkReturn;
// Simplified attribution analysis
let allocationEffect = 0;
let selectionEffect = 0;
let interactionEffect = 0;
// This would require proper implementation with sector-level analysis
// For now, return the total active return distributed equally
allocationEffect = totalActiveReturn * 0.4;
selectionEffect = totalActiveReturn * 0.4;
interactionEffect = totalActiveReturn * 0.2;
return {
totalActiveReturn,
allocationEffect,
selectionEffect,
interactionEffect,
};
}
/**
* Calculate Efficient Frontier points
*/
export function calculateEfficientFrontier(
returns: number[][], // Array of return series for each asset
symbols: string[],
riskFreeRate: number = 0.02,
numPoints: number = 50
): Array<{
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
}> {
if (returns.length !== symbols.length || returns.length < 2) {
return [];
}
const n = returns.length;
const results: Array<{
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
}> = [];
// Calculate expected returns and covariance matrix
const expectedReturns = returns.map(
assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length
);
const covarianceMatrix = calculateCovarianceMatrix(returns);
// Generate target returns from min to max expected return
const minReturn = Math.min(...expectedReturns);
const maxReturn = Math.max(...expectedReturns);
const returnStep = (maxReturn - minReturn) / (numPoints - 1);
for (let i = 0; i < numPoints; i++) {
const targetReturn = minReturn + i * returnStep;
// Find minimum variance portfolio for target return using quadratic programming (simplified)
const weights = findMinimumVarianceWeights(expectedReturns, covarianceMatrix, targetReturn);
if (weights && weights.length === n) {
const portfolioReturn = weights.reduce((sum, w, j) => sum + w * expectedReturns[j], 0);
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
const sharpeRatio =
portfolioVolatility > 0 ? (portfolioReturn - riskFreeRate) / portfolioVolatility : 0;
results.push({
weights,
expectedReturn: portfolioReturn,
volatility: portfolioVolatility,
sharpeRatio,
});
}
}
return results.sort((a, b) => a.volatility - b.volatility);
}
/**
* Find Minimum Variance Portfolio
*/
export function findMinimumVariancePortfolio(
returns: number[][],
symbols: string[]
): PortfolioOptimizationResult | null {
if (returns.length !== symbols.length || returns.length < 2) {
return null;
}
const covarianceMatrix = calculateCovarianceMatrix(returns);
const n = returns.length;
// For minimum variance portfolio: w = (Σ^-1 * 1) / (1' * Σ^-1 * 1)
// Simplified implementation using equal weights as starting point
const weights = new Array(n).fill(1 / n);
// Iterative optimization (simplified)
for (let iter = 0; iter < 100; iter++) {
const gradient = calculateVarianceGradient(weights, covarianceMatrix);
const stepSize = 0.01;
// Update weights
for (let i = 0; i < n; i++) {
weights[i] -= stepSize * gradient[i];
}
// Normalize weights to sum to 1
const weightSum = weights.reduce((sum, w) => sum + w, 0);
for (let i = 0; i < n; i++) {
weights[i] = Math.max(0, weights[i] / weightSum);
}
}
const expectedReturns = returns.map(
assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length
);
const portfolioReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0);
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
const sharpeRatio = portfolioVolatility > 0 ? portfolioReturn / portfolioVolatility : 0;
return {
weights,
expectedReturn: portfolioReturn,
volatility: portfolioVolatility,
sharpeRatio,
symbols,
};
}
// Helper functions for portfolio optimization
function calculateCovarianceMatrix(returns: number[][]): number[][] {
const n = returns.length;
const matrix: number[][] = [];
for (let i = 0; i < n; i++) {
matrix[i] = [];
for (let j = 0; j < n; j++) {
matrix[i][j] = calculateCovariance(returns[i], returns[j]);
}
}
return matrix;
}
function calculateCovariance(x: number[], y: number[]): number {
if (x.length !== y.length || x.length < 2) {
return 0;
}
const n = x.length;
const meanX = x.reduce((sum, val) => sum + val, 0) / n;
const meanY = y.reduce((sum, val) => sum + val, 0) / n;
return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1);
}
// calculatePortfolioVariance is already exported above
function calculateVarianceGradient(weights: number[], covarianceMatrix: number[][]): number[] {
const n = weights.length;
const gradient: number[] = [];
for (let i = 0; i < n; i++) {
let grad = 0;
for (let j = 0; j < n; j++) {
grad += 2 * weights[j] * covarianceMatrix[i][j];
}
gradient[i] = grad;
}
return gradient;
}
function findMinimumVarianceWeights(
expectedReturns: number[],
covarianceMatrix: number[][],
targetReturn: number
): number[] | null {
const n = expectedReturns.length;
// Simplified implementation - in practice would use quadratic programming solver
// Start with equal weights and adjust
const weights = new Array(n).fill(1 / n);
// Iterative adjustment to meet target return constraint
for (let iter = 0; iter < 50; iter++) {
const currentReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0);
const returnDiff = targetReturn - currentReturn;
if (Math.abs(returnDiff) < 0.001) {
break;
}
// Adjust weights proportionally to expected returns
const totalExpectedReturn = expectedReturns.reduce((sum, r) => sum + Math.abs(r), 0);
for (let i = 0; i < n; i++) {
const adjustment = (returnDiff * Math.abs(expectedReturns[i])) / totalExpectedReturn;
weights[i] = Math.max(0, weights[i] + adjustment * 0.1);
}
// Normalize weights
const weightSum = weights.reduce((sum, w) => sum + w, 0);
if (weightSum > 0) {
for (let i = 0; i < n; i++) {
weights[i] /= weightSum;
}
}
}
return weights;
}
```

View file

@ -1,109 +0,0 @@
# 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!

View file

@ -1,593 +0,0 @@
# 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
*/
export interface PositionSizeParams {
accountSize: number;
riskPercentage: number;
entryPrice: number;
stopLoss: number;
leverage?: number;
}
export interface KellyParams {
winRate: number;
averageWin: number;
averageLoss: number;
}
export interface VolatilityParams {
price: number;
volatility: number;
targetVolatility: number;
lookbackDays: number;
}
/**
* Calculate position size based on fixed risk percentage
*/
export function fixedRiskPositionSize(params: PositionSizeParams): number {
const { accountSize, riskPercentage, entryPrice, stopLoss, leverage = 1 } = params;
// Input validation
if (accountSize <= 0 || riskPercentage <= 0 || entryPrice <= 0 || leverage <= 0) {
return 0;
}
if (entryPrice === stopLoss) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const riskPerShare = Math.abs(entryPrice - stopLoss);
const basePositionSize = riskAmount / riskPerShare;
return Math.floor(basePositionSize * leverage);
}
/**
* Calculate position size using Kelly Criterion
*/
export function kellyPositionSize(params: KellyParams, accountSize: number): number {
const { winRate, averageWin, averageLoss } = params;
// Validate inputs
if (averageLoss === 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0) {
return 0;
}
const lossRate = 1 - winRate;
const winLossRatio = averageWin / Math.abs(averageLoss);
// Correct Kelly formula: f = (bp - q) / b
// where: b = win/loss ratio, p = win rate, q = loss rate
const kellyFraction = (winRate * winLossRatio - lossRate) / winLossRatio;
// Cap Kelly fraction to prevent over-leveraging (max 25% of Kelly recommendation)
const cappedKelly = Math.max(0, Math.min(kellyFraction * 0.25, 0.25));
return accountSize * cappedKelly;
}
/**
* Calculate fractional Kelly position size (more conservative)
*/
export function fractionalKellyPositionSize(
params: KellyParams,
accountSize: number,
fraction: number = 0.25
): number {
// Input validation
if (fraction <= 0 || fraction > 1) {
return 0;
}
const fullKelly = kellyPositionSize(params, accountSize);
return fullKelly * fraction;
}
/**
* Calculate position size based on volatility targeting
*/
export function volatilityTargetPositionSize(
params: VolatilityParams,
accountSize: number
): number {
const { price, volatility, targetVolatility } = params;
// Input validation
if (volatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) {
return 0;
}
const volatilityRatio = targetVolatility / volatility;
const basePositionValue = accountSize * Math.min(volatilityRatio, 2); // Cap at 2x leverage
return Math.floor(basePositionValue / price);
}
/**
* Calculate equal weight position size
*/
export function equalWeightPositionSize(
accountSize: number,
numberOfPositions: number,
price: number
): number {
// Input validation
if (numberOfPositions <= 0 || price <= 0 || accountSize <= 0) {
return 0;
}
const positionValue = accountSize / numberOfPositions;
return Math.floor(positionValue / price);
}
/**
* Calculate position size based on Average True Range (ATR)
*/
export function atrBasedPositionSize(
accountSize: number,
riskPercentage: number,
atrValue: number,
atrMultiplier: number = 2,
price: number
): number {
if (atrValue === 0 || price === 0) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const stopDistance = atrValue * atrMultiplier;
const positionSize = riskAmount / stopDistance;
// Return position size in shares, not dollars
return Math.floor(positionSize);
}
/**
* Calculate position size using Van Tharp's expectancy
*/
export function expectancyPositionSize(
accountSize: number,
winRate: number,
averageWin: number,
averageLoss: number,
maxRiskPercentage: number = 2
): number {
// Input validation
if (accountSize <= 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0 || averageLoss === 0) {
return 0;
}
const expectancy = winRate * averageWin - (1 - winRate) * Math.abs(averageLoss);
if (expectancy <= 0) {
return 0;
}
// Scale position size based on expectancy relative to average loss
// Higher expectancy relative to risk allows for larger position
const expectancyRatio = expectancy / Math.abs(averageLoss);
const riskPercentage = Math.min(expectancyRatio * 0.5, maxRiskPercentage);
const positionValue = accountSize * (riskPercentage / 100);
return positionValue;
}
/**
* Calculate optimal position size using Monte Carlo simulation
*/
export function monteCarloPositionSize(
accountSize: number,
historicalReturns: number[],
simulations: number = 1000,
confidenceLevel: number = 0.95
): number {
if (historicalReturns.length === 0) {
return 0;
}
const outcomes: number[] = [];
const mean = historicalReturns.reduce((sum, ret) => sum + ret, 0) / historicalReturns.length;
const variance =
historicalReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) /
historicalReturns.length;
const stdDev = Math.sqrt(variance);
// Test different position sizes (as fraction of account)
const testFractions = [0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25];
let optimalFraction = 0;
let bestSharpe = -Infinity;
for (const fraction of testFractions) {
const simOutcomes: number[] = [];
for (let i = 0; i < simulations; i++) {
let portfolioValue = accountSize;
// Simulate trades over a period
for (let j = 0; j < 50; j++) {
// 50 trades
const randomReturn =
historicalReturns[Math.floor(Math.random() * historicalReturns.length)];
const positionReturn = randomReturn * fraction;
portfolioValue = portfolioValue * (1 + positionReturn);
}
simOutcomes.push(portfolioValue);
}
// Calculate Sharpe ratio for this fraction
const avgOutcome = simOutcomes.reduce((sum, val) => sum + val, 0) / simOutcomes.length;
const returns = simOutcomes.map(val => (val - accountSize) / accountSize);
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const returnStdDev = Math.sqrt(
returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / returns.length
);
const sharpe = returnStdDev > 0 ? avgReturn / returnStdDev : -Infinity;
if (sharpe > bestSharpe) {
bestSharpe = sharpe;
optimalFraction = fraction;
}
}
return accountSize * optimalFraction;
}
/**
* Calculate position size based on Sharpe ratio optimization
*/
export function sharpeOptimizedPositionSize(
accountSize: number,
expectedReturn: number,
volatility: number,
riskFreeRate: number = 0.02,
maxLeverage: number = 3
): number {
// Input validation
if (volatility <= 0 || accountSize <= 0 || expectedReturn <= riskFreeRate || maxLeverage <= 0) {
return 0;
}
// Kelly criterion with Sharpe ratio optimization
const excessReturn = expectedReturn - riskFreeRate;
const kellyFraction = excessReturn / (volatility * volatility);
// Apply maximum leverage constraint
const constrainedFraction = Math.max(0, Math.min(kellyFraction, maxLeverage));
return accountSize * constrainedFraction;
}
/**
* Fixed fractional position sizing
*/
export function fixedFractionalPositionSize(
accountSize: number,
riskPercentage: number,
stopLossPercentage: number,
price: number
): number {
// Input validation
if (stopLossPercentage <= 0 || price <= 0 || riskPercentage <= 0 || accountSize <= 0) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const stopLossAmount = price * (stopLossPercentage / 100);
return Math.floor(riskAmount / stopLossAmount);
}
/**
* Volatility-adjusted position sizing
*/
export function volatilityAdjustedPositionSize(
accountSize: number,
targetVolatility: number,
assetVolatility: number,
price: number
): number {
// Input validation
if (assetVolatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) {
return 0;
}
const volatilityRatio = targetVolatility / assetVolatility;
const cappedRatio = Math.min(volatilityRatio, 3); // Cap at 3x leverage
const positionValue = accountSize * cappedRatio;
return Math.floor(positionValue / price);
}
/**
* Calculate position size with correlation adjustment
*/
export function correlationAdjustedPositionSize(
basePositionSize: number,
existingPositions: Array<{ size: number; correlation: number }>,
maxCorrelationRisk: number = 0.3
): number {
if (existingPositions.length === 0 || basePositionSize <= 0) {
return basePositionSize;
}
// Calculate portfolio correlation risk
// This should consider the correlation between the new position and existing ones
const totalCorrelationRisk = existingPositions.reduce((total, position) => {
// Weight correlation by position size relative to new position
const relativeSize = position.size / (basePositionSize + position.size);
return total + relativeSize * Math.abs(position.correlation);
}, 0);
// Adjust position size based on correlation risk
const correlationAdjustment = Math.max(0.1, 1 - totalCorrelationRisk / maxCorrelationRisk);
return Math.floor(basePositionSize * correlationAdjustment);
}
/**
* Calculate portfolio heat (total risk across all positions)
*/
export function calculatePortfolioHeat(
positions: Array<{ value: number; risk: number }>,
accountSize: number
): number {
// Input validation
if (accountSize <= 0 || positions.length === 0) {
return 0;
}
const totalRisk = positions.reduce((sum, position) => {
// Ensure risk values are positive
return sum + Math.max(0, position.risk);
}, 0);
return Math.min((totalRisk / accountSize) * 100, 100); // Cap at 100%
}
/**
* Dynamic position sizing based on market conditions
*/
export function dynamicPositionSize(
basePositionSize: number,
marketVolatility: number,
normalVolatility: number,
drawdownLevel: number,
maxDrawdownThreshold: number = 0.1
): number {
// Input validation
if (basePositionSize <= 0 || marketVolatility <= 0 || normalVolatility <= 0) {
return 0;
}
if (drawdownLevel < 0 || maxDrawdownThreshold <= 0) {
return basePositionSize;
}
// Volatility adjustment - reduce size when volatility is high
const volatilityAdjustment = Math.min(normalVolatility / marketVolatility, 2); // Cap at 2x
// Drawdown adjustment - reduce size as drawdown increases
const normalizedDrawdown = Math.min(drawdownLevel / maxDrawdownThreshold, 1);
const drawdownAdjustment = Math.max(0.1, 1 - normalizedDrawdown);
const adjustedSize = basePositionSize * volatilityAdjustment * drawdownAdjustment;
return Math.floor(Math.max(0, adjustedSize));
}
/**
* Calculate maximum position size based on liquidity
*/
export function liquidityConstrainedPositionSize(
desiredPositionSize: number,
averageDailyVolume: number,
maxVolumePercentage: number = 0.05,
price: number
): number {
if (averageDailyVolume === 0 || price === 0) {
return 0;
}
const maxShares = averageDailyVolume * maxVolumePercentage;
return Math.min(desiredPositionSize, maxShares);
}
/**
* Multi-timeframe position sizing
*/
export function multiTimeframePositionSize(
accountSize: number,
shortTermSignal: number, // -1 to 1
mediumTermSignal: number, // -1 to 1
longTermSignal: number, // -1 to 1
baseRiskPercentage: number = 1
): number {
// Input validation
if (accountSize <= 0 || baseRiskPercentage <= 0) {
return 0;
}
// Clamp signals to valid range
const clampedShort = Math.max(-1, Math.min(1, shortTermSignal));
const clampedMedium = Math.max(-1, Math.min(1, mediumTermSignal));
const clampedLong = Math.max(-1, Math.min(1, longTermSignal));
// Weight the signals (long-term gets higher weight)
const weightedSignal = clampedShort * 0.2 + clampedMedium * 0.3 + clampedLong * 0.5;
// Adjust risk based on signal strength
const adjustedRisk = baseRiskPercentage * Math.abs(weightedSignal);
return accountSize * (adjustedRisk / 100);
}
/**
* Risk parity position sizing
*/
export function riskParityPositionSize(
assets: Array<{ volatility: number; price: number }>,
targetRisk: number,
accountSize: number
): number[] {
if (assets.length === 0) {
return [];
}
// Calculate inverse volatility weights
const totalInverseVol = assets.reduce((sum, asset) => {
if (asset.volatility === 0) {
return sum;
}
return sum + 1 / asset.volatility;
}, 0);
if (totalInverseVol === 0) {
return assets.map(() => 0);
}
return assets.map(asset => {
if (asset.volatility === 0 || asset.price === 0) {
return 0;
}
// Calculate weight based on inverse volatility
const weight = 1 / asset.volatility / totalInverseVol;
// The weight itself already accounts for risk parity
// We just need to scale by target risk once
const positionValue = accountSize * weight * targetRisk;
return Math.floor(positionValue / asset.price);
});
}
/**
* Validate position size against risk limits
*/
export function validatePositionSize(
positionSize: number,
price: number,
accountSize: number,
maxPositionPercentage: number = 10,
maxLeverage: number = 1
): { isValid: boolean; adjustedSize: number; violations: string[] } {
const violations: string[] = [];
let adjustedSize = positionSize;
// Check maximum position percentage
const positionValue = positionSize * price;
const positionPercentage = (positionValue / accountSize) * 100;
if (positionPercentage > maxPositionPercentage) {
violations.push(`Position exceeds maximum ${maxPositionPercentage}% of account`);
adjustedSize = (accountSize * maxPositionPercentage) / 100 / price;
}
// Check leverage limits
const leverage = positionValue / accountSize;
if (leverage > maxLeverage) {
violations.push(`Position exceeds maximum leverage of ${maxLeverage}x`);
adjustedSize = Math.min(adjustedSize, (accountSize * maxLeverage) / price);
}
// Check minimum position size
if (adjustedSize < 1 && adjustedSize > 0) {
violations.push('Position size too small (less than 1 share)');
adjustedSize = 0;
}
return {
isValid: violations.length === 0,
adjustedSize: Math.max(0, adjustedSize),
violations,
};
}
/**
* Optimal F position sizing (Ralph Vince's method)
*/
export function optimalFPositionSize(
accountSize: number,
historicalReturns: number[],
maxIterations: number = 100
): number {
if (historicalReturns.length === 0 || accountSize <= 0) {
return 0;
}
// Convert returns to P&L per unit
const pnlValues = historicalReturns.map(ret => ret * 1000); // Assuming $1000 per unit
let bestF = 0;
let bestTWR = 0; // Terminal Wealth Relative
// Test different f values (0.01 to 1.00)
for (let f = 0.01; f <= 1.0; f += 0.01) {
let twr = 1.0;
let valid = true;
for (const pnl of pnlValues) {
const hpr = 1 + (f * pnl) / 1000; // Holding Period Return
if (hpr <= 0) {
valid = false;
break;
}
twr *= hpr;
}
if (valid && twr > bestTWR) {
bestTWR = twr;
bestF = f;
}
}
// Apply safety factor
const safeF = bestF * 0.75; // 75% of optimal f for safety
return accountSize * safeF;
}
/**
* Secure F position sizing (safer version of Optimal F)
*/
export function secureFPositionSize(
accountSize: number,
historicalReturns: number[],
confidenceLevel: number = 0.95
): number {
if (historicalReturns.length === 0 || accountSize <= 0) {
return 0;
}
// Sort returns to find worst-case scenarios
const sortedReturns = [...historicalReturns].sort((a, b) => a - b);
const worstCaseIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length);
const worstCaseReturn = sortedReturns[worstCaseIndex];
// Calculate maximum position size that won't bankrupt at confidence level
const maxLoss = Math.abs(worstCaseReturn);
const maxRiskPercentage = 0.02; // Never risk more than 2% on worst case
if (maxLoss === 0) {
return accountSize * 0.1;
} // Default to 10% if no historical losses
const secureF = Math.min(maxRiskPercentage / maxLoss, 0.25); // Cap at 25%
return accountSize * secureF;
}
```

File diff suppressed because it is too large Load diff

View file

@ -1,633 +0,0 @@
# 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
*/
// Local interface definition to avoid circular dependency
interface OHLCVData {
open: number;
high: number;
low: number;
close: number;
volume: number;
timestamp: Date;
}
export interface GARCHParameters {
omega: number; // Constant term
alpha: number; // ARCH parameter
beta: number; // GARCH parameter
logLikelihood: number;
aic: number;
bic: number;
}
export interface VolatilityEstimates {
closeToClose: number;
parkinson: number;
garmanKlass: number;
rogersSatchell: number;
yangZhang: number;
}
export interface VolatilityRegime {
regime: number;
startDate: Date;
endDate: Date;
averageVolatility: number;
observations: number;
}
export interface VolatilityTerm {
maturity: number; // Days to maturity
impliedVolatility: number;
confidence: number;
}
export interface HestonParameters {
kappa: number; // Mean reversion speed
theta: number; // Long-term variance
sigma: number; // Volatility of variance
rho: number; // Correlation
v0: number; // Initial variance
logLikelihood: number;
}
/**
* Calculate realized volatility using different estimators
*/
export function calculateRealizedVolatility(
ohlcv: OHLCVData[],
annualizationFactor: number = 252
): VolatilityEstimates {
if (ohlcv.length < 2) {
throw new Error('Need at least 2 observations for volatility calculation');
}
const n = ohlcv.length;
let closeToCloseSum = 0;
let parkinsonSum = 0;
let garmanKlassSum = 0;
let rogersSatchellSum = 0;
let yangZhangSum = 0;
// Calculate log returns and volatility estimators
for (let i = 1; i < n; i++) {
const prev = ohlcv[i - 1];
const curr = ohlcv[i];
// Close-to-close
const logReturn = Math.log(curr.close / prev.close);
closeToCloseSum += logReturn * logReturn;
// Parkinson estimator
const logHighLow = Math.log(curr.high / curr.low);
parkinsonSum += logHighLow * logHighLow;
// Garman-Klass estimator
const logOpenClose = Math.log(curr.close / curr.open);
garmanKlassSum +=
0.5 * logHighLow * logHighLow - (2 * Math.log(2) - 1) * logOpenClose * logOpenClose;
// Rogers-Satchell estimator
const logHighOpen = Math.log(curr.high / curr.open);
const logHighClose = Math.log(curr.high / curr.close);
const logLowOpen = Math.log(curr.low / curr.open);
const logLowClose = Math.log(curr.low / curr.close);
rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose;
// Yang-Zhang estimator components
const overnight = Math.log(curr.open / prev.close);
yangZhangSum += overnight * overnight + rogersSatchellSum / i; // Simplified for brevity
}
return {
closeToClose: Math.sqrt((closeToCloseSum / (n - 1)) * annualizationFactor),
parkinson: Math.sqrt((parkinsonSum / (n - 1) / (4 * Math.log(2))) * annualizationFactor),
garmanKlass: Math.sqrt((garmanKlassSum / (n - 1)) * annualizationFactor),
rogersSatchell: Math.sqrt((rogersSatchellSum / (n - 1)) * annualizationFactor),
yangZhang: Math.sqrt((yangZhangSum / (n - 1)) * annualizationFactor),
};
}
/**
* Estimate GARCH(1,1) model parameters
*/
export function estimateGARCH(
returns: number[],
maxIterations: number = 100,
tolerance: number = 1e-6
): GARCHParameters {
const n = returns.length;
// Initial parameter estimates
let omega = 0.01;
let alpha = 0.05;
let beta = 0.9;
// Calculate unconditional variance
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
const unconditionalVar =
returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
let logLikelihood = -Infinity;
for (let iter = 0; iter < maxIterations; iter++) {
const variances: number[] = [unconditionalVar];
let newLogLikelihood = 0;
// Calculate conditional variances
for (let t = 1; t < n; t++) {
const prevVar = variances[t - 1];
const prevReturn = returns[t - 1] - meanReturn;
const currentVar = omega + alpha * prevReturn * prevReturn + beta * prevVar;
variances.push(Math.max(currentVar, 1e-8)); // Ensure positive variance
// Add to log-likelihood
const currentReturn = returns[t] - meanReturn;
newLogLikelihood -=
0.5 *
(Math.log(2 * Math.PI) +
Math.log(currentVar) +
(currentReturn * currentReturn) / currentVar);
}
// Check for convergence
if (Math.abs(newLogLikelihood - logLikelihood) < tolerance) {
break;
}
logLikelihood = newLogLikelihood;
// Simple gradient update (in practice, use more sophisticated optimization)
const gradientStep = 0.001;
omega = Math.max(0.001, omega + gradientStep);
alpha = Math.max(0.001, Math.min(0.999, alpha + gradientStep));
beta = Math.max(0.001, Math.min(0.999 - alpha, beta + gradientStep));
}
// Calculate information criteria
const k = 3; // Number of parameters
const aic = -2 * logLikelihood + 2 * k;
const bic = -2 * logLikelihood + k * Math.log(n);
return {
omega,
alpha,
beta,
logLikelihood,
aic,
bic,
};
}
/**
* Calculate EWMA volatility
*/
export function calculateEWMAVolatility(
returns: number[],
lambda: number = 0.94,
annualizationFactor: number = 252
): number[] {
const n = returns.length;
const volatilities: number[] = [];
// Initialize with sample variance
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
let variance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
for (let t = 0; t < n; t++) {
if (t > 0) {
const prevReturn = returns[t - 1] - meanReturn;
variance = lambda * variance + (1 - lambda) * prevReturn * prevReturn;
}
volatilities.push(Math.sqrt(variance * annualizationFactor));
}
return volatilities;
}
/**
* Identify volatility regimes
*/
export function identifyVolatilityRegimes(
returns: number[],
numRegimes: number = 3,
windowSize: number = 60
): VolatilityRegime[] {
// Calculate rolling volatility
const rollingVol: number[] = [];
const timestamps: Date[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
const mean = window.reduce((sum, r) => sum + r, 0) / window.length;
const variance =
window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1);
rollingVol.push(Math.sqrt(variance * 252)); // Annualized
timestamps.push(new Date(Date.now() + i * 24 * 60 * 60 * 1000)); // Mock timestamps
}
// Simple k-means clustering on absolute returns
const absReturns = returns.map(ret => Math.abs(ret));
const sortedReturns = [...absReturns].sort((a, b) => a - b);
// Define regime thresholds
const thresholds: number[] = [];
for (let i = 1; i < numRegimes; i++) {
const index = Math.floor((i / numRegimes) * sortedReturns.length);
thresholds.push(sortedReturns[index]);
}
// Classify returns into regimes
const regimeSequence = absReturns.map(absRet => {
for (let i = 0; i < thresholds.length; i++) {
if (absRet <= thresholds[i]) {
return i;
}
}
return numRegimes - 1;
});
// Calculate regime statistics
const regimes: VolatilityRegime[] = [];
for (let regime = 0; regime < numRegimes; regime++) {
const regimeIndices = regimeSequence
.map((r, idx) => (r === regime ? idx : -1))
.filter(idx => idx !== -1);
if (regimeIndices.length > 0) {
const regimeVolatilities = regimeIndices.map(idx =>
idx < rollingVol.length ? rollingVol[idx] : 0
);
const avgVol =
regimeVolatilities.reduce((sum, vol) => sum + vol, 0) / regimeVolatilities.length;
regimes.push({
regime,
startDate: new Date(Date.now()),
endDate: new Date(Date.now() + regimeIndices.length * 24 * 60 * 60 * 1000),
averageVolatility: avgVol,
observations: regimeIndices.length,
});
}
}
return regimes;
}
/**
* Calculate volatility term structure
*/
export function calculateVolatilityTermStructure(
spotVol: number,
maturities: number[],
meanReversion: number = 0.5
): VolatilityTerm[] {
return maturities.map(maturity => {
// Simple mean reversion model for term structure
const timeToMaturity = maturity / 365; // Convert to years
const termVolatility = spotVol * Math.exp(-meanReversion * timeToMaturity);
return {
maturity,
impliedVolatility: Math.max(termVolatility, 0.01), // Floor at 1%
confidence: Math.exp(-timeToMaturity), // Confidence decreases with maturity
};
});
}
/**
* Calculate volatility smile/skew parameters
*/
export function calculateVolatilitySmile(
strikes: number[],
spotPrice: number,
impliedVols: number[]
): {
atmVolatility: number;
skew: number;
convexity: number;
riskReversal: number;
} {
if (strikes.length !== impliedVols.length || strikes.length < 3) {
throw new Error('Need at least 3 strikes with corresponding implied volatilities');
}
// Find ATM volatility
const atmIndex = strikes.reduce(
(closest, strike, idx) =>
Math.abs(strike - spotPrice) < Math.abs(strikes[closest] - spotPrice) ? idx : closest,
0
);
const atmVolatility = impliedVols[atmIndex];
// Calculate skew (derivative at ATM)
let skew = 0;
if (atmIndex > 0 && atmIndex < strikes.length - 1) {
const deltaStrike = strikes[atmIndex + 1] - strikes[atmIndex - 1];
const deltaVol = impliedVols[atmIndex + 1] - impliedVols[atmIndex - 1];
skew = deltaVol / deltaStrike;
}
// Calculate convexity (second derivative)
let convexity = 0;
if (atmIndex > 0 && atmIndex < strikes.length - 1) {
const h = strikes[atmIndex + 1] - strikes[atmIndex];
convexity =
(impliedVols[atmIndex + 1] - 2 * impliedVols[atmIndex] + impliedVols[atmIndex - 1]) / (h * h);
}
// Risk reversal (put-call vol difference)
const otmPutIndex = strikes.findIndex(strike => strike < spotPrice * 0.9);
const otmCallIndex = strikes.findIndex(strike => strike > spotPrice * 1.1);
let riskReversal = 0;
if (otmPutIndex !== -1 && otmCallIndex !== -1) {
riskReversal = impliedVols[otmCallIndex] - impliedVols[otmPutIndex];
}
return {
atmVolatility,
skew,
convexity,
riskReversal,
};
}
/**
* Estimate Heston stochastic volatility model parameters
*/
export function estimateHestonParameters(
returns: number[],
maxIterations: number = 100
): HestonParameters {
const n = returns.length;
if (n < 10) {
throw new Error('Need at least 10 observations for Heston parameter estimation');
}
// Initial parameter estimates
let kappa = 2.0; // Mean reversion speed
let theta = 0.04; // Long-term variance
let sigma = 0.3; // Volatility of variance
let rho = -0.5; // Correlation
let v0 = 0.04; // Initial variance
// Calculate sample statistics for initialization
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
const sampleVariance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
theta = sampleVariance;
v0 = sampleVariance;
let logLikelihood = -Infinity;
for (let iter = 0; iter < maxIterations; iter++) {
let newLogLikelihood = 0;
let currentVariance = v0;
for (let t = 1; t < n; t++) {
const dt = 1.0; // Assuming daily data
const prevReturn = returns[t - 1];
// Euler discretization of variance process
const dW1 = Math.random() - 0.5; // Simplified random shock
const dW2 = rho * dW1 + Math.sqrt(1 - rho * rho) * (Math.random() - 0.5);
const varianceChange =
kappa * (theta - currentVariance) * dt +
sigma * Math.sqrt(Math.max(currentVariance, 0)) * dW2;
currentVariance = Math.max(currentVariance + varianceChange, 0.001);
// Log-likelihood contribution (simplified)
const expectedReturn = meanReturn;
const variance = currentVariance;
if (variance > 0) {
newLogLikelihood -= 0.5 * Math.log(2 * Math.PI * variance);
newLogLikelihood -= (0.5 * Math.pow(returns[t] - expectedReturn, 2)) / variance;
}
}
// Check for convergence
if (Math.abs(newLogLikelihood - logLikelihood) < 1e-6) {
break;
}
logLikelihood = newLogLikelihood;
// Simple parameter updates (in practice, use maximum likelihood estimation)
const learningRate = 0.001;
kappa = Math.max(0.1, Math.min(10, kappa + learningRate));
theta = Math.max(0.001, Math.min(1, theta + learningRate));
sigma = Math.max(0.01, Math.min(2, sigma + learningRate));
rho = Math.max(-0.99, Math.min(0.99, rho + learningRate * 0.1));
v0 = Math.max(0.001, Math.min(1, v0 + learningRate));
}
return {
kappa,
theta,
sigma,
rho,
v0,
logLikelihood,
};
}
/**
* Calculate volatility risk metrics
*/
export function calculateVolatilityRisk(
returns: number[],
confidenceLevel: number = 0.05
): {
volatilityVaR: number;
expectedShortfall: number;
maxVolatility: number;
volatilityVolatility: number;
} {
// Calculate rolling volatilities
const windowSize = 30;
const volatilities: number[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
const mean = window.reduce((sum, r) => sum + r, 0) / window.length;
const variance =
window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1);
volatilities.push(Math.sqrt(variance * 252)); // Annualized
}
// Sort volatilities for VaR calculation
const sortedVols = [...volatilities].sort((a, b) => b - a); // Descending order
const varIndex = Math.floor(confidenceLevel * sortedVols.length);
const volatilityVaR = sortedVols[varIndex];
// Expected shortfall (average of worst volatilities)
const esVols = sortedVols.slice(0, varIndex + 1);
const expectedShortfall = esVols.reduce((sum, vol) => sum + vol, 0) / esVols.length;
// Maximum volatility
const maxVolatility = Math.max(...volatilities);
// Volatility of volatility
const meanVol = volatilities.reduce((sum, vol) => sum + vol, 0) / volatilities.length;
const volVariance =
volatilities.reduce((sum, vol) => sum + Math.pow(vol - meanVol, 2), 0) /
(volatilities.length - 1);
const volatilityVolatility = Math.sqrt(volVariance);
return {
volatilityVaR,
expectedShortfall,
maxVolatility,
volatilityVolatility,
};
}
/**
* Fix Yang-Zhang volatility calculation
*/
export function calculateYangZhangVolatility(
ohlcv: OHLCVData[],
annualizationFactor: number = 252
): number {
if (ohlcv.length < 2) {
throw new Error('Need at least 2 observations for Yang-Zhang volatility calculation');
}
const n = ohlcv.length;
let overnightSum = 0;
let openToCloseSum = 0;
let rogersSatchellSum = 0;
for (let i = 1; i < n; i++) {
const prev = ohlcv[i - 1];
const curr = ohlcv[i];
// Overnight return (close to open)
const overnight = Math.log(curr.open / prev.close);
overnightSum += overnight * overnight;
// Open to close return
const openToClose = Math.log(curr.close / curr.open);
openToCloseSum += openToClose * openToClose;
// Rogers-Satchell component
const logHighOpen = Math.log(curr.high / curr.open);
const logHighClose = Math.log(curr.high / curr.close);
const logLowOpen = Math.log(curr.low / curr.open);
const logLowClose = Math.log(curr.low / curr.close);
rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose;
}
// Yang-Zhang estimator
const k = 0.34 / (1.34 + (n + 1) / (n - 1)); // Drift adjustment factor
const yangZhangVariance =
overnightSum / (n - 1) +
(k * openToCloseSum) / (n - 1) +
((1 - k) * rogersSatchellSum) / (n - 1);
return Math.sqrt(yangZhangVariance * annualizationFactor);
}
/**
* Parkinson volatility estimator
*/
export function parkinsonVolatility(ohlcv: OHLCVData[], annualizationFactor: number = 252): number {
if (ohlcv.length < 2) {
return 0;
}
const sum = ohlcv.slice(1).reduce((acc, curr) => {
const range = Math.log(curr.high / curr.low);
return acc + range * range;
}, 0);
return Math.sqrt((sum / (ohlcv.length - 1)) * annualizationFactor);
}
/**
* Black-Scholes option pricing model
*/
function blackScholes(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
volatility: number,
riskFreeRate: number,
optionType: 'call' | 'put'
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
if (optionType === 'call') {
return (
spotPrice * normalCDF(d1) -
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(d2)
);
} else {
return (
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2) -
spotPrice * normalCDF(-d1)
);
}
}
/**
* Normal cumulative distribution function
*/
function normalCDF(x: number): number {
const a1 = 0.254829592;
const a2 = -0.284496736;
const a3 = 1.421060743;
const a4 = -1.453152027;
const a5 = 1.061405429;
const p = 0.3275911;
const sign = x < 0 ? -1 : 1;
const absX = Math.abs(x);
const t = 1 / (1 + p * absX);
const y =
1 -
(a1 * t + a2 * t * t + a3 * t * t * t + a4 * t * t * t * t + a5 * t * t * t * t * t) *
Math.exp((-absX * absX) / 2);
return 0.5 * (1 + sign * y);
}
/**
* Forecast volatility using EWMA
*/
export function forecastVolatilityEWMA(
volatilities: number[],
lambda: number = 0.94,
forecastHorizon: number = 1
): number {
if (volatilities.length === 0) {
return 0;
}
let forecast = volatilities[volatilities.length - 1];
for (let i = 0; i < forecastHorizon; i++) {
forecast = lambda * forecast + (1 - lambda) * forecast; // Using the last value as the long-term average
}
return forecast;
}
```

View file

@ -1,454 +0,0 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
/**
* Basic Financial Calculations
* Core mathematical functions for financial analysis
*/
/**
* Calculate percentage change between two values
*/
export function percentageChange(oldValue: number, newValue: number): number {
if (oldValue === 0) {
return 0;
}
return ((newValue - oldValue) / oldValue) * 100;
}
/**
* Calculate simple return
*/
export function simpleReturn(initialPrice: number, finalPrice: number): number {
if (initialPrice === 0) {
return 0;
}
return (finalPrice - initialPrice) / initialPrice;
}
/**
* Calculate logarithmic return
*/
export function logReturn(initialPrice: number, finalPrice: number): number {
if (initialPrice <= 0 || finalPrice <= 0) {
return 0;
}
return Math.log(finalPrice / initialPrice);
}
/**
* Calculate compound annual growth rate (CAGR)
*/
export function cagr(startValue: number, endValue: number, years: number): number {
if (years <= 0 || startValue <= 0 || endValue <= 0) {
return 0;
}
return Math.pow(endValue / startValue, 1 / years) - 1;
}
/**
* Calculate annualized return from periodic returns
*/
export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number {
return Math.pow(1 + periodicReturn, periodsPerYear) - 1;
}
/**
* Calculate annualized volatility from periodic returns
*/
export function annualizeVolatility(periodicVolatility: number, periodsPerYear: number): number {
return periodicVolatility * Math.sqrt(periodsPerYear);
}
/**
* Calculate present value
*/
export function presentValue(futureValue: number, rate: number, periods: number): number {
return futureValue / Math.pow(1 + rate, periods);
}
/**
* Calculate future value
*/
export function futureValue(presentValue: number, rate: number, periods: number): number {
return presentValue * Math.pow(1 + rate, periods);
}
/**
* Calculate net present value of cash flows
*/
export function netPresentValue(cashFlows: number[], discountRate: number): number {
return cashFlows.reduce((npv, cashFlow, index) => {
return npv + cashFlow / Math.pow(1 + discountRate, index);
}, 0);
}
/**
* Calculate internal rate of return (IRR) using Newton-Raphson method
*/
export function internalRateOfReturn(
cashFlows: number[],
guess: number = 0.1,
maxIterations: number = 100
): number {
let rate = guess;
for (let i = 0; i < maxIterations; i++) {
let npv = 0;
let dnpv = 0;
for (let j = 0; j < cashFlows.length; j++) {
const cashFlow = cashFlows[j];
if (cashFlow !== undefined) {
npv += cashFlow / Math.pow(1 + rate, j);
dnpv += (-j * cashFlow) / Math.pow(1 + rate, j + 1);
}
}
if (Math.abs(npv) < 1e-10) {
break;
}
if (Math.abs(dnpv) < 1e-10) {
break;
}
rate = rate - npv / dnpv;
}
return rate;
}
/**
* Calculate payback period
*/
export function paybackPeriod(initialInvestment: number, cashFlows: number[]): number {
let cumulativeCashFlow = 0;
for (let i = 0; i < cashFlows.length; i++) {
const cashFlow = cashFlows[i];
if (cashFlow !== undefined) {
cumulativeCashFlow += cashFlow;
if (cumulativeCashFlow >= initialInvestment) {
return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow;
}
}
}
return -1; // Never pays back
}
/**
* Calculate compound interest
*/
export function compoundInterest(
principal: number,
rate: number,
periods: number,
compoundingFrequency: number = 1
): number {
return principal * Math.pow(1 + rate / compoundingFrequency, compoundingFrequency * periods);
}
/**
* Calculate effective annual rate
*/
export function effectiveAnnualRate(nominalRate: number, compoundingFrequency: number): number {
return Math.pow(1 + nominalRate / compoundingFrequency, compoundingFrequency) - 1;
}
/**
* Calculate bond price given yield
*/
export function bondPrice(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
let price = 0;
// Present value of coupon payments
for (let i = 1; i <= periodsToMaturity; i++) {
price += couponPayment / Math.pow(1 + discountRate, i);
}
// Present value of face value
price += faceValue / Math.pow(1 + discountRate, periodsToMaturity);
return price;
}
/**
* Calculate bond yield given price (Newton-Raphson approximation)
*/
export function bondYield(
price: number,
faceValue: number,
couponRate: number,
periodsToMaturity: number,
paymentsPerYear: number = 2,
guess: number = 0.05
): number {
let yield_ = guess;
const maxIterations = 100;
const tolerance = 1e-8;
for (let i = 0; i < maxIterations; i++) {
const calculatedPrice = bondPrice(
faceValue,
couponRate,
yield_,
periodsToMaturity,
paymentsPerYear
);
const diff = calculatedPrice - price;
if (Math.abs(diff) < tolerance) {
break;
}
// Numerical derivative
const delta = 0.0001;
const priceUp = bondPrice(
faceValue,
couponRate,
yield_ + delta,
periodsToMaturity,
paymentsPerYear
);
const derivative = (priceUp - calculatedPrice) / delta;
if (Math.abs(derivative) < tolerance) {
break;
}
yield_ = yield_ - diff / derivative;
}
return yield_;
}
/**
* Calculate duration (Macaulay duration)
*/
export function macaulayDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
let weightedTime = 0;
// Weighted time of coupon payments
for (let i = 1; i <= periodsToMaturity; i++) {
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
weightedTime += (i * presentValue) / bondPriceValue;
}
// Weighted time of face value
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
weightedTime += (periodsToMaturity * faceValuePV) / bondPriceValue;
return weightedTime / paymentsPerYear; // Convert to years
}
/**
* Calculate modified duration
*/
export function modifiedDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const macDuration = macaulayDuration(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
return macDuration / (1 + yieldToMaturity / paymentsPerYear);
}
/**
* Calculate bond convexity
*/
export function bondConvexity(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
let convexity = 0;
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
for (let i = 1; i <= periodsToMaturity; i++) {
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
convexity += (i * (i + 1) * presentValue) / Math.pow(1 + discountRate, 2);
}
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
convexity +=
(periodsToMaturity * (periodsToMaturity + 1) * faceValuePV) / Math.pow(1 + discountRate, 2);
return convexity / (bondPriceValue * paymentsPerYear * paymentsPerYear);
}
/**
* Calculate dollar duration
*/
export function dollarDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2,
basisPointChange: number = 0.01 // 1 basis point = 0.01%
): number {
const modifiedDur = modifiedDuration(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
return modifiedDur * bondPriceValue * basisPointChange;
}
/**
* Calculate accrued interest
*/
export function accruedInterest(
faceValue: number,
couponRate: number,
daysSinceLastCoupon: number,
daysInCouponPeriod: number
): number {
return faceValue * couponRate * (daysSinceLastCoupon / daysInCouponPeriod);
}
/**
* Calculate clean price
*/
export function cleanPrice(dirtyPrice: number, accruedInterestValue: number): number {
return dirtyPrice - accruedInterestValue;
}
/**
* Calculate dirty price
*/
export function dirtyPrice(cleanPriceValue: number, accruedInterestValue: number): number {
return cleanPriceValue + accruedInterestValue;
}
/**
* Calculate dividend discount model (DDM)
*/
export function dividendDiscountModel(
currentDividend: number,
growthRate: number,
discountRate: number
): number {
if (discountRate <= growthRate) {
return NaN;
} // Indeterminate
return (currentDividend * (1 + growthRate)) / (discountRate - growthRate);
}
/**
* Calculate weighted average cost of capital (WACC)
*/
export function weightedAverageCostOfCapital(
costOfEquity: number,
costOfDebt: number,
equityWeight: number,
debtWeight: number,
taxRate: number
): number {
return equityWeight * costOfEquity + debtWeight * costOfDebt * (1 - taxRate);
}
/**
* Calculate capital asset pricing model (CAPM)
*/
export function capitalAssetPricingModel(
riskFreeRate: number,
beta: number,
marketRiskPremium: number
): number {
return riskFreeRate + beta * marketRiskPremium;
}
/**
* Calculate hurdle rate
*/
export function hurdleRate(costOfCapital: number, riskPremium: number): number {
return costOfCapital + riskPremium;
}
/**
* Calculate degree of operating leverage (DOL)
*/
export function degreeOfOperatingLeverage(
contributionMargin: number,
operatingIncome: number
): number {
return contributionMargin / operatingIncome;
}
/**
* Calculate degree of financial leverage (DFL)
*/
export function degreeOfFinancialLeverage(ebit: number, earningsBeforeTax: number): number {
return ebit / earningsBeforeTax;
}
/**
* Calculate degree of total leverage (DTL)
*/
export function degreeOfTotalLeverage(dol: number, dfl: number): number {
return dol * dfl;
}
/**
* Calculate economic value added (EVA)
*/
export function economicValueAdded(
netOperatingProfitAfterTax: number,
capitalInvested: number,
wacc: number
): number {
return netOperatingProfitAfterTax - capitalInvested * wacc;
}

View file

@ -1,5 +0,0 @@
/** 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';

View file

@ -1,941 +0,0 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
import { ulcerIndex } from './risk-metrics';
/**
* Performance Metrics and Analysis
* Comprehensive performance measurement tools for trading strategies and portfolios
*/
// import type { PortfolioMetrics } from '@stock-bot/types';
// Define PortfolioMetrics locally until it's added to types library
export interface PortfolioMetrics {
totalValue: number;
totalReturn: number;
totalReturnPercent: number;
dailyReturn: number;
dailyReturnPercent: number;
maxDrawdown: number;
sharpeRatio: number;
beta: number;
alpha: number;
volatility: number;
}
export interface TradePerformance {
totalTrades: number;
winningTrades: number;
losingTrades: number;
winRate: number;
averageWin: number;
averageLoss: number;
largestWin: number;
largestLoss: number;
profitFactor: number;
expectancy: number;
averageTradeReturn: number;
consecutiveWins: number;
consecutiveLosses: number;
}
export interface DrawdownAnalysis {
maxDrawdown: number;
maxDrawdownDuration: number;
averageDrawdown: number;
drawdownPeriods: Array<{
start: Date;
end: Date;
duration: number;
magnitude: number;
}>;
}
export interface ReturnAnalysis {
totalReturn: number;
annualizedReturn: number;
compoundAnnualGrowthRate: number;
volatility: number;
annualizedVolatility: number;
skewness: number;
kurtosis: number;
bestMonth: number;
worstMonth: number;
positiveMonths: number;
negativeMonths: number;
}
/**
* Calculate comprehensive trade performance metrics
*/
export function analyzeTradePerformance(
trades: Array<{ pnl: number; date: Date }>
): TradePerformance {
if (trades.length === 0) {
return {
totalTrades: 0,
winningTrades: 0,
losingTrades: 0,
winRate: 0,
averageWin: 0,
averageLoss: 0,
largestWin: 0,
largestLoss: 0,
profitFactor: 0,
expectancy: 0,
averageTradeReturn: 0,
consecutiveWins: 0,
consecutiveLosses: 0,
};
}
const winningTrades = trades.filter(trade => trade.pnl > 0);
const losingTrades = trades.filter(trade => trade.pnl < 0);
const totalWins = winningTrades.reduce((sum, trade) => sum + trade.pnl, 0);
const totalLosses = Math.abs(losingTrades.reduce((sum, trade) => sum + trade.pnl, 0));
const averageWin = winningTrades.length > 0 ? totalWins / winningTrades.length : 0;
const averageLoss = losingTrades.length > 0 ? totalLosses / losingTrades.length : 0;
const largestWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.pnl)) : 0;
const largestLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.pnl)) : 0;
const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;
const winRate = winningTrades.length / trades.length;
const expectancy = winRate * averageWin - (1 - winRate) * averageLoss;
const totalPnL = trades.reduce((sum, trade) => sum + trade.pnl, 0);
const averageTradeReturn = totalPnL / trades.length;
// Calculate consecutive wins/losses
let consecutiveWins = 0;
let consecutiveLosses = 0;
let currentWinStreak = 0;
let currentLossStreak = 0;
for (const trade of trades) {
if (trade.pnl > 0) {
currentWinStreak++;
currentLossStreak = 0;
consecutiveWins = Math.max(consecutiveWins, currentWinStreak);
} else if (trade.pnl < 0) {
currentLossStreak++;
currentWinStreak = 0;
consecutiveLosses = Math.max(consecutiveLosses, currentLossStreak);
}
}
return {
totalTrades: trades.length,
winningTrades: winningTrades.length,
losingTrades: losingTrades.length,
winRate,
averageWin,
averageLoss,
largestWin,
largestLoss,
profitFactor,
expectancy,
averageTradeReturn,
consecutiveWins,
consecutiveLosses,
};
}
/**
* Analyze drawdown characteristics
*/
export function analyzeDrawdowns(
equityCurve: Array<{ value: number; date: Date }>
): DrawdownAnalysis {
if (equityCurve.length < 2) {
return {
maxDrawdown: 0,
maxDrawdownDuration: 0,
averageDrawdown: 0,
drawdownPeriods: [],
};
}
const first = equityCurve[0];
if (!first) {
return { maxDrawdown: 0, maxDrawdownDuration: 0, averageDrawdown: 0, drawdownPeriods: [] };
}
let peak = first.value;
let peakDate = first.date;
let maxDrawdown = 0;
let maxDrawdownDuration = 0;
const drawdownPeriods: Array<{
start: Date;
end: Date;
duration: number;
magnitude: number;
}> = [];
let currentDrawdownStart: Date | null = null;
const drawdowns: number[] = [];
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
if (!current) {
continue;
}
if (current.value > peak) {
// New peak - end any current drawdown
if (currentDrawdownStart) {
const prev = equityCurve[i - 1];
if (!prev) {
continue;
}
const drawdownMagnitude = (peak - prev.value) / peak;
const duration = Math.floor(
(prev.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
);
drawdownPeriods.push({
start: currentDrawdownStart,
end: prev.date,
duration,
magnitude: drawdownMagnitude,
});
drawdowns.push(drawdownMagnitude);
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
currentDrawdownStart = null;
}
peak = current.value;
peakDate = current.date;
} else {
// In drawdown
if (!currentDrawdownStart) {
currentDrawdownStart = peakDate;
}
const drawdown = (peak - current.value) / peak;
maxDrawdown = Math.max(maxDrawdown, drawdown);
}
}
// Handle ongoing drawdown
if (currentDrawdownStart) {
const lastPoint = equityCurve[equityCurve.length - 1];
if (!lastPoint) {
return { maxDrawdown, maxDrawdownDuration, averageDrawdown: 0, drawdownPeriods };
}
const drawdownMagnitude = (peak - lastPoint.value) / peak;
const duration = Math.floor(
(lastPoint.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
);
drawdownPeriods.push({
start: currentDrawdownStart,
end: lastPoint.date,
duration,
magnitude: drawdownMagnitude,
});
drawdowns.push(drawdownMagnitude);
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
}
const averageDrawdown =
drawdowns.length > 0 ? drawdowns.reduce((sum, dd) => sum + dd, 0) / drawdowns.length : 0;
return {
maxDrawdown,
maxDrawdownDuration,
averageDrawdown,
drawdownPeriods,
};
}
/**
* Analyze return characteristics
*/
export function analyzeReturns(
returns: Array<{ return: number; date: Date }>,
periodsPerYear: number = 252
): ReturnAnalysis {
if (returns.length === 0) {
return {
totalReturn: 0,
annualizedReturn: 0,
compoundAnnualGrowthRate: 0,
volatility: 0,
annualizedVolatility: 0,
skewness: 0,
kurtosis: 0,
bestMonth: 0,
worstMonth: 0,
positiveMonths: 0,
negativeMonths: 0,
};
}
const returnValues = returns.map(r => r.return);
// Calculate basic statistics
const totalReturn = returnValues.reduce((product, ret) => product * (1 + ret), 1) - 1;
const averageReturn = returnValues.reduce((sum, ret) => sum + ret, 0) / returnValues.length;
const annualizedReturn = Math.pow(1 + averageReturn, periodsPerYear) - 1;
// Calculate CAGR
const years = returns.length / periodsPerYear;
const cagr = years > 0 ? Math.pow(1 + totalReturn, 1 / years) - 1 : 0;
// Calculate volatility
const variance =
returnValues.reduce((sum, ret) => sum + Math.pow(ret - averageReturn, 2), 0) /
(returnValues.length - 1);
const volatility = Math.sqrt(variance);
const annualizedVolatility = volatility * Math.sqrt(periodsPerYear);
// Calculate skewness and kurtosis
const skewness = calculateSkewness(returnValues);
const kurtosis = calculateKurtosis(returnValues);
// Monthly analysis
const monthlyReturns = aggregateMonthlyReturns(returns);
const bestMonth = monthlyReturns.length > 0 ? Math.max(...monthlyReturns) : 0;
const worstMonth = monthlyReturns.length > 0 ? Math.min(...monthlyReturns) : 0;
const positiveMonths = monthlyReturns.filter(ret => ret > 0).length;
const negativeMonths = monthlyReturns.filter(ret => ret < 0).length;
return {
totalReturn,
annualizedReturn,
compoundAnnualGrowthRate: cagr,
volatility,
annualizedVolatility,
skewness,
kurtosis,
bestMonth,
worstMonth,
positiveMonths,
negativeMonths,
};
}
/**
* Calculate rolling performance metrics
*/
export function calculateRollingMetrics(
returns: number[],
windowSize: number,
metricType: 'sharpe' | 'volatility' | 'return' = 'sharpe'
): number[] {
if (returns.length < windowSize) {
return [];
}
const rollingMetrics: number[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
switch (metricType) {
case 'sharpe':
rollingMetrics.push(calculateSharpeRatio(window));
break;
case 'volatility':
rollingMetrics.push(calculateVolatility(window));
break;
case 'return': {
const avgReturn = window.reduce((sum, ret) => sum + ret, 0) / window.length;
rollingMetrics.push(avgReturn);
break;
}
}
}
return rollingMetrics;
}
/**
* Calculate performance attribution
*/
export function strategyPerformanceAttribution(
portfolioReturns: number[],
benchmarkReturns: number[],
sectorWeights: number[],
sectorReturns: number[]
): {
allocationEffect: number;
selectionEffect: number;
interactionEffect: number;
totalActiveReturn: number;
} {
if (portfolioReturns.length !== benchmarkReturns.length) {
throw new Error('Portfolio and benchmark returns must have same length');
}
const portfolioReturn =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const benchmarkReturn =
benchmarkReturns.reduce((sum, ret) => sum + ret, 0) / benchmarkReturns.length;
let allocationEffect = 0;
let selectionEffect = 0;
let interactionEffect = 0;
for (let i = 0; i < sectorWeights.length; i++) {
const portfolioWeight = sectorWeights[i];
const sectorReturn = sectorReturns[i];
if (portfolioWeight === undefined || sectorReturn === undefined) {
continue;
}
const benchmarkWeight = 1 / sectorWeights.length; // Assuming equal benchmark weights
// Allocation effect: (portfolio weight - benchmark weight) * (benchmark sector return - benchmark return)
allocationEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - benchmarkReturn);
// Selection effect: benchmark weight * (portfolio sector return - benchmark sector return)
selectionEffect += benchmarkWeight * (sectorReturn - sectorReturn); // Simplified
// Interaction effect: (portfolio weight - benchmark weight) * (portfolio sector return - benchmark sector return)
interactionEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - sectorReturn); // Simplified
}
const totalActiveReturn = portfolioReturn - benchmarkReturn;
return {
allocationEffect,
selectionEffect,
interactionEffect,
totalActiveReturn,
};
}
/**
* Calculate Omega ratio
*/
export function omegaRatio(returns: number[], threshold: number = 0): number {
if (returns.length === 0) {
return 0;
}
const gains = returns
.filter(ret => ret > threshold)
.reduce((sum, ret) => sum + (ret - threshold), 0);
const losses = returns
.filter(ret => ret < threshold)
.reduce((sum, ret) => sum + Math.abs(ret - threshold), 0);
return losses === 0 ? Infinity : gains / losses;
}
/**
* Calculate gain-to-pain ratio
*/
export function gainToPainRatio(returns: number[]): number {
if (returns.length === 0) {
return 0;
}
const totalGain = returns.reduce((sum, ret) => sum + ret, 0);
const totalPain = returns.filter(ret => ret < 0).reduce((sum, ret) => sum + Math.abs(ret), 0);
return totalPain === 0 ? (totalGain > 0 ? Infinity : 0) : totalGain / totalPain;
}
/**
* Calculate Martin ratio (modified Sharpe with downside deviation)
*/
export function martinRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length === 0) {
return 0;
}
const averageReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
if (downsideReturns.length === 0) {
return Infinity;
}
const downsideDeviation = Math.sqrt(
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
);
return downsideDeviation === 0 ? Infinity : (averageReturn - riskFreeRate) / downsideDeviation;
}
/**
* Calculate comprehensive portfolio metrics
*/
export function calculateStrategyMetrics(
equityCurve: Array<{ value: number; date: Date }>,
benchmarkReturns?: number[],
riskFreeRate: number = 0.02
): PortfolioMetrics {
if (equityCurve.length < 2) {
return {
totalValue: 0,
totalReturn: 0,
totalReturnPercent: 0,
dailyReturn: 0,
dailyReturnPercent: 0,
maxDrawdown: 0,
sharpeRatio: 0,
beta: 0,
alpha: 0,
volatility: 0,
};
}
const returns = [];
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
const previous = equityCurve[i - 1];
if (!current || !previous) {
continue;
}
const ret = (current.value - previous.value) / previous.value;
returns.push(ret);
}
const lastPoint = equityCurve[equityCurve.length - 1];
const firstPoint = equityCurve[0];
if (!lastPoint || !firstPoint) {
return {
totalValue: 0,
totalReturn: 0,
totalReturnPercent: 0,
dailyReturn: 0,
dailyReturnPercent: 0,
maxDrawdown: 0,
sharpeRatio: 0,
beta: 0,
alpha: 0,
volatility: 0,
};
}
const totalValue = lastPoint.value;
const totalReturn = totalValue - firstPoint.value;
const totalReturnPercent = (totalReturn / firstPoint.value) * 100;
const dailyReturn = returns[returns.length - 1] || 0;
const dailyReturnPercent = dailyReturn * 100;
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
const sharpeRatio = calculateSharpeRatio(returns, riskFreeRate);
const volatility = calculateVolatility(returns);
let beta = 0;
let alpha = 0;
if (benchmarkReturns && benchmarkReturns.length === returns.length) {
beta = calculateBeta(returns, benchmarkReturns);
alpha = calculateAlpha(returns, benchmarkReturns, riskFreeRate);
}
return {
totalValue,
totalReturn,
totalReturnPercent,
dailyReturn,
dailyReturnPercent,
maxDrawdown,
sharpeRatio,
beta,
alpha,
volatility,
};
}
/**
* Calculate Calmar Ratio
*/
export function calmarRatio(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return maxDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / maxDrawdown;
}
/**
* Calculate Sterling Ratio
*/
export function sterlingRatio(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const averageDrawdown = analyzeDrawdowns(equityCurve).averageDrawdown;
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return averageDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / averageDrawdown;
}
/**
* Calculate Information Ratio
*/
export function informationRatio(portfolioReturns: number[], benchmarkReturns: number[]): number {
if (portfolioReturns.length !== benchmarkReturns.length) {
throw new Error('Portfolio and benchmark returns must have the same length.');
}
const excessReturns = portfolioReturns.map((portfolioReturn, index) => {
const benchmark = benchmarkReturns[index];
return benchmark !== undefined ? portfolioReturn - benchmark : 0;
});
const trackingError = calculateVolatility(excessReturns);
const avgExcessReturn = excessReturns.reduce((sum, ret) => sum + ret, 0) / excessReturns.length;
return trackingError === 0 ? 0 : avgExcessReturn / trackingError;
}
// Treynor Ratio is already exported from risk-metrics
/**
* Calculate Jensen's Alpha (same as Alpha, but included for clarity)
*/
export function jensensAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number
): number {
return calculateAlpha(portfolioReturns, marketReturns, riskFreeRate);
}
/**
* Calculate Capture Ratio (Up Capture and Down Capture)
*/
export function captureRatio(
portfolioReturns: number[],
benchmarkReturns: number[]
): { upCaptureRatio: number; downCaptureRatio: number } {
let upCapture = 0;
let downCapture = 0;
let upMarketPeriods = 0;
let downMarketPeriods = 0;
for (let i = 0; i < portfolioReturns.length; i++) {
const benchmarkReturn = benchmarkReturns[i];
const portfolioReturn = portfolioReturns[i];
if (benchmarkReturn === undefined || portfolioReturn === undefined) {
continue;
}
if (benchmarkReturn > 0) {
upCapture += portfolioReturn;
upMarketPeriods++;
} else if (benchmarkReturn < 0) {
downCapture += portfolioReturn;
downMarketPeriods++;
}
}
const upCaptureRatio =
upMarketPeriods > 0
? upCapture /
upMarketPeriods /
(benchmarkReturns.filter(r => r > 0).reduce((sum, r) => sum + r, 0) / upMarketPeriods)
: 0;
const downCaptureRatio =
downMarketPeriods > 0
? downCapture /
downMarketPeriods /
(benchmarkReturns.filter(r => r < 0).reduce((sum, r) => sum + r, 0) / downMarketPeriods)
: 0;
return { upCaptureRatio, downCaptureRatio };
}
/**
* Calculate Sortino Ratio
*/
export function sortinoRatio(returns: number[], riskFreeRate: number = 0): number {
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
const downsideDeviation = Math.sqrt(
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
);
return downsideDeviation === 0 ? 0 : (avgReturn - riskFreeRate) / downsideDeviation;
}
/**
* Calculate Tail Ratio
*/
export function tailRatio(returns: number[], tailPercent: number = 0.1): number {
const numReturns = returns.length;
const tailSize = Math.floor(numReturns * tailPercent);
if (tailSize === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const worstTail = sortedReturns.slice(0, tailSize);
const bestTail = sortedReturns.slice(numReturns - tailSize);
const avgWorst = worstTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
const avgBest = bestTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
return avgWorst === 0 ? 0 : avgBest / Math.abs(avgWorst);
}
/**
* Calculate Rolling Beta
*/
export function calculateRollingBeta(
portfolioReturns: number[],
marketReturns: number[],
windowSize: number
): number[] {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
return [];
}
const rollingBetas: number[] = [];
for (let i = windowSize; i <= portfolioReturns.length; i++) {
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
const marketWindow = marketReturns.slice(i - windowSize, i);
rollingBetas.push(calculateBeta(portfolioWindow, marketWindow));
}
return rollingBetas;
}
/**
* Calculate Ulcer Performance Index (UPI)
*/
export function ulcerPerformanceIndex(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const ui = ulcerIndex(equityCurve);
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return ui === 0 ? 0 : (avgReturn - riskFreeRate) / ui;
}
/**
* Calculate Rolling Alpha
*/
export function calculateRollingAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number,
windowSize: number
): number[] {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
return [];
}
const rollingAlphas: number[] = [];
for (let i = windowSize; i <= portfolioReturns.length; i++) {
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
const marketWindow = marketReturns.slice(i - windowSize, i);
rollingAlphas.push(calculateAlpha(portfolioWindow, marketWindow, riskFreeRate));
}
return rollingAlphas;
}
/**
* Calculate Time Weighted Rate of Return (TWRR)
*/
export function timeWeightedRateOfReturn(
cashFlows: Array<{ amount: number; date: Date; value: number }>
): number {
if (cashFlows.length < 2) {
return 0;
}
const first = cashFlows[0];
if (!first) {
return 0;
}
let totalReturn = 1;
let previousValue = first.value;
for (let i = 1; i < cashFlows.length; i++) {
const current = cashFlows[i];
if (!current) {
continue;
}
const periodReturn =
(current.value - previousValue - current.amount) / (previousValue + current.amount);
totalReturn *= 1 + periodReturn;
previousValue = current.value;
}
return totalReturn - 1;
}
/**
* Calculate Money Weighted Rate of Return (MWRR) - Approximation using IRR
*/
export function moneyWeightedRateOfReturn(
cashFlows: Array<{ amount: number; date: Date; value: number }>
): number {
if (cashFlows.length === 0) {
return 0;
}
const first = cashFlows[0];
if (!first) {
return 0;
}
// Approximate MWRR using Internal Rate of Return (IRR)
// This requires a numerical method or library for accurate IRR calculation
// This is a simplified example and may not be accurate for all cases
let totalCashFlow = 0;
let totalWeightedCashFlow = 0;
const startDate = first.date.getTime();
for (const cf of cashFlows) {
const timeDiff = (cf.date.getTime() - startDate) / (1000 * 60 * 60 * 24 * 365); // Years
totalCashFlow += cf.amount;
totalWeightedCashFlow += cf.amount * timeDiff;
}
// Simplified approximation: MWRR ≈ totalCashFlow / totalWeightedCashFlow - 1
return totalWeightedCashFlow === 0 ? 0 : totalCashFlow / totalWeightedCashFlow - 1;
}
// Helper functions
function calculateSharpeRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length < 2) {
return 0;
}
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
return stdDev === 0 ? 0 : (avgReturn - riskFreeRate) / stdDev;
}
function calculateVolatility(returns: number[]): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
return Math.sqrt(variance);
}
function calculateBeta(portfolioReturns: number[], marketReturns: number[]): number {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
return 0;
}
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < portfolioReturns.length; i++) {
const portfolioReturn = portfolioReturns[i];
const marketReturn = marketReturns[i];
if (portfolioReturn === undefined || marketReturn === undefined) {
continue;
}
const portfolioDiff = portfolioReturn - portfolioMean;
const marketDiff = marketReturn - marketMean;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
covariance /= portfolioReturns.length - 1;
marketVariance /= marketReturns.length - 1;
return marketVariance === 0 ? 0 : covariance / marketVariance;
}
function calculateAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number
): number {
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
const beta = calculateBeta(portfolioReturns, marketReturns);
return portfolioMean - (riskFreeRate + beta * (marketMean - riskFreeRate));
}
function calculateSkewness(returns: number[]): number {
if (returns.length < 3) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const skew =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
return skew;
}
function calculateKurtosis(returns: number[]): number {
if (returns.length < 4) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const kurt =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
return kurt - 3; // Excess kurtosis
}
function aggregateMonthlyReturns(returns: Array<{ return: number; date: Date }>): number[] {
const monthlyReturns: { [key: string]: number } = {};
for (const ret of returns) {
const monthKey = `${ret.date.getFullYear()}-${ret.date.getMonth()}`;
if (!monthlyReturns[monthKey]) {
monthlyReturns[monthKey] = 1;
}
monthlyReturns[monthKey] *= 1 + ret.return;
}
return Object.values(monthlyReturns).map(cumReturn => cumReturn - 1);
}

View file

@ -1,482 +0,0 @@
/** 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
*/
import type { RiskMetrics } from '@stock-bot/types';
/**
* Calculate Value at Risk (VaR) using historical simulation
*/
export function valueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
if (returns.length === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const index = Math.floor((1 - confidenceLevel) * sortedReturns.length);
return sortedReturns[index] || 0;
}
/**
* Calculate Conditional Value at Risk (CVaR/Expected Shortfall)
*/
export function conditionalValueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
if (returns.length === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const cutoffIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length);
if (cutoffIndex === 0) {
return sortedReturns[0] || 0;
}
const tailReturns = sortedReturns.slice(0, cutoffIndex);
return tailReturns.reduce((sum, ret) => sum + ret, 0) / tailReturns.length;
}
/**
* Calculate parametric VaR using normal distribution
*/
export function parametricVaR(
returns: number[],
confidenceLevel: number = 0.95,
portfolioValue: number = 1
): number {
if (returns.length === 0) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
// Z-score for confidence level (normal distribution)
const zScore = getZScore(confidenceLevel);
return portfolioValue * (mean - zScore * stdDev);
}
/**
* Calculate maximum drawdown
*/
export function maxDrawdown(equityCurve: number[]): number {
if (equityCurve.length < 2) {
return 0;
}
let maxDD = 0;
const first = equityCurve[0];
if (first === undefined) {
return 0;
}
let peak = first;
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
if (current === undefined) {
continue;
}
if (current > peak) {
peak = current;
} else {
const drawdown = (peak - current) / peak;
maxDD = Math.max(maxDD, drawdown);
}
}
return maxDD;
}
/**
* Calculate downside deviation
*/
export function downsideDeviation(returns: number[], targetReturn: number = 0): number {
if (returns.length === 0) {
return 0;
}
const downsideReturns = returns.filter(ret => ret < targetReturn);
if (downsideReturns.length === 0) {
return 0;
}
const sumSquaredDownside = downsideReturns.reduce(
(sum, ret) => sum + Math.pow(ret - targetReturn, 2),
0
);
return Math.sqrt(sumSquaredDownside / returns.length);
}
/**
* Calculate Sharpe ratio
*/
export function sharpeRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
return (mean - riskFreeRate) / stdDev;
}
/**
* Calculate beta coefficient
*/
export function beta(portfolioReturns: number[], marketReturns: number[]): number {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
return 0;
}
const n = portfolioReturns.length;
const portfolioMean = portfolioReturns.reduce((sum, ret) => sum + ret, 0) / n;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / n;
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < n; i++) {
const portfolioReturn = portfolioReturns[i];
const marketReturn = marketReturns[i];
if (portfolioReturn === undefined || marketReturn === undefined) {
continue;
}
const portfolioDiff = portfolioReturn - portfolioMean;
const marketDiff = marketReturn - marketMean;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
return marketVariance === 0 ? 0 : covariance / marketVariance;
}
/**
* Calculate alpha
*/
export function alpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number = 0
): number {
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
const portfolioBeta = beta(portfolioReturns, marketReturns);
return portfolioMean - (riskFreeRate + portfolioBeta * (marketMean - riskFreeRate));
}
/**
* Calculate Treynor ratio
*/
export function treynorRatio(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number = 0
): number {
const portfolioBeta = beta(portfolioReturns, marketReturns);
if (portfolioBeta === 0) {
return 0;
}
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
return (portfolioMean - riskFreeRate) / portfolioBeta;
}
/**
* Calculate tracking error
*/
export function trackingError(portfolioReturns: number[], benchmarkReturns: number[]): number {
if (portfolioReturns.length !== benchmarkReturns.length || portfolioReturns.length === 0) {
return 0;
}
const activeReturns = portfolioReturns.map((ret, i) => {
const benchmark = benchmarkReturns[i];
return benchmark !== undefined ? ret - benchmark : 0;
});
const mean = activeReturns.reduce((sum, ret) => sum + ret, 0) / activeReturns.length;
const variance =
activeReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) /
(activeReturns.length - 1);
return Math.sqrt(variance);
}
/**
* Calculate volatility (standard deviation of returns)
*/
export function volatility(returns: number[]): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
return Math.sqrt(variance);
}
/**
* Calculate annualized volatility
*/
export function annualizedVolatility(returns: number[], periodsPerYear: number = 252): number {
return volatility(returns) * Math.sqrt(periodsPerYear);
}
/**
* Calculate skewness (measure of asymmetry)
*/
export function skewness(returns: number[]): number {
if (returns.length < 3) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const skew =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
return skew;
}
/**
* Calculate kurtosis (measure of tail heaviness)
*/
export function kurtosis(returns: number[]): number {
if (returns.length < 4) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const kurt =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
return kurt - 3; // Excess kurtosis (subtract 3 for normal distribution baseline)
}
/**
* Calculate comprehensive risk metrics
*/
export function calculateRiskMetrics(
returns: number[],
equityCurve: number[],
marketReturns?: number[],
riskFreeRate: number = 0
): RiskMetrics {
if (returns.length === 0) {
return {
var95: 0,
var99: 0,
cvar95: 0,
maxDrawdown: 0,
volatility: 0,
downside_deviation: 0,
calmar_ratio: 0,
sortino_ratio: 0,
beta: 0,
alpha: 0,
sharpeRatio: 0,
treynorRatio: 0,
trackingError: 0,
informationRatio: 0,
};
}
const portfolioVolatility = volatility(returns);
const portfolioMean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
// Calculate VaR
const var95Value = valueAtRisk(returns, 0.95);
const var99Value = valueAtRisk(returns, 0.99);
const cvar95Value = conditionalValueAtRisk(returns, 0.95);
// Calculate max drawdown
const maxDD = maxDrawdown(equityCurve);
// Calculate downside deviation
const downsideDeviationValue = downsideDeviation(returns);
// Calculate ratios
const calmarRatio = maxDD > 0 ? portfolioMean / maxDD : 0;
const sortinoRatio =
downsideDeviationValue > 0 ? (portfolioMean - riskFreeRate) / downsideDeviationValue : 0;
const sharpeRatio =
portfolioVolatility > 0 ? (portfolioMean - riskFreeRate) / portfolioVolatility : 0;
let portfolioBeta = 0;
let portfolioAlpha = 0;
let portfolioTreynorRatio = 0;
let portfolioTrackingError = 0;
let informationRatio = 0;
if (marketReturns && marketReturns.length === returns.length) {
portfolioBeta = beta(returns, marketReturns);
portfolioAlpha = alpha(returns, marketReturns, riskFreeRate);
portfolioTreynorRatio = treynorRatio(returns, marketReturns, riskFreeRate);
portfolioTrackingError = trackingError(returns, marketReturns);
informationRatio = portfolioTrackingError > 0 ? portfolioAlpha / portfolioTrackingError : 0;
}
return {
var95: var95Value,
var99: var99Value,
cvar95: cvar95Value,
maxDrawdown: maxDD,
volatility: portfolioVolatility,
downside_deviation: downsideDeviationValue,
calmar_ratio: calmarRatio,
sortino_ratio: sortinoRatio,
beta: portfolioBeta,
alpha: portfolioAlpha,
sharpeRatio,
treynorRatio: portfolioTreynorRatio,
trackingError: portfolioTrackingError,
informationRatio,
};
}
/**
* Helper function to get Z-score for confidence level
* This implementation handles arbitrary confidence levels
*/
function getZScore(confidenceLevel: number): number {
// First check our lookup table for common values (more precise)
const zScores: { [key: string]: number } = {
'0.90': 1.282,
'0.95': 1.645,
'0.975': 1.96,
'0.99': 2.326,
'0.995': 2.576,
};
const key = confidenceLevel.toString();
if (zScores[key]) {
return zScores[key];
}
// For arbitrary confidence levels, use approximation
if (confidenceLevel < 0.5) {
return -getZScore(1 - confidenceLevel);
}
if (confidenceLevel >= 0.999) {
return 3.09;
} // Cap at 99.9% for numerical stability
// Approximation of inverse normal CDF
const y = Math.sqrt(-2.0 * Math.log(1.0 - confidenceLevel));
return (
y -
(2.515517 + 0.802853 * y + 0.010328 * y * y) /
(1.0 + 1.432788 * y + 0.189269 * y * y + 0.001308 * y * y * y)
);
}
/**
* Calculate portfolio risk contribution
*/
export function riskContribution(
weights: number[],
covarianceMatrix: number[][],
portfolioVolatility: number
): number[] {
const n = weights.length;
const contributions: number[] = [];
for (let i = 0; i < n; i++) {
let marginalContribution = 0;
const row = covarianceMatrix[i];
if (!row) {
continue;
}
for (let j = 0; j < n; j++) {
const weight = weights[j];
const covariance = row[j];
if (weight !== undefined && covariance !== undefined) {
marginalContribution += weight * covariance;
}
}
const weight = weights[i];
if (weight !== undefined && portfolioVolatility !== 0) {
const contribution = (weight * marginalContribution) / Math.pow(portfolioVolatility, 2);
contributions.push(contribution);
}
}
return contributions;
}
/**
* Calculate Ulcer Index
*/
export function ulcerIndex(equityCurve: Array<{ value: number; date: Date }>): number {
if (equityCurve.length === 0) {
return 0;
}
let sumSquaredDrawdown = 0;
const first = equityCurve[0];
if (!first) {
return 0;
}
let peak = first.value;
for (const point of equityCurve) {
peak = Math.max(peak, point.value);
const drawdownPercent = ((peak - point.value) / peak) * 100;
sumSquaredDrawdown += drawdownPercent * drawdownPercent;
}
return Math.sqrt(sumSquaredDrawdown / equityCurve.length);
}
/**
* Calculate risk-adjusted return (RAR)
*/
export function riskAdjustedReturn(
portfolioReturn: number,
portfolioRisk: number,
riskFreeRate: number = 0
): number {
if (portfolioRisk === 0) {
return 0;
}
return (portfolioReturn - riskFreeRate) / portfolioRisk;
}

File diff suppressed because it is too large Load diff

View file

@ -1,55 +0,0 @@
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<string, object> = {
'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
);
}
});
});

View file

@ -1,83 +0,0 @@
export class CacheKeyGenerator {
/**
* Generate cache key for market data
*/
static marketData(symbol: string, timeframe: string, date?: Date): string {
const dateStr = date ? date.toISOString().split('T')[0] : 'latest';
return `market:${symbol.toLowerCase()}:${timeframe}:${dateStr}`;
}
/**
* Generate cache key for technical indicators
*/
static indicator(symbol: string, indicator: string, period: number, dataHash: string): string {
return `indicator:${symbol.toLowerCase()}:${indicator}:${period}:${dataHash}`;
}
/**
* Generate cache key for backtest results
*/
static backtest(strategyName: string, params: Record<string, unknown>): string {
const paramHash = this.hashObject(params);
return `backtest:${strategyName}:${paramHash}`;
}
/**
* Generate cache key for strategy results
*/
static strategy(strategyName: string, symbol: string, timeframe: string): string {
return `strategy:${strategyName}:${symbol.toLowerCase()}:${timeframe}`;
}
/**
* Generate cache key for user sessions
*/
static userSession(userId: string): string {
return `session:${userId}`;
}
/**
* Generate cache key for portfolio data
*/
static portfolio(userId: string, portfolioId: string): string {
return `portfolio:${userId}:${portfolioId}`;
}
/**
* Generate cache key for real-time prices
*/
static realtimePrice(symbol: string): string {
return `price:realtime:${symbol.toLowerCase()}`;
}
/**
* Generate cache key for order book data
*/
static orderBook(symbol: string, depth: number = 10): string {
return `orderbook:${symbol.toLowerCase()}:${depth}`;
}
/**
* Create a simple hash from object for cache keys
*/
private static hashObject(obj: Record<string, unknown>): string {
const str = JSON.stringify(obj, Object.keys(obj).sort());
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString(36);
}
}
/**
* Simple key generator function
*/
export function generateKey(...parts: (string | number | boolean | undefined)[]): string {
return parts
.filter(part => part !== undefined)
.map(part => String(part))
.join(':');
}

View file

@ -41,7 +41,7 @@ export class NamespacedCache implements CacheProvider {
// Clear only keys with this namespace prefix
const keys = await this.cache.keys(`${this.prefix}*`);
if (keys.length > 0) {
await Promise.all(keys.map(key => this.cache.del(key.substring(this.prefix.length))));
await Promise.all(keys.map(key => this.cache.del(key)));
}
}

View file

@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { CacheFactory, createNamespacedCache } from '../src/cache-factory';
import { generateKey } from '../src/key-generator';
import type { ICache } from '../src/types';
describe('CacheFactory', () => {
@ -89,25 +88,3 @@ describe('NamespacedCache', () => {
expect(keys).toEqual(['key1', 'key2']);
});
});
describe('KeyGenerator', () => {
it('should generate key from parts', () => {
const key = generateKey('part1', 'part2', 'part3');
expect(key).toBe('part1:part2:part3');
});
it('should handle empty parts', () => {
const key = generateKey();
expect(key).toBe('');
});
it('should skip undefined parts', () => {
const key = generateKey('part1', undefined, 'part3');
expect(key).toBe('part1:part3');
});
it('should convert non-string parts', () => {
const key = generateKey('prefix', 123, true);
expect(key).toBe('prefix:123:true');
});
});

View file

@ -1,220 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { CacheKeyGenerator, generateKey } from '../src/key-generator';
describe('CacheKeyGenerator', () => {
describe('marketData', () => {
it('should generate key with symbol, timeframe and date', () => {
const date = new Date('2024-01-15T10:30:00Z');
const key = CacheKeyGenerator.marketData('AAPL', '1h', date);
expect(key).toBe('market:aapl:1h:2024-01-15');
});
it('should generate key with "latest" when no date provided', () => {
const key = CacheKeyGenerator.marketData('MSFT', '1d');
expect(key).toBe('market:msft:1d:latest');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.marketData('GOOGL', '5m');
expect(key).toBe('market:googl:5m:latest');
});
it('should handle different timeframes', () => {
expect(CacheKeyGenerator.marketData('TSLA', '1m')).toBe('market:tsla:1m:latest');
expect(CacheKeyGenerator.marketData('TSLA', '15m')).toBe('market:tsla:15m:latest');
expect(CacheKeyGenerator.marketData('TSLA', '1w')).toBe('market:tsla:1w:latest');
});
});
describe('indicator', () => {
it('should generate key with all parameters', () => {
const key = CacheKeyGenerator.indicator('AAPL', 'RSI', 14, 'abc123');
expect(key).toBe('indicator:aapl:RSI:14:abc123');
});
it('should lowercase the symbol but not indicator name', () => {
const key = CacheKeyGenerator.indicator('META', 'MACD', 20, 'hash456');
expect(key).toBe('indicator:meta:MACD:20:hash456');
});
it('should handle different period values', () => {
expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 50, 'hash1')).toBe(
'indicator:amzn:SMA:50:hash1'
);
expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 200, 'hash2')).toBe(
'indicator:amzn:SMA:200:hash2'
);
});
});
describe('backtest', () => {
it('should generate key with strategy name and hashed params', () => {
const params = { stopLoss: 0.02, takeProfit: 0.05 };
const key = CacheKeyGenerator.backtest('MomentumStrategy', params);
expect(key).toMatch(/^backtest:MomentumStrategy:[a-z0-9]+$/);
});
it('should generate same hash for same params regardless of order', () => {
const params1 = { a: 1, b: 2, c: 3 };
const params2 = { c: 3, a: 1, b: 2 };
const key1 = CacheKeyGenerator.backtest('Strategy', params1);
const key2 = CacheKeyGenerator.backtest('Strategy', params2);
expect(key1).toBe(key2);
});
it('should generate different hashes for different params', () => {
const params1 = { threshold: 0.01 };
const params2 = { threshold: 0.02 };
const key1 = CacheKeyGenerator.backtest('Strategy', params1);
const key2 = CacheKeyGenerator.backtest('Strategy', params2);
expect(key1).not.toBe(key2);
});
it('should handle complex nested params', () => {
const params = {
indicators: { rsi: { period: 14 }, macd: { fast: 12, slow: 26 } },
risk: { maxDrawdown: 0.1 },
};
const key = CacheKeyGenerator.backtest('ComplexStrategy', params);
expect(key).toMatch(/^backtest:ComplexStrategy:[a-z0-9]+$/);
});
});
describe('strategy', () => {
it('should generate key with strategy name, symbol and timeframe', () => {
const key = CacheKeyGenerator.strategy('TrendFollowing', 'NVDA', '4h');
expect(key).toBe('strategy:TrendFollowing:nvda:4h');
});
it('should lowercase the symbol but not strategy name', () => {
const key = CacheKeyGenerator.strategy('MeanReversion', 'AMD', '1d');
expect(key).toBe('strategy:MeanReversion:amd:1d');
});
});
describe('userSession', () => {
it('should generate key with userId', () => {
const key = CacheKeyGenerator.userSession('user123');
expect(key).toBe('session:user123');
});
it('should handle different userId formats', () => {
expect(CacheKeyGenerator.userSession('uuid-123-456')).toBe('session:uuid-123-456');
expect(CacheKeyGenerator.userSession('email@example.com')).toBe('session:email@example.com');
});
});
describe('portfolio', () => {
it('should generate key with userId and portfolioId', () => {
const key = CacheKeyGenerator.portfolio('user123', 'portfolio456');
expect(key).toBe('portfolio:user123:portfolio456');
});
it('should handle UUID format IDs', () => {
const key = CacheKeyGenerator.portfolio(
'550e8400-e29b-41d4-a716-446655440000',
'6ba7b810-9dad-11d1-80b4-00c04fd430c8'
);
expect(key).toBe(
'portfolio:550e8400-e29b-41d4-a716-446655440000:6ba7b810-9dad-11d1-80b4-00c04fd430c8'
);
});
});
describe('realtimePrice', () => {
it('should generate key with symbol', () => {
const key = CacheKeyGenerator.realtimePrice('BTC');
expect(key).toBe('price:realtime:btc');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.realtimePrice('ETH-USD');
expect(key).toBe('price:realtime:eth-usd');
});
});
describe('orderBook', () => {
it('should generate key with symbol and default depth', () => {
const key = CacheKeyGenerator.orderBook('BTC');
expect(key).toBe('orderbook:btc:10');
});
it('should generate key with custom depth', () => {
const key = CacheKeyGenerator.orderBook('ETH', 20);
expect(key).toBe('orderbook:eth:20');
});
it('should lowercase the symbol', () => {
const key = CacheKeyGenerator.orderBook('USDT', 5);
expect(key).toBe('orderbook:usdt:5');
});
});
describe('hashObject', () => {
it('should generate consistent hashes', () => {
const params = { x: 1, y: 2 };
const key1 = CacheKeyGenerator.backtest('Test', params);
const key2 = CacheKeyGenerator.backtest('Test', params);
expect(key1).toBe(key2);
});
it('should handle empty objects', () => {
const key = CacheKeyGenerator.backtest('Empty', {});
expect(key).toMatch(/^backtest:Empty:[a-z0-9]+$/);
});
it('should handle arrays in objects', () => {
const params = { symbols: ['AAPL', 'MSFT'], periods: [10, 20, 30] };
const key = CacheKeyGenerator.backtest('ArrayTest', params);
expect(key).toMatch(/^backtest:ArrayTest:[a-z0-9]+$/);
});
it('should handle null and undefined values', () => {
const params = { a: null, b: undefined, c: 'value' };
const key = CacheKeyGenerator.backtest('NullTest', params);
expect(key).toMatch(/^backtest:NullTest:[a-z0-9]+$/);
});
});
});
describe('generateKey', () => {
it('should join parts with colons', () => {
const key = generateKey('user', 123, 'data');
expect(key).toBe('user:123:data');
});
it('should filter undefined values', () => {
const key = generateKey('prefix', undefined, 'suffix');
expect(key).toBe('prefix:suffix');
});
it('should convert all types to strings', () => {
const key = generateKey('bool', true, 'num', 42, 'str', 'text');
expect(key).toBe('bool:true:num:42:str:text');
});
it('should handle empty input', () => {
const key = generateKey();
expect(key).toBe('');
});
it('should handle single part', () => {
const key = generateKey('single');
expect(key).toBe('single');
});
it('should handle all undefined values', () => {
const key = generateKey(undefined, undefined, undefined);
expect(key).toBe('');
});
it('should handle boolean false', () => {
const key = generateKey('flag', false, 'end');
expect(key).toBe('flag:false:end');
});
it('should handle zero', () => {
const key = generateKey('count', 0, 'items');
expect(key).toBe('count:0:items');
});
});

View file

@ -189,9 +189,9 @@ describe('NamespacedCache', () => {
expect(mockCache.keys).toHaveBeenCalledWith('test-namespace:*');
expect(mockCache.del).toHaveBeenCalledTimes(3);
expect(mockCache.del).toHaveBeenCalledWith('key1');
expect(mockCache.del).toHaveBeenCalledWith('key2');
expect(mockCache.del).toHaveBeenCalledWith('key3');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key1');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key2');
expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key3');
});
it('should handle empty namespace', async () => {

View file

@ -1,50 +0,0 @@
# Environment
NODE_ENV=development
# Service Configuration
STOCKBOT_SERVICE_NAME=stock-bot-service
STOCKBOT_SERVICE_PORT=3000
# Database Configuration
STOCKBOT_DATABASE_POSTGRES_HOST=localhost
STOCKBOT_DATABASE_POSTGRES_PORT=5432
STOCKBOT_DATABASE_POSTGRES_DATABASE=stockbot
STOCKBOT_DATABASE_POSTGRES_USER=postgres
STOCKBOT_DATABASE_POSTGRES_PASSWORD=postgres
STOCKBOT_DATABASE_QUESTDB_HOST=localhost
STOCKBOT_DATABASE_QUESTDB_ILP_PORT=9009
STOCKBOT_DATABASE_QUESTDB_HTTP_PORT=9000
STOCKBOT_DATABASE_MONGODB_HOST=localhost
STOCKBOT_DATABASE_MONGODB_PORT=27017
STOCKBOT_DATABASE_MONGODB_DATABASE=stockbot
STOCKBOT_DATABASE_DRAGONFLY_HOST=localhost
STOCKBOT_DATABASE_DRAGONFLY_PORT=6379
# Provider Configuration
STOCKBOT_PROVIDERS_EOD_API_KEY=your_eod_api_key
STOCKBOT_PROVIDERS_EOD_ENABLED=true
STOCKBOT_PROVIDERS_IB_ENABLED=false
STOCKBOT_PROVIDERS_IB_GATEWAY_HOST=localhost
STOCKBOT_PROVIDERS_IB_GATEWAY_PORT=5000
STOCKBOT_PROVIDERS_IB_ACCOUNT=your_account_id
STOCKBOT_PROVIDERS_QM_ENABLED=false
STOCKBOT_PROVIDERS_QM_USERNAME=your_username
STOCKBOT_PROVIDERS_QM_PASSWORD=your_password
STOCKBOT_PROVIDERS_QM_WEBMASTER_ID=your_webmaster_id
# Logging
STOCKBOT_LOGGING_LEVEL=info
STOCKBOT_LOGGING_LOKI_ENABLED=false
STOCKBOT_LOGGING_LOKI_HOST=localhost
STOCKBOT_LOGGING_LOKI_PORT=3100
# HTTP Proxy (optional)
STOCKBOT_HTTP_PROXY_ENABLED=false
STOCKBOT_HTTP_PROXY_URL=http://proxy.example.com:8080
STOCKBOT_HTTP_PROXY_AUTH_USERNAME=username
STOCKBOT_HTTP_PROXY_AUTH_PASSWORD=password

View file

@ -1,94 +0,0 @@
{
"name": "stock-bot",
"version": "1.0.0",
"debug": false,
"service": {
"name": "stock-bot-service",
"port": 3000,
"host": "0.0.0.0",
"healthCheckPath": "/health",
"metricsPath": "/metrics",
"shutdownTimeout": 30000,
"cors": {
"enabled": true,
"origin": "*",
"credentials": true
}
},
"logging": {
"level": "info",
"format": "json",
"loki": {
"enabled": false,
"host": "localhost",
"port": 3100,
"labels": {}
}
},
"database": {
"postgres": {
"host": "localhost",
"port": 5432,
"database": "stockbot",
"user": "postgres",
"password": "postgres",
"ssl": false,
"poolSize": 10,
"connectionTimeout": 30000,
"idleTimeout": 10000
},
"questdb": {
"host": "localhost",
"ilpPort": 9009,
"httpPort": 9000,
"pgPort": 8812,
"database": "questdb",
"user": "admin",
"password": "quest",
"bufferSize": 65536,
"flushInterval": 1000
},
"mongodb": {
"host": "localhost",
"port": 27017,
"database": "stockbot",
"authSource": "admin",
"poolSize": 10
},
"dragonfly": {
"host": "localhost",
"port": 6379,
"db": 0,
"maxRetries": 3,
"retryDelay": 100
}
},
"queue": {
"redis": {
"host": "localhost",
"port": 6379,
"db": 0
},
"defaultJobOptions": {
"attempts": 3,
"backoff": {
"type": "exponential",
"delay": 1000
},
"removeOnComplete": 100,
"removeOnFail": 100
}
},
"http": {
"timeout": 30000,
"retries": 3,
"retryDelay": 1000,
"proxy": {
"enabled": false
}
},
"webshare": {
"apiKey": "",
"apiUrl": "https://proxy.webshare.io/api/v2/"
}
}

View file

@ -1,48 +0,0 @@
{
"debug": true,
"logging": {
"level": "debug",
"format": "pretty"
},
"providers": {
"eod": {
"name": "eod-historical-data",
"enabled": true,
"priority": 1,
"apiKey": "demo",
"tier": "free",
"rateLimit": {
"maxRequests": 20,
"windowMs": 60000
}
},
"yahoo": {
"name": "yahoo-finance",
"enabled": true,
"priority": 2,
"rateLimit": {
"maxRequests": 100,
"windowMs": 60000
}
},
"ib": {
"name": "interactive-brokers",
"enabled": false,
"priority": 0,
"gateway": {
"host": "localhost",
"port": 5000,
"clientId": 1
},
"marketDataType": "delayed"
},
"qm": {
"name": "quotemedia",
"enabled": false,
"priority": 3,
"username": "",
"password": "",
"webmasterId": ""
}
}
}

View file

@ -1,32 +0,0 @@
{
"debug": false,
"logging": {
"level": "warn",
"format": "json",
"loki": {
"enabled": true,
"labels": {
"app": "stock-bot",
"env": "production"
}
}
},
"database": {
"postgres": {
"ssl": true,
"poolSize": 20
},
"questdb": {
"bufferSize": 131072,
"flushInterval": 500
},
"mongodb": {
"poolSize": 20
}
},
"http": {
"timeout": 60000,
"retries": 5,
"retryDelay": 2000
}
}

View file

@ -1,42 +0,0 @@
{
"debug": true,
"logging": {
"level": "error",
"format": "json"
},
"service": {
"port": 0,
"shutdownTimeout": 5000
},
"database": {
"postgres": {
"database": "stockbot_test",
"poolSize": 5
},
"questdb": {
"database": "questdb_test"
},
"mongodb": {
"database": "stockbot_test",
"poolSize": 5
},
"dragonfly": {
"db": 15,
"keyPrefix": "test:"
}
},
"queue": {
"redis": {
"db": 15
},
"defaultJobOptions": {
"attempts": 1,
"removeOnComplete": 100,
"removeOnFail": 100
}
},
"http": {
"timeout": 5000,
"retries": 1
}
}

View file

@ -14,13 +14,7 @@
"build": "tsc",
"dev": "tsc --watch",
"test": "bun test",
"clean": "rm -rf dist",
"cli": "bun run src/cli.ts",
"validate": "bun run src/cli.ts --validate",
"check": "bun run src/cli.ts --check"
},
"bin": {
"config-cli": "./dist/cli.js"
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/logger": "workspace:*",

View file

@ -1,175 +0,0 @@
#!/usr/bin/env bun
/* eslint-disable no-console */
import { join } from 'path';
import { parseArgs } from 'util';
import { redactSecrets } from './utils/secrets';
import {
checkRequiredEnvVars,
formatValidationResult,
validateCompleteness,
validateConfig,
} from './utils/validation';
import { ConfigManager } from './config-manager';
import { baseAppSchema } from './schemas';
import type { Environment } from './types';
interface CliOptions {
config?: string;
env?: string;
validate?: boolean;
show?: boolean;
check?: boolean;
json?: boolean;
help?: boolean;
}
const REQUIRED_PATHS = [
'service.name',
'service.port',
'database.postgres.host',
'database.postgres.database',
];
const REQUIRED_ENV_VARS = ['NODE_ENV'];
const SECRET_PATHS = [
'database.postgres.password',
'database.mongodb.uri',
'providers.quoteMedia.apiKey',
'providers.interactiveBrokers.clientId',
];
function printUsage() {
console.log(`
Stock Bot Configuration CLI
Usage: bun run config-cli [options]
Options:
--config <path> Path to config directory (default: ./config)
--env <env> Environment to use (development, test, production)
--validate Validate configuration against schema
--show Show current configuration (secrets redacted)
--check Run all configuration checks
--json Output in JSON format
--help Show this help message
Examples:
# Validate configuration
bun run config-cli --validate
# Show configuration for production
bun run config-cli --env production --show
# Run all checks
bun run config-cli --check
# Output configuration as JSON
bun run config-cli --show --json
`);
}
async function main() {
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
config: { type: 'string' },
env: { type: 'string' },
validate: { type: 'boolean' },
show: { type: 'boolean' },
check: { type: 'boolean' },
json: { type: 'boolean' },
help: { type: 'boolean' },
},
}) as { values: CliOptions };
if (values.help) {
printUsage();
process.exit(0);
}
const configPath = values.config || join(process.cwd(), 'config');
const environment = values.env as Environment;
try {
const manager = new ConfigManager({
configPath,
environment,
});
const config = await manager.initialize(baseAppSchema);
if (values.validate) {
const result = validateConfig(config, baseAppSchema);
if (values.json) {
console.log(JSON.stringify(result, null, 2));
} else {
console.log(formatValidationResult(result));
}
process.exit(result.valid ? 0 : 1);
}
if (values.show) {
const redacted = redactSecrets(config, SECRET_PATHS);
if (values.json) {
console.log(JSON.stringify(redacted, null, 2));
} else {
console.log('Current Configuration:');
console.log(JSON.stringify(redacted, null, 2));
}
}
if (values.check) {
console.log('Running configuration checks...\n');
// Schema validation
console.log('1. Schema Validation:');
const schemaResult = validateConfig(config, baseAppSchema);
console.log(formatValidationResult(schemaResult));
console.log();
// Environment variables
console.log('2. Required Environment Variables:');
const envResult = checkRequiredEnvVars(REQUIRED_ENV_VARS);
console.log(formatValidationResult(envResult));
console.log();
// Required paths
console.log('3. Required Configuration Paths:');
const pathResult = validateCompleteness(config, REQUIRED_PATHS);
console.log(formatValidationResult(pathResult));
console.log();
// Overall result
const allValid = schemaResult.valid && envResult.valid && pathResult.valid;
if (allValid) {
console.log('✅ All configuration checks passed!');
process.exit(0);
} else {
console.log('❌ Some configuration checks failed');
process.exit(1);
}
}
if (!values.validate && !values.show && !values.check) {
console.log('No action specified. Use --help for usage information.');
process.exit(1);
}
} catch (error) {
if (values.json) {
console.error(JSON.stringify({ error: String(error) }));
} else {
console.error('Error:', error);
}
process.exit(1);
}
}
// Run CLI
if (import.meta.main) {
main();
}

View file

@ -1,9 +1,9 @@
import { join } from 'path';
import { z } from 'zod';
import { getLogger } from '@stock-bot/logger';
import { ConfigError, ConfigValidationError } from './errors';
import { EnvLoader } from './loaders/env.loader';
import { FileLoader } from './loaders/file.loader';
import { ConfigError, ConfigValidationError } from './errors';
import type {
ConfigLoader,
ConfigManagerOptions,
@ -21,8 +21,9 @@ export class ConfigManager<T = Record<string, unknown>> {
private environment: Environment;
private schema?: ConfigSchema;
constructor(options: ConfigManagerOptions = {}) {
constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) {
this.environment = options.environment || this.detectEnvironment();
this.schema = defaultSchema;
if (options.loaders) {
this.loaders = options.loaders;
@ -32,20 +33,17 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Initialize the configuration by loading from all sources
*/
initialize(schema?: ConfigSchema): T {
if (this.config) {
return this.config;
}
this.schema = schema;
if (schema) {
this.schema = schema;
}
// Sort loaders by priority (higher priority last)
const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority);
// Load configurations from all sources
const configs: Record<string, unknown>[] = [];
for (const loader of sortedLoaders) {
const config = loader.load();
@ -54,10 +52,8 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
// Merge all configurations
const mergedConfig = this.merge(...configs) as T;
// Add environment if not present
if (
typeof mergedConfig === 'object' &&
mergedConfig !== null &&
@ -66,7 +62,6 @@ export class ConfigManager<T = Record<string, unknown>> {
(mergedConfig as Record<string, unknown>)['environment'] = this.environment;
}
// Validate if schema provided
if (this.schema) {
try {
this.config = this.schema.parse(mergedConfig) as T;
@ -90,9 +85,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return this.config;
}
/**
* Get the current configuration
*/
get(): T {
if (!this.config) {
throw new ConfigError('Configuration not initialized. Call initialize() first.');
@ -100,9 +92,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return this.config;
}
/**
* Get a specific configuration value by path
*/
getValue<R = unknown>(path: string): R {
const config = this.get();
const keys = path.split('.');
@ -119,9 +108,6 @@ export class ConfigManager<T = Record<string, unknown>> {
return value as R;
}
/**
* Check if a configuration path exists
*/
has(path: string): boolean {
try {
this.getValue(path);
@ -131,9 +117,6 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Update configuration at runtime
*/
set(updates: DeepPartial<T>): void {
if (!this.config) {
throw new ConfigError('Configuration not initialized. Call initialize() first.');
@ -161,23 +144,14 @@ export class ConfigManager<T = Record<string, unknown>> {
}
}
/**
* Get the current environment
*/
getEnvironment(): Environment {
return this.environment;
}
/**
* Reset configuration
*/
reset(): void {
this.config = null;
}
/**
* Validate configuration against a schema
*/
validate<S extends ConfigSchema>(schema: S): z.infer<S> {
const config = this.get();
return schema.parse(config);
@ -201,11 +175,12 @@ export class ConfigManager<T = Record<string, unknown>> {
}
/**
* Deep merge with circular reference handling
* Deep merge tracking only active ancestor objects so valid shared DAG references
* (e.g. redis = database.dragonfly) are preserved rather than replaced with '[Circular]'.
*/
private merge(...objects: Record<string, unknown>[]): Record<string, unknown> {
const seen = new WeakSet();
const ancestors = new WeakSet<object>();
const mergeRecursive = (...objs: Record<string, unknown>[]): Record<string, unknown> => {
const result: Record<string, unknown> = {};
@ -219,17 +194,21 @@ export class ConfigManager<T = Record<string, unknown>> {
!(value instanceof Date) &&
!(value instanceof RegExp)
) {
// Check for circular reference
if (seen.has(value)) {
if (ancestors.has(value)) {
result[key] = '[Circular]';
continue;
}
seen.add(value);
result[key] = mergeRecursive(
(result[key] as Record<string, unknown>) || {},
value as Record<string, unknown>
);
ancestors.add(value);
try {
result[key] = mergeRecursive(
(result[key] && typeof result[key] === 'object' && !Array.isArray(result[key])
? (result[key] as Record<string, unknown>)
: {}),
value as Record<string, unknown>
);
} finally {
ancestors.delete(value);
}
} else {
result[key] = value;
}
@ -238,7 +217,7 @@ export class ConfigManager<T = Record<string, unknown>> {
return result;
};
return mergeRecursive(...objects);
}
}

View file

@ -1,14 +1,10 @@
import { ConfigManager, type ConfigManagerOptions } from './config-manager';
import type { ConfigSchema } from './types';
// Export only what's actually used
export { ConfigManager } from './config-manager';
export type { ConfigManagerOptions } from './config-manager';
export { toUnifiedConfig } from './schemas/unified-app.schema';
// Export used types
export type { BaseAppConfig, UnifiedAppConfig } from './schemas';
// Export schemas that are used by apps
export {
baseAppSchema,
dragonflyConfigSchema,
@ -24,33 +20,13 @@ export {
type ProviderName,
} from './schemas';
// createAppConfig function for apps/stock
export function createAppConfig<T>(
schema: unknown,
options?: ConfigManagerOptions
): ConfigManager<T> {
return new ConfigManager<T>(options);
const zodSchema =
schema && typeof schema === 'object' && 'parse' in schema
? (schema as ConfigSchema)
: undefined;
return new ConfigManager<T>(options, zodSchema);
}
// Export utilities
export {
SecretValue,
secret,
isSecret,
isSecretEnvVar,
COMMON_SECRET_PATTERNS,
redactSecrets,
wrapSecretEnvVars,
secretSchema,
secretStringSchema
} from './utils/secrets';
export {
checkRequiredEnvVars,
createStrictSchema,
formatValidationResult,
mergeSchemas,
validateConfig,
validateCompleteness,
type ValidationResult
} from './utils/validation';

View file

@ -10,7 +10,7 @@ interface EnvLoaderOptions {
}
export class EnvLoader implements ConfigLoader {
readonly priority = 100; // Highest priority
readonly priority = 100;
constructor(
private prefix = '',
@ -27,10 +27,12 @@ export class EnvLoader implements ConfigLoader {
load(): Record<string, unknown> {
try {
// Load root .env file - try multiple possible locations
// Stop on the first .env file found so repo-root runs never traverse into parent directories
const possiblePaths = ['./.env', '../.env', '../../.env', '../../../.env'];
for (const path of possiblePaths) {
this.loadEnvFile(path);
if (this.loadEnvFile(path)) {
break;
}
}
const config: Record<string, unknown> = {};
@ -44,10 +46,8 @@ export class EnvLoader implements ConfigLoader {
const configKey = this.prefix ? key.slice(this.prefix.length) : key;
if (!this.options.convertCase && !this.options.nestedDelimiter) {
// Simple case - just keep the key as is
config[configKey] = this.parseValue(value || '');
} else {
// Handle nested structure or case conversion
this.setConfigValue(config, configKey, value || '');
}
}
@ -60,22 +60,19 @@ export class EnvLoader implements ConfigLoader {
private setConfigValue(config: Record<string, unknown>, key: string, value: string): void {
try {
// Handle provider-specific environment variables (only for application usage, not tests)
if (!this.prefix && !this.options.convertCase) {
const providerMapping = this.getProviderMapping(key);
if (providerMapping) {
// For certain fields, we need to preserve the string value
const shouldPreserveString = this.shouldPreserveStringForKey(key);
const parsedValue = shouldPreserveString ? value : this.parseValue(value);
this.setNestedValue(config, providerMapping.path, parsedValue);
this.setNestedValue(config, [...providerMapping.path], parsedValue);
return;
}
}
const parsedValue = this.parseValue(value);
const parsedValue = this.shouldPreserveStringForKey(key) ? value : this.parseValue(value);
if (this.options.convertCase) {
// Convert to camelCase
const camelKey = this.toCamelCase(key);
config[camelKey] = parsedValue;
} else if (
@ -83,32 +80,26 @@ export class EnvLoader implements ConfigLoader {
this.options.nestedDelimiter !== '_' &&
key.includes(this.options.nestedDelimiter)
) {
// Handle nested delimiter (e.g., APP__NAME -> { APP: { NAME: value } })
const parts = key.split(this.options.nestedDelimiter);
this.setNestedValue(config, parts, parsedValue);
} else if (key.includes('_')) {
const path = key.toLowerCase().split('_');
this.setNestedValue(config, path, parsedValue);
} else {
// Convert to nested structure based on underscores, or keep as-is if no underscores
if (key.includes('_')) {
const path = key.toLowerCase().split('_');
this.setNestedValue(config, path, parsedValue);
} else {
// Single key without underscores - keep original case
config[key] = parsedValue;
}
config[key] = parsedValue;
}
} catch {
// Skip environment variables that can't be set (readonly properties)
// This is expected behavior for system environment variables
// Skip environment variables that cannot be set on readonly target keys
}
}
private setNestedValue(obj: Record<string, unknown>, path: string[], value: unknown): boolean {
if (path.length === 0) {
return false; // Cannot set value on empty path
return false;
}
const lastKey = path.pop();
if (!lastKey) {
return false; // This should never happen due to length check above
return false;
}
try {
@ -122,7 +113,6 @@ export class EnvLoader implements ConfigLoader {
(target as Record<string, unknown>)[lastKey] = value;
return true;
} catch {
// If we can't assign to any property (readonly), skip this env var silently
return false;
}
}
@ -132,22 +122,19 @@ export class EnvLoader implements ConfigLoader {
}
private shouldPreserveStringForKey(key: string): boolean {
// Keys that should preserve string values even if they look like numbers
const preserveStringKeys = [
'QM_WEBMASTER_ID',
'IB_MARKET_DATA_TYPE',
'MONGODB_URI',
'MONGODB_READ_URI',
'MONGODB_PASSWORD',
'POSTGRES_PASSWORD',
'DRAGONFLY_PASSWORD',
'QUESTDB_PASSWORD',
];
return preserveStringKeys.includes(key);
if (preserveStringKeys.includes(key)) {
return true;
}
return /(?:^|_)(?:PASSWORD|SECRET|TOKEN|API_KEY|URI)$/i.test(key);
}
private getProviderMapping(envKey: string): { path: string[] } | null {
// Provider-specific and special environment variable mappings
const providerMappings: Record<string, string[]> = {
// Database mappings
MONGODB_URI: ['database', 'mongodb', 'uri'],
@ -167,8 +154,25 @@ export class EnvLoader implements ConfigLoader {
DRAGONFLY_HOST: ['database', 'dragonfly', 'host'],
DRAGONFLY_PORT: ['database', 'dragonfly', 'port'],
DRAGONFLY_PASSWORD: ['database', 'dragonfly', 'password'],
QUESTDB_ENABLED: ['database', 'questdb', 'enabled'],
QUESTDB_HOST: ['database', 'questdb', 'host'],
QUESTDB_PORT: ['database', 'questdb', 'httpPort'],
QUESTDB_HTTP_PORT: ['database', 'questdb', 'httpPort'],
QUESTDB_PG_PORT: ['database', 'questdb', 'pgPort'],
QUESTDB_ILP_PORT: ['database', 'questdb', 'ilpPort'],
QUESTDB_INFLUX_PORT: ['database', 'questdb', 'influxPort'],
QUESTDB_USER: ['database', 'questdb', 'user'],
QUESTDB_PASSWORD: ['database', 'questdb', 'password'],
// Queue mappings
QUEUE_ENABLED: ['queue', 'enabled'],
QUEUE_ENABLE_SCHEDULED_JOBS: ['queue', 'enableScheduledJobs'],
QUEUE_WORKERS: ['queue', 'workers'],
QUEUE_CONCURRENCY: ['queue', 'concurrency'],
QUEUE_REDIS_HOST: ['queue', 'redis', 'host'],
QUEUE_REDIS_PORT: ['queue', 'redis', 'port'],
QUEUE_REDIS_PASSWORD: ['queue', 'redis', 'password'],
QUEUE_REDIS_DB: ['queue', 'redis', 'db'],
// WebShare provider mappings
WEBSHARE_API_KEY: ['webshare', 'apiKey'],
@ -210,7 +214,7 @@ export class EnvLoader implements ConfigLoader {
NAME: ['name'],
VERSION: ['version'],
// Log mappings (using LOG_ prefix for all)
// Log mappings
LOG_LEVEL: ['log', 'level'],
LOG_FORMAT: ['log', 'format'],
LOG_HIDE_OBJECT: ['log', 'hideObject'],
@ -218,7 +222,6 @@ export class EnvLoader implements ConfigLoader {
LOG_LOKI_HOST: ['log', 'loki', 'host'],
LOG_LOKI_PORT: ['log', 'loki', 'port'],
// Special mappings to avoid conflicts
DEBUG_MODE: ['debug'],
};
@ -231,12 +234,11 @@ export class EnvLoader implements ConfigLoader {
return value;
}
// Try to parse as JSON first if enabled
if (this.options.parseJson) {
try {
return JSON.parse(value);
} catch {
// Not JSON, continue with other parsing
// Not JSON, continue
}
}
@ -244,7 +246,6 @@ export class EnvLoader implements ConfigLoader {
return value;
}
// Handle booleans
if (value.toLowerCase() === 'true') {
return true;
}
@ -252,7 +253,6 @@ export class EnvLoader implements ConfigLoader {
return false;
}
// Handle numbers (but preserve strings with leading zeros or plus signs)
if (!/^[+-]/.test(value) && !/^0\d/.test(value)) {
const num = Number(value);
if (!isNaN(num) && value !== '') {
@ -260,7 +260,6 @@ export class EnvLoader implements ConfigLoader {
}
}
// Handle null/undefined
if (value.toLowerCase() === 'null') {
return null;
}
@ -268,11 +267,10 @@ export class EnvLoader implements ConfigLoader {
return undefined;
}
// Return as string
return value;
}
private loadEnvFile(filePath: string): void {
private loadEnvFile(filePath: string): boolean {
try {
const envContent = readFileSync(filePath, 'utf-8');
const lines = envContent.split('\n');
@ -280,18 +278,20 @@ export class EnvLoader implements ConfigLoader {
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) {
continue; // Skip empty lines and comments
continue;
}
const equalIndex = trimmed.indexOf('=');
if (equalIndex === -1) {
continue; // Skip lines without =
continue;
}
const key = trimmed.substring(0, equalIndex).trim();
if (!key) {
continue;
}
let value = trimmed.substring(equalIndex + 1).trim();
// Remove surrounding quotes if present
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
@ -299,13 +299,12 @@ export class EnvLoader implements ConfigLoader {
value = value.slice(1, -1);
}
// Only set if not already set (allows override precedence)
if (!(key in process.env)) {
process.env[key] = value;
}
}
return true;
} catch (error: unknown) {
// File not found is not an error (env files are optional)
if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.warn(
@ -313,6 +312,7 @@ export class EnvLoader implements ConfigLoader {
error instanceof Error ? error.message : String(error)
);
}
return false;
}
}
}

View file

@ -1,178 +0,0 @@
import { z } from 'zod';
/**
* Secret value wrapper to prevent accidental logging
*/
export class SecretValue<T = string> {
private readonly value: T;
private readonly masked: string;
constructor(value: T, mask: string = '***') {
this.value = value;
this.masked = mask;
}
/**
* Get the actual secret value
* @param reason - Required reason for accessing the secret
*/
reveal(reason: string): T {
if (!reason) {
throw new Error('Reason required for revealing secret value');
}
return this.value;
}
/**
* Get masked representation
*/
toString(): string {
return this.masked;
}
/**
* Prevent JSON serialization of actual value
*/
toJSON(): string {
return this.masked;
}
/**
* Check if value matches without revealing it
*/
equals(other: T): boolean {
return this.value === other;
}
/**
* Transform the secret value
*/
map<R>(fn: (value: T) => R, reason: string): SecretValue<R> {
return new SecretValue(fn(this.reveal(reason)));
}
}
/**
* Zod schema for secret values
*/
export const secretSchema = <T extends z.ZodTypeAny>(_schema: T) => {
return z.custom<SecretValue<z.infer<T>>>(val => val instanceof SecretValue, {
message: 'Expected SecretValue instance',
});
};
/**
* Transform string to SecretValue in Zod schema
*/
export const secretStringSchema = z.string().transform(val => new SecretValue(val));
/**
* Create a secret value
*/
export function secret<T = string>(value: T, mask?: string): SecretValue<T> {
return new SecretValue(value, mask);
}
/**
* Check if a value is a secret
*/
export function isSecret(value: unknown): value is SecretValue {
return value instanceof SecretValue;
}
/**
* Redact secrets from an object
*/
export function redactSecrets<T extends Record<string, unknown>>(
obj: T,
secretPaths: string[] = []
): T {
const result = redactSecretValues(obj) as T;
// Redact known secret paths
for (const path of secretPaths) {
const keys = path.split('.');
let current: Record<string, unknown> = result;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (key && current[key] && typeof current[key] === 'object') {
current = current[key] as Record<string, unknown>;
} else {
break;
}
}
const lastKey = keys[keys.length - 1];
if (current && lastKey && lastKey in current) {
current[lastKey] = '***REDACTED***';
}
}
// Recursively redact SecretValue instances
function redactSecretValues(obj: unknown): unknown {
if (obj === null || obj === undefined) {
return obj;
}
if (isSecret(obj)) {
return obj.toString();
}
if (Array.isArray(obj)) {
return obj.map(redactSecretValues);
}
if (typeof obj === 'object') {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = redactSecretValues(value);
}
return result;
}
return obj;
}
return result;
}
/**
* Environment variable names that should be treated as secrets
*/
export const COMMON_SECRET_PATTERNS = [
/password/i,
/secret/i,
/key/i,
/token/i,
/credential/i,
/private/i,
/auth/i,
/api[-_]?key/i,
];
/**
* Check if an environment variable name indicates a secret
*/
export function isSecretEnvVar(name: string): boolean {
return COMMON_SECRET_PATTERNS.some(pattern => pattern.test(name));
}
/**
* Wrap environment variables that look like secrets
*/
export function wrapSecretEnvVars(
env: Record<string, string | undefined>
): Record<string, string | SecretValue | undefined> {
const result: Record<string, string | SecretValue | undefined> = {};
for (const [key, value] of Object.entries(env)) {
if (value !== undefined && isSecretEnvVar(key)) {
result[key] = new SecretValue(value, `***${key}***`);
} else {
result[key] = value;
}
}
return result;
}

View file

@ -1,155 +0,0 @@
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
export interface ValidationResult {
valid: boolean;
errors?: Array<{
path: string;
message: string;
expected?: string;
received?: string;
}>;
warnings?: Array<{
path: string;
message: string;
}>;
}
/**
* Validate configuration against a schema
*/
export function validateConfig<T>(config: unknown, schema: z.ZodSchema<T>): ValidationResult {
try {
schema.parse(config);
return { valid: true };
} catch (error) {
if (error instanceof z.ZodError) {
const errors = error.errors.map(err => ({
path: err.path.join('.'),
message: err.message,
expected: 'expected' in err ? String(err.expected) : undefined,
received: 'received' in err ? String(err.received) : undefined,
}));
return { valid: false, errors };
}
throw error;
}
}
/**
* Check for required environment variables
*/
export function checkRequiredEnvVars(required: string[]): ValidationResult {
const errors: ValidationResult['errors'] = [];
for (const envVar of required) {
if (!process.env[envVar]) {
errors.push({
path: `env.${envVar}`,
message: `Required environment variable ${envVar} is not set`,
});
}
}
return {
valid: errors.length === 0,
errors: errors.length > 0 ? errors : undefined,
};
}
/**
* Validate configuration completeness
*/
export function validateCompleteness(
config: Record<string, unknown>,
required: string[]
): ValidationResult {
const errors: ValidationResult['errors'] = [];
for (const path of required) {
const keys = path.split('.');
let current: unknown = config;
let found = true;
for (const key of keys) {
if (current && typeof current === 'object' && key in current) {
current = (current as Record<string, unknown>)[key];
} else {
found = false;
break;
}
}
if (!found || current === undefined || current === null) {
errors.push({
path,
message: `Required configuration value is missing`,
});
}
}
return {
valid: errors.length === 0,
errors: errors.length > 0 ? errors : undefined,
};
}
/**
* Format validation result for display
*/
export function formatValidationResult(result: ValidationResult): string {
const lines: string[] = [];
if (result.valid) {
lines.push('✅ Configuration is valid');
} else {
lines.push('❌ Configuration validation failed');
}
if (result.errors && result.errors.length > 0) {
lines.push('\nErrors:');
for (const error of result.errors) {
lines.push(` - ${error.path}: ${error.message}`);
if (error.expected && error.received) {
lines.push(` Expected: ${error.expected}, Received: ${error.received}`);
}
}
}
if (result.warnings && result.warnings.length > 0) {
lines.push('\nWarnings:');
for (const warning of result.warnings) {
lines.push(` - ${warning.path}: ${warning.message}`);
}
}
return lines.join('\n');
}
/**
* Create a strict schema that doesn't allow extra properties
*/
export function createStrictSchema<T extends z.ZodRawShape>(shape: T): z.ZodObject<T, 'strict'> {
return z.object(shape).strict();
}
/**
* Merge multiple schemas
*/
export function mergeSchemas<T extends z.ZodSchema[]>(
...schemas: T
): z.ZodIntersection<T[0], T[1]> {
if (schemas.length < 2) {
throw new Error('At least two schemas required for merge');
}
let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1]));
for (let i = 2; i < schemas.length; i++) {
result = result.and(defined(schemas[i]));
}
return result as z.ZodIntersection<T[0], T[1]>;
}

View file

@ -1,518 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { z } from 'zod';
import {
checkRequiredEnvVars,
COMMON_SECRET_PATTERNS,
createStrictSchema,
formatValidationResult,
isSecret,
isSecretEnvVar,
mergeSchemas,
redactSecrets,
secret,
secretSchema,
secretStringSchema,
SecretValue,
validateCompleteness,
validateConfig,
wrapSecretEnvVars,
type ValidationResult,
} from '../src';
describe('Config Utils', () => {
describe('SecretValue', () => {
it('should create a secret value', () => {
const secret = new SecretValue('my-secret');
expect(secret).toBeInstanceOf(SecretValue);
expect(secret.toString()).toBe('***');
});
it('should use custom mask', () => {
const secret = new SecretValue('my-secret', 'HIDDEN');
expect(secret.toString()).toBe('HIDDEN');
});
it('should reveal value with reason', () => {
const secret = new SecretValue('my-secret');
expect(secret.reveal('testing')).toBe('my-secret');
});
it('should throw when revealing without reason', () => {
const secret = new SecretValue('my-secret');
expect(() => secret.reveal('')).toThrow('Reason required for revealing secret value');
});
it('should mask value in JSON', () => {
const secret = new SecretValue('my-secret');
expect(JSON.stringify(secret)).toBe('"***"');
expect(secret.toJSON()).toBe('***');
});
it('should compare values without revealing', () => {
const secret = new SecretValue('my-secret');
expect(secret.equals('my-secret')).toBe(true);
expect(secret.equals('other-secret')).toBe(false);
});
it('should map secret values', () => {
const secret = new SecretValue('hello');
const mapped = secret.map(val => val.toUpperCase(), 'testing transformation');
expect(mapped.reveal('checking result')).toBe('HELLO');
expect(mapped.toString()).toBe('***');
});
it('should work with non-string types', () => {
const numberSecret = new SecretValue(12345, 'XXX');
expect(numberSecret.reveal('test')).toBe(12345);
expect(numberSecret.toString()).toBe('XXX');
const objectSecret = new SecretValue({ key: 'value' }, '[OBJECT]');
expect(objectSecret.reveal('test')).toEqual({ key: 'value' });
expect(objectSecret.toString()).toBe('[OBJECT]');
});
});
describe('secret helper function', () => {
it('should create secret values', () => {
const s = secret('my-secret');
expect(s).toBeInstanceOf(SecretValue);
expect(s.reveal('test')).toBe('my-secret');
});
it('should accept custom mask', () => {
const s = secret('my-secret', 'REDACTED');
expect(s.toString()).toBe('REDACTED');
});
});
describe('isSecret', () => {
it('should identify secret values', () => {
expect(isSecret(new SecretValue('test'))).toBe(true);
expect(isSecret(secret('test'))).toBe(true);
expect(isSecret('test')).toBe(false);
expect(isSecret(null)).toBe(false);
expect(isSecret(undefined)).toBe(false);
expect(isSecret({})).toBe(false);
});
});
describe('secretSchema', () => {
it('should validate SecretValue instances', () => {
const schema = secretSchema(z.string());
const secretVal = new SecretValue('test');
expect(() => schema.parse(secretVal)).not.toThrow();
expect(() => schema.parse('test')).toThrow();
expect(() => schema.parse(null)).toThrow();
});
});
describe('secretStringSchema', () => {
it('should transform string to SecretValue', () => {
const result = secretStringSchema.parse('my-secret');
expect(result).toBeInstanceOf(SecretValue);
expect(result.reveal('test')).toBe('my-secret');
});
it('should reject non-strings', () => {
expect(() => secretStringSchema.parse(123)).toThrow();
expect(() => secretStringSchema.parse(null)).toThrow();
});
});
describe('redactSecrets', () => {
it('should redact specified paths', () => {
const obj = {
username: 'admin',
password: 'secret123',
nested: {
apiKey: 'key123',
public: 'visible',
},
};
const redacted = redactSecrets(obj, ['password', 'nested.apiKey']);
expect(redacted).toEqual({
username: 'admin',
password: '***REDACTED***',
nested: {
apiKey: '***REDACTED***',
public: 'visible',
},
});
});
it('should redact SecretValue instances', () => {
const obj = {
normal: 'value',
secret: new SecretValue('hidden', 'MASKED'),
nested: {
anotherSecret: secret('also-hidden'),
},
};
const redacted = redactSecrets(obj);
expect(redacted).toEqual({
normal: 'value',
secret: 'MASKED',
nested: {
anotherSecret: '***',
},
});
});
it('should handle arrays', () => {
const obj = {
items: [
{ name: 'item1', secret: new SecretValue('s1') },
{ name: 'item2', secret: new SecretValue('s2') },
],
};
const redacted = redactSecrets(obj);
expect(redacted.items).toEqual([
{ name: 'item1', secret: '***' },
{ name: 'item2', secret: '***' },
]);
});
it('should handle null and undefined', () => {
const obj = {
nullValue: null,
undefinedValue: undefined,
secret: new SecretValue('test'),
};
const redacted = redactSecrets(obj);
expect(redacted).toEqual({
nullValue: null,
undefinedValue: undefined,
secret: '***',
});
});
it('should handle non-existent paths gracefully', () => {
const obj = { a: 'value' };
const redacted = redactSecrets(obj, ['b.c.d']);
expect(redacted).toEqual({ a: 'value' });
});
it('should not modify original object', () => {
const obj = { password: 'secret', nested: { token: 'nested-secret' } };
const original = { password: 'secret', nested: { token: 'nested-secret' } };
const redacted = redactSecrets(obj, ['password', 'nested.token']);
expect(redacted.nested.token).toBe('***REDACTED***');
expect(obj).toEqual(original);
});
});
describe('isSecretEnvVar', () => {
it('should identify common secret patterns', () => {
// Positive cases
expect(isSecretEnvVar('PASSWORD')).toBe(true);
expect(isSecretEnvVar('DB_PASSWORD')).toBe(true);
expect(isSecretEnvVar('API_KEY')).toBe(true);
expect(isSecretEnvVar('API-KEY')).toBe(true);
expect(isSecretEnvVar('SECRET_TOKEN')).toBe(true);
expect(isSecretEnvVar('AUTH_TOKEN')).toBe(true);
expect(isSecretEnvVar('PRIVATE_KEY')).toBe(true);
expect(isSecretEnvVar('CREDENTIAL')).toBe(true);
expect(isSecretEnvVar('password')).toBe(true); // Case insensitive
// Negative cases
expect(isSecretEnvVar('USERNAME')).toBe(false);
expect(isSecretEnvVar('PORT')).toBe(false);
expect(isSecretEnvVar('DEBUG')).toBe(false);
expect(isSecretEnvVar('NODE_ENV')).toBe(false);
});
});
describe('wrapSecretEnvVars', () => {
it('should wrap secret environment variables', () => {
const env = {
USERNAME: 'admin',
PASSWORD: 'secret123',
API_KEY: 'key123',
PORT: '3000',
};
const wrapped = wrapSecretEnvVars(env);
expect(wrapped.USERNAME).toBe('admin');
expect(wrapped.PORT).toBe('3000');
expect(isSecret(wrapped.PASSWORD)).toBe(true);
expect(isSecret(wrapped.API_KEY)).toBe(true);
const passwordSecret = wrapped.PASSWORD as SecretValue;
expect(passwordSecret.reveal('test')).toBe('secret123');
expect(passwordSecret.toString()).toBe('***PASSWORD***');
});
it('should handle undefined values', () => {
const env = {
PASSWORD: undefined,
USERNAME: 'admin',
};
const wrapped = wrapSecretEnvVars(env);
expect(wrapped.PASSWORD).toBeUndefined();
expect(wrapped.USERNAME).toBe('admin');
});
});
describe('validateConfig', () => {
const schema = z.object({
name: z.string(),
port: z.number(),
optional: z.string().optional(),
});
it('should validate valid config', () => {
const result = validateConfig({ name: 'app', port: 3000 }, schema);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should return errors for invalid config', () => {
const result = validateConfig({ name: 'app', port: 'invalid' }, schema);
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0].path).toBe('port');
expect(result.errors![0].message).toContain('Expected number');
});
it('should handle missing required fields', () => {
const result = validateConfig({ port: 3000 }, schema);
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0].path).toBe('name');
});
it('should rethrow non-Zod errors', () => {
const badSchema = {
parse: () => {
throw new Error('Not a Zod error');
},
} as any;
expect(() => validateConfig({}, badSchema)).toThrow('Not a Zod error');
});
});
describe('checkRequiredEnvVars', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
// Clear environment
for (const key in process.env) {
delete process.env[key];
}
});
afterEach(() => {
// Restore environment
for (const key in process.env) {
delete process.env[key];
}
Object.assign(process.env, originalEnv);
});
it('should pass when all required vars are set', () => {
process.env.API_KEY = 'key123';
process.env.DATABASE_URL = 'postgres://...';
const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL']);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should fail when required vars are missing', () => {
process.env.API_KEY = 'key123';
const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL', 'MISSING_VAR']);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
expect(result.errors![0].path).toBe('env.DATABASE_URL');
expect(result.errors![1].path).toBe('env.MISSING_VAR');
});
it('should handle empty required list', () => {
const result = checkRequiredEnvVars([]);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
});
describe('validateCompleteness', () => {
it('should validate complete config', () => {
const config = {
database: {
host: 'localhost',
port: 5432,
credentials: {
username: 'admin',
password: 'secret',
},
},
};
const result = validateCompleteness(config, [
'database.host',
'database.port',
'database.credentials.username',
]);
expect(result.valid).toBe(true);
expect(result.errors).toBeUndefined();
});
it('should detect missing values', () => {
const config = {
database: {
host: 'localhost',
credentials: {},
},
};
const result = validateCompleteness(config, [
'database.host',
'database.port',
'database.credentials.username',
]);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
expect(result.errors![0].path).toBe('database.port');
expect(result.errors![1].path).toBe('database.credentials.username');
});
it('should handle null and undefined as missing', () => {
const config = {
a: null,
b: undefined,
c: 'value',
};
const result = validateCompleteness(config, ['a', 'b', 'c']);
expect(result.valid).toBe(false);
expect(result.errors).toHaveLength(2);
});
it('should handle non-existent paths', () => {
const config = { a: 'value' };
const result = validateCompleteness(config, ['b.c.d']);
expect(result.valid).toBe(false);
expect(result.errors![0].path).toBe('b.c.d');
});
});
describe('formatValidationResult', () => {
it('should format valid result', () => {
const result: ValidationResult = { valid: true };
const formatted = formatValidationResult(result);
expect(formatted).toBe('✅ Configuration is valid');
});
it('should format errors', () => {
const result: ValidationResult = {
valid: false,
errors: [
{ path: 'port', message: 'Expected number' },
{
path: 'database.host',
message: 'Invalid value',
expected: 'string',
received: 'number',
},
],
};
const formatted = formatValidationResult(result);
expect(formatted).toContain('❌ Configuration validation failed');
expect(formatted).toContain('Errors:');
expect(formatted).toContain('- port: Expected number');
expect(formatted).toContain('- database.host: Invalid value');
expect(formatted).toContain('Expected: string, Received: number');
});
it('should format warnings', () => {
const result: ValidationResult = {
valid: true,
warnings: [{ path: 'deprecated.feature', message: 'This feature is deprecated' }],
};
const formatted = formatValidationResult(result);
expect(formatted).toContain('✅ Configuration is valid');
expect(formatted).toContain('Warnings:');
expect(formatted).toContain('- deprecated.feature: This feature is deprecated');
});
});
describe('createStrictSchema', () => {
it('should create strict schema', () => {
const schema = createStrictSchema({
name: z.string(),
age: z.number(),
});
expect(() => schema.parse({ name: 'John', age: 30 })).not.toThrow();
expect(() => schema.parse({ name: 'John', age: 30, extra: 'field' })).toThrow();
});
});
describe('mergeSchemas', () => {
it('should merge two schemas', () => {
const schema1 = z.object({ a: z.string() });
const schema2 = z.object({ b: z.number() });
const merged = mergeSchemas(schema1, schema2);
const result = merged.parse({ a: 'test', b: 123 });
expect(result).toEqual({ a: 'test', b: 123 });
});
it('should merge multiple schemas', () => {
const schema1 = z.object({ a: z.string() });
const schema2 = z.object({ b: z.number() });
const schema3 = z.object({ c: z.boolean() });
const merged = mergeSchemas(schema1, schema2, schema3);
const result = merged.parse({ a: 'test', b: 123, c: true });
expect(result).toEqual({ a: 'test', b: 123, c: true });
});
it('should throw with less than two schemas', () => {
expect(() => mergeSchemas(z.object({}))).toThrow('At least two schemas required');
expect(() => mergeSchemas()).toThrow('At least two schemas required');
});
it('should handle overlapping fields', () => {
const schema1 = z.object({ a: z.string(), shared: z.string() });
const schema2 = z.object({ b: z.number(), shared: z.string() });
const merged = mergeSchemas(schema1, schema2);
// Both schemas require 'shared' to be a string
expect(() => merged.parse({ a: 'test', b: 123, shared: 'value' })).not.toThrow();
expect(() => merged.parse({ a: 'test', b: 123, shared: 123 })).toThrow();
});
});
describe('COMMON_SECRET_PATTERNS', () => {
it('should be an array of RegExp', () => {
expect(Array.isArray(COMMON_SECRET_PATTERNS)).toBe(true);
expect(COMMON_SECRET_PATTERNS.length).toBeGreaterThan(0);
for (const pattern of COMMON_SECRET_PATTERNS) {
expect(pattern).toBeInstanceOf(RegExp);
}
});
});
});

View file

@ -1,8 +1,21 @@
{
"name": "@stock-bot/di",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./http-security": {
"types": "./dist/http/security.d.ts",
"import": "./dist/http/security.js",
"default": "./dist/http/security.js"
}
},
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
@ -13,11 +26,10 @@
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/browser": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/queue": "workspace:*",
"@stock-bot/shutdown": "workspace:*",

View file

@ -1,7 +0,0 @@
import type { AwilixContainer } from 'awilix';
import type { ServiceDefinitions } from './container/types';
// Compatibility exports use the same composition contract as the active builder.
export type { AppConfig } from './config/schemas';
export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types';
export type ServiceContainer = AwilixContainer<ServiceDefinitions>;

View file

@ -1,4 +1,11 @@
import { asClass, asFunction, createContainer, InjectionMode, type AwilixContainer } from 'awilix';
import {
asClass,
asFunction,
asValue,
createContainer,
InjectionMode,
type AwilixContainer,
} from 'awilix';
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
import { toUnifiedConfig } from '@stock-bot/config';
import { HandlerRegistry } from '@stock-bot/handler-registry';
@ -14,8 +21,22 @@ import { HandlerScanner } from '../scanner';
import { ServiceLifecycleManager } from '../utils/lifecycle';
import type { ContainerBuildOptions, ServiceDefinitions } from './types';
export interface ContainerRegistrationHelpers {
asClass: typeof asClass;
asFunction: typeof asFunction;
asValue: typeof asValue;
}
export type ContainerRegistrar = (
container: AwilixContainer<ServiceDefinitions>,
config: AppConfig,
helpers: ContainerRegistrationHelpers
) => void;
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
if (!uri) return undefined;
if (!uri) {
return undefined;
}
try {
const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0];
return db || undefined;
@ -31,6 +52,7 @@ function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): numbe
export class ServiceContainerBuilder {
private config: Partial<AppConfig> = {};
private unifiedConfig: UnifiedAppConfig | null = null;
private customRegistrations: ContainerRegistrar[] = [];
private options: ContainerBuildOptions = {
enableCache: true,
enableQueue: true,
@ -55,6 +77,11 @@ export class ServiceContainerBuilder {
return this;
}
withRegistrations(registrar: ContainerRegistrar): this {
this.customRegistrations.push(registrar);
return this;
}
enableService(
service: keyof Omit<ContainerBuildOptions, 'skipInitialization' | 'initializationTimeout'>,
enabled = true
@ -85,6 +112,10 @@ export class ServiceContainerBuilder {
// Register services
this.registerServices(container, validatedConfig);
const helpers: ContainerRegistrationHelpers = { asClass, asFunction, asValue };
for (const registrar of this.customRegistrations) {
registrar(container, validatedConfig, helpers);
}
const lifecycleManager = new ServiceLifecycleManager();
// Initialize services if not skipped

View file

@ -1,26 +1,21 @@
import type { Browser } from '@stock-bot/browser';
import type { CacheProvider } from '@stock-bot/cache';
import type { HandlerRegistry } from '@stock-bot/handler-registry';
import type { Logger } from '@stock-bot/logger';
import type { MongoDBClient } from '@stock-bot/mongodb';
import type { PostgreSQLClient } from '@stock-bot/postgres';
import type { ProxyManager } from '@stock-bot/proxy';
import type { QuestDBClient } from '@stock-bot/questdb';
import type { QueueManager } from '@stock-bot/queue';
import type { IServiceContainer } from '@stock-bot/services';
import type { Browser, IServiceContainer, ProxyManager } from '@stock-bot/services';
import type { AppConfig } from '../config/schemas';
import type { HandlerScanner } from '../scanner';
export interface ServiceDefinitions {
// Configuration
config: AppConfig;
logger: Logger;
// Handler infrastructure
handlerRegistry: HandlerRegistry;
handlerScanner: HandlerScanner;
// Core services
cache: CacheProvider | null;
globalCache: CacheProvider | null;
proxyCache: CacheProvider | null;
@ -28,12 +23,10 @@ export interface ServiceDefinitions {
browser: Browser | null;
queueManager: QueueManager | null;
// Database clients
mongoClient: MongoDBClient | null;
postgresClient: PostgreSQLClient | null;
questdbClient: QuestDBClient | null;
// Aggregate service container
serviceContainer: IServiceContainer;
}

View file

@ -1 +0,0 @@
// This directory is reserved for future factory implementations

View file

@ -1,7 +1,6 @@
// Export only what's actually used
export { ServiceApplication } from './service-application';
export { ServiceContainerBuilder } from './container/builder';
export { OperationContext } from './operation-context';
export type { ContainerRegistrar, ContainerRegistrationHelpers } from './container/builder';
export {
createHttpSecurity,
httpSecurityOptions,
@ -11,12 +10,10 @@ export {
getResearchHttpPrincipal,
} from './http/security';
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
export { ServiceLifecycleManager } from './utils/lifecycle';
export { HandlerScanner } from './scanner/handler-scanner';
export type { IServiceContainer } from '@stock-bot/services';
// Export schemas
export {
appConfigSchema,
redisConfigSchema,
@ -29,5 +26,4 @@ export {
} from './config/schemas';
export type { ServiceDefinitions, ServiceCradle } from './container/types';
export type { HandlerInitializationContext } from './service-application';

View file

@ -1,144 +0,0 @@
/**
* OperationContext - Unified context for handler operations
*/
import { getLogger, type Logger } from '@stock-bot/logger';
interface ServiceResolver {
resolve<T>(serviceName: string): T;
resolveAsync<T>(serviceName: string): Promise<T>;
}
export interface OperationContextOptions {
handlerName: string;
operationName: string;
parentLogger?: Logger;
container?: ServiceResolver;
metadata?: Record<string, unknown>;
traceId?: string;
}
export class OperationContext {
public readonly logger: Logger;
public readonly traceId: string;
public readonly metadata: Record<string, unknown>;
private readonly container?: ServiceResolver;
private readonly startTime: Date;
constructor(options: OperationContextOptions) {
this.container = options.container;
this.metadata = options.metadata || {};
this.traceId = options.traceId || this.generateTraceId();
this.startTime = new Date();
this.logger =
options.parentLogger ||
getLogger(`${options.handlerName}:${options.operationName}`, {
traceId: this.traceId,
metadata: this.metadata,
});
}
/**
* Creates a new OperationContext with automatic resource management
*/
static create(
handlerName: string,
operationName: string,
options: {
container?: ServiceResolver;
parentLogger?: Logger;
metadata?: Record<string, unknown>;
traceId?: string;
} = {}
): OperationContext {
return new OperationContext({
handlerName,
operationName,
...options,
});
}
/**
* Resolve a service from the container
*/
resolve<T>(serviceName: string): T {
if (!this.container) {
throw new Error('No service container available');
}
return this.container.resolve<T>(serviceName);
}
/**
* Resolve a service asynchronously from the container
*/
async resolveAsync<T>(serviceName: string): Promise<T> {
if (!this.container) {
throw new Error('No service container available');
}
return this.container.resolveAsync<T>(serviceName);
}
/**
* Add metadata to the context
*/
addMetadata(key: string, value: unknown): void {
this.metadata[key] = value;
}
/**
* Get execution time in milliseconds
*/
getExecutionTime(): number {
return Date.now() - this.startTime.getTime();
}
/**
* Log operation completion with metrics
*/
logCompletion(success: boolean, error?: Error): void {
const executionTime = this.getExecutionTime();
if (success) {
this.logger.info('Operation completed successfully', {
executionTime,
metadata: this.metadata,
});
} else {
this.logger.error('Operation failed', {
executionTime,
error: error?.message,
stack: error?.stack,
metadata: this.metadata,
});
}
}
/**
* Cleanup method
*/
async dispose(): Promise<void> {
this.logCompletion(true);
}
/**
* Create child context
*/
createChild(operationName: string, metadata?: Record<string, unknown>): OperationContext {
return new OperationContext({
handlerName: 'child',
operationName,
parentLogger: this.logger,
container: this.container,
traceId: this.traceId,
metadata: { ...this.metadata, ...metadata },
});
}
/**
* Generate a unique trace ID
*/
private generateTraceId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
}

View file

@ -1,102 +0,0 @@
import type { ConnectionPoolConfig } from './types';
export interface PoolSizeRecommendation {
min: number;
max: number;
idle: number;
}
export class PoolSizeCalculator {
private static readonly DEFAULT_SIZES: Record<string, PoolSizeRecommendation> = {
// Service-level defaults
'data-ingestion': { min: 5, max: 50, idle: 10 },
'data-pipeline': { min: 3, max: 30, idle: 5 },
'processing-service': { min: 2, max: 20, idle: 3 },
'web-api': { min: 2, max: 10, idle: 2 },
'portfolio-service': { min: 2, max: 15, idle: 3 },
'strategy-service': { min: 3, max: 25, idle: 5 },
'execution-service': { min: 2, max: 10, idle: 2 },
// Handler-level defaults
'batch-import': { min: 10, max: 100, idle: 20 },
'real-time': { min: 2, max: 10, idle: 3 },
analytics: { min: 5, max: 30, idle: 10 },
reporting: { min: 3, max: 20, idle: 5 },
};
static calculate(
serviceName: string,
handlerName?: string,
customConfig?: Partial<ConnectionPoolConfig>
): PoolSizeRecommendation {
// Check for custom configuration first
if (customConfig?.minConnections && customConfig?.maxConnections) {
return {
min: customConfig.minConnections,
max: customConfig.maxConnections,
idle: Math.floor((customConfig.minConnections + customConfig.maxConnections) / 4),
};
}
// Try handler-specific sizes first, then service-level
const key = handlerName || serviceName;
const recommendation = this.DEFAULT_SIZES[key] || this.DEFAULT_SIZES[serviceName];
if (recommendation) {
return { ...recommendation };
}
// Fall back to generic defaults
return {
min: 2,
max: 10,
idle: 3,
};
}
static getOptimalPoolSize(
expectedConcurrency: number,
averageQueryTimeMs: number,
targetLatencyMs: number
): number {
// Little's Law: L = λ * W
// L = number of connections needed
// λ = arrival rate (requests per second)
// W = average time in system (seconds)
const requestsPerSecond = expectedConcurrency;
const averageTimeInSystem = averageQueryTimeMs / 1000;
const minConnections = Math.ceil(requestsPerSecond * averageTimeInSystem);
// Add buffer for burst traffic (20% overhead)
const recommendedSize = Math.ceil(minConnections * 1.2);
// Ensure we meet target latency
const latencyBasedSize = Math.ceil(
expectedConcurrency * (averageQueryTimeMs / targetLatencyMs)
);
return Math.max(recommendedSize, latencyBasedSize, 2); // Minimum 2 connections
}
}
// Export convenience functions
export function calculatePoolSize(
serviceName: string,
handlerName?: string,
customConfig?: Partial<ConnectionPoolConfig>
): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName, handlerName, customConfig);
}
export function getServicePoolSize(serviceName: string): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName);
}
export function getHandlerPoolSize(
serviceName: string,
handlerName: string
): PoolSizeRecommendation {
return PoolSizeCalculator.calculate(serviceName, handlerName);
}

View file

@ -1,7 +1,8 @@
import { asClass, asFunction, asValue, type AwilixContainer } from 'awilix';
import { Browser } from '@stock-bot/browser';
import { asFunction, asValue, type AwilixContainer } from 'awilix';
import { createCache } from '@stock-bot/cache';
import { defined } from '@stock-bot/invariants';
import { ProxyManager } from '@stock-bot/proxy';
import { QueueManager } from '@stock-bot/queue';
import type { AppConfig } from '../config/schemas';
import type { ServiceDefinitions } from '../container/types';
@ -9,52 +10,40 @@ export function registerApplicationServices(
container: AwilixContainer<ServiceDefinitions>,
config: AppConfig
): void {
// Browser
if (config.browser) {
container.register({
browser: asClass(Browser)
.singleton()
.inject(() => ({
options: {
headless: defined(config.browser).headless,
timeout: defined(config.browser).timeout,
},
})),
});
} else {
container.register({
browser: asValue(null), // Required field
});
}
// Browser is an ingestion-only capability registered by apps/stock/data-ingestion
// via ServiceContainerBuilder.withRegistrations() so non-ingestion apps never pull Playwright.
container.register({
browser: asValue(null),
});
// Proxy Manager
// Proxy Manager (pure TypeScript + Redis cache; zero browser dependencies)
if (config.proxy && config.redis?.enabled) {
const redisConfig = config.redis;
const proxyConfig = config.proxy;
container.register({
proxyCache: asFunction(({ logger }) => {
// Create a separate cache instance for proxy with global prefix
const { createCache } = require('@stock-bot/cache');
return createCache({
redisConfig: {
host: config.redis.host,
port: config.redis.port,
password: config.redis.password,
username: config.redis.username,
maxRetriesPerRequest: config.redis.maxRetries,
retryDelay: config.redis.retryDelay,
db: 1, // Use cache DB (usually DB 1)
host: redisConfig.host,
port: redisConfig.port,
password: redisConfig.password,
username: redisConfig.username,
maxRetriesPerRequest: redisConfig.maxRetries,
retryDelay: redisConfig.retryDelay,
db: 1,
},
shared: false,
keyPrefix: 'cache:proxy:',
ttl: 86400, // 24 hours default
ttl: 86400,
enableMetrics: true,
logger,
});
})
.singleton()
.disposer(cache => cache.disconnect?.()),
proxyManager: asFunction(
({ logger, proxyCache }) => new ProxyManager(defined(proxyCache), config.proxy, logger)
).singleton(),
proxyManager: asFunction(({ logger, proxyCache }) => {
return new ProxyManager(defined(proxyCache), proxyConfig, logger);
}).singleton(),
});
} else {
container.register({
@ -67,8 +56,6 @@ export function registerApplicationServices(
if (config.queue?.enabled && config.redis?.enabled) {
container.register({
queueManager: asFunction(({ logger, handlerRegistry }) => {
const { QueueManager } = require('@stock-bot/queue');
const queueConfig = {
serviceName: config.service?.serviceName || config.service?.name || 'unknown',
redis: {

View file

@ -168,6 +168,25 @@ export class ServiceApplication {
return app;
}
private resolveOptional<K extends keyof ServiceDefinitions>(
name: K
): ServiceDefinitions[K] | null {
if (!this.container) {
return null;
}
if (
typeof this.container.hasRegistration === 'function' &&
!this.container.hasRegistration(name)
) {
return null;
}
try {
return this.container.resolve(name);
} catch {
return null;
}
}
/**
* Register graceful shutdown handlers
*/
@ -178,30 +197,26 @@ export class ServiceApplication {
timeout: this.serviceConfig.shutdownTimeout,
});
// Priority 1: Queue system (highest priority)
if (this.serviceConfig.enableScheduledJobs) {
this.shutdown.onShutdown(
async () => {
this.logger.info('Shutting down queue system...');
const startTime = Date.now();
try {
const queueManager = this.container?.resolve('queueManager');
if (queueManager) {
await queueManager.shutdown();
const duration = Date.now() - startTime;
this.logger.info('Queue system shut down successfully', { duration });
} else {
this.logger.warn('No queue manager found to shut down');
}
} catch (error) {
// Priority 1: Queue system (always register so active workers drain even when scheduled cron jobs are disabled)
this.shutdown.onShutdown(
async () => {
const startTime = Date.now();
try {
const queueManager = this.resolveOptional('queueManager');
if (queueManager) {
this.logger.info('Shutting down queue system...');
await queueManager.shutdown();
const duration = Date.now() - startTime;
this.logger.error('Error shutting down queue system', { error, duration });
this.logger.info('Queue system shut down successfully', { duration });
}
},
SHUTDOWN_DEFAULTS.HIGH_PRIORITY,
'Queue System'
);
}
} catch (error) {
const duration = Date.now() - startTime;
this.logger.error('Error shutting down queue system', { error, duration });
}
},
SHUTDOWN_DEFAULTS.HIGH_PRIORITY,
'Queue System'
);
// Priority 1: HTTP Server (high priority)
this.shutdown.onShutdown(
@ -251,7 +266,7 @@ export class ServiceApplication {
try {
if (this.container) {
// Disconnect database clients
const mongoClient = this.container.resolve('mongoClient');
const mongoClient = this.resolveOptional('mongoClient');
if (mongoClient?.disconnect) {
try {
const mongoStart = Date.now();
@ -263,7 +278,7 @@ export class ServiceApplication {
}
}
const postgresClient = this.container.resolve('postgresClient');
const postgresClient = this.resolveOptional('postgresClient');
if (postgresClient?.disconnect) {
try {
const pgStart = Date.now();
@ -275,7 +290,7 @@ export class ServiceApplication {
}
}
const questdbClient = this.container.resolve('questdbClient');
const questdbClient = this.resolveOptional('questdbClient');
if (questdbClient?.disconnect) {
try {
const questStart = Date.now();
@ -287,6 +302,13 @@ export class ServiceApplication {
}
}
if (typeof this.container.dispose === 'function') {
await this.container.dispose().catch(error => {
this.logger.error('Failed to dispose DI container resources', { error });
failed.push('Container');
});
}
const duration = Date.now() - startTime;
this.logger.info('Service disposal completed', {
duration,
@ -326,10 +348,7 @@ export class ServiceApplication {
this.logger.info('All shutdown handlers registered', {
service: this.serviceConfig.serviceName,
handlerCount:
3 +
(this.serviceConfig.enableScheduledJobs ? 1 : 0) +
(this.hooks.onBeforeShutdown ? 1 : 0),
handlerCount: 4 + (this.hooks.onBeforeShutdown ? 1 : 0),
});
}
@ -377,10 +396,10 @@ export class ServiceApplication {
this.logger.info('Handlers initialized');
// After handlers are initialized, add rate limit rules to queue manager
const queueManager = this.container.resolve('queueManager');
const handlerRegistry = this.container.resolve<HandlerRegistry>('handlerRegistry');
const queueManager = this.resolveOptional('queueManager');
const handlerRegistry = this.resolveOptional('handlerRegistry');
if (queueManager && handlerRegistry) {
if (queueManager && typeof handlerRegistry?.getAllMetadata === 'function') {
const rateLimitRules = [];
const allMetadata = handlerRegistry.getAllMetadata();
@ -420,9 +439,17 @@ export class ServiceApplication {
const routes = routeFactory(this.serviceContainer);
this.app.route('/', routes);
// Initialize scheduled jobs if enabled
if (this.serviceConfig.enableScheduledJobs) {
// Initialize scheduled jobs if enabled in both serviceConfig and runtime queue config
const scheduledJobsEnabled =
this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? true);
if (scheduledJobsEnabled) {
await this.initializeScheduledJobs();
} else {
const queueManager = this.resolveOptional('queueManager');
if (queueManager?.startAllWorkers) {
queueManager.startAllWorkers();
this.logger.info('Queue workers started (scheduled cron jobs disabled)');
}
}
// Call before start hook

View file

@ -1,71 +0,0 @@
// Generic types to avoid circular dependencies
export interface GenericClientConfig {
[key: string]: unknown;
}
export interface ConnectionPoolConfig {
name: string;
poolSize?: number;
minConnections?: number;
maxConnections?: number;
idleTimeoutMillis?: number;
connectionTimeoutMillis?: number;
enableMetrics?: boolean;
}
export interface MongoDBPoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface PostgreSQLPoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface CachePoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface QueuePoolConfig extends ConnectionPoolConfig {
config: GenericClientConfig;
}
export interface ConnectionFactoryConfig {
service: string;
environment: 'development' | 'qa' | 'production' | 'test';
pools?: {
mongodb?: Partial<MongoDBPoolConfig>;
postgres?: Partial<PostgreSQLPoolConfig>;
cache?: Partial<CachePoolConfig>;
queue?: Partial<QueuePoolConfig>;
};
}
export interface ConnectionPool<T> {
name: string;
client: T;
metrics: PoolMetrics;
health(): Promise<boolean>;
dispose(): Promise<void>;
}
export interface PoolMetrics {
created: Date;
totalConnections: number;
activeConnections: number;
idleConnections: number;
waitingRequests: number;
errors: number;
}
export interface ConnectionFactory {
createMongoDB(config: MongoDBPoolConfig): Promise<ConnectionPool<unknown>>;
createPostgreSQL(config: PostgreSQLPoolConfig): Promise<ConnectionPool<unknown>>;
createCache(config: CachePoolConfig): Promise<ConnectionPool<unknown>>;
createQueue(config: QueuePoolConfig): Promise<ConnectionPool<unknown>>;
getPool(
type: 'mongodb' | 'postgres' | 'cache' | 'queue',
name: string
): ConnectionPool<unknown> | undefined;
listPools(): Array<{ type: string; name: string; metrics: PoolMetrics }>;
disposeAll(): Promise<void>;
}

View file

@ -20,6 +20,7 @@ export class ServiceLifecycleManager {
{ name: 'postgresClient', key: 'postgresClient' as const },
{ name: 'questdbClient', key: 'questdbClient' as const },
{ name: 'proxyManager', key: 'proxyManager' as const },
{ name: 'browser', key: 'browser' as const },
{ name: 'queueManager', key: 'queueManager' as const },
];

View file

@ -1,76 +0,0 @@
import { describe, expect, it } from 'bun:test';
import type {
ServiceContainer,
ServiceContainerOptions,
ServiceCradle,
ServiceDefinitions,
} from '../src/awilix-container';
describe('Awilix Container Types', () => {
it('should export ServiceDefinitions interface', () => {
// Type test - if this compiles, the type exists
const testDefinitions: Partial<ServiceDefinitions> = {
config: {} as any,
logger: {} as any,
cache: null,
proxyManager: null,
browser: {} as any,
queueManager: null,
mongoClient: null,
postgresClient: null,
questdbClient: null,
serviceContainer: {} as any,
};
expect(testDefinitions).toBeDefined();
});
it('should export ServiceContainer type', () => {
// Type test - if this compiles, the type exists
const testContainer: ServiceContainer | null = null;
expect(testContainer).toBeNull();
});
it('should export ServiceCradle type', () => {
// Type test - if this compiles, the type exists
const testCradle: Partial<ServiceCradle> = {
config: {} as any,
logger: {} as any,
};
expect(testCradle).toBeDefined();
});
it('should export ServiceContainerOptions interface', () => {
// Type test - if this compiles, the type exists
const testOptions: ServiceContainerOptions = {
enableQuestDB: true,
enableMongoDB: true,
enablePostgres: true,
enableCache: true,
enableQueue: true,
enableBrowser: true,
enableProxy: true,
};
expect(testOptions).toBeDefined();
expect(testOptions.enableQuestDB).toBe(true);
expect(testOptions.enableMongoDB).toBe(true);
expect(testOptions.enablePostgres).toBe(true);
expect(testOptions.enableCache).toBe(true);
expect(testOptions.enableQueue).toBe(true);
expect(testOptions.enableBrowser).toBe(true);
expect(testOptions.enableProxy).toBe(true);
});
it('should allow partial ServiceContainerOptions', () => {
const partialOptions: ServiceContainerOptions = {
enableCache: true,
enableQueue: false,
};
expect(partialOptions.enableCache).toBe(true);
expect(partialOptions.enableQueue).toBe(false);
expect(partialOptions.enableQuestDB).toBeUndefined();
});
});

View file

@ -102,6 +102,23 @@ describe('ServiceContainerBuilder production configuration', () => {
}
});
it('allows service-specific capability overrides via withRegistrations', async () => {
const fakeBrowser = { close: async () => {} } as never;
const container = await new ServiceContainerBuilder()
.withConfig(configuration())
.withRegistrations((diContainer, _cfg, { asValue }) => {
diContainer.register({ browser: asValue(fakeBrowser) });
})
.skipInitialization()
.build();
try {
expect(container.resolve('browser')).toBe(fakeBrowser);
expect(container.resolve('serviceContainer').browser).toBe(fakeBrowser);
} finally {
await container.dispose();
}
});
it('rejects invalid settings and missing required app fields with schema errors', () => {
expect(() =>
new ServiceContainerBuilder().withConfig({

View file

@ -1,8 +1,6 @@
import { asClass, asFunction, asValue, createContainer, InjectionMode } from 'awilix';
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ServiceContainerBuilder } from '../src/container/builder';
import { OperationContext } from '../src/operation-context';
import { PoolSizeCalculator } from '../src/pool-size-calculator';
import { HandlerScanner } from '../src/scanner/handler-scanner';
import { ServiceApplication } from '../src/service-application';
@ -124,55 +122,6 @@ describe('Dependency Injection', () => {
});
});
describe('OperationContext', () => {
it('should create operation context', () => {
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
});
expect(context.traceId).toBeDefined();
expect(context.logger).toBeDefined();
expect(context.metadata).toEqual({});
});
it('should include metadata', () => {
const metadata = { userId: '123', source: 'api' };
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
metadata,
});
expect(context.metadata).toEqual(metadata);
});
it('should track execution time', async () => {
const context = new OperationContext({
handlerName: 'test-handler',
operationName: 'test-op',
});
await new Promise(resolve => setTimeout(resolve, 10));
const executionTime = context.getExecutionTime();
expect(executionTime).toBeGreaterThanOrEqual(10);
});
it('should create child context', () => {
const parentContext = new OperationContext({
handlerName: 'parent-handler',
operationName: 'parent-op',
metadata: { parentId: '123' },
});
const childContext = parentContext.createChild('child-op', { childId: '456' });
expect(childContext.traceId).toBe(parentContext.traceId);
expect(childContext.metadata).toEqual({ parentId: '123', childId: '456' });
});
});
describe('HandlerScanner', () => {
it('should create scanner instance', () => {
const mockRegistry = {
@ -219,52 +168,4 @@ describe('Dependency Injection', () => {
expect(app.stop).toBeDefined();
});
});
describe('Pool Size Calculator', () => {
it('should calculate pool size for services', () => {
const recommendation = PoolSizeCalculator.calculate('web-api');
expect(recommendation.min).toBe(2);
expect(recommendation.max).toBe(10);
expect(recommendation.idle).toBe(2);
});
it('should calculate pool size for handlers', () => {
const recommendation = PoolSizeCalculator.calculate('data-ingestion', 'batch-import');
expect(recommendation.min).toBe(10);
expect(recommendation.max).toBe(100);
expect(recommendation.idle).toBe(20);
});
it('should use custom configuration', () => {
const recommendation = PoolSizeCalculator.calculate('custom', undefined, {
minConnections: 5,
maxConnections: 50,
});
expect(recommendation.min).toBe(5);
expect(recommendation.max).toBe(50);
expect(recommendation.idle).toBe(13); // (5+50)/4 = 13.75 -> 13
});
it('should fall back to defaults', () => {
const recommendation = PoolSizeCalculator.calculate('unknown-service');
expect(recommendation.min).toBe(2);
expect(recommendation.max).toBe(10);
expect(recommendation.idle).toBe(3);
});
it('should calculate optimal pool size', () => {
const size = PoolSizeCalculator.getOptimalPoolSize(
100, // 100 requests per second
50, // 50ms average query time
100 // 100ms target latency
);
expect(size).toBeGreaterThan(0);
expect(size).toBe(50); // max(100*0.05*1.2, 100*50/100, 2) = max(6, 50, 2) = 50
});
});
});

View file

@ -2,16 +2,6 @@ import { describe, expect, it } from 'bun:test';
import * as diExports from '../src/index';
describe('DI Package Exports', () => {
it('should export OperationContext', () => {
expect(diExports.OperationContext).toBeDefined();
});
it('should export pool size calculator', () => {
expect(diExports.calculatePoolSize).toBeDefined();
expect(diExports.getServicePoolSize).toBeDefined();
expect(diExports.getHandlerPoolSize).toBeDefined();
});
it('should export ServiceContainerBuilder', () => {
expect(diExports.ServiceContainerBuilder).toBeDefined();
});

View file

@ -1,273 +0,0 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { OperationContext } from '../src/operation-context';
import type { OperationContextOptions } from '../src/operation-context';
describe('OperationContext', () => {
const mockLogger = {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
child: mock(() => mockLogger),
};
const mockContainer = {
resolve: mock((name: string) => ({ name })),
resolveAsync: mock(async (name: string) => ({ name })),
};
beforeEach(() => {
// Reset mocks
Object.keys(mockLogger).forEach(key => {
if (typeof mockLogger[key as keyof typeof mockLogger] === 'function') {
(mockLogger as any)[key] = mock(() => (key === 'child' ? mockLogger : undefined));
}
});
mockContainer.resolve = mock((name: string) => ({ name }));
mockContainer.resolveAsync = mock(async (name: string) => ({ name }));
});
describe('constructor', () => {
it('should create context with required options', () => {
const options: OperationContextOptions = {
handlerName: 'test-handler',
operationName: 'test-op',
};
const context = new OperationContext(options);
expect(context).toBeDefined();
expect(context.traceId).toBeDefined();
expect(context.metadata).toEqual({});
expect(context.logger).toBeDefined();
});
it('should create context with all options', () => {
const options: OperationContextOptions = {
handlerName: 'test-handler',
operationName: 'test-op',
parentLogger: mockLogger,
container: mockContainer,
metadata: { key: 'value' },
traceId: 'custom-trace-id',
};
const context = new OperationContext(options);
expect(context.traceId).toBe('custom-trace-id');
expect(context.metadata).toEqual({ key: 'value' });
expect(context.logger).toBe(mockLogger);
});
});
describe('static create', () => {
it('should create context using static method', () => {
const context = OperationContext.create('handler', 'operation', {
metadata: { foo: 'bar' },
});
expect(context).toBeDefined();
expect(context.metadata).toEqual({ foo: 'bar' });
});
});
describe('service resolution', () => {
it('should resolve services from container', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
container: mockContainer,
});
const service = context.resolve('myService');
expect(service).toEqual({ name: 'myService' });
expect(mockContainer.resolve).toHaveBeenCalledWith('myService');
});
it('should resolve services asynchronously', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
container: mockContainer,
});
const service = await context.resolveAsync('myService');
expect(service).toEqual({ name: 'myService' });
expect(mockContainer.resolveAsync).toHaveBeenCalledWith('myService');
});
it('should throw error when no container available', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
expect(() => context.resolve('service')).toThrow('No service container available');
});
it('should throw error when no container available for async', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
await expect(context.resolveAsync('service')).rejects.toThrow(
'No service container available'
);
});
});
describe('metadata', () => {
it('should add metadata', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
context.addMetadata('userId', '12345');
context.addMetadata('correlationId', 'corr-456');
expect(context.metadata.userId).toBe('12345');
expect(context.metadata.correlationId).toBe('corr-456');
});
it('should preserve initial metadata', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
metadata: { initial: 'value' },
});
context.addMetadata('added', 'new-value');
expect(context.metadata.initial).toBe('value');
expect(context.metadata.added).toBe('new-value');
});
});
describe('execution time', () => {
it('should track execution time', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
// Wait a bit
await new Promise(resolve => setTimeout(resolve, 50));
const executionTime = context.getExecutionTime();
expect(executionTime).toBeGreaterThan(40);
expect(executionTime).toBeLessThan(100);
});
});
describe('logging', () => {
it('should log successful completion', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
context.logCompletion(true);
expect(mockLogger.info).toHaveBeenCalledWith(
'Operation completed successfully',
expect.objectContaining({
executionTime: expect.any(Number),
metadata: {},
})
);
});
it('should log failed completion with error', () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
const error = new Error('Test error');
context.logCompletion(false, error);
expect(mockLogger.error).toHaveBeenCalledWith(
'Operation failed',
expect.objectContaining({
executionTime: expect.any(Number),
error: 'Test error',
stack: expect.any(String),
metadata: {},
})
);
});
});
describe('child context', () => {
it('should create child context', () => {
const parent = new OperationContext({
handlerName: 'parent',
operationName: 'parent-op',
parentLogger: mockLogger,
container: mockContainer,
traceId: 'parent-trace',
metadata: { parentKey: 'parentValue' },
});
const child = parent.createChild('child-op', { childKey: 'childValue' });
expect(child.traceId).toBe('parent-trace'); // Inherits trace ID
expect(child.metadata).toEqual({
parentKey: 'parentValue',
childKey: 'childValue',
});
expect(child.logger).toBe(mockLogger); // Inherits logger
});
it('should create child without additional metadata', () => {
const parent = new OperationContext({
handlerName: 'parent',
operationName: 'parent-op',
metadata: { key: 'value' },
});
const child = parent.createChild('child-op');
expect(child.metadata).toEqual({ key: 'value' });
});
});
describe('dispose', () => {
it('should log completion on dispose', async () => {
const context = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
parentLogger: mockLogger,
});
await context.dispose();
expect(mockLogger.info).toHaveBeenCalledWith(
'Operation completed successfully',
expect.any(Object)
);
});
});
describe('trace ID generation', () => {
it('should generate unique trace IDs', () => {
const context1 = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
const context2 = new OperationContext({
handlerName: 'test',
operationName: 'test-op',
});
expect(context1.traceId).not.toBe(context2.traceId);
expect(context1.traceId).toMatch(/^\d+-[a-z0-9]+$/);
});
});
});

View file

@ -1,165 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { PoolSizeCalculator } from '../src/pool-size-calculator';
import type { ConnectionPoolConfig } from '../src/types';
describe('PoolSizeCalculator', () => {
describe('calculate', () => {
it('should return service-level defaults for known services', () => {
const result = PoolSizeCalculator.calculate('data-ingestion');
expect(result).toEqual({ min: 5, max: 50, idle: 10 });
});
it('should return handler-level defaults when handler name is provided', () => {
const result = PoolSizeCalculator.calculate('any-service', 'batch-import');
expect(result).toEqual({ min: 10, max: 100, idle: 20 });
});
it('should prefer handler-level over service-level defaults', () => {
const result = PoolSizeCalculator.calculate('data-ingestion', 'real-time');
expect(result).toEqual({ min: 2, max: 10, idle: 3 });
});
it('should return generic defaults for unknown services', () => {
const result = PoolSizeCalculator.calculate('unknown-service');
expect(result).toEqual({ min: 2, max: 10, idle: 3 });
});
it('should use custom configuration when provided', () => {
const customConfig: Partial<ConnectionPoolConfig> = {
minConnections: 15,
maxConnections: 75,
};
const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig);
expect(result).toEqual({
min: 15,
max: 75,
idle: Math.floor((15 + 75) / 4), // 22
});
});
it('should ignore partial custom configuration', () => {
const customConfig: Partial<ConnectionPoolConfig> = {
minConnections: 15,
// maxConnections not provided
};
const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig);
// Should fall back to defaults
expect(result).toEqual({ min: 5, max: 50, idle: 10 });
});
it('should handle all predefined service types', () => {
const services = [
{ name: 'data-pipeline', expected: { min: 3, max: 30, idle: 5 } },
{ name: 'processing-service', expected: { min: 2, max: 20, idle: 3 } },
{ name: 'web-api', expected: { min: 2, max: 10, idle: 2 } },
{ name: 'portfolio-service', expected: { min: 2, max: 15, idle: 3 } },
{ name: 'strategy-service', expected: { min: 3, max: 25, idle: 5 } },
{ name: 'execution-service', expected: { min: 2, max: 10, idle: 2 } },
];
services.forEach(({ name, expected }) => {
const result = PoolSizeCalculator.calculate(name);
expect(result).toEqual(expected);
});
});
it('should handle all predefined handler types', () => {
const handlers = [
{ name: 'analytics', expected: { min: 5, max: 30, idle: 10 } },
{ name: 'reporting', expected: { min: 3, max: 20, idle: 5 } },
];
handlers.forEach(({ name, expected }) => {
const result = PoolSizeCalculator.calculate('any-service', name);
expect(result).toEqual(expected);
});
});
it('should return a new object each time', () => {
const result1 = PoolSizeCalculator.calculate('data-ingestion');
const result2 = PoolSizeCalculator.calculate('data-ingestion');
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
});
describe('getOptimalPoolSize', () => {
it("should calculate pool size based on Little's Law", () => {
// 10 requests/second, 100ms average query time, 50ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(10, 100, 50);
// Little's Law: L = λ * W = 10 * 0.1 = 1
// With 20% buffer: 1 * 1.2 = 1.2, ceil = 2
// Latency based: 10 * (100/50) = 20
// Max of (2, 20, 2) = 20
expect(result).toBe(20);
});
it('should return minimum 2 connections', () => {
// Very low concurrency
const result = PoolSizeCalculator.getOptimalPoolSize(0.1, 10, 1000);
expect(result).toBe(2);
});
it('should handle high concurrency scenarios', () => {
// 100 requests/second, 500ms average query time, 100ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(100, 500, 100);
// Little's Law: L = 100 * 0.5 = 50
// With 20% buffer: 50 * 1.2 = 60
// Latency based: 100 * (500/100) = 500
// Max of (60, 500, 2) = 500
expect(result).toBe(500);
});
it('should handle scenarios where latency target is already met', () => {
// 10 requests/second, 50ms average query time, 200ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(10, 50, 200);
// Little's Law: L = 10 * 0.05 = 0.5
// With 20% buffer: 0.5 * 1.2 = 0.6, ceil = 1
// Latency based: 10 * (50/200) = 2.5, ceil = 3
// Max of (1, 3, 2) = 3
expect(result).toBe(3);
});
it('should handle edge cases with zero values', () => {
expect(PoolSizeCalculator.getOptimalPoolSize(0, 100, 100)).toBe(2);
expect(PoolSizeCalculator.getOptimalPoolSize(10, 0, 100)).toBe(2);
});
it('should handle fractional calculations correctly', () => {
// 15 requests/second, 75ms average query time, 150ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(15, 75, 150);
// Little's Law: L = 15 * 0.075 = 1.125
// With 20% buffer: 1.125 * 1.2 = 1.35, ceil = 2
// Latency based: 15 * (75/150) = 7.5, ceil = 8
// Max of (2, 8, 2) = 8
expect(result).toBe(8);
});
it('should prioritize latency-based sizing when it requires more connections', () => {
// Scenario where latency requirements demand more connections than throughput
const result = PoolSizeCalculator.getOptimalPoolSize(5, 200, 50);
// Little's Law: L = 5 * 0.2 = 1
// With 20% buffer: 1 * 1.2 = 1.2, ceil = 2
// Latency based: 5 * (200/50) = 20
// Max of (2, 20, 2) = 20
expect(result).toBe(20);
});
it('should handle very high query times', () => {
// 50 requests/second, 2000ms average query time, 500ms target latency
const result = PoolSizeCalculator.getOptimalPoolSize(50, 2000, 500);
// Little's Law: L = 50 * 2 = 100
// With 20% buffer: 100 * 1.2 = 120
// Latency based: 50 * (2000/500) = 200
// Max of (120, 200, 2) = 200
expect(result).toBe(200);
});
});
});

View file

@ -231,44 +231,20 @@ describe('DI Registrations', () => {
});
describe('registerApplicationServices', () => {
it('should register browser when config exists', () => {
it('should register default null browser outside ingestion and register proxy when redis enabled', () => {
const container = createContainer();
// Mock browser factory
const mockBrowser = {
launch: mock(() => Promise.resolve()),
close: mock(() => Promise.resolve()),
};
mock.module('@stock-bot/browser', () => ({
createBrowser: () => mockBrowser,
}));
const config = {
browser: {
headless: true,
timeout: 30000,
},
} as any;
registerApplicationServices(container, config);
expect(container.hasRegistration('browser')).toBe(true);
});
it('should register proxy when config exists', () => {
const container = createContainer();
// Mock proxy factory
const mockProxy = {
getProxy: mock(() => 'http://proxy:8080'),
};
mock.module('@stock-bot/proxy', () => ({
createProxyManager: () => mockProxy,
}));
const config = {
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
proxy: {
enabled: true,
url: 'http://proxy:8080',
@ -277,10 +253,14 @@ describe('DI Registrations', () => {
registerApplicationServices(container, config);
expect(container.hasRegistration('browser')).toBe(true);
expect(container.hasRegistration('proxyCache')).toBe(true);
expect(container.hasRegistration('proxyManager')).toBe(true);
expect(container.resolve('browser')).toBeNull();
expect(container.getRegistration('proxyManager')?.lifetime).toBe('SINGLETON');
});
it('should register queue manager when queue config exists', () => {
it('should register queue manager when queue and redis configs exist', () => {
const container = createContainer();
// Mock dependencies
@ -321,6 +301,12 @@ describe('DI Registrations', () => {
name: 'test-service',
serviceName: 'test-service',
},
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
queue: {
enabled: true,
workers: 2,
@ -394,20 +380,26 @@ describe('DI Registrations', () => {
});
describe('registration options', () => {
it('should register services as singletons', () => {
it('should register queueManager as singleton when enabled', () => {
const container = createContainer();
const config = {
browser: {
headless: true,
timeout: 30000,
redis: {
enabled: true,
host: 'localhost',
port: 6379,
db: 0,
},
queue: {
enabled: true,
workers: 1,
concurrency: 1,
},
} as any;
registerApplicationServices(container, config);
// Check that browser was registered as singleton
const registration = container.getRegistration('browser');
const registration = container.getRegistration('queueManager');
expect(registration).toBeDefined();
expect(registration?.lifetime).toBe('SINGLETON');
});

View file

@ -263,9 +263,9 @@ describe('ServiceApplication', () => {
await app.start(mockContainerFactory, mockRouteFactory, mockHandlerInitializer);
expect(mockHandlerInitializer).toHaveBeenCalledWith(
{ test: 'container' },
expect.objectContaining({
test: 'container',
_diContainer: mockContainer,
handlerRegistry: expect.anything(),
})
);
expect(mockLogger.info).toHaveBeenCalledWith('Handlers initialized');

View file

@ -1,270 +0,0 @@
import { describe, expect, it } from 'bun:test';
import type {
CachePoolConfig,
ConnectionFactory,
ConnectionFactoryConfig,
ConnectionPool,
ConnectionPoolConfig,
GenericClientConfig,
MongoDBPoolConfig,
PoolMetrics,
PostgreSQLPoolConfig,
QueuePoolConfig,
} from '../src/types';
describe('DI Types', () => {
describe('GenericClientConfig', () => {
it('should allow any key-value pairs', () => {
const config: GenericClientConfig = {
host: 'localhost',
port: 5432,
username: 'test',
password: 'test',
customOption: true,
};
expect(config.host).toBe('localhost');
expect(config.port).toBe(5432);
expect(config.customOption).toBe(true);
});
});
describe('ConnectionPoolConfig', () => {
it('should have required and optional fields', () => {
const config: ConnectionPoolConfig = {
name: 'test-pool',
poolSize: 10,
minConnections: 2,
maxConnections: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
enableMetrics: true,
};
expect(config.name).toBe('test-pool');
expect(config.poolSize).toBe(10);
expect(config.enableMetrics).toBe(true);
});
it('should allow minimal configuration', () => {
const config: ConnectionPoolConfig = {
name: 'minimal-pool',
};
expect(config.name).toBe('minimal-pool');
expect(config.poolSize).toBeUndefined();
});
});
describe('Specific Pool Configs', () => {
it('should extend ConnectionPoolConfig for MongoDB', () => {
const config: MongoDBPoolConfig = {
name: 'mongo-pool',
poolSize: 5,
config: {
uri: 'mongodb://localhost:27017',
database: 'test',
},
};
expect(config.name).toBe('mongo-pool');
expect(config.config.uri).toBe('mongodb://localhost:27017');
});
it('should extend ConnectionPoolConfig for PostgreSQL', () => {
const config: PostgreSQLPoolConfig = {
name: 'postgres-pool',
config: {
host: 'localhost',
port: 5432,
database: 'test',
},
};
expect(config.name).toBe('postgres-pool');
expect(config.config.host).toBe('localhost');
});
it('should extend ConnectionPoolConfig for Cache', () => {
const config: CachePoolConfig = {
name: 'cache-pool',
config: {
host: 'localhost',
port: 6379,
},
};
expect(config.name).toBe('cache-pool');
expect(config.config.port).toBe(6379);
});
it('should extend ConnectionPoolConfig for Queue', () => {
const config: QueuePoolConfig = {
name: 'queue-pool',
config: {
redis: {
host: 'localhost',
port: 6379,
},
},
};
expect(config.name).toBe('queue-pool');
expect(config.config.redis.host).toBe('localhost');
});
});
describe('ConnectionFactoryConfig', () => {
it('should define factory configuration', () => {
const config: ConnectionFactoryConfig = {
service: 'test-service',
environment: 'development',
pools: {
mongodb: {
poolSize: 10,
},
postgres: {
maxConnections: 20,
},
cache: {
idleTimeoutMillis: 60000,
},
queue: {
enableMetrics: true,
},
},
};
expect(config.service).toBe('test-service');
expect(config.environment).toBe('development');
expect(config.pools?.mongodb?.poolSize).toBe(10);
expect(config.pools?.postgres?.maxConnections).toBe(20);
});
it('should allow minimal factory config', () => {
const config: ConnectionFactoryConfig = {
service: 'minimal-service',
environment: 'test',
};
expect(config.service).toBe('minimal-service');
expect(config.pools).toBeUndefined();
});
});
describe('ConnectionPool', () => {
it('should define connection pool interface', () => {
const mockPool: ConnectionPool<any> = {
name: 'test-pool',
client: { connected: true },
metrics: {
created: new Date(),
totalConnections: 10,
activeConnections: 5,
idleConnections: 5,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
};
expect(mockPool.name).toBe('test-pool');
expect(mockPool.client.connected).toBe(true);
expect(mockPool.metrics.totalConnections).toBe(10);
});
});
describe('PoolMetrics', () => {
it('should define pool metrics structure', () => {
const metrics: PoolMetrics = {
created: new Date('2024-01-01'),
totalConnections: 100,
activeConnections: 25,
idleConnections: 75,
waitingRequests: 2,
errors: 3,
};
expect(metrics.totalConnections).toBe(100);
expect(metrics.activeConnections).toBe(25);
expect(metrics.idleConnections).toBe(75);
expect(metrics.waitingRequests).toBe(2);
expect(metrics.errors).toBe(3);
});
});
describe('ConnectionFactory', () => {
it('should define connection factory interface', () => {
const mockFactory: ConnectionFactory = {
createMongoDB: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createPostgreSQL: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createCache: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
createQueue: async config => ({
name: config.name,
client: {},
metrics: {
created: new Date(),
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
},
health: async () => true,
dispose: async () => {},
}),
getPool: (_type, _name) => undefined,
listPools: () => [],
disposeAll: async () => {},
};
expect(mockFactory.createMongoDB).toBeDefined();
expect(mockFactory.createPostgreSQL).toBeDefined();
expect(mockFactory.createCache).toBeDefined();
expect(mockFactory.createQueue).toBeDefined();
expect(mockFactory.getPool).toBeDefined();
expect(mockFactory.listPools).toBeDefined();
expect(mockFactory.disposeAll).toBeDefined();
});
});
});

View file

@ -1,191 +0,0 @@
# @stock-bot/event-bus
Lightweight event bus for inter-service communication in the Stock Bot platform.
## Overview
This library provides a simple pub/sub event system using Redis, designed for real-time event distribution between microservices. It focuses on simplicity and reliability for event-driven communication.
## Features
- Simple pub/sub pattern using Redis
- Automatic reconnection and resubscription
- Local event emission (works even without Redis)
- TypeScript support with predefined trading event types
- Lightweight with minimal dependencies
## Installation
```bash
bun add @stock-bot/event-bus
```
## Usage
### Basic Setup
```typescript
import { createEventBus, TradingEventType } from '@stock-bot/event-bus';
const eventBus = createEventBus({
serviceName: 'data-ingestion',
redisConfig: {
host: 'localhost',
port: 6379,
},
enableLogging: true,
});
// Wait for connection
await eventBus.waitForConnection();
```
### Publishing Events
```typescript
// Publish a price update
await eventBus.publish(TradingEventType.PRICE_UPDATE, {
symbol: 'AAPL',
price: 150.25,
volume: 1000000,
timestamp: Date.now(),
});
// Publish with metadata
await eventBus.publish(TradingEventType.ORDER_FILLED,
{
orderId: '12345',
symbol: 'TSLA',
side: 'buy',
quantity: 100,
price: 250.50,
},
{ source: 'ib-gateway', region: 'us' }
);
```
### Subscribing to Events
```typescript
// Subscribe to price updates
await eventBus.subscribe(TradingEventType.PRICE_UPDATE, async (message) => {
console.log(`Price update for ${message.data.symbol}: $${message.data.price}`);
});
// Subscribe to order events
await eventBus.subscribe(TradingEventType.ORDER_FILLED, async (message) => {
const { orderId, symbol, quantity, price } = message.data;
console.log(`Order ${orderId} filled: ${quantity} ${symbol} @ $${price}`);
});
```
### Event Types
The library includes predefined event types for common trading operations:
```typescript
enum TradingEventType {
// Market data events
PRICE_UPDATE = 'market.price.update',
ORDERBOOK_UPDATE = 'market.orderbook.update',
TRADE_EXECUTED = 'market.trade.executed',
// Order events
ORDER_CREATED = 'order.created',
ORDER_FILLED = 'order.filled',
ORDER_CANCELLED = 'order.cancelled',
ORDER_REJECTED = 'order.rejected',
// Position events
POSITION_OPENED = 'position.opened',
POSITION_CLOSED = 'position.closed',
POSITION_UPDATED = 'position.updated',
// Strategy events
STRATEGY_SIGNAL = 'strategy.signal',
STRATEGY_STARTED = 'strategy.started',
STRATEGY_STOPPED = 'strategy.stopped',
// Risk events
RISK_LIMIT_BREACH = 'risk.limit.breach',
RISK_WARNING = 'risk.warning',
// System events
SERVICE_STARTED = 'system.service.started',
SERVICE_STOPPED = 'system.service.stopped',
SERVICE_ERROR = 'system.service.error',
}
```
### Typed Events
Use TypeScript generics for type-safe event handling:
```typescript
import type { PriceUpdateEvent, OrderEvent } from '@stock-bot/event-bus';
// Type-safe subscription
await eventBus.subscribe<PriceUpdateEvent>(
TradingEventType.PRICE_UPDATE,
async (message) => {
// message.data is typed as PriceUpdateEvent
const { symbol, price, volume } = message.data;
}
);
```
### Cleanup
```typescript
// Unsubscribe from specific event
await eventBus.unsubscribe(TradingEventType.PRICE_UPDATE);
// Close all connections
await eventBus.close();
```
## Architecture Notes
This library is designed for lightweight, real-time event distribution. For reliable job processing, retries, and persistence, use the `@stock-bot/queue` library with BullMQ instead.
### When to Use Event Bus
- Real-time notifications (price updates, trade executions)
- Service coordination (strategy signals, risk alerts)
- System monitoring (service status, errors)
### When to Use Queue
- Data processing jobs
- Batch operations
- Tasks requiring persistence and retries
- Scheduled operations
## Error Handling
The event bus handles connection failures gracefully:
```typescript
try {
await eventBus.publish(TradingEventType.PRICE_UPDATE, data);
} catch (error) {
// Event will still be emitted locally
console.error('Failed to publish to Redis:', error);
}
```
## Development
```bash
# Install dependencies
bun install
# Build
bun run build
# Run tests
bun test
# Clean build artifacts
bun run clean
```

View file

@ -1,40 +0,0 @@
{
"name": "@stock-bot/event-bus",
"version": "1.0.0",
"description": "Event bus library for inter-service communication",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"build": "tsc",
"test": "bun test",
"clean": "rimraf dist"
},
"dependencies": {
"@stock-bot/logger": "*",
"ioredis": "^5.3.2",
"eventemitter3": "^5.0.1",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.11.0",
"typescript": "^5.3.0",
"bun-types": "^1.2.15"
},
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./types": {
"import": "./dist/types.js",
"require": "./dist/types.js",
"types": "./dist/types.d.ts"
}
},
"files": [
"dist",
"README.md"
]
}

View file

@ -1,246 +0,0 @@
import { EventEmitter } from 'eventemitter3';
import Redis from 'ioredis';
import { getLogger } from '@stock-bot/logger';
import type { EventBusConfig, EventBusMessage, EventHandler, EventSubscription } from './types';
/**
* Lightweight Event Bus for inter-service communication
* Uses Redis pub/sub for simple, real-time event distribution
*/
export class EventBus extends EventEmitter {
private publisher: Redis;
private subscriber: Redis;
private readonly serviceName: string;
private readonly logger: ReturnType<typeof getLogger>;
private subscriptions: Map<string, EventSubscription> = new Map();
private isConnected: boolean = false;
constructor(config: EventBusConfig) {
super();
this.serviceName = config.serviceName;
this.logger = getLogger(`event-bus:${this.serviceName}`);
// Create Redis connections
const redisOptions = {
host: config.redisConfig.host,
port: config.redisConfig.port,
password: config.redisConfig.password,
db: config.redisConfig.db || 0,
lazyConnect: false,
enableOfflineQueue: true,
reconnectOnError: (err: Error) => {
this.logger.error('Redis connection error:', err);
return true;
},
};
this.publisher = new Redis(redisOptions);
this.subscriber = new Redis(redisOptions);
this.setupRedisHandlers();
}
private setupRedisHandlers(): void {
// Publisher handlers
this.publisher.on('connect', () => {
this.logger.info('Publisher connected to Redis');
this.isConnected = true;
});
this.publisher.on('error', error => {
this.logger.error('Publisher Redis error:', error);
});
// Subscriber handlers
this.subscriber.on('connect', () => {
this.logger.info('Subscriber connected to Redis');
// Resubscribe to all channels on reconnect
this.resubscribeAll();
});
this.subscriber.on('error', error => {
this.logger.error('Subscriber Redis error:', error);
});
// Handle incoming messages
this.subscriber.on('message', this.handleMessage.bind(this));
}
private handleMessage(channel: string, message: string): void {
try {
const eventMessage: EventBusMessage = JSON.parse(message);
// Skip messages from self
if (eventMessage.source === this.serviceName) {
return;
}
// Extract event type from channel (remove 'events:' prefix)
const eventType = channel.replace('events:', '');
// Emit locally
this.emit(eventType, eventMessage);
// Call registered handler if exists
const subscription = this.subscriptions.get(eventType);
if (subscription?.handler) {
Promise.resolve(subscription.handler(eventMessage)).catch(error => {
this.logger.error(`Handler error for event ${eventType}:`, error);
});
}
this.logger.debug(`Received event: ${eventType} from ${eventMessage.source}`);
} catch (error) {
this.logger.error('Failed to handle message:', { error, channel, message });
}
}
/**
* Publish an event
*/
async publish<T = unknown>(
type: string,
data: T,
metadata?: Record<string, unknown>
): Promise<void> {
const message: EventBusMessage<T> = {
id: this.generateId(),
type,
source: this.serviceName,
timestamp: Date.now(),
data,
metadata,
};
// Emit locally first
this.emit(type, message);
// Publish to Redis
if (this.isConnected) {
try {
const channel = `events:${type}`;
await this.publisher.publish(channel, JSON.stringify(message));
this.logger.debug(`Published event: ${type}`, { messageId: message.id });
} catch (error) {
this.logger.error(`Failed to publish event: ${type}`, { error, messageId: message.id });
throw error;
}
} else {
this.logger.warn(`Not connected to Redis, event ${type} only emitted locally`);
}
}
/**
* Subscribe to an event
*/
async subscribe<T = unknown>(eventType: string, handler: EventHandler<T>): Promise<void> {
// Register handler
this.subscriptions.set(eventType, {
channel: `events:${eventType}`,
handler: message => handler(message as EventBusMessage<T>),
});
// Add local listener
this.on(eventType, handler);
// Subscribe to Redis channel
try {
const channel = `events:${eventType}`;
await this.subscriber.subscribe(channel);
this.logger.debug(`Subscribed to event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to subscribe to event: ${eventType}`, error);
throw error;
}
}
/**
* Unsubscribe from an event
*/
async unsubscribe(eventType: string, handler?: EventHandler): Promise<void> {
// Remove specific handler or all handlers
if (handler) {
this.off(eventType, handler);
} else {
this.removeAllListeners(eventType);
}
// Remove from subscriptions
this.subscriptions.delete(eventType);
// Unsubscribe from Redis
try {
const channel = `events:${eventType}`;
await this.subscriber.unsubscribe(channel);
this.logger.debug(`Unsubscribed from event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to unsubscribe from event: ${eventType}`, error);
}
}
/**
* Resubscribe to all channels (used on reconnect)
*/
private async resubscribeAll(): Promise<void> {
for (const [eventType, subscription] of this.subscriptions.entries()) {
try {
await this.subscriber.subscribe(subscription.channel);
this.logger.debug(`Resubscribed to event: ${eventType}`);
} catch (error) {
this.logger.error(`Failed to resubscribe to event: ${eventType}`, error);
}
}
}
/**
* Wait for connection to be established
*/
async waitForConnection(timeout: number = 5000): Promise<void> {
const startTime = Date.now();
while (!this.isConnected && Date.now() - startTime < timeout) {
await new Promise(resolve => setTimeout(resolve, 100));
}
if (!this.isConnected) {
throw new Error(`Failed to connect to Redis within ${timeout}ms`);
}
}
/**
* Close all connections
*/
async close(): Promise<void> {
this.isConnected = false;
// Clear all subscriptions
this.subscriptions.clear();
this.removeAllListeners();
// Close Redis connections
await Promise.all([this.publisher.quit(), this.subscriber.quit()]);
this.logger.info('Event bus closed');
}
/**
* Generate unique message ID
*/
private generateId(): string {
return `${this.serviceName}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Check if connected to Redis
*/
get connected(): boolean {
return this.isConnected;
}
/**
* Get service name
*/
get service(): string {
return this.serviceName;
}
}

View file

@ -1,13 +0,0 @@
import { EventBus } from './event-bus';
import type { EventBusConfig } from './types';
/**
* Create a new event bus instance
*/
export function createEventBus(config: EventBusConfig): EventBus {
return new EventBus(config);
}
// Re-export everything
export { EventBus } from './event-bus';
export * from './types';

View file

@ -1,205 +0,0 @@
import { defined } from '@stock-bot/invariants';
import type { EventBusMessage, EventHandler, EventSubscription } from './types';
/**
* Simple in-memory event bus for testing
*/
export class SimpleEventBus {
private subscriptions = new Map<string, Set<{ id: string; handler: EventHandler }>>();
private subscriptionById = new Map<
string,
{ id: string; channel: string; handler: EventHandler }
>();
private nextId = 1;
subscribe(channel: string, handler: EventHandler): EventSubscription {
const id = `sub-${this.nextId++}`;
const subscription = { id, handler };
if (!this.subscriptions.has(channel)) {
this.subscriptions.set(channel, new Set());
}
defined(this.subscriptions.get(channel)).add(subscription);
this.subscriptionById.set(id, { id, channel, handler });
return { channel, handler };
}
unsubscribe(idOrSubscription: string | EventSubscription): boolean {
if (typeof idOrSubscription === 'string') {
const subscription = this.subscriptionById.get(idOrSubscription);
if (!subscription) {
return false;
}
const channelSubs = this.subscriptions.get(subscription.channel);
if (channelSubs) {
channelSubs.forEach(sub => {
if (sub.id === idOrSubscription) {
channelSubs.delete(sub);
}
});
if (channelSubs.size === 0) {
this.subscriptions.delete(subscription.channel);
}
}
this.subscriptionById.delete(idOrSubscription);
return true;
} else {
// Unsubscribe by matching handler and channel
const channelSubs = this.subscriptions.get(idOrSubscription.channel);
if (channelSubs) {
let removed = false;
channelSubs.forEach(sub => {
if (sub.handler === idOrSubscription.handler) {
channelSubs.delete(sub);
this.subscriptionById.delete(sub.id);
removed = true;
}
});
if (channelSubs.size === 0) {
this.subscriptions.delete(idOrSubscription.channel);
}
return removed;
}
return false;
}
}
async publish(event: string, data: unknown): Promise<void> {
const message: EventBusMessage = {
id: `msg-${this.nextId++}`,
type: event,
source: 'simple-event-bus',
timestamp: Date.now(),
data,
};
const handlers: EventHandler[] = [];
// Direct matches
const directSubs = this.subscriptions.get(event);
if (directSubs) {
handlers.push(...Array.from(directSubs).map(s => s.handler));
}
// Pattern matches
for (const [pattern, subs] of this.subscriptions) {
if (pattern.includes('*') && this.matchPattern(pattern, event)) {
handlers.push(...Array.from(subs).map(s => s.handler));
}
}
// Execute all handlers
await Promise.all(
handlers.map(handler =>
Promise.resolve(handler(message)).catch(_err => {
// Silently catch errors
})
)
);
}
publishSync(event: string, data: unknown): void {
const message: EventBusMessage = {
id: `msg-${this.nextId++}`,
type: event,
source: 'simple-event-bus',
timestamp: Date.now(),
data,
};
const handlers: EventHandler[] = [];
// Direct matches
const directSubs = this.subscriptions.get(event);
if (directSubs) {
handlers.push(...Array.from(directSubs).map(s => s.handler));
}
// Pattern matches
for (const [pattern, subs] of this.subscriptions) {
if (pattern.includes('*') && this.matchPattern(pattern, event)) {
handlers.push(...Array.from(subs).map(s => s.handler));
}
}
// Execute all handlers synchronously
handlers.forEach(handler => {
try {
handler(message);
} catch {
// Silently catch errors
}
});
}
once(event: string, handler: EventHandler): EventSubscription {
let subId: string;
const wrappedHandler: EventHandler = async message => {
await handler(message);
this.unsubscribe(subId);
};
const subscription = this.subscribe(event, wrappedHandler);
// Find the subscription ID
this.subscriptionById.forEach((value, key) => {
if (value.handler === wrappedHandler) {
subId = key;
}
});
return subscription;
}
off(event: string, handler?: EventHandler): void {
if (!handler) {
// Remove all handlers for this event
const subs = this.subscriptions.get(event);
if (subs) {
for (const sub of subs) {
this.subscriptionById.delete(sub.id);
}
this.subscriptions.delete(event);
}
} else {
// Remove specific handler
const subs = this.subscriptions.get(event);
if (subs) {
const toRemove: string[] = [];
subs.forEach(sub => {
if (sub.handler === handler) {
toRemove.push(sub.id);
}
});
toRemove.forEach(id => {
subs.forEach(sub => {
if (sub.id === id) {
subs.delete(sub);
}
});
this.subscriptionById.delete(id);
});
if (subs.size === 0) {
this.subscriptions.delete(event);
}
}
}
}
hasSubscribers(event: string): boolean {
return this.subscriptions.has(event) && defined(this.subscriptions.get(event)).size > 0;
}
clear(): void {
this.subscriptions.clear();
this.subscriptionById.clear();
}
private matchPattern(pattern: string, event: string): boolean {
// Simple pattern matching: user.* matches user.created, user.updated, etc.
const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
return regex.test(event);
}
}

View file

@ -1,111 +0,0 @@
export interface EventBusMessage<T = unknown> {
id: string;
type: string;
source: string;
timestamp: number;
data: T;
metadata?: Record<string, unknown>;
}
export interface EventHandler<T = unknown> {
(message: EventBusMessage<T>): Promise<void> | void;
}
export interface EventBusConfig {
serviceName: string;
redisConfig: {
host: string;
port: number;
password?: string;
db?: number;
};
enableLogging?: boolean;
}
export interface EventSubscription {
channel: string;
handler: EventHandler;
}
// Trading-specific event types
export enum TradingEventType {
// Market data events
PRICE_UPDATE = 'market.price.update',
ORDERBOOK_UPDATE = 'market.orderbook.update',
TRADE_EXECUTED = 'market.trade.executed',
// Order events
ORDER_CREATED = 'order.created',
ORDER_FILLED = 'order.filled',
ORDER_CANCELLED = 'order.cancelled',
ORDER_REJECTED = 'order.rejected',
// Position events
POSITION_OPENED = 'position.opened',
POSITION_CLOSED = 'position.closed',
POSITION_UPDATED = 'position.updated',
// Strategy events
STRATEGY_SIGNAL = 'strategy.signal',
STRATEGY_STARTED = 'strategy.started',
STRATEGY_STOPPED = 'strategy.stopped',
// Risk events
RISK_LIMIT_BREACH = 'risk.limit.breach',
RISK_WARNING = 'risk.warning',
// System events
SERVICE_STARTED = 'system.service.started',
SERVICE_STOPPED = 'system.service.stopped',
SERVICE_ERROR = 'system.service.error',
}
// Event data types
export interface PriceUpdateEvent {
symbol: string;
price: number;
volume: number;
timestamp: number;
}
export interface OrderEvent {
orderId: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price?: number;
type: 'market' | 'limit' | 'stop' | 'stop_limit';
status: string;
portfolioId: string;
strategyId?: string;
}
export interface PositionEvent {
positionId: string;
symbol: string;
quantity: number;
averageCost: number;
currentPrice: number;
unrealizedPnl: number;
realizedPnl: number;
portfolioId: string;
}
export interface StrategySignalEvent {
strategyId: string;
signal: 'buy' | 'sell' | 'hold';
symbol: string;
confidence: number;
indicators: Record<string, number>;
timestamp: number;
}
export interface RiskEvent {
type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration';
severity: 'warning' | 'critical';
currentValue: number;
limit: number;
portfolioId?: string;
strategyId?: string;
message: string;
}

View file

@ -1,17 +0,0 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": true
},
"include": ["src/**/*"],
"references": [
{
"path": "../../core/logger"
},
{
"path": "../../../libs/core/invariants"
}
]
}

View file

@ -12,7 +12,6 @@
"dependencies": {
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/handler-registry": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",

View file

@ -11,7 +11,6 @@
"test": "bun test"
},
"dependencies": {
"got": "^14.4.7",
"pino": "^9.7.0",
"pino-loki": "^2.6.0",
"pino-pretty": "^13.0.0"

View file

@ -346,6 +346,7 @@ async function addJobsInChunks(
chunkSize: chunk.length,
error,
});
throw error;
}
}

View file

@ -1,257 +0,0 @@
import { Queue, type Job } from 'bullmq';
import type { DLQConfig, RedisConfig } from './types';
import { getRedisConnection } from './utils';
// Logger interface for type safety
interface Logger {
info(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
}
export class DeadLetterQueueHandler {
private dlq: Queue;
private config: Required<DLQConfig>;
private failureCount = new Map<string, number>();
private readonly logger: Logger;
constructor(
private mainQueue: Queue,
connection: RedisConfig,
config: DLQConfig = {},
logger?: Logger
) {
this.logger = logger || console;
this.config = {
maxRetries: config.maxRetries ?? 3,
retryDelay: config.retryDelay ?? 60000, // 1 minute
alertThreshold: config.alertThreshold ?? 100,
cleanupAge: config.cleanupAge ?? 168, // 7 days
};
// Create DLQ with same name but -dlq suffix
const dlqName = `${mainQueue.name}-dlq`;
this.dlq = new Queue(dlqName, { connection: getRedisConnection(connection) });
}
/**
* Process a failed job - either retry or move to DLQ
*/
async handleFailedJob(job: Job, error: Error): Promise<void> {
const jobKey = `${job.name}:${job.id}`;
const currentFailures = (this.failureCount.get(jobKey) || 0) + 1;
this.failureCount.set(jobKey, currentFailures);
this.logger.warn('Job failed', {
jobId: job.id,
jobName: job.name,
attempt: job.attemptsMade,
maxAttempts: job.opts.attempts,
error: error.message,
failureCount: currentFailures,
});
// Check if job should be moved to DLQ
if (job.attemptsMade >= (job.opts.attempts || this.config.maxRetries)) {
await this.moveToDeadLetterQueue(job, error);
this.failureCount.delete(jobKey);
}
}
/**
* Move job to dead letter queue
*/
private async moveToDeadLetterQueue(job: Job, error: Error): Promise<void> {
try {
const dlqData = {
originalJob: {
id: job.id,
name: job.name,
data: job.data,
opts: job.opts,
attemptsMade: job.attemptsMade,
failedReason: job.failedReason,
processedOn: job.processedOn,
timestamp: job.timestamp,
},
error: {
message: error.message,
stack: error.stack,
name: error.name,
},
movedToDLQAt: new Date().toISOString(),
};
await this.dlq.add('failed-job', dlqData, {
removeOnComplete: 100,
removeOnFail: 100,
});
this.logger.error('Job moved to DLQ', {
jobId: job.id,
jobName: job.name,
error: error.message,
});
// Check if we need to alert
await this.checkAlertThreshold();
} catch (dlqError) {
this.logger.error('Failed to move job to DLQ', {
jobId: job.id,
error: dlqError,
});
}
}
/**
* Retry jobs from DLQ
*/
async retryDLQJobs(limit = 10): Promise<number> {
const jobs = await this.dlq.getCompleted(0, limit);
let retriedCount = 0;
for (const dlqJob of jobs) {
try {
const { originalJob } = dlqJob.data;
// Re-add to main queue with delay
await this.mainQueue.add(originalJob.name, originalJob.data, {
...originalJob.opts,
delay: this.config.retryDelay,
attempts: this.config.maxRetries,
});
// Remove from DLQ
await dlqJob.remove();
retriedCount++;
this.logger.info('Job retried from DLQ', {
originalJobId: originalJob.id,
jobName: originalJob.name,
});
} catch (error) {
this.logger.error('Failed to retry DLQ job', {
dlqJobId: dlqJob.id,
error,
});
}
}
return retriedCount;
}
/**
* Get DLQ statistics
*/
async getStats(): Promise<{
total: number;
recent: number;
byJobName: Record<string, number>;
oldestJob: Date | null;
}> {
const [completed, failed, waiting] = await Promise.all([
this.dlq.getCompleted(),
this.dlq.getFailed(),
this.dlq.getWaiting(),
]);
const allJobs = [...completed, ...failed, ...waiting];
const byJobName: Record<string, number> = {};
let oldestTimestamp: number | null = null;
for (const job of allJobs) {
const jobName = job.data.originalJob?.name || 'unknown';
byJobName[jobName] = (byJobName[jobName] || 0) + 1;
if (!oldestTimestamp || job.timestamp < oldestTimestamp) {
oldestTimestamp = job.timestamp;
}
}
// Count recent jobs (last 24 hours)
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
const recent = allJobs.filter(job => job.timestamp > oneDayAgo).length;
return {
total: allJobs.length,
recent,
byJobName,
oldestJob: oldestTimestamp ? new Date(oldestTimestamp) : null,
};
}
/**
* Clean up old DLQ entries
*/
async cleanup(): Promise<number> {
const ageInMs = this.config.cleanupAge * 60 * 60 * 1000;
const cutoffTime = Date.now() - ageInMs;
const jobs = await this.dlq.getCompleted();
let removedCount = 0;
for (const job of jobs) {
if (job.timestamp < cutoffTime) {
await job.remove();
removedCount++;
}
}
this.logger.info('DLQ cleanup completed', {
removedCount,
cleanupAge: `${this.config.cleanupAge} hours`,
});
return removedCount;
}
/**
* Check if alert threshold is exceeded
*/
private async checkAlertThreshold(): Promise<void> {
const stats = await this.getStats();
if (stats.total >= this.config.alertThreshold) {
this.logger.error('DLQ alert threshold exceeded', {
threshold: this.config.alertThreshold,
currentCount: stats.total,
byJobName: stats.byJobName,
});
// In a real implementation, this would trigger alerts
}
}
/**
* Get failed jobs for inspection
*/
async inspectFailedJobs(limit = 10): Promise<
Array<{
id: string;
name: string;
data: unknown;
error: unknown;
failedAt: string;
attempts: number;
}>
> {
const jobs = await this.dlq.getCompleted(0, limit);
return jobs.map(job => ({
id: job.data.originalJob.id,
name: job.data.originalJob.name,
data: job.data.originalJob.data,
error: job.data.error,
failedAt: job.data.movedToDLQAt,
attempts: job.data.originalJob.attemptsMade,
}));
}
/**
* Shutdown DLQ handler
*/
async shutdown(): Promise<void> {
await this.dlq.close();
this.failureCount.clear();
}
}

View file

@ -1,67 +1,32 @@
// Core exports
export { Queue } from './queue';
export { QueueManager } from './queue-manager';
export { ServiceCache, createServiceCache } from './service-cache';
// Service utilities
export {
normalizeServiceName,
generateCachePrefix,
getFullQueueName,
parseQueueName,
} from './service-utils';
// Batch processing
export { processBatchJob, processItems } from './batch-processor';
// DLQ handling
export { DeadLetterQueueHandler } from './dlq-handler';
// Metrics
export { QueueMetricsCollector } from './queue-metrics';
// Rate limiting
export { QueueRateLimiter } from './rate-limiter';
// Types
export type {
// Core types
JobData,
JobOptions,
QueueOptions,
GlobalStats,
// Batch processing types
BatchResult,
ProcessOptions,
BatchJobData,
// Handler types
JobHandler,
TypedJobHandler,
HandlerConfig,
HandlerConfigWithSchedule,
HandlerInitializer,
QueueStats,
QueueWorkerConfig,
// Configuration types
RedisConfig,
QueueConfig,
QueueManagerConfig,
// Rate limiting types
RateLimitConfig,
RateLimitRule,
// DLQ types
DLQConfig,
DLQJobInfo,
// Scheduled job types
ScheduledJob,
ScheduleConfig,
// Smart Queue types
SmartQueueConfig,
QueueRoute,
} from './types';

View file

@ -1,318 +0,0 @@
import { Queue, QueueEvents } from 'bullmq';
// import { getLogger } from '@stock-bot/logger';
// const logger = getLogger('queue-metrics');
interface QueueMetrics {
// Job counts
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
paused?: number;
// Performance metrics
processingTime: {
avg: number;
min: number;
max: number;
p95: number;
p99: number;
};
// Throughput
throughput: {
completedPerMinute: number;
failedPerMinute: number;
totalPerMinute: number;
};
// Job age
oldestWaitingJob: Date | null;
// Health
isHealthy: boolean;
healthIssues: string[];
}
export class QueueMetricsCollector {
private processingTimes: number[] = [];
private completedTimestamps: number[] = [];
private failedTimestamps: number[] = [];
private jobStartTimes = new Map<string, number>();
private readonly maxSamples = 1000;
private readonly metricsInterval = 60000; // 1 minute
constructor(
private queue: Queue,
private queueEvents: QueueEvents
) {
this.setupEventListeners();
}
/**
* Setup event listeners for metrics collection
*/
private setupEventListeners(): void {
this.queueEvents.on('completed', () => {
// Record completion
this.completedTimestamps.push(Date.now());
this.cleanupOldTimestamps();
});
this.queueEvents.on('failed', () => {
// Record failure
this.failedTimestamps.push(Date.now());
this.cleanupOldTimestamps();
});
// Track processing times
this.queueEvents.on('active', ({ jobId }) => {
this.jobStartTimes.set(jobId, Date.now());
});
this.queueEvents.on('completed', ({ jobId }) => {
const startTime = this.jobStartTimes.get(jobId);
if (startTime) {
const processingTime = Date.now() - startTime;
this.recordProcessingTime(processingTime);
this.jobStartTimes.delete(jobId);
}
});
}
/**
* Record processing time
*/
private recordProcessingTime(time: number): void {
this.processingTimes.push(time);
// Keep only recent samples
if (this.processingTimes.length > this.maxSamples) {
this.processingTimes = this.processingTimes.slice(-this.maxSamples);
}
}
/**
* Clean up old timestamps
*/
private cleanupOldTimestamps(): void {
const cutoff = Date.now() - this.metricsInterval;
this.completedTimestamps = this.completedTimestamps.filter(ts => ts > cutoff);
this.failedTimestamps = this.failedTimestamps.filter(ts => ts > cutoff);
}
/**
* Collect current metrics
*/
async collect(): Promise<QueueMetrics> {
// Get job counts
const [waiting, active, completed, failed, delayed] = await Promise.all([
this.queue.getWaitingCount(),
this.queue.getActiveCount(),
this.queue.getCompletedCount(),
this.queue.getFailedCount(),
this.queue.getDelayedCount(),
]);
// BullMQ doesn't have getPausedCount, check if queue is paused
const paused = (await this.queue.isPaused()) ? waiting : 0;
// Calculate processing time metrics
const processingTime = this.calculateProcessingTimeMetrics();
// Calculate throughput
const throughput = this.calculateThroughput();
// Get oldest waiting job
const oldestWaitingJob = await this.getOldestWaitingJob();
// Check health
const { isHealthy, healthIssues } = this.checkHealth({
waiting,
active,
failed,
processingTime,
});
return {
waiting,
active,
completed,
failed,
delayed,
paused,
processingTime,
throughput,
oldestWaitingJob,
isHealthy,
healthIssues,
};
}
/**
* Calculate processing time metrics
*/
private calculateProcessingTimeMetrics(): QueueMetrics['processingTime'] {
if (this.processingTimes.length === 0) {
return { avg: 0, min: 0, max: 0, p95: 0, p99: 0 };
}
const sorted = [...this.processingTimes].sort((a, b) => a - b);
const sum = sorted.reduce((acc, val) => acc + val, 0);
return {
avg: sorted.length > 0 ? Math.round(sum / sorted.length) : 0,
min: sorted[0] || 0,
max: sorted[sorted.length - 1] || 0,
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
};
}
/**
* Calculate throughput metrics
*/
private calculateThroughput(): QueueMetrics['throughput'] {
const now = Date.now();
const oneMinuteAgo = now - 60000;
const completedPerMinute = this.completedTimestamps.filter(ts => ts > oneMinuteAgo).length;
const failedPerMinute = this.failedTimestamps.filter(ts => ts > oneMinuteAgo).length;
return {
completedPerMinute,
failedPerMinute,
totalPerMinute: completedPerMinute + failedPerMinute,
};
}
/**
* Get oldest waiting job
*/
private async getOldestWaitingJob(): Promise<Date | null> {
const waitingJobs = await this.queue.getWaiting(0, 1);
if (waitingJobs.length > 0) {
return new Date(waitingJobs[0].timestamp);
}
return null;
}
/**
* Check queue health
*/
private checkHealth(metrics: {
waiting: number;
active: number;
failed: number;
processingTime: QueueMetrics['processingTime'];
}): { isHealthy: boolean; healthIssues: string[] } {
const issues: string[] = [];
// Check for high failure rate
const failureRate = metrics.failed / (metrics.failed + this.completedTimestamps.length);
if (failureRate > 0.1) {
issues.push(`High failure rate: ${(failureRate * 100).toFixed(1)}%`);
}
// Check for queue backlog
if (metrics.waiting > 1000) {
issues.push(`Large queue backlog: ${metrics.waiting} jobs waiting`);
}
// Check for slow processing
if (metrics.processingTime.avg > 30000) {
// 30 seconds
issues.push(
`Slow average processing time: ${(metrics.processingTime.avg / 1000).toFixed(1)}s`
);
}
// Check for stalled active jobs
if (metrics.active > 100) {
issues.push(`High number of active jobs: ${metrics.active}`);
}
return {
isHealthy: issues.length === 0,
healthIssues: issues,
};
}
/**
* Get formatted metrics report
*/
async getReport(): Promise<string> {
const metrics = await this.collect();
return `
Queue Metrics Report
===================
Status: ${metrics.isHealthy ? '✅ Healthy' : '⚠️ Issues Detected'}
Job Counts:
- Waiting: ${metrics.waiting}
- Active: ${metrics.active}
- Completed: ${metrics.completed}
- Failed: ${metrics.failed}
- Delayed: ${metrics.delayed}
- Paused: ${metrics.paused}
Performance:
- Avg Processing Time: ${(metrics.processingTime.avg / 1000).toFixed(2)}s
- Min/Max: ${(metrics.processingTime.min / 1000).toFixed(2)}s / ${(metrics.processingTime.max / 1000).toFixed(2)}s
- P95/P99: ${(metrics.processingTime.p95 / 1000).toFixed(2)}s / ${(metrics.processingTime.p99 / 1000).toFixed(2)}s
Throughput:
- Completed/min: ${metrics.throughput.completedPerMinute}
- Failed/min: ${metrics.throughput.failedPerMinute}
- Total/min: ${metrics.throughput.totalPerMinute}
${metrics.oldestWaitingJob ? `Oldest Waiting Job: ${metrics.oldestWaitingJob.toISOString()}` : 'No waiting jobs'}
${metrics.healthIssues.length > 0 ? `\nHealth Issues:\n${metrics.healthIssues.map(issue => `- ${issue}`).join('\n')}` : ''}
`.trim();
}
/**
* Export metrics in Prometheus format
*/
async getPrometheusMetrics(): Promise<string> {
const metrics = await this.collect();
const queueName = this.queue.name;
return `
# HELP queue_jobs_total Total number of jobs by status
# TYPE queue_jobs_total gauge
queue_jobs_total{queue="${queueName}",status="waiting"} ${metrics.waiting}
queue_jobs_total{queue="${queueName}",status="active"} ${metrics.active}
queue_jobs_total{queue="${queueName}",status="completed"} ${metrics.completed}
queue_jobs_total{queue="${queueName}",status="failed"} ${metrics.failed}
queue_jobs_total{queue="${queueName}",status="delayed"} ${metrics.delayed}
queue_jobs_total{queue="${queueName}",status="paused"} ${metrics.paused}
# HELP queue_processing_time_seconds Job processing time in seconds
# TYPE queue_processing_time_seconds summary
queue_processing_time_seconds{queue="${queueName}",quantile="0.5"} ${(metrics.processingTime.avg / 1000).toFixed(3)}
queue_processing_time_seconds{queue="${queueName}",quantile="0.95"} ${(metrics.processingTime.p95 / 1000).toFixed(3)}
queue_processing_time_seconds{queue="${queueName}",quantile="0.99"} ${(metrics.processingTime.p99 / 1000).toFixed(3)}
queue_processing_time_seconds_sum{queue="${queueName}"} ${((metrics.processingTime.avg * this.processingTimes.length) / 1000).toFixed(3)}
queue_processing_time_seconds_count{queue="${queueName}"} ${this.processingTimes.length}
# HELP queue_throughput_per_minute Jobs processed per minute
# TYPE queue_throughput_per_minute gauge
queue_throughput_per_minute{queue="${queueName}",status="completed"} ${metrics.throughput.completedPerMinute}
queue_throughput_per_minute{queue="${queueName}",status="failed"} ${metrics.throughput.failedPerMinute}
queue_throughput_per_minute{queue="${queueName}",status="total"} ${metrics.throughput.totalPerMinute}
# HELP queue_health Queue health status
# TYPE queue_health gauge
queue_health{queue="${queueName}"} ${metrics.isHealthy ? 1 : 0}
`.trim();
}
}

View file

@ -84,16 +84,6 @@ export interface GlobalStats {
uptime: number;
}
// Legacy type for backward compatibility
export interface QueueConfig extends QueueManagerConfig {
queueName?: string;
workers?: number;
concurrency?: number;
handlers?: HandlerInitializer[];
dlqConfig?: DLQConfig;
enableMetrics?: boolean;
}
// Extended batch job data for queue implementation
export interface BatchJobData {
payloadKey: string;
@ -103,10 +93,6 @@ export interface BatchJobData {
totalDelayHours: number; // Total time to distribute all batches
}
export interface HandlerInitializer {
(): void | Promise<void>;
}
// Rate limiting types
export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow;
@ -120,40 +106,6 @@ export interface RateLimitRule {
config: RateLimitConfig;
}
// DLQ types
export interface DLQConfig {
maxRetries?: number;
retryDelay?: number;
alertThreshold?: number;
cleanupAge?: number;
}
export interface DLQJobInfo {
id: string;
name: string;
failedReason: string;
attemptsMade: number;
timestamp: number;
data: unknown;
}
export interface ScheduleConfig {
pattern: string;
jobName: string;
data?: unknown;
options?: ExtendedJobOptions;
}
// Smart Queue Types
export interface SmartQueueConfig extends QueueManagerConfig {
/** Name of the current service */
serviceName: string;
/** Whether to auto-discover handlers from registry */
autoDiscoverHandlers?: boolean;
/** Custom service registry (defaults to built-in) */
serviceRegistry?: Record<string, unknown>;
}
export interface QueueRoute {
/** Full queue name (now just the handler name, e.g., 'ceo') */
fullName: string;

View file

@ -120,15 +120,17 @@ describe('Batch Processor', () => {
throw new Error('Failed to add jobs');
});
// processBatchJob should still complete even if addBulk fails
const _result = await processBatchJob(
batchData,
'test-queue',
mockQueueManager as unknown as QueueManager
);
// processBatchJob rethrows chunk errors and retains the cached payload for retry
await expect(
processBatchJob(
batchData,
'test-queue',
mockQueueManager as unknown as QueueManager
)
).rejects.toThrow('Failed to add jobs');
expect(mockQueue.addBulk).toHaveBeenCalled();
// The error is logged in addJobsInChunks, not in processBatchJob
expect(mockCache.del).not.toHaveBeenCalled();
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
});
@ -273,15 +275,15 @@ describe('Batch Processor', () => {
throw new Error('Process error');
});
// processItems catches errors and continues, so it won't reject
const result = await processItems(
items,
'test-queue',
options,
mockQueueManager as unknown as QueueManager
);
await expect(
processItems(
items,
'test-queue',
options,
mockQueueManager as unknown as QueueManager
)
).rejects.toThrow('Process error');
expect(result.jobsCreated).toBe(0);
expect(mockQueue.addBulk).toHaveBeenCalled();
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
});

View file

@ -1,278 +0,0 @@
import type { Job, Queue } from 'bullmq';
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { DeadLetterQueueHandler } from '../src/dlq-handler';
import type { RedisConfig } from '../src/types';
describe('DeadLetterQueueHandler', () => {
// Mock the DLQ Queue that will be created
const mockDLQQueue = {
name: 'test-queue-dlq',
add: mock(() => Promise.resolve({})),
getCompleted: mock(() => Promise.resolve([])),
getFailed: mock(() => Promise.resolve([])),
getWaiting: mock(() => Promise.resolve([])),
close: mock(() => Promise.resolve()),
} as unknown as Queue;
const mockLogger = {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
};
const mockQueue = {
name: 'test-queue',
add: mock(() => Promise.resolve({})),
getCompleted: mock(() => Promise.resolve([])),
getFailed: mock(() => Promise.resolve([])),
getWaiting: mock(() => Promise.resolve([])),
} as unknown as Queue;
const mockRedisConfig: RedisConfig = {
host: 'localhost',
port: 6379,
};
let dlqHandler: DeadLetterQueueHandler;
beforeEach(() => {
// Reset DLQ queue mocks
mockDLQQueue.add = mock(() => Promise.resolve({}));
mockDLQQueue.getCompleted = mock(() => Promise.resolve([]));
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
mockDLQQueue.close = mock(() => Promise.resolve());
// Create handler with mocked DLQ queue
dlqHandler = new DeadLetterQueueHandler(mockQueue, mockRedisConfig, {}, mockLogger);
// Override the dlq property to use our mock
(dlqHandler as any).dlq = mockDLQQueue;
// Reset mocks
mockLogger.info = mock(() => {});
mockLogger.error = mock(() => {});
mockLogger.warn = mock(() => {});
});
describe('handleFailedJob', () => {
it('should log failed job details', async () => {
const mockJob = {
id: 'job-123',
name: 'test-job',
queueName: 'test-queue',
data: {
handler: 'testHandler',
operation: 'testOp',
payload: { test: true },
},
attemptsMade: 3,
opts: { attempts: 3 },
failedReason: 'Test error',
finishedOn: Date.now(),
processedOn: Date.now() - 5000,
timestamp: Date.now() - 10000,
} as Job;
const error = new Error('Job processing failed');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.error).toHaveBeenCalledWith(
'Job moved to DLQ',
expect.objectContaining({
jobId: 'job-123',
jobName: 'test-job',
error: 'Job processing failed',
})
);
});
it('should handle jobs without data gracefully', async () => {
const mockJob = {
id: 'job-123',
name: 'test-job',
queueName: 'test-queue',
data: null,
attemptsMade: 3,
opts: { attempts: 3 },
timestamp: Date.now() - 10000,
processedOn: Date.now() - 5000,
} as any;
const error = new Error('No data');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.error).toHaveBeenCalled();
});
it('should check alert threshold', async () => {
const mockJob = {
id: 'job-123',
name: 'critical-job',
queueName: 'critical-queue',
data: { handler: 'critical', operation: 'process' },
attemptsMade: 3,
opts: { attempts: 3 },
} as Job;
const error = new Error('Critical failure');
await dlqHandler.handleFailedJob(mockJob, error);
expect(mockLogger.warn).toHaveBeenCalled();
});
});
describe('getStats', () => {
it('should return DLQ statistics', async () => {
const mockJobs = [
{
id: 'job-1',
data: { originalJob: { name: 'process' } },
timestamp: Date.now(),
},
{
id: 'job-2',
data: { originalJob: { name: 'process' } },
timestamp: Date.now() - 100000,
},
{
id: 'job-3',
data: { originalJob: { name: 'validate' } },
timestamp: Date.now() - 200000,
},
];
mockDLQQueue.getCompleted = mock(() => Promise.resolve(mockJobs));
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
const stats = await dlqHandler.getStats();
expect(stats.total).toBe(3);
expect(stats.byJobName['process']).toBe(2);
expect(stats.byJobName['validate']).toBe(1);
expect(stats.oldestJob).toBeDefined();
});
it('should handle empty DLQ', async () => {
const stats = await dlqHandler.getStats();
expect(stats.total).toBe(0);
expect(stats.byJobName).toEqual({});
expect(stats.oldestJob).toBeNull();
});
});
describe('retryDLQJobs', () => {
it('should retry jobs from DLQ', async () => {
const mockDLQJobs = [
{
id: 'dlq-1',
data: {
originalJob: {
id: 'orig-1',
name: 'retry-job',
data: { test: true },
opts: {},
},
},
remove: mock(() => Promise.resolve()),
},
];
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
};
const retriedCount = await dlqHandler.retryDLQJobs(1);
expect(retriedCount).toBe(1);
expect(mockQueue.add).toHaveBeenCalledWith(
'retry-job',
{ test: true },
expect.objectContaining({ delay: expect.any(Number) })
);
expect(mockDLQJobs[0].remove).toHaveBeenCalled();
});
});
describe('cleanup', () => {
it('should clean up old DLQ entries', async () => {
const oldJob = {
id: 'old-1',
timestamp: Date.now() - 8 * 24 * 60 * 60 * 1000, // 8 days old
remove: mock(() => Promise.resolve()),
};
const newJob = {
id: 'new-1',
timestamp: Date.now() - 1 * 24 * 60 * 60 * 1000, // 1 day old
remove: mock(() => Promise.resolve()),
};
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve([oldJob, newJob])),
};
const removedCount = await dlqHandler.cleanup();
expect(removedCount).toBe(1);
expect(oldJob.remove).toHaveBeenCalled();
expect(newJob.remove).not.toHaveBeenCalled();
});
});
describe('inspectFailedJobs', () => {
it('should return formatted failed jobs', async () => {
const mockDLQJobs = [
{
data: {
originalJob: {
id: 'orig-1',
name: 'test-job',
data: { test: true },
attemptsMade: 3,
},
error: {
message: 'Test error',
stack: 'Error stack',
},
movedToDLQAt: '2024-01-01T00:00:00Z',
},
},
];
(dlqHandler as any).dlq = {
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
};
const inspected = await dlqHandler.inspectFailedJobs(10);
expect(inspected).toHaveLength(1);
expect(inspected[0]).toEqual({
id: 'orig-1',
name: 'test-job',
data: { test: true },
error: { message: 'Test error', stack: 'Error stack' },
failedAt: '2024-01-01T00:00:00Z',
attempts: 3,
});
});
});
describe('shutdown', () => {
it('should close DLQ and clear state', async () => {
const mockClose = mock(() => Promise.resolve());
(dlqHandler as any).dlq = {
close: mockClose,
};
await dlqHandler.shutdown();
expect(mockClose).toHaveBeenCalled();
});
});
});

View file

@ -1,233 +0,0 @@
import type { Job, Queue, QueueEvents } from 'bullmq';
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
import { QueueMetricsCollector } from '../src/queue-metrics';
describe('QueueMetricsCollector', () => {
let metrics: QueueMetricsCollector;
let mockQueue: {
name: string;
getWaitingCount: Mock<() => Promise<number>>;
getActiveCount: Mock<() => Promise<number>>;
getCompletedCount: Mock<() => Promise<number>>;
getFailedCount: Mock<() => Promise<number>>;
getDelayedCount: Mock<() => Promise<number>>;
isPaused: Mock<() => Promise<boolean>>;
getWaiting: Mock<() => Promise<Job[]>>;
};
let mockQueueEvents: {
on: Mock<(event: string, handler: Function) => void>;
};
beforeEach(() => {
mockQueue = {
name: 'test-queue',
getWaitingCount: mock(() => Promise.resolve(0)),
getActiveCount: mock(() => Promise.resolve(0)),
getCompletedCount: mock(() => Promise.resolve(0)),
getFailedCount: mock(() => Promise.resolve(0)),
getDelayedCount: mock(() => Promise.resolve(0)),
isPaused: mock(() => Promise.resolve(false)),
getWaiting: mock(() => Promise.resolve([])),
};
mockQueueEvents = {
on: mock(() => {}),
};
metrics = new QueueMetricsCollector(
mockQueue as unknown as Queue,
mockQueueEvents as unknown as QueueEvents
);
});
describe('collect metrics', () => {
it('should collect current metrics', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
mockQueue.getDelayedCount.mockImplementation(() => Promise.resolve(1));
// Add some completed timestamps to avoid 100% failure rate
const completedHandler = mockQueueEvents.on.mock.calls.find(
call => call[0] === 'completed'
)?.[1];
if (completedHandler) {
for (let i = 0; i < 50; i++) {
completedHandler();
}
}
const result = await metrics.collect();
expect(result.waiting).toBe(5);
expect(result.active).toBe(2);
expect(result.completed).toBe(100);
expect(result.failed).toBe(3);
expect(result.delayed).toBe(1);
expect(result.isHealthy).toBe(true);
});
it('should detect health issues', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(2000)); // High backlog
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(150)); // High active
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(50));
const result = await metrics.collect();
expect(result.isHealthy).toBe(false);
expect(result.healthIssues.length).toBeGreaterThan(0);
expect(result.healthIssues.some(issue => issue.includes('queue backlog'))).toBe(true);
expect(result.healthIssues.some(issue => issue.includes('active jobs'))).toBe(true);
});
it('should handle paused queue', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(10));
mockQueue.isPaused.mockImplementation(() => Promise.resolve(true));
const result = await metrics.collect();
expect(result.paused).toBe(10);
});
});
describe('processing time metrics', () => {
it('should calculate processing time metrics', async () => {
// Access private property for testing
const metricsWithPrivate = metrics as QueueMetricsCollector & {
processingTimes: number[];
};
metricsWithPrivate.processingTimes = [1000, 2000, 3000, 4000, 5000];
const result = await metrics.collect();
expect(result.processingTime.avg).toBe(3000);
expect(result.processingTime.min).toBe(1000);
expect(result.processingTime.max).toBe(5000);
expect(result.processingTime.p95).toBe(5000);
});
it('should handle no processing times', async () => {
const result = await metrics.collect();
expect(result.processingTime.avg).toBe(0);
expect(result.processingTime.min).toBe(0);
expect(result.processingTime.max).toBe(0);
});
});
describe('throughput metrics', () => {
it('should calculate throughput', async () => {
// Access private properties for testing
const metricsWithPrivate = metrics as QueueMetricsCollector & {
completedTimestamps: number[];
failedTimestamps: number[];
};
const now = Date.now();
metricsWithPrivate.completedTimestamps = [
now - 30000, // 30 seconds ago
now - 20000,
now - 10000,
];
metricsWithPrivate.failedTimestamps = [now - 25000, now - 5000];
const result = await metrics.collect();
expect(result.throughput.completedPerMinute).toBe(3);
expect(result.throughput.failedPerMinute).toBe(2);
expect(result.throughput.totalPerMinute).toBe(5);
});
});
describe('getReport', () => {
it('should generate formatted report', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
// Add some completed timestamps to make it healthy
const completedHandler = mockQueueEvents.on.mock.calls.find(
call => call[0] === 'completed'
)?.[1];
if (completedHandler) {
for (let i = 0; i < 50; i++) {
completedHandler();
}
}
const report = await metrics.getReport();
expect(report).toContain('Queue Metrics Report');
expect(report).toContain('✅ Healthy');
expect(report).toContain('Waiting: 5');
expect(report).toContain('Active: 2');
expect(report).toContain('Completed: 100');
expect(report).toContain('Failed: 3');
});
});
describe('getPrometheusMetrics', () => {
it('should generate Prometheus formatted metrics', async () => {
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
const prometheusMetrics = await metrics.getPrometheusMetrics();
expect(prometheusMetrics).toContain('# HELP queue_jobs_total');
expect(prometheusMetrics).toContain(
'queue_jobs_total{queue="test-queue",status="waiting"} 5'
);
expect(prometheusMetrics).toContain('queue_jobs_total{queue="test-queue",status="active"} 2');
expect(prometheusMetrics).toContain(
'queue_jobs_total{queue="test-queue",status="completed"} 100'
);
expect(prometheusMetrics).toContain('# HELP queue_processing_time_seconds');
expect(prometheusMetrics).toContain('# HELP queue_throughput_per_minute');
expect(prometheusMetrics).toContain('# HELP queue_health');
});
});
describe('event listeners', () => {
it('should setup event listeners on construction', () => {
const newMockQueueEvents = {
on: mock<(event: string, handler: Function) => void>(() => {}),
};
new QueueMetricsCollector(
mockQueue as unknown as Queue,
newMockQueueEvents as unknown as QueueEvents
);
expect(newMockQueueEvents.on).toHaveBeenCalledWith('completed', expect.any(Function));
expect(newMockQueueEvents.on).toHaveBeenCalledWith('failed', expect.any(Function));
expect(newMockQueueEvents.on).toHaveBeenCalledWith('active', expect.any(Function));
});
});
describe('oldest waiting job', () => {
it('should get oldest waiting job date', async () => {
const oldJob = {
timestamp: Date.now() - 60000, // 1 minute ago
} as Job;
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([oldJob]));
const result = await metrics.collect();
expect(result.oldestWaitingJob).toBeDefined();
expect(result.oldestWaitingJob).toBeInstanceOf(Date);
});
it('should return null when no waiting jobs', async () => {
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([]));
const result = await metrics.collect();
expect(result.oldestWaitingJob).toBeNull();
});
});
});

View file

@ -23,7 +23,6 @@
"@stock-bot/postgres": "workspace:*",
"@stock-bot/proxy": "workspace:*",
"@stock-bot/questdb": "workspace:*",
"@stock-bot/queue": "workspace:*",
"playwright": "^1.40.0"
"@stock-bot/queue": "workspace:*"
}
}

View file

@ -22,7 +22,6 @@ export type QuestDBClient = Public<QuestDBImplementation>;
export type Browser = Public<BrowserImplementation>;
export type ProxyManager = Public<ProxyImplementation>;
export type { CacheProvider, CacheStats } from '@stock-bot/cache';
export type { BrowserContext, Page } from 'playwright';
export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy';
/** Disabled adapters are null; omitted capabilities are undefined. */

View file

@ -1,34 +0,0 @@
/**
* Backtesting & Strategy Types
* Types for strategy backtesting and analysis
*/
import type { PortfolioAnalysis } from './portfolio';
import type { DrawdownAnalysis, RiskMetrics } from './risk-metrics';
import type { TradeExecution, TradePerformance } from './trading';
/**
* Backtesting results
*/
export interface BacktestResults {
/** All trades executed */
trades: TradeExecution[];
/** Equity curve over time */
equityCurve: Array<{ value: number; date: Date }>;
/** Performance metrics */
performance: PortfolioAnalysis;
/** Risk metrics */
riskMetrics: RiskMetrics;
/** Drawdown analysis */
drawdownAnalysis: DrawdownAnalysis;
/** Trade performance */
tradePerformance: TradePerformance;
/** Start date */
startDate: Date;
/** End date */
endDate: Date;
/** Initial capital */
initialCapital: number;
/** Final value */
finalValue: number;
}

View file

@ -1,45 +1,3 @@
/**
* Decorator Type Definitions
* Type definitions for handler decorators
*/
/**
* Schedule configuration for operations
*/
export interface ScheduleConfig {
cronPattern: string;
priority?: number;
immediately?: boolean;
description?: string;
}
/**
* Decorator metadata stored on classes
*/
export interface DecoratorMetadata {
handlerName?: string;
operations?: Array<{
name: string;
methodName: string;
schedules?: ScheduleConfig[];
}>;
disabled?: boolean;
}
/**
* Type for decorator factories
*/
export type DecoratorFactory<T = object> = (target: T, context?: unknown) => T | void;
/**
* Type for method decorators
*/
export type MethodDecoratorFactory = (
target: object,
propertyKey: string,
descriptor?: PropertyDescriptor
) => void | PropertyDescriptor;
/** Metadata shared by decorators, discovery, and handler dispatch. */
export interface RateLimitWindow {
points: number;

View file

@ -1,197 +0,0 @@
/**
* Financial Statements Types
* Types for fundamental financial statement data
*/
/**
* Balance Sheet data structure
*/
export interface BalanceSheet {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
// Assets
/** Total current assets */
totalCurrentAssets: number;
/** Cash and cash equivalents */
cashAndEquivalents: number;
/** Short-term investments */
shortTermInvestments?: number;
/** Accounts receivable */
accountsReceivable: number;
/** Inventory */
inventory: number;
/** Prepaid expenses */
prepaidExpenses?: number;
/** Other current assets */
otherCurrentAssets?: number;
/** Total non-current assets */
totalNonCurrentAssets: number;
/** Property, plant & equipment (net) */
propertyPlantEquipmentNet: number;
/** Intangible assets */
intangibleAssets?: number;
/** Goodwill */
goodwill?: number;
/** Long-term investments */
longTermInvestments?: number;
/** Other non-current assets */
otherNonCurrentAssets?: number;
/** Total assets */
totalAssets: number;
// Liabilities
/** Total current liabilities */
totalCurrentLiabilities: number;
/** Accounts payable */
accountsPayable: number;
/** Short-term debt */
shortTermDebt: number;
/** Accrued liabilities */
accruedLiabilities?: number;
/** Other current liabilities */
otherCurrentLiabilities?: number;
/** Total non-current liabilities */
totalNonCurrentLiabilities: number;
/** Long-term debt */
longTermDebt: number;
/** Deferred tax liabilities */
deferredTaxLiabilities?: number;
/** Other non-current liabilities */
otherNonCurrentLiabilities?: number;
/** Total liabilities */
totalLiabilities: number;
// Equity
/** Total stockholders' equity */
totalStockholdersEquity: number;
/** Common stock */
commonStock: number;
/** Retained earnings */
retainedEarnings: number;
/** Additional paid-in capital */
additionalPaidInCapital?: number;
/** Treasury stock */
treasuryStock?: number;
/** Accumulated other comprehensive income */
accumulatedOtherComprehensiveIncome?: number;
}
/**
* Income Statement data structure
*/
export interface IncomeStatement {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
/** Total revenue/net sales */
totalRevenue: number;
/** Cost of goods sold */
costOfGoodsSold: number;
/** Gross profit */
grossProfit: number;
/** Operating expenses */
operatingExpenses: number;
/** Research and development */
researchAndDevelopment?: number;
/** Selling, general & administrative */
sellingGeneralAdministrative?: number;
/** Depreciation and amortization */
depreciationAmortization?: number;
/** Other operating expenses */
otherOperatingExpenses?: number;
/** Operating income */
operatingIncome: number;
/** Interest income */
interestIncome?: number;
/** Interest expense */
interestExpense?: number;
/** Other income/expense */
otherIncomeExpense?: number;
/** Income before taxes */
incomeBeforeTaxes: number;
/** Income tax expense */
incomeTaxExpense: number;
/** Net income */
netIncome: number;
/** Earnings per share (basic) */
earningsPerShareBasic: number;
/** Earnings per share (diluted) */
earningsPerShareDiluted: number;
/** Weighted average shares outstanding (basic) */
sharesOutstandingBasic: number;
/** Weighted average shares outstanding (diluted) */
sharesOutstandingDiluted: number;
}
/**
* Cash Flow Statement data structure
*/
export interface CashFlowStatement {
/** Reporting period date */
date: string;
/** Fiscal period (Q1, Q2, Q3, Q4, FY) */
period: string;
/** Currency */
currency: string;
// Operating Activities
/** Net income */
netIncome: number;
/** Depreciation and amortization */
depreciationAmortization: number;
/** Changes in working capital */
changesInWorkingCapital: number;
/** Other operating activities */
otherOperatingActivities?: number;
/** Net cash from operating activities */
netCashFromOperatingActivities: number;
// Investing Activities
/** Capital expenditures */
capitalExpenditures: number;
/** Acquisitions */
acquisitions?: number;
/** Investments */
investments?: number;
/** Other investing activities */
otherInvestingActivities?: number;
/** Net cash from investing activities */
netCashFromInvestingActivities: number;
// Financing Activities
/** Debt issuance/repayment */
debtIssuanceRepayment?: number;
/** Equity issuance/repurchase */
equityIssuanceRepurchase?: number;
/** Dividends paid */
dividendsPaid?: number;
/** Other financing activities */
otherFinancingActivities?: number;
/** Net cash from financing activities */
netCashFromFinancingActivities: number;
/** Net change in cash */
netChangeInCash: number;
/** Cash at beginning of period */
cashAtBeginningOfPeriod: number;
/** Cash at end of period */
cashAtEndOfPeriod: number;
}

View file

@ -1,19 +1,7 @@
/**
* Helper Types
* Generic utility types for making functions work across different data types
*/
/**
* Interface for data that has a close price
* Used to make functions generic across different data types
*/
export interface HasClose {
close: number;
}
/**
* Interface for data that has OHLC prices
*/
export interface HasOHLC {
open: number;
high: number;
@ -21,16 +9,6 @@ export interface HasOHLC {
close: number;
}
/**
* Interface for data that has volume
*/
export interface HasVolume {
volume: number;
}
/**
* Interface for data that has timestamp
*/
export interface HasTimestamp {
timestamp: number;
}

View file

@ -1,49 +1,9 @@
/**
* Stock Bot Types Library
* Standardized type definitions for the entire trading platform
* Standardized type definitions for the trading and research platform
*/
// Export all market data types
export type {
LiquidityMetrics,
MarketData,
MarketRegime,
OHLCV,
OHLCVWithMetadata,
} from './market-data';
// Export all portfolio & position types
export type {
AssetAllocation,
KellyParams,
PortfolioAnalysis,
PortfolioPosition,
PositionSizeParams,
} from './portfolio';
// Export all trading & execution types
export type { TradeExecution, TradePerformance } from './trading';
// Export all risk & performance metrics
export type { DrawdownAnalysis, ReturnAnalysis, RiskMetrics } from './risk-metrics';
// Export all options pricing types
export type { GreeksCalculation, OptionParameters, OptionPricing } from './options';
// Export all financial statement types
export type { BalanceSheet, CashFlowStatement, IncomeStatement } from './financial-statements';
// Export all technical analysis types
export type {
CorrelationMatrix,
CorrelationResult,
GARCHParameters,
TechnicalIndicators,
VolatilityEstimates,
} from './technical-analysis';
// Export backtesting types
export type { BacktestResults } from './backtesting';
export type { OHLCV } from './market-data';
export type {
BacktestRunConfiguration,
BacktestRunMetrics,
@ -59,11 +19,7 @@ export type {
CanonicalMetrics,
CanonicalBacktestAnalytics,
} from './canonical-analytics';
// Export helper types
export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers';
// Export handler types
export type { HasClose, HasOHLC, HasVolume } from './helpers';
export type {
ExecutionContext,
HandlerConfig,
@ -75,18 +31,7 @@ export type {
ScheduledJob,
TypedJobHandler,
} from './handlers';
// Export decorator types
export type {
ScheduleConfig,
DecoratorMetadata,
DecoratorFactory,
MethodDecoratorFactory,
} from './decorators';
// Export queue types
export type { JobData, JobOptions, QueueStats, BatchJobData, QueueWorkerConfig } from './queue';
export type {
DecoratedHandlerClass,
DecoratedHandlerMetadata,

View file

@ -1,11 +1,6 @@
/**
* Market Data Types
* Standard types for market data and pricing information
*/
/**
* Standard OHLCV (Open, High, Low, Close, Volume) data structure
* Used for candlestick/bar chart data across all market data providers
* Used for candlestick/bar chart data across market data adapters
*/
export interface OHLCV {
/** Opening price for the time period */
@ -25,83 +20,3 @@ export interface OHLCV {
/** Time interval (e.g., '1m', '5m', '1h', '1d') */
interval?: string;
}
/**
* OHLCV data with additional metadata
*/
export interface OHLCVWithMetadata extends OHLCV {
/** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */
source: string;
/** Whether this is adjusted data */
adjusted?: boolean;
/** Number of trades during the period */
trades?: number;
/** Volume weighted average price */
vwap?: number;
}
/**
* Market data structure
*/
export interface MarketData {
/** Security symbol */
symbol: string;
/** Current price */
price: number;
/** Trading volume */
volume: number;
/** Timestamp */
timestamp: number;
/** Bid price */
bid?: number;
/** Ask price */
ask?: number;
/** Bid size */
bidSize?: number;
/** Ask size */
askSize?: number;
/** Previous close */
previousClose?: number;
/** Day's high */
high?: number;
/** Day's low */
low?: number;
/** Day's open */
open?: number;
}
/**
* Market liquidity metrics
*/
export interface LiquidityMetrics {
/** Bid-ask spread */
bidAskSpread: number;
/** Bid-ask spread percentage */
bidAskSpreadPercent: number;
/** Market depth */
marketDepth: number;
/** Average daily volume */
averageDailyVolume: number;
/** Volume rate */
volumeRate: number;
/** Price impact */
priceImpact: number;
/** Liquidity score */
liquidityScore: number;
}
/**
* Market regime classification
*/
export interface MarketRegime {
/** Current regime */
regime: 'trending' | 'ranging' | 'volatile' | 'quiet';
/** Regime strength (0-1) */
strength: number;
/** Regime duration (periods) */
duration: number;
/** Trend direction (if trending) */
trendDirection?: 'up' | 'down';
/** Volatility level */
volatilityLevel: 'low' | 'medium' | 'high';
}

View file

@ -1,58 +0,0 @@
/**
* Options Pricing Types
* Types for options pricing and derivatives
*/
/**
* Options pricing parameters
*/
export interface OptionParameters {
/** Underlying asset price */
spotPrice: number;
/** Strike price */
strikePrice: number;
/** Time to expiration (in years) */
timeToExpiry: number;
/** Risk-free interest rate */
riskFreeRate: number;
/** Volatility */
volatility: number;
/** Dividend yield */
dividendYield?: number;
/** Option type */
optionType: 'call' | 'put';
}
/**
* Option pricing results
*/
export interface OptionPricing {
/** Call option price */
callPrice: number;
/** Put option price */
putPrice: number;
/** Call intrinsic value */
callIntrinsic: number;
/** Put intrinsic value */
putIntrinsic: number;
/** Call time value */
callTimeValue: number;
/** Put time value */
putTimeValue: number;
}
/**
* Option Greeks calculation
*/
export interface GreeksCalculation {
/** Delta - price sensitivity */
delta: number;
/** Gamma - delta sensitivity */
gamma: number;
/** Theta - time decay */
theta: number;
/** Vega - volatility sensitivity */
vega: number;
/** Rho - interest rate sensitivity */
rho: number;
}

View file

@ -1,108 +0,0 @@
/**
* Portfolio & Position Types
* Types for portfolio management and position tracking
*/
/**
* Individual portfolio position
*/
export interface PortfolioPosition {
/** Security symbol/ticker */
symbol: string;
/** Number of shares/units */
shares: number;
/** Average entry price */
averagePrice: number;
/** Current market price */
currentPrice: number;
/** Current market value */
marketValue: number;
/** Unrealized P&L */
unrealizedPnL: number;
/** Unrealized P&L percentage */
unrealizedPnLPercent: number;
/** Weight in portfolio */
weight: number;
/** Security type (stock, bond, option, etc.) */
securityType?: string;
/** Currency */
currency?: string;
}
/**
* Portfolio analysis metrics
*/
export interface PortfolioAnalysis {
/** Total portfolio value */
totalValue: number;
/** Total cash balance */
cash: number;
/** Total invested amount */
invested: number;
/** Total unrealized P&L */
unrealizedPnL: number;
/** Total unrealized P&L percentage */
unrealizedPnLPercent: number;
/** Total return */
totalReturn: number;
/** Total return percentage */
totalReturnPercent: number;
/** Annualized return */
annualizedReturn: number;
/** Portfolio volatility (annualized) */
volatility: number;
/** Sharpe ratio */
sharpeRatio: number;
/** Maximum drawdown */
maxDrawdown: number;
/** Number of positions */
positionCount: number;
/** Portfolio concentration (largest position weight) */
concentration: number;
}
/**
* Asset allocation breakdown
*/
export interface AssetAllocation {
/** Asset class or category */
category: string;
/** Allocation value */
value: number;
/** Allocation percentage */
percentage: number;
/** Target allocation percentage */
target?: number;
/** Deviation from target */
deviation?: number;
}
/**
* Position sizing parameters
*/
export interface PositionSizeParams {
/** Account size */
accountSize: number;
/** Risk percentage per trade */
riskPercent: number;
/** Entry price */
entryPrice: number;
/** Stop loss price */
stopPrice: number;
/** Commission per share */
commission?: number;
}
/**
* Kelly Criterion parameters
*/
export interface KellyParams {
/** Win rate (0-1) */
winRate: number;
/** Average winning trade */
averageWin: number;
/** Average losing trade */
averageLoss: number;
/** Risk-free rate */
riskFreeRate?: number;
}

View file

@ -1,86 +0,0 @@
/**
* Risk & Performance Metrics Types
* Types for risk measurement and performance analysis
*/
/**
* Comprehensive risk metrics
*/
export interface RiskMetrics {
/** Value at Risk 95% */
var95: number;
/** Value at Risk 99% */
var99: number;
/** Conditional VaR 95% */
cvar95: number;
/** Maximum drawdown */
maxDrawdown: number;
/** Volatility (annualized) */
volatility: number;
/** Downside deviation */
downside_deviation: number;
/** Calmar ratio */
calmar_ratio: number;
/** Sortino ratio */
sortino_ratio: number;
/** Beta (vs benchmark) */
beta: number;
/** Alpha (vs benchmark) */
alpha: number;
/** Sharpe ratio */
sharpeRatio: number;
/** Treynor ratio */
treynorRatio: number;
/** Tracking error */
trackingError: number;
/** Information ratio */
informationRatio: number;
}
/**
* Drawdown analysis
*/
export interface DrawdownAnalysis {
/** Maximum drawdown percentage */
maxDrawdown: number;
/** Maximum drawdown duration (days) */
maxDrawdownDuration: number;
/** Current drawdown percentage */
currentDrawdown: number;
/** Current drawdown duration (days) */
currentDrawdownDuration: number;
/** Average drawdown percentage */
averageDrawdown: number;
/** Average drawdown duration (days) */
averageDrawdownDuration: number;
/** Number of drawdown periods */
drawdownPeriods: number;
/** Recovery factor */
recoveryFactor: number;
}
/**
* Return analysis statistics
*/
export interface ReturnAnalysis {
/** Total return */
totalReturn: number;
/** Annualized return */
annualizedReturn: number;
/** Volatility (annualized) */
volatility: number;
/** Skewness */
skewness: number;
/** Kurtosis */
kurtosis: number;
/** Best period return */
bestPeriod: number;
/** Worst period return */
worstPeriod: number;
/** Positive periods percentage */
positivePeriods: number;
/** Average positive return */
averagePositiveReturn: number;
/** Average negative return */
averageNegativeReturn: number;
}

View file

@ -1,109 +0,0 @@
/**
* Technical Analysis Types
* Types for technical indicators and market analysis
*/
/**
* Technical indicators collection
*/
export interface TechnicalIndicators {
/** Simple Moving Average */
sma: number[];
/** Exponential Moving Average */
ema: number[];
/** Relative Strength Index */
rsi: number[];
/** MACD indicator */
macd: {
macd: number[];
signal: number[];
histogram: number[];
};
/** Bollinger Bands */
bollinger: {
upper: number[];
middle: number[];
lower: number[];
};
/** Average True Range */
atr: number[];
/** Stochastic Oscillator */
stochastic: {
k: number[];
d: number[];
};
/** Williams %R */
williams_r: number[];
/** Commodity Channel Index */
cci: number[];
/** Momentum */
momentum: number[];
/** Rate of Change */
roc: number[];
}
/**
* Correlation analysis result
*/
export interface CorrelationResult {
/** Correlation coefficient */
correlation: number;
/** P-value for statistical significance */
pValue: number;
/** Is statistically significant */
isSignificant: boolean;
/** Confidence interval */
confidenceInterval: [number, number];
/** Sample size */
sampleSize: number;
}
/**
* Correlation matrix
*/
export interface CorrelationMatrix {
/** Asset symbols */
symbols: string[];
/** Correlation matrix values */
matrix: number[][];
/** Eigenvalues */
eigenvalues: number[];
/** Condition number */
conditionNumber: number;
/** Is positive definite */
isPositiveDefinite: boolean;
}
/**
* Volatility estimates using different models
*/
export interface VolatilityEstimates {
/** Close-to-close volatility */
closeToClose: number;
/** Parkinson volatility */
parkinson: number;
/** Garman-Klass volatility */
garmanKlass: number;
/** Rogers-Satchell volatility */
rogersSatchell: number;
/** Yang-Zhang volatility */
yangZhang: number;
}
/**
* GARCH model parameters
*/
export interface GARCHParameters {
/** Alpha parameter */
alpha: number;
/** Beta parameter */
beta: number;
/** Omega parameter */
omega: number;
/** Log likelihood */
logLikelihood: number;
/** AIC (Akaike Information Criterion) */
aic: number;
/** BIC (Bayesian Information Criterion) */
bic: number;
}

View file

@ -1,62 +0,0 @@
/**
* Trading & Execution Types
* Types for trade execution and performance analysis
*/
/**
* Trade execution record
*/
export interface TradeExecution {
/** Trade ID */
id?: string;
/** Security symbol */
symbol: string;
/** Trade type */
type: 'buy' | 'sell' | 'short' | 'cover';
/** Number of shares/units */
quantity: number;
/** Execution price */
price: number;
/** Total trade value */
value: number;
/** Commission/fees */
commission?: number;
/** Execution timestamp */
timestamp: number;
/** Order ID reference */
orderId?: string;
/** Execution venue */
venue?: string;
}
/**
* Trade performance analysis
*/
export interface TradePerformance {
/** Total number of trades */
totalTrades: number;
/** Number of winning trades */
winningTrades: number;
/** Number of losing trades */
losingTrades: number;
/** Win rate percentage */
winRate: number;
/** Average winning trade */
averageWin: number;
/** Average losing trade */
averageLoss: number;
/** Largest winning trade */
largestWin: number;
/** Largest losing trade */
largestLoss: number;
/** Profit factor (gross profit / gross loss) */
profitFactor: number;
/** Mathematical expectancy */
expectancy: number;
/** Total gross profit */
grossProfit: number;
/** Total gross loss */
grossLoss: number;
/** Net profit */
netProfit: number;
}

View file

@ -14,8 +14,6 @@
},
"dependencies": {
"@stock-bot/logger": "*",
"@stock-bot/types": "*",
"@types/mongodb": "^4.0.7",
"mongodb": "^6.17.0"
},
"devDependencies": {

View file

@ -18,17 +18,37 @@ import type { Logger } from '@stock-bot/logger';
import type {
ConnectionEvents,
DocumentBase,
DynamicPoolConfig,
MongoDBClientConfig,
PoolMetrics,
} from './types';
/**
* MongoDB Client for Stock Bot Data Service
*
* MongoDB client focused on batch upsert operations
* with minimal configuration and no health monitoring complexity.
*/
const READ_ONLY_COLLECTION_METHODS = new Set<string | symbol>([
'find',
'findOne',
'countDocuments',
'estimatedDocumentCount',
'distinct',
'listIndexes',
'indexExists',
'indexes',
'options',
]);
const READ_ONLY_COLLECTION_PROPS = new Set<string | symbol>([
'collectionName',
'dbName',
'namespace',
'then',
]);
const READ_ONLY_DB_METHODS = new Set<string | symbol>(['listCollections', 'stats']);
const READ_ONLY_DB_PROPS = new Set<string | symbol>([
'databaseName',
'namespace',
'options',
'then',
]);
export class MongoDBClient {
private client: MongoClient | null = null;
private db: Db | null = null;
@ -38,8 +58,6 @@ export class MongoDBClient {
private isConnected = false;
private readonly metrics: PoolMetrics;
private readonly events?: ConnectionEvents;
private dynamicPoolConfig?: DynamicPoolConfig;
private poolMonitorInterval?: Timer;
constructor(mongoConfig: MongoDBClientConfig, logger: Logger, events?: ConnectionEvents) {
this.config = mongoConfig;
@ -56,9 +74,6 @@ export class MongoDBClient {
};
}
/**
* Connect to MongoDB with simple configuration
*/
async connect(retryAttempts: number = 3, retryDelay: number = 1000): Promise<void> {
if (this.isConnected && this.client) {
return;
@ -74,6 +89,7 @@ export class MongoDBClient {
this.client = new MongoClient(uri, {
maxPoolSize: this.config.poolSettings?.maxPoolSize || 10,
minPoolSize: this.config.poolSettings?.minPoolSize || 1,
maxIdleTimeMS: this.config.poolSettings?.maxIdleTime,
connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000,
socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000,
serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000,
@ -82,20 +98,15 @@ export class MongoDBClient {
await this.client.connect();
await this.client.db(this.defaultDatabase).command({ ping: 1 });
// Set default database from config
this.db = this.client.db(this.defaultDatabase);
this.isConnected = true;
// Update metrics
this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10;
this.metrics.idleConnections = this.metrics.totalConnections;
// Fire connection event
if (this.events?.onConnect) {
await Promise.resolve(this.events.onConnect());
}
// Fire pool created event
if (this.events?.onPoolCreated) {
await Promise.resolve(this.events.onPoolCreated());
}
@ -103,20 +114,14 @@ export class MongoDBClient {
this.logger.info('Successfully connected to MongoDB', {
database: this.defaultDatabase,
poolSize: this.metrics.totalConnections,
readOnly: Boolean(this.config.readOnly),
});
// Start pool monitoring if dynamic sizing is enabled
if (this.dynamicPoolConfig?.enabled) {
this.startPoolMonitoring();
}
return;
} catch (error) {
lastError = error as Error;
this.metrics.errors++;
this.metrics.lastError = lastError.message;
// Fire error event
if (this.events?.onError) {
await Promise.resolve(this.events.onError(lastError));
}
@ -124,7 +129,7 @@ export class MongoDBClient {
this.logger.error(`MongoDB connection attempt ${attempt} failed:`, error);
if (this.client) {
await this.client.close();
await this.client.close().catch(() => {});
this.client = null;
}
@ -139,27 +144,17 @@ export class MongoDBClient {
);
}
/**
* Disconnect from MongoDB
*/
async disconnect(): Promise<void> {
if (!this.client) {
return;
}
try {
// Stop pool monitoring
if (this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
await this.client.close();
this.isConnected = false;
this.client = null;
this.db = null;
// Fire disconnect event
if (this.events?.onDisconnect) {
await Promise.resolve(this.events.onDisconnect());
}
@ -171,9 +166,6 @@ export class MongoDBClient {
}
}
/**
* Set the default database for operations
*/
setDefaultDatabase(databaseName: string): void {
this.defaultDatabase = databaseName;
if (this.client) {
@ -182,28 +174,90 @@ export class MongoDBClient {
}
}
/**
* Get the current default database name
*/
getDefaultDatabase(): string {
return this.defaultDatabase;
}
/**
* Get a database instance by name
*/
getDatabase(databaseName?: string): Db {
private getRawDatabase(databaseName?: string): Db {
if (!this.client) {
throw new Error('MongoDB client not connected');
}
const dbName = databaseName || this.defaultDatabase;
return this.client.db(dbName);
return this.client.db(databaseName || this.defaultDatabase);
}
private wrapReadOnlyCollection<T extends Document>(collection: Collection<T>): Collection<T> {
return new Proxy(collection, {
get: (target, prop, receiver) => {
if (typeof prop === 'symbol' || READ_ONLY_COLLECTION_PROPS.has(prop)) {
return Reflect.get(target, prop, receiver);
}
if (prop === 'aggregate') {
return (pipeline: Document[] = [], options?: AggregateOptions) => {
this.assertReadOnlyPipeline(pipeline);
return target.aggregate(pipeline, options);
};
}
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {
const fn = Reflect.get(target, prop, target);
return typeof fn === 'function' ? fn.bind(target) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; collection operation "${String(prop)}" is forbidden`
);
};
},
});
}
private wrapReadOnlyDatabase(db: Db): Db {
return new Proxy(db, {
get: (target, prop, receiver) => {
if (typeof prop === 'symbol' || READ_ONLY_DB_PROPS.has(prop)) {
return Reflect.get(target, prop, receiver);
}
if (prop === 'collection') {
return <T extends Document = Document>(name: string) =>
this.wrapReadOnlyCollection(target.collection<T>(name));
}
if (READ_ONLY_DB_METHODS.has(prop)) {
const fn = Reflect.get(target, prop, target);
return typeof fn === 'function' ? fn.bind(target) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; database operation "${String(prop)}" is forbidden`
);
};
},
});
}
getDatabase(databaseName?: string): Db {
const raw = this.getRawDatabase(databaseName);
return this.config.readOnly ? this.wrapReadOnlyDatabase(raw) : raw;
}
getDb(dbName?: string): Db {
return this.getDatabase(dbName);
}
get database(): Db | null {
if (!this.db) {
return null;
}
return this.config.readOnly ? this.wrapReadOnlyDatabase(this.db) : this.db;
}
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const raw = this.getRawDatabase(database).collection<T>(name);
return this.config.readOnly ? this.wrapReadOnlyCollection(raw) : raw;
}
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
/**
* Check whether this client is locked to read-only mode
*/
isReadOnly(): boolean {
return this.config.readOnly === true;
}
@ -221,7 +275,9 @@ export class MongoDBClient {
return;
}
const checkStage = (value: unknown): void => {
if (!value || typeof value !== 'object') return;
if (!value || typeof value !== 'object') {
return;
}
for (const [key, child] of Object.entries(value)) {
if (key === '$out' || key === '$merge') {
throw new Error(
@ -236,10 +292,6 @@ export class MongoDBClient {
}
}
/**
* Batch upsert documents for high-performance operations
* Supports single or multiple unique keys for matching
*/
async batchUpsert<T extends DocumentBase>(
collectionName: string,
documents: Array<
@ -248,7 +300,7 @@ export class MongoDBClient {
uniqueKeys: string | string[],
options: {
chunkSize?: number;
database?: string; // Optional database override
database?: string;
} = {}
): Promise<{ insertedCount: number; updatedCount: number; errors: unknown[] }> {
this.assertWritable(`batchUpsert(${collectionName})`);
@ -260,42 +312,24 @@ export class MongoDBClient {
return { insertedCount: 0, updatedCount: 0, errors: [] };
}
// Normalize uniqueKeys to array
const keyFields = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys];
if (keyFields.length === 0) {
throw new Error('At least one unique key must be provided');
}
const { chunkSize = 10000, database } = options;
const db = this.getDatabase(database);
const collection = db.collection<T>(collectionName);
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const operationId = Math.random().toString(36).substring(7);
const dbName = database || this.defaultDatabase;
let totalInserted = 0;
let totalUpdated = 0;
const errors: unknown[] = [];
this.logger.debug(
`Starting batch upsert operation [${collectionName}-${documents.length}][${operationId}]`,
{
database: dbName,
collection: collectionName,
totalDocuments: documents.length,
uniqueKeys: keyFields,
chunkSize,
}
);
// Process documents in chunks to avoid memory issues
for (let i = 0; i < documents.length; i += chunkSize) {
const chunk = documents.slice(i, i + chunkSize);
try {
const startTime = Date.now();
// Prepare bulk operations
const bulkOps = chunk.map(doc => {
const now = new Date();
const docWithTimestamps = {
@ -304,17 +338,15 @@ export class MongoDBClient {
updated_at: now,
};
// Create filter using multiple unique keys
const filter: Record<string, unknown> = {};
keyFields.forEach(key => {
for (const key of keyFields) {
const value = (doc as Record<string, unknown>)[key];
if (value === undefined || value === null) {
throw new Error(`Document missing required unique key: ${key}`);
}
filter[key] = value;
});
}
// Remove created_at from $set to avoid conflict with $setOnInsert
const { created_at, ...updateFields } = docWithTimestamps;
return {
@ -329,22 +361,16 @@ export class MongoDBClient {
};
});
// Execute bulk operation with type assertion to handle complex MongoDB types
const result = await collection.bulkWrite(bulkOps as never, { ordered: false });
const executionTime = Date.now() - startTime;
const inserted = result.upsertedCount;
const updated = result.modifiedCount;
totalInserted += inserted;
totalUpdated += updated;
totalInserted += result.upsertedCount;
totalUpdated += result.modifiedCount;
this.logger.debug(`Batch upsert chunk processed [${operationId}]`, {
chunkNumber: Math.floor(i / chunkSize) + 1,
chunkSize: chunk.length,
inserted,
updated,
executionTime,
inserted: result.upsertedCount,
updated: result.modifiedCount,
executionTime: Date.now() - startTime,
database: dbName,
collection: collectionName,
});
@ -358,45 +384,13 @@ export class MongoDBClient {
chunkSize: chunk.length,
uniqueKeys: keyFields,
});
errors.push(error);
throw error;
}
}
this.logger.debug(
`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`,
{
database: dbName,
collection: collectionName,
totalRecords: documents.length,
inserted: totalInserted,
updated: totalUpdated,
errors: errors.length,
uniqueKeys: keyFields,
}
);
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors };
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors: [] };
}
/**
* Get a typed collection
*/
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const db = this.getDatabase(database);
return db.collection<T>(name);
}
/**
* Get a collection (interface compatibility method)
* This method provides compatibility with the IMongoDBClient interface
*/
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
/**
* Simple insert operation
*/
async insertOne<T extends DocumentBase>(
collectionName: string,
document: Omit<T, '_id' | 'created_at' | 'updated_at'> &
@ -404,7 +398,7 @@ export class MongoDBClient {
database?: string
): Promise<T> {
this.assertWritable(`insertOne(${collectionName})`);
const collection = this.getCollection<T>(collectionName, database);
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const now = new Date();
const docWithTimestamps = {
@ -417,9 +411,6 @@ export class MongoDBClient {
return { ...docWithTimestamps, _id: result.insertedId } as T;
}
/**
* Insert multiple documents
*/
async insertMany<T extends Document = Document>(
collectionName: string,
documents: T[],
@ -427,7 +418,7 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`insertMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const now = new Date();
const docsWithTimestamps = documents.map(doc => ({
@ -446,9 +437,6 @@ export class MongoDBClient {
};
}
/**
* Find multiple documents
*/
async find<T extends Document = Document>(
collectionName: string,
filter: Filter<Document> = {},
@ -460,9 +448,6 @@ export class MongoDBClient {
return (await cursor.toArray()) as T[];
}
/**
* Find a single document
*/
async findOne<T extends Document = Document>(
collectionName: string,
filter: Filter<Document>,
@ -474,9 +459,21 @@ export class MongoDBClient {
return result as T | null;
}
/**
* Update a single document
*/
private withUpdatedTimestamp(update: Document): Document {
const now = new Date();
const hasOperator = Object.keys(update).some(key => key.startsWith('$'));
if (!hasOperator) {
return { $set: { ...update, updated_at: now } };
}
return {
...update,
$set: {
...(update.$set && typeof update.$set === 'object' ? update.$set : {}),
updated_at: now,
},
};
}
async updateOne(
collectionName: string,
filter: Filter<Document>,
@ -485,16 +482,8 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`updateOne(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
if (update.$set) {
update.$set.updated_at = new Date();
} else if (!update.$setOnInsert && !update.$unset && !update.$inc) {
update = { $set: { ...update, updated_at: new Date() } };
}
const result = await collection.updateOne(filter, update, options);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateOne(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
@ -503,9 +492,6 @@ export class MongoDBClient {
};
}
/**
* Update multiple documents
*/
async updateMany(
collectionName: string,
filter: Filter<Document>,
@ -514,16 +500,8 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`updateMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
if (update.$set) {
update.$set.updated_at = new Date();
} else if (!update.$setOnInsert && !update.$unset && !update.$inc) {
update = { $set: { ...update, updated_at: new Date() } };
}
const result = await collection.updateMany(filter, update, options);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateMany(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
@ -532,9 +510,6 @@ export class MongoDBClient {
};
}
/**
* Delete a single document
*/
async deleteOne(
collectionName: string,
filter: Filter<Document>,
@ -542,16 +517,11 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`deleteOne(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteOne(filter, options);
return {
deletedCount: result.deletedCount,
};
return { deletedCount: result.deletedCount };
}
/**
* Delete multiple documents
*/
async deleteMany(
collectionName: string,
filter: Filter<Document>,
@ -559,16 +529,11 @@ export class MongoDBClient {
dbName?: string
) {
this.assertWritable(`deleteMany(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteMany(filter, options);
return {
deletedCount: result.deletedCount,
};
return { deletedCount: result.deletedCount };
}
/**
* Count documents matching a filter
*/
async countDocuments(
collectionName: string,
filter: Filter<Document> = {},
@ -579,9 +544,6 @@ export class MongoDBClient {
return await collection.countDocuments(filter, options);
}
/**
* Perform aggregation operations
*/
async aggregate<T extends Document = Document>(
collectionName: string,
pipeline: Document[],
@ -589,14 +551,11 @@ export class MongoDBClient {
dbName?: string
): Promise<T[]> {
this.assertReadOnlyPipeline(pipeline);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const cursor = collection.aggregate(pipeline, options);
return (await cursor.toArray()) as T[];
}
/**
* Create an index
*/
async createIndex(
collectionName: string,
indexSpec: IndexSpecification,
@ -604,13 +563,10 @@ export class MongoDBClient {
dbName?: string
): Promise<string> {
this.assertWritable(`createIndex(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
return await collection.createIndex(indexSpec, options);
}
/**
* Drop an index
*/
async dropIndex(
collectionName: string,
indexName: string,
@ -618,118 +574,44 @@ export class MongoDBClient {
dbName?: string
): Promise<void> {
this.assertWritable(`dropIndex(${collectionName})`);
const collection = this.getCollection(collectionName, dbName);
const collection = this.getRawDatabase(dbName).collection(collectionName);
await collection.dropIndex(indexName, options);
}
/**
* List all indexes on a collection
*/
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
const collection = this.getCollection(collectionName, dbName);
const cursor = collection.listIndexes();
return await cursor.toArray();
}
/**
* Get a database instance (interface compatibility)
*/
getDb(dbName?: string): Db {
return this.getDatabase(dbName);
}
/**
* Create a new collection
*/
async createCollection(
collectionName: string,
options?: CreateCollectionOptions,
dbName?: string
): Promise<void> {
this.assertWritable(`createCollection(${collectionName})`);
const db = this.getDatabase(dbName);
const db = this.getRawDatabase(dbName);
await db.createCollection(collectionName, options);
}
/**
* Drop a collection
*/
async dropCollection(collectionName: string, dbName?: string): Promise<void> {
this.assertWritable(`dropCollection(${collectionName})`);
const db = this.getDatabase(dbName);
const db = this.getRawDatabase(dbName);
await db.dropCollection(collectionName);
}
/**
* List all collections in a database
*/
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
const db = this.getDatabase(dbName);
const collections = await db.listCollections(filter).toArray();
return collections;
return await db.listCollections(filter).toArray();
}
/**
* Check if client is connected
*/
get connected(): boolean {
return this.isConnected && !!this.client;
}
/**
* Get the default database instance
*/
get database(): Db | null {
return this.db;
}
/**
* Convenience methods for common databases
*/
// Stock database operations
async batchUpsertStock<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'stock',
});
}
// Trading documents database operations
async batchUpsertTrading<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'trading_documents',
});
}
// Analytics database operations
async batchUpsertAnalytics<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: { chunkSize?: number } = {}
) {
return this.batchUpsert(collectionName, documents, uniqueKeys, {
...options,
database: 'analytics',
});
getPoolMetrics(): PoolMetrics {
this.metrics.lastUsed = new Date();
return { ...this.metrics };
}
private buildConnectionUri(): string {
@ -738,136 +620,12 @@ export class MongoDBClient {
}
const { host, port, username, password, database, authSource } = this.config;
// Build URI components
const auth = username && password ? `${username}:${password}@` : '';
const authParam = authSource && username ? `?authSource=${authSource}` : '';
const auth =
username && password !== undefined
? `${encodeURIComponent(username)}:${encodeURIComponent(password)}@`
: '';
const authParam = authSource && username ? `?authSource=${encodeURIComponent(authSource)}` : '';
return `mongodb://${auth}${host}:${port}/${database}${authParam}`;
}
/**
* Get current pool metrics
*/
getPoolMetrics(): PoolMetrics {
// Update last used timestamp
this.metrics.lastUsed = new Date();
// Note: MongoDB driver doesn't expose detailed pool metrics
// These are estimates based on configuration
return { ...this.metrics };
}
/**
* Set dynamic pool configuration
*/
setDynamicPoolConfig(config: DynamicPoolConfig): void {
this.dynamicPoolConfig = config;
if (config.enabled && this.isConnected && !this.poolMonitorInterval) {
this.startPoolMonitoring();
} else if (!config.enabled && this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
}
/**
* Start monitoring pool and adjust size dynamically
*/
private startPoolMonitoring(): void {
if (!this.dynamicPoolConfig || this.poolMonitorInterval) {
return;
}
this.poolMonitorInterval = setInterval(() => {
this.evaluatePoolSize();
}, this.dynamicPoolConfig.evaluationInterval);
}
/**
* Evaluate and adjust pool size based on usage
*/
private async evaluatePoolSize(): Promise<void> {
if (!this.dynamicPoolConfig || !this.client) {
return;
}
const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig;
const currentSize = this.metrics.totalConnections;
const utilization = (this.metrics.activeConnections / currentSize) * 100;
this.logger.debug('Pool utilization', {
utilization: `${utilization.toFixed(1)}%`,
active: this.metrics.activeConnections,
total: currentSize,
});
// Scale up if utilization is high
if (utilization > scaleUpThreshold && currentSize < maxSize) {
const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize);
await this.resizePool(newSize);
this.logger.info('Scaling up connection pool', {
from: currentSize,
to: newSize,
utilization,
});
}
// Scale down if utilization is low
else if (utilization < scaleDownThreshold && currentSize > minSize) {
const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize);
await this.resizePool(newSize);
this.logger.info('Scaling down connection pool', {
from: currentSize,
to: newSize,
utilization,
});
}
}
/**
* Resize the connection pool
* Note: MongoDB driver doesn't support dynamic resizing, this would require reconnection
*/
private async resizePool(newSize: number): Promise<void> {
// MongoDB doesn't support dynamic pool resizing
// This is a placeholder for future implementation
this.logger.warn('Dynamic pool resizing not yet implemented for MongoDB', {
requestedSize: newSize,
});
// Update metrics to reflect desired state
this.metrics.totalConnections = newSize;
}
/**
* Enable pool warmup on connect
*/
async warmupPool(): Promise<void> {
if (!this.client || !this.isConnected) {
throw new Error('Client not connected');
}
const minSize = this.config.poolSettings?.minPoolSize || 1;
const promises: Promise<void>[] = [];
// Create minimum connections by running parallel pings
for (let i = 0; i < minSize; i++) {
promises.push(
this.client
.db(this.defaultDatabase)
.admin()
.ping()
.then(() => {
this.logger.debug(`Warmed up connection ${i + 1}/${minSize}`);
})
.catch(error => {
this.logger.warn(`Failed to warm up connection ${i + 1}`, { error });
})
);
}
await Promise.allSettled(promises);
this.logger.info('Connection pool warmup complete', { connections: minSize });
}
}

View file

@ -1,29 +1,10 @@
/**
* MongoDB Client Library for Stock Bot Data Service
*
* Provides a MongoDB client focused on batch upsert operations
* for high-performance data ingestion.
*/
export { MongoDBClient } from './client';
// Types
export type {
AnalystReport,
ConnectionEvents,
DocumentBase,
DynamicPoolConfig,
EarningsTranscript,
ExchangeSourceMapping,
MasterExchange,
MongoDBClientConfig,
MongoDBConnectionOptions,
NewsArticle,
PoolMetrics,
RawDocument,
SecFiling,
SentimentData,
} from './types';
// Note: Factory functions removed - use Awilix DI container instead
// See: libs/core/di/src/awilix-container.ts

View file

@ -1,8 +1,5 @@
import type { ObjectId } from 'mongodb';
/**
* MongoDB Client Configuration
*/
export interface MongoDBClientConfig {
host: string;
port: number;
@ -35,9 +32,6 @@ export interface MongoDBClientConfig {
};
}
/**
* MongoDB Connection Options
*/
export interface MongoDBConnectionOptions {
retryAttempts?: number;
retryDelay?: number;
@ -63,20 +57,6 @@ export interface ConnectionEvents {
onPoolCreated?: () => void | Promise<void>;
}
export interface DynamicPoolConfig {
enabled: boolean;
minSize: number;
maxSize: number;
scaleUpThreshold: number; // % of pool in use (0-100)
scaleDownThreshold: number; // % of pool idle (0-100)
scaleUpIncrement: number; // connections to add
scaleDownIncrement: number; // connections to remove
evaluationInterval: number; // ms between checks
}
/**
* Base Document Interface
*/
export interface DocumentBase {
_id?: ObjectId;
created_at: Date;
@ -85,129 +65,6 @@ export interface DocumentBase {
metadata?: Record<string, unknown>;
}
/**
* Sentiment Data Document
*/
export interface SentimentData extends DocumentBase {
symbol: string;
sentiment_score: number;
sentiment_label: 'positive' | 'negative' | 'neutral';
confidence: number;
text: string;
source_type: 'reddit' | 'twitter' | 'news' | 'forums';
source_id: string;
timestamp: Date;
processed_at: Date;
language: string;
keywords: string[];
entities: Array<{
name: string;
type: string;
confidence: number;
}>;
}
/**
* Raw Document
*/
export interface RawDocument extends DocumentBase {
document_type: 'html' | 'pdf' | 'text' | 'json' | 'xml';
content: string;
content_hash: string;
url?: string;
title?: string;
author?: string;
published_date?: Date;
extracted_text?: string;
processing_status: 'pending' | 'processed' | 'failed';
size_bytes: number;
language?: string;
}
/**
* News Article
*/
export interface NewsArticle extends DocumentBase {
headline: string;
content: string;
summary?: string;
author: string;
publication: string;
published_date: Date;
url: string;
symbols: string[];
categories: string[];
sentiment_score?: number;
relevance_score?: number;
image_url?: string;
tags: string[];
}
/**
* SEC Filing
*/
export interface SecFiling extends DocumentBase {
cik: string;
accession_number: string;
filing_type: string;
company_name: string;
symbols: string[];
filing_date: Date;
period_end_date: Date;
url: string;
content: string;
extracted_data?: Record<string, unknown>;
financial_statements?: Array<{
statement_type: string;
data: Record<string, number>;
}>;
processing_status: 'pending' | 'processed' | 'failed';
}
/**
* Earnings Transcript
*/
export interface EarningsTranscript extends DocumentBase {
symbol: string;
company_name: string;
quarter: string;
year: number;
call_date: Date;
transcript: string;
participants: Array<{
name: string;
title: string;
type: 'executive' | 'analyst';
}>;
key_topics: string[];
sentiment_analysis?: {
overall_sentiment: number;
topic_sentiments: Record<string, number>;
};
financial_highlights?: Record<string, number>;
}
/**
* Analyst Report
*/
export interface AnalystReport extends DocumentBase {
symbol: string;
analyst_firm: string;
analyst_name: string;
report_title: string;
report_date: Date;
rating: 'buy' | 'hold' | 'sell' | 'strong_buy' | 'strong_sell';
price_target?: number;
previous_rating?: string;
content: string;
summary: string;
key_points: string[];
financial_projections?: Record<string, number>;
}
/**
* Exchange-related types
*/
export interface ExchangeSourceMapping {
id: string;
name: string;
@ -224,13 +81,11 @@ export interface MasterExchange extends DocumentBase {
currency: string;
timezone: string;
active?: boolean;
tradingHours?: {
open: string;
close: string;
timezone: string;
};
sourceMappings: Record<string, ExchangeSourceMapping>;
confidence: number;
verified: boolean;

View file

@ -1,197 +0,0 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import { SimpleMongoDBClient } from './support/simple-mongodb';
describe('MongoDBClient', () => {
let client: SimpleMongoDBClient;
const config = {
uri: 'mongodb://localhost:27017',
database: 'test-db',
};
beforeEach(() => {
client = new SimpleMongoDBClient(config);
});
describe('connection', () => {
it('should connect on first operation', async () => {
const results = await client.find('test-collection', {});
expect(results).toBeDefined();
expect(results).toEqual([]);
});
it('should handle health check', async () => {
// Connect first by doing an operation
await client.find('test', {});
const health = await client.healthCheck();
expect(health.status).toBe('healthy');
expect(health.isConnected).toBe(true);
});
it('should disconnect properly', async () => {
await client.find('test', {});
await client.disconnect();
const health = await client.healthCheck();
expect(health.isConnected).toBe(false);
});
});
describe('CRUD operations', () => {
it('should find documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: true });
await client.insert('users', { id: 3, active: false });
const results = await client.find('users', { active: true });
expect(results).toHaveLength(2);
expect(results[0].active).toBe(true);
expect(results[1].active).toBe(true);
});
it('should find one document', async () => {
await client.insert('users', { id: 1, name: 'Test' });
await client.insert('users', { id: 2, name: 'Other' });
const result = await client.findOne('users', { id: 1 });
expect(result).toBeDefined();
expect(result.id).toBe(1);
expect(result.name).toBe('Test');
});
it('should insert documents', async () => {
const doc = { name: 'Test User', email: 'test@example.com' };
await client.insert('users', doc);
const result = await client.findOne('users', { email: 'test@example.com' });
expect(result).toBeDefined();
expect(result.name).toBe('Test User');
});
it('should insert many documents', async () => {
const docs = [{ name: 'User 1' }, { name: 'User 2' }];
await client.insertMany('users', docs);
const all = await client.find('users', {});
expect(all).toHaveLength(2);
});
it('should update documents', async () => {
await client.insert('users', { id: 1, active: true });
const updated = await client.update('users', { id: 1 }, { $set: { active: false } });
expect(updated).toBe(1);
const result = await client.findOne('users', { id: 1 });
expect(result.active).toBe(false);
});
it('should update many documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: true });
await client.insert('users', { id: 3, active: false });
const updated = await client.updateMany(
'users',
{ active: true },
{ $set: { status: 'active' } }
);
expect(updated).toBe(2);
const activeUsers = await client.find('users', { status: 'active' });
expect(activeUsers).toHaveLength(2);
});
it('should delete documents', async () => {
await client.insert('users', { id: 1 });
await client.insert('users', { id: 2 });
const deleted = await client.delete('users', { id: 1 });
expect(deleted).toBe(1);
const remaining = await client.find('users', {});
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe(2);
});
it('should delete many documents', async () => {
await client.insert('users', { id: 1, active: true });
await client.insert('users', { id: 2, active: false });
await client.insert('users', { id: 3, active: false });
const deleted = await client.deleteMany('users', { active: false });
expect(deleted).toBe(2);
const remaining = await client.find('users', {});
expect(remaining).toHaveLength(1);
expect(remaining[0].active).toBe(true);
});
});
describe('batch operations', () => {
it('should perform batch upsert', async () => {
const docs = [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
];
await client.batchUpsert('users', docs, ['id']);
const all = await client.find('users', {});
expect(all).toHaveLength(2);
// Update existing
await client.batchUpsert('users', [{ id: 1, name: 'Updated User 1' }], ['id']);
const updated = await client.findOne('users', { id: 1 });
expect(updated.name).toBe('Updated User 1');
});
it('should handle empty batch', async () => {
await client.batchUpsert('users', [], ['id']);
const all = await client.find('users', {});
expect(all).toHaveLength(0);
});
});
describe('utility methods', () => {
it('should count documents', async () => {
await client.insert('users', { active: true });
await client.insert('users', { active: true });
await client.insert('users', { active: false });
const count = await client.count('users', { active: true });
expect(count).toBe(2);
});
it('should create indexes', async () => {
await client.createIndex('users', { email: 1 }, { unique: true });
// Simple implementation doesn't throw, just no-op
expect(true).toBe(true);
});
});
describe('error handling', () => {
it('should handle disconnected state', async () => {
await client.disconnect();
// Simple implementation auto-reconnects
const results = await client.find('users', {});
expect(results).toBeDefined();
});
it('should return empty array for non-existent collection', async () => {
const results = await client.find('non-existent', {});
expect(results).toEqual([]);
});
});
});

View file

@ -1,165 +0,0 @@
/**
* Test-only in-memory MongoDB double. Never used by production adapters.
*/
export class SimpleMongoDBClient {
private collections = new Map<string, any[]>();
private connected = false;
constructor(private config: any) {}
async connect(): Promise<void> {
this.connected = true;
}
async disconnect(): Promise<void> {
this.connected = false;
}
async find(collection: string, filter: any = {}): Promise<any[]> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
// Simple filter matching
if (Object.keys(filter).length === 0) {
return docs;
}
return docs.filter(doc => {
for (const [key, value] of Object.entries(filter)) {
if (doc[key] !== value) {
return false;
}
}
return true;
});
}
async findOne(collection: string, filter: any = {}): Promise<any | null> {
const results = await this.find(collection, filter);
return results[0] || null;
}
async insert(collection: string, doc: any): Promise<void> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
docs.push({ ...doc, _id: Math.random().toString(36) });
this.collections.set(collection, docs);
}
async insertMany(collection: string, documents: any[]): Promise<void> {
for (const doc of documents) {
await this.insert(collection, doc);
}
}
async update(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
if (docs.length === 0) {
return 0;
}
const doc = docs[0];
if (update.$set) {
Object.assign(doc, update.$set);
}
return 1;
}
async updateMany(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
for (const doc of docs) {
if (update.$set) {
Object.assign(doc, update.$set);
}
}
return docs.length;
}
async delete(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
if (toDelete.length === 0) {
return 0;
}
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return 1;
}
async deleteMany(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return toDelete.length;
}
async batchUpsert(collection: string, documents: any[], uniqueKeys: string[]): Promise<void> {
if (!this.connected) {
await this.connect();
}
for (const doc of documents) {
const filter: any = {};
for (const key of uniqueKeys) {
filter[key] = doc[key];
}
const existing = await this.findOne(collection, filter);
if (existing) {
await this.update(collection, filter, { $set: doc });
} else {
await this.insert(collection, doc);
}
}
}
async count(collection: string, filter: any = {}): Promise<number> {
const docs = await this.find(collection, filter);
return docs.length;
}
async createIndex(_collection: string, _index: any, _options?: any): Promise<void> {
// No-op for simple implementation
}
async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> {
try {
return {
status: this.connected ? 'healthy' : 'unhealthy',
isConnected: this.connected,
};
} catch (error: any) {
return {
status: 'unhealthy',
isConnected: false,
error: error.message,
};
}
}
}

View file

@ -14,7 +14,6 @@
},
"dependencies": {
"@stock-bot/logger": "*",
"@stock-bot/types": "*",
"pg": "^8.11.3",
"@stock-bot/invariants": "workspace:*"
},

View file

@ -1,13 +1,9 @@
import type { PoolConfig, QueryResultRow } from 'pg';
import { Pool } from 'pg';
import { at } from '@stock-bot/invariants';
import type { LoggerLike } from '@stock-bot/logger';
import { PostgreSQLHealthMonitor } from './health';
import { PostgreSQLQueryBuilder } from './query-builder';
import { PostgreSQLTransactionManager } from './transactions';
import type {
ConnectionEvents,
DynamicPoolConfig,
PoolMetrics,
PostgreSQLClientConfig,
PostgreSQLConnectionOptions,
@ -15,24 +11,15 @@ import type {
TransactionCallback,
} from './types';
/**
* PostgreSQL Client for Stock Bot
*
* Provides type-safe access to PostgreSQL with connection pooling,
* health monitoring, and transaction support.
*/
export class PostgreSQLClient {
private pool: Pool | null = null;
private readonly config: PostgreSQLClientConfig;
private readonly options: PostgreSQLConnectionOptions;
private readonly logger: LoggerLike;
private readonly healthMonitor: PostgreSQLHealthMonitor;
private readonly transactionManager: PostgreSQLTransactionManager;
private isConnected = false;
private readonly metrics: PoolMetrics;
private readonly events?: ConnectionEvents;
private dynamicPoolConfig?: DynamicPoolConfig;
private poolMonitorInterval?: NodeJS.Timeout;
constructor(
config: PostgreSQLClientConfig,
@ -44,15 +31,11 @@ export class PostgreSQLClient {
this.options = {
retryAttempts: 3,
retryDelay: 1000,
healthCheckInterval: 30000,
...options,
};
this.events = events;
this.logger = logger || console;
this.healthMonitor = new PostgreSQLHealthMonitor(this);
this.transactionManager = new PostgreSQLTransactionManager(this);
this.metrics = {
totalConnections: 0,
activeConnections: 0,
@ -63,71 +46,48 @@ export class PostgreSQLClient {
};
}
/**
* Connect to PostgreSQL
*/
async connect(): Promise<void> {
if (this.isConnected && this.pool) {
return;
}
let lastError: Error | null = null;
const attempts = this.options.retryAttempts ?? 3;
for (let attempt = 1; attempt <= (this.options.retryAttempts ?? 3); attempt++) {
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
this.logger.info(
`Connecting to PostgreSQL (attempt ${attempt}/${this.options.retryAttempts})...`
);
this.logger.info(`Connecting to PostgreSQL (attempt ${attempt}/${attempts})...`);
this.pool = new Pool(this.buildPoolConfig());
// Test the connection
const client = await this.pool.connect();
await client.query('SELECT 1');
client.release();
try {
await client.query('SELECT 1');
} finally {
client.release();
}
this.isConnected = true;
this.metrics.totalConnections = this.config.poolSettings?.max || 10;
this.metrics.idleConnections = this.pool.idleCount;
// Update metrics
const poolConfig = this.config.poolSettings;
this.metrics.totalConnections = poolConfig?.max || 10;
this.metrics.idleConnections = poolConfig?.min || 2;
// Fire connection event
if (this.events?.onConnect) {
await Promise.resolve(this.events.onConnect());
}
// Fire pool created event
if (this.events?.onPoolCreated) {
await Promise.resolve(this.events.onPoolCreated());
}
this.setupErrorHandlers();
this.logger.info('Successfully connected to PostgreSQL', {
poolSize: this.metrics.totalConnections,
});
// Start health monitoring
this.healthMonitor.start();
// Setup error handlers
this.setupErrorHandlers();
// Setup pool event listeners for metrics
this.setupPoolMetrics();
// Start dynamic pool monitoring if enabled
if (this.dynamicPoolConfig?.enabled) {
this.startPoolMonitoring();
}
return;
} catch (error) {
lastError = error as Error;
this.metrics.errors++;
this.metrics.lastError = lastError.message;
// Fire error event
if (this.events?.onError) {
await Promise.resolve(this.events.onError(lastError));
}
@ -135,42 +95,31 @@ export class PostgreSQLClient {
this.logger.error(`PostgreSQL connection attempt ${attempt} failed:`, error);
if (this.pool) {
await this.pool.end();
await this.pool.end().catch(() => {});
this.pool = null;
}
if (attempt < (this.options.retryAttempts ?? 3)) {
await this.delay((this.options.retryDelay ?? 1000) * attempt);
if (attempt < attempts) {
await new Promise(resolve => setTimeout(resolve, (this.options.retryDelay ?? 1000) * attempt));
}
}
}
throw new Error(
`Failed to connect to PostgreSQL after ${this.options.retryAttempts} attempts: ${lastError?.message}`
`Failed to connect to PostgreSQL after ${attempts} attempts: ${lastError?.message}`
);
}
/**
* Disconnect from PostgreSQL
*/
async disconnect(): Promise<void> {
if (!this.pool) {
return;
}
try {
// Stop pool monitoring
if (this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
this.healthMonitor.stop();
await this.pool.end();
this.isConnected = false;
this.pool = null;
// Fire disconnect event
if (this.events?.onDisconnect) {
await Promise.resolve(this.events.onDisconnect());
}
@ -182,9 +131,6 @@ export class PostgreSQLClient {
}
}
/**
* Execute a query
*/
async query<T extends QueryResultRow = QueryResultRow>(
text: string,
params?: unknown[]
@ -194,16 +140,13 @@ export class PostgreSQLClient {
}
const startTime = Date.now();
try {
const result = await this.pool.query<T>(text, params);
const executionTime = Date.now() - startTime;
this.logger.debug(`Query executed in ${executionTime}ms`, {
query: text.substring(0, 100),
params: params?.length,
});
return {
...result,
executionTime,
@ -219,204 +162,13 @@ export class PostgreSQLClient {
}
}
/**
* Execute multiple queries in a transaction
*/
async transaction<T>(callback: TransactionCallback<T>): Promise<T> {
return await this.transactionManager.execute(callback);
}
/**
* Get a query builder instance
*/
queryBuilder(): PostgreSQLQueryBuilder {
return new PostgreSQLQueryBuilder(this);
}
/**
* Create a new query builder with SELECT
*/
select(columns: string | string[] = '*'): PostgreSQLQueryBuilder {
return this.queryBuilder().select(columns);
}
/**
* Create a new query builder with INSERT
*/
insert(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().insert(table);
}
/**
* Create a new query builder with UPDATE
*/
update(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().update(table);
}
/**
* Create a new query builder with DELETE
*/
delete(table: string): PostgreSQLQueryBuilder {
return this.queryBuilder().delete(table);
}
/**
* Execute a stored procedure or function
*/
async callFunction<T extends QueryResultRow = QueryResultRow>(
functionName: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : '';
const query = `SELECT * FROM ${functionName}(${placeholders})`;
return await this.query<T>(query, params);
}
/**
* Batch upsert operation for high-performance inserts/updates
*/
async batchUpsert(
tableName: string,
data: Record<string, unknown>[],
conflictColumn: string,
options: {
chunkSize?: number;
excludeColumns?: string[];
} = {}
): Promise<{ insertedCount: number; updatedCount: number }> {
if (!this.pool) {
throw new Error('PostgreSQL client not connected');
}
if (data.length === 0) {
return { insertedCount: 0, updatedCount: 0 };
}
const { chunkSize = 1000, excludeColumns = [] } = options;
const columns = Object.keys(data[0] ?? {}).filter(col => !excludeColumns.includes(col));
const updateColumns = columns.filter(col => col !== conflictColumn);
let totalInserted = 0;
let totalUpdated = 0;
// Process in chunks to avoid memory issues and parameter limits
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
// Build placeholders for this chunk
const placeholders = chunk.map((_, rowIndex) => {
const rowPlaceholders = columns.map((_, colIndex) => {
return `$${rowIndex * columns.length + colIndex + 1}`;
});
return `(${rowPlaceholders.join(', ')})`;
});
// Flatten the chunk data
const values = chunk.flatMap(row => columns.map(col => row[col as keyof typeof row]));
// Build the upsert query
const updateClauses = updateColumns.map(col => `${col} = EXCLUDED.${col}`);
const query = `
INSERT INTO ${tableName} (${columns.join(', ')})
VALUES ${placeholders.join(', ')}
ON CONFLICT (${conflictColumn})
DO UPDATE SET
${updateClauses.join(', ')},
updated_at = NOW()
RETURNING (xmax = 0) AS is_insert
`;
try {
const startTime = Date.now();
const result = await this.pool.query(query, values);
const executionTime = Date.now() - startTime;
// Count inserts vs updates
const inserted = result.rows.filter((row: { is_insert: boolean }) => row.is_insert).length;
const updated = result.rows.length - inserted;
totalInserted += inserted;
totalUpdated += updated;
this.logger.debug(`Batch upsert chunk processed in ${executionTime}ms`, {
chunkSize: chunk.length,
inserted,
updated,
table: tableName,
});
} catch (error) {
this.logger.error(`Batch upsert failed on chunk ${Math.floor(i / chunkSize) + 1}:`, {
error,
table: tableName,
chunkStart: i,
chunkSize: chunk.length,
});
throw error;
}
}
this.logger.info('Batch upsert completed', {
table: tableName,
totalRecords: data.length,
inserted: totalInserted,
updated: totalUpdated,
});
return { insertedCount: totalInserted, updatedCount: totalUpdated };
}
/**
* Check if a table exists
*/
async tableExists(tableName: string, schemaName: string = 'public'): Promise<boolean> {
const result = await this.query(
`SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = $1 AND table_name = $2
)`,
[schemaName, tableName]
);
return at(result.rows, 0).exists;
}
/**
* Get table schema information
*/
async getTableSchema(
tableName: string,
schemaName: string = 'public'
): Promise<QueryResultRow[]> {
const result = await this.query(
`SELECT
column_name,
data_type,
is_nullable,
column_default,
character_maximum_length
FROM information_schema.columns
WHERE table_schema = $1 AND table_name = $2
ORDER BY ordinal_position`,
[schemaName, tableName]
);
return result.rows;
}
/**
* Execute EXPLAIN for query analysis
*/
async explain(query: string, params?: unknown[]): Promise<QueryResultRow[]> {
const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`;
const result = await this.query(explainQuery, params);
return at(result.rows, 0)['QUERY PLAN'];
}
/**
* Get database statistics
*/
async getStats(): Promise<QueryResultRow> {
const result = await this.query(`
SELECT
SELECT
(SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections,
(SELECT count(*) FROM pg_stat_activity WHERE state = 'idle') as idle_connections,
(SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections,
@ -425,34 +177,24 @@ export class PostgreSQLClient {
return result.rows[0] ?? {};
}
/**
* Check if client is connected
*/
get connected(): boolean {
return this.isConnected && !!this.pool;
}
/**
* Get the underlying connection pool
*/
get connectionPool(): Pool | null {
return this.pool;
}
private buildPoolConfig(): PoolConfig {
buildPoolConfig(): PoolConfig {
this.logger.debug('Building PostgreSQL pool config:', {
host: this.config.host,
port: this.config.port,
database: this.config.database,
user: this.config.username,
passwordLength: this.config.password?.length,
passwordType: typeof this.config.password,
passwordValue: this.config.password
? `${this.config.password.substring(0, 3)}***`
: 'NO_PASSWORD',
hasPassword: Boolean(this.config.password),
});
const poolConfig = {
return {
host: this.config.host,
port: this.config.port,
database: this.config.database,
@ -475,166 +217,28 @@ export class PostgreSQLClient {
}
: false,
};
}
return poolConfig;
getPoolMetrics(): PoolMetrics {
this.metrics.lastUsed = new Date();
if (this.pool) {
this.metrics.totalConnections = this.pool.totalCount;
this.metrics.idleConnections = this.pool.idleCount;
this.metrics.waitingRequests = this.pool.waitingCount;
this.metrics.activeConnections = Math.max(
0,
this.metrics.totalConnections - this.metrics.idleConnections
);
}
return { ...this.metrics };
}
private setupErrorHandlers(): void {
if (!this.pool) {
return;
}
this.pool.on('error', error => {
this.logger.error('PostgreSQL pool error:', error);
});
this.pool.on('connect', () => {
this.logger.debug('New PostgreSQL client connected');
});
this.pool.on('remove', () => {
this.logger.debug('PostgreSQL client removed from pool');
});
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Get current pool metrics
*/
getPoolMetrics(): PoolMetrics {
// Update last used timestamp
this.metrics.lastUsed = new Date();
// Update metrics from pool if available
if (this.pool) {
this.metrics.totalConnections = this.pool.totalCount;
this.metrics.idleConnections = this.pool.idleCount;
this.metrics.waitingRequests = this.pool.waitingCount;
this.metrics.activeConnections = this.metrics.totalConnections - this.metrics.idleConnections;
}
return { ...this.metrics };
}
/**
* Set dynamic pool configuration
*/
setDynamicPoolConfig(config: DynamicPoolConfig): void {
this.dynamicPoolConfig = config;
if (config.enabled && this.isConnected && !this.poolMonitorInterval) {
this.startPoolMonitoring();
} else if (!config.enabled && this.poolMonitorInterval) {
clearInterval(this.poolMonitorInterval);
this.poolMonitorInterval = undefined;
}
}
/**
* Start monitoring pool and adjust size dynamically
*/
private startPoolMonitoring(): void {
if (!this.dynamicPoolConfig || this.poolMonitorInterval) {
return;
}
this.poolMonitorInterval = setInterval(() => {
this.evaluatePoolSize();
}, this.dynamicPoolConfig.evaluationInterval);
}
/**
* Setup pool event listeners for metrics
*/
private setupPoolMetrics(): void {
if (!this.pool) {
return;
}
// Track when connections are acquired
this.pool.on('acquire', () => {
this.metrics.activeConnections++;
this.metrics.idleConnections--;
});
// Track when connections are released
this.pool.on('release', () => {
this.metrics.activeConnections--;
this.metrics.idleConnections++;
});
}
/**
* Evaluate and adjust pool size based on usage
*/
private async evaluatePoolSize(): Promise<void> {
if (!this.dynamicPoolConfig || !this.pool) {
return;
}
const metrics = this.getPoolMetrics();
const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig;
const currentSize = metrics.totalConnections;
const utilization = currentSize > 0 ? (metrics.activeConnections / currentSize) * 100 : 0;
this.logger.debug('Pool utilization', {
utilization: `${utilization.toFixed(1)}%`,
active: metrics.activeConnections,
total: currentSize,
waiting: metrics.waitingRequests,
});
// Scale up if utilization is high or there are waiting requests
if ((utilization > scaleUpThreshold || metrics.waitingRequests > 0) && currentSize < maxSize) {
const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize);
this.logger.info('Would scale up connection pool', {
from: currentSize,
to: newSize,
utilization,
});
// Note: pg module doesn't support dynamic resizing, would need reconnection
}
// Scale down if utilization is low
else if (utilization < scaleDownThreshold && currentSize > minSize) {
const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize);
this.logger.info('Would scale down connection pool', {
from: currentSize,
to: newSize,
utilization,
});
// Note: pg module doesn't support dynamic resizing, would need reconnection
}
}
/**
* Enable pool warmup on connect
*/
async warmupPool(): Promise<void> {
if (!this.pool || !this.isConnected) {
throw new Error('Client not connected');
}
const minSize = this.config.poolSettings?.min || 2;
const promises: Promise<void>[] = [];
// Create minimum connections by running parallel queries
for (let i = 0; i < minSize; i++) {
promises.push(
this.pool
.query('SELECT 1')
.then(() => {
this.logger.debug(`Warmed up connection ${i + 1}/${minSize}`);
})
.catch(error => {
this.logger.warn(`Failed to warm up connection ${i + 1}`, { error });
})
);
}
await Promise.allSettled(promises);
this.logger.info('Connection pool warmup complete', { connections: minSize });
}
}

View file

@ -1,145 +0,0 @@
import { getLogger } from '@stock-bot/logger';
import type { PostgreSQLClient } from './client';
import type { PostgreSQLHealthCheck, PostgreSQLHealthStatus, PostgreSQLMetrics } from './types';
/**
* PostgreSQL Health Monitor
*
* Monitors PostgreSQL connection health and provides metrics
*/
export class PostgreSQLHealthMonitor {
private readonly client: PostgreSQLClient;
private readonly logger: ReturnType<typeof getLogger>;
private healthCheckInterval: NodeJS.Timeout | null = null;
private metrics: PostgreSQLMetrics;
private lastHealthCheck: PostgreSQLHealthCheck | null = null;
constructor(client: PostgreSQLClient) {
this.client = client;
this.logger = getLogger('postgres-health-monitor');
this.metrics = {
queriesPerSecond: 0,
averageQueryTime: 0,
errorRate: 0,
connectionPoolUtilization: 0,
slowQueries: 0,
};
}
/**
* Start health monitoring
*/
start(intervalMs: number = 30000): void {
if (this.healthCheckInterval) {
this.stop();
}
this.logger.info(`Starting PostgreSQL health monitoring (interval: ${intervalMs}ms)`);
this.healthCheckInterval = setInterval(async () => {
try {
await this.performHealthCheck();
} catch (error) {
this.logger.error('Health check failed:', error);
}
}, intervalMs);
// Perform initial health check
this.performHealthCheck().catch(error => {
this.logger.error('Initial health check failed:', error);
});
}
/**
* Stop health monitoring
*/
stop(): void {
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
this.healthCheckInterval = null;
this.logger.info('Stopped PostgreSQL health monitoring');
}
}
/**
* Get current health status
*/
async getHealth(): Promise<PostgreSQLHealthCheck> {
if (!this.lastHealthCheck) {
await this.performHealthCheck();
}
if (!this.lastHealthCheck) {
throw new Error('Health check failed to produce results');
}
return this.lastHealthCheck;
}
/**
* Get current metrics
*/
getMetrics(): PostgreSQLMetrics {
return { ...this.metrics };
}
/**
* Perform a health check
*/
private async performHealthCheck(): Promise<void> {
const startTime = Date.now();
const errors: string[] = [];
let status: PostgreSQLHealthStatus = 'healthy';
try {
if (!this.client.connected) {
errors.push('PostgreSQL client not connected');
status = 'unhealthy';
} else {
// Test basic connectivity
await this.client.query('SELECT 1');
// Get connection stats
const stats = await this.client.getStats();
// Check connection pool utilization
const utilization = parseInt(stats.active_connections) / parseInt(stats.max_connections);
if (utilization > 0.8) {
errors.push('High connection pool utilization');
status = status === 'healthy' ? 'degraded' : status;
}
// Check for high latency
const latency = Date.now() - startTime;
if (latency > 1000) {
errors.push(`High latency: ${latency}ms`);
status = status === 'healthy' ? 'degraded' : status;
}
this.metrics.connectionPoolUtilization = utilization;
}
} catch (error) {
errors.push(`Health check failed: ${(error as Error).message}`);
status = 'unhealthy';
}
const latency = Date.now() - startTime;
this.lastHealthCheck = {
status,
timestamp: new Date(),
latency,
connections: {
active: 1,
idle: 9,
total: 10,
},
errors: errors.length > 0 ? errors : undefined,
};
// Log health status changes
if (status !== 'healthy') {
this.logger.warn(`PostgreSQL health status: ${status}`, { errors, latency });
} else {
this.logger.debug(`PostgreSQL health check passed (${latency}ms)`);
}
}
}

View file

@ -1,37 +1,11 @@
/**
* PostgreSQL Client Library for Stock Bot
*
* Provides type-safe PostgreSQL access for operational data,
* transactions, and relational queries.
*/
export { PostgreSQLClient } from './client';
export { PostgreSQLHealthMonitor } from './health';
export { PostgreSQLTransactionManager } from './transactions';
export { PostgreSQLQueryBuilder } from './query-builder';
// export { PostgreSQLMigrationManager } from './migrations'; // TODO: Implement migrations
// Types
export { runPostgresMigrations, type MigrationTrack } from './migrations';
export type {
ConnectionEvents,
PoolMetrics,
PostgreSQLClientConfig,
PostgreSQLConnectionOptions,
PostgreSQLHealthStatus,
PostgreSQLMetrics,
QueryResult,
TransactionCallback,
SchemaNames,
TableNames,
Trade,
Order,
Position,
Portfolio,
Strategy,
RiskLimit,
AuditLog,
PoolMetrics,
ConnectionEvents,
DynamicPoolConfig,
} from './types';
// Note: Factory functions removed - instantiate directly with new PostgreSQLClient()
// or use the Awilix DI container (recommended)

View file

@ -0,0 +1,113 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { getLogger } from '@stock-bot/logger';
import type { PostgreSQLClient } from './client';
const logger = getLogger('postgres-migrations');
export type MigrationTrack = 'master' | 'research' | 'all';
const MASTER_FILES = new Set([
'01-init-database.sql',
'02-master-schema.sql',
'03-initial-data.sql',
'04-provider-exchange-mapping-schema.sql',
'05-add-visible-column.sql',
]);
const RESEARCH_FILES = new Set([
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
'13-strategy-recovery.sql',
'14-backtest-submission.sql',
'15-canonical-paper-intents.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
'29-isolated-candidates.sql',
'30-paper-deployments.sql',
'31-research-agent-project-links.sql',
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
]);
function locateMigrationsDir(): string {
let directory = dirname(fileURLToPath(import.meta.url));
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
const parent = dirname(directory);
if (parent === directory) {
throw new Error('Cannot locate PostgreSQL migrations directory (database/postgres/init)');
}
directory = parent;
}
return join(directory, 'database', 'postgres', 'init');
}
function matchesTrack(file: string, track: MigrationTrack): boolean {
if (!file.endsWith('.sql')) {
return false;
}
const inMaster = MASTER_FILES.has(file);
const inResearch = file.startsWith('001_') || RESEARCH_FILES.has(file);
if (track === 'master') {
return inMaster;
}
if (track === 'research') {
return inResearch;
}
return inMaster || inResearch;
}
export async function runPostgresMigrations(
postgres: Pick<PostgreSQLClient, 'transaction'>,
options: { track?: MigrationTrack; migrationsDir?: string } = {}
): Promise<string[]> {
const track = options.track ?? 'research';
const applied: string[] = [];
await postgres.transaction(async client => {
await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]);
await client.query(`
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL UNIQUE,
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
`);
const migrationsDir = options.migrationsDir ?? locateMigrationsDir();
const files = readdirSync(migrationsDir)
.filter(f => matchesTrack(f, track))
.sort();
for (const file of files) {
const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]);
if (result.rows.length === 0) {
logger.info(`Running migration: ${file}`);
const sql = readFileSync(join(migrationsDir, file), 'utf8');
await client.query(sql);
await client.query(
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
[file]
);
applied.push(file);
}
}
});
return applied;
}

View file

@ -1,270 +0,0 @@
import type { QueryResultRow } from 'pg';
import type { PostgreSQLClient } from './client';
import type { JoinCondition, OrderByCondition, QueryResult, WhereCondition } from './types';
/**
* PostgreSQL Query Builder
*
* Provides a fluent interface for building SQL queries
*/
export class PostgreSQLQueryBuilder {
private queryType: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | null = null;
private selectColumns: string[] = [];
private fromTable: string = '';
private joins: JoinCondition[] = [];
private whereConditions: WhereCondition[] = [];
private groupByColumns: string[] = [];
private havingConditions: WhereCondition[] = [];
private orderByConditions: OrderByCondition[] = [];
private limitCount: number | null = null;
private offsetCount: number | null = null;
private insertValues: Record<string, unknown> = {};
private updateValues: Record<string, unknown> = {};
private readonly client: PostgreSQLClient;
constructor(client: PostgreSQLClient) {
this.client = client;
}
/**
* SELECT statement
*/
select(columns: string | string[] = '*'): this {
this.queryType = 'SELECT';
this.selectColumns = Array.isArray(columns) ? columns : [columns];
return this;
}
/**
* FROM clause
*/
from(table: string): this {
this.fromTable = table;
return this;
}
/**
* JOIN clause
*/
join(table: string, on: string, type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL' = 'INNER'): this {
this.joins.push({ type, table, on });
return this;
}
/**
* WHERE clause
*/
where(column: string, operator: WhereCondition['operator'], value?: unknown): this {
this.whereConditions.push({ column, operator, value });
return this;
}
/**
* GROUP BY clause
*/
groupBy(columns: string | string[]): this {
this.groupByColumns = Array.isArray(columns) ? columns : [columns];
return this;
}
/**
* ORDER BY clause
*/
orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): this {
this.orderByConditions.push({ column, direction });
return this;
}
/**
* LIMIT clause
*/
limit(count: number): this {
this.limitCount = count;
return this;
}
/**
* OFFSET clause
*/
offset(count: number): this {
this.offsetCount = count;
return this;
}
/**
* INSERT statement
*/
insert(table: string): this {
this.queryType = 'INSERT';
this.fromTable = table;
return this;
}
/**
* VALUES for INSERT
*/
values(data: Record<string, unknown>): this {
this.insertValues = data;
return this;
}
/**
* UPDATE statement
*/
update(table: string): this {
this.queryType = 'UPDATE';
this.fromTable = table;
return this;
}
/**
* SET for UPDATE
*/
set(data: Record<string, unknown>): this {
this.updateValues = data;
return this;
}
/**
* DELETE statement
*/
delete(table: string): this {
this.queryType = 'DELETE';
this.fromTable = table;
return this;
}
/**
* Build and execute the query
*/
async execute<T extends QueryResultRow = QueryResultRow>(): Promise<QueryResult<T>> {
const { sql, params } = this.build();
return await this.client.query<T>(sql, params);
}
/**
* Build the SQL query
*/
build(): { sql: string; params: unknown[] } {
const params: unknown[] = [];
let sql = '';
switch (this.queryType) {
case 'SELECT':
sql = this.buildSelectQuery(params);
break;
case 'INSERT':
sql = this.buildInsertQuery(params);
break;
case 'UPDATE':
sql = this.buildUpdateQuery(params);
break;
case 'DELETE':
sql = this.buildDeleteQuery(params);
break;
default:
throw new Error('Query type not specified');
}
return { sql, params };
}
private buildSelectQuery(params: unknown[]): string {
let sql = `SELECT ${this.selectColumns.join(', ')}`;
if (this.fromTable) {
sql += ` FROM ${this.fromTable}`;
}
// Add JOINs
for (const join of this.joins) {
sql += ` ${join.type} JOIN ${join.table} ON ${join.on}`;
}
// Add WHERE
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
// Add GROUP BY
if (this.groupByColumns.length > 0) {
sql += ` GROUP BY ${this.groupByColumns.join(', ')}`;
}
// Add HAVING
if (this.havingConditions.length > 0) {
sql += ' HAVING ' + this.buildWhereClause(this.havingConditions, params);
}
// Add ORDER BY
if (this.orderByConditions.length > 0) {
const orderBy = this.orderByConditions
.map(order => `${order.column} ${order.direction}`)
.join(', ');
sql += ` ORDER BY ${orderBy}`;
}
// Add LIMIT
if (this.limitCount !== null) {
sql += ` LIMIT $${params.length + 1}`;
params.push(this.limitCount);
}
// Add OFFSET
if (this.offsetCount !== null) {
sql += ` OFFSET $${params.length + 1}`;
params.push(this.offsetCount);
}
return sql;
}
private buildInsertQuery(params: unknown[]): string {
const columns = Object.keys(this.insertValues);
const placeholders = columns.map((_, i) => `$${params.length + i + 1}`);
params.push(...Object.values(this.insertValues));
return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`;
}
private buildUpdateQuery(params: unknown[]): string {
const sets = Object.keys(this.updateValues).map((key, i) => {
return `${key} = $${params.length + i + 1}`;
});
params.push(...Object.values(this.updateValues));
let sql = `UPDATE ${this.fromTable} SET ${sets.join(', ')}`;
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
return sql;
}
private buildDeleteQuery(params: unknown[]): string {
let sql = `DELETE FROM ${this.fromTable}`;
if (this.whereConditions.length > 0) {
sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params);
}
return sql;
}
private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string {
return conditions
.map(condition => {
if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') {
return `${condition.column} ${condition.operator}`;
} else {
params.push(condition.value);
return `${condition.column} ${condition.operator} $${params.length}`;
}
})
.join(' AND ');
}
}

Some files were not shown because too many files have changed in this diff Show more