commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

View file

@ -1,81 +0,0 @@
# Dependencies
node_modules/
**/node_modules/
# Build outputs
dist/
build/
**/dist/
**/build/
.next/
**/.next/
# Cache directories
.turbo/
**/.turbo/
.cache/
**/.cache/
# Environment files
.env
.env.local
.env.production
.env.staging
**/.env*
# Lock files
package-lock.json
yarn.lock
bun.lockb
pnpm-lock.yaml
# Logs
*.log
logs/
**/logs/
# Database files
*.db
*.sqlite
*.sqlite3
# Temporary files
*.tmp
*.temp
.DS_Store
Thumbs.db
# Generated files
*.d.ts
**/*.d.ts
# JavaScript files (we're focusing on TypeScript)
*.js
*.mjs
!.eslintrc.js
!eslint.config.js
# Scripts and config directories
scripts/
monitoring/
database/
docker-compose*.yml
Dockerfile*
# Documentation
*.md
docs/
# Test coverage
coverage/
**/coverage/
# IDE/Editor files
.vscode/
.idea/
*.swp
*.swo
# Angular specific
**/.angular/
**/src/polyfills.ts

View file

@ -10,7 +10,9 @@
"bracketSpacing": true, "bracketSpacing": true,
"bracketSameLine": false, "bracketSameLine": false,
"quoteProps": "as-needed", "quoteProps": "as-needed",
"plugins": ["@ianvs/prettier-plugin-sort-imports"], "plugins": [
"@ianvs/prettier-plugin-sort-imports"
],
"importOrder": [ "importOrder": [
"^(node:.*|fs|path|crypto|url|os|util|events|stream|buffer|child_process|cluster|http|https|net|tls|dgram|dns|readline|repl|vm|zlib|querystring|punycode|assert|timers|constants)$", "^(node:.*|fs|path|crypto|url|os|util|events|stream|buffer|child_process|cluster|http|https|net|tls|dgram|dns|readline|repl|vm|zlib|querystring|punycode|assert|timers|constants)$",
"<THIRD_PARTY_MODULES>", "<THIRD_PARTY_MODULES>",
@ -22,5 +24,20 @@
"^\\.(?!/?$)", "^\\.(?!/?$)",
"^\\./?$" "^\\./?$"
], ],
"importOrderParserPlugins": ["typescript", "decorators-legacy"] "importOrderParserPlugins": [
"typescript",
"decorators-legacy"
],
"overrides": [
{
"files": "**/*.tsx",
"options": {
"importOrderParserPlugins": [
"typescript",
"jsx",
"decorators-legacy"
]
}
}
]
} }

View file

@ -7,7 +7,7 @@ the root workspace checks.
## Build and verify ## Build and verify
Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust
1.88. Building and the tooling/contract checks do not require running databases or provider 1.88. Building and the tooling/contract/integration checks do not require running databases or provider
credentials. credentials.
```sh ```sh
@ -26,17 +26,19 @@ native engine. `bun run build --dry=json` shows the actual Turbo task plan.
| `bun run typecheck` | Check library, stock application, and tool source directly | | `bun run typecheck` | Check library, stock application, and tool source directly |
| `bun run test:contracts` | Compile positive and negative service-contract assertions | | `bun run test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | | `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | | `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contract tests, tooling tests, and lint; report every failed gate | | `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate |
`check` exits nonzero if any gate fails. Existing application type/lint errors are reported; `check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined.
they are not suppressed or baselined. The larger existing `bun run test` suite is separate: The larger existing `bun run test` suite is separate:
some tests need databases, Redis, browsers, or native-engine fixes. some tests need databases, Redis, browsers, or native-engine fixes.
Native builds generate `apps/stock/engine/dist/engine.node` and `dist/index.d.ts`. The public Native builds generate `apps/stock/engine/dist/engine.node` and `dist/index.d.ts`. The public
ESM/CommonJS loaders and declaration facade use those generated artifacts. Rebuild after ESM/CommonJS loaders and declaration facade use those generated artifacts. Rebuild after
changing Rust APIs. TensorFlow is an optional orchestrator peer dependency used by the ML changing Rust APIs. TensorFlow is loaded only when starting the optional ML strategy.
strategy; install it when using that strategy. Its TypeScript dependency is present for checking; using ML also requires installing its
platform-specific native binding. Dependency install scripts were not enabled for verification.
## Service contracts ## Service contracts
@ -53,3 +55,28 @@ The DI and handler packages re-export `IServiceContainer` for existing consumers
managers and individual queues are separate capabilities: obtain queues through managers and individual queues are separate capabilities: obtain queues through
`container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`. `container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`.
Use `getFullQueueName(service, handler)` when addressing another service's queue. Use `getFullQueueName(service, handler)` when addressing another service's queue.
Use `requireServices(container, 'mongodb', 'queueManager')` at consumer boundaries when
those capabilities are required. Missing/disabled adapters fail explicitly before work begins.
`@stock-bot/invariants` provides small, dependency-free checks for required values and
indexed array reads; browser code can use it without importing server utilities.
Handler initializers receive their scanner/registry explicitly through the DI application
initialization context. WebSocket connections and completion timers belong to the socket
handler and are released on close/shutdown.
## Backtest data integrity
Historical storage no longer invents prices when a database is unavailable. Configure a
historical store, or explicitly set `services.orchestrator.backtesting.allowSyntheticData`
for offline demos, with `syntheticSeed` for repeatability. Synthetic data is disabled by
default and must not be used to assess trading performance. MongoDB's normalized EOD
store currently supports daily bars only; intraday requests require QuestDB.
The integration test uses an in-memory persistence transport and the real storage/native
engine path. It checks idempotent ingestion, invalid-price rejection, repeatable trades,
and explicit failures for missing data or unsupported strategies. No live provider or broker
is contacted. Native SMA and MACD regressions are covered by the repository checks.
Coverage reports contain measured LCOV data only. Missing coverage or an empty package
selection fails the coverage command instead of producing an estimated score.

View file

@ -91,6 +91,9 @@ export const stockAppSchema = baseAppSchema.extend({
backtesting: z backtesting: z
.object({ .object({
maxConcurrent: z.number().default(5), maxConcurrent: z.number().default(5),
useRustEngine: z.boolean().default(true),
allowSyntheticData: z.boolean().default(false),
syntheticSeed: z.number().int().default(42),
defaultSpeed: z.string().default('max'), defaultSpeed: z.string().default('max'),
dataResolutions: z.array(z.string()).default(['1m', '5m', '15m', '1h', '1d']), dataResolutions: z.array(z.string()).default(['1m', '5m', '15m', '1h', '1d']),
}) })

View file

@ -29,7 +29,8 @@
"@stock-bot/proxy": "*", "@stock-bot/proxy": "*",
"hono": "^4.0.0", "hono": "^4.0.0",
"pako": "^2.1.0", "pako": "^2.1.0",
"cheerio": "^1.0.0" "cheerio": "^1.0.0",
"@stock-bot/invariants": "workspace:*"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5.0.0" "typescript": "^5.0.0"

View file

@ -35,33 +35,40 @@ export async function getChannels(this: CeoHandler, payload: number | undefined)
const channels = results.channel_categories[0].channels; const channels = results.channel_categories[0].channels;
const totalChannels = results.channel_categories[0].total_channels; const totalChannels = results.channel_categories[0].total_channels;
const totalPages = Math.ceil(totalChannels / channels.length); const totalPages = Math.ceil(totalChannels / channels.length);
const exchanges: { exchange: string; countryCode: string }[] = []; const exchanges: { exchange: string; countryCode: string; source: string }[] = [];
const symbols = channels.map((channel: any) => { const symbols = channels.map(
// check if exchange is in the exchanges array object (channel: {
if (!exchanges.find((e: any) => e.exchange === channel.exchange)) { exchange: string;
exchanges.push({ symbol: string;
title: string;
type: string;
channel: string;
company_details?: Record<string, unknown>;
}) => {
// check if exchange is in the exchanges array object
if (!exchanges.find(e => e.exchange === channel.exchange)) {
exchanges.push({ source: 'ceo', exchange: channel.exchange, countryCode: 'CA' });
}
const details = channel.company_details || {};
return {
source: 'ceo',
symbol: channel.symbol,
exchange: channel.exchange, exchange: channel.exchange,
countryCode: 'CA', name: channel.title,
}); type: channel.type,
ceoId: channel.channel,
marketCap: details.market_cap,
volumeRatio: details.volume_ratio,
avgVolume: details.avg_volume,
stockType: details.stock_type,
issueType: details.issue_type,
sharesOutstanding: details.shares_outstanding,
float: details.float,
lastSeen: new Date(),
active: true,
};
} }
const details = channel.company_details || {}; );
return {
symbol: channel.symbol,
exchange: channel.exchange,
name: channel.title,
type: channel.type,
ceoId: channel.channel,
marketCap: details.market_cap,
volumeRatio: details.volume_ratio,
avgVolume: details.avg_volume,
stockType: details.stock_type,
issueType: details.issue_type,
sharesOutstanding: details.shares_outstanding,
float: details.float,
lastSeen: new Date(),
active: true,
};
});
await this.mongodb.batchUpsert('ceoSymbols', symbols, ['symbol', 'exchange']); await this.mongodb.batchUpsert('ceoSymbols', symbols, ['symbol', 'exchange']);
await this.mongodb.batchUpsert('ceoExchanges', exchanges, ['exchange']); await this.mongodb.batchUpsert('ceoExchanges', exchanges, ['exchange']);
@ -75,8 +82,11 @@ export async function getChannels(this: CeoHandler, payload: number | undefined)
this.logger.info(`Fetched CEO channels for page ${page}/${totalPages}`); this.logger.info(`Fetched CEO channels for page ${page}/${totalPages}`);
return { page, totalPages }; return { page, totalPages };
} catch (error: any) { } catch (error) {
this.logger.error(`Error fetching CEO channels for page ${page} with proxy ${proxy}:`, error); this.logger.error(`Error fetching CEO channels for page ${page} with proxy ${proxy}:`, error);
throw new Error(`Failed to fetch CEO channels: ${error.message}`); throw new Error(
`Failed to fetch CEO channels: ${error instanceof Error ? error.message : String(error)}`,
{ cause: error }
);
} }
} }

View file

@ -1,7 +1,11 @@
import { getRandomUserAgent } from '@stock-bot/utils'; import { getRandomUserAgent } from '@stock-bot/utils';
import type { CeoHandler } from '../ceo.handler'; import type { CeoHandler } from '../ceo.handler';
export async function getPosts(this: CeoHandler, payload: any, _context: any): Promise<unknown> { export async function getPosts(
this: CeoHandler,
payload: { ceoId: string; symbol: string; timestamp?: number; finished?: boolean },
_context: unknown
): Promise<unknown> {
const { ceoId, symbol, timestamp, finished } = payload; const { ceoId, symbol, timestamp, finished } = payload;
const proxy = this.proxy?.getProxy(); const proxy = this.proxy?.getProxy();
if (!proxy) { if (!proxy) {
@ -31,7 +35,9 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
throw new Error(`Failed to fetch details for ceoId ${ceoId}: ${response.statusText}`); throw new Error(`Failed to fetch details for ceoId ${ceoId}: ${response.statusText}`);
} }
const data = await response.json(); const data = (await response.json()) as {
spiels: Array<Record<string, unknown> & { timestamp: number }>;
};
const spielCount = data.spiels.length; const spielCount = data.spiels.length;
if (spielCount === 0) { if (spielCount === 0) {
@ -56,7 +62,8 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
// Extract timestamps clearly // Extract timestamps clearly
const oldestPostInBatch = data.spiels[0]?.timestamp; const oldestPostInBatch = data.spiels[0]?.timestamp;
const newestPostInBatch = data.spiels[data.spiels.length - 1]?.timestamp; const newestPostInBatch = data.spiels[data.spiels.length - 1]?.timestamp;
const posts = data.spiels.map((spiel: any) => ({ const posts = data.spiels.map(spiel => ({
source: 'ceo',
ceoId, ceoId,
spiel: spiel.spiel, spiel: spiel.spiel,
spielReplyToId: spiel.spiel_reply_to_id, spielReplyToId: spiel.spiel_reply_to_id,
@ -125,7 +132,7 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
symbolData?.newestPostTimestamp || symbolData?.lastSpielTime || 0; symbolData?.newestPostTimestamp || symbolData?.lastSpielTime || 0;
// Filter to only posts newer than what we've seen // Filter to only posts newer than what we've seen
const newPosts = posts.filter((p: any) => p.timestamp > lastKnownNewestTimestamp); const newPosts = posts.filter(p => p.timestamp > lastKnownNewestTimestamp);
if (newPosts.length === 0) { if (newPosts.length === 0) {
this.logger.info(`No new posts for ${ceoId}, all ${posts.length} posts already collected`); this.logger.info(`No new posts for ${ceoId}, all ${posts.length} posts already collected`);
@ -146,7 +153,11 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
// If all posts in batch were new, there might be more in the gap // If all posts in batch were new, there might be more in the gap
// Continue paginating until we hit posts we've already seen // Continue paginating until we hit posts we've already seen
if (newPosts.length === posts.length && oldestPostInBatch > lastKnownNewestTimestamp) { if (
newPosts.length === posts.length &&
oldestPostInBatch !== undefined &&
oldestPostInBatch > lastKnownNewestTimestamp
) {
this.logger.info(`All posts were new, checking for more in the gap`); this.logger.info(`All posts were new, checking for more in the gap`);
await this.scheduleOperation( await this.scheduleOperation(
'get-posts', 'get-posts',
@ -171,12 +182,12 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
this.logger.info(`Successfully processed channel ${ceoId}`); this.logger.info(`Successfully processed channel ${ceoId}`);
return { ceoId, spielCount, timestamp }; return { ceoId, spielCount, timestamp };
} catch (error: any) { } catch (error) {
this.logger.error(`Failed to process individual symbol ${symbol}`, { this.logger.error(`Failed to process individual symbol ${symbol}`, {
error, error,
ceoId, ceoId,
timestamp, timestamp,
}); });
throw new Error(`Failed to process individual symbol ${symbol}`, error.message); throw new Error(`Failed to process individual symbol ${symbol}`, { cause: error });
} }
} }

View file

@ -1,7 +1,11 @@
import { getRandomUserAgent } from '@stock-bot/utils'; import { getRandomUserAgent } from '@stock-bot/utils';
import type { CeoHandler } from '../ceo.handler'; import type { CeoHandler } from '../ceo.handler';
export async function getShorts(this: CeoHandler, payload: any, _context: any): Promise<unknown> { export async function getShorts(
this: CeoHandler,
payload: { ceoId: string; symbol: string; timestamp?: number },
_context: unknown
): Promise<unknown> {
const { ceoId, symbol, timestamp } = payload; const { ceoId, symbol, timestamp } = payload;
const proxy = this.proxy?.getProxy(); const proxy = this.proxy?.getProxy();
if (!proxy) { if (!proxy) {

View file

@ -2,7 +2,7 @@ import type { CeoHandler } from '../ceo.handler';
export async function updateUniqueSymbols( export async function updateUniqueSymbols(
this: CeoHandler, this: CeoHandler,
payload: any, payload: { action?: string } | undefined,
_context: unknown _context: unknown
): Promise<unknown> { ): Promise<unknown> {
const action = payload?.action || 'get-posts'; // Default to get-posts if no action specified const action = payload?.action || 'get-posts'; // Default to get-posts if no action specified

View file

@ -1,18 +1,14 @@
import { import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
BaseHandler, import type { IServiceContainer } from '@stock-bot/services';
Disabled, import { resolveIngestionServices } from '../../types';
Handler,
Operation,
ScheduledOperation,
} from '@stock-bot/handlers';
import { getChannels, getPosts, getShorts, updateUniqueSymbols } from './actions';
import type { DataIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types';
import { getChannels, getPosts, getShorts, updateUniqueSymbols } from './actions';
@Handler('ceo') @Handler('ceo')
@Disabled() @Disabled()
export class CeoHandler extends BaseHandler<DataIngestionServices> { export class CeoHandler extends BaseHandler<DataIngestionServices> {
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); // Handler name read from @Handler decorator super(resolveIngestionServices(services, 'ceo')); // Handler name read from @Handler decorator
} }
@ScheduledOperation('get-channels', '0 */15 * * *', { @ScheduledOperation('get-channels', '0 */15 * * *', {

View file

@ -1,233 +1,249 @@
import type { EodHandler } from '../eod.handler'; import { at } from '@stock-bot/utils';
import { EOD_CONFIG } from '../shared'; import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';
interface FetchCorporateActionsInput {
eodSearchCode: string; interface FetchCorporateActionsInput {
actionType: 'dividends' | 'splits'; eodSearchCode: string;
} actionType: 'dividends' | 'splits';
}
export async function scheduleFetchCorporateActions(
this: EodHandler export async function scheduleFetchCorporateActions(
): Promise<{ success: boolean; jobsScheduled: number }> { this: EodHandler
const logger = this.logger; ): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling corporate actions fetch jobs'); try {
logger.info('Scheduling corporate actions fetch jobs');
// Get Canadian exchanges for now
const canadianExchanges = ['TO', 'V', 'CN', 'NEO']; // Get Canadian exchanges for now
const canadianExchanges = ['TO', 'V', 'CN', 'NEO'];
// Use OperationTracker to find stale symbols for both dividends and splits
const allStaleDividends = await this.operationRegistry.getStaleSymbols('eod', 'dividends_update', { // Use OperationTracker to find stale symbols for both dividends and splits
limit: 50000 // Get all symbols needing update const allStaleDividends = await this.operationRegistry.getStaleSymbols(
}); 'eod',
'dividends_update',
const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', { {
limit: 50000 // Get all symbols needing update limit: 50000, // Get all symbols needing update
}); }
);
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbolsDividends = allStaleDividends.filter(item => const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', {
canadianExchanges.includes(item.symbol.Exchange) && limit: 50000, // Get all symbols needing update
item.symbol.delisted === false });
); // Remove the slice limit to process all symbols
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbolsSplits = allStaleSplits.filter(item => const staleSymbolsDividends = allStaleDividends.filter(
canadianExchanges.includes(item.symbol.Exchange) && item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
item.symbol.delisted === false ); // Remove the slice limit to process all symbols
); // Remove the slice limit to process all symbols
const staleSymbolsSplits = allStaleSplits.filter(
if ((!staleSymbolsDividends || staleSymbolsDividends.length === 0) && item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
(!staleSymbolsSplits || staleSymbolsSplits.length === 0)) { ); // Remove the slice limit to process all symbols
logger.info('No symbols need corporate actions update');
return { success: true, jobsScheduled: 0 }; if (
} (!staleSymbolsDividends || staleSymbolsDividends.length === 0) &&
(!staleSymbolsSplits || staleSymbolsSplits.length === 0)
logger.info(`Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update`); ) {
logger.info('No symbols need corporate actions update');
let jobsScheduled = 0; return { success: true, jobsScheduled: 0 };
}
// Schedule dividends jobs
for (let i = 0; i < staleSymbolsDividends.length; i++) { logger.info(
const { symbol } = staleSymbolsDividends[i]; `Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update`
);
await this.scheduleOperation('fetch-corporate-actions', {
eodSearchCode: symbol.eodSearchCode, let jobsScheduled = 0;
actionType: 'dividends'
}, { // Schedule dividends jobs
attempts: 3, for (let i = 0; i < staleSymbolsDividends.length; i++) {
backoff: { const { symbol } = at(staleSymbolsDividends, i);
type: 'exponential',
delay: 5000 await this.scheduleOperation(
}, 'fetch-corporate-actions',
delay: i * 200 // Stagger jobs by 200ms per symbol {
}); eodSearchCode: symbol.eodSearchCode,
jobsScheduled++; actionType: 'dividends',
} },
{
// Schedule splits jobs attempts: 3,
for (let i = 0; i < staleSymbolsSplits.length; i++) { backoff: {
const { symbol } = staleSymbolsSplits[i]; type: 'exponential',
delay: 5000,
await this.scheduleOperation('fetch-corporate-actions', { },
eodSearchCode: symbol.eodSearchCode, delay: i * 200, // Stagger jobs by 200ms per symbol
actionType: 'splits' }
}, { );
attempts: 3, jobsScheduled++;
backoff: { }
type: 'exponential',
delay: 5000 // Schedule splits jobs
}, for (let i = 0; i < staleSymbolsSplits.length; i++) {
delay: (i * 200) + 100 // Offset splits by 100ms from dividends const { symbol } = at(staleSymbolsSplits, i);
});
jobsScheduled++; await this.scheduleOperation(
} 'fetch-corporate-actions',
{
logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`); eodSearchCode: symbol.eodSearchCode,
actionType: 'splits',
return { },
success: true, {
jobsScheduled attempts: 3,
}; backoff: {
} catch (error) { type: 'exponential',
logger.error('Failed to schedule corporate actions fetch jobs', { error }); delay: 5000,
throw error; },
} delay: i * 200 + 100, // Offset splits by 100ms from dividends
} }
);
export async function fetchCorporateActions( jobsScheduled++;
this: EodHandler, }
input: FetchCorporateActionsInput
): Promise<{ success: boolean; recordsCount: number }> { logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`);
const logger = this.logger;
const { eodSearchCode, actionType } = input; return {
success: true,
// Declare variables for catch block jobsScheduled,
let symbol: string = ''; };
let exchange: string = ''; } catch (error) {
logger.error('Failed to schedule corporate actions fetch jobs', { error });
try { throw error;
// Lookup symbol using eodSearchCode }
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ }
eodSearchCode: eodSearchCode
}); export async function fetchCorporateActions(
this: EodHandler,
if (!symbolDoc) { input: FetchCorporateActionsInput
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); ): Promise<{ success: boolean; recordsCount: number }> {
throw new Error(`Symbol not found: ${eodSearchCode}`); const logger = this.logger;
} const { eodSearchCode, actionType } = input;
symbol = symbolDoc.Code; // Declare variables for catch block
exchange = symbolDoc.eodExchange || symbolDoc.Exchange; let symbol: string = '';
const country = symbolDoc.Country; let exchange: string = '';
logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`); try {
// Lookup symbol using eodSearchCode
// Get API key const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
const apiKey = EOD_CONFIG.API_TOKEN; eodSearchCode: eodSearchCode,
if (!apiKey) { });
throw new Error('EOD API key not configured');
} if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
// Build URL based on action type throw new Error(`Symbol not found: ${eodSearchCode}`);
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) }
const endpoint = actionType === 'dividends' ? 'div' : 'splits';
const url = new URL(`https://eodhd.com/api/${endpoint}/${eodSearchCode}`); symbol = symbolDoc.Code;
url.searchParams.append('api_token', apiKey); exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
url.searchParams.append('fmt', 'json'); const _country = symbolDoc.Country;
// Fetch data logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`);
const response = await fetch(url.toString());
// Get API key
if (!response.ok) { const apiKey = EOD_CONFIG.API_TOKEN;
throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`); if (!apiKey) {
} throw new Error('EOD API key not configured');
}
const data = await response.json();
// Build URL based on action type
// EOD returns an array of corporate actions // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
if (!Array.isArray(data)) { const endpoint = actionType === 'dividends' ? 'div' : 'splits';
throw new Error('Invalid response format from EOD API - expected array'); const url = new URL(`https://eodhd.com/api/${endpoint}/${eodSearchCode}`);
} url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`);
// Fetch data
// Log sample records if any const response = await fetch(url.toString());
if (data.length > 0) {
logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, { if (!response.ok) {
count: data.length, throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`);
samples: data.slice(0, 3).map(record => ({ }
date: record.date,
value: record.value || record.split || record.amount, const data = await response.json();
...record
})) // EOD returns an array of corporate actions
}); if (!Array.isArray(data)) {
} throw new Error('Invalid response format from EOD API - expected array');
}
if (data.length === 0) {
// Update symbol to indicate we checked but found no data logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`);
await this.mongodb.collection('eodSymbols').updateOne(
{ eodSearchCode: eodSearchCode }, // Log sample records if any
{ if (data.length > 0) {
$set: { logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, {
[`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(), count: data.length,
[`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false samples: data.slice(0, 3).map(record => ({
} date: record.date,
} value: record.value || record.split || record.amount,
); ...record,
})),
return { success: true, recordsCount: 0 }; });
} }
// Add metadata to each record if (data.length === 0) {
const recordsWithMetadata = data.map(record => ({ // Update symbol to indicate we checked but found no data
symbol, await this.mongodb.collection('eodSymbols').updateOne(
exchange, { eodSearchCode: eodSearchCode },
eodSearchCode, {
...record, $set: {
actionType, [`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(),
updatedAt: new Date(), [`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false,
source: 'eod' },
})); }
);
// Determine collection name based on action type
const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits'; return { success: true, recordsCount: 0 };
}
// Save to MongoDB - use date and eodSearchCode as unique identifier
const result = await this.mongodb.batchUpsert( // Add metadata to each record
collectionName, const recordsWithMetadata = data.map(record => ({
recordsWithMetadata, symbol,
['date', 'eodSearchCode'] exchange,
); eodSearchCode,
...record,
// Update operation tracker based on action type actionType,
const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; updatedAt: new Date(),
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { source: 'eod',
status: 'success', }));
recordCount: result.insertedCount,
metadata: { // Determine collection name based on action type
actionType: actionType, const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits';
exchange: exchange,
hasData: result.insertedCount > 0 // Save to MongoDB - use date and eodSearchCode as unique identifier
} const result = await this.mongodb.batchUpsert(collectionName, recordsWithMetadata, [
}); 'date',
'eodSearchCode',
logger.info(`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`); ]);
return { // Update operation tracker based on action type
success: true, const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update';
recordsCount: result.insertedCount await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, {
}; status: 'success',
} catch (error) { recordCount: result.insertedCount,
logger.error('Failed to fetch corporate actions', { error, symbol, exchange, actionType }); metadata: {
actionType: actionType,
// Update operation tracker with failure exchange: exchange,
const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; hasData: result.insertedCount > 0,
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { },
status: 'failure', });
error: error instanceof Error ? error.message : String(error)
}); logger.info(
`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`
throw error; );
}
} return {
success: true,
recordsCount: result.insertedCount,
};
} catch (error) {
logger.error('Failed to fetch corporate actions', { error, symbol, exchange, actionType });
// Update operation tracker with failure
const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update';
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, {
status: 'failure',
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}

View file

@ -1,376 +1,403 @@
import type { EodHandler } from '../eod.handler'; import { at } from '@stock-bot/utils';
import { EOD_CONFIG } from '../shared'; import type { EodHandler } from '../eod.handler';
interface BulkFundamentalsInput { import { EOD_CONFIG } from '../shared';
eodSearchCodes: string[];
} interface BulkFundamentalsInput {
eodSearchCodes: string[];
interface FetchSingleFundamentalsInput { }
eodSearchCode: string;
} interface FetchSingleFundamentalsInput {
eodSearchCode: string;
export async function scheduleFetchFundamentals( }
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> { export async function scheduleFetchFundamentals(
const logger = this.logger; this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
try { const logger = this.logger;
logger.info('Scheduling fundamentals fetch jobs');
try {
// Get Canadian exchanges for now logger.info('Scheduling fundamentals fetch jobs');
const canadianExchanges = ['TO', 'V', 'CN', 'NEO'];
// Get Canadian exchanges for now
// Use OperationTracker to find stale symbols const canadianExchanges = ['TO', 'V', 'CN', 'NEO'];
const allStaleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'fundamentals_update', {
limit: 50000 // Get all symbols needing update // Use OperationTracker to find stale symbols
}); const allStaleSymbols = await this.operationRegistry.getStaleSymbols(
'eod',
// Filter for Canadian exchanges and non-delisted symbols 'fundamentals_update',
const staleSymbols = allStaleSymbols.filter(item => {
canadianExchanges.includes(item.symbol.Exchange) && limit: 50000, // Get all symbols needing update
item.symbol.delisted === false }
); // Remove the slice limit to process all symbols );
if (!staleSymbols || staleSymbols.length === 0) { // Filter for Canadian exchanges and non-delisted symbols
logger.info('No symbols need fundamentals update'); const staleSymbols = allStaleSymbols.filter(
return { success: true, jobsScheduled: 0 }; item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
} ); // Remove the slice limit to process all symbols
logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`); if (!staleSymbols || staleSymbols.length === 0) {
logger.info('No symbols need fundamentals update');
// Separate ETFs from regular stocks return { success: true, jobsScheduled: 0 };
const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF'); }
const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF');
logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`);
logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, {
etfSamples: etfs.slice(0, 5).map(e => ({ // Separate ETFs from regular stocks
symbol: e.symbol.Code, const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF');
exchange: e.symbol.Exchange, const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF');
name: e.symbol.Name
})), logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, {
nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({ etfSamples: etfs.slice(0, 5).map(e => ({
symbol: s.symbol.Code, symbol: e.symbol.Code,
exchange: s.symbol.Exchange, exchange: e.symbol.Exchange,
name: s.symbol.Name, name: e.symbol.Name,
type: s.symbol.Type })),
})) nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({
}); symbol: s.symbol.Code,
exchange: s.symbol.Exchange,
let jobsScheduled = 0; name: s.symbol.Name,
type: s.symbol.Type,
// Schedule individual jobs for ETFs })),
for (let i = 0; i < etfs.length; i++) { });
const { symbol: etf } = etfs[i];
await this.scheduleOperation('fetch-single-fundamentals', { let jobsScheduled = 0;
eodSearchCode: etf.eodSearchCode
}, { // Schedule individual jobs for ETFs
attempts: 3, for (let i = 0; i < etfs.length; i++) {
backoff: { const { symbol: etf } = at(etfs, i);
type: 'exponential', await this.scheduleOperation(
delay: 10000 'fetch-single-fundamentals',
}, {
delay: jobsScheduled * 1000 // Stagger by 1 second eodSearchCode: etf.eodSearchCode,
}); },
jobsScheduled++; {
} attempts: 3,
backoff: {
if (etfs.length > 0) { type: 'exponential',
logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`); delay: 10000,
} },
delay: jobsScheduled * 1000, // Stagger by 1 second
// Create batches of 500 symbols for non-ETFs }
const batchSize = 500; // EOD allows up to 500 symbols per bulk request );
jobsScheduled++;
for (let i = 0; i < nonEtfs.length; i += batchSize) { }
const batch = nonEtfs.slice(i, i + batchSize);
if (etfs.length > 0) {
// Convert to array of eodSearchCodes logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`);
const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode); }
await this.scheduleOperation('fetch-bulk-fundamentals', { // Create batches of 500 symbols for non-ETFs
eodSearchCodes: eodSearchCodes const batchSize = 500; // EOD allows up to 500 symbols per bulk request
}, {
attempts: 3, for (let i = 0; i < nonEtfs.length; i += batchSize) {
backoff: { const batch = nonEtfs.slice(i, i + batchSize);
type: 'exponential',
delay: 10000 // Convert to array of eodSearchCodes
}, const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode);
delay: jobsScheduled * 5000 // Stagger batches by 5 seconds
}); await this.scheduleOperation(
'fetch-bulk-fundamentals',
jobsScheduled++; {
logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`); eodSearchCodes: eodSearchCodes,
} },
{
logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`); attempts: 3,
backoff: {
return { type: 'exponential',
success: true, delay: 10000,
jobsScheduled },
}; delay: jobsScheduled * 5000, // Stagger batches by 5 seconds
} catch (error) { }
logger.error('Failed to schedule fundamentals fetch jobs', { error }); );
throw error;
} jobsScheduled++;
} logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`);
}
export async function fetchBulkFundamentals(
this: EodHandler, logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`);
input: BulkFundamentalsInput
): Promise<{ success: boolean; symbolsProcessed: number }> { return {
const logger = this.logger; success: true,
const { eodSearchCodes } = input; jobsScheduled,
};
try { } catch (error) {
logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length }); logger.error('Failed to schedule fundamentals fetch jobs', { error });
throw error;
// Lookup all symbols }
const symbolDocs = await this.mongodb.collection('eodSymbols').find({ }
eodSearchCode: { $in: eodSearchCodes }
}).toArray(); export async function fetchBulkFundamentals(
this: EodHandler,
if (symbolDocs.length === 0) { input: BulkFundamentalsInput
logger.error('No symbols found for provided eodSearchCodes'); ): Promise<{ success: boolean; symbolsProcessed: number }> {
return { success: true, symbolsProcessed: 0 }; const logger = this.logger;
} const { eodSearchCodes } = input;
// Get API key try {
const apiKey = EOD_CONFIG.API_TOKEN; logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length });
if (!apiKey) {
throw new Error('EOD API key not configured'); // Lookup all symbols
} const symbolDocs = await this.mongodb
.collection('eodSymbols')
// Group symbols by actual exchange for API endpoint .find({
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) eodSearchCode: { $in: eodSearchCodes },
const exchangeGroups = symbolDocs.reduce((acc, symbolDoc) => { })
const exchange = symbolDoc.eodExchange || symbolDoc.Exchange; .toArray();
const eodSearchCode = symbolDoc.eodSearchCode;
if (symbolDocs.length === 0) {
if (!acc[exchange]) { logger.error('No symbols found for provided eodSearchCodes');
acc[exchange] = []; return { success: true, symbolsProcessed: 0 };
} }
// eodSearchCode already has the correct format (e.g., AAPL.US)
acc[exchange].push(eodSearchCode); // Get API key
return acc; const apiKey = EOD_CONFIG.API_TOKEN;
}, {} as Record<string, string[]>); if (!apiKey) {
throw new Error('EOD API key not configured');
let totalProcessed = 0; }
// Process each exchange group // Group symbols by actual exchange for API endpoint
for (const [exchange, symbolList] of Object.entries(exchangeGroups)) { // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
// Build URL - using the exchange as the endpoint const exchangeGroups = symbolDocs.reduce(
const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`); (acc, symbolDoc) => {
url.searchParams.append('api_token', apiKey); const exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
url.searchParams.append('fmt', 'json'); const eodSearchCode = symbolDoc.eodSearchCode;
url.searchParams.append('symbols', symbolList.join(','));
if (!acc[exchange]) {
logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, { acc[exchange] = [];
exchange, }
count: symbolList.length, // eodSearchCode already has the correct format (e.g., AAPL.US)
samples: symbolList.slice(0, 5) acc[exchange].push(eodSearchCode);
}); return acc;
},
// Fetch data {} as Record<string, string[]>
const response = await fetch(url.toString()); );
if (!response.ok) { let totalProcessed = 0;
throw new Error(`EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`);
} // Process each exchange group
for (const [exchange, symbolList] of Object.entries(exchangeGroups)) {
const data = await response.json(); // Build URL - using the exchange as the endpoint
const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`);
// EOD bulk fundamentals returns an object with symbol keys url.searchParams.append('api_token', apiKey);
if (typeof data !== 'object' || !data) { url.searchParams.append('fmt', 'json');
throw new Error('Invalid response format from EOD API - expected object'); url.searchParams.append('symbols', symbolList.join(','));
}
logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, {
// Process each symbol's fundamentals exchange,
const fundamentalsToSave = []; count: symbolList.length,
const symbolsToUpdate = []; samples: symbolList.slice(0, 5),
});
for (const [symbolExchange, fundamentals] of Object.entries(data)) {
if (!fundamentals || typeof fundamentals !== 'object') { // Fetch data
logger.warn(`No fundamentals data for ${symbolExchange}`); const response = await fetch(url.toString());
continue;
} if (!response.ok) {
throw new Error(
// Extract symbol and exchange from the key `EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`
const [symbol, exchangeSuffix] = symbolExchange.split('.'); );
}
// Find the original symbol doc to get the actual exchange code
const symbolDoc = symbolDocs.find(doc => const data = await response.json();
doc.Code === symbol &&
(doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix) // EOD bulk fundamentals returns an object with symbol keys
); if (typeof data !== 'object' || !data) {
throw new Error('Invalid response format from EOD API - expected object');
if (!symbolDoc) { }
logger.warn(`Could not find symbol doc for ${symbolExchange}`);
continue; // Process each symbol's fundamentals
} const fundamentalsToSave = [];
const symbolsToUpdate = [];
const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const eodSearchCode = symbolDoc.eodSearchCode; for (const [symbolExchange, fundamentals] of Object.entries(data)) {
if (!fundamentals || typeof fundamentals !== 'object') {
// Add metadata logger.warn(`No fundamentals data for ${symbolExchange}`);
const fundamentalsWithMetadata = { continue;
symbol, }
exchange: actualExchange,
eodSearchCode, // Extract symbol and exchange from the key
...fundamentals, const [symbol, exchangeSuffix] = symbolExchange.split('.');
updatedAt: new Date(),
source: 'eod' // Find the original symbol doc to get the actual exchange code
}; const symbolDoc = symbolDocs.find(
doc =>
fundamentalsToSave.push(fundamentalsWithMetadata); doc.Code === symbol &&
symbolsToUpdate.push({ eodSearchCode }); (doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix)
} );
if (fundamentalsToSave.length > 0) { if (!symbolDoc) {
// Save fundamentals to MongoDB logger.warn(`Could not find symbol doc for ${symbolExchange}`);
const result = await this.mongodb.batchUpsert( continue;
'eodFundamentals', }
fundamentalsToSave,
['eodSearchCode'] const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange;
); const eodSearchCode = symbolDoc.eodSearchCode;
logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`); // Add metadata
const fundamentalsWithMetadata = {
// Update operation tracker for each symbol symbol,
const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => { exchange: actualExchange,
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { eodSearchCode,
status: 'success', ...fundamentals,
recordCount: 1, updatedAt: new Date(),
metadata: { source: 'eod',
hasData: true, };
exchange: exchange
} fundamentalsToSave.push(fundamentalsWithMetadata);
}); symbolsToUpdate.push({ eodSearchCode });
}); }
await Promise.all(updatePromises); if (fundamentalsToSave.length > 0) {
totalProcessed += fundamentalsToSave.length; // Save fundamentals to MongoDB
} const result = await this.mongodb.batchUpsert('eodFundamentals', fundamentalsToSave, [
} 'eodSearchCode',
]);
logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`);
logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`);
return {
success: true, // Update operation tracker for each symbol
symbolsProcessed: totalProcessed const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => {
}; return this.operationRegistry.updateOperation(
} catch (error) { 'eod',
logger.error('Failed to fetch bulk fundamentals', { error }); eodSearchCode,
'fundamentals_update',
// Mark all symbols as failed {
const failPromises = eodSearchCodes.map((eodSearchCode) => { status: 'success',
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { recordCount: 1,
status: 'failure', metadata: {
error: error.message hasData: true,
}); exchange: exchange,
}); },
}
await Promise.all(failPromises); );
throw error; });
}
} await Promise.all(updatePromises);
totalProcessed += fundamentalsToSave.length;
export async function fetchSingleFundamentals( }
this: EodHandler, }
input: FetchSingleFundamentalsInput
): Promise<{ success: boolean; saved: boolean }> { logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`);
const logger = this.logger;
const { eodSearchCode } = input; return {
success: true,
// Declare variables for catch block symbolsProcessed: totalProcessed,
let symbol: string = ''; };
let exchange: string = ''; } catch (error) {
logger.error('Failed to fetch bulk fundamentals', { error });
try {
// Lookup symbol using eodSearchCode // Mark all symbols as failed
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ const failPromises = eodSearchCodes.map(eodSearchCode => {
eodSearchCode: eodSearchCode return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
}); status: 'failure',
error: error instanceof Error ? error.message : String(error),
if (!symbolDoc) { });
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); });
throw new Error(`Symbol not found: ${eodSearchCode}`);
} await Promise.all(failPromises);
throw error;
symbol = symbolDoc.Code; }
exchange = symbolDoc.eodExchange || symbolDoc.Exchange; }
const country = symbolDoc.Country;
export async function fetchSingleFundamentals(
logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`); this: EodHandler,
input: FetchSingleFundamentalsInput
// Get API key ): Promise<{ success: boolean; saved: boolean }> {
const apiKey = EOD_CONFIG.API_TOKEN; const logger = this.logger;
if (!apiKey) { const { eodSearchCode } = input;
throw new Error('EOD API key not configured');
} // Declare variables for catch block
let symbol: string = '';
// Build URL for single fundamentals endpoint let exchange: string = '';
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`); try {
url.searchParams.append('api_token', apiKey); // Lookup symbol using eodSearchCode
url.searchParams.append('fmt', 'json'); const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode,
// Fetch data });
const response = await fetch(url.toString());
if (!symbolDoc) {
if (!response.ok) { logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`); throw new Error(`Symbol not found: ${eodSearchCode}`);
} }
const fundamentals = await response.json(); symbol = symbolDoc.Code;
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
// Check if we got valid data const _country = symbolDoc.Country;
if (!fundamentals || typeof fundamentals !== 'object') {
logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`); logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`);
return { success: true, saved: false };
} // Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
// Add metadata if (!apiKey) {
const fundamentalsWithMetadata = { throw new Error('EOD API key not configured');
symbol, }
exchange,
eodSearchCode, // Build URL for single fundamentals endpoint
...fundamentals, // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
updatedAt: new Date(), const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`);
source: 'eod' url.searchParams.append('api_token', apiKey);
}; url.searchParams.append('fmt', 'json');
// Save to MongoDB // Fetch data
const result = await this.mongodb.batchUpsert( const response = await fetch(url.toString());
'eodFundamentals',
[fundamentalsWithMetadata], if (!response.ok) {
['eodSearchCode'] throw new Error(
); `EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`
);
// Update operation tracker }
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'success', const fundamentals = await response.json();
recordCount: result.insertedCount,
metadata: { // Check if we got valid data
hasData: true, if (!fundamentals || typeof fundamentals !== 'object') {
exchange: exchange, logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`);
saved: result.insertedCount > 0 return { success: true, saved: false };
} }
});
// Add metadata
logger.info(`Successfully saved fundamentals for ${symbol}.${exchange}`); const fundamentalsWithMetadata = {
symbol,
return { exchange,
success: true, eodSearchCode,
saved: result.insertedCount > 0 ...fundamentals,
}; updatedAt: new Date(),
} catch (error) { source: 'eod',
logger.error('Failed to fetch single fundamentals', { error, symbol, exchange }); };
// Update operation tracker with failure // Save to MongoDB
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { const result = await this.mongodb.batchUpsert(
status: 'failure', 'eodFundamentals',
error: error.message [fundamentalsWithMetadata],
}); ['eodSearchCode']
);
throw error;
} // Update operation tracker
} await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'success',
recordCount: result.insertedCount,
metadata: {
hasData: true,
exchange: exchange,
saved: result.insertedCount > 0,
},
});
logger.info(`Successfully saved fundamentals for ${symbol}.${exchange}`);
return {
success: true,
saved: result.insertedCount > 0,
};
} catch (error) {
logger.error('Failed to fetch single fundamentals', { error, symbol, exchange });
// Update operation tracker with failure
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'failure',
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,197 +1,187 @@
import type { EodHandler } from '../eod.handler'; import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared'; import { EOD_CONFIG } from '../shared';
import { persistEodPrices } from '../shared/price-storage';
interface FetchPricesInput {
eodSearchCode: string; interface FetchPricesInput {
} eodSearchCode: string;
}
export async function scheduleFetchPrices(
this: EodHandler export async function scheduleFetchPrices(
): Promise<{ success: boolean; jobsScheduled: number }> { this: EodHandler
const logger = this.logger; ): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling price fetch jobs for all symbols'); try {
logger.info('Scheduling price fetch jobs for all symbols');
// Use OperationTracker to find stale symbols
const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'price_update', { // Use OperationTracker to find stale symbols
limit: 100000 // Higher limit to process all symbols const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'price_update', {
}); limit: 100000, // Higher limit to process all symbols
});
if (!staleSymbols || staleSymbols.length === 0) {
logger.info('No symbols need price updates'); if (!staleSymbols || staleSymbols.length === 0) {
return { success: true, jobsScheduled: 0 }; logger.info('No symbols need price updates');
} return { success: true, jobsScheduled: 0 };
}
logger.info(`Found ${staleSymbols.length} symbols needing price updates`, {
symbols: staleSymbols.slice(0, 10).map(s => ({ logger.info(`Found ${staleSymbols.length} symbols needing price updates`, {
symbol: s.symbol.Code, symbols: staleSymbols.slice(0, 10).map(s => ({
exchange: s.symbol.Exchange, symbol: s.symbol.Code,
name: s.symbol.Name, exchange: s.symbol.Exchange,
lastUpdate: s.lastRun name: s.symbol.Name,
})) lastUpdate: s.lastRun,
}); })),
});
let jobsScheduled = 0;
let jobsScheduled = 0;
// Schedule jobs with staggered delays
for (let i = 0; i < staleSymbols.length; i++) { // Schedule jobs with staggered delays
const staleSymbol = staleSymbols[i]; for (let i = 0; i < staleSymbols.length; i++) {
if (!staleSymbol || !staleSymbol.symbol) { const staleSymbol = staleSymbols[i];
logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol }); if (!staleSymbol || !staleSymbol.symbol) {
continue; logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol });
} continue;
const { symbol } = staleSymbol; }
const jobId = `fetch-prices-${symbol.eodSearchCode}`; const { symbol } = staleSymbol;
logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, { const jobId = `fetch-prices-${symbol.eodSearchCode}`;
name: symbol.Name, logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, {
lastUpdate: staleSymbol.lastRun, name: symbol.Name,
delay: i * 100, lastUpdate: staleSymbol.lastRun,
jobId delay: i * 100,
}); jobId,
});
try {
await this.scheduleOperation('fetch-prices', { try {
eodSearchCode: symbol.eodSearchCode await this.scheduleOperation(
}, { 'fetch-prices',
jobId, {
attempts: 3, eodSearchCode: symbol.eodSearchCode,
backoff: { },
type: 'exponential', {
delay: 5000 jobId,
}, attempts: 3,
delay: i * 100 // Stagger jobs by 100ms per symbol to avoid rate limit spikes backoff: {
}); type: 'exponential',
jobsScheduled++; delay: 5000,
} catch (error: any) { },
if (error?.message?.includes('Job already exists')) { delay: i * 100, // Stagger jobs by 100ms per symbol to avoid rate limit spikes
logger.debug(`Job already exists: ${jobId}`); }
} else { );
throw error; jobsScheduled++;
} } catch (error) {
} if (error instanceof Error && error.message.includes('Job already exists')) {
} logger.debug(`Job already exists: ${jobId}`);
} else {
logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`); throw error;
}
return { }
success: true, }
jobsScheduled
}; logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`);
} catch (error) {
logger.error('Failed to schedule price fetch jobs', { error }); return {
throw error; success: true,
} jobsScheduled,
} };
} catch (error) {
export async function fetchPrices( logger.error('Failed to schedule price fetch jobs', { error });
this: EodHandler, throw error;
input: FetchPricesInput }
): Promise<{ success: boolean; priceCount: number }> { }
const logger = this.logger;
const { eodSearchCode } = input; export async function fetchPrices(
this: EodHandler,
// Declare variables that need to be accessible in catch block input: FetchPricesInput
let symbol: string = ''; ): Promise<{ success: boolean; priceCount: number }> {
let exchange: string = ''; const logger = this.logger;
const { eodSearchCode } = input;
try {
// Lookup symbol using eodSearchCode // Declare variables that need to be accessible in catch block
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ let symbol: string = '';
eodSearchCode: eodSearchCode let exchange: string = '';
});
try {
if (!symbolDoc) { // Lookup symbol using eodSearchCode
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
throw new Error(`Symbol not found: ${eodSearchCode}`); eodSearchCode: eodSearchCode,
} });
symbol = symbolDoc.Code; if (!symbolDoc) {
exchange = symbolDoc.Exchange; logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
logger.info(`Fetching prices for ${eodSearchCode}`); }
// Get API key from config symbol = symbolDoc.Code;
const apiKey = EOD_CONFIG.API_TOKEN; exchange = symbolDoc.Exchange;
if (!apiKey) {
throw new Error('EOD API key not configured'); logger.info(`Fetching prices for ${eodSearchCode}`);
}
// Get API key from config
const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`); const apiKey = EOD_CONFIG.API_TOKEN;
url.searchParams.append('api_token', apiKey); if (!apiKey) {
url.searchParams.append('fmt', 'json'); throw new Error('EOD API key not configured');
// Fetch price data from EOD API }
const response = await fetch(url.toString());
const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`);
if (!response.ok) { url.searchParams.append('api_token', apiKey);
throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`); url.searchParams.append('fmt', 'json');
} // Fetch price data from EOD API
const response = await fetch(url.toString());
const priceData = await response.json();
if (!response.ok) {
// EOD returns an array of historical prices throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`);
if (!Array.isArray(priceData)) { }
throw new Error('Invalid response format from EOD API - expected array');
} const priceData = await response.json();
logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`); // EOD returns an array of historical prices
if (!Array.isArray(priceData)) {
// Log date range of prices throw new Error('Invalid response format from EOD API - expected array');
if (priceData.length > 0) { }
logger.debug(`Price data range for ${eodSearchCode}:`, {
oldest: priceData[0].date, logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`);
newest: priceData[priceData.length - 1].date,
count: priceData.length // Log date range of prices
}); if (priceData.length > 0) {
} logger.debug(`Price data range for ${eodSearchCode}:`, {
oldest: priceData[0].date,
// Add metadata to each price record newest: priceData[priceData.length - 1].date,
const pricesWithMetadata = priceData.map(price => ({ count: priceData.length,
symbol, });
exchange, }
eodSearchCode,
date: price.date, const result = await persistEodPrices(
open: price.open, this.mongodb,
high: price.high, { symbol, exchange, eodSearchCode },
low: price.low, priceData
close: price.close, );
adjustedClose: price.adjusted_close,
volume: price.volume, // Update operation tracker instead of directly updating the symbol
})); await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
status: 'success',
// Save to MongoDB - use date and eodSearchCode as unique identifier lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null,
const result = await this.mongodb.batchUpsert( recordCount: priceData.length,
'eodPrices', metadata: {
pricesWithMetadata, insertedCount: result.insertedCount,
['date', 'eodSearchCode'] updatedCount: priceData.length - result.insertedCount,
); },
});
// Update operation tracker instead of directly updating the symbol
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', { logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`);
status: 'success',
lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null, return {
recordCount: priceData.length, success: true,
metadata: { priceCount: result.insertedCount,
insertedCount: result.insertedCount, };
updatedCount: priceData.length - result.insertedCount } catch (error: unknown) {
} logger.error('Failed to fetch or save prices', { error, symbol, exchange });
});
// Update operation tracker with failure
logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`); await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
status: 'failure',
return { error: error instanceof Error ? error.message : String(error),
success: true, });
priceCount: result.insertedCount
}; throw error;
} catch (error: unknown) { }
logger.error('Failed to fetch or save prices', { error, symbol, exchange }); }
// Update operation tracker with failure
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
status: 'failure',
error: error instanceof Error ? error.message : String(error)
});
throw error;
}
}

View file

@ -1,153 +1,162 @@
import type { BaseHandler } from '@stock-bot/handlers'; import type { BaseHandler } from '@stock-bot/handlers';
import type { DataIngestionServices } from '../../../types'; import type { DataIngestionServices } from '../../../types';
import { EOD_CONFIG } from '../shared'; import { EOD_CONFIG } from '../shared';
interface FetchSymbolsInput { interface FetchSymbolsInput {
exchangeCode: string; exchangeCode: string;
delisted: boolean; delisted: boolean;
} }
export async function scheduleFetchSymbols(
export async function scheduleFetchSymbols( this: BaseHandler<DataIngestionServices>
this: BaseHandler<DataIngestionServices> ): Promise<{ success: boolean; jobsCreated: number }> {
): Promise<{ success: boolean; jobsCreated: number }> { const logger = this.logger;
const logger = this.logger;
try {
try { logger.info('Starting symbol fetch job scheduling');
logger.info('Starting symbol fetch job scheduling');
// Get all exchanges from MongoDB
// Get all exchanges from MongoDB const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray();
const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray();
if (!exchanges || exchanges.length === 0) {
if (!exchanges || exchanges.length === 0) { logger.warn('No exchanges found in database - run fetch-exchanges first');
logger.warn('No exchanges found in database - run fetch-exchanges first'); return { success: true, jobsCreated: 0 };
return { success: true, jobsCreated: 0 }; }
}
logger.info(`Found ${exchanges.length} exchanges to process`, {
logger.info(`Found ${exchanges.length} exchanges to process`, { exchanges: exchanges.map(e => ({ code: e.Code, name: e.Name, country: e.Country })),
exchanges: exchanges.map((e: any) => ({ code: e.Code, name: e.Name, country: e.Country })) });
});
let jobsCreated = 0;
let jobsCreated = 0;
// Create jobs for each exchange - both active and delisted symbols
// Create jobs for each exchange - both active and delisted symbols for (const exchange of exchanges) {
for (const exchange of exchanges) { const exchangeCode = exchange.Code;
const exchangeCode = exchange.Code;
// Job for active symbols
// Job for active symbols await this.scheduleOperation(
await this.scheduleOperation('fetch-symbols', { 'fetch-symbols',
exchangeCode, {
delisted: false exchangeCode,
}, { delisted: false,
attempts: 3, },
backoff: { {
type: 'exponential', attempts: 3,
delay: 5000 backoff: {
} type: 'exponential',
}); delay: 5000,
jobsCreated++; },
}
// Job for delisted symbols );
await this.scheduleOperation('fetch-symbols', { jobsCreated++;
exchangeCode,
delisted: true // Job for delisted symbols
}, { await this.scheduleOperation(
attempts: 3, 'fetch-symbols',
backoff: { {
type: 'exponential', exchangeCode,
delay: 5000 delisted: true,
} },
}); {
jobsCreated++; attempts: 3,
} backoff: {
type: 'exponential',
logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`); delay: 5000,
},
return { }
success: true, );
jobsCreated jobsCreated++;
}; }
} catch (error) {
logger.error('Failed to schedule symbol fetch jobs', { error }); logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`);
throw error;
} return {
} success: true,
jobsCreated,
export async function fetchSymbols( };
this: BaseHandler<DataIngestionServices>, } catch (error) {
input: FetchSymbolsInput logger.error('Failed to schedule symbol fetch jobs', { error });
): Promise<{ success: boolean; count: number }> { throw error;
const logger = this.logger; }
const { exchangeCode, delisted } = input; }
try { export async function fetchSymbols(
logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); this: BaseHandler<DataIngestionServices>,
input: FetchSymbolsInput
// Get API key from config ): Promise<{ success: boolean; count: number }> {
const apiKey = EOD_CONFIG.API_TOKEN; const logger = this.logger;
if (!apiKey) { const { exchangeCode, delisted } = input;
throw new Error('EOD API key not configured');
} try {
logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
// Build URL with query parameters
const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`); // Get API key from config
url.searchParams.append('api_token', apiKey); const apiKey = EOD_CONFIG.API_TOKEN;
url.searchParams.append('fmt', 'json'); if (!apiKey) {
throw new Error('EOD API key not configured');
if (delisted) { }
url.searchParams.append('delisted', '1');
} // Build URL with query parameters
const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`);
// Fetch symbols from EOD API using Bun fetch url.searchParams.append('api_token', apiKey);
const response = await fetch(url.toString()); url.searchParams.append('fmt', 'json');
if (!response.ok) { if (delisted) {
throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`); url.searchParams.append('delisted', '1');
} }
const symbols = await response.json(); // Fetch symbols from EOD API using Bun fetch
const response = await fetch(url.toString());
if (!Array.isArray(symbols)) {
throw new Error('Invalid response format from EOD API - expected array'); if (!response.ok) {
} throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`);
}
logger.info(`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
const symbols = await response.json();
// Log some sample symbols
if (symbols.length > 0) { if (!Array.isArray(symbols)) {
logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, { throw new Error('Invalid response format from EOD API - expected array');
count: symbols.length, }
samples: symbols.slice(0, 5).map(s => ({
symbol: s.Code, logger.info(
name: s.Name, `Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`
type: s.Type );
}))
}); // Log some sample symbols
} if (symbols.length > 0) {
logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, {
// Add metadata to each symbol count: symbols.length,
const symbolsWithMetadata = symbols.map(symbol => ({ samples: symbols.slice(0, 5).map(s => ({
...symbol, symbol: s.Code,
eodExchange: exchangeCode, // Store the correct exchange code used to fetch this symbol name: s.Name,
eodSearchCode: `${symbol.Code}.${exchangeCode}`, // Create unique search code like AAPL.US type: s.Type,
delisted: delisted, })),
})); });
}
// Save to MongoDB - use Code as unique identifier along with exchange
const result = await this.mongodb.batchUpsert( // Add metadata to each symbol
'eodSymbols', const symbolsWithMetadata = symbols.map(symbol => ({
symbolsWithMetadata, ...symbol,
['eodSearchCode'] eodExchange: exchangeCode, // Store the correct exchange code used to fetch this symbol
); eodSearchCode: `${symbol.Code}.${exchangeCode}`, // Create unique search code like AAPL.US
delisted: delisted,
logger.info(`Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); }));
return { // Save to MongoDB - use Code as unique identifier along with exchange
success: true, const result = await this.mongodb.batchUpsert('eodSymbols', symbolsWithMetadata, [
count: result.insertedCount 'eodSearchCode',
}; ]);
} catch (error) {
logger.error('Failed to fetch or save symbols', { error, exchangeCode, delisted }); logger.info(
throw error; `Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`
} );
}
return {
success: true,
count: result.insertedCount,
};
} catch (error) {
logger.error('Failed to fetch or save symbols', { error, exchangeCode, delisted });
throw error;
}
}

View file

@ -1,186 +1,189 @@
import { import {
BaseHandler, BaseHandler,
Disabled, Disabled,
Handler, Handler,
Operation, Operation,
RateLimit, RateLimit,
ScheduledOperation ScheduledOperation,
} from '@stock-bot/handlers'; } from '@stock-bot/handlers';
import type { OperationRegistry } from '../../shared/operation-manager'; import type { IServiceContainer } from '@stock-bot/services';
import type { DataIngestionServices } from '../../types'; import type { OperationRegistry } from '../../shared/operation-manager';
import { import { resolveIngestionServices } from '../../types';
crawlIntraday, import type { DataIngestionServices } from '../../types';
fetchBulkFundamentals, import {
fetchCorporateActions, crawlIntraday,
fetchExchanges, fetchBulkFundamentals,
fetchIntraday, fetchCorporateActions,
fetchPrices, fetchExchanges,
fetchSingleFundamentals, fetchIntraday,
fetchSymbolChangeHistory, fetchPrices,
fetchSymbols, fetchSingleFundamentals,
scheduleFetchCorporateActions, fetchSymbolChangeHistory,
scheduleFetchFundamentals, fetchSymbols,
scheduleFetchPrices, scheduleFetchCorporateActions,
scheduleFetchSymbols, scheduleFetchFundamentals,
scheduleIntradayCrawl scheduleFetchPrices,
} from './actions'; scheduleFetchSymbols,
import { createEODOperationRegistry } from './shared'; scheduleIntradayCrawl,
} from './actions';
/** import { createEODOperationRegistry } from './shared';
* EOD (End of Day) Handler demonstrating advanced rate limiting
* /**
* Handler-level limits apply to all operations unless overridden * EOD (End of Day) Handler demonstrating advanced rate limiting
* Operations can specify just a cost to use handler limits, or override with custom limits *
*/ * Handler-level limits apply to all operations unless overridden
@Handler('eod') * Operations can specify just a cost to use handler limits, or override with custom limits
@Disabled() */
@RateLimit({ @Handler('eod')
limits: [ @Disabled()
{ points: 900, duration: 60 }, // 1000 points per minute @RateLimit({
{ points: 100500, duration: 86400 }, // 100,500 points per day limits: [
], { points: 900, duration: 60 }, // 1000 points per minute
}) { points: 100500, duration: 86400 }, // 100,500 points per day
export class EodHandler extends BaseHandler<DataIngestionServices> { ],
public operationRegistry!: OperationRegistry; })
export class EodHandler extends BaseHandler<DataIngestionServices> {
constructor(services: any) { static operationRegistry?: OperationRegistry;
super(services); public operationRegistry!: OperationRegistry;
// Use pre-initialized registry if available, otherwise create new one constructor(services: IServiceContainer) {
if ((EodHandler as any).operationRegistry) { super(resolveIngestionServices(services, 'eod'));
this.operationRegistry = (EodHandler as any).operationRegistry;
this.logger.info('Using pre-initialized EOD operation registry'); // Use pre-initialized registry if available, otherwise create new one
} else { if (EodHandler.operationRegistry) {
// Fallback: Initialize operation registry with EOD provider this.operationRegistry = EodHandler.operationRegistry;
createEODOperationRegistry(this.mongodb, this.logger) this.logger.info('Using pre-initialized EOD operation registry');
.then(registry => { } else {
this.operationRegistry = registry; // Fallback: Initialize operation registry with EOD provider
this.logger.info('EOD operation registry initialized successfully'); createEODOperationRegistry(this.mongodb, this.logger)
}) .then(registry => {
.catch(error => { this.operationRegistry = registry;
this.logger.error('Failed to initialize EOD operations', { error }); this.logger.info('EOD operation registry initialized successfully');
}); })
} .catch(error => {
} this.logger.error('Failed to initialize EOD operations', { error });
});
/** }
* Fetch exchanges list from EOD }
* Runs weekly on Sundays at midnight
*/ /**
@Operation('fetch-exchanges') * Fetch exchanges list from EOD
@ScheduledOperation('fetch-exchanges', '0 0 * * 0') * Runs weekly on Sundays at midnight
@RateLimit(1) // 1 point per call */
fetchExchanges = fetchExchanges; @Operation('fetch-exchanges')
@ScheduledOperation('fetch-exchanges', '0 0 * * 0')
/** @RateLimit(1) // 1 point per call
* Schedule symbol fetching for all exchanges fetchExchanges = fetchExchanges;
* Runs daily at 1 AM
*/ /**
@Operation('schedule-fetch-symbols') * Schedule symbol fetching for all exchanges
@ScheduledOperation('schedule-fetch-symbols', '0 1 * * *') * Runs daily at 1 AM
@RateLimit(1) // 1 point for scheduling */
scheduleFetchSymbols = scheduleFetchSymbols; @Operation('schedule-fetch-symbols')
@ScheduledOperation('schedule-fetch-symbols', '0 1 * * *')
/** @RateLimit(1) // 1 point for scheduling
* Fetch symbols for a specific exchange scheduleFetchSymbols = scheduleFetchSymbols;
* Called by schedule-fetch-symbols for each exchange
*/ /**
@Operation('fetch-symbols') * Fetch symbols for a specific exchange
@RateLimit(1) // 1 point per exchange * Called by schedule-fetch-symbols for each exchange
fetchSymbols = fetchSymbols; */
@Operation('fetch-symbols')
/** @RateLimit(1) // 1 point per exchange
* Schedule price fetching for all symbols not updated in last week fetchSymbols = fetchSymbols;
* Runs daily at 2 AM
*/ /**
@Operation('schedule-fetch-prices') * Schedule price fetching for all symbols not updated in last week
@ScheduledOperation('schedule-fetch-prices', '0 2 * * *') * Runs daily at 2 AM
@RateLimit(1) // 1 point for scheduling */
scheduleFetchPrices = scheduleFetchPrices; @Operation('schedule-fetch-prices')
@ScheduledOperation('schedule-fetch-prices', '0 2 * * *')
/** @RateLimit(1) // 1 point for scheduling
* Fetch historical prices for a specific symbol scheduleFetchPrices = scheduleFetchPrices;
* Called by schedule-fetch-prices for each symbol
*/ /**
@Operation('fetch-prices') * Fetch historical prices for a specific symbol
@RateLimit(1) // 1 point per price fetch * Called by schedule-fetch-prices for each symbol
fetchPrices = fetchPrices; */
@Operation('fetch-prices')
/** @RateLimit(1) // 1 point per price fetch
* Schedule intraday crawl for symbols needing intraday data fetchPrices = fetchPrices;
* Runs daily at 3 AM
*/ /**
@Operation('schedule-intraday-crawl') * Schedule intraday crawl for symbols needing intraday data
@ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', { * Runs daily at 3 AM
immediately: true, */
}) @Operation('schedule-intraday-crawl')
@RateLimit(1) // 1 point for scheduling @ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', {
scheduleIntradayCrawl = scheduleIntradayCrawl; immediately: true,
})
/** @RateLimit(1) // 1 point for scheduling
* Crawl intraday data for a specific symbol and interval scheduleIntradayCrawl = scheduleIntradayCrawl;
* Handles resumption and batch processing
*/ /**
@Operation('crawl-intraday') * Crawl intraday data for a specific symbol and interval
@RateLimit(5) // 5 points per crawl batch * Handles resumption and batch processing
crawlIntraday = crawlIntraday; */
@Operation('crawl-intraday')
/** @RateLimit(5) // 5 points per crawl batch
* Fetch intraday data for a specific date range crawlIntraday = crawlIntraday;
* Called by crawl-intraday
*/ /**
@Operation('fetch-intraday') * Fetch intraday data for a specific date range
@RateLimit(5) // 5 points per intraday fetch * Called by crawl-intraday
fetchIntraday = fetchIntraday; */
@Operation('fetch-intraday')
/** @RateLimit(5) // 5 points per intraday fetch
* Schedule bulk fundamentals fetch for symbols fetchIntraday = fetchIntraday;
* DISABLED - Not scheduled automatically
*/ /**
@Operation('schedule-fetch-fundamentals') * Schedule bulk fundamentals fetch for symbols
// @ScheduledOperation('schedule-fetch-fundamentals', '0 4 * * 0') // Disabled - would run weekly at 4 AM on Sundays * DISABLED - Not scheduled automatically
@RateLimit(1) // 1 point for scheduling */
scheduleFetchFundamentals = scheduleFetchFundamentals; @Operation('schedule-fetch-fundamentals')
// @ScheduledOperation('schedule-fetch-fundamentals', '0 4 * * 0') // Disabled - would run weekly at 4 AM on Sundays
/** @RateLimit(1) // 1 point for scheduling
* Fetch fundamentals for up to 500 symbols in bulk scheduleFetchFundamentals = scheduleFetchFundamentals;
* Called by schedule-fetch-fundamentals for non-ETFs
*/ /**
@Operation('fetch-bulk-fundamentals') * Fetch fundamentals for up to 500 symbols in bulk
@RateLimit(600) // 100 base + up to 500 symbols = 600 points max * Called by schedule-fetch-fundamentals for non-ETFs
fetchBulkFundamentals = fetchBulkFundamentals; */
@Operation('fetch-bulk-fundamentals')
/** @RateLimit(600) // 100 base + up to 500 symbols = 600 points max
* Fetch fundamentals for a single symbol fetchBulkFundamentals = fetchBulkFundamentals;
* Called by schedule-fetch-fundamentals for ETFs
*/ /**
@Operation('fetch-single-fundamentals') * Fetch fundamentals for a single symbol
@RateLimit(10) // 10 points per single fundamentals fetch * Called by schedule-fetch-fundamentals for ETFs
fetchSingleFundamentals = fetchSingleFundamentals; */
@Operation('fetch-single-fundamentals')
/** @RateLimit(10) // 10 points per single fundamentals fetch
* Fetch symbol change history fetchSingleFundamentals = fetchSingleFundamentals;
* Runs weekly on Mondays at 5 AM
*/ /**
@Operation('fetch-symbol-change-history') * Fetch symbol change history
@ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1') * Runs weekly on Mondays at 5 AM
@RateLimit(5) // 5 points per request */
fetchSymbolChangeHistory = fetchSymbolChangeHistory; @Operation('fetch-symbol-change-history')
@ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1')
/** @RateLimit(5) // 5 points per request
* Schedule corporate actions (dividends and splits) fetch fetchSymbolChangeHistory = fetchSymbolChangeHistory;
* DISABLED - Corporate actions likely come with fundamentals
*/ /**
@Operation('schedule-fetch-corporate-actions') * Schedule corporate actions (dividends and splits) fetch
// @ScheduledOperation('schedule-fetch-corporate-actions', '0 6 1 * *') // Disabled - would run monthly on the 1st at 6 AM * DISABLED - Corporate actions likely come with fundamentals
@RateLimit(1) // 1 point for scheduling */
scheduleFetchCorporateActions = scheduleFetchCorporateActions; @Operation('schedule-fetch-corporate-actions')
// @ScheduledOperation('schedule-fetch-corporate-actions', '0 6 1 * *') // Disabled - would run monthly on the 1st at 6 AM
/** @RateLimit(1) // 1 point for scheduling
* Fetch dividends or splits for a specific symbol scheduleFetchCorporateActions = scheduleFetchCorporateActions;
* Called by schedule-fetch-corporate-actions
*/ /**
@Operation('fetch-corporate-actions') * Fetch dividends or splits for a specific symbol
@RateLimit(10) // 10 points per fetch * Called by schedule-fetch-corporate-actions
fetchCorporateActions = fetchCorporateActions; */
} @Operation('fetch-corporate-actions')
@RateLimit(10) // 10 points per fetch
fetchCorporateActions = fetchCorporateActions;
}

View file

@ -1,118 +1,127 @@
/** import type { Logger, MongoDBClient } from '@stock-bot/services';
* EOD Operation Provider - Defines operations for EOD Historical Data source /**
*/ * EOD Operation Provider - Defines operations for EOD Historical Data source
*/
import { BaseOperationProvider, OperationRegistry, type OperationConfig, type ProviderConfig } from '../../../shared/operation-manager';
import {
/** BaseOperationProvider,
* EOD operation definitions OperationRegistry,
*/ type OperationConfig,
export const EOD_OPERATIONS: OperationConfig[] = [ type ProviderConfig,
// Exchange data } from '../../../shared/operation-manager';
{
name: 'exchange_update', /**
type: 'standard', * EOD operation definitions
description: 'Update exchange list', */
defaultStaleHours: 24 * 7 // Weekly export const EOD_OPERATIONS: OperationConfig[] = [
}, // Exchange data
{
// Symbol data name: 'exchange_update',
{ type: 'standard',
name: 'symbol_update', description: 'Update exchange list',
type: 'standard', defaultStaleHours: 24 * 7, // Weekly
description: 'Update symbol list for exchange', },
defaultStaleHours: 24 // Daily
}, // Symbol data
{
// Price data name: 'symbol_update',
{ type: 'standard',
name: 'price_update', description: 'Update symbol list for exchange',
type: 'standard', defaultStaleHours: 24, // Daily
description: 'Update daily price data', },
defaultStaleHours: 24 * 7 // Weekly - EOD's schedule-fetch-prices runs for symbols not updated in last week
}, // Price data
{
// Intraday data name: 'price_update',
{ type: 'standard',
name: 'intraday_1m', description: 'Update daily price data',
type: 'intraday_crawl', defaultStaleHours: 24 * 7, // Weekly - EOD's schedule-fetch-prices runs for symbols not updated in last week
description: 'Crawl 1-minute intraday data', },
requiresFinishedFlag: true,
defaultStaleHours: 50000 // Daily check for new data // Intraday data
}, {
{ name: 'intraday_1m',
name: 'intraday_5m', type: 'intraday_crawl',
type: 'intraday_crawl', description: 'Crawl 1-minute intraday data',
description: 'Crawl 5-minute intraday data', requiresFinishedFlag: true,
requiresFinishedFlag: true, defaultStaleHours: 50000, // Daily check for new data
defaultStaleHours: 50000 // Daily check for new data },
}, {
{ name: 'intraday_5m',
name: 'intraday_1h', type: 'intraday_crawl',
type: 'intraday_crawl', description: 'Crawl 5-minute intraday data',
description: 'Crawl 1-hour intraday data', requiresFinishedFlag: true,
requiresFinishedFlag: true, defaultStaleHours: 50000, // Daily check for new data
defaultStaleHours: 50000 // Daily check for new data },
}, {
name: 'intraday_1h',
// Fundamental data type: 'intraday_crawl',
{ description: 'Crawl 1-hour intraday data',
name: 'fundamentals_update', requiresFinishedFlag: true,
type: 'standard', defaultStaleHours: 50000, // Daily check for new data
description: 'Update fundamental data', },
defaultStaleHours: 24 * 7 // Weekly
}, // Fundamental data
{
// Corporate actions name: 'fundamentals_update',
{ type: 'standard',
name: 'dividends_update', description: 'Update fundamental data',
type: 'standard', defaultStaleHours: 24 * 7, // Weekly
description: 'Update dividend data', },
defaultStaleHours: 24 * 30 // Monthly
}, // Corporate actions
{ {
name: 'splits_update', name: 'dividends_update',
type: 'standard', type: 'standard',
description: 'Update stock split data', description: 'Update dividend data',
defaultStaleHours: 24 * 30 // Monthly defaultStaleHours: 24 * 30, // Monthly
}, },
{
// Symbol changes name: 'splits_update',
{ type: 'standard',
name: 'symbol_change_update', description: 'Update stock split data',
type: 'standard', defaultStaleHours: 24 * 30, // Monthly
description: 'Update symbol change history', },
defaultStaleHours: 24 * 7 // Weekly
} // Symbol changes
]; {
name: 'symbol_change_update',
/** type: 'standard',
* EOD Operation Provider description: 'Update symbol change history',
*/ defaultStaleHours: 24 * 7, // Weekly
export class EODOperationProvider extends BaseOperationProvider { },
getProviderConfig(): ProviderConfig { ];
return {
name: 'eod', /**
collectionName: 'eodSymbols', * EOD Operation Provider
symbolField: 'eodSearchCode', */
description: 'EOD Historical Data provider' export class EODOperationProvider extends BaseOperationProvider {
}; getProviderConfig(): ProviderConfig {
} return {
name: 'eod',
getOperations(): OperationConfig[] { collectionName: 'eodSymbols',
return EOD_OPERATIONS; symbolField: 'eodSearchCode',
} description: 'EOD Historical Data provider',
} };
}
/**
* Create and initialize EOD operation registry getOperations(): OperationConfig[] {
*/ return EOD_OPERATIONS;
export async function createEODOperationRegistry( }
mongodb: any, }
logger: any
): Promise<OperationRegistry> { /**
const registry = new OperationRegistry({ mongodb, logger }); * Create and initialize EOD operation registry
const provider = new EODOperationProvider({ mongodb, logger }); */
await registry.registerProvider(provider); export async function createEODOperationRegistry(
return registry; mongodb: MongoDBClient | null | undefined,
} logger: Logger
): Promise<OperationRegistry> {
if (!mongodb) {
throw new Error('Operation registry requires MongoDB');
}
const registry = new OperationRegistry({ mongodb, logger });
const provider = new EODOperationProvider({ mongodb, logger });
await registry.registerProvider(provider);
return registry;
}

View file

@ -0,0 +1,47 @@
import type { MongoDBClient } from '@stock-bot/services';
export interface EodPrice {
date: string;
open: number;
high: number;
low: number;
close: number;
adjusted_close?: number;
volume: number;
}
/** Shared persistence boundary used by the HTTP action and deterministic replay tests. */
export async function persistEodPrices(
mongodb: Pick<MongoDBClient, 'batchUpsert'>,
identity: { symbol: string; exchange: string; eodSearchCode: string },
prices: readonly EodPrice[]
) {
const documents = prices.map(price => {
if (
typeof price.date !== 'string' ||
!/^\d{4}-\d{2}-\d{2}$/.test(price.date) ||
!Number.isFinite(Date.parse(price.date)) ||
new Date(price.date).toISOString().slice(0, 10) !== price.date ||
![price.open, price.high, price.low, price.close, price.volume].every(Number.isFinite) ||
(price.adjusted_close !== undefined && !Number.isFinite(price.adjusted_close)) ||
price.low <= 0 ||
price.high < Math.max(price.open, price.close) ||
price.low > Math.min(price.open, price.close) ||
price.volume < 0
) {
throw new Error(`Invalid OHLCV price record for ${identity.eodSearchCode}`);
}
return {
...identity,
source: 'eod',
date: price.date,
open: price.open,
high: price.high,
low: price.low,
close: price.close,
adjustedClose: price.adjusted_close ?? price.close,
volume: price.volume,
};
});
return mongodb.batchUpsert('eodPrices', documents, ['date', 'eodSearchCode']);
}

View file

@ -1,3 +1,4 @@
import type { IServiceContainer } from '@stock-bot/services';
import { fetchExchanges } from './fetch-exchanges.action'; import { fetchExchanges } from './fetch-exchanges.action';
import { fetchSession } from './fetch-session.action'; import { fetchSession } from './fetch-session.action';
import { fetchSymbols } from './fetch-symbols.action'; import { fetchSymbols } from './fetch-symbols.action';

View file

@ -1,19 +1,20 @@
import { Browser } from '@stock-bot/browser';
import type { IServiceContainer } from '@stock-bot/handlers'; import type { IServiceContainer } from '@stock-bot/handlers';
import { requireServices } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config'; import { IB_CONFIG } from '../shared/config';
export async function fetchSession( export async function fetchSession(
services: IServiceContainer services: IServiceContainer
): Promise<Record<string, string> | undefined> { ): Promise<Record<string, string> | undefined> {
try { try {
await Browser.initialize({ const { browser } = requireServices(services, 'browser');
await browser.initialize({
headless: true, headless: true,
timeout: IB_CONFIG.BROWSER_TIMEOUT, timeout: IB_CONFIG.BROWSER_TIMEOUT,
blockResources: false, blockResources: false,
}); });
services.logger.info('✅ Browser initialized'); services.logger.info('✅ Browser initialized');
const { page } = await Browser.createPageWithProxy( const { page } = await browser.createPageWithProxy(
IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE, IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE,
IB_CONFIG.DEFAULT_PROXY IB_CONFIG.DEFAULT_PROXY
); );

View file

@ -1,4 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers'; import type { IServiceContainer } from '@stock-bot/handlers';
import { requireServices } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config'; import { IB_CONFIG } from '../shared/config';
import { fetchSession } from './fetch-session.action'; import { fetchSession } from './fetch-session.action';
@ -104,7 +105,10 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
services.logger.info('✅ IB symbols fetched successfully, saving to DB...', { services.logger.info('✅ IB symbols fetched successfully, saving to DB...', {
totalSymbols: symbols.length, totalSymbols: symbols.length,
}); });
await services.mongodb.batchUpsert('ib_symbols', symbols, ['symbol', 'exchangeId']); await requireServices(services, 'mongodb').mongodb.batchUpsert('ib_symbols', symbols, [
'symbol',
'exchangeId',
]);
services.logger.info('Saved IB symbols to DB', { services.logger.info('Saved IB symbols to DB', {
totalSymbols: symbols.length, totalSymbols: symbols.length,
}); });

View file

@ -1,17 +1,13 @@
import { import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
BaseHandler, import type { IServiceContainer } from '@stock-bot/services';
Disabled, import { resolveIngestionServices } from '../../types';
Handler,
Operation,
ScheduledOperation,
} from '@stock-bot/handlers';
import { fetchExchanges, fetchExchangesAndSymbols, fetchSession, fetchSymbols } from './actions'; import { fetchExchanges, fetchExchangesAndSymbols, fetchSession, fetchSymbols } from './actions';
@Handler('ib') @Handler('ib')
@Disabled() @Disabled()
export class IbHandler extends BaseHandler { export class IbHandler extends BaseHandler {
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); super(resolveIngestionServices(services, 'ib'));
} }
@Operation('fetch-session') @Operation('fetch-session')

View file

@ -1,3 +1,4 @@
import type { HandlerInitializationContext } from '@stock-bot/di';
/** /**
* Handler initialization for data-ingestion service * Handler initialization for data-ingestion service
* Uses explicit imports for bundling compatibility * Uses explicit imports for bundling compatibility
@ -5,74 +6,88 @@
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services'; import type { IServiceContainer } from '@stock-bot/services';
import type { DecoratedHandlerClass } from '@stock-bot/types';
import type { OperationRegistry } from '../shared/operation-manager';
// Import handlers explicitly for bundling (ensures they're included in the build) // Import handlers explicitly for bundling (ensures they're included in the build)
// These imports trigger the decorator metadata to be set // These imports trigger the decorator metadata to be set
import { CeoHandler } from './ceo/ceo.handler'; import { CeoHandler } from './ceo/ceo.handler';
import { EodHandler } from './eod/eod.handler';
import { createEODOperationRegistry } from './eod/shared';
import { IbHandler } from './ib/ib.handler'; import { IbHandler } from './ib/ib.handler';
import { QMHandler } from './qm/qm.handler'; import { QMHandler } from './qm/qm.handler';
import { WebShareHandler } from './webshare/webshare.handler';
import { TradingViewHandler } from './tradingview/tradingview.handler';
import { TeHandler } from './te/te.handler';
import { EodHandler } from './eod/eod.handler';
import { TtHandler } from './tt/tt.handler';
import { createEODOperationRegistry } from './eod/shared';
import { createQMOperationRegistry } from './qm/shared/operation-provider'; import { createQMOperationRegistry } from './qm/shared/operation-provider';
import { TeHandler } from './te/te.handler';
import { TradingViewHandler } from './tradingview/tradingview.handler';
import { TtHandler } from './tt/tt.handler';
import { WebShareHandler } from './webshare/webshare.handler';
// Add more handler imports as needed // Add more handler imports as needed
const logger = getLogger('handler-init'); const logger = getLogger('handler-init');
// Global operation registries that handlers will reference // Global operation registries that handlers will reference
let eodOperationRegistry: any; let eodOperationRegistry: OperationRegistry | undefined;
let qmOperationRegistry: any; let qmOperationRegistry: OperationRegistry | undefined;
/** /**
* Initialize and register all handlers * Initialize and register all handlers
* Note: The actual registration is now handled by the HandlerScanner in the DI container * Note: The actual registration is now handled by the HandlerScanner in the DI container
* This function is kept for backward compatibility and explicit handler imports * This function is kept for backward compatibility and explicit handler imports
*/ */
export async function initializeAllHandlers(serviceContainer: IServiceContainer): Promise<void> { export async function initializeAllHandlers(
serviceContainer: IServiceContainer,
context: HandlerInitializationContext
): Promise<void> {
try { try {
// Initialize operation registries first // Initialize operation registries first
logger.info('Initializing operation registries'); logger.info('Initializing operation registries');
const mongodb = serviceContainer.mongodb; const mongodb = serviceContainer.mongodb;
const operationLogger = serviceContainer.logger; const operationLogger = serviceContainer.logger;
// Create operation registries // Create operation registries
try { try {
eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger); eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger);
logger.info('EOD operation registry created'); logger.info('EOD operation registry created');
// Attach to handler class so instances can access it // Attach to handler class so instances can access it
(EodHandler as any).operationRegistry = eodOperationRegistry; EodHandler.operationRegistry = eodOperationRegistry;
} catch (error) { } catch (error) {
logger.error('Failed to create EOD operation registry', { error }); logger.error('Failed to create EOD operation registry', { error });
} }
try { try {
qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger); qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger);
logger.info('QM operation registry created'); logger.info('QM operation registry created');
// Attach to handler class so instances can access it // Attach to handler class so instances can access it
(QMHandler as any).operationRegistry = qmOperationRegistry; QMHandler.operationRegistry = qmOperationRegistry;
} catch (error) { } catch (error) {
logger.error('Failed to create QM operation registry', { error }); logger.error('Failed to create QM operation registry', { error });
} }
// The HandlerScanner in the DI container will handle the actual registration // The HandlerScanner in the DI container will handle the actual registration
// We just need to ensure handlers are imported so their decorators run // We just need to ensure handlers are imported so their decorators run
const handlers = [CeoHandler, IbHandler, QMHandler, WebShareHandler, TradingViewHandler, TeHandler, EodHandler, TtHandler]; const handlers = [
CeoHandler,
IbHandler,
QMHandler,
WebShareHandler,
TradingViewHandler,
TeHandler,
EodHandler,
TtHandler,
];
logger.info('Handler imports loaded', { logger.info('Handler imports loaded', {
count: handlers.length, count: handlers.length,
handlers: handlers.map(h => (h as any).__handlerName || h.name), handlers: handlers.map(h => (h as DecoratedHandlerClass).__handlerName || h.name),
}); });
// Log what metadata the handlers have // Log what metadata the handlers have
for (const HandlerClass of handlers) { for (const HandlerClass of handlers) {
const metadata = (HandlerClass as any).__handlerMetadata; const metadata = HandlerClass.extractMetadata();
logger.info(`Handler ${HandlerClass.name} metadata`, { logger.info(`Handler ${HandlerClass.name} metadata`, {
hasMetadata: !!metadata, hasMetadata: !!metadata,
handlerName: metadata?.name, handlerName: metadata?.name,
@ -82,11 +97,11 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
} }
// Get the DI container from the service container // Get the DI container from the service container
const diContainer = (serviceContainer as any)._diContainer; const diContainer = context;
if (diContainer?.resolve) { if (diContainer) {
// Get handler scanner from DI container // Get handler scanner from DI container
const scanner = diContainer.resolve('handlerScanner'); const scanner = context.handlerScanner;
if (scanner?.registerHandlerClass) { if (scanner?.registerHandlerClass) {
for (const HandlerClass of handlers) { for (const HandlerClass of handlers) {
scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' }); scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' });
@ -97,13 +112,13 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
} }
// Also check the handler registry directly // Also check the handler registry directly
const handlerRegistry = diContainer.resolve('handlerRegistry'); const handlerRegistry = context.handlerRegistry;
if (handlerRegistry) { if (handlerRegistry) {
logger.info('Handler registry state after registration', { logger.info('Handler registry state after registration', {
registeredHandlers: handlerRegistry.getHandlerNames(), registeredHandlers: handlerRegistry.getHandlerNames(),
handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size, handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size,
}); });
// Initialize handlers that have onInit method // Initialize handlers that have onInit method
// We need to instantiate handlers and call their onInit // We need to instantiate handlers and call their onInit
for (const HandlerClass of handlers) { for (const HandlerClass of handlers) {
@ -111,7 +126,8 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
// Create handler instance with service container // Create handler instance with service container
const handlerInstance = new HandlerClass(serviceContainer); const handlerInstance = new HandlerClass(serviceContainer);
if (handlerInstance && typeof handlerInstance.onInit === 'function') { if (handlerInstance && typeof handlerInstance.onInit === 'function') {
const handlerName = (HandlerClass as any).__handlerName || HandlerClass.name; const handlerName =
(HandlerClass as DecoratedHandlerClass).__handlerName || HandlerClass.name;
logger.info(`Calling onInit for handler: ${handlerName}`); logger.info(`Calling onInit for handler: ${handlerName}`);
await handlerInstance.onInit(); await handlerInstance.onInit();
} }

View file

@ -1,3 +1,4 @@
import type { Document } from 'mongodb';
/** /**
* QM Events Actions - Fetch and update dividends, splits, and earnings together * QM Events Actions - Fetch and update dividends, splits, and earnings together
*/ */
@ -30,7 +31,7 @@ export async function updateEvents(
}; };
}> { }> {
const { symbol, exchange, qmSearchCode } = input; const { symbol, exchange, qmSearchCode } = input;
this.logger.info(`Fetching events ${qmSearchCode}`, { symbol, exchange, qmSearchCode }); this.logger.info(`Fetching events ${qmSearchCode}`, { symbol, exchange, qmSearchCode });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
@ -39,7 +40,7 @@ export async function updateEvents(
// Get a session - you'll need to add the appropriate session ID // Get a session - you'll need to add the appropriate session ID
const sessionId = QM_SESSION_IDS.PRICES; // TODO: Update with correct session ID const sessionId = QM_SESSION_IDS.PRICES; // TODO: Update with correct session ID
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM events ${qmSearchCode}`); throw new Error(`No active session found for QM events ${qmSearchCode}`);
} }
@ -50,10 +51,9 @@ export async function updateEvents(
earnings: 'true', earnings: 'true',
splits: 'true', splits: 'true',
dividends: 'true', dividends: 'true',
symbol: qmSearchCode, symbol: qmSearchCode,
}); });
// TODO: Update with correct events endpoint // TODO: Update with correct events endpoint
const apiUrl = `${QM_CONFIG.EVENTS_URL}?${searchParams.toString()}`; const apiUrl = `${QM_CONFIG.EVENTS_URL}?${searchParams.toString()}`;
@ -75,111 +75,121 @@ export async function updateEvents(
}); });
throw new Error(`Invalid response structure from QM API for ${qmSearchCode}`); throw new Error(`Invalid response structure from QM API for ${qmSearchCode}`);
} }
// Update session success stats // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
let dividendCount = 0; let dividendCount = 0;
let splitCount = 0; let splitCount = 0;
let earningsCount = 0; let earningsCount = 0;
// Process dividends // Process dividends
if (results.dividends[0].dividend && results.dividends[0].dividend.length > 0 && Array.isArray(results.dividends[0].dividend)) { if (
results.dividends[0].dividend &&
results.dividends[0].dividend.length > 0 &&
Array.isArray(results.dividends[0].dividend)
) {
await this.mongodb.batchUpsert( await this.mongodb.batchUpsert(
'qmDividends', 'qmDividends',
results.dividends[0].dividend.map((dividend: any) => ({ results.dividends[0].dividend.map((dividend: Document) => ({
...dividend, ...dividend,
symbol, symbol,
exchange, exchange,
qmSearchCode, qmSearchCode,
reportDate: new Date(dividend.date), reportDate: new Date(dividend.date),
})), })),
['qmSearchCode','reportDate'] ['qmSearchCode', 'reportDate']
); );
dividendCount = results.dividends[0].dividend.length; dividendCount = results.dividends[0].dividend.length;
} }
// Process splits // Process splits
if (results.splits[0].split && results.splits[0].split.length > 0 && Array.isArray(results.splits[0].split)) { if (
results.splits[0].split &&
results.splits[0].split.length > 0 &&
Array.isArray(results.splits[0].split)
) {
await this.mongodb.batchUpsert( await this.mongodb.batchUpsert(
'qmSplits', 'qmSplits',
results.splits[0].split.map((split: any) => ({ results.splits[0].split.map((split: Document) => ({
...split, ...split,
symbol, symbol,
exchange, exchange,
qmSearchCode, qmSearchCode,
reportDate: new Date(split.date), reportDate: new Date(split.date),
})), })),
['qmSearchCode','reportDate'] ['qmSearchCode', 'reportDate']
); );
splitCount = results.splits[0].split.length; splitCount = results.splits[0].split.length;
} }
// Process earnings // Process earnings
if (results.earnings[0].earning && results.earnings[0].earning.length > 0 && Array.isArray(results.earnings[0].earning)) { if (
results.earnings[0].earning &&
results.earnings[0].earning.length > 0 &&
Array.isArray(results.earnings[0].earning)
) {
await this.mongodb.batchUpsert( await this.mongodb.batchUpsert(
'qmEarnings', 'qmEarnings',
results.earnings[0].earning.map((earning: any) => ({ results.earnings[0].earning.map((earning: Document) => ({
...earning, ...earning,
symbol, symbol,
exchange, exchange,
qmSearchCode, qmSearchCode,
reportDate: new Date(earning.reportDate[0]), reportDate: new Date(earning.reportDate[0]),
})), })),
['qmSearchCode','reportDate'] ['qmSearchCode', 'reportDate']
); );
earningsCount = results.earnings[0].earning.length; earningsCount = results.earnings[0].earning.length;
} }
// Update tracking for events // Update tracking for events
const updateTime = new Date(); const updateTime = new Date();
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', {
status: 'success', status: 'success',
lastRecordDate: updateTime, lastRecordDate: updateTime,
recordCount: dividendCount + splitCount + earningsCount recordCount: dividendCount + splitCount + earningsCount,
}); });
this.logger.info(`Events updated successfully ${qmSearchCode}`, { this.logger.info(`Events updated successfully ${qmSearchCode}`, {
symbol, symbol,
dividendCount, dividendCount,
splitCount, splitCount,
earningsCount earningsCount,
}); });
return { return {
success: true, success: true,
symbol, symbol,
message: `Events updated for ${qmSearchCode}`, message: `Events updated for ${qmSearchCode}`,
data: { data: {
dividends: dividendCount, dividends: dividendCount,
splits: splitCount, splits: splitCount,
earnings: earningsCount earnings: earningsCount,
} },
}; };
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error fetching events', { this.logger.error('Error fetching events', {
symbol, symbol,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
// Track failure for events // Track failure for events
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', {
status: 'failure' status: 'failure',
}); });
return { return {
success: false, success: false,
symbol, symbol,
message: `Failed to fetch events: ${error instanceof Error ? error.message : 'Unknown error'}` message: `Failed to fetch events: ${error instanceof Error ? error.message : 'Unknown error'}`,
}; };
} }
} }
@ -200,14 +210,14 @@ export async function scheduleEventsUpdates(
errors: number; errors: number;
}> { }> {
const { limit = 100000, forceUpdate = false } = input; const { limit = 100000, forceUpdate = false } = input;
this.logger.info('Scheduling events updates', { limit, forceUpdate }); this.logger.info('Scheduling events updates', { limit, forceUpdate });
try { try {
// Get symbols that need events updates // Get symbols that need events updates
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'events_update', { const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'events_update', {
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly
limit limit,
}); });
if (staleSymbols.length === 0) { if (staleSymbols.length === 0) {
@ -215,7 +225,7 @@ export async function scheduleEventsUpdates(
return { return {
message: 'No symbols need events updates', message: 'No symbols need events updates',
symbolsQueued: 0, symbolsQueued: 0,
errors: 0 errors: 0,
}; };
} }
@ -227,15 +237,19 @@ export async function scheduleEventsUpdates(
// Schedule individual update jobs for each symbol // Schedule individual update jobs for each symbol
for (const item of staleSymbols) { for (const item of staleSymbols) {
try { try {
await this.scheduleOperation('update-events', { await this.scheduleOperation(
symbol: item.symbol.symbol, 'update-events',
exchange: item.symbol.exchange, {
qmSearchCode: item.symbol.qmSearchCode symbol: item.symbol.symbol,
}, { exchange: item.symbol.exchange,
priority: 4, qmSearchCode: item.symbol.qmSearchCode,
delay: queued * 0.05 // 1.5 seconds between jobs },
}); {
priority: 4,
delay: queued * 0.05, // 1.5 seconds between jobs
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule events update for ${item.symbol.symbol}`, { error }); this.logger.error(`Failed to schedule events update for ${item.symbol.symbol}`, { error });
@ -246,16 +260,16 @@ export async function scheduleEventsUpdates(
this.logger.info('Events update scheduling completed', { this.logger.info('Events update scheduling completed', {
symbolsQueued: queued, symbolsQueued: queued,
errors, errors,
total: staleSymbols.length total: staleSymbols.length,
}); });
return { return {
message: `Scheduled events updates for ${queued} symbols`, message: `Scheduled events updates for ${queued} symbols`,
symbolsQueued: queued, symbolsQueued: queued,
errors errors,
}; };
} catch (error) { } catch (error) {
this.logger.error('Events scheduling failed', { error }); this.logger.error('Events scheduling failed', { error });
throw error; throw error;
} }
} }

View file

@ -1,3 +1,4 @@
import type { Document } from 'mongodb';
/** /**
* QM Filings Actions - Fetch and update SEC filings * QM Filings Actions - Fetch and update SEC filings
*/ */
@ -25,11 +26,14 @@ export async function updateFilings(
success: boolean; success: boolean;
symbol: string; symbol: string;
message: string; message: string;
data?: any; data?: unknown;
}> { }> {
const { qmSearchCode, page, symbol, exchange, lastRecordDate, totalPages } = input; const { qmSearchCode, page, symbol, exchange, lastRecordDate, totalPages } = input;
this.logger.info(`Fetching filings ${qmSearchCode} - ${page}/${totalPages}`, { qmSearchCode, page }); this.logger.info(`Fetching filings ${qmSearchCode} - ${page}/${totalPages}`, {
qmSearchCode,
page,
});
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger); await sessionManager.initialize(this.cache, this.logger);
@ -37,7 +41,7 @@ export async function updateFilings(
// Get a session - you'll need to add the appropriate session ID for filings // Get a session - you'll need to add the appropriate session ID for filings
const sessionId = QM_SESSION_IDS.LOOKUP; // TODO: Update with correct session ID const sessionId = QM_SESSION_IDS.LOOKUP; // TODO: Update with correct session ID
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM filings`); throw new Error(`No active session found for QM filings`);
} }
@ -52,12 +56,12 @@ export async function updateFilings(
// inclIxbrl: "true", // inclIxbrl: "true",
// inclXbrl: "true", // inclXbrl: "true",
// resultsPerPage: "25", // resultsPerPage: "25",
webmasterId: "500", webmasterId: '500',
token: session.headers['Datatool-Token'] || '', token: session.headers['Datatool-Token'] || '',
}); });
delete session?.headers?.["Datatool-Token"] delete session?.headers?.['Datatool-Token'];
const formData = new FormData(); const formData = new FormData();
formData.append('symbol', qmSearchCode); formData.append('symbol', qmSearchCode);
formData.append('inclXbrl', 'true'); formData.append('inclXbrl', 'true');
@ -68,11 +72,11 @@ export async function updateFilings(
formData.append('xbrlSubDoc', 'true'); formData.append('xbrlSubDoc', 'true');
// https://app.quotemedia.com/data/getCompanyFilings.json?page=1&webmasterId=500&symbol=AAPL&xbrlSubDoc=true&inclIxbrl=true&inclXbrl=true&resultsPerPage=25 // https://app.quotemedia.com/data/getCompanyFilings.json?page=1&webmasterId=500&symbol=AAPL&xbrlSubDoc=true&inclIxbrl=true&inclXbrl=true&resultsPerPage=25
// TODO: Update with correct filings endpoint // TODO: Update with correct filings endpoint
const apiUrl = `${QM_CONFIG.FILING_URL}?${searchParams.toString()}`; const apiUrl = `${QM_CONFIG.FILING_URL}?${searchParams.toString()}`;
console.log('Fetching filings from:', apiUrl, formData, session.headers); this.logger.debug('Fetching filings', { apiUrl });
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
@ -87,19 +91,26 @@ export async function updateFilings(
const filingsData = await response.json(); const filingsData = await response.json();
if( parseInt(filingsData.results.pagenumber) * filingsData.results.count >= filingsData.results.totalCount) { if (
await this.scheduleOperation('update-filings', { parseInt(filingsData.results.pagenumber) * filingsData.results.count >=
symbol: symbol, filingsData.results.totalCount
exchange: exchange, ) {
qmSearchCode: qmSearchCode, await this.scheduleOperation(
lastRecordDate: lastRecordDate || null, 'update-filings',
page: parseInt(filingsData.results.pagenumber) + 1, {
totalPages: (filingsData.results.totalCount / filingsData.results.count) + 1 symbol: symbol,
}, { exchange: exchange,
priority: 5, // Lower priority than financial data qmSearchCode: qmSearchCode,
}); lastRecordDate: lastRecordDate || null,
page: parseInt(filingsData.results.pagenumber) + 1,
totalPages: filingsData.results.totalCount / filingsData.results.count + 1,
},
{
priority: 5, // Lower priority than financial data
}
);
} }
// Update session success stats // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
@ -108,7 +119,7 @@ export async function updateFilings(
// Store filings in a separate collection // Store filings in a separate collection
await this.mongodb.batchUpsert( await this.mongodb.batchUpsert(
'qmFilings', 'qmFilings',
filingsData.results.filings.filing[0].map((filing: any) => ({ filingsData.results.filings.filing[0].map((filing: Document) => ({
...filing, ...filing,
symbol, symbol,
exchange, exchange,
@ -120,28 +131,28 @@ export async function updateFilings(
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', {
status: 'success', status: 'success',
lastRecordDate: new Date(), lastRecordDate: new Date(),
recordCount: filingsData.length recordCount: filingsData.length,
}); });
this.logger.info(`Filings updated successfully ${qmSearchCode} - ${page}/${totalPages}`, { this.logger.info(`Filings updated successfully ${qmSearchCode} - ${page}/${totalPages}`, {
qmSearchCode, qmSearchCode,
page, page,
totalPages, totalPages,
filingsCount: filingsData.length filingsCount: filingsData.length,
}); });
return { return {
success: true, success: true,
symbol, symbol,
message: `Filings updated for ${symbol}`, message: `Filings updated for ${symbol}`,
data: { count: filingsData.length } data: { count: filingsData.length },
}; };
} else { } else {
// Some symbols may not have filings (non-US companies, etc) // Some symbols may not have filings (non-US companies, etc)
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', {
status: 'success', status: 'success',
lastRecordDate: new Date(), lastRecordDate: new Date(),
recordCount: 0 recordCount: 0,
}); });
this.logger.info('No filings found for symbol', { symbol }); this.logger.info('No filings found for symbol', { symbol });
@ -149,30 +160,29 @@ export async function updateFilings(
success: true, success: true,
symbol, symbol,
message: `No filings found for ${symbol}`, message: `No filings found for ${symbol}`,
data: { count: 0 } data: { count: 0 },
}; };
} }
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error fetching filings', { this.logger.error('Error fetching filings', {
symbol, symbol,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
// Track failure // Track failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', {
status: 'failure' status: 'failure',
}); });
return { return {
success: false, success: false,
symbol, symbol,
message: `Failed to fetch filings: ${error instanceof Error ? error.message : 'Unknown error'}` message: `Failed to fetch filings: ${error instanceof Error ? error.message : 'Unknown error'}`,
}; };
} }
} }
@ -193,7 +203,7 @@ export async function scheduleFilingsUpdates(
errors: number; errors: number;
}> { }> {
const { limit = 1, forceUpdate = false } = input; const { limit = 1, forceUpdate = false } = input;
this.logger.info('Scheduling filings updates', { limit, forceUpdate }); this.logger.info('Scheduling filings updates', { limit, forceUpdate });
try { try {
@ -203,25 +213,29 @@ export async function scheduleFilingsUpdates(
// limit // limit
// }); // });
const staleSymbols = ['AAPL'] const staleSymbols = ['AAPL'];
if (staleSymbols.length === 0) { if (staleSymbols.length === 0) {
this.logger.info('No symbols need filings updates'); this.logger.info('No symbols need filings updates');
return { return {
message: 'No symbols need filings updates', message: 'No symbols need filings updates',
symbolsQueued: 0, symbolsQueued: 0,
errors: 0 errors: 0,
}; };
} }
this.logger.info(`Found ${staleSymbols.length} symbols needing filings updates`); this.logger.info(`Found ${staleSymbols.length} symbols needing filings updates`);
// Get full symbol data to include symbolId // Get full symbol data to include symbolId
const symbolDocs = await this.mongodb.find('qmSymbols', { const symbolDocs = await this.mongodb.find(
qmSearchCode: { $in: staleSymbols } 'qmSymbols',
}, { {
projection: { qmSearchCode: 1, operations: 1, symbol: 1, exchange: 1 } qmSearchCode: { $in: staleSymbols },
}); },
{
projection: { qmSearchCode: 1, operations: 1, symbol: 1, exchange: 1 },
}
);
let queued = 0; let queued = 0;
let errors = 0; let errors = 0;
@ -229,15 +243,19 @@ export async function scheduleFilingsUpdates(
// Schedule individual update jobs for each symbol // Schedule individual update jobs for each symbol
for (const doc of symbolDocs) { for (const doc of symbolDocs) {
try { try {
await this.scheduleOperation('update-filings', { await this.scheduleOperation(
symbol: doc.symbol, 'update-filings',
exchange: doc.exchange, {
qmSearchCode: doc.qmSearchCode, symbol: doc.symbol,
lastRecordDate: doc.operations?.filings_update?.lastRecordDate || null, exchange: doc.exchange,
}, { qmSearchCode: doc.qmSearchCode,
priority: 5, // Lower priority than financial data lastRecordDate: doc.operations?.filings_update?.lastRecordDate || null,
}); },
{
priority: 5, // Lower priority than financial data
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule filings update for ${doc.symbol}`, { error }); this.logger.error(`Failed to schedule filings update for ${doc.symbol}`, { error });
@ -248,16 +266,16 @@ export async function scheduleFilingsUpdates(
this.logger.info('Filings update scheduling completed', { this.logger.info('Filings update scheduling completed', {
symbolsQueued: queued, symbolsQueued: queued,
errors, errors,
total: staleSymbols.length total: staleSymbols.length,
}); });
return { return {
message: `Scheduled filings updates for ${queued} symbols`, message: `Scheduled filings updates for ${queued} symbols`,
symbolsQueued: queued, symbolsQueued: queued,
errors errors,
}; };
} catch (error) { } catch (error) {
this.logger.error('Filings scheduling failed', { error }); this.logger.error('Filings scheduling failed', { error });
throw error; throw error;
} }
} }

View file

@ -1,8 +1,10 @@
import type { Document } from 'mongodb';
/** /**
* QM Financials Actions - Fetch and update financial statements * QM Financials Actions - Fetch and update financial statements
*/ */
import type { ExecutionContext } from '@stock-bot/handlers'; import type { ExecutionContext } from '@stock-bot/handlers';
import { defined } from '@stock-bot/invariants';
import type { QMHandler } from '../qm.handler'; import type { QMHandler } from '../qm.handler';
import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager'; import { QMSessionManager } from '../shared/session-manager';
@ -24,10 +26,10 @@ export async function updateFinancials(
success: boolean; success: boolean;
qmSearchCode: string; qmSearchCode: string;
message: string; message: string;
data?: any; data?: unknown;
}> { }> {
const { symbol, exchange, qmSearchCode, reportType, lastRecordDate } = input; const { symbol, exchange, qmSearchCode, reportType, lastRecordDate } = input;
this.logger.info('Fetching financials', { symbol, exchange, qmSearchCode }); this.logger.info('Fetching financials', { symbol, exchange, qmSearchCode });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
@ -36,7 +38,7 @@ export async function updateFinancials(
// Get a session - you'll need to add the appropriate session ID for financials // Get a session - you'll need to add the appropriate session ID for financials
const sessionId = QM_SESSION_IDS.FINANCIALS; // TODO: Update with correct session ID const sessionId = QM_SESSION_IDS.FINANCIALS; // TODO: Update with correct session ID
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM financials`); throw new Error(`No active session found for QM financials`);
} }
@ -69,9 +71,10 @@ export async function updateFinancials(
const financialData = await response.json(); const financialData = await response.json();
let reports = []; let reports = [];
if(Array.isArray(financialData.results.Company)){ //WEIRD BUG ON THEIR END FOR SOME REASON FOR ONE COMP ITS A ARRAY INSTEAD OF OBJECT if (Array.isArray(financialData.results.Company)) {
//WEIRD BUG ON THEIR END FOR SOME REASON FOR ONE COMP ITS A ARRAY INSTEAD OF OBJECT
reports = financialData?.results?.Company[0].Report || []; reports = financialData?.results?.Company[0].Report || [];
}else{ } else {
reports = financialData?.results?.Company.Report || []; reports = financialData?.results?.Company.Report || [];
} }
@ -80,62 +83,74 @@ export async function updateFinancials(
// Store financial statements in a separate collection // Store financial statements in a separate collection
await this.mongodb.batchUpsert( await this.mongodb.batchUpsert(
'qmFinancials-new', 'qmFinancials-new',
reports.map((statement: any) => ({ reports.map((statement: Document) => ({
...statement, ...statement,
symbol, symbol,
exchange, exchange,
qmSearchCode qmSearchCode,
})), })),
['qmSearchCode', 'reportPeriod', 'reportDate'] // Unique keys ['qmSearchCode', 'reportPeriod', 'reportDate'] // Unique keys
); );
// Update symbol to track last financials update // Update symbol to track last financials update
await this.operationRegistry.updateOperation('qm', qmSearchCode, `financials_update_${reportType === 'Q'? 'quarterly' : 'annual'}`, { await this.operationRegistry.updateOperation(
status: 'success', 'qm',
lastRecordDate: new Date(),
recordCount: reports.length
});
this.logger.info(`Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`, {
qmSearchCode, qmSearchCode,
statementCount: reports.length `financials_update_${reportType === 'Q' ? 'quarterly' : 'annual'}`,
}); {
status: 'success',
lastRecordDate: new Date(),
recordCount: reports.length,
}
);
this.logger.info(
`Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`,
{
qmSearchCode,
statementCount: reports.length,
}
);
return { return {
success: true, success: true,
qmSearchCode, qmSearchCode,
message: `Financials updated for ${qmSearchCode} - ${reportType} - ${reports.length}`, message: `Financials updated for ${qmSearchCode} - ${reportType} - ${reports.length}`,
data: { count: reports.length } data: { count: reports.length },
}; };
} else { } else {
this.logger.warn('No financial data returned from API', { qmSearchCode }); this.logger.warn('No financial data returned from API', { qmSearchCode });
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `No financial data found for symbol ${qmSearchCode}` message: `No financial data found for symbol ${qmSearchCode}`,
}; };
} }
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error fetching financials', { this.logger.error('Error fetching financials', {
symbol, symbol,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
// Track failure // Track failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, `financials_update_${reportType === 'Q'? 'quarterly' : 'annual'}`, { await this.operationRegistry.updateOperation(
status: 'failure', 'qm',
}); qmSearchCode,
`financials_update_${reportType === 'Q' ? 'quarterly' : 'annual'}`,
{
status: 'failure',
}
);
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `Failed to fetch financials: ${error instanceof Error ? error.message : 'Unknown error'}` message: `Failed to fetch financials: ${error instanceof Error ? error.message : 'Unknown error'}`,
}; };
} }
} }
@ -156,51 +171,64 @@ export async function scheduleFinancialsUpdates(
errors: number; errors: number;
}> { }> {
const { limit = 100000, forceUpdate = false } = input; const { limit = 100000, forceUpdate = false } = input;
this.logger.info('Scheduling financials updates', { limit, forceUpdate }); this.logger.info('Scheduling financials updates', { limit, forceUpdate });
try { try {
// Get symbols that need updating for both quarterly and annual // Get symbols that need updating for both quarterly and annual
const staleSymbolsQ = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_quarterly', { const staleSymbolsQ = await this.operationRegistry.getStaleSymbols(
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default 'qm',
limit 'financials_update_quarterly',
}); {
const staleSymbolsA = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_annual', { minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default limit,
limit }
}); );
const staleSymbolsA = await this.operationRegistry.getStaleSymbols(
'qm',
'financials_update_annual',
{
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default
limit,
}
);
if (staleSymbolsQ.length === 0 && staleSymbolsA.length === 0) { if (staleSymbolsQ.length === 0 && staleSymbolsA.length === 0) {
this.logger.info('No symbols need financials updates'); this.logger.info('No symbols need financials updates');
return { return {
message: 'No symbols need financials updates', message: 'No symbols need financials updates',
symbolsQueued: 0, symbolsQueued: 0,
errors: 0 errors: 0,
}; };
} }
this.logger.info(`Found ${staleSymbolsQ.length} symbols needing quarterly updates and ${staleSymbolsA.length} symbols needing annual updates`); this.logger.info(
`Found ${staleSymbolsQ.length} symbols needing quarterly updates and ${staleSymbolsA.length} symbols needing annual updates`
);
// Create a map of symbols needing updates // Create a map of symbols needing updates
const symbolsNeedingUpdates = new Map<string, { quarterly: boolean, annual: boolean, item: any }>(); const symbolsNeedingUpdates = new Map<
string,
{ quarterly: boolean; annual: boolean; item: Document }
>();
// Add quarterly symbols // Add quarterly symbols
for (const item of staleSymbolsQ) { for (const item of staleSymbolsQ) {
const key = item.symbol.qmSearchCode; const key = item.symbol.qmSearchCode;
if (!symbolsNeedingUpdates.has(key)) { if (!symbolsNeedingUpdates.has(key)) {
symbolsNeedingUpdates.set(key, { quarterly: true, annual: false, item }); symbolsNeedingUpdates.set(key, { quarterly: true, annual: false, item });
} else { } else {
symbolsNeedingUpdates.get(key)!.quarterly = true; defined(symbolsNeedingUpdates.get(key)).quarterly = true;
} }
} }
// Add annual symbols // Add annual symbols
for (const item of staleSymbolsA) { for (const item of staleSymbolsA) {
const key = item.symbol.qmSearchCode; const key = item.symbol.qmSearchCode;
if (!symbolsNeedingUpdates.has(key)) { if (!symbolsNeedingUpdates.has(key)) {
symbolsNeedingUpdates.set(key, { quarterly: false, annual: true, item }); symbolsNeedingUpdates.set(key, { quarterly: false, annual: true, item });
} else { } else {
symbolsNeedingUpdates.get(key)!.annual = true; defined(symbolsNeedingUpdates.get(key)).annual = true;
} }
} }
@ -212,20 +240,26 @@ export async function scheduleFinancialsUpdates(
// Schedule quarterly updates if needed // Schedule quarterly updates if needed
if (quarterly) { if (quarterly) {
try { try {
await this.scheduleOperation('update-financials', { await this.scheduleOperation(
symbol: item.symbol.symbol, 'update-financials',
exchange: item.symbol.exchange, {
qmSearchCode: qmSearchCode, symbol: item.symbol.symbol,
reportType: 'Q', exchange: item.symbol.exchange,
lastRecordDate: item.operations?.financials_update_quarterly?.lastRecordDate, qmSearchCode: qmSearchCode,
}, { reportType: 'Q',
priority: 4, lastRecordDate: item.operations?.financials_update_quarterly?.lastRecordDate,
delay: queued // 1 second between jobs },
}); {
priority: 4,
delay: queued, // 1 second between jobs
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule quarterly financials update for ${qmSearchCode}`, { error }); this.logger.error(`Failed to schedule quarterly financials update for ${qmSearchCode}`, {
error,
});
errors++; errors++;
} }
} }
@ -233,20 +267,26 @@ export async function scheduleFinancialsUpdates(
// Schedule annual updates if needed // Schedule annual updates if needed
if (annual) { if (annual) {
try { try {
await this.scheduleOperation('update-financials', { await this.scheduleOperation(
symbol: item.symbol.symbol, 'update-financials',
exchange: item.symbol.exchange, {
qmSearchCode: qmSearchCode, symbol: item.symbol.symbol,
reportType: 'A', exchange: item.symbol.exchange,
lastRecordDate: item.operations?.financials_update_annual?.lastRecordDate, qmSearchCode: qmSearchCode,
}, { reportType: 'A',
priority: 4, lastRecordDate: item.operations?.financials_update_annual?.lastRecordDate,
delay: queued // 1 second between jobs },
}); {
priority: 4,
delay: queued, // 1 second between jobs
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule annual financials update for ${qmSearchCode}`, { error }); this.logger.error(`Failed to schedule annual financials update for ${qmSearchCode}`, {
error,
});
errors++; errors++;
} }
} }
@ -256,16 +296,16 @@ export async function scheduleFinancialsUpdates(
symbolsQueued: queued, symbolsQueued: queued,
errors, errors,
totalQuarterly: staleSymbolsQ.length, totalQuarterly: staleSymbolsQ.length,
totalAnnual: staleSymbolsA.length totalAnnual: staleSymbolsA.length,
}); });
return { return {
message: `Scheduled ${queued} financials updates (${staleSymbolsQ.length} quarterly, ${staleSymbolsA.length} annual)`, message: `Scheduled ${queued} financials updates (${staleSymbolsQ.length} quarterly, ${staleSymbolsA.length} annual)`,
symbolsQueued: queued, symbolsQueued: queued,
errors errors,
}; };
} catch (error) { } catch (error) {
this.logger.error('Financials scheduling failed', { error }); this.logger.error('Financials scheduling failed', { error });
throw error; throw error;
} }
} }

View file

@ -1,279 +1,284 @@
/** /**
* QM Insiders Actions - Fetch and update insider trading data * QM Insiders Actions - Fetch and update insider trading data
*/ */
import type { ExecutionContext } from '@stock-bot/handlers'; import type { ExecutionContext } from '@stock-bot/handlers';
import type { QMHandler } from '../qm.handler'; import type { QMHandler } from '../qm.handler';
import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager'; import { QMSessionManager } from '../shared/session-manager';
import type { QMInsiderTransaction } from '../shared/types';
/**
* Update insider transactions for a single symbol /**
*/ * Update insider transactions for a single symbol
export async function updateInsiders( */
this: QMHandler, export async function updateInsiders(
input: { this: QMHandler,
symbol: string; input: {
symbolId: number; symbol: string;
qmSearchCode: string; symbolId: number;
lookbackDays?: number; qmSearchCode: string;
}, lookbackDays?: number;
_context?: ExecutionContext },
): Promise<{ _context?: ExecutionContext
success: boolean; ): Promise<{
symbol: string; success: boolean;
message: string; symbol: string;
data?: any; message: string;
}> { data?: unknown;
const { symbol, symbolId, qmSearchCode, lookbackDays = 365 } = input; }> {
const { symbol, symbolId, qmSearchCode, lookbackDays = 365 } = input;
this.logger.info('Fetching insider transactions', { symbol, symbolId, lookbackDays });
this.logger.info('Fetching insider transactions', { symbol, symbolId, lookbackDays });
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger); const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
const sessionId = QM_SESSION_IDS.LOOKUP;
const session = await sessionManager.getSession(sessionId); const sessionId = QM_SESSION_IDS.LOOKUP;
const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM insiders`); if (!session || !session.uuid) {
} throw new Error(`No active session found for QM insiders`);
}
try {
// Calculate date range try {
const endDate = new Date(); // Calculate date range
const startDate = new Date(); const endDate = new Date();
startDate.setDate(startDate.getDate() - lookbackDays); const startDate = new Date();
startDate.setDate(startDate.getDate() - lookbackDays);
// Build API request for insider transactions
const searchParams = new URLSearchParams({ // Build API request for insider transactions
symbol: symbol, const searchParams = new URLSearchParams({
symbolId: symbolId.toString(), symbol: symbol,
qmodTool: 'InsiderActivity', symbolId: symbolId.toString(),
webmasterId: '500', qmodTool: 'InsiderActivity',
startDate: startDate.toISOString().split('T')[0], webmasterId: '500',
endDate: endDate.toISOString().split('T')[0], startDate: startDate.toISOString().split('T')[0],
includeOptions: 'true', endDate: endDate.toISOString().split('T')[0],
pageSize: '100' includeOptions: 'true',
} as Record<string, string>); pageSize: '100',
} as Record<string, string>);
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/insiders.json?${searchParams.toString()}`;
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/insiders.json?${searchParams.toString()}`;
const response = await fetch(apiUrl, {
method: 'GET', const response = await fetch(apiUrl, {
headers: session.headers, method: 'GET',
proxy: session.proxy, headers: session.headers,
}); proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); if (!response.ok) {
} throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const insiderData = await response.json();
const insiderData = (await response.json()) as { transactions?: QMInsiderTransaction[] };
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store insider data
if (insiderData && insiderData.transactions && insiderData.transactions.length > 0) { // Process and store insider data
const processedTransactions = insiderData.transactions.map((transaction: any) => ({ if (insiderData && insiderData.transactions && insiderData.transactions.length > 0) {
symbol, const processedTransactions = insiderData.transactions.map(transaction => ({
symbolId, source: 'qm',
transactionDate: new Date(transaction.transactionDate), symbol,
filingDate: new Date(transaction.filingDate), symbolId,
insiderName: transaction.insiderName, transactionDate: new Date(transaction.transactionDate),
insiderTitle: transaction.insiderTitle || 'Unknown', filingDate: new Date(transaction.filingDate),
transactionType: transaction.transactionType, insiderName: transaction.insiderName,
shares: parseFloat(transaction.shares) || 0, insiderTitle: transaction.insiderTitle || 'Unknown',
pricePerShare: parseFloat(transaction.pricePerShare) || 0, transactionType: transaction.transactionType,
totalValue: parseFloat(transaction.totalValue) || 0, shares: Number(transaction.shares) || 0,
sharesOwned: parseFloat(transaction.sharesOwned) || 0, pricePerShare: Number(transaction.pricePerShare) || 0,
ownershipType: transaction.ownershipType || 'Direct', totalValue: Number(transaction.totalValue) || 0,
formType: transaction.formType || 'Form 4', sharesOwned: Number(transaction.sharesOwned) || 0,
transactionCode: transaction.transactionCode, ownershipType: transaction.ownershipType || 'Direct',
updated_at: new Date() formType: transaction.formType || 'Form 4',
})); transactionCode: transaction.transactionCode,
updated_at: new Date(),
// Store in MongoDB }));
await this.mongodb.batchUpsert(
'qmInsiders', // Store in MongoDB
processedTransactions, await this.mongodb.batchUpsert(
['symbol', 'transactionDate', 'insiderName', 'transactionType'] // Unique keys 'qmInsiders',
); processedTransactions,
['symbol', 'transactionDate', 'insiderName', 'transactionType'] // Unique keys
// Calculate summary statistics );
const totalBuys = processedTransactions.filter((t: any) =>
t.transactionType === 'Buy' || t.transactionType === 'Purchase' // Calculate summary statistics
).length; const totalBuys = processedTransactions.filter(
t => t.transactionType === 'Buy' || t.transactionType === 'Purchase'
const totalSells = processedTransactions.filter((t: any) => ).length;
t.transactionType === 'Sell' || t.transactionType === 'Sale'
).length; const totalSells = processedTransactions.filter(
t => t.transactionType === 'Sell' || t.transactionType === 'Sale'
const totalBuyValue = processedTransactions ).length;
.filter((t: any) => t.transactionType === 'Buy' || t.transactionType === 'Purchase')
.reduce((sum: number, t: any) => sum + t.totalValue, 0); const totalBuyValue = processedTransactions
.filter(t => t.transactionType === 'Buy' || t.transactionType === 'Purchase')
const totalSellValue = processedTransactions .reduce((sum, t) => sum + t.totalValue, 0);
.filter((t: any) => t.transactionType === 'Sell' || t.transactionType === 'Sale')
.reduce((sum: number, t: any) => sum + t.totalValue, 0); const totalSellValue = processedTransactions
.filter(t => t.transactionType === 'Sell' || t.transactionType === 'Sale')
// Update operation tracking .reduce((sum, t) => sum + t.totalValue, 0);
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', {
status: 'success', // Update operation tracking
lastRecordDate: endDate, await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', {
recordCount: processedTransactions.length, status: 'success',
metadata: { lastRecordDate: endDate,
totalBuys, recordCount: processedTransactions.length,
totalSells, metadata: {
totalBuyValue, totalBuys,
totalSellValue, totalSells,
netValue: totalBuyValue - totalSellValue, totalBuyValue,
uniqueInsiders: new Set(processedTransactions.map((t: any) => t.insiderName)).size totalSellValue,
} netValue: totalBuyValue - totalSellValue,
}); uniqueInsiders: new Set(processedTransactions.map(t => t.insiderName)).size,
},
this.logger.info('Insider transactions updated successfully', { });
symbol,
transactionCount: processedTransactions.length, this.logger.info('Insider transactions updated successfully', {
totalBuys, symbol,
totalSells, transactionCount: processedTransactions.length,
netValue: totalBuyValue - totalSellValue totalBuys,
}); totalSells,
netValue: totalBuyValue - totalSellValue,
return { });
success: true,
symbol, return {
message: `Updated ${processedTransactions.length} insider transactions`, success: true,
data: { symbol,
count: processedTransactions.length, message: `Updated ${processedTransactions.length} insider transactions`,
totalBuys, data: {
totalSells, count: processedTransactions.length,
totalBuyValue, totalBuys,
totalSellValue, totalSells,
netValue: totalBuyValue - totalSellValue totalBuyValue,
} totalSellValue,
}; netValue: totalBuyValue - totalSellValue,
} else { },
// No insider data };
this.logger.info('No insider transactions found', { symbol }); } else {
// No insider data
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { this.logger.info('No insider transactions found', { symbol });
status: 'success',
lastRecordDate: endDate, await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', {
recordCount: 0 status: 'success',
}); lastRecordDate: endDate,
recordCount: 0,
return { });
success: true,
symbol, return {
message: 'No insider transactions found', success: true,
data: { count: 0 } symbol,
}; message: 'No insider transactions found',
} data: { count: 0 },
};
} catch (error) { }
// Update session failure stats } catch (error) {
if (session.uuid) { // Update session failure stats
await sessionManager.incrementFailedCalls(sessionId, session.uuid); if (session.uuid) {
} await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching insider transactions', {
symbol, this.logger.error('Error fetching insider transactions', {
error: error instanceof Error ? error.message : 'Unknown error' symbol,
}); error: error instanceof Error ? error.message : 'Unknown error',
});
// Update operation tracking for failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { // Update operation tracking for failure
status: 'failure', await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', {
error: error instanceof Error ? error.message : 'Unknown error' status: 'failure',
}); error: error instanceof Error ? error.message : 'Unknown error',
});
return {
success: false, return {
symbol, success: false,
message: `Failed to fetch insider transactions: ${error instanceof Error ? error.message : 'Unknown error'}` symbol,
}; message: `Failed to fetch insider transactions: ${error instanceof Error ? error.message : 'Unknown error'}`,
} };
} }
}
/**
* Schedule insider updates for symbols /**
*/ * Schedule insider updates for symbols
export async function scheduleInsidersUpdates( */
this: QMHandler, export async function scheduleInsidersUpdates(
input: { this: QMHandler,
limit?: number; input: {
minHoursSinceRun?: number; limit?: number;
forceUpdate?: boolean; minHoursSinceRun?: number;
} = {}, forceUpdate?: boolean;
_context?: ExecutionContext } = {},
): Promise<{ _context?: ExecutionContext
message: string; ): Promise<{
symbolsQueued: number; message: string;
errors: number; symbolsQueued: number;
}> { errors: number;
const { limit = 100, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; }> {
const { limit = 100, minHoursSinceRun = 24 * 7, forceUpdate = false } = input;
this.logger.info('Scheduling insider updates', { limit, minHoursSinceRun, forceUpdate });
this.logger.info('Scheduling insider updates', { limit, minHoursSinceRun, forceUpdate });
try {
// Get symbols that need insider updates try {
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'insiders_update', { // Get symbols that need insider updates
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'insiders_update', {
limit minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
}); limit,
});
if (staleSymbols.length === 0) {
this.logger.info('No symbols need insider updates'); if (staleSymbols.length === 0) {
return { this.logger.info('No symbols need insider updates');
message: 'No symbols need insider updates', return {
symbolsQueued: 0, message: 'No symbols need insider updates',
errors: 0 symbolsQueued: 0,
}; errors: 0,
} };
}
this.logger.info(`Found ${staleSymbols.length} symbols for insider updates`);
this.logger.info(`Found ${staleSymbols.length} symbols for insider updates`);
let symbolsQueued = 0;
let errors = 0; let symbolsQueued = 0;
let errors = 0;
// Schedule update jobs
for (const item of staleSymbols) { // Schedule update jobs
try { for (const item of staleSymbols) {
if (!item.symbol.symbolId) { try {
this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); if (!item.symbol.symbolId) {
continue; this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`);
} continue;
}
await this.scheduleOperation('update-insiders', {
symbol: item.symbol.symbol, await this.scheduleOperation(
symbolId: item.symbol.symbolId, 'update-insiders',
qmSearchCode: item.symbol.qmSearchCode {
}, { symbol: item.symbol.symbol,
priority: 5, // Medium priority symbolId: item.symbol.symbolId,
delay: symbolsQueued * 1000 // 1 second between jobs qmSearchCode: item.symbol.qmSearchCode,
}); },
{
symbolsQueued++; priority: 5, // Medium priority
} catch (error) { delay: symbolsQueued * 1000, // 1 second between jobs
this.logger.error(`Failed to schedule insider update for ${item.symbol.symbol}`, { error }); }
errors++; );
}
} symbolsQueued++;
} catch (error) {
this.logger.info('Insider update scheduling completed', { this.logger.error(`Failed to schedule insider update for ${item.symbol.symbol}`, { error });
symbolsQueued, errors++;
errors }
}); }
return { this.logger.info('Insider update scheduling completed', {
message: `Scheduled insider updates for ${symbolsQueued} symbols`, symbolsQueued,
symbolsQueued, errors,
errors });
};
} catch (error) { return {
this.logger.error('Insider scheduling failed', { error }); message: `Scheduled insider updates for ${symbolsQueued} symbols`,
throw error; symbolsQueued,
} errors,
} };
} catch (error) {
this.logger.error('Insider scheduling failed', { error });
throw error;
}
}

View file

@ -1,423 +1,425 @@
/** import type { Document } from 'mongodb';
* QM Intraday Crawl Actions - Sophisticated crawling with resumption support /**
*/ * QM Intraday Crawl Actions - Sophisticated crawling with resumption support
*/
import type { ExecutionContext } from '@stock-bot/handlers';
import type { CrawlState } from '../../../shared/operation-manager/types'; import type { ExecutionContext } from '@stock-bot/handlers';
import type { QMHandler } from '../qm.handler'; import type { OperationStatus } from '../../../shared/operation-manager/types';
import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; import type { QMHandler } from '../qm.handler';
import { QMSessionManager } from '../shared/session-manager'; import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';
interface IntradayCrawlInput {
symbol: string; interface IntradayCrawlInput {
exchange: string; symbol: string;
qmSearchCode: string; exchange: string;
targetOldestDate?: string; // ISO date string for how far back to crawl qmSearchCode: string;
existingCrawlState?: CrawlState; // Pass existing crawl state to avoid re-querying targetOldestDate?: string; // ISO date string for how far back to crawl
gaps?: { forward?: boolean; backward?: boolean }; // Pass gap information existingCrawlState?: Partial<OperationStatus>; // Pass existing crawl state to avoid re-querying
} gaps?: { forward?: boolean; backward?: boolean }; // Pass gap information
}
/** /**
* Main intraday crawl handler - crawls backwards week by week (Sunday to Sunday) * Main intraday crawl handler - crawls backwards week by week (Sunday to Sunday)
*/ */
export async function crawlIntradayData( export async function crawlIntradayData(
this: QMHandler, this: QMHandler,
input: IntradayCrawlInput, input: IntradayCrawlInput,
_context?: ExecutionContext _context?: ExecutionContext
): Promise<{ ): Promise<{
success: boolean; success: boolean;
symbol: string; symbol: string;
exchange: string; exchange: string;
qmSearchCode: string; qmSearchCode: string;
message: string; message: string;
data?: any; data?: unknown;
}> { }> {
const { const {
symbol, symbol,
exchange, exchange,
qmSearchCode, qmSearchCode,
targetOldestDate = '1960-01-01', // Default to ~5 years of data targetOldestDate = '1960-01-01', // Default to ~5 years of data
existingCrawlState, existingCrawlState,
gaps gaps,
} = input; } = input;
this.logger.info('Starting intraday crawl', { this.logger.info('Starting intraday crawl', {
symbol, symbol,
exchange, exchange,
targetOldestDate, targetOldestDate,
hasExistingState: !!existingCrawlState, hasExistingState: !!existingCrawlState,
gaps gaps,
}); });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger); await sessionManager.initialize(this.cache, this.logger);
const sessionId = QM_SESSION_IDS.PRICES; const sessionId = QM_SESSION_IDS.PRICES;
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM intraday`); throw new Error(`No active session found for QM intraday`);
} }
try { try {
// Use passed crawl state if available, otherwise query for it // Use passed crawl state if available, otherwise query for it
let currentCrawlState: CrawlState; let currentCrawlState: Partial<OperationStatus>;
if (existingCrawlState) { if (existingCrawlState) {
currentCrawlState = existingCrawlState; currentCrawlState = existingCrawlState;
} else { } else {
// Only query if not passed // Only query if not passed
const symbolData = await this.mongodb.findOne('qmSymbols', { const symbolData = await this.mongodb.findOne('qmSymbols', {
qmSearchCode qmSearchCode,
}); });
currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || { currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || {
finished: false finished: false,
}; };
} }
// Determine starting point for crawl // Determine starting point for crawl
let currentWeek: Date; let currentWeek: Date;
if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) { if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) {
// Start from oldest date reached // Start from oldest date reached
currentWeek = new Date(currentCrawlState.oldestDateReached); currentWeek = new Date(currentCrawlState.oldestDateReached);
} else if (currentCrawlState.lastProcessedDate) { } else if (currentCrawlState.lastProcessedDate) {
// Resume from last processed date // Resume from last processed date
currentWeek = new Date(currentCrawlState.lastProcessedDate); currentWeek = new Date(currentCrawlState.lastProcessedDate);
} else { } else {
// New crawl, start from today // New crawl, start from today
currentWeek = new Date(); currentWeek = new Date();
// console.log('Current week before adjustment:', currentWeek); // console.log('Current week before adjustment:', currentWeek);
} }
// Get the Sunday of the current week
// Get the Sunday of the current week currentWeek = getLastWeek(currentWeek);
currentWeek = getLastWeek(currentWeek);
const targetOldest = new Date(targetOldestDate);
const targetOldest = new Date(targetOldestDate); targetOldest.setHours(0, 0, 0, 0);
targetOldest.setHours(0, 0, 0, 0);
// Check if already finished
// Check if already finished if (currentCrawlState.finished || currentWeek <= targetOldest) {
if (currentCrawlState.finished || currentWeek <= targetOldest) { this.logger.info('Intraday crawl already complete', { symbol });
this.logger.info('Intraday crawl already complete', { symbol }); return {
return { success: true,
success: true, qmSearchCode,
qmSearchCode, symbol,
symbol, exchange,
exchange, message: 'Intraday crawl already complete',
message: 'Intraday crawl already complete' };
}; }
}
let totalRecords = 0;
let totalRecords = 0; let weeksProcessed = 0;
let weeksProcessed = 0; const errors: string[] = [];
const errors: string[] = [];
const endOfWeek = new Date(currentWeek);
const endOfWeek = new Date(currentWeek) endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday
endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday // Build API request for the week
// Build API request for the week const searchParams = new URLSearchParams({
const searchParams = new URLSearchParams({ adjType: 'none',
adjType:'none', adjusted: 'true',
adjusted:'true', freq: 'day',
freq:'day', interval: '1',
interval:'1', marketSession: 'mkt',
marketSession:'mkt', pathName: '/demo/portal/company-quotes.php',
pathName:'/demo/portal/company-quotes.php', qmodTool: 'InteractiveChart',
qmodTool:'InteractiveChart', start: currentWeek.toISOString().split('T')[0],
start: currentWeek.toISOString().split('T')[0], end: endOfWeek.toISOString().split('T')[0], // Next Sunday
end: endOfWeek.toISOString().split('T')[0], // Next Sunday symbol: qmSearchCode,
symbol: qmSearchCode, unadjusted: 'false',
unadjusted:'false', webmasterId: '500',
webmasterId:'500', zeroTradeDays: 'false',
zeroTradeDays:'false', } as Record<string, string>);
} as Record<string, string>);
try {
try { const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, {
const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, { method: 'GET',
method: 'GET', headers: session.headers,
headers: session.headers, proxy: session.proxy,
proxy: session.proxy, });
});
if (!response.ok) {
if (!response.ok) { throw new Error(`API request failed: ${response.status}`);
throw new Error(`API request failed: ${response.status}`); }
}
const barsResults = await response.json();
const barsResults = await response.json();
// Parse the results based on the API response structure
// Parse the results based on the API response structure const barsData = barsResults.results?.intraday?.[0]?.interval || null;
const barsData = barsResults.results?.intraday?.[0]?.interval || null; const barsLength = barsData !== null ? barsData.length : 0;
const barsLength = barsData !== null ? barsData.length : 0; this.logger.info(
this.logger.info(`Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`, { `Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`,
qmSearchCode, {
currentWeek, qmSearchCode,
records: barsLength currentWeek,
}); records: barsLength,
}
// Update session success stats );
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Update session success stats
// Process and store data if we got any await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
if (barsData !== null && barsLength > 0) {
const processedBars = barsData.map((bar: any) => ({ // Process and store data if we got any
...bar, if (barsData !== null && barsLength > 0) {
qmSearchCode, const processedBars = barsData.map((bar: Document) => ({
symbol, ...bar,
exchange, qmSearchCode,
timestamp: new Date(bar.startdatetime || bar.date || bar.datetime), symbol,
})); exchange,
timestamp: new Date(bar.startdatetime || bar.date || bar.datetime),
await this.mongodb.batchUpsert( }));
'qmIntraday',
processedBars, await this.mongodb.batchUpsert('qmIntraday', processedBars, ['qmSearchCode', 'timestamp']);
['qmSearchCode', 'timestamp']
); totalRecords += barsLength;
}
totalRecords += barsLength;
} weeksProcessed = 1;
const nextWeek = getLastWeek(new Date(currentWeek));
weeksProcessed = 1; const finished = barsData === null && nextWeek < new Date('2024-01-01');
const nextWeek = getLastWeek(new Date(currentWeek)); await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
const finished = (barsData === null) && nextWeek < new Date('2024-01-01') status: 'success',
this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { finished,
status: 'success', oldestDateReached: currentCrawlState.oldestDateReached,
crawlState: { lastProcessedDate: currentWeek,
finished: finished, });
oldestDateReached: currentCrawlState.oldestDateReached,
lastProcessedDate: currentWeek // Calculate next week to process (previous Sunday)
}
}); // console.log(barsData === null , existingCrawlState);
if (!finished) {
// Calculate next week to process (previous Sunday) currentCrawlState.lastProcessedDate = nextWeek;
await this.scheduleOperation(
// console.log(barsData === null , existingCrawlState); 'crawl-intraday-data',
if(!finished) { {
currentCrawlState.lastProcessedDate = nextWeek; symbol: symbol,
await this.scheduleOperation('crawl-intraday-data', { exchange: exchange,
symbol: symbol, qmSearchCode: qmSearchCode,
exchange: exchange, targetOldestDate,
qmSearchCode: qmSearchCode, // Pass existing crawl state and gaps to avoid re-querying
targetOldestDate, existingCrawlState: currentCrawlState,
// Pass existing crawl state and gaps to avoid re-querying gaps: gaps,
existingCrawlState: currentCrawlState, },
gaps: gaps {
}, { priority: 4, // Standard priority for backward crawls
priority: 4, // Standard priority for backward crawls }
}); );
} }
return { return {
success: true, success: true,
symbol, symbol,
exchange, exchange,
qmSearchCode, qmSearchCode,
message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`, message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`,
data: { data: {
totalRecords, totalRecords,
weeksProcessed, weeksProcessed,
nextWeek: nextWeek.toISOString().split('T')[0], nextWeek: nextWeek.toISOString().split('T')[0],
errors: errors.length > 0 ? errors : undefined errors: errors.length > 0 ? errors : undefined,
} },
} };
} catch (error) {
} catch (error) { this.logger.error('Intraday crawl failed', {
this.logger.error('Intraday crawl failed', { symbol,
symbol, error: error instanceof Error ? error.message : 'Unknown error',
error: error instanceof Error ? error.message : 'Unknown error' });
});
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { status: 'failure',
status: 'failure', error: error instanceof Error ? error.message : 'Unknown error',
error: error instanceof Error ? error.message : 'Unknown error' });
});
return {
return { success: false,
success: false, symbol,
symbol, exchange,
exchange, qmSearchCode,
qmSearchCode, message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}` };
}; }
} } catch (error) {
}catch (error) { return {
return { success: false,
success: false, symbol,
symbol, exchange,
exchange, qmSearchCode,
qmSearchCode, message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}` };
}; }
} }
}
/**
/** * Schedule intraday crawls for multiple symbols
* Schedule intraday crawls for multiple symbols */
*/ export async function scheduleIntradayCrawls(
export async function scheduleIntradayCrawls( this: QMHandler,
this: QMHandler, input: {
input: { limit?: number;
limit?: number; targetOldestDate?: string;
targetOldestDate?: string; priorityMode?: 'never_run' | 'incomplete' | 'all';
priorityMode?: 'never_run' | 'incomplete' | 'all'; } = {},
} = {}, _context?: ExecutionContext
_context?: ExecutionContext ): Promise<{
): Promise<{ message: string;
message: string; symbolsQueued: number;
symbolsQueued: number; errors: number;
errors: number; }> {
}> { const { limit = 999999999, targetOldestDate = '1960-01-01', priorityMode = 'all' } = input;
const {
limit = 999999999, this.logger.info('Scheduling intraday crawls', {
targetOldestDate = '1960-01-01', limit,
priorityMode = 'all' targetOldestDate,
} = input; priorityMode,
});
this.logger.info('Scheduling intraday crawls', {
limit, try {
targetOldestDate, // Get symbols based on priority mode
priorityMode let symbolsToProcess: Document[] = [];
}); const tracker = this.operationRegistry.getTracker('qm');
try { switch (priorityMode) {
// Get symbols based on priority mode case 'never_run':
let symbolsToProcess: any[] = []; // Get symbols that have never been crawled
const tracker = this.operationRegistry.getTracker('qm'); symbolsToProcess = await this.mongodb.find(
'qmSymbols',
switch (priorityMode) { {
case 'never_run': 'operations.intraday_bars': { $exists: false },
// Get symbols that have never been crawled active: { $ne: false },
symbolsToProcess = await this.mongodb.find('qmSymbols', { },
'operations.intraday_bars': { $exists: false }, {
active: { $ne: false } limit,
}, { projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 },
limit, }
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 } );
}); break;
break;
case 'incomplete':
case 'incomplete': // Get symbols with incomplete crawls
// Get symbols with incomplete crawls symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl( limit,
'intraday_bars', targetOldestDate: new Date(targetOldestDate),
{ includeNewDataGaps: false, // Only backward gaps
limit, // symbolFilter: { symbol: 'ETU' } // Filter for testing
targetOldestDate: new Date(targetOldestDate), });
includeNewDataGaps: false, // Only backward gaps break;
// symbolFilter: { symbol: 'ETU' } // Filter for testing
} case 'all':
); default:
break; // Get all symbols that need any processing
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit,
case 'all': targetOldestDate: new Date(targetOldestDate),
default: includeNewDataGaps: false, // Only backward gaps since we removed forward crawling
// Get all symbols that need any processing // symbolFilter: { symbol: 'AAPL' } // Filter for testing
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl( });
'intraday_bars', break;
{ }
limit,
targetOldestDate: new Date(targetOldestDate), if (symbolsToProcess.length === 0) {
includeNewDataGaps: false, // Only backward gaps since we removed forward crawling return {
// symbolFilter: { symbol: 'AAPL' } // Filter for testing message: `No symbols found for priority mode: ${priorityMode}`,
} symbolsQueued: 0,
); errors: 0,
break; };
} }
if (symbolsToProcess.length === 0) { this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', {
return { count: symbolsToProcess.length,
message: `No symbols found for priority mode: ${priorityMode}`, firstSymbol: symbolsToProcess[0]
symbolsQueued: 0, ? {
errors: 0 symbol: symbolsToProcess[0].symbol,
}; gaps: symbolsToProcess[0].gaps,
} hasOperationStatus: !!symbolsToProcess[0].operationStatus,
crawlState: symbolsToProcess[0].operationStatus?.crawlState,
this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', { }
count: symbolsToProcess.length, : null,
firstSymbol: symbolsToProcess[0] ? { });
symbol: symbolsToProcess[0].symbol,
gaps: symbolsToProcess[0].gaps, // Get full symbol data if needed
hasOperationStatus: !!symbolsToProcess[0].operationStatus, if (priorityMode !== 'never_run') {
crawlState: symbolsToProcess[0].operationStatus?.crawlState const qmSearchCodes = symbolsToProcess.map(s => s.symbol);
} : null const fullSymbols = await this.mongodb.find(
}); 'qmSymbols',
{
// Get full symbol data if needed qmSearchCode: { $in: qmSearchCodes },
if (priorityMode !== 'never_run') { },
const qmSearchCodes = symbolsToProcess.map(s => s.symbol); {
const fullSymbols = await this.mongodb.find('qmSymbols', { projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 },
qmSearchCode: { $in: qmSearchCodes } }
}, { );
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 }
}); // Map back the full data while preserving gaps and operation status
symbolsToProcess = symbolsToProcess.map(sp => {
// Map back the full data while preserving gaps and operation status const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol);
symbolsToProcess = symbolsToProcess.map(sp => { if (full) {
const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol); return {
if (full) { ...full,
return { gaps: sp.gaps, // Preserve gap information
...full, operationStatus: sp.operationStatus, // Preserve original operation status
gaps: sp.gaps, // Preserve gap information };
operationStatus: sp.operationStatus // Preserve original operation status }
}; return sp;
} });
return sp; }
});
} this.logger.info('After mapping, symbols to process', {
count: symbolsToProcess.length,
this.logger.info('After mapping, symbols to process', { firstSymbol: symbolsToProcess[0]
count: symbolsToProcess.length, ? {
firstSymbol: symbolsToProcess[0] ? { symbol: symbolsToProcess[0].symbol,
symbol: symbolsToProcess[0].symbol, exchange: symbolsToProcess[0].exchange,
exchange: symbolsToProcess[0].exchange, qmSearchCode: symbolsToProcess[0].qmSearchCode,
qmSearchCode: symbolsToProcess[0].qmSearchCode, gaps: symbolsToProcess[0].gaps,
gaps: symbolsToProcess[0].gaps, hasOperationStatus: !!symbolsToProcess[0].operationStatus,
hasOperationStatus: !!symbolsToProcess[0].operationStatus, crawlState: symbolsToProcess[0].operationStatus?.crawlState,
crawlState: symbolsToProcess[0].operationStatus?.crawlState }
} : null : null,
}); });
let symbolsQueued = 0; let symbolsQueued = 0;
let errors = 0; let errors = 0;
// Schedule crawl jobs
// Schedule crawl jobs for (const doc of symbolsToProcess) {
for (const doc of symbolsToProcess) { try {
try { await this.scheduleOperation(
await this.scheduleOperation('crawl-intraday-data', { 'crawl-intraday-data',
symbol: doc.symbol, {
exchange: doc.exchange, symbol: doc.symbol,
qmSearchCode: doc.qmSearchCode, exchange: doc.exchange,
targetOldestDate, qmSearchCode: doc.qmSearchCode,
// Pass existing crawl state and gaps to avoid re-querying targetOldestDate,
existingCrawlState: doc.operationStatus?.crawlState, // Pass existing crawl state and gaps to avoid re-querying
gaps: doc.gaps existingCrawlState: doc.operationStatus?.crawlState,
}, { gaps: doc.gaps,
priority: 6, // Standard priority for backward crawls },
}); {
priority: 6, // Standard priority for backward crawls
symbolsQueued++; }
} catch (error) { );
this.logger.error(`Failed to schedule intraday crawl for ${doc.symbol}`, { error });
errors++; symbolsQueued++;
} } catch (error) {
} this.logger.error(`Failed to schedule intraday crawl for ${doc.symbol}`, { error });
errors++;
this.logger.info('Intraday crawl scheduling completed', { }
priorityMode, }
symbolsQueued,
errors this.logger.info('Intraday crawl scheduling completed', {
}); priorityMode,
symbolsQueued,
return { errors,
message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`, });
symbolsQueued,
errors return {
}; message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`,
symbolsQueued,
} catch (error) { errors,
this.logger.error('Intraday crawl scheduling failed', { error }); };
throw error; } catch (error) {
} this.logger.error('Intraday crawl scheduling failed', { error });
} throw error;
}
}

View file

@ -1,441 +1,438 @@
/** /**
* QM News Actions - Fetch symbol-specific and general market news * QM News Actions - Fetch symbol-specific and general market news
*/ */
import type { ExecutionContext } from '@stock-bot/handlers'; import type { ExecutionContext } from '@stock-bot/handlers';
import type { QMHandler } from '../qm.handler'; import type { QMHandler } from '../qm.handler';
import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager'; import { QMSessionManager } from '../shared/session-manager';
import type { QMNewsArticle } from '../shared/types';
interface NewsArticle {
id: string; /**
publishedDate: Date; * Update news for a single symbol
title: string; */
summary: string; export async function updateSymbolNews(
source: string; this: QMHandler,
url: string; input: {
symbols?: string[]; symbol: string;
categories?: string[]; symbolId: number;
sentiment?: { qmSearchCode: string;
score: number; lookbackDays?: number;
label: string; // positive, negative, neutral },
}; _context?: ExecutionContext
imageUrl?: string; ): Promise<{
} success: boolean;
symbol: string;
/** message: string;
* Update news for a single symbol data?: unknown;
*/ }> {
export async function updateSymbolNews( const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input;
this: QMHandler,
input: { this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays });
symbol: string;
symbolId: number; const sessionManager = QMSessionManager.getInstance();
qmSearchCode: string; await sessionManager.initialize(this.cache, this.logger);
lookbackDays?: number;
}, const sessionId = QM_SESSION_IDS.LOOKUP;
_context?: ExecutionContext const session = await sessionManager.getSession(sessionId);
): Promise<{
success: boolean; if (!session || !session.uuid) {
symbol: string; throw new Error(`No active session found for QM news`);
message: string; }
data?: any;
}> { try {
const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input; // Calculate date range
const endDate = new Date();
this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays }); const startDate = new Date();
startDate.setDate(startDate.getDate() - lookbackDays);
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger); // Build API request for symbol news
const searchParams = new URLSearchParams({
const sessionId = QM_SESSION_IDS.LOOKUP; symbol: symbol,
const session = await sessionManager.getSession(sessionId); symbolId: symbolId.toString(),
qmodTool: 'News',
if (!session || !session.uuid) { webmasterId: '500',
throw new Error(`No active session found for QM news`); startDate: startDate.toISOString().split('T')[0],
} endDate: endDate.toISOString().split('T')[0],
includeContent: 'true',
try { pageSize: '50',
// Calculate date range } as Record<string, string>);
const endDate = new Date();
const startDate = new Date(); const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`;
startDate.setDate(startDate.getDate() - lookbackDays);
const response = await fetch(apiUrl, {
// Build API request for symbol news method: 'GET',
const searchParams = new URLSearchParams({ headers: session.headers,
symbol: symbol, proxy: session.proxy,
symbolId: symbolId.toString(), });
qmodTool: 'News',
webmasterId: '500', if (!response.ok) {
startDate: startDate.toISOString().split('T')[0], throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
endDate: endDate.toISOString().split('T')[0], }
includeContent: 'true',
pageSize: '50' const newsData = (await response.json()) as { articles?: QMNewsArticle[] };
} as Record<string, string>);
// Update session success stats
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`; await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
const response = await fetch(apiUrl, { // Process and store news data
method: 'GET', if (newsData && newsData.articles && newsData.articles.length > 0) {
headers: session.headers, const processedArticles = newsData.articles.map(article => ({
proxy: session.proxy, articleId:
}); article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`,
symbol,
if (!response.ok) { symbolId,
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); publishedDate: new Date(article.publishedDate),
} title: article.title,
summary: article.summary || article.content?.substring(0, 500),
const newsData = await response.json(); source: article.source || 'Unknown',
url: article.url,
// Update session success stats symbols: article.symbols || [symbol],
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); categories: article.categories || [],
sentiment: article.sentiment
// Process and store news data ? {
if (newsData && newsData.articles && newsData.articles.length > 0) { score: Number(article.sentiment.score) || 0,
const processedArticles = newsData.articles.map((article: any) => ({ label: article.sentiment.label || 'neutral',
articleId: article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`, }
symbol, : null,
symbolId, imageUrl: article.imageUrl,
publishedDate: new Date(article.publishedDate), isSymbolSpecific: true,
title: article.title, updated_at: new Date(),
summary: article.summary || article.content?.substring(0, 500), }));
source: article.source || 'Unknown',
url: article.url, // Store in MongoDB
symbols: article.symbols || [symbol], await this.mongodb.batchUpsert(
categories: article.categories || [], 'qmNews',
sentiment: article.sentiment ? { processedArticles,
score: parseFloat(article.sentiment.score) || 0, ['articleId'] // Unique key
label: article.sentiment.label || 'neutral' );
} : null,
imageUrl: article.imageUrl, // Calculate sentiment summary
isSymbolSpecific: true, const sentimentCounts = processedArticles.reduce<Record<string, number>>((acc, article) => {
updated_at: new Date() if (article.sentiment) {
})); acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1;
}
// Store in MongoDB return acc;
await this.mongodb.batchUpsert( }, {});
'qmNews',
processedArticles, // Update operation tracking
['articleId'] // Unique key await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
); status: 'success',
lastRecordDate: endDate,
// Calculate sentiment summary recordCount: processedArticles.length,
const sentimentCounts = processedArticles.reduce((acc: any, article: any) => { metadata: {
if (article.sentiment) { sentimentCounts,
acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1; uniqueSources: new Set(processedArticles.map(a => a.source)).size,
} avgSentimentScore: processedArticles
return acc; .filter(a => a.sentiment?.score)
}, {}); .reduce(
(sum, a, i, arr) =>
// Update operation tracking i === arr.length - 1
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { ? (sum + (a.sentiment?.score ?? 0)) / arr.length
status: 'success', : sum + (a.sentiment?.score ?? 0),
lastRecordDate: endDate, 0
recordCount: processedArticles.length, ),
metadata: { },
sentimentCounts, });
uniqueSources: new Set(processedArticles.map((a: any) => a.source)).size,
avgSentimentScore: processedArticles this.logger.info('Symbol news updated successfully', {
.filter((a: any) => a.sentiment?.score) symbol,
.reduce((sum: number, a: any, i: number, arr: any[]) => articleCount: processedArticles.length,
i === arr.length - 1 ? (sum + a.sentiment.score) / arr.length : sum + a.sentiment.score, 0 sentimentCounts,
) });
}
}); return {
success: true,
this.logger.info('Symbol news updated successfully', { symbol,
symbol, message: `Updated ${processedArticles.length} news articles`,
articleCount: processedArticles.length, data: {
sentimentCounts count: processedArticles.length,
}); sentimentCounts,
sources: new Set(processedArticles.map(a => a.source)).size,
return { },
success: true, };
symbol, } else {
message: `Updated ${processedArticles.length} news articles`, // No news found
data: { this.logger.info('No news articles found', { symbol });
count: processedArticles.length,
sentimentCounts, await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
sources: new Set(processedArticles.map((a: any) => a.source)).size status: 'success',
} lastRecordDate: endDate,
}; recordCount: 0,
} else { });
// No news found
this.logger.info('No news articles found', { symbol }); return {
success: true,
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { symbol,
status: 'success', message: 'No news articles found',
lastRecordDate: endDate, data: { count: 0 },
recordCount: 0 };
}); }
} catch (error) {
return { // Update session failure stats
success: true, if (session.uuid) {
symbol, await sessionManager.incrementFailedCalls(sessionId, session.uuid);
message: 'No news articles found', }
data: { count: 0 }
}; this.logger.error('Error fetching symbol news', {
} symbol,
error: error instanceof Error ? error.message : 'Unknown error',
} catch (error) { });
// Update session failure stats
if (session.uuid) { // Update operation tracking for failure
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
} status: 'failure',
error: error instanceof Error ? error.message : 'Unknown error',
this.logger.error('Error fetching symbol news', { });
symbol,
error: error instanceof Error ? error.message : 'Unknown error' return {
}); success: false,
symbol,
// Update operation tracking for failure message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`,
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { };
status: 'failure', }
error: error instanceof Error ? error.message : 'Unknown error' }
});
/**
return { * Update general market news
success: false, */
symbol, export async function updateGeneralNews(
message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}` this: QMHandler,
}; input: {
} categories?: string[];
} lookbackMinutes?: number;
} = {},
/** _context?: ExecutionContext
* Update general market news ): Promise<{
*/ success: boolean;
export async function updateGeneralNews( message: string;
this: QMHandler, data?: unknown;
input: { }> {
categories?: string[]; const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input;
lookbackMinutes?: number;
} = {}, this.logger.info('Fetching general news', { categories, lookbackMinutes });
_context?: ExecutionContext
): Promise<{ const sessionManager = QMSessionManager.getInstance();
success: boolean; await sessionManager.initialize(this.cache, this.logger);
message: string;
data?: any; const sessionId = QM_SESSION_IDS.LOOKUP;
}> { const session = await sessionManager.getSession(sessionId);
const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input;
if (!session || !session.uuid) {
this.logger.info('Fetching general news', { categories, lookbackMinutes }); throw new Error(`No active session found for QM general news`);
}
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger); try {
// Calculate time range
const sessionId = QM_SESSION_IDS.LOOKUP; const endDate = new Date();
const session = await sessionManager.getSession(sessionId); const startDate = new Date();
startDate.setMinutes(startDate.getMinutes() - lookbackMinutes);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM general news`); // Build API request for general news
} const searchParams = new URLSearchParams({
qmodTool: 'MarketNews',
try { webmasterId: '500',
// Calculate time range categories: categories.join(','),
const endDate = new Date(); startDateTime: startDate.toISOString(),
const startDate = new Date(); endDateTime: endDate.toISOString(),
startDate.setMinutes(startDate.getMinutes() - lookbackMinutes); includeContent: 'true',
pageSize: '100',
// Build API request for general news } as Record<string, string>);
const searchParams = new URLSearchParams({
qmodTool: 'MarketNews', const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`;
webmasterId: '500',
categories: categories.join(','), const response = await fetch(apiUrl, {
startDateTime: startDate.toISOString(), method: 'GET',
endDateTime: endDate.toISOString(), headers: session.headers,
includeContent: 'true', proxy: session.proxy,
pageSize: '100' });
} as Record<string, string>);
if (!response.ok) {
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`; throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const response = await fetch(apiUrl, {
method: 'GET', const newsData = (await response.json()) as { articles?: QMNewsArticle[] };
headers: session.headers,
proxy: session.proxy, // Update session success stats
}); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
if (!response.ok) { // Process and store general news
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); if (newsData && newsData.articles && newsData.articles.length > 0) {
} const processedArticles = newsData.articles.map(article => ({
articleId:
const newsData = await response.json(); article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`,
publishedDate: new Date(article.publishedDate),
// Update session success stats title: article.title,
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); summary: article.summary || article.content?.substring(0, 500),
source: article.source || 'Unknown',
// Process and store general news url: article.url,
if (newsData && newsData.articles && newsData.articles.length > 0) { symbols: article.symbols || [],
const processedArticles = newsData.articles.map((article: any) => ({ categories: article.categories || categories,
articleId: article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`, sentiment: article.sentiment
publishedDate: new Date(article.publishedDate), ? {
title: article.title, score: Number(article.sentiment.score) || 0,
summary: article.summary || article.content?.substring(0, 500), label: article.sentiment.label || 'neutral',
source: article.source || 'Unknown', }
url: article.url, : null,
symbols: article.symbols || [], imageUrl: article.imageUrl,
categories: article.categories || categories, isSymbolSpecific: false,
sentiment: article.sentiment ? { isMarketMoving: article.isMarketMoving || false,
score: parseFloat(article.sentiment.score) || 0, importance: article.importance || 'medium',
label: article.sentiment.label || 'neutral' updated_at: new Date(),
} : null, }));
imageUrl: article.imageUrl,
isSymbolSpecific: false, // Store in MongoDB
isMarketMoving: article.isMarketMoving || false, await this.mongodb.batchUpsert(
importance: article.importance || 'medium', 'qmNews',
updated_at: new Date() processedArticles,
})); ['articleId'] // Unique key
);
// Store in MongoDB
await this.mongodb.batchUpsert( // Find high-importance articles
'qmNews', const highImportanceCount = processedArticles.filter(
processedArticles, a => a.importance === 'high' || a.isMarketMoving
['articleId'] // Unique key ).length;
);
// Update a general tracking document
// Find high-importance articles await this.mongodb.updateOne(
const highImportanceCount = processedArticles.filter((a: any) => 'qmOperationStats',
a.importance === 'high' || a.isMarketMoving { operation: 'general_news_update' },
).length; {
$set: {
// Update a general tracking document lastRunAt: new Date(),
await this.mongodb.updateOne( lastRecordCount: processedArticles.length,
'qmOperationStats', highImportanceCount,
{ operation: 'general_news_update' }, categories,
{ updated_at: new Date(),
$set: { },
lastRunAt: new Date(), },
lastRecordCount: processedArticles.length, { upsert: true }
highImportanceCount, );
categories,
updated_at: new Date() this.logger.info('General news updated successfully', {
} articleCount: processedArticles.length,
}, highImportanceCount,
{ upsert: true } categories,
); });
this.logger.info('General news updated successfully', { return {
articleCount: processedArticles.length, success: true,
highImportanceCount, message: `Updated ${processedArticles.length} general news articles`,
categories data: {
}); count: processedArticles.length,
highImportanceCount,
return { categories,
success: true, sources: new Set(processedArticles.map(a => a.source)).size,
message: `Updated ${processedArticles.length} general news articles`, },
data: { };
count: processedArticles.length, } else {
highImportanceCount, // No news found
categories, this.logger.info('No general news articles found');
sources: new Set(processedArticles.map((a: any) => a.source)).size
} return {
}; success: true,
} else { message: 'No general news articles found',
// No news found data: { count: 0 },
this.logger.info('No general news articles found'); };
}
return { } catch (error) {
success: true, // Update session failure stats
message: 'No general news articles found', if (session.uuid) {
data: { count: 0 } await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}; }
}
this.logger.error('Error fetching general news', {
} catch (error) { error: error instanceof Error ? error.message : 'Unknown error',
// Update session failure stats });
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); return {
} success: false,
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`,
this.logger.error('Error fetching general news', { };
error: error instanceof Error ? error.message : 'Unknown error' }
}); }
return { /**
success: false, * Schedule symbol news updates
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}` */
}; export async function scheduleSymbolNewsUpdates(
} this: QMHandler,
} input: {
limit?: number;
/** minHoursSinceRun?: number;
* Schedule symbol news updates forceUpdate?: boolean;
*/ } = {},
export async function scheduleSymbolNewsUpdates( _context?: ExecutionContext
this: QMHandler, ): Promise<{
input: { message: string;
limit?: number; symbolsQueued: number;
minHoursSinceRun?: number; errors: number;
forceUpdate?: boolean; }> {
} = {}, const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input;
_context?: ExecutionContext
): Promise<{ this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate });
message: string;
symbolsQueued: number; try {
errors: number; // Get symbols that need news updates
}> { const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', {
const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
limit,
this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate }); });
try { if (staleSymbols.length === 0) {
// Get symbols that need news updates this.logger.info('No symbols need news updates');
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', { return {
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, message: 'No symbols need news updates',
limit symbolsQueued: 0,
}); errors: 0,
};
if (staleSymbols.length === 0) { }
this.logger.info('No symbols need news updates');
return { this.logger.info(`Found ${staleSymbols.length} symbols for news updates`);
message: 'No symbols need news updates',
symbolsQueued: 0, let symbolsQueued = 0;
errors: 0 let errors = 0;
};
} // Schedule update jobs
for (const item of staleSymbols) {
this.logger.info(`Found ${staleSymbols.length} symbols for news updates`); try {
if (!item.symbol.symbolId) {
let symbolsQueued = 0; this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`);
let errors = 0; continue;
}
// Schedule update jobs
for (const item of staleSymbols) { await this.scheduleOperation(
try { 'update-symbol-news',
if (!item.symbol.symbolId) { {
this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); symbol: item.symbol.symbol,
continue; symbolId: item.symbol.symbolId,
} qmSearchCode: item.symbol.qmSearchCode,
},
await this.scheduleOperation('update-symbol-news', { {
symbol: item.symbol.symbol, priority: 4, // Lower priority than price data
symbolId: item.symbol.symbolId, delay: symbolsQueued * 500, // 0.5 seconds between jobs
qmSearchCode: item.symbol.qmSearchCode }
}, { );
priority: 4, // Lower priority than price data
delay: symbolsQueued * 500 // 0.5 seconds between jobs symbolsQueued++;
}); } catch (error) {
this.logger.error(`Failed to schedule news update for ${item.symbol.symbol}`, { error });
symbolsQueued++; errors++;
} catch (error) { }
this.logger.error(`Failed to schedule news update for ${item.symbol.symbol}`, { error }); }
errors++;
} this.logger.info('Symbol news update scheduling completed', {
} symbolsQueued,
errors,
this.logger.info('Symbol news update scheduling completed', { });
symbolsQueued,
errors return {
}); message: `Scheduled news updates for ${symbolsQueued} symbols`,
symbolsQueued,
return { errors,
message: `Scheduled news updates for ${symbolsQueued} symbols`, };
symbolsQueued, } catch (error) {
errors this.logger.error('Symbol news scheduling failed', { error });
}; throw error;
} catch (error) { }
this.logger.error('Symbol news scheduling failed', { error }); }
throw error;
}
}

View file

@ -1,3 +1,4 @@
import type { Document } from 'mongodb';
/** /**
* QM Prices Actions - Fetch and update daily price data * QM Prices Actions - Fetch and update daily price data
*/ */
@ -23,10 +24,10 @@ export async function updatePrices(
success: boolean; success: boolean;
qmSearchCode: string; qmSearchCode: string;
message: string; message: string;
data?: any; data?: unknown;
}> { }> {
const { qmSearchCode, lastRecordDate, symbol, exchange } = input; const { qmSearchCode, lastRecordDate, symbol, exchange } = input;
this.logger.info(`Fetching daily prices ${qmSearchCode}`, { qmSearchCode }); this.logger.info(`Fetching daily prices ${qmSearchCode}`, { qmSearchCode });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
@ -35,7 +36,7 @@ export async function updatePrices(
// Get a session - you'll need to add the appropriate session ID for prices // Get a session - you'll need to add the appropriate session ID for prices
const sessionId = QM_SESSION_IDS.PRICES; const sessionId = QM_SESSION_IDS.PRICES;
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM prices`); throw new Error(`No active session found for QM prices`);
} }
@ -43,16 +44,18 @@ export async function updatePrices(
try { try {
// Build API request for daily prices // Build API request for daily prices
const searchParams = new URLSearchParams({ const searchParams = new URLSearchParams({
zeroTradeDays: 'false', zeroTradeDays: 'false',
start: lastRecordDate ? new Date(lastRecordDate).toISOString().split('T')[0] + '' : '1960-01-01', start: lastRecordDate
interval: '1', ? new Date(lastRecordDate).toISOString().split('T')[0] + ''
marketSession: 'mkt', : '1960-01-01',
freq: 'day', interval: '1',
adjusted: 'false', marketSession: 'mkt',
adjustmentType: 'none', freq: 'day',
unadjusted: 'true', adjusted: 'false',
datatype: 'eod', adjustmentType: 'none',
symbol: qmSearchCode, unadjusted: 'true',
datatype: 'eod',
symbol: qmSearchCode,
}); });
// https://app.quotemedia.com/datatool/getEnhancedChartData.json?zeroTradeDays=false&start=2025-06-22&interval=1&marketSession=mkt&freq=day&adjusted=true&adjustmentType=none&unadjusted=false&datatype=int&symbol=AAPL // https://app.quotemedia.com/datatool/getEnhancedChartData.json?zeroTradeDays=false&start=2025-06-22&interval=1&marketSession=mkt&freq=day&adjusted=true&adjustmentType=none&unadjusted=false&datatype=int&symbol=AAPL
// TODO: Update with correct prices endpoint // TODO: Update with correct prices endpoint
@ -72,26 +75,26 @@ export async function updatePrices(
// Update session success stats // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Update symbol to track last price update // Update symbol to track last price update
const priceData = responseData.results?.history[0].eoddata || []; const priceData = responseData.results?.history[0].eoddata || [];
if(!priceData || priceData.length === 0) { if (!priceData || priceData.length === 0) {
this.logger.warn(`No price data found for symbol ${qmSearchCode}`); this.logger.warn(`No price data found for symbol ${qmSearchCode}`);
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'success', status: 'success',
recordCount: priceData.length recordCount: priceData.length,
}); });
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `No price data found for symbol ${qmSearchCode}` message: `No price data found for symbol ${qmSearchCode}`,
}; };
} }
// Process and store price data // Process and store price data
if (priceData && priceData.length > 0) { if (priceData && priceData.length > 0) {
// Store prices in a separate collection // Store prices in a separate collection
const processedPrices = priceData.map((price: any) => ({ const processedPrices = priceData.map((price: Document) => ({
...price, ...price,
symbol, symbol,
exchange, exchange,
@ -106,62 +109,60 @@ export async function updatePrices(
); );
// Find the latest price date // Find the latest price date
const latestDate = processedPrices.reduce((latest: Date, price: any) => const latestDate = processedPrices.reduce(
price.dateTime > latest ? price.dateTime : latest, (latest: Date, price: Document) => (price.dateTime > latest ? price.dateTime : latest),
new Date(0) new Date(0)
); );
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'success', status: 'success',
lastRecordDate: latestDate, lastRecordDate: latestDate,
recordCount: priceData.length recordCount: priceData.length,
}); });
this.logger.info('Prices updated successfully', { this.logger.info('Prices updated successfully', {
qmSearchCode, qmSearchCode,
priceCount: priceData.length, priceCount: priceData.length,
latestDate latestDate,
}); });
return { return {
success: true, success: true,
qmSearchCode, qmSearchCode,
message: `Prices updated for ${qmSearchCode}`, message: `Prices updated for ${qmSearchCode}`,
data: { data: {
count: priceData.length, count: priceData.length,
latestDate latestDate,
} },
}; };
} else { } else {
this.logger.warn('No price data returned from API', { qmSearchCode }); this.logger.warn('No price data returned from API', { qmSearchCode });
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `No price data found for qmSearchCode ${qmSearchCode}` message: `No price data found for qmSearchCode ${qmSearchCode}`,
}; };
} }
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error fetching prices', { this.logger.error('Error fetching prices', {
qmSearchCode, qmSearchCode,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
// Track failure // Track failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'failure' status: 'failure',
}); });
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `Failed to fetch prices: ${error instanceof Error ? error.message : 'Unknown error'}` message: `Failed to fetch prices: ${error instanceof Error ? error.message : 'Unknown error'}`,
}; };
} }
} }
@ -182,14 +183,14 @@ export async function schedulePriceUpdates(
errors: number; errors: number;
}> { }> {
const { limit = 50000, forceUpdate = false } = input; const { limit = 50000, forceUpdate = false } = input;
this.logger.info('Scheduling price updates', { limit, forceUpdate }); this.logger.info('Scheduling price updates', { limit, forceUpdate });
try { try {
// Get symbols that need updating // Get symbols that need updating
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'price_update', { const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: forceUpdate ? 0 : 24, // Daily updates minHoursSinceRun: forceUpdate ? 0 : 24, // Daily updates
limit limit,
}); });
if (staleSymbols.length === 0) { if (staleSymbols.length === 0) {
@ -197,7 +198,7 @@ export async function schedulePriceUpdates(
return { return {
message: 'No symbols need price updates', message: 'No symbols need price updates',
symbolsQueued: 0, symbolsQueued: 0,
errors: 0 errors: 0,
}; };
} }
@ -209,19 +210,25 @@ export async function schedulePriceUpdates(
// Schedule individual update jobs for each symbol // Schedule individual update jobs for each symbol
for (const item of staleSymbols) { for (const item of staleSymbols) {
try { try {
await this.scheduleOperation('update-prices', { await this.scheduleOperation(
qmSearchCode: item.symbol.qmSearchCode, 'update-prices',
lastRecordDate: item.operations?.price_update?.lastRecordDate, {
symbol: item.symbol.symbol, qmSearchCode: item.symbol.qmSearchCode,
exchange: item.symbol.exchange lastRecordDate: item.operations?.price_update?.lastRecordDate,
}, { symbol: item.symbol.symbol,
priority: 7, // High priority for price data exchange: item.symbol.exchange,
delay: queued * 100 // 0.1 seconds between jobs },
}); {
priority: 7, // High priority for price data
delay: queued * 100, // 0.1 seconds between jobs
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule price update for ${item.symbol.qmSearchCode}`, { error }); this.logger.error(`Failed to schedule price update for ${item.symbol.qmSearchCode}`, {
error,
});
errors++; errors++;
} }
} }
@ -229,16 +236,16 @@ export async function schedulePriceUpdates(
this.logger.info('Price update scheduling completed', { this.logger.info('Price update scheduling completed', {
symbolsQueued: queued, symbolsQueued: queued,
errors, errors,
total: staleSymbols.length total: staleSymbols.length,
}); });
return { return {
message: `Scheduled price updates for ${queued} symbols`, message: `Scheduled price updates for ${queued} symbols`,
symbolsQueued: queued, symbolsQueued: queued,
errors errors,
}; };
} catch (error) { } catch (error) {
this.logger.error('Price scheduling failed', { error }); this.logger.error('Price scheduling failed', { error });
throw error; throw error;
} }
} }

View file

@ -1,3 +1,4 @@
import type { Document } from 'mongodb';
/** /**
* QM Symbol Deduplication and Exchange Statistics * QM Symbol Deduplication and Exchange Statistics
* - Updates exchange statistics (symbol count, market cap) * - Updates exchange statistics (symbol count, market cap)
@ -6,6 +7,7 @@
*/ */
import type { ExecutionContext } from '@stock-bot/handlers'; import type { ExecutionContext } from '@stock-bot/handlers';
import { at, defined } from '@stock-bot/invariants';
import type { QMHandler } from '../qm.handler'; import type { QMHandler } from '../qm.handler';
import type { ExchangeStats } from '../shared/types'; import type { ExchangeStats } from '../shared/types';
@ -14,26 +16,26 @@ import type { ExchangeStats } from '../shared/types';
*/ */
const EXCHANGE_PRIORITIES: Record<string, number> = { const EXCHANGE_PRIORITIES: Record<string, number> = {
// Major US exchanges // Major US exchanges
'NYSE': 10, NYSE: 10,
'NASDAQ': 10, NASDAQ: 10,
'NYSE American': 9, 'NYSE American': 9,
// Other US exchanges // Other US exchanges
'EDGX': 5, EDGX: 5,
'BZX': 5, BZX: 5,
'ARCA': 5, ARCA: 5,
// Canadian main exchanges // Canadian main exchanges
'TSX': 8, TSX: 8,
'TSXV': 8, TSXV: 8,
'CSE': 7, CSE: 7,
// Canadian quote exchanges // Canadian quote exchanges
'CCQ TSX': 3, 'CCQ TSX': 3,
'CCQ TSXV': 3, 'CCQ TSXV': 3,
// Default for others // Default for others
'default': 1 default: 1,
}; };
/** /**
@ -41,7 +43,7 @@ const EXCHANGE_PRIORITIES: Record<string, number> = {
*/ */
export async function updateExchangeStats( export async function updateExchangeStats(
this: QMHandler, this: QMHandler,
_input: any, _input: unknown,
_context: ExecutionContext _context: ExecutionContext
): Promise<{ message: string; exchangesUpdated: number }> { ): Promise<{ message: string; exchangesUpdated: number }> {
this.logger.info('Updating exchange statistics'); this.logger.info('Updating exchange statistics');
@ -49,32 +51,32 @@ export async function updateExchangeStats(
try { try {
// Get all exchanges // Get all exchanges
const exchanges = await this.mongodb.find('qmExchanges', {}); const exchanges = await this.mongodb.find('qmExchanges', {});
if (!exchanges || exchanges.length === 0) { if (!exchanges || exchanges.length === 0) {
return { message: 'No exchanges found', exchangesUpdated: 0 }; return { message: 'No exchanges found', exchangesUpdated: 0 };
} }
// Calculate stats for each exchange // Calculate stats for each exchange
const bulkOps = []; const bulkOps = [];
for (const exchange of exchanges) { for (const exchange of exchanges) {
// Get symbol statistics for this exchange // Get symbol statistics for this exchange
const stats = await this.mongodb.aggregate('qmSymbols', [ const stats = await this.mongodb.aggregate<ExchangeStats>('qmSymbols', [
{ $match: { exchange: exchange.exchange } }, { $match: { exchange: exchange.exchange } },
{ {
$group: { $group: {
_id: null, _id: null,
symbolCount: { $sum: 1 }, symbolCount: { $sum: 1 },
totalMarketCap: { $sum: { $ifNull: ['$marketCap', 0] } }, totalMarketCap: { $sum: { $ifNull: ['$marketCap', 0] } },
avgMarketCap: { $avg: { $ifNull: ['$marketCap', 0] } } avgMarketCap: { $avg: { $ifNull: ['$marketCap', 0] } },
} },
} },
]); ]);
const exchangeStats: ExchangeStats = stats[0] || { const exchangeStats: ExchangeStats = stats[0] || {
symbolCount: 0, symbolCount: 0,
totalMarketCap: 0, totalMarketCap: 0,
avgMarketCap: 0 avgMarketCap: 0,
}; };
// Get priority for this exchange // Get priority for this exchange
@ -90,10 +92,10 @@ export async function updateExchangeStats(
'stats.totalMarketCap': exchangeStats.totalMarketCap, 'stats.totalMarketCap': exchangeStats.totalMarketCap,
'stats.avgMarketCap': Math.round(exchangeStats.avgMarketCap), 'stats.avgMarketCap': Math.round(exchangeStats.avgMarketCap),
priority, priority,
updated_at: new Date() updated_at: new Date(),
} },
} },
} },
}); });
} }
@ -103,13 +105,11 @@ export async function updateExchangeStats(
await collection.bulkWrite(bulkOps); await collection.bulkWrite(bulkOps);
} }
this.logger.info(`Updated statistics for ${exchanges.length} exchanges`); this.logger.info(`Updated statistics for ${exchanges.length} exchanges`);
return { return {
message: `Updated statistics for ${exchanges.length} exchanges`, message: `Updated statistics for ${exchanges.length} exchanges`,
exchangesUpdated: exchanges.length exchangesUpdated: exchanges.length,
}; };
} catch (error) { } catch (error) {
this.logger.error('Failed to update exchange statistics', { error }); this.logger.error('Failed to update exchange statistics', { error });
throw error; throw error;
@ -121,7 +121,7 @@ export async function updateExchangeStats(
*/ */
export async function deduplicateSymbols( export async function deduplicateSymbols(
this: QMHandler, this: QMHandler,
_input: any, _input: unknown,
_context: ExecutionContext _context: ExecutionContext
): Promise<{ message: string; symbolsProcessed: number; deactivated: number }> { ): Promise<{ message: string; symbolsProcessed: number; deactivated: number }> {
this.logger.info('Starting symbol deduplication'); this.logger.info('Starting symbol deduplication');
@ -138,11 +138,11 @@ export async function deduplicateSymbols(
exchange: '$exchange', exchange: '$exchange',
countryCode: '$countryCode', countryCode: '$countryCode',
marketCap: { $ifNull: ['$marketCap', 0] }, marketCap: { $ifNull: ['$marketCap', 0] },
_id: '$_id' _id: '$_id',
} },
} },
} },
} },
]); ]);
let totalProcessed = 0; let totalProcessed = 0;
@ -150,9 +150,13 @@ export async function deduplicateSymbols(
const bulkOps = []; const bulkOps = [];
// Get exchange priorities for sorting // Get exchange priorities for sorting
const exchangePriorities = await this.mongodb.find('qmExchanges', {}, { const exchangePriorities = await this.mongodb.find(
projection: { exchange: 1, priority: 1 } 'qmExchanges',
}); {},
{
projection: { exchange: 1, priority: 1 },
}
);
const priorityMap = new Map(exchangePriorities.map(e => [e.exchange, e.priority || 1])); const priorityMap = new Map(exchangePriorities.map(e => [e.exchange, e.priority || 1]));
for (const group of symbolGroups) { for (const group of symbolGroups) {
@ -160,13 +164,13 @@ export async function deduplicateSymbols(
const documents = group.symbols; const documents = group.symbols;
// Group by country // Group by country
const byCountry = new Map<string, any[]>(); const byCountry = new Map<string, Document[]>();
for (const doc of documents) { for (const doc of documents) {
const country = doc.countryCode || 'UNKNOWN'; const country = doc.countryCode || 'UNKNOWN';
if (!byCountry.has(country)) { if (!byCountry.has(country)) {
byCountry.set(country, []); byCountry.set(country, []);
} }
byCountry.get(country)!.push(doc); defined(byCountry.get(country)).push(doc);
} }
// Process each country separately // Process each country separately
@ -175,9 +179,9 @@ export async function deduplicateSymbols(
// Only one symbol in this country, mark as active // Only one symbol in this country, mark as active
bulkOps.push({ bulkOps.push({
updateOne: { updateOne: {
filter: { _id: countryDocs[0]._id }, filter: { _id: at(countryDocs, 0)._id },
update: { $set: { active: true } } update: { $set: { active: true } },
} },
}); });
totalProcessed++; totalProcessed++;
continue; continue;
@ -201,10 +205,12 @@ export async function deduplicateSymbols(
countryDocs.sort((a, b) => { countryDocs.sort((a, b) => {
const priorityA = priorityMap.get(a.exchange) || 1; const priorityA = priorityMap.get(a.exchange) || 1;
const priorityB = priorityMap.get(b.exchange) || 1; const priorityB = priorityMap.get(b.exchange) || 1;
if (priorityA !== priorityB) { return priorityB - priorityA } if (priorityA !== priorityB) {
return priorityB - priorityA;
}
return (b.marketCap || 0) - (a.marketCap || 0); return (b.marketCap || 0) - (a.marketCap || 0);
}); });
activeDoc = countryDocs[0]; activeDoc = at(countryDocs, 0);
} }
// Mark active and inactive documents // Mark active and inactive documents
@ -213,11 +219,13 @@ export async function deduplicateSymbols(
bulkOps.push({ bulkOps.push({
updateOne: { updateOne: {
filter: { _id: doc._id }, filter: { _id: doc._id },
update: { $set: { active: isActive } } update: { $set: { active: isActive } },
} },
}); });
totalProcessed++; totalProcessed++;
if (!isActive) { totalDeactivated++ } if (!isActive) {
totalDeactivated++;
}
} }
} }
} }
@ -228,14 +236,14 @@ export async function deduplicateSymbols(
await collection.bulkWrite(bulkOps, { ordered: false }); await collection.bulkWrite(bulkOps, { ordered: false });
} }
this.logger.info(
this.logger.info(`Deduplication complete: processed ${totalProcessed} symbols, deactivated ${totalDeactivated}`); `Deduplication complete: processed ${totalProcessed} symbols, deactivated ${totalDeactivated}`
);
return { return {
message: `Processed ${totalProcessed} symbols, deactivated ${totalDeactivated} duplicates`, message: `Processed ${totalProcessed} symbols, deactivated ${totalDeactivated} duplicates`,
symbolsProcessed: totalProcessed, symbolsProcessed: totalProcessed,
deactivated: totalDeactivated deactivated: totalDeactivated,
}; };
} catch (error) { } catch (error) {
this.logger.error('Failed to deduplicate symbols', { error }); this.logger.error('Failed to deduplicate symbols', { error });
throw error; throw error;
@ -247,7 +255,7 @@ export async function deduplicateSymbols(
*/ */
export async function updateExchangeStatsAndDeduplicate( export async function updateExchangeStatsAndDeduplicate(
this: QMHandler, this: QMHandler,
input: any, input: { exchange?: string; country?: string },
context: ExecutionContext context: ExecutionContext
): Promise<{ message: string }> { ): Promise<{ message: string }> {
this.logger.info('Running exchange stats update and symbol deduplication'); this.logger.info('Running exchange stats update and symbol deduplication');
@ -255,15 +263,15 @@ export async function updateExchangeStatsAndDeduplicate(
try { try {
// First update exchange stats // First update exchange stats
const statsResult = await updateExchangeStats.call(this, input, context); const statsResult = await updateExchangeStats.call(this, input, context);
// Then deduplicate symbols // Then deduplicate symbols
const dedupResult = await deduplicateSymbols.call(this, input, context); const dedupResult = await deduplicateSymbols.call(this, input, context);
return { return {
message: `${statsResult.message}. ${dedupResult.message}` message: `${statsResult.message}. ${dedupResult.message}`,
}; };
} catch (error) { } catch (error) {
this.logger.error('Failed to update stats and deduplicate', { error }); this.logger.error('Failed to update stats and deduplicate', { error });
throw error; throw error;
} }
} }

View file

@ -21,10 +21,10 @@ export async function updateSymbolInfo(
success: boolean; success: boolean;
qmSearchCode: string; qmSearchCode: string;
message: string; message: string;
data?: any; data?: unknown;
}> { }> {
const { qmSearchCode } = input; const { qmSearchCode } = input;
this.logger.info(`Fetching symbol info ${qmSearchCode}`, { qmSearchCode }); this.logger.info(`Fetching symbol info ${qmSearchCode}`, { qmSearchCode });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
@ -33,7 +33,7 @@ export async function updateSymbolInfo(
// Get a session // Get a session
const sessionId = QM_SESSION_IDS.SYMBOL; const sessionId = QM_SESSION_IDS.SYMBOL;
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM LOOKUP`); throw new Error(`No active session found for QM LOOKUP`);
} }
@ -48,7 +48,7 @@ export async function updateSymbolInfo(
pathName: '/demo/portal/company-summary.php', pathName: '/demo/portal/company-summary.php',
webmasterId: '500', webmasterId: '500',
} as Record<string, string>); } as Record<string, string>);
const apiUrl = `${QM_CONFIG.SYMBOL_URL}?${searchParams.toString()}`; const apiUrl = `${QM_CONFIG.SYMBOL_URL}?${searchParams.toString()}`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'GET', method: 'GET',
@ -61,23 +61,26 @@ export async function updateSymbolInfo(
} }
const symbolData = await response.json(); const symbolData = await response.json();
// Update session success stats // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store symbol info // Process and store symbol info
if (symbolData && Array.isArray(symbolData?.results?.company) && symbolData?.results?.company.length > 0) { if (
symbolData &&
Array.isArray(symbolData?.results?.company) &&
symbolData?.results?.company.length > 0
) {
// Update symbol in database with new metadata // Update symbol in database with new metadata
const updateData = { const updateData = {
qmSearchCode: qmSearchCode, qmSearchCode: qmSearchCode,
profile: symbolData?.results?.company[0].profile, profile: symbolData?.results?.company[0].profile,
symbolInfo: symbolData?.results?.company[0].symbolinfo, symbolInfo: symbolData?.results?.company[0].symbolinfo,
} };
await this.mongodb.updateOne( await this.mongodb.updateOne(
'qmSymbols', 'qmSymbols',
{ qmSearchCode, }, { qmSearchCode },
{ $set: updateData }, { $set: updateData },
{ upsert: true } { upsert: true }
); );
@ -85,10 +88,10 @@ export async function updateSymbolInfo(
// Update operation tracking // Update operation tracking
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', {
status: 'success', status: 'success',
lastRecordDate: new Date() lastRecordDate: new Date(),
}); });
this.logger.info(`Symbol info updated successfully ${qmSearchCode}`, { this.logger.info(`Symbol info updated successfully ${qmSearchCode}`, {
qmSearchCode, qmSearchCode,
}); });
@ -102,30 +105,29 @@ export async function updateSymbolInfo(
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `No data found for symbol ${qmSearchCode}` message: `No data found for symbol ${qmSearchCode}`,
}; };
} }
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error fetching symbol info', { this.logger.error('Error fetching symbol info', {
qmSearchCode, qmSearchCode,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
// Update operation tracking for failure // Update operation tracking for failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', { await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', {
status: 'failure' status: 'failure',
}); });
return { return {
success: false, success: false,
qmSearchCode, qmSearchCode,
message: `Failed to fetch symbol info: ${error instanceof Error ? error.message : 'Unknown error'}` message: `Failed to fetch symbol info: ${error instanceof Error ? error.message : 'Unknown error'}`,
}; };
} }
} }
@ -147,14 +149,14 @@ export async function scheduleSymbolInfoUpdates(
errors: number; errors: number;
}> { }> {
const { limit = 100000, forceUpdate = false } = input; const { limit = 100000, forceUpdate = false } = input;
this.logger.info('Scheduling symbol info updates', { limit, forceUpdate }); this.logger.info('Scheduling symbol info updates', { limit, forceUpdate });
try { try {
// Get symbols that need updating // Get symbols that need updating
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'symbol_info', { const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'symbol_info', {
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default
limit limit,
}); });
if (staleSymbols.length === 0) { if (staleSymbols.length === 0) {
@ -162,7 +164,7 @@ export async function scheduleSymbolInfoUpdates(
return { return {
message: 'No symbols need info updates', message: 'No symbols need info updates',
symbolsQueued: 0, symbolsQueued: 0,
errors: 0 errors: 0,
}; };
} }
@ -174,14 +176,18 @@ export async function scheduleSymbolInfoUpdates(
// Schedule individual update jobs for each symbol // Schedule individual update jobs for each symbol
for (const item of staleSymbols) { for (const item of staleSymbols) {
try { try {
await this.scheduleOperation('update-symbol-info', { await this.scheduleOperation(
qmSearchCode: item.symbol.qmSearchCode 'update-symbol-info',
}, { {
// priority: 3, qmSearchCode: item.symbol.qmSearchCode,
// Add some delay to avoid overwhelming the API },
// delay: queued * 1000 // 1 second between jobs {
}); // priority: 3,
// Add some delay to avoid overwhelming the API
// delay: queued * 1000 // 1 second between jobs
}
);
queued++; queued++;
} catch (error) { } catch (error) {
this.logger.error(`Failed to schedule update for ${item.symbol.qmSearchCode}`, { error }); this.logger.error(`Failed to schedule update for ${item.symbol.qmSearchCode}`, { error });
@ -192,16 +198,16 @@ export async function scheduleSymbolInfoUpdates(
this.logger.info('Symbol info update scheduling completed', { this.logger.info('Symbol info update scheduling completed', {
symbolsQueued: queued, symbolsQueued: queued,
errors, errors,
total: staleSymbols.length total: staleSymbols.length,
}); });
return { return {
message: `Scheduled info updates for ${queued} symbols`, message: `Scheduled info updates for ${queued} symbols`,
symbolsQueued: queued, symbolsQueued: queued,
errors errors,
}; };
} catch (error) { } catch (error) {
this.logger.error('Symbol info scheduling failed', { error }); this.logger.error('Symbol info scheduling failed', { error });
throw error; throw error;
} }
} }

View file

@ -1,3 +1,4 @@
import type { Document } from 'mongodb';
/** /**
* QM Symbol Actions - Symbol search and spider operations * QM Symbol Actions - Symbol search and spider operations
*/ */
@ -31,41 +32,49 @@ export async function spiderSymbol(
let jobsCreated = 0; let jobsCreated = 0;
for (let i = 0; i < 26; i++) { for (let i = 0; i < 26; i++) {
const letter = String.fromCharCode(65 + i); // A-Z const letter = String.fromCharCode(65 + i); // A-Z
await this.scheduleOperation('spider-symbols', { await this.scheduleOperation(
prefix: letter, 'spider-symbols',
depth: 1, {
source: 'qm', prefix: letter,
maxDepth depth: 1,
}, { source: 'qm',
priority: 5 maxDepth,
}); },
{
priority: 5,
}
);
jobsCreated++; jobsCreated++;
} }
this.logger.info('Created root spider jobs', { jobsCreated }); this.logger.info('Created root spider jobs', { jobsCreated });
return { return {
message: `Queued ${jobsCreated} root jobs (A-Z)`, message: `Queued ${jobsCreated} root jobs (A-Z)`,
jobsCreated jobsCreated,
}; };
} }
try { try {
// Search current prefix // Search current prefix
const symbols = await searchSymbols.call(this, { query: prefix }); const symbols = await searchSymbols.call(this, { query: prefix });
if (!symbols || symbols.length === 0) { if (!symbols || symbols.length === 0) {
this.logger.debug('No symbols found for prefix', { prefix }); this.logger.debug('No symbols found for prefix', { prefix });
return { return {
message: `No symbols found for prefix: ${prefix}`, message: `No symbols found for prefix: ${prefix}`,
symbolsFound: 0 symbolsFound: 0,
}; };
} }
await this.mongodb?.batchUpsert('qmSymbols', symbols, ['qmSearchCode']); await this.mongodb?.batchUpsert(
'qmSymbols',
this.logger.info(`Stored symbols from spider search ${prefix} - ${symbols.length}`, { symbols.map(symbol => ({ ...symbol, source: 'qm' })),
prefix, ['qmSearchCode']
count: symbols.length );
this.logger.info(`Stored symbols from spider search ${prefix} - ${symbols.length}`, {
prefix,
count: symbols.length,
}); });
// Extract and store unique exchanges // Extract and store unique exchanges
@ -83,49 +92,52 @@ export async function spiderSymbol(
if (exchanges.length > 0) { if (exchanges.length > 0) {
await this.mongodb?.batchUpsert('qmExchanges', exchanges, ['exchange']); await this.mongodb?.batchUpsert('qmExchanges', exchanges, ['exchange']);
this.logger.debug('Stored exchanges from spider search', { this.logger.debug('Stored exchanges from spider search', {
count: exchanges.length count: exchanges.length,
}); });
} }
// If not at max depth and we found symbols, create child jobs // If not at max depth and we found symbols, create child jobs
if (depth < maxDepth && symbols.length > 0) { if (depth < maxDepth && symbols.length > 0) {
let jobsCreated = 0; let jobsCreated = 0;
// Only create child jobs if we found a significant number of symbols // Only create child jobs if we found a significant number of symbols
// This prevents excessive branching on sparse results // This prevents excessive branching on sparse results
if (symbols.length >= 50) { if (symbols.length >= 50) {
for (let i = 0; i < 26; i++) { for (let i = 0; i < 26; i++) {
const nextPrefix = prefix + String.fromCharCode(65 + i); const nextPrefix = prefix + String.fromCharCode(65 + i);
await this.scheduleOperation('spider-symbols', { await this.scheduleOperation(
prefix: nextPrefix, 'spider-symbols',
depth: depth + 1, {
source: 'qm', prefix: nextPrefix,
maxDepth depth: depth + 1,
}, { source: 'qm',
priority: Math.max(1, 5 - depth) maxDepth,
}); },
{
priority: Math.max(1, 5 - depth),
}
);
jobsCreated++; jobsCreated++;
} }
} }
return { return {
message: `Found ${symbols.length} symbols for ${prefix}, queued ${jobsCreated} child jobs`, message: `Found ${symbols.length} symbols for ${prefix}, queued ${jobsCreated} child jobs`,
symbolsFound: symbols.length, symbolsFound: symbols.length,
jobsCreated jobsCreated,
}; };
} }
return { return {
message: `Found ${symbols.length} symbols for ${prefix} (at max depth or too few results)`, message: `Found ${symbols.length} symbols for ${prefix} (at max depth or too few results)`,
symbolsFound: symbols.length symbolsFound: symbols.length,
}; };
} catch (error) { } catch (error) {
this.logger.error(`Spider search failed ${prefix}`, { prefix, error }); this.logger.error(`Spider search failed ${prefix}`, { prefix, error });
return { return {
message: `Spider search failed for prefix: ${prefix}`, message: `Spider search failed for prefix: ${prefix}`,
symbolsFound: 0 symbolsFound: 0,
}; };
} }
} }
@ -137,9 +149,9 @@ export async function searchSymbols(
this: QMHandler, this: QMHandler,
input: { query: string }, input: { query: string },
_context?: ExecutionContext _context?: ExecutionContext
): Promise<any[]> { ): Promise<Document[]> {
const { query } = input; const { query } = input;
this.logger.debug('Searching QM symbols', { query }); this.logger.debug('Searching QM symbols', { query });
const sessionManager = QMSessionManager.getInstance(); const sessionManager = QMSessionManager.getInstance();
@ -148,7 +160,7 @@ export async function searchSymbols(
// Get a session // Get a session
const sessionId = QM_SESSION_IDS.LOOKUP; const sessionId = QM_SESSION_IDS.LOOKUP;
const session = await sessionManager.getSession(sessionId); const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) { if (!session || !session.uuid) {
throw new Error(`No active session found for QM LOOKUP`); throw new Error(`No active session found for QM LOOKUP`);
} }
@ -163,9 +175,9 @@ export async function searchSymbols(
searchType: 'symbol', searchType: 'symbol',
showFree: 'false', showFree: 'false',
showHisa: 'false', showHisa: 'false',
webmasterId: '500' webmasterId: '500',
}); });
const apiUrl = `${QM_CONFIG.LOOKUP_URL}?${searchParams.toString()}`; const apiUrl = `${QM_CONFIG.LOOKUP_URL}?${searchParams.toString()}`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
@ -179,40 +191,41 @@ export async function searchSymbols(
} }
const symbols = await response.json(); const symbols = await response.json();
// Update session success stats // Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process symbol data // Process symbol data
const processedSymbols = Array.isArray(symbols) ? symbols.map((symbol: any) => { const processedSymbols = Array.isArray(symbols)
const { exchangeCode, exchangeShortName, ...rest } = symbol; ? symbols.map((symbol: Document) => {
return { const { exchangeCode, exchangeShortName, ...rest } = symbol;
...rest, return {
exchange: exchangeCode, ...rest,
exchangeName: exchangeShortName, exchange: exchangeCode,
qmSearchCode: symbol.symbol, exchangeName: exchangeShortName,
symbol: (symbol.symbol as string)?.split(':')[0], qmSearchCode: symbol.symbol,
}; symbol: (symbol.symbol as string)?.split(':')[0],
}) : []; };
})
: [];
this.logger.debug('QM API returned symbols ${query} - ${processedSymbols.length}', { this.logger.debug('QM API returned symbols ${query} - ${processedSymbols.length}', {
query, query,
count: processedSymbols.length count: processedSymbols.length,
}); });
return processedSymbols; return processedSymbols;
} catch (error) { } catch (error) {
// Update session failure stats // Update session failure stats
if (session.uuid) { if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid); await sessionManager.incrementFailedCalls(sessionId, session.uuid);
} }
this.logger.error('Error searching QM symbols', { this.logger.error('Error searching QM symbols', {
query, query,
error: error instanceof Error ? error.message : 'Unknown error' error: error instanceof Error ? error.message : 'Unknown error',
}); });
throw error; throw error;
} }
} }

View file

@ -1,12 +1,10 @@
import { import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
BaseHandler, import type { IServiceContainer } from '@stock-bot/services';
Disabled,
Handler,
Operation,
ScheduledOperation,
} from '@stock-bot/handlers';
import type { OperationRegistry } from '../../shared/operation-manager'; import type { OperationRegistry } from '../../shared/operation-manager';
import { resolveIngestionServices } from '../../types';
import type { DataIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types';
import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action';
import { createQMOperationRegistry } from './shared/operation-provider';
import { import {
checkSessions, checkSessions,
createSession, createSession,
@ -27,22 +25,21 @@ import {
updateInsiders, updateInsiders,
updatePrices, updatePrices,
updateSymbolInfo, updateSymbolInfo,
updateSymbolNews updateSymbolNews,
} from './actions'; } from './actions';
import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action';
import { createQMOperationRegistry } from './shared/operation-provider';
@Handler('qm') @Handler('qm')
@Disabled() // Disable by default, enable specific operations as needed @Disabled() // Disable by default, enable specific operations as needed
export class QMHandler extends BaseHandler<DataIngestionServices> { export class QMHandler extends BaseHandler<DataIngestionServices> {
static operationRegistry?: OperationRegistry;
public operationRegistry!: OperationRegistry; public operationRegistry!: OperationRegistry;
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); // Handler name read from @Handler decorator super(resolveIngestionServices(services, 'qm')); // Handler name read from @Handler decorator
// Use pre-initialized registry if available, otherwise create new one // Use pre-initialized registry if available, otherwise create new one
if ((QMHandler as any).operationRegistry) { if (QMHandler.operationRegistry) {
this.operationRegistry = (QMHandler as any).operationRegistry; this.operationRegistry = QMHandler.operationRegistry;
this.logger.info('Using pre-initialized QM operation registry'); this.logger.info('Using pre-initialized QM operation registry');
} else { } else {
// Fallback: Initialize operation registry with QM provider // Fallback: Initialize operation registry with QM provider
@ -79,7 +76,8 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('spider-symbols', '0 0 * * 0', { @ScheduledOperation('spider-symbols', '0 0 * * 0', {
priority: 9, priority: 9,
immediately: false, immediately: false,
description: 'Weekly comprehensive symbol search using QM API spider - runs every Saturday at midnight' description:
'Weekly comprehensive symbol search using QM API spider - runs every Saturday at midnight',
}) })
spiderSymbol = spiderSymbol; spiderSymbol = spiderSymbol;
@ -98,7 +96,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-exchange-stats-and-dedup', '0 1 * * *', { @ScheduledOperation('schedule-exchange-stats-and-dedup', '0 1 * * *', {
priority: 7, priority: 7,
immediately: false, immediately: false,
description: 'Update exchange statistics and deduplicate symbols daily at 1 AM' description: 'Update exchange statistics and deduplicate symbols daily at 1 AM',
}) })
scheduleExchangeStatsAndDedup = updateExchangeStatsAndDeduplicate; scheduleExchangeStatsAndDedup = updateExchangeStatsAndDeduplicate;
@ -112,7 +110,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-symbol-info-updates', '0 */6 * * *', { @ScheduledOperation('schedule-symbol-info-updates', '0 */6 * * *', {
priority: 7, priority: 7,
immediately: false, immediately: false,
description: 'Check for symbols needing info updates every 6 hours' description: 'Check for symbols needing info updates every 6 hours',
}) })
scheduleSymbolInfoUpdates = scheduleSymbolInfoUpdates; scheduleSymbolInfoUpdates = scheduleSymbolInfoUpdates;
@ -126,7 +124,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-financials-updates', '0 2 * * *', { @ScheduledOperation('schedule-financials-updates', '0 2 * * *', {
priority: 6, priority: 6,
immediately: false, immediately: false,
description: 'Check for symbols needing financials updates daily at 2 AM' description: 'Check for symbols needing financials updates daily at 2 AM',
}) })
scheduleFinancialsUpdates = scheduleFinancialsUpdates; scheduleFinancialsUpdates = scheduleFinancialsUpdates;
@ -140,7 +138,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-events-updates', '0 3 * * *', { @ScheduledOperation('schedule-events-updates', '0 3 * * *', {
priority: 6, priority: 6,
immediately: false, immediately: false,
description: 'Check for symbols needing events updates daily at 3 AM' description: 'Check for symbols needing events updates daily at 3 AM',
}) })
scheduleEventsUpdates = scheduleEventsUpdates; scheduleEventsUpdates = scheduleEventsUpdates;
@ -154,7 +152,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-price-updates', '0 */6 * * *', { @ScheduledOperation('schedule-price-updates', '0 */6 * * *', {
priority: 8, priority: 8,
immediately: false, immediately: false,
description: 'Check for symbols needing price updates every 6 hours' description: 'Check for symbols needing price updates every 6 hours',
}) })
schedulePriceUpdates = schedulePriceUpdates; schedulePriceUpdates = schedulePriceUpdates;
@ -171,11 +169,11 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-intraday-crawls-batch', '0 0 * * 0', { @ScheduledOperation('schedule-intraday-crawls-batch', '0 0 * * 0', {
priority: 5, priority: 5,
immediately: false, immediately: false,
description: 'Schedule intraday crawls for incomplete symbols every 12 hours' description: 'Schedule intraday crawls for incomplete symbols every 12 hours',
}) })
scheduleIntradayCrawlsBatch = async () => { scheduleIntradayCrawlsBatch = async () => {
return scheduleIntradayCrawls.call(this, { return scheduleIntradayCrawls.call(this, {
priorityMode: 'incomplete' priorityMode: 'incomplete',
}); });
}; };
@ -189,7 +187,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-insiders-updates', '0 4 * * 1', { @ScheduledOperation('schedule-insiders-updates', '0 4 * * 1', {
priority: 5, priority: 5,
immediately: false, immediately: false,
description: 'Check for symbols needing insider updates weekly on Monday at 4 AM' description: 'Check for symbols needing insider updates weekly on Monday at 4 AM',
}) })
scheduleInsidersUpdates = scheduleInsidersUpdates; scheduleInsidersUpdates = scheduleInsidersUpdates;
@ -206,7 +204,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-symbol-news-updates', '0 5 * * 1', { @ScheduledOperation('schedule-symbol-news-updates', '0 5 * * 1', {
priority: 4, priority: 4,
immediately: false, immediately: false,
description: 'Check for symbols needing news updates weekly on Monday at 5 AM' description: 'Check for symbols needing news updates weekly on Monday at 5 AM',
}) })
scheduleSymbolNewsUpdates = scheduleSymbolNewsUpdates; scheduleSymbolNewsUpdates = scheduleSymbolNewsUpdates;
@ -214,16 +212,16 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('update-general-news-frequent', '*/1 * * * *', { @ScheduledOperation('update-general-news-frequent', '*/1 * * * *', {
priority: 9, priority: 9,
immediately: true, immediately: true,
description: 'Update general market news every minute' description: 'Update general market news every minute',
}) })
updateGeneralNewsFrequent = async () => { updateGeneralNewsFrequent = async () => {
return updateGeneralNews.call(this, { return updateGeneralNews.call(this, {
categories: ['market', 'economy', 'politics', 'breaking'], categories: ['market', 'economy', 'politics', 'breaking'],
lookbackMinutes: 5 // Only look back 5 minutes to avoid duplicates lookbackMinutes: 5, // Only look back 5 minutes to avoid duplicates
}); });
}; };
/** /**
* FILINGS * FILINGS
*/ */
// @Operation('update-filings') // @Operation('update-filings')
@ -236,4 +234,4 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
// description: 'Check for symbols needing filings updates every 8 hours' // description: 'Check for symbols needing filings updates every 8 hours'
// }) // })
// scheduleFilingsUpdates = scheduleFilingsUpdates; // scheduleFilingsUpdates = scheduleFilingsUpdates;
} }

View file

@ -1,8 +1,14 @@
import type { Logger, MongoDBClient } from '@stock-bot/services';
/** /**
* QM Operation Provider - Defines operations for QuoteMedia data source * QM Operation Provider - Defines operations for QuoteMedia data source
*/ */
import { BaseOperationProvider, OperationRegistry, type OperationConfig, type ProviderConfig } from '../../../shared/operation-manager'; import {
BaseOperationProvider,
OperationRegistry,
type OperationConfig,
type ProviderConfig,
} from '../../../shared/operation-manager';
/** /**
* QM operation definitions * QM operation definitions
@ -13,69 +19,69 @@ export const QM_OPERATIONS: OperationConfig[] = [
name: 'symbol_info', name: 'symbol_info',
type: 'standard', type: 'standard',
description: 'Update symbol metadata', description: 'Update symbol metadata',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
}, },
// Price data // Price data
{ {
name: 'price_update', name: 'price_update',
type: 'standard', type: 'standard',
description: 'Update daily price data', description: 'Update daily price data',
defaultStaleHours: 24 defaultStaleHours: 24,
}, },
{ {
name: 'intraday_bars', name: 'intraday_bars',
type: 'intraday_crawl', type: 'intraday_crawl',
description: 'Crawl intraday price bars from today backwards', description: 'Crawl intraday price bars from today backwards',
requiresFinishedFlag: true, requiresFinishedFlag: true,
defaultStaleHours: 1 // Check every hour for new data defaultStaleHours: 1, // Check every hour for new data
}, },
// Fundamental data // Fundamental data
{ {
name: 'financials_update_quarterly', name: 'financials_update_quarterly',
type: 'standard', type: 'standard',
description: 'Update quarterly financial statements', description: 'Update quarterly financial statements',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
}, },
{ {
name: 'financials_update_annual', name: 'financials_update_annual',
type: 'standard', type: 'standard',
description: 'Update annual financial statements', description: 'Update annual financial statements',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
}, },
// Corporate actions // Corporate actions
{ {
name: 'events_update', name: 'events_update',
type: 'standard', type: 'standard',
description: 'Update events (earnings, dividends, splits)', description: 'Update events (earnings, dividends, splits)',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
}, },
// Filings // Filings
{ {
name: 'filings_update', name: 'filings_update',
type: 'standard', type: 'standard',
description: 'Update SEC filings', description: 'Update SEC filings',
defaultStaleHours: 24 // Daily defaultStaleHours: 24, // Daily
}, },
// Insider trading // Insider trading
{ {
name: 'insiders_update', name: 'insiders_update',
type: 'standard', type: 'standard',
description: 'Update insider transactions', description: 'Update insider transactions',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
}, },
// News // News
{ {
name: 'news_update', name: 'news_update',
type: 'standard', type: 'standard',
description: 'Update symbol-specific news', description: 'Update symbol-specific news',
defaultStaleHours: 24 * 7 // Weekly defaultStaleHours: 24 * 7, // Weekly
} },
]; ];
/** /**
@ -87,7 +93,7 @@ export class QMOperationProvider extends BaseOperationProvider {
name: 'qm', name: 'qm',
collectionName: 'qmSymbols', collectionName: 'qmSymbols',
symbolField: 'qmSearchCode', symbolField: 'qmSearchCode',
description: 'QuoteMedia data provider' description: 'QuoteMedia data provider',
}; };
} }
@ -100,11 +106,14 @@ export class QMOperationProvider extends BaseOperationProvider {
* Create and initialize QM operation registry * Create and initialize QM operation registry
*/ */
export async function createQMOperationRegistry( export async function createQMOperationRegistry(
mongodb: any, mongodb: MongoDBClient | null | undefined,
logger: any logger: Logger
): Promise<OperationRegistry> { ): Promise<OperationRegistry> {
if (!mongodb) {
throw new Error('Operation registry requires MongoDB');
}
const registry = new OperationRegistry({ mongodb, logger }); const registry = new OperationRegistry({ mongodb, logger });
const provider = new QMOperationProvider({ mongodb, logger }); const provider = new QMOperationProvider({ mongodb, logger });
await registry.registerProvider(provider); await registry.registerProvider(provider);
return registry; return registry;
} }

View file

@ -48,7 +48,7 @@ export class QMSessionManagerRedis {
try { try {
// Get all session UUIDs for this sessionId // Get all session UUIDs for this sessionId
const sessionUuids = await this.getSessionUuids(sessionId); const sessionUuids = await this.getSessionUuids(sessionId);
if (sessionUuids.length === 0) { if (sessionUuids.length === 0) {
this.logger?.debug(`No sessions found for ${sessionId}`); this.logger?.debug(`No sessions found for ${sessionId}`);
return null; return null;
@ -56,7 +56,7 @@ export class QMSessionManagerRedis {
// Shuffle and try to find a valid session // Shuffle and try to find a valid session
const shuffled = [...sessionUuids].sort(() => Math.random() - 0.5); const shuffled = [...sessionUuids].sort(() => Math.random() - 0.5);
for (const uuid of shuffled) { for (const uuid of shuffled) {
const session = await this.getSessionByUuid(sessionId, uuid); const session = await this.getSessionByUuid(sessionId, uuid);
if (session && (session.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS) { if (session && (session.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS) {
@ -114,7 +114,7 @@ export class QMSessionManagerRedis {
try { try {
// Store the session data // Store the session data
await this.cacheProvider.set(sessionKey, session, this.SESSION_TTL); await this.cacheProvider.set(sessionKey, session, this.SESSION_TTL);
// Add UUID to the session list (using SET to simulate SADD) // Add UUID to the session list (using SET to simulate SADD)
const uuids = await this.getSessionUuids(sessionId); const uuids = await this.getSessionUuids(sessionId);
if (!uuids.includes(session.uuid)) { if (!uuids.includes(session.uuid)) {
@ -143,7 +143,7 @@ export class QMSessionManagerRedis {
try { try {
// Remove session data // Remove session data
await this.cacheProvider.del(sessionKey); await this.cacheProvider.del(sessionKey);
// Remove UUID from list // Remove UUID from list
const uuids = await this.getSessionUuids(sessionId); const uuids = await this.getSessionUuids(sessionId);
const filtered = uuids.filter(u => u !== uuid); const filtered = uuids.filter(u => u !== uuid);
@ -212,7 +212,7 @@ export class QMSessionManagerRedis {
for (const sessionId of Object.values(QM_SESSION_IDS)) { for (const sessionId of Object.values(QM_SESSION_IDS)) {
const sessions = await this.getSessions(sessionId); const sessions = await this.getSessions(sessionId);
for (const session of sessions) { for (const session of sessions) {
if (session.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS) { if (session.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS) {
await this.removeSession(sessionId, session.uuid); await this.removeSession(sessionId, session.uuid);
@ -242,14 +242,12 @@ export class QMSessionManagerRedis {
async getStats(): Promise<Record<string, { total: number; valid: number; failed: number }>> { async getStats(): Promise<Record<string, { total: number; valid: number; failed: number }>> {
const stats: Record<string, { total: number; valid: number; failed: number }> = {}; const stats: Record<string, { total: number; valid: number; failed: number }> = {};
for (const [sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) { for (const [_sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) {
const sessions = await this.getSessions(sessionId); const sessions = await this.getSessions(sessionId);
const validSessions = sessions.filter( const validSessions = sessions.filter(
s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS
); );
const failedSessions = sessions.filter( const failedSessions = sessions.filter(s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS);
s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS
);
stats[sessionId] = { stats[sessionId] = {
total: sessions.length, total: sessions.length,
@ -266,18 +264,18 @@ export class QMSessionManagerRedis {
*/ */
async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise<void> { async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise<void> {
const session = await this.getSessionByUuid(sessionId, sessionUuid); const session = await this.getSessionByUuid(sessionId, sessionUuid);
if (session) { if (session) {
session.failedCalls = (session.failedCalls || 0) + 1; session.failedCalls = (session.failedCalls || 0) + 1;
session.lastUsed = new Date(); session.lastUsed = new Date();
const sessionKey = this.getSessionKey(sessionId, sessionUuid); const sessionKey = this.getSessionKey(sessionId, sessionUuid);
await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL);
this.logger?.debug(`Incremented failed calls for session`, { this.logger?.debug(`Incremented failed calls for session`, {
sessionUuid, sessionUuid,
failedCalls: session.failedCalls, failedCalls: session.failedCalls,
sessionId sessionId,
}); });
} else { } else {
this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); this.logger?.warn(`Session not found`, { sessionUuid, sessionId });
@ -289,18 +287,18 @@ export class QMSessionManagerRedis {
*/ */
async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise<void> { async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise<void> {
const session = await this.getSessionByUuid(sessionId, sessionUuid); const session = await this.getSessionByUuid(sessionId, sessionUuid);
if (session) { if (session) {
session.successfulCalls = (session.successfulCalls || 0) + 1; session.successfulCalls = (session.successfulCalls || 0) + 1;
session.lastUsed = new Date(); session.lastUsed = new Date();
const sessionKey = this.getSessionKey(sessionId, sessionUuid); const sessionKey = this.getSessionKey(sessionId, sessionUuid);
await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL);
this.logger?.debug(`Incremented successful calls for session`, { this.logger?.debug(`Incremented successful calls for session`, {
sessionUuid, sessionUuid,
successfulCalls: session.successfulCalls, successfulCalls: session.successfulCalls,
sessionId sessionId,
}); });
} else { } else {
this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); this.logger?.warn(`Session not found`, { sessionUuid, sessionId });
@ -355,7 +353,8 @@ export class QMSessionManagerRedis {
for (const id of oldSessionIds) { for (const id of oldSessionIds) {
const oldSessionKey = `qm:sessions:${sessionType.toLowerCase()}:${id}`; const oldSessionKey = `qm:sessions:${sessionType.toLowerCase()}:${id}`;
const oldSession = await this.cacheProvider.get<any>(oldSessionKey); const oldSession =
await this.cacheProvider.get<import('./types').CachedSession>(oldSessionKey);
if (oldSession && oldSession.uuid) { if (oldSession && oldSession.uuid) {
const session: QMSession = { const session: QMSession = {

View file

@ -18,9 +18,9 @@ export class SessionManagerWrapper {
private constructor() { private constructor() {
// Use Redis implementation if env var is set or if in production // Use Redis implementation if env var is set or if in production
const useRedis = process.env.REDIS_SESSION_MANAGER === 'true' || const useRedis =
process.env.NODE_ENV === 'production'; process.env.REDIS_SESSION_MANAGER === 'true' || process.env.NODE_ENV === 'production';
if (useRedis) { if (useRedis) {
this.implementation = QMSessionManagerRedis.getInstance(); this.implementation = QMSessionManagerRedis.getInstance();
} else { } else {
@ -85,7 +85,7 @@ export class SessionManagerWrapper {
if (this.implementation instanceof QMSessionManagerRedis) { if (this.implementation instanceof QMSessionManagerRedis) {
return this.implementation.getSessionCount(sessionId); return this.implementation.getSessionCount(sessionId);
} else { } else {
return this.implementation.getSessionCount(); return this.implementation.getSessionCount(sessionId ?? '');
} }
} }
@ -110,7 +110,7 @@ export class SessionManagerWrapper {
} }
// Additional methods for memory implementation // Additional methods for memory implementation
isAtCapacity(sessionId: string): boolean { async isAtCapacity(sessionId: string): Promise<boolean> {
if (this.implementation instanceof QMSessionManager) { if (this.implementation instanceof QMSessionManager) {
return this.implementation.isAtCapacity(sessionId); return this.implementation.isAtCapacity(sessionId);
} }

View file

@ -12,6 +12,37 @@ export interface QMSession {
createdAt: Date; createdAt: Date;
} }
export interface QMNewsArticle {
id?: string;
title: string;
publishedDate: string;
content?: string;
summary?: string;
source?: string;
url?: string;
symbols?: string[];
categories?: string[];
sentiment?: { score: string | number; label?: string };
imageUrl?: string;
isMarketMoving?: boolean;
importance?: string;
}
export interface QMInsiderTransaction {
transactionDate: string;
filingDate: string;
insiderName: string;
insiderTitle?: string;
transactionType: string;
shares: string | number;
pricePerShare: string | number;
totalValue: string | number;
sharesOwned: string | number;
ownershipType?: string;
formType?: string;
transactionCode?: string;
}
export interface SymbolSpiderJob { export interface SymbolSpiderJob {
prefix: string | null; // null = root job (A-Z) prefix: string | null; // null = root job (A-Z)
depth: number; // 1=A, 2=AA, 3=AAA, etc. depth: number; // 1=A, 2=AA, 3=AAA, etc.
@ -62,4 +93,4 @@ export interface ExchangeStats {
symbolCount: number; symbolCount: number;
totalMarketCap: number; totalMarketCap: number;
avgMarketCap: number; avgMarketCap: number;
} }

View file

@ -1,3 +1,4 @@
import { at } from '@stock-bot/invariants';
import type { TeHandler } from '../te.handler'; import type { TeHandler } from '../te.handler';
const STALE_DAYS = 30; const STALE_DAYS = 30;
@ -7,16 +8,17 @@ export async function crawlScheduler(this: TeHandler): Promise<{ scheduled: numb
const cutoff = new Date(Date.now() - STALE_DAYS * 24 * 60 * 60 * 1000); const cutoff = new Date(Date.now() - STALE_DAYS * 24 * 60 * 60 * 1000);
const staleUrls = await mongodb?.find('teUrls', { const staleUrls = await mongodb?.find(
$or: [ 'teUrls',
{ lastCrawled: { $exists: false } }, {
{ lastCrawled: { $lt: cutoff } } $or: [{ lastCrawled: { $exists: false } }, { lastCrawled: { $lt: cutoff } }],
], skipReason: { $exists: false },
skipReason: { $exists: false } },
}, { {
sort: { lastCrawled: 1 }, sort: { lastCrawled: 1 },
projection: { url: 1 } projection: { url: 1 },
}); }
);
if (!staleUrls?.length) { if (!staleUrls?.length) {
logger.debug('No stale URLs to schedule'); logger.debug('No stale URLs to schedule');
@ -26,12 +28,16 @@ export async function crawlScheduler(this: TeHandler): Promise<{ scheduled: numb
logger.info(`Scheduling ${staleUrls.length} stale/uncrawled URLs for spidering`); logger.info(`Scheduling ${staleUrls.length} stale/uncrawled URLs for spidering`);
for (let i = 0; i < staleUrls.length; i++) { for (let i = 0; i < staleUrls.length; i++) {
const { url } = staleUrls[i]; const { url } = at(staleUrls, i);
await this.scheduleOperation('te-spider', { url }, { await this.scheduleOperation(
jobId: `spider-${url.replace(/\//g, '-')}`, 'te-spider',
priority: 8, { url },
delay: i * 200 {
}); jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 8,
delay: i * 200,
}
);
} }
return { scheduled: staleUrls.length }; return { scheduled: staleUrls.length };

View file

@ -5,13 +5,18 @@ import type { TeHandler } from '../te.handler';
export async function dataFetch( export async function dataFetch(
this: TeHandler, this: TeHandler,
payload: TeDataFetchPayload, payload: TeDataFetchPayload
): Promise<{ success: boolean; recordCount: number }> { ): Promise<{ success: boolean; recordCount: number }> {
const { logger, mongodb, http, proxy } = this; const { logger, mongodb, http, proxy } = this;
const { teSymbol, url, isInitialFetch } = payload; const { teSymbol, url, isInitialFetch } = payload;
const teDoc = await mongodb?.findOne('teUrls', { url }); const teDoc = await mongodb?.findOne('teUrls', { url });
if (!teDoc?.teChartsDatasource || !teDoc?.teChartToken || !teDoc?.teChart || !teDoc?.teLastUpdate) { if (
!teDoc?.teChartsDatasource ||
!teDoc?.teChartToken ||
!teDoc?.teChart ||
!teDoc?.teLastUpdate
) {
logger.error(`Missing CDN fields for ${teSymbol} (${url})`); logger.error(`Missing CDN fields for ${teSymbol} (${url})`);
return { success: false, recordCount: 0 }; return { success: false, recordCount: 0 };
} }
@ -23,7 +28,9 @@ export async function dataFetch(
} }
// Build CDN URL // Build CDN URL
const cdnUrl = new URL(`${teDoc.teChartsDatasource}/${pathSegment}/${encodeURIComponent(teSymbol.toLowerCase())}`); const cdnUrl = new URL(
`${teDoc.teChartsDatasource}/${pathSegment}/${encodeURIComponent(teSymbol.toLowerCase())}`
);
if (isInitialFetch) { if (isInitialFetch) {
cdnUrl.searchParams.set('span', 'max'); cdnUrl.searchParams.set('span', 'max');
} }
@ -34,7 +41,7 @@ export async function dataFetch(
const response = await http.get(cdnUrl.toString(), { const response = await http.get(cdnUrl.toString(), {
proxy: proxy?.getProxy(), proxy: proxy?.getProxy(),
headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
}); });
if (!response.ok) { if (!response.ok) {
@ -54,61 +61,35 @@ export async function dataFetch(
if (!serie?.data?.length) { if (!serie?.data?.length) {
logger.warn(`No data points decoded for ${teSymbol}`); logger.warn(`No data points decoded for ${teSymbol}`);
await mongodb?.updateOne('teUrls', { url }, { await mongodb?.updateOne(
$set: { 'teUrls',
lastDataFetch: new Date(), { url },
lastDataFetchUpdate: teDoc.teLastUpdate, {
lastDataFetchCount: 0, $set: {
}, lastDataFetch: new Date(),
}); lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 0,
},
}
);
return { success: true, recordCount: 0 }; return { success: true, recordCount: 0 };
} }
// Transform data points: [value, epoch, null, "YYYY-MM-DD"] → { d, v } // Transform data points: [value, epoch, null, "YYYY-MM-DD"] → { d, v }
const dataPoints = serie.data.map(([value, _epoch, _null, date]) => ({ d: date, v: value })); const dataPoints = serie.data.map(([value, _epoch, _null, date]) => ({ d: date, v: value }));
const forecastPoints = serie.forecast?.map(([value, _epoch, _null, date]) => ({ d: date, v: value })) ?? []; const forecastPoints =
serie.forecast?.map(([value, _epoch, _null, date]) => ({ d: date, v: value })) ?? [];
logger.info(`Storing ${dataPoints.length} points + ${forecastPoints.length} forecast for ${teSymbol}`); logger.info(
`Storing ${dataPoints.length} points + ${forecastPoints.length} forecast for ${teSymbol}`
);
if (isInitialFetch) { if (isInitialFetch) {
// Initial: upsert the full document // Initial: upsert the full document
await mongodb?.updateOne('teData', { teSymbol }, { await mongodb?.updateOne(
$set: { 'teData',
teSymbol, { teSymbol },
name: serie.name, {
unit: serie.unit,
source: serie.source,
frequency: serie.frequency,
country: serie.country,
category: serie.category,
data: dataPoints,
forecast: forecastPoints,
lastUpdated: new Date(),
},
$setOnInsert: { createdAt: new Date() },
}, { upsert: true });
} else {
// Update: merge new points into existing data array by date
const existing = await mongodb?.findOne('teData', { teSymbol });
if (existing?.data) {
const dateMap = new Map(existing.data.map((p: any) => [p.d, p.v]));
for (const p of dataPoints) {
dateMap.set(p.d, p.v);
}
const merged = Array.from(dateMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([d, v]) => ({ d, v }));
await mongodb?.updateOne('teData', { teSymbol }, {
$set: {
data: merged,
forecast: forecastPoints,
lastUpdated: new Date(),
},
});
} else {
// No existing doc (shouldn't happen but handle gracefully)
await mongodb?.updateOne('teData', { teSymbol }, {
$set: { $set: {
teSymbol, teSymbol,
name: serie.name, name: serie.name,
@ -122,19 +103,72 @@ export async function dataFetch(
lastUpdated: new Date(), lastUpdated: new Date(),
}, },
$setOnInsert: { createdAt: new Date() }, $setOnInsert: { createdAt: new Date() },
}, { upsert: true }); },
{ upsert: true }
);
} else {
// Update: merge new points into existing data array by date
const existing = await mongodb?.findOne('teData', { teSymbol });
if (existing?.data) {
const dateMap = new Map<string, number>(
(existing.data as { d: string; v: number }[]).map(p => [p.d, p.v])
);
for (const p of dataPoints) {
dateMap.set(p.d, p.v);
}
const merged = Array.from(dateMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([d, v]) => ({ d, v }));
await mongodb?.updateOne(
'teData',
{ teSymbol },
{
$set: {
data: merged,
forecast: forecastPoints,
lastUpdated: new Date(),
},
}
);
} else {
// No existing doc (shouldn't happen but handle gracefully)
await mongodb?.updateOne(
'teData',
{ teSymbol },
{
$set: {
teSymbol,
name: serie.name,
unit: serie.unit,
source: serie.source,
frequency: serie.frequency,
country: serie.country,
category: serie.category,
data: dataPoints,
forecast: forecastPoints,
lastUpdated: new Date(),
},
$setOnInsert: { createdAt: new Date() },
},
{ upsert: true }
);
} }
} }
const totalPoints = dataPoints.length + forecastPoints.length; const totalPoints = dataPoints.length + forecastPoints.length;
await mongodb?.updateOne('teUrls', { url }, { await mongodb?.updateOne(
$set: { 'teUrls',
lastDataFetch: new Date(), { url },
lastDataFetchUpdate: teDoc.teLastUpdate, {
lastDataFetchCount: totalPoints, $set: {
}, lastDataFetch: new Date(),
}); lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: totalPoints,
},
}
);
return { success: true, recordCount: totalPoints }; return { success: true, recordCount: totalPoints };
} }

View file

@ -1,5 +1,5 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config'; import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler'; import type { TeHandler } from '../te.handler';
@ -10,7 +10,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number }
proxy: proxy?.getProxy(), proxy: proxy?.getProxy(),
headers: { headers: {
'User-Agent': getRandomUserAgent(), 'User-Agent': getRandomUserAgent(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5', 'Accept-Language': 'en-US,en;q=0.5',
}, },
}); });
@ -40,6 +40,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number }
logger.info(`Found ${countries.size} countries`); logger.info(`Found ${countries.size} countries`);
const docs = Array.from(countries.entries()).map(([slug, name]) => ({ const docs = Array.from(countries.entries()).map(([slug, name]) => ({
source: 'te',
slug, slug,
name, name,
url: `/${slug}`, url: `/${slug}`,

View file

@ -1,5 +1,5 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config'; import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler'; import type { TeHandler } from '../te.handler';
@ -12,7 +12,7 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
proxy: proxy?.getProxy(), proxy: proxy?.getProxy(),
headers: { headers: {
'User-Agent': getRandomUserAgent(), 'User-Agent': getRandomUserAgent(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5', 'Accept-Language': 'en-US,en;q=0.5',
}, },
}); });
@ -28,20 +28,27 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
$('li.list-group-item.active').each((_, groupEl) => { $('li.list-group-item.active').each((_, groupEl) => {
const group = $(groupEl).text().trim(); const group = $(groupEl).text().trim();
if (SKIP_GROUPS.has(group)) return; if (SKIP_GROUPS.has(group)) {
return;
}
$(groupEl).nextAll('li.list-group-item').each((_, li) => { $(groupEl)
if ($(li).hasClass('active')) return false; // next group .nextAll('li.list-group-item')
const $a = $(li).find('a[href*="/country-list/"]'); .each((_, li) => {
if ($a.length) { if ($(li).hasClass('active')) {
const href = $a.attr('href') || ''; return false;
const name = $a.text().trim(); } // next group
const slug = href.replace('/country-list/', ''); const $a = $(li).find('a[href*="/country-list/"]');
if (slug && name) { if ($a.length) {
indicators.push({ group, slug, name, url: href }); const href = $a.attr('href') || '';
const name = $a.text().trim();
const slug = href.replace('/country-list/', '');
if (slug && name) {
indicators.push({ group, slug, name, url: href });
}
} }
} return undefined;
}); });
}); });
if (!indicators.length) { if (!indicators.length) {
@ -50,7 +57,11 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
logger.info(`Found ${indicators.length} indicators across groups`); logger.info(`Found ${indicators.length} indicators across groups`);
await mongodb?.batchUpsert('teIndicators', indicators, ['slug']); await mongodb?.batchUpsert(
'teIndicators',
indicators.map(indicator => ({ ...indicator, source: 'te' })),
['slug']
);
logger.info(`Upserted ${indicators.length} indicators into teIndicators`); logger.info(`Upserted ${indicators.length} indicators into teIndicators`);
return { count: indicators.length }; return { count: indicators.length };

View file

@ -24,16 +24,16 @@ interface MkDataPoint {
async function fetchMkSerie( async function fetchMkSerie(
handler: TeHandler, handler: TeHandler,
cdnBase: string, cdnBase: string,
params: Record<string, string>, params: Record<string, string>
): Promise<TeMkCdnSerie | null> { ): Promise<TeMkCdnSerie | null> {
const url = new URL(cdnBase); const url = new URL(cdnBase);
for (const [k, v] of Object.entries(params)) { for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v); url.searchParams.set(k, v);
} }
const response = await handler.http.get(url.toString(), { const response = await handler.fetchMarketSeries(url.toString(), {
proxy: handler.proxy?.getProxy(), proxy: handler.proxy?.getProxy(),
headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
}); });
if (!response.ok) { if (!response.ok) {
@ -41,18 +41,31 @@ async function fetchMkSerie(
} }
const rawText = (await response.text()).replaceAll('"', ''); const rawText = (await response.text()).replaceAll('"', '');
if (!rawText.length) return null; if (!rawText.length) {
return null;
}
const decoded = decodeTEData<{ series: TeMkCdnSerie[] }>(rawText, TE_CONFIG.KEY); const decoded = decodeTEData<{ series: TeMkCdnSerie[] }>(rawText, TE_CONFIG.KEY);
return decoded?.series?.[0] ?? null; return decoded?.series?.[0] ?? null;
} }
function toPoints(data: any[]): MkDataPoint[] { function toPoints(data: TeMkCdnSerie['data']): MkDataPoint[] {
return data.map(([t, _c, pc, ac, o, h, l, c]: number[]) => ({ t, o, h, l, c, pc, ac })); return data.map(row => {
if (
row.length < 8 ||
!row.every(
(value, index) => ((index === 2 || index === 3) && value === null) || Number.isFinite(value)
)
) {
throw new Error('Invalid market-data OHLC row');
}
const [t, _c, pc, ac, o, h, l, c] = row;
return { t, o, h, l, c, pc, ac };
});
} }
function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPoint[] { function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPoint[] {
const map = new Map(existing.map((p) => [p.t, p])); const map = new Map(existing.map(p => [p.t, p]));
for (const p of incoming) { for (const p of incoming) {
map.set(p.t, p); map.set(p.t, p);
} }
@ -61,7 +74,7 @@ function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPo
export async function marketDataFetch( export async function marketDataFetch(
this: TeHandler, this: TeHandler,
payload: TeMarketDataFetchPayload, payload: TeMarketDataFetchPayload
): Promise<{ success: boolean; recordCount: number }> { ): Promise<{ success: boolean; recordCount: number }> {
const { logger, mongodb } = this; const { logger, mongodb } = this;
const { teSymbol, symbolType, url, isInitialFetch } = payload; const { teSymbol, symbolType, url, isInitialFetch } = payload;
@ -94,39 +107,62 @@ export async function marketDataFetch(
if (!daily.length && !monthly.length) { if (!daily.length && !monthly.length) {
logger.warn(`No data points decoded for ${teSymbol}:${symbolType}`); logger.warn(`No data points decoded for ${teSymbol}:${symbolType}`);
await mongodb?.updateOne('teUrls', { url }, { await mongodb?.updateOne(
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: 0 }, 'teUrls',
}); { url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 0,
},
}
);
return { success: true, recordCount: 0 }; return { success: true, recordCount: 0 };
} }
logger.info(`Storing ${daily.length} daily + ${monthly.length} monthly OHLC points for ${teSymbol} (${category})`); logger.info(
`Storing ${daily.length} daily + ${monthly.length} monthly OHLC points for ${teSymbol} (${category})`
);
await mongodb?.updateOne('teMarketData', { teSymbol }, { await mongodb?.updateOne(
$set: { 'teMarketData',
teSymbol, { teSymbol },
name: serie?.name, {
fullName: serie?.full_name, $set: {
unit: serie?.unit, teSymbol,
type: serie?.type, name: serie?.name,
category, fullName: serie?.full_name,
symbolType, unit: serie?.unit,
ticker: serie?.ticker, type: serie?.type,
sector: serie?.sector, category,
industry: serie?.industry, symbolType,
frequency: serie?.frequency, ticker: serie?.ticker,
daily, sector: serie?.sector,
monthly, industry: serie?.industry,
lastUpdated: new Date(), frequency: serie?.frequency,
daily,
monthly,
lastUpdated: new Date(),
},
$setOnInsert: { createdAt: new Date() },
}, },
$setOnInsert: { createdAt: new Date() }, { upsert: true }
}, { upsert: true }); );
const totalPoints = daily.length + monthly.length; const totalPoints = daily.length + monthly.length;
await mongodb?.updateOne('teUrls', { url }, { await mongodb?.updateOne(
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: totalPoints }, 'teUrls',
}); { url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: totalPoints,
},
}
);
return { success: true, recordCount: totalPoints }; return { success: true, recordCount: totalPoints };
} }
@ -146,13 +182,25 @@ export async function marketDataFetch(
const merged = existing?.daily ? mergePoints(existing.daily, incoming) : incoming; const merged = existing?.daily ? mergePoints(existing.daily, incoming) : incoming;
await mongodb?.updateOne('teMarketData', { teSymbol }, { await mongodb?.updateOne(
$set: { daily: merged, lastUpdated: new Date() }, 'teMarketData',
}); { teSymbol },
{
$set: { daily: merged, lastUpdated: new Date() },
}
);
await mongodb?.updateOne('teUrls', { url }, { await mongodb?.updateOne(
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: merged.length }, 'teUrls',
}); { url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: merged.length,
},
}
);
return { success: true, recordCount: merged.length }; return { success: true, recordCount: merged.length };
} }

View file

@ -1,13 +1,16 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { at, getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config'; import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler'; import type { TeHandler } from '../te.handler';
export async function spiderUrl(this: TeHandler, payload: { url: string }): Promise<string[] | null> { export async function spiderUrl(
const { logger, mongodb, proxy, http } = this; this: TeHandler,
payload: { url: string }
): Promise<string[] | null> {
const { logger, mongodb, proxy: _proxy, http: _http } = this;
const urlPath = payload?.url || '/'; const urlPath = payload?.url || '/';
const fullUrl = TE_CONFIG.MAIN_URL + urlPath; const fullUrl = TE_CONFIG.MAIN_URL + urlPath;
// 1. Check if already crawled recently (30 days) // 1. Check if already crawled recently (30 days)
const record = await mongodb?.findOne('teUrls', { url: urlPath }); const record = await mongodb?.findOne('teUrls', { url: urlPath });
if (record?.lastCrawled) { if (record?.lastCrawled) {
@ -17,7 +20,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
return null; return null;
} }
} }
// 2. Fetch the page // 2. Fetch the page
logger.info(`Crawling ${fullUrl}`); logger.info(`Crawling ${fullUrl}`);
const html = await fetchPage.call(this, fullUrl); const html = await fetchPage.call(this, fullUrl);
@ -27,86 +30,100 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
await mongodb?.updateOne( await mongodb?.updateOne(
'teUrls', 'teUrls',
{ url: urlPath }, { url: urlPath },
{ {
$set: { $set: {
lastCrawled: new Date(), lastCrawled: new Date(),
foundLinks: 0, foundLinks: 0,
error: true error: true,
} },
}, },
{ upsert: true } { upsert: true }
); );
return null; return null;
} }
// 3. Extract TE data from the HTML // 3. Extract TE data from the HTML
let match = html.match(/var TESymbol = '([^']+)'/); let match = html.match(/var TESymbol = '([^']+)'/);
const teSymbol = match ? match[1] : undefined; const teSymbol = match ? match[1] : undefined;
match = html.match(/TELastUpdate = '([^']+)'/); match = html.match(/TELastUpdate = '([^']+)'/);
const teLastUpdate = match ? match[1] : undefined; const teLastUpdate = match ? match[1] : undefined;
match = html.match(/TEChart = '([^']+)'/); match = html.match(/TEChart = '([^']+)'/);
const teChart = match ? match[1] : undefined; const teChart = match ? match[1] : undefined;
match = html.match(/var TEAlertsName\s*=\s*'([^']+)'/); match = html.match(/var TEAlertsName\s*=\s*'([^']+)'/);
const teAlertsName = match ? match[1] : undefined; const teAlertsName = match ? match[1] : undefined;
// Extract from script tags - these appear after TEChartUrl // Extract from script tags - these appear after TEChartUrl
match = html.match(/TEChartUrl = '([^']+)'/); match = html.match(/TEChartUrl = '([^']+)'/);
const teChartUrl = match ? match[1] : undefined; const teChartUrl = match ? match[1] : undefined;
match = html.match(/TECountry = '([^']+)'/); match = html.match(/TECountry = '([^']+)'/);
const teCountry = match ? match[1] : undefined; const teCountry = match ? match[1] : undefined;
match = html.match(/TECategory = '([^']+)'/); match = html.match(/TECategory = '([^']+)'/);
const teCategory = match ? match[1] : undefined; const teCategory = match ? match[1] : undefined;
match = html.match(/TEType = '([^']+)'/); match = html.match(/TEType = '([^']+)'/);
const teType = match ? match[1] : undefined; const teType = match ? match[1] : undefined;
match = html.match(/TEFrequency = '([^']+)'/); match = html.match(/TEFrequency = '([^']+)'/);
const teFrequency = match ? match[1] : undefined; const teFrequency = match ? match[1] : undefined;
// Extract array data // Extract array data
match = html.match(/TEForecast\s*=\s*\[([^\]]+)\]/); match = html.match(/TEForecast\s*=\s*\[([^\]]+)\]/);
const teForecast = match ? JSON.parse('[' + match[1] + ']') : undefined; const teForecast = match ? JSON.parse('[' + match[1] + ']') : undefined;
// Extract JSON metadata - use a more flexible regex // Extract JSON metadata - use a more flexible regex
match = html.match(/TEChartsMeta = (\[[\s\S]*?\]);/); match = html.match(/TEChartsMeta = (\[[\s\S]*?\]);/);
const teChartsMeta = match ? (() => { const teChartsMeta = match
try { ? (() => {
return JSON.parse(match[1]); try {
} catch (e) { return JSON.parse(at(match, 1));
logger.warn('Failed to parse TEChartsMeta:', e); } catch (e) {
return undefined; logger.warn('Failed to parse TEChartsMeta', { error: e });
} return undefined;
})() : undefined; }
})()
: undefined;
// Extract symbol data // Extract symbol data
match = html.match(/symbol = '([^']+)'/); match = html.match(/symbol = '([^']+)'/);
const symbol = match ? match[1] : undefined; const symbol = match ? match[1] : undefined;
match = html.match(/symbolType = '([^']+)'/); match = html.match(/symbolType = '([^']+)'/);
const symbolType = match ? match[1] : undefined; const symbolType = match ? match[1] : undefined;
// TEChartsDatasource is the CDN URL for chart data // TEChartsDatasource is the CDN URL for chart data
match = html.match(/; var TEChartsDatasource = '([^']+)'/); match = html.match(/; var TEChartsDatasource = '([^']+)'/);
const teChartsDatasource = match ? match[1] : undefined; const teChartsDatasource = match ? match[1] : undefined;
match = html.match(/; var TEChartsToken = '([^']+)'/); match = html.match(/; var TEChartsToken = '([^']+)'/);
const teChartToken = match ? match[1] : undefined; const teChartToken = match ? match[1] : undefined;
// Log if we found any TE data // Log if we found any TE data
const foundData = teSymbol || teLastUpdate || teChartUrl || teChartsDatasource || const foundData =
teChartToken || teChart || teAlertsName || teCountry || teSymbol ||
teCategory || teType || teFrequency || teForecast || teLastUpdate ||
teChartsMeta || symbol || symbolType; teChartUrl ||
teChartsDatasource ||
teChartToken ||
teChart ||
teAlertsName ||
teCountry ||
teCategory ||
teType ||
teFrequency ||
teForecast ||
teChartsMeta ||
symbol ||
symbolType;
if (foundData) { if (foundData) {
logger.debug('Found TE data:', { logger.debug('Found TE data:', {
teSymbol, teSymbol,
teLastUpdate, teLastUpdate,
teChart, teChart,
teAlertsName, teAlertsName,
teChartUrl, teChartUrl,
@ -119,32 +136,45 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
symbol, symbol,
symbolType, symbolType,
teChartsDatasource, teChartsDatasource,
teChartToken teChartToken,
}); });
} }
// 4. Extract all links // 4. Extract all links
const $ = cheerio.load(html); const $ = cheerio.load(html);
const foundUrls = new Set<string>(); const foundUrls = new Set<string>();
// Add some seed URLs if this is the root page // Add some seed URLs if this is the root page
if (urlPath === '/') { if (urlPath === '/') {
const seedUrls = [ const seedUrls = [
'/united-states', '/china', '/eurozone', '/japan', '/united-kingdom', '/united-states',
'/indicators', '/calendar', '/forecasts', '/countries', '/china',
'/gdp', '/inflation', '/unemployment', '/interest-rate', '/eurozone',
'/stocks', '/bonds', '/commodity', '/currency' '/japan',
'/united-kingdom',
'/indicators',
'/calendar',
'/forecasts',
'/countries',
'/gdp',
'/inflation',
'/unemployment',
'/interest-rate',
'/stocks',
'/bonds',
'/commodity',
'/currency',
]; ];
seedUrls.forEach(url => foundUrls.add(url)); seedUrls.forEach(url => foundUrls.add(url));
} }
// Extract links from the page // Extract links from the page
$('a[href]').each((_, element) => { $('a[href]').each((_, element) => {
const href = $(element).attr('href'); const href = $(element).attr('href');
if (!href) { if (!href) {
return; return;
} }
// Convert to absolute path // Convert to absolute path
let path: string; let path: string;
if (href.startsWith('/')) { if (href.startsWith('/')) {
@ -158,27 +188,27 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
} else { } else {
return; // Skip external links return; // Skip external links
} }
// Clean the path // Clean the path
path = path.split('?')[0].split('#')[0]; path = at(at(path.split('?'), 0).split('#'), 0);
// Basic filtering // Basic filtering
if (shouldCrawl(path)) { if (shouldCrawl(path)) {
foundUrls.add(path); foundUrls.add(path);
} }
}); });
const urls = Array.from(foundUrls); const urls = Array.from(foundUrls);
logger.info(`Found ${urls.length} URLs on ${urlPath}`); logger.info(`Found ${urls.length} URLs on ${urlPath}`);
// 5. Update database // 5. Update database
// Mark current URL as crawled with TE data if found // Mark current URL as crawled with TE data if found
const updateData: any = { const updateData: Record<string, unknown> = {
lastCrawled: new Date(), lastCrawled: new Date(),
foundLinks: urls.length, foundLinks: urls.length,
error: false error: false,
}; };
// Add TE data if found // Add TE data if found
if (teSymbol) { if (teSymbol) {
updateData.teSymbol = teSymbol; updateData.teSymbol = teSymbol;
@ -193,7 +223,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
updateData.teAlertsName = teAlertsName; updateData.teAlertsName = teAlertsName;
} }
if (teChartUrl) { if (teChartUrl) {
updateData.teChartUrl = teChartUrl; // Full chart URL with PNG updateData.teChartUrl = teChartUrl; // Full chart URL with PNG
} }
if (teCountry) { if (teCountry) {
updateData.teCountry = teCountry; updateData.teCountry = teCountry;
@ -220,31 +250,26 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
updateData.symbolType = symbolType; updateData.symbolType = symbolType;
} }
if (teChartsDatasource) { if (teChartsDatasource) {
updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data
} }
if (teChartToken) { if (teChartToken) {
updateData.teChartToken = teChartToken; updateData.teChartToken = teChartToken;
} }
await mongodb?.updateOne( await mongodb?.updateOne('teUrls', { url: urlPath }, { $set: updateData }, { upsert: true });
'teUrls',
{ url: urlPath },
{ $set: updateData },
{ upsert: true }
);
// Insert new URLs (without lastCrawled so they'll be picked up for crawling) // Insert new URLs (without lastCrawled so they'll be picked up for crawling)
const newUrls: string[] = []; const newUrls: string[] = [];
for (const url of urls) { for (const url of urls) {
const result = await mongodb?.updateOne( const result = await mongodb?.updateOne(
'teUrls', 'teUrls',
{ url }, { url },
{ {
$setOnInsert: { $setOnInsert: {
url, url,
createdAt: new Date(), createdAt: new Date(),
source: urlPath source: urlPath,
} },
}, },
{ upsert: true } { upsert: true }
); );
@ -253,55 +278,58 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
newUrls.push(url); newUrls.push(url);
} }
} }
// 6. Schedule individual jobs for each new URL // 6. Schedule individual jobs for each new URL
logger.info(`Scheduling ${newUrls.length} new URLs for crawling`); logger.info(`Scheduling ${newUrls.length} new URLs for crawling`);
for (const url of newUrls) { for (const url of newUrls) {
await this.scheduleOperation('te-spider', { url }, { await this.scheduleOperation(
jobId: `spider-${url.replace(/\//g, '-')}`, 'te-spider',
priority: 10, { url },
delay: Math.floor(Math.random() * 10000) // Spread requests over 10 seconds {
}); jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 10,
delay: Math.floor(Math.random() * 10000), // Spread requests over 10 seconds
}
);
} }
return urls; return urls;
} }
// Simple fetch with retry using http service with proxy // Simple fetch with retry using http service with proxy
async function fetchPage(this: TeHandler, url: string): Promise<string | null> { async function fetchPage(this: TeHandler, url: string): Promise<string | null> {
const { http, proxy, logger } = this; const { http, proxy, logger } = this;
for (let attempt = 1; attempt <= 3; attempt++) { for (let attempt = 1; attempt <= 3; attempt++) {
try { try {
// Get a proxy URL for this request // Get a proxy URL for this request
const proxyUrl = proxy?.getProxy(); const proxyUrl = proxy?.getProxy();
const response = await http.get(url, { const response = await http.get(url, {
proxy: proxyUrl, proxy: proxyUrl,
headers: { headers: {
'User-Agent': getRandomUserAgent(), 'User-Agent': getRandomUserAgent(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5', 'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br', 'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive', Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1', 'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0' 'Cache-Control': 'max-age=0',
} },
}); });
if (response.ok) { if (response.ok) {
return await response.text(); return await response.text();
} }
// If not OK, log the status // If not OK, log the status
logger.error(`HTTP ${response.status} for ${url}`); logger.error(`HTTP ${response.status} for ${url}`);
} catch (error) { } catch (error) {
logger.error(`Attempt ${attempt}/3 failed for ${url}:`, error); logger.error(`Attempt ${attempt}/3 failed for ${url}:`, error);
if (attempt === 3) { if (attempt === 3) {
return null; return null;
} }
// Wait before retrying (exponential backoff) // Wait before retrying (exponential backoff)
await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
} }
@ -315,18 +343,20 @@ function shouldCrawl(url: string): boolean {
if (!url || url === '/') { if (!url || url === '/') {
return false; return false;
} }
// Skip static files // Skip static files
if (/\.(pdf|jpg|jpeg|png|gif|svg|css|js|ico|xml|rss|json|txt|csv|xlsx|xls|doc|docx|zip)$/i.test(url)) { if (
/\.(pdf|jpg|jpeg|png|gif|svg|css|js|ico|xml|rss|json|txt|csv|xlsx|xls|doc|docx|zip)$/i.test(url)
) {
return false; return false;
} }
// Skip deep URLs (more than 4 levels) // Skip deep URLs (more than 4 levels)
const depth = (url.match(/\//g) || []).length; const depth = (url.match(/\//g) || []).length;
if (depth > 4) { if (depth > 4) {
return false; return false;
} }
// Skip common non-content pages // Skip common non-content pages
const skipPatterns = [ const skipPatterns = [
/\/api\//, /\/api\//,
@ -343,13 +373,13 @@ function shouldCrawl(url: string): boolean {
/\/rss\//, /\/rss\//,
/#/, /#/,
]; ];
for (const pattern of skipPatterns) { for (const pattern of skipPatterns) {
if (pattern.test(url)) { if (pattern.test(url)) {
return false; return false;
} }
} }
// Accept everything else // Accept everything else
return true; return true;
} }

View file

@ -1,79 +1,79 @@
// Define types and interfaces for the TE handler here // Define types and interfaces for the TE handler here
export interface TeData { export interface TeData {
id: string; id: string;
name: string; name: string;
// Add more fields as needed // Add more fields as needed
} }
export interface TeResponse { export interface TeResponse {
data: TeData[]; data: TeData[];
status: string; status: string;
timestamp: Date; timestamp: Date;
} }
export interface TeCountry { export interface TeCountry {
name: string; name: string;
code?: string; code?: string;
region?: string; region?: string;
url?: string; url?: string;
updated_at: Date; updated_at: Date;
created_at?: Date; created_at?: Date;
} }
export interface TeDataFetchPayload { export interface TeDataFetchPayload {
teSymbol: string; teSymbol: string;
url: string; url: string;
isInitialFetch: boolean; isInitialFetch: boolean;
} }
export interface TeMarketDataFetchPayload { export interface TeMarketDataFetchPayload {
teSymbol: string; teSymbol: string;
symbolType: string; symbolType: string;
url: string; url: string;
isInitialFetch: boolean; isInitialFetch: boolean;
} }
/** MK/TV CDN series structure (flat, no nested serie wrapper) */ /** MK/TV CDN series structure (flat, no nested serie wrapper) */
export interface TeMkCdnSerie { export interface TeMkCdnSerie {
symbol: string; symbol: string;
name: string; name: string;
shortname: string; shortname: string;
full_name: string; full_name: string;
unit: string; unit: string;
type: string; type: string;
ticker: string; ticker: string;
description: string; description: string;
sector: string; sector: string;
industry: string; industry: string;
frequency: string; frequency: string;
/** Each point: [epoch, value, pctChange, absChange] */ /** OHLC endpoint: epoch, close, changes, open, high, low, close. */
data: Array<[number, number, number | null, number | null]>; data: Array<[number, number, number | null, number | null, number, number, number, number]>;
} }
/** Decoded CDN response wrapper */ /** Decoded CDN response wrapper */
export interface TeCdnResponse { export interface TeCdnResponse {
series: Array<{ series: Array<{
serie: TeCdnSerie; serie: TeCdnSerie;
}>; }>;
span: string; span: string;
agr: string; agr: string;
frequency: string; frequency: string;
} }
/** Serie metadata + data from CDN */ /** Serie metadata + data from CDN */
export interface TeCdnSerie { export interface TeCdnSerie {
s: string; s: string;
name: string; name: string;
shortname: string; shortname: string;
unit: string; unit: string;
type: string; type: string;
source: string; source: string;
frequency: string; frequency: string;
country: string; country: string;
category: string; category: string;
/** Each point: [value, unix_epoch, null, "YYYY-MM-DD"] */ /** Each point: [value, unix_epoch, null, "YYYY-MM-DD"] */
data: Array<[number, number, null, string]>; data: Array<[number, number, null, string]>;
forecast?: Array<[number, number, null, string]>; forecast?: Array<[number, number, null, string]>;
projection?: Array<[number, number, null, string]>; projection?: Array<[number, number, null, string]>;
} }

View file

@ -1,24 +1,35 @@
import { import type { CreateIndexesOptions, IndexSpecification } from 'mongodb';
BaseHandler, import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
Handler, import type { IServiceContainer } from '@stock-bot/services';
Operation, import { resolveIngestionServices } from '../../types';
ScheduledOperation
} from '@stock-bot/handlers';
import type { DataIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types';
import { crawlScheduler, dataFetch, dataScheduler, fetchCountries, fetchIndicators, marketDataFetch, marketDataScheduler, spiderUrl } from './actions'; import {
crawlScheduler,
dataFetch,
dataScheduler,
fetchCountries,
fetchIndicators,
marketDataFetch,
marketDataScheduler,
spiderUrl,
} from './actions';
@Handler('te') @Handler('te')
export class TeHandler extends BaseHandler<DataIngestionServices> { export class TeHandler extends BaseHandler<DataIngestionServices> {
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); super(resolveIngestionServices(services, 'te'));
}
fetchMarketSeries(...args: Parameters<typeof this.http.get>) {
return this.http.get(...args);
} }
/** /**
* Initialize handler and create necessary indexes * Initialize handler and create necessary indexes
*/ */
async onInit(): Promise<void> { override async onInit(): Promise<void> {
this.logger.info('Initializing TeHandler and creating indexes'); this.logger.info('Initializing TeHandler and creating indexes');
if (!this.mongodb) { if (!this.mongodb) {
this.logger.warn('MongoDB not available, skipping index creation'); this.logger.warn('MongoDB not available, skipping index creation');
return; return;
@ -26,49 +37,49 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
try { try {
// Create indexes for teUrls collection // Create indexes for teUrls collection
const indexes = [ const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
// Compound index for finding URLs to crawl // Compound index for finding URLs to crawl
{ {
indexSpec: { lastCrawled: 1, url: 1 }, indexSpec: { lastCrawled: 1, url: 1 },
options: { options: {
name: 'crawl_status_idx', name: 'crawl_status_idx',
background: true background: true,
} },
}, },
// Unique index on URL to prevent duplicates // Unique index on URL to prevent duplicates
{ {
indexSpec: { url: 1 }, indexSpec: { url: 1 },
options: { options: {
name: 'url_unique_idx', name: 'url_unique_idx',
unique: true, unique: true,
background: true background: true,
} },
}, },
// Index for finding URLs by symbol // Index for finding URLs by symbol
{ {
indexSpec: { teSymbol: 1 }, indexSpec: { teSymbol: 1 },
options: { options: {
name: 'symbol_idx', name: 'symbol_idx',
sparse: true, sparse: true,
background: true background: true,
} },
}, },
// Index for skip reason filtering // Index for skip reason filtering
{ {
indexSpec: { skipReason: 1 }, indexSpec: { skipReason: 1 },
options: { options: {
name: 'skip_reason_idx', name: 'skip_reason_idx',
sparse: true, sparse: true,
background: true background: true,
} },
}, },
// Compound index for efficient batch queries // Compound index for efficient batch queries
{ {
indexSpec: { lastCrawled: 1, skipReason: 1 }, indexSpec: { lastCrawled: 1, skipReason: 1 },
options: { options: {
name: 'batch_query_idx', name: 'batch_query_idx',
background: true background: true,
} },
}, },
// Index for finding URLs with chart data // Index for finding URLs with chart data
{ {
@ -76,8 +87,8 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
options: { options: {
name: 'chart_url_idx', name: 'chart_url_idx',
sparse: true, sparse: true,
background: true background: true,
} },
}, },
// Index for data-scheduler: filter by teType + sort by lastDataFetch // Index for data-scheduler: filter by teType + sort by lastDataFetch
{ {
@ -85,8 +96,8 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
options: { options: {
name: 'data_fetch_schedule_idx', name: 'data_fetch_schedule_idx',
background: true, background: true,
} },
} },
]; ];
for (const index of indexes) { for (const index of indexes) {
@ -95,12 +106,12 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
this.logger.info(`Created/verified index: ${index.options.name}`); this.logger.info(`Created/verified index: ${index.options.name}`);
} catch (error) { } catch (error) {
// Index might already exist, that's OK // Index might already exist, that's OK
this.logger.debug(`Index ${index.options.name} may already exist:`, error); this.logger.debug(`Index ${index.options.name} may already exist:`, { error });
} }
} }
// Indexes for teData collection (one doc per symbol with data array) // Indexes for teData collection (one doc per symbol with data array)
const teDataIndexes = [ const teDataIndexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
{ {
indexSpec: { teSymbol: 1 }, indexSpec: { teSymbol: 1 },
options: { options: {
@ -123,12 +134,15 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
await this.mongodb.createIndex('teData', index.indexSpec, index.options); await this.mongodb.createIndex('teData', index.indexSpec, index.options);
this.logger.info(`Created/verified teData index: ${index.options.name}`); this.logger.info(`Created/verified teData index: ${index.options.name}`);
} catch (error) { } catch (error) {
this.logger.debug(`teData index ${index.options.name} may already exist:`, error); this.logger.debug(`teData index ${index.options.name} may already exist:`, { error });
} }
} }
// Indexes for teMarketData collection // Indexes for teMarketData collection
const teMarketDataIndexes = [ const teMarketDataIndexes: {
indexSpec: IndexSpecification;
options: CreateIndexesOptions;
}[] = [
{ {
indexSpec: { teSymbol: 1 }, indexSpec: { teSymbol: 1 },
options: { options: {
@ -151,14 +165,15 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
await this.mongodb.createIndex('teMarketData', index.indexSpec, index.options); await this.mongodb.createIndex('teMarketData', index.indexSpec, index.options);
this.logger.info(`Created/verified teMarketData index: ${index.options.name}`); this.logger.info(`Created/verified teMarketData index: ${index.options.name}`);
} catch (error) { } catch (error) {
this.logger.debug(`teMarketData index ${index.options.name} may already exist:`, error); this.logger.debug(`teMarketData index ${index.options.name} may already exist:`, {
error,
});
} }
} }
// Check collection stats // Check collection stats
const count = await this.mongodb.countDocuments('teUrls', {}); const count = await this.mongodb.countDocuments('teUrls', {});
this.logger.info(`TeUrls collection has ${count} documents`); this.logger.info(`TeUrls collection has ${count} documents`);
} catch (error) { } catch (error) {
this.logger.error('Error creating indexes for TeHandler:', error); this.logger.error('Error creating indexes for TeHandler:', error);
// Don't throw - allow handler to continue even if indexes fail // Don't throw - allow handler to continue even if indexes fail
@ -212,4 +227,4 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
@Operation('te-market-data-fetch') @Operation('te-market-data-fetch')
marketDataFetch = marketDataFetch; marketDataFetch = marketDataFetch;
} }

View file

@ -1,155 +1,171 @@
import type { TradingViewHandler } from '../tradingview.handler'; import { at } from '@stock-bot/utils';
import { TradingViewExchange } from '../shared/types'; import { TRADINGVIEW_CONFIG } from '../shared/config';
import { TRADINGVIEW_CONFIG } from '../shared/config'; import { type TradingViewExchange } from '../shared/types';
import type { TradingViewHandler } from '../tradingview.handler';
export async function fetchExchanges(handler: TradingViewHandler): Promise<TradingViewExchange[] | null> {
const { logger, mongodb } = handler; export async function fetchExchanges(
handler: TradingViewHandler
if (!mongodb?.db) { ): Promise<TradingViewExchange[] | null> {
logger.error('MongoDB not available'); const { logger, mongodb } = handler;
return null;
} if (!mongodb) {
logger.error('MongoDB not available');
const db = mongodb.db; return null;
}
try {
// 1. Fetch the HTML page const db = mongodb.getDatabase();
const response = await fetch(TRADINGVIEW_CONFIG.DATA_COVERAGE_URL, {
headers: { try {
'User-Agent': TRADINGVIEW_CONFIG.USER_AGENT, // 1. Fetch the HTML page
}, const response = await fetch(TRADINGVIEW_CONFIG.DATA_COVERAGE_URL, {
}); headers: {
'User-Agent': TRADINGVIEW_CONFIG.USER_AGENT,
logger.debug('Response status:', { },
status: response.status, });
statusText: response.statusText,
url: response.url logger.debug('Response status:', {
}); status: response.status,
statusText: response.statusText,
if (!response.ok) { url: response.url,
throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`); });
}
if (!response.ok) {
const html = await response.text(); throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`);
}
logger.info('Fetched HTML length:', { length: html.length });
const html = await response.text();
// Save HTML for debugging
if (process.env.DEBUG_HTML) { logger.info('Fetched HTML length:', { length: html.length });
const fs = await import('fs/promises');
await fs.writeFile('/tmp/tradingview-data-coverage.html', html); // Save HTML for debugging
logger.info('Saved HTML to /tmp/tradingview-data-coverage.html'); if (process.env.DEBUG_HTML) {
} const fs = await import('fs/promises');
await fs.writeFile('/tmp/tradingview-data-coverage.html', html);
// 2. Parse HTML to extract exchange data from the table logger.info('Saved HTML to /tmp/tradingview-data-coverage.html');
const exchanges: TradingViewExchange[] = []; }
// Match table rows containing exchange data // 2. Parse HTML to extract exchange data from the table
const rowRegex = /<tr[^>]*class="row-qJcpoITA[^"]*"[^>]*>[\s\S]*?<\/tr>/g; const exchanges: TradingViewExchange[] = [];
const rows = html.match(rowRegex) || [];
// Match table rows containing exchange data
logger.debug('Found table rows:', { count: rows.length }); const rowRegex = /<tr[^>]*class="row-qJcpoITA[^"]*"[^>]*>[\s\S]*?<\/tr>/g;
const rows = html.match(rowRegex) || [];
for (const row of rows) {
try { logger.debug('Found table rows:', { count: rows.length });
// Extract exchange ID
const exchangeMatch = row.match(/alt="([^"]+)"/); for (const row of rows) {
const exchangeNameMatch = row.match(/<span[^>]*class="exchangeName-qJcpoITA"[^>]*>([^<]+)<\/span>/); try {
const descriptionMatch = row.match(/<span[^>]*class="exchangeDescName-qJcpoITA"[^>]*>([^<]+)<\/span>/); // Extract exchange ID
const countryFlagMatch = row.match(/src="https:\/\/s3-symbol-logo\.tradingview\.com\/country\/([^.]+)\.svg"/); const exchangeMatch = row.match(/alt="([^"]+)"/);
const countryNameMatch = row.match(/<img[^>]*class="[^"]*exchangeCountryFlag[^"]*"[^>]*\/>([^<]+)<\/span>/); const exchangeNameMatch = row.match(
/<span[^>]*class="exchangeName-qJcpoITA"[^>]*>([^<]+)<\/span>/
// Extract data types from badges );
const badgeMatches = row.matchAll(/<span[^>]*class="badge-PlSmolIm[^"]*"[^>]*>[\s\S]*?<span[^>]*class="content-PlSmolIm"[^>]*>([^<]+)<\/span>/g); const descriptionMatch = row.match(
const dataTypes: string[] = []; /<span[^>]*class="exchangeDescName-qJcpoITA"[^>]*>([^<]+)<\/span>/
for (const match of badgeMatches) { );
dataTypes.push(match[1].toLowerCase()); const countryFlagMatch = row.match(
} /src="https:\/\/s3-symbol-logo\.tradingview\.com\/country\/([^.]+)\.svg"/
);
if (exchangeNameMatch && descriptionMatch && countryFlagMatch) { const countryNameMatch = row.match(
const exchange: TradingViewExchange = { /<img[^>]*class="[^"]*exchangeCountryFlag[^"]*"[^>]*\/>([^<]+)<\/span>/
exchange: descriptionMatch[1].toLowerCase().replace(/\s+/g, '_').replace(/[()]/g, ''), );
name: exchangeNameMatch[1],
description: descriptionMatch[1], // Extract data types from badges
dataType: dataTypes, const badgeMatches = row.matchAll(
countryCode: countryFlagMatch[1].toUpperCase(), /<span[^>]*class="badge-PlSmolIm[^"]*"[^>]*>[\s\S]*?<span[^>]*class="content-PlSmolIm"[^>]*>([^<]+)<\/span>/g
countryName: '', // Will be filled from alt text or other sources );
}; const dataTypes: string[] = [];
for (const match of badgeMatches) {
// Try to extract country name dataTypes.push(at(match, 1).toLowerCase());
if (countryNameMatch) { }
exchange.countryName = countryNameMatch[1].trim();
} else if (exchangeMatch) { if (exchangeNameMatch && descriptionMatch && countryFlagMatch) {
// Use alt text to extract country name const exchange: TradingViewExchange = {
const parts = exchangeMatch[1].split(' '); exchange: at(descriptionMatch, 1)
if (parts.length > 1) { .toLowerCase()
exchange.countryName = parts[0]; .replace(/\s+/g, '_')
} .replace(/[()]/g, ''),
} name: at(exchangeNameMatch, 1),
description: at(descriptionMatch, 1),
exchanges.push(exchange); dataType: dataTypes,
} countryCode: at(countryFlagMatch, 1).toUpperCase(),
} catch (e) { countryName: '', // Will be filled from alt text or other sources
logger.debug('Failed to parse row', { error: e }); };
}
} // Try to extract country name
if (countryNameMatch) {
if (exchanges.length === 0) { exchange.countryName = at(countryNameMatch, 1).trim();
throw new Error('No exchanges found in HTML'); } else if (exchangeMatch) {
} // Use alt text to extract country name
const parts = at(exchangeMatch, 1).split(' ');
logger.info('Extracted exchanges from HTML', { count: exchanges.length }); if (parts.length > 1) {
exchange.countryName = at(parts, 0);
// Batch update tvExchanges collection }
try { }
const batchOps = exchanges.map(exchange => ({
updateOne: { exchanges.push(exchange);
filter: { exchange: exchange.exchange }, }
update: { } catch (e) {
$set: { logger.debug('Failed to parse row', { error: e });
...exchange, }
updated_at: new Date(), }
},
$setOnInsert: { if (exchanges.length === 0) {
created_at: new Date(), throw new Error('No exchanges found in HTML');
}, }
},
upsert: true, logger.info('Extracted exchanges from HTML', { count: exchanges.length });
},
})); // Batch update tvExchanges collection
try {
if (batchOps.length > 0) { const batchOps = exchanges.map(exchange => ({
await db.collection('tvExchanges').bulkWrite(batchOps); updateOne: {
} filter: { exchange: exchange.exchange },
update: {
logger.info('TradingView exchanges saved to MongoDB'); $set: {
} catch (dbError) { ...exchange,
logger.warn('Failed to save exchanges to MongoDB', { error: dbError }); updated_at: new Date(),
} },
$setOnInsert: {
logger.info('TradingView exchanges fetched', { created_at: new Date(),
count: exchanges.length, },
byType: groupExchangesByType(exchanges), },
}); upsert: true,
},
return exchanges; }));
} catch (error) {
logger.error('Failed to fetch TradingView exchanges', { if (batchOps.length > 0) {
error: error instanceof Error ? error.message : String(error), await db.collection('tvExchanges').bulkWrite(batchOps);
stack: error instanceof Error ? error.stack : undefined, }
});
return null; logger.info('TradingView exchanges saved to MongoDB');
} } catch (dbError) {
} logger.warn('Failed to save exchanges to MongoDB', { error: dbError });
}
function groupExchangesByType(exchanges: TradingViewExchange[]) {
const groups: Record<string, number> = {}; logger.info('TradingView exchanges fetched', {
count: exchanges.length,
for (const exchange of exchanges) { byType: groupExchangesByType(exchanges),
for (const type of exchange.dataType) { });
groups[type] = (groups[type] || 0) + 1;
} return exchanges;
} } catch (error) {
logger.error('Failed to fetch TradingView exchanges', {
return groups; error: error instanceof Error ? error.message : String(error),
} stack: error instanceof Error ? error.stack : undefined,
});
return null;
}
}
function groupExchangesByType(exchanges: TradingViewExchange[]) {
const groups: Record<string, number> = {};
for (const exchange of exchanges) {
for (const type of exchange.dataType) {
groups[type] = (groups[type] || 0) + 1;
}
}
return groups;
}

View file

@ -1,36 +1,36 @@
export interface TradingViewExchange { export interface TradingViewExchange {
exchange: string; exchange: string;
name: string; name: string;
description: string; description: string;
dataType: string[]; dataType: string[];
countryCode: string; // All caps countryCode: string; // All caps
countryName: string; countryName: string;
popularityRank?: number; popularityRank?: number;
} }
// Raw data from TradingView // Raw data from TradingView
export interface TradingViewRawExchange { export interface TradingViewRawExchange {
text_id?: string; text_id?: string;
exchange: string; exchange: string;
provider_id?: string | null; provider_id?: string | null;
name: string; name: string;
description: string; description: string;
data_type: string[]; data_type: string[];
country: string; country: string;
country_name: string; country_name: string;
popularity_rank?: number; popularity_rank?: number;
[key: string]: any; // Other fields we don't need [key: string]: unknown; // Other fields we don't need
} }
export interface ExchangeGroup { export interface ExchangeGroup {
name: string; name: string;
exchanges: TradingViewRawExchange[]; exchanges: TradingViewRawExchange[];
} }
export interface TradingViewData { export interface TradingViewData {
locale: string; locale: string;
user: any; user: unknown;
is_authenticated: boolean; is_authenticated: boolean;
exchanges: ExchangeGroup[]; exchanges: ExchangeGroup[];
currency: string; currency: string;
} }

View file

@ -1,31 +1,27 @@
import { import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
BaseHandler, import type { IServiceContainer } from '@stock-bot/services';
Disabled, import { resolveIngestionServices } from '../../types';
Handler, import { fetchExchanges } from './actions';
Operation,
ScheduledOperation, @Disabled()
} from '@stock-bot/handlers'; @Handler('tradingview')
import { fetchExchanges } from './actions'; export class TradingViewHandler extends BaseHandler {
constructor(services: IServiceContainer) {
@Disabled() super(resolveIngestionServices(services, 'tradingview'));
@Handler('tradingview') }
export class TradingViewHandler extends BaseHandler {
constructor(services: any) { @Operation('fetch-exchanges')
super(services); async fetchExchanges(): Promise<unknown[] | null> {
} return fetchExchanges(this);
}
@Operation('fetch-exchanges')
async fetchExchanges(): Promise<unknown[] | null> { @ScheduledOperation('tradingview-exchanges', '0 0 * * 0', {
return fetchExchanges(this); priority: 5,
} description: 'Fetch and update TradingView exchanges data',
immediately: false,
@ScheduledOperation('tradingview-exchanges', '0 0 * * 0', { })
priority: 5, @Disabled()
description: 'Fetch and update TradingView exchanges data', async scheduledFetchExchanges(): Promise<unknown> {
immediately: false, return this.fetchExchanges();
}) }
@Disabled() }
async scheduledFetchExchanges(): Promise<unknown> {
return this.fetchExchanges();
}
}

View file

@ -1,16 +1,27 @@
import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { existsSync, mkdirSync, rmSync, readdirSync, readFileSync } from 'fs';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import * as cheerio from 'cheerio';
import { defined } from '@stock-bot/invariants';
import { getRandomUserAgent } from '@stock-bot/utils';
import type { TtHandler } from '../tt.handler'; import type { TtHandler } from '../tt.handler';
const BASE_URL = 'https://www.turtletrader.com'; const BASE_URL = 'https://www.turtletrader.com';
const TMP_DIR = '/tmp/tt'; const TMP_DIR = '/tmp/tt';
const MONTH_MAP: Record<string, string> = { const _MONTH_MAP: Record<string, string> = {
F: '01', G: '02', H: '03', J: '04', K: '05', M: '06', F: '01',
N: '07', Q: '08', U: '09', V: '10', X: '11', Z: '12', G: '02',
H: '03',
J: '04',
K: '05',
M: '06',
N: '07',
Q: '08',
U: '09',
V: '10',
X: '11',
Z: '12',
}; };
function parseDate(yymmdd: string): string { function parseDate(yymmdd: string): string {
@ -40,7 +51,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
$('a[href$=".zip"]').each((_, el) => { $('a[href$=".zip"]').each((_, el) => {
const href = $(el).attr('href') || ''; const href = $(el).attr('href') || '';
const name = $(el).text().trim(); const name = $(el).text().trim();
if (href) zipLinks.push({ href, name }); if (href) {
zipLinks.push({ href, name });
}
}); });
if (!zipLinks.length) { if (!zipLinks.length) {
@ -60,7 +73,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
try { try {
for (const { href, name } of zipLinks) { for (const { href, name } of zipLinks) {
const zipUrl = href.startsWith('http') ? href : `${BASE_URL}${href}`; const zipUrl = href.startsWith('http') ? href : `${BASE_URL}${href}`;
const symbol = href.split('/').pop()!.replace('.zip', '').toUpperCase(); const symbol = defined(href.split('/').pop()).replace('.zip', '').toUpperCase();
const zipPath = join(TMP_DIR, `${symbol}.zip`); const zipPath = join(TMP_DIR, `${symbol}.zip`);
const extractDir = join(TMP_DIR, symbol); const extractDir = join(TMP_DIR, symbol);
@ -84,7 +97,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
// Parse each txt file // Parse each txt file
const files = readdirSync(extractDir).filter(f => f.endsWith('.txt')); const files = readdirSync(extractDir).filter(f => f.endsWith('.txt'));
const records: any[] = []; const records = [];
for (const file of files) { for (const file of files) {
const contract = file.replace('.txt', ''); const contract = file.replace('.txt', '');
@ -101,14 +114,27 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
for (const line of content.split('\n')) { for (const line of content.split('\n')) {
const trimmed = line.trim(); const trimmed = line.trim();
if (!trimmed) continue; if (!trimmed) {
continue;
}
const parts = trimmed.split(','); const parts = trimmed.split(',');
if (parts.length < 7) continue; if (parts.length < 7) {
continue;
}
const [dateStr, o, h, l, c, v, oi] = parts; const [dateStr, o, h, l, c, v, oi] = parts as [
string,
string,
string,
string,
string,
string,
string,
];
records.push({ records.push({
source: 'tt',
contract, contract,
symbol: sym, symbol: sym,
name, name,
@ -128,7 +154,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
if (records.length) { if (records.length) {
await mongodb?.batchUpsert('ttFutures', records, ['contract', 'date']); await mongodb?.batchUpsert('ttFutures', records, ['contract', 'date']);
totalRecords += records.length; totalRecords += records.length;
logger.info(`Imported ${records.length} records for ${name} (${symbol}, ${files.length} contracts)`); logger.info(
`Imported ${records.length} records for ${name} (${symbol}, ${files.length} contracts)`
);
} }
// Clean up this zip // Clean up this zip

View file

@ -1,21 +1,22 @@
import { import type { CreateIndexesOptions, IndexSpecification } from 'mongodb';
BaseHandler, import { BaseHandler, Handler, ScheduledOperation } from '@stock-bot/handlers';
Handler, import type { IServiceContainer } from '@stock-bot/services';
ScheduledOperation, import { resolveIngestionServices } from '../../types';
} from '@stock-bot/handlers';
import type { DataIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types';
import { importData } from './actions'; import { importData } from './actions';
@Handler('tt') @Handler('tt')
export class TtHandler extends BaseHandler<DataIngestionServices> { export class TtHandler extends BaseHandler<DataIngestionServices> {
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); super(resolveIngestionServices(services, 'tt'));
} }
async onInit(): Promise<void> { override async onInit(): Promise<void> {
if (!this.mongodb) return; if (!this.mongodb) {
return;
}
const indexes = [ const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [
{ {
indexSpec: { contract: 1, date: 1 }, indexSpec: { contract: 1, date: 1 },
options: { name: 'contract_date_unique_idx', unique: true, background: true }, options: { name: 'contract_date_unique_idx', unique: true, background: true },
@ -34,7 +35,7 @@ export class TtHandler extends BaseHandler<DataIngestionServices> {
try { try {
await this.mongodb.createIndex('ttFutures', index.indexSpec, index.options); await this.mongodb.createIndex('ttFutures', index.indexSpec, index.options);
} catch (error) { } catch (error) {
this.logger.debug(`ttFutures index ${index.options.name} may already exist:`, error); this.logger.debug(`ttFutures index ${index.options.name} may already exist:`, { error });
} }
} }
} }

View file

@ -5,11 +5,13 @@ import {
QueueSchedule, QueueSchedule,
type ExecutionContext, type ExecutionContext,
} from '@stock-bot/handlers'; } from '@stock-bot/handlers';
import type { IServiceContainer } from '@stock-bot/services';
import { resolveIngestionServices } from '../../types';
@Handler('webshare') @Handler('webshare')
export class WebShareHandler extends BaseHandler { export class WebShareHandler extends BaseHandler {
constructor(services: any) { constructor(services: IServiceContainer) {
super(services); super(resolveIngestionServices(services, 'webshare'));
} }
@Operation('fetch-proxies') @Operation('fetch-proxies')

View file

@ -5,7 +5,7 @@
import { ServiceApplication } from '@stock-bot/di'; import { ServiceApplication } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config'; import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes'; import { createRoutes } from './routes/create-routes';
// Local imports // Local imports
import { initializeAllHandlers } from './handlers'; import { initializeAllHandlers } from './handlers';
@ -49,11 +49,11 @@ const app = new ServiceApplication(
); );
// Container factory function // Container factory function
async function createContainer(config: StockAppConfig) { async function createContainer(baseConfig: import('@stock-bot/config').UnifiedAppConfig) {
const { ServiceContainerBuilder } = await import('@stock-bot/di'); const { ServiceContainerBuilder } = await import('@stock-bot/di');
const container = await new ServiceContainerBuilder() const container = await new ServiceContainerBuilder()
.withConfig(config) .withConfig({ ...config, ...baseConfig })
.withOptions({ .withOptions({
enableQuestDB: false, // Data ingestion doesn't need QuestDB yet enableQuestDB: false, // Data ingestion doesn't need QuestDB yet
enableMongoDB: true, enableMongoDB: true,

View file

@ -21,17 +21,9 @@ export function createRoutes(services: IServiceContainer): Hono {
app.route('/api/exchanges', exchangeRoutes); app.route('/api/exchanges', exchangeRoutes);
app.route('/api/queue', createQueueRoutes(services)); app.route('/api/queue', createQueueRoutes(services));
// Store services in app context for handlers that need it
app.use('*', async (c, next) => {
c.set('services', services);
await next();
});
// Add a new endpoint to test the improved DI // Add a new endpoint to test the improved DI
app.get('/api/di-test', async c => { app.get('/api/di-test', async c => {
try { try {
const services = c.get('services') as IServiceContainer;
// Test MongoDB connection // Test MongoDB connection
const mongoStats = services.mongodb?.getPoolMetrics?.() || { const mongoStats = services.mongodb?.getPoolMetrics?.() || {
status: services.mongodb ? 'connected' : 'disabled', status: services.mongodb ? 'connected' : 'disabled',
@ -44,7 +36,7 @@ export function createRoutes(services: IServiceContainer): Hono {
const cacheReady = services.cache?.isReady() || false; const cacheReady = services.cache?.isReady() || false;
// Test queue // Test queue
const queueStats = services.queue?.getGlobalStats() || { status: 'disabled' }; const queueStats = (await services.queueManager?.getGlobalStats()) || { status: 'disabled' };
return c.json({ return c.json({
success: true, success: true,
@ -58,7 +50,6 @@ export function createRoutes(services: IServiceContainer): Hono {
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
}); });
} catch (error) { } catch (error) {
const services = c.get('services') as IServiceContainer;
services.logger.error('DI test endpoint failed', { error }); services.logger.error('DI test endpoint failed', { error });
return c.json( return c.json(
{ {

View file

@ -1,13 +1,14 @@
import type { Document } from 'mongodb';
/** /**
* Base class for operation providers * Base class for operation providers
*/ */
import type { Logger, MongoDBClient } from '@stock-bot/services'; import type { Logger, MongoDBClient } from '@stock-bot/services';
import type { import type {
OperationConfig, OperationComponentOptions,
OperationUpdate, OperationConfig,
OperationUpdate,
ProviderConfig, ProviderConfig,
OperationComponentOptions
} from './types'; } from './types';
/** /**
@ -42,10 +43,10 @@ export abstract class BaseOperationProvider {
} }
this.logger.info(`Initializing ${this.getProviderConfig().name} operation provider`); this.logger.info(`Initializing ${this.getProviderConfig().name} operation provider`);
// Allow providers to perform custom initialization // Allow providers to perform custom initialization
await this.onInitialize(); await this.onInitialize();
this._initialized = true; this._initialized = true;
} }
@ -78,16 +79,16 @@ export abstract class BaseOperationProvider {
/** /**
* Get the symbol identifier value from a document * Get the symbol identifier value from a document
*/ */
getSymbolIdentifier(doc: any): string { getSymbolIdentifier(doc: Document): string {
const { symbolField } = this.getProviderConfig(); const { symbolField } = this.getProviderConfig();
const value = doc[symbolField]; const value = doc[symbolField];
if (!value) { if (!value) {
throw new Error( throw new Error(
`Symbol field '${symbolField}' not found in document for provider '${this.getProviderConfig().name}'` `Symbol field '${symbolField}' not found in document for provider '${this.getProviderConfig().name}'`
); );
} }
return value; return value;
} }
@ -110,9 +111,9 @@ export abstract class BaseOperationProvider {
* Hook called before operation update (optional override) * Hook called before operation update (optional override)
*/ */
async beforeOperationUpdate( async beforeOperationUpdate(
symbol: string, _symbol: string,
operation: string, _operation: string,
data: OperationUpdate _data: OperationUpdate
): Promise<void> { ): Promise<void> {
// Providers can override this for custom logic // Providers can override this for custom logic
} }
@ -121,9 +122,9 @@ export abstract class BaseOperationProvider {
* Hook called after operation update (optional override) * Hook called after operation update (optional override)
*/ */
async afterOperationUpdate( async afterOperationUpdate(
symbol: string, _symbol: string,
operation: string, _operation: string,
data: OperationUpdate _data: OperationUpdate
): Promise<void> { ): Promise<void> {
// Providers can override this for custom logic // Providers can override this for custom logic
} }
@ -157,7 +158,7 @@ export abstract class BaseOperationProvider {
logInfo(): void { logInfo(): void {
const config = this.getProviderConfig(); const config = this.getProviderConfig();
const operations = this.getOperations(); const operations = this.getOperations();
this.logger.info(`Provider: ${config.name}`, { this.logger.info(`Provider: ${config.name}`, {
provider: config.name, provider: config.name,
collection: config.collectionName, collection: config.collectionName,
@ -166,8 +167,8 @@ export abstract class BaseOperationProvider {
operations: operations.map(op => ({ operations: operations.map(op => ({
name: op.name, name: op.name,
type: op.type, type: op.type,
defaultStaleHours: op.defaultStaleHours defaultStaleHours: op.defaultStaleHours,
})) })),
}); });
} }
} }

View file

@ -1,8 +1,10 @@
import type { Document } from 'mongodb';
/** /**
* Central registry for managing operations across multiple providers * Central registry for managing operations across multiple providers
*/ */
import type { Logger, MongoDBClient } from '@stock-bot/services'; import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import { BaseOperationProvider } from './BaseOperationProvider'; import { BaseOperationProvider } from './BaseOperationProvider';
import { OperationTracker } from './OperationTracker'; import { OperationTracker } from './OperationTracker';
import type { import type {
@ -10,7 +12,7 @@ import type {
OperationConfig, OperationConfig,
OperationStats, OperationStats,
OperationUpdate, OperationUpdate,
StaleSymbolOptions StaleSymbolOptions,
} from './types'; } from './types';
/** /**
@ -45,7 +47,7 @@ export class OperationRegistry {
*/ */
async registerProvider(provider: BaseOperationProvider): Promise<void> { async registerProvider(provider: BaseOperationProvider): Promise<void> {
const config = provider.getProviderConfig(); const config = provider.getProviderConfig();
if (this.providers.has(config.name)) { if (this.providers.has(config.name)) {
throw new Error(`Provider '${config.name}' is already registered`); throw new Error(`Provider '${config.name}' is already registered`);
} }
@ -56,11 +58,8 @@ export class OperationRegistry {
this.providers.set(config.name, provider); this.providers.set(config.name, provider);
// Create and initialize tracker // Create and initialize tracker
const tracker = new OperationTracker( const tracker = new OperationTracker({ mongodb: this.mongodb, logger: this.logger }, provider);
{ mongodb: this.mongodb, logger: this.logger },
provider
);
await tracker.initialize(); await tracker.initialize();
this.trackers.set(config.name, tracker); this.trackers.set(config.name, tracker);
@ -85,7 +84,7 @@ export class OperationRegistry {
this.logger.info('Operation registry initialized', { this.logger.info('Operation registry initialized', {
providerCount: this.providers.size, providerCount: this.providers.size,
providers: Array.from(this.providers.keys()) providers: Array.from(this.providers.keys()),
}); });
} }
@ -146,7 +145,14 @@ export class OperationRegistry {
providerName: string, providerName: string,
operationName: string, operationName: string,
options?: StaleSymbolOptions options?: StaleSymbolOptions
): Promise<Array<{ symbol: any; lastRun?: Date; lastSuccess?: Date; operations?: any }>> { ): Promise<
Array<{
symbol: Document;
lastRun?: Date;
lastSuccess?: Date;
operations?: Record<string, import('./types').OperationStatus>;
}>
> {
const tracker = this.getTracker(providerName); const tracker = this.getTracker(providerName);
return tracker.getStaleSymbols(operationName, options); return tracker.getStaleSymbols(operationName, options);
} }
@ -154,10 +160,7 @@ export class OperationRegistry {
/** /**
* Get operation statistics * Get operation statistics
*/ */
async getOperationStats( async getOperationStats(providerName: string, operationName: string): Promise<OperationStats> {
providerName: string,
operationName: string
): Promise<OperationStats> {
const tracker = this.getTracker(providerName); const tracker = this.getTracker(providerName);
return tracker.getOperationStats(operationName); return tracker.getOperationStats(operationName);
} }
@ -183,7 +186,7 @@ export class OperationRegistry {
getAllOperations(): Array<{ provider: string; operations: OperationConfig[] }> { getAllOperations(): Array<{ provider: string; operations: OperationConfig[] }> {
return Array.from(this.providers.entries()).map(([name, provider]) => ({ return Array.from(this.providers.entries()).map(([name, provider]) => ({
provider: name, provider: name,
operations: provider.getOperations() operations: provider.getOperations(),
})); }));
} }
@ -209,15 +212,15 @@ export class OperationRegistry {
const operations = provider.getOperations(); const operations = provider.getOperations();
const operationStats = await Promise.all( const operationStats = await Promise.all(
operations.map(async (op) => ({ operations.map(async op => ({
name: op.name, name: op.name,
stats: await tracker.getOperationStats(op.name) stats: await tracker.getOperationStats(op.name),
})) }))
); );
return { return {
provider: providerName, provider: providerName,
operations: operationStats operations: operationStats,
}; };
} }
@ -235,15 +238,16 @@ export class OperationRegistry {
}>; }>;
}> { }> {
const providerStats = await Promise.all( const providerStats = await Promise.all(
Array.from(this.providers.keys()).map(async (providerName) => { Array.from(this.providers.keys()).map(async providerName => {
const provider = this.getProvider(providerName); const provider = this.getProvider(providerName);
const tracker = this.getTracker(providerName); const tracker = this.getTracker(providerName);
const operations = provider.getOperations(); const operations = provider.getOperations();
// Get stats for first operation to get total symbols // Get stats for first operation to get total symbols
const firstOpStats = operations.length > 0 const firstOpStats =
? await tracker.getOperationStats(operations[0].name) operations.length > 0
: { totalSymbols: 0, processedSymbols: 0 }; ? await tracker.getOperationStats(at(operations, 0).name)
: { totalSymbols: 0, processedSymbols: 0 };
// Sum processed symbols across all operations // Sum processed symbols across all operations
let totalProcessed = 0; let totalProcessed = 0;
@ -256,16 +260,18 @@ export class OperationRegistry {
provider: providerName, provider: providerName,
operationCount: operations.length, operationCount: operations.length,
totalSymbols: firstOpStats.totalSymbols, totalSymbols: firstOpStats.totalSymbols,
totalProcessed: totalProcessed totalProcessed: totalProcessed,
}; };
}) })
); );
return { return {
totalProviders: this.providers.size, totalProviders: this.providers.size,
totalOperations: Array.from(this.providers.values()) totalOperations: Array.from(this.providers.values()).reduce(
.reduce((sum, p) => sum + p.getOperations().length, 0), (sum, p) => sum + p.getOperations().length,
providerStats 0
),
providerStats,
}; };
} }
@ -279,9 +285,8 @@ export class OperationRegistry {
const results: Array<{ provider: string; operation: OperationConfig }> = []; const results: Array<{ provider: string; operation: OperationConfig }> = [];
for (const [providerName, provider] of this.providers) { for (const [providerName, provider] of this.providers) {
const operations = provider.getOperations() const operations = provider.getOperations().filter(op => op.type === type);
.filter(op => op.type === type);
operations.forEach(operation => { operations.forEach(operation => {
results.push({ provider: providerName, operation }); results.push({ provider: providerName, operation });
}); });
@ -297,7 +302,7 @@ export class OperationRegistry {
providerName: string, providerName: string,
operationName: string, operationName: string,
options?: StaleSymbolOptions options?: StaleSymbolOptions
): Promise<Array<{ symbol: string; metadata?: any }>> { ): Promise<Array<{ symbol: string; metadata?: unknown }>> {
const provider = this.getProvider(providerName); const provider = this.getProvider(providerName);
const tracker = this.getTracker(providerName); const tracker = this.getTracker(providerName);
const { collectionName, symbolField } = provider.getProviderConfig(); const { collectionName, symbolField } = provider.getProviderConfig();
@ -310,16 +315,20 @@ export class OperationRegistry {
} }
// Get full symbol data for scheduling // Get full symbol data for scheduling
const symbols = await this.mongodb.find(collectionName, { const symbols = await this.mongodb.find(
[symbolField]: { $in: staleSymbols } collectionName,
}, { {
projection: { [symbolField]: { $in: staleSymbols },
[symbolField]: 1, },
symbol: 1, {
exchange: 1, projection: {
// Include any other fields needed for scheduling [symbolField]: 1,
symbol: 1,
exchange: 1,
// Include any other fields needed for scheduling
},
} }
}); );
return symbols.map(doc => ({ return symbols.map(doc => ({
symbol: doc[symbolField], symbol: doc[symbolField],
@ -327,7 +336,7 @@ export class OperationRegistry {
symbol: doc.symbol, symbol: doc.symbol,
exchange: doc.exchange, exchange: doc.exchange,
// Include other metadata as needed // Include other metadata as needed
} },
})); }));
} }
} }

View file

@ -1,8 +1,10 @@
import { MongoServerError, type Document, type Filter } from 'mongodb';
/** /**
* General operation tracker that works with any provider * General operation tracker that works with any provider
*/ */
import type { Logger, MongoDBClient } from '@stock-bot/services'; import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import type { BaseOperationProvider } from './BaseOperationProvider'; import type { BaseOperationProvider } from './BaseOperationProvider';
import type { import type {
BulkOperationUpdate, BulkOperationUpdate,
@ -11,7 +13,7 @@ import type {
OperationStats, OperationStats,
OperationUpdate, OperationUpdate,
StaleSymbolOptions, StaleSymbolOptions,
SymbolWithOperations SymbolWithOperations,
} from './types'; } from './types';
/** /**
@ -23,10 +25,7 @@ export class OperationTracker {
private provider: BaseOperationProvider; private provider: BaseOperationProvider;
private indexesCreated: Set<string> = new Set(); private indexesCreated: Set<string> = new Set();
constructor( constructor({ mongodb, logger }: OperationComponentOptions, provider: BaseOperationProvider) {
{ mongodb, logger }: OperationComponentOptions,
provider: BaseOperationProvider
) {
this.mongodb = mongodb; this.mongodb = mongodb;
this.logger = logger; this.logger = logger;
this.provider = provider; this.provider = provider;
@ -49,7 +48,7 @@ export class OperationTracker {
} }
this.logger.info(`Operation tracker initialized for ${name}`, { this.logger.info(`Operation tracker initialized for ${name}`, {
operationCount: operations.length operationCount: operations.length,
}); });
} }
@ -58,7 +57,7 @@ export class OperationTracker {
*/ */
private async createOperationIndexes(operation: OperationConfig): Promise<void> { private async createOperationIndexes(operation: OperationConfig): Promise<void> {
const { collectionName, symbolField } = this.provider.getProviderConfig(); const { collectionName, symbolField } = this.provider.getProviderConfig();
if (this.indexesCreated.has(operation.name)) { if (this.indexesCreated.has(operation.name)) {
return; return;
} }
@ -66,61 +65,67 @@ export class OperationTracker {
try { try {
const indexes = [ const indexes = [
// Index for finding stale symbols // Index for finding stale symbols
{ {
[`operations.${operation.name}.lastSuccessAt`]: 1, [`operations.${operation.name}.lastSuccessAt`]: 1,
[symbolField]: 1 [symbolField]: 1,
}, },
// Index for finding by last record date // Index for finding by last record date
{ {
[`operations.${operation.name}.lastRecordDate`]: 1, [`operations.${operation.name}.lastRecordDate`]: 1,
[symbolField]: 1 [symbolField]: 1,
}, },
// Index for operation status // Index for operation status
{ {
[`operations.${operation.name}.status`]: 1, [`operations.${operation.name}.status`]: 1,
[symbolField]: 1 [symbolField]: 1,
} },
]; ];
// Add crawl-specific indexes for crawl operations // Add crawl-specific indexes for crawl operations
if (operation.type === 'crawl' || operation.type === 'intraday_crawl') { if (operation.type === 'crawl' || operation.type === 'intraday_crawl') {
indexes.push( indexes.push(
{ {
[`operations.${operation.name}.finished`]: 1, [`operations.${operation.name}.finished`]: 1,
[symbolField]: 1 [symbolField]: 1,
}, },
{ {
[`operations.${operation.name}.newestDateReached`]: 1, [`operations.${operation.name}.newestDateReached`]: 1,
[symbolField]: 1 [symbolField]: 1,
}, },
{ {
[`operations.${operation.name}.oldestDateReached`]: 1, [`operations.${operation.name}.oldestDateReached`]: 1,
[symbolField]: 1 [symbolField]: 1,
} }
); );
} }
const collection = this.mongodb.collection(collectionName); const collection = this.mongodb.collection(collectionName);
for (const indexSpec of indexes) { for (const indexSpec of indexes) {
try { try {
await collection.createIndex(indexSpec, { await collection.createIndex(indexSpec, {
background: true, background: true,
name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}` name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}`,
}); });
} catch (indexError) { } catch (indexError) {
// Log but don't fail if index already exists or we hit the limit // Log but don't fail if index already exists or we hit the limit
if (indexError.message?.includes('too many indexes') || indexError.code === 86) { if (
indexError instanceof MongoServerError &&
(indexError.message.includes('too many indexes') || indexError.code === 86)
) {
this.logger.warn(`Skipping index creation due to limit`, { this.logger.warn(`Skipping index creation due to limit`, {
operation: operation.name, operation: operation.name,
index: Object.keys(indexSpec).join('_'), index: Object.keys(indexSpec).join('_'),
error: indexError.message error: indexError.message,
}); });
} else if (indexError.code === 11000 || indexError.code === 85) { } else if (
indexError instanceof MongoServerError &&
(indexError.code === 11000 || indexError.code === 85)
) {
// Index already exists // Index already exists
this.logger.debug(`Index already exists`, { this.logger.debug(`Index already exists`, {
operation: operation.name, operation: operation.name,
index: Object.keys(indexSpec).join('_') index: Object.keys(indexSpec).join('_'),
}); });
} else { } else {
throw indexError; throw indexError;
@ -129,16 +134,16 @@ export class OperationTracker {
} }
this.indexesCreated.add(operation.name); this.indexesCreated.add(operation.name);
this.logger.debug(`Created indexes for operation: ${operation.name}`, { this.logger.debug(`Created indexes for operation: ${operation.name}`, {
provider: this.provider.getProviderConfig().name, provider: this.provider.getProviderConfig().name,
operation: operation.name, operation: operation.name,
indexCount: indexes.length indexCount: indexes.length,
}); });
} catch (error) { } catch (error) {
this.logger.error(`Failed to create indexes for operation: ${operation.name}`, { this.logger.error(`Failed to create indexes for operation: ${operation.name}`, {
error, error,
provider: this.provider.getProviderConfig().name provider: this.provider.getProviderConfig().name,
}); });
throw error; throw error;
} }
@ -153,19 +158,19 @@ export class OperationTracker {
data: OperationUpdate data: OperationUpdate
): Promise<void> { ): Promise<void> {
const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig(); const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();
// Validate operation exists // Validate operation exists
this.provider.validateOperation(operationName); this.provider.validateOperation(operationName);
// Call before hook // Call before hook
await this.provider.beforeOperationUpdate(symbol, operationName, data); await this.provider.beforeOperationUpdate(symbol, operationName, data);
const update: any = { const update: Document = {
$set: { $set: {
[`operations.${operationName}.lastRunAt`]: new Date(), [`operations.${operationName}.lastRunAt`]: new Date(),
[`operations.${operationName}.status`]: data.status, [`operations.${operationName}.status`]: data.status,
updated_at: new Date() updated_at: new Date(),
} },
}; };
// Only update lastSuccessAt on successful operations // Only update lastSuccessAt on successful operations
@ -217,7 +222,7 @@ export class OperationTracker {
filter: { [symbolField]: symbol }, filter: { [symbolField]: symbol },
symbolField, symbolField,
symbol, symbol,
operation: operationName operation: operationName,
}); });
const updateResult = await this.mongodb.updateOne( const updateResult = await this.mongodb.updateOne(
@ -230,7 +235,7 @@ export class OperationTracker {
matched: updateResult.matchedCount, matched: updateResult.matchedCount,
modified: updateResult.modifiedCount, modified: updateResult.modifiedCount,
symbol, symbol,
operation: operationName operation: operationName,
}); });
// Call after hook // Call after hook
@ -240,7 +245,7 @@ export class OperationTracker {
provider: providerName, provider: providerName,
symbol, symbol,
operation: operationName, operation: operationName,
status: data.status status: data.status,
}); });
} }
@ -248,7 +253,9 @@ export class OperationTracker {
* Bulk update symbol operations for performance * Bulk update symbol operations for performance
*/ */
async bulkUpdateSymbolOperations(updates: BulkOperationUpdate[]): Promise<void> { async bulkUpdateSymbolOperations(updates: BulkOperationUpdate[]): Promise<void> {
if (updates.length === 0) {return;} if (updates.length === 0) {
return;
}
const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig(); const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();
@ -256,7 +263,7 @@ export class OperationTracker {
const operationGroups = new Map<string, BulkOperationUpdate[]>(); const operationGroups = new Map<string, BulkOperationUpdate[]>();
for (const update of updates) { for (const update of updates) {
this.provider.validateOperation(update.operation); this.provider.validateOperation(update.operation);
const group = operationGroups.get(update.operation) || []; const group = operationGroups.get(update.operation) || [];
group.push(update); group.push(update);
operationGroups.set(update.operation, group); operationGroups.set(update.operation, group);
@ -269,12 +276,12 @@ export class OperationTracker {
// Build bulk operations // Build bulk operations
const bulkOps = updates.map(({ symbol, operation, data }) => { const bulkOps = updates.map(({ symbol, operation, data }) => {
const update: any = { const update: Document = {
$set: { $set: {
[`operations.${operation}.lastRunAt`]: new Date(), [`operations.${operation}.lastRunAt`]: new Date(),
[`operations.${operation}.status`]: data.status, [`operations.${operation}.status`]: data.status,
updated_at: new Date() updated_at: new Date(),
} },
}; };
if (data.status === 'success') { if (data.status === 'success') {
@ -323,8 +330,8 @@ export class OperationTracker {
return { return {
updateOne: { updateOne: {
filter: { [symbolField]: symbol }, filter: { [symbolField]: symbol },
update update,
} },
}; };
}); });
@ -340,7 +347,7 @@ export class OperationTracker {
provider: providerName, provider: providerName,
totalUpdates: updates.length, totalUpdates: updates.length,
modified: result.modifiedCount, modified: result.modifiedCount,
operations: Array.from(operationGroups.keys()) operations: Array.from(operationGroups.keys()),
}); });
} }
@ -350,32 +357,41 @@ export class OperationTracker {
async getStaleSymbols( async getStaleSymbols(
operationName: string, operationName: string,
options: StaleSymbolOptions = {} options: StaleSymbolOptions = {}
): Promise<Array<{ symbol: any; lastRun?: Date; lastSuccess?: Date; operations?: any }>> { ): Promise<
Array<{
symbol: Document;
lastRun?: Date;
lastSuccess?: Date;
operations?: Record<string, import('./types').OperationStatus>;
}>
> {
const { collectionName, symbolField } = this.provider.getProviderConfig(); const { collectionName, symbolField } = this.provider.getProviderConfig();
const { const {
limit = 1000, limit = 1000,
excludeSymbols = [], excludeSymbols = [],
activeOnly = true, activeOnly = true,
symbolFilter, symbolFilter,
exchanges, exchanges,
delisted delisted,
} = options; } = options;
this.provider.validateOperation(operationName); this.provider.validateOperation(operationName);
const cutoffDate = options.notRunSince || (() => { const cutoffDate =
const date = new Date(); options.notRunSince ||
const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName); (() => {
date.setHours(date.getHours() - hours); const date = new Date();
return date; const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName);
})(); date.setHours(date.getHours() - hours);
return date;
})();
const filter: any = { const filter: Filter<Document> = {
$or: [ $or: [
{ [`operations.${operationName}.lastSuccessAt`]: { $lt: cutoffDate } }, { [`operations.${operationName}.lastSuccessAt`]: { $lt: cutoffDate } },
{ [`operations.${operationName}.lastSuccessAt`]: { $exists: false } }, { [`operations.${operationName}.lastSuccessAt`]: { $exists: false } },
{ [`operations.${operationName}`]: { $exists: false } } { [`operations.${operationName}`]: { $exists: false } },
] ],
}; };
if (activeOnly) { if (activeOnly) {
@ -403,15 +419,15 @@ export class OperationTracker {
const symbols = await this.mongodb.find(collectionName, filter, { const symbols = await this.mongodb.find(collectionName, filter, {
limit, limit,
projection: { }, // Return all fields projection: {}, // Return all fields
sort: { [`operations.${operationName}.lastSuccessAt`]: 1 } sort: { [`operations.${operationName}.lastSuccessAt`]: 1 },
}); });
return symbols.map(doc => ({ return symbols.map(doc => ({
symbol: doc, symbol: doc,
lastRun: doc.operations?.[operationName]?.lastRunAt, lastRun: doc.operations?.[operationName]?.lastRunAt,
lastSuccess: doc.operations?.[operationName]?.lastSuccessAt, lastSuccess: doc.operations?.[operationName]?.lastSuccessAt,
operations: doc.operations operations: doc.operations,
})); }));
} }
@ -430,8 +446,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName); this.provider.validateOperation(operationName);
const filter: any = { const filter: Filter<Document> = {
active: { $ne: false } active: { $ne: false },
}; };
if (!includeFinished) { if (!includeFinished) {
@ -442,17 +458,17 @@ export class OperationTracker {
limit, limit,
projection: { projection: {
[symbolField]: 1, [symbolField]: 1,
[`operations.${operationName}`]: 1 [`operations.${operationName}`]: 1,
}, },
sort: { sort: {
[`operations.${operationName}.lastRunAt`]: 1 [`operations.${operationName}.lastRunAt`]: 1,
} },
}); });
return symbols.map(doc => ({ return symbols.map(doc => ({
symbol: doc[symbolField], symbol: doc[symbolField],
lastRecordDate: doc.operations?.[operationName]?.lastRecordDate, lastRecordDate: doc.operations?.[operationName]?.lastRecordDate,
operationStatus: doc.operations?.[operationName] operationStatus: doc.operations?.[operationName],
})); }));
} }
@ -469,7 +485,7 @@ export class OperationTracker {
status: 'success', status: 'success',
finished: true, finished: true,
oldestDateReached, oldestDateReached,
newestDateReached: newestDateReached || new Date() newestDateReached: newestDateReached || new Date(),
}); });
this.logger.info('Marked crawl as finished', { this.logger.info('Marked crawl as finished', {
@ -477,7 +493,7 @@ export class OperationTracker {
symbol, symbol,
operation: operationName, operation: operationName,
oldestDateReached, oldestDateReached,
newestDateReached newestDateReached,
}); });
} }
@ -499,8 +515,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName); this.provider.validateOperation(operationName);
// Build filter // Build filter
const filter: any = { const filter: Filter<Document> = {
active: { $ne: false } active: { $ne: false },
}; };
// Add symbol filter if provided // Add symbol filter if provided
@ -512,18 +528,18 @@ export class OperationTracker {
// 1. Have never been crawled // 1. Have never been crawled
// 2. Are not finished // 2. Are not finished
// 3. Have gaps (new data since last crawl) // 3. Have gaps (new data since last crawl)
const orConditions = [ const orConditions: Filter<Document>[] = [
{ [`operations.${operationName}`]: { $exists: false } }, { [`operations.${operationName}`]: { $exists: false } },
{ [`operations.${operationName}.finished`]: { $ne: true } } { [`operations.${operationName}.finished`]: { $ne: true } },
]; ];
if (includeNewDataGaps) { if (includeNewDataGaps) {
const yesterday = new Date(); const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0); yesterday.setHours(0, 0, 0, 0);
orConditions.push({ orConditions.push({
[`operations.${operationName}.newestDateReached`]: { $lt: yesterday } [`operations.${operationName}.newestDateReached`]: { $lt: yesterday },
}); });
} }
@ -537,19 +553,19 @@ export class OperationTracker {
// Include common fields that might be needed // Include common fields that might be needed
symbol: 1, symbol: 1,
exchange: 1, exchange: 1,
qmSearchCode: 1 qmSearchCode: 1,
}, },
sort: { sort: {
[`operations.${operationName}.lastRunAt`]: 1 [`operations.${operationName}.lastRunAt`]: 1,
} },
}); });
return symbols.map(doc => { return symbols.map(doc => {
const opStatus = doc.operations?.[operationName]; const opStatus = doc.operations?.[operationName];
// Determine gaps (only backward since we removed forward crawling) // Determine gaps (only backward since we removed forward crawling)
const gaps: { forward?: boolean; backward?: boolean } = {}; const gaps: { forward?: boolean; backward?: boolean } = {};
if (opStatus) { if (opStatus) {
// Only check for backward gap (historical data) // Only check for backward gap (historical data)
if (!opStatus.finished) { if (!opStatus.finished) {
@ -570,7 +586,7 @@ export class OperationTracker {
gaps, gaps,
// Include other potentially useful fields // Include other potentially useful fields
exchange: doc.exchange, exchange: doc.exchange,
qmSearchCode: doc.qmSearchCode || doc[symbolField] qmSearchCode: doc.qmSearchCode || doc[symbolField],
} as SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } }; } as SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } };
}); });
} }
@ -584,19 +600,23 @@ export class OperationTracker {
targetOldestDate: Date targetOldestDate: Date
): Promise<boolean> { ): Promise<boolean> {
const { collectionName, symbolField } = this.provider.getProviderConfig(); const { collectionName, symbolField } = this.provider.getProviderConfig();
const doc = await this.mongodb.findOne(collectionName, { const doc = await this.mongodb.findOne(
[symbolField]: symbol collectionName,
}, { {
projection: { [`operations.${operationName}`]: 1 } [symbolField]: symbol,
}); },
{
projection: { [`operations.${operationName}`]: 1 },
}
);
if (!doc?.operations?.[operationName]) { if (!doc?.operations?.[operationName]) {
return false; return false;
} }
const opStatus = doc.operations[operationName]; const opStatus = doc.operations[operationName];
// Check if explicitly marked as finished // Check if explicitly marked as finished
if (opStatus.finished) { if (opStatus.finished) {
return true; return true;
@ -626,8 +646,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName); this.provider.validateOperation(operationName);
const filter: any = { const filter: Filter<Document> = {
active: { $ne: false } active: { $ne: false },
}; };
if (options.neverRun) { if (options.neverRun) {
@ -635,7 +655,7 @@ export class OperationTracker {
} else if (options.lastRecordBefore) { } else if (options.lastRecordBefore) {
filter.$or = [ filter.$or = [
{ [`operations.${operationName}.lastRecordDate`]: { $lt: options.lastRecordBefore } }, { [`operations.${operationName}.lastRecordDate`]: { $lt: options.lastRecordBefore } },
{ [`operations.${operationName}`]: { $exists: false } } { [`operations.${operationName}`]: { $exists: false } },
]; ];
} }
@ -644,15 +664,15 @@ export class OperationTracker {
projection: { projection: {
[symbolField]: 1, [symbolField]: 1,
[`operations.${operationName}.lastRecordDate`]: 1, [`operations.${operationName}.lastRecordDate`]: 1,
[`operations.${operationName}`]: 1 [`operations.${operationName}`]: 1,
}, },
sort: { [`operations.${operationName}.lastRecordDate`]: 1 } sort: { [`operations.${operationName}.lastRecordDate`]: 1 },
}); });
return symbols.map(doc => ({ return symbols.map(doc => ({
symbol: doc[symbolField], symbol: doc[symbolField],
lastRecordDate: doc.operations?.[operationName]?.lastRecordDate, lastRecordDate: doc.operations?.[operationName]?.lastRecordDate,
operationStatus: doc.operations?.[operationName] operationStatus: doc.operations?.[operationName],
})); }));
} }
@ -662,60 +682,53 @@ export class OperationTracker {
async getOperationStats(operationName: string): Promise<OperationStats> { async getOperationStats(operationName: string): Promise<OperationStats> {
const { collectionName } = this.provider.getProviderConfig(); const { collectionName } = this.provider.getProviderConfig();
const operation = this.provider.getOperation(operationName); const operation = this.provider.getOperation(operationName);
if (!operation) { if (!operation) {
throw new Error(`Unknown operation: ${operationName}`); throw new Error(`Unknown operation: ${operationName}`);
} }
const collection = this.mongodb.collection(collectionName); const collection = this.mongodb.collection(collectionName);
const [ const [total, processed, successful, failed, staleStats, crawlStats, recordStats] =
total, await Promise.all([
processed, // Total symbols
successful, collection.countDocuments({}),
failed,
staleStats, // Processed symbols
crawlStats, collection.countDocuments({
recordStats [`operations.${operationName}`]: { $exists: true },
] = await Promise.all([ }),
// Total symbols
collection.countDocuments({}), // Successful symbols
collection.countDocuments({
// Processed symbols [`operations.${operationName}.status`]: 'success',
collection.countDocuments({ }),
[`operations.${operationName}`]: { $exists: true }
}), // Failed symbols
collection.countDocuments({
// Successful symbols [`operations.${operationName}.status`]: 'failure',
collection.countDocuments({ }),
[`operations.${operationName}.status`]: 'success'
}), // Stale symbols
this.countStaleSymbols(operationName, operation.defaultStaleHours || 24),
// Failed symbols
collection.countDocuments({ // Crawl stats (if applicable)
[`operations.${operationName}.status`]: 'failure' operation.type === 'crawl' || operation.type === 'intraday_crawl'
}), ? collection.countDocuments({
[`operations.${operationName}.finished`]: true,
// Stale symbols })
this.countStaleSymbols(operationName, operation.defaultStaleHours || 24), : Promise.resolve(undefined),
// Crawl stats (if applicable) // Average records
(operation.type === 'crawl' || operation.type === 'intraday_crawl') this.calculateAverageRecords(operationName),
? collection.countDocuments({ ]);
[`operations.${operationName}.finished`]: true
})
: Promise.resolve(undefined),
// Average records
this.calculateAverageRecords(operationName)
]);
const result: OperationStats = { const result: OperationStats = {
totalSymbols: total, totalSymbols: total,
processedSymbols: processed, processedSymbols: processed,
staleSymbols: staleStats, staleSymbols: staleStats,
successfulSymbols: successful, successfulSymbols: successful,
failedSymbols: failed failedSymbols: failed,
}; };
if (crawlStats !== undefined) { if (crawlStats !== undefined) {
@ -735,15 +748,15 @@ export class OperationTracker {
private async countStaleSymbols(operationName: string, staleHours: number): Promise<number> { private async countStaleSymbols(operationName: string, staleHours: number): Promise<number> {
const { collectionName } = this.provider.getProviderConfig(); const { collectionName } = this.provider.getProviderConfig();
const collection = this.mongodb.collection(collectionName); const collection = this.mongodb.collection(collectionName);
const staleDate = new Date(); const staleDate = new Date();
staleDate.setHours(staleDate.getHours() - staleHours); staleDate.setHours(staleDate.getHours() - staleHours);
return collection.countDocuments({ return collection.countDocuments({
$or: [ $or: [
{ [`operations.${operationName}.lastSuccessAt`]: { $lt: staleDate } }, { [`operations.${operationName}.lastSuccessAt`]: { $lt: staleDate } },
{ [`operations.${operationName}`]: { $exists: false } } { [`operations.${operationName}`]: { $exists: false } },
] ],
}); });
} }
@ -753,23 +766,25 @@ export class OperationTracker {
private async calculateAverageRecords(operationName: string): Promise<number | undefined> { private async calculateAverageRecords(operationName: string): Promise<number | undefined> {
const { collectionName } = this.provider.getProviderConfig(); const { collectionName } = this.provider.getProviderConfig();
const collection = this.mongodb.collection(collectionName); const collection = this.mongodb.collection(collectionName);
const aggregation = await collection.aggregate([
{
$match: {
[`operations.${operationName}.recordCount`]: { $exists: true }
}
},
{
$group: {
_id: null,
avgRecords: { $avg: `$operations.${operationName}.recordCount` }
}
}
]).toArray();
if (aggregation.length > 0 && aggregation[0].avgRecords) { const aggregation = await collection
return Math.round(aggregation[0].avgRecords); .aggregate([
{
$match: {
[`operations.${operationName}.recordCount`]: { $exists: true },
},
},
{
$group: {
_id: null,
avgRecords: { $avg: `$operations.${operationName}.recordCount` },
},
},
])
.toArray();
if (aggregation.length > 0 && at(aggregation, 0).avgRecords) {
return Math.round(at(aggregation, 0).avgRecords);
} }
return undefined; return undefined;

View file

@ -21,7 +21,7 @@ export interface OperationConfig {
/** Whether operation requires a finished flag (for crawl operations) */ /** Whether operation requires a finished flag (for crawl operations) */
requiresFinishedFlag?: boolean; requiresFinishedFlag?: boolean;
/** Custom metadata for provider-specific needs */ /** Custom metadata for provider-specific needs */
metadata?: Record<string, any>; metadata?: Record<string, unknown>;
} }
/** /**
@ -41,8 +41,8 @@ export interface OperationStatus {
/** Error message if status is failure */ /** Error message if status is failure */
error?: string; error?: string;
/** Provider-specific metadata */ /** Provider-specific metadata */
metadata?: Record<string, any>; metadata?: Record<string, unknown>;
// Crawl-specific fields (used for crawl and intraday_crawl operations) // Crawl-specific fields (used for crawl and intraday_crawl operations)
/** Whether the crawl has completed */ /** Whether the crawl has completed */
finished?: boolean; finished?: boolean;
@ -89,8 +89,8 @@ export interface OperationUpdate {
/** Error message for failures */ /** Error message for failures */
error?: string; error?: string;
/** Additional metadata */ /** Additional metadata */
metadata?: Record<string, any>; metadata?: Record<string, unknown>;
// Crawl-specific update fields // Crawl-specific update fields
/** Whether the crawl has completed */ /** Whether the crawl has completed */
finished?: boolean; finished?: boolean;
@ -161,7 +161,7 @@ export interface OperationStats {
/** Average records per symbol */ /** Average records per symbol */
avgRecordsPerSymbol?: number; avgRecordsPerSymbol?: number;
/** Additional provider-specific stats */ /** Additional provider-specific stats */
customStats?: Record<string, any>; customStats?: Record<string, unknown>;
} }
/** /**
@ -175,7 +175,7 @@ export interface SymbolWithOperations {
/** Full operation status */ /** Full operation status */
operationStatus?: OperationStatus; operationStatus?: OperationStatus;
/** Additional symbol data */ /** Additional symbol data */
metadata?: Record<string, any>; metadata?: Record<string, unknown>;
} }
/** /**

View file

@ -1,3 +1,4 @@
import { requireServices } from '@stock-bot/services';
/** /**
* Data Ingestion Service Types * Data Ingestion Service Types
* Defines required services for data ingestion handlers * Defines required services for data ingestion handlers
@ -19,7 +20,22 @@ export type DataIngestionServices = ServiceTypes & {
browser: NonNullable<ServiceTypes['browser']>; browser: NonNullable<ServiceTypes['browser']>;
proxy: NonNullable<ServiceTypes['proxy']>; proxy: NonNullable<ServiceTypes['proxy']>;
// Optional services remain optional // Optional services remain optional
postgres: ServiceTypes['postgres']; postgres?: ServiceTypes['postgres'];
questdb: ServiceTypes['questdb']; questdb?: ServiceTypes['questdb'];
globalCache: ServiceTypes['globalCache']; globalCache?: ServiceTypes['globalCache'];
}; };
export function resolveIngestionServices(
services: import('@stock-bot/services').IServiceContainer,
handler: string
): DataIngestionServices {
const required = requireServices(
services,
'mongodb',
'cache',
'queueManager',
'browser',
'proxy'
);
return { ...required, queue: required.queueManager.getQueue(handler) };
}

View file

@ -1,100 +1,99 @@
#!/usr/bin/env bun #!/usr/bin/env bun
import { getLogger } from '@stock-bot/logger';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('test-advanced-rate-limit');
const logger = getLogger('test-advanced-rate-limit');
async function testAdvancedRateLimits() {
async function testAdvancedRateLimits() { logger.info('Testing advanced rate limit features...');
logger.info('Testing advanced rate limit features...');
const baseUrl = 'http://localhost:3001/api';
const baseUrl = 'http://localhost:3001/api';
logger.info('\n📋 Rate Limit Configuration:');
logger.info('\n📋 Rate Limit Configuration:'); logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day');
logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day'); logger.info('fetch-daily-prices: 1 point per call');
logger.info('fetch-daily-prices: 1 point per call'); logger.info('fetch-fundamentals: 10 points per call');
logger.info('fetch-fundamentals: 10 points per call'); logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)');
logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)');
// First test: test-burst operation
// First test: test-burst operation logger.info('\n🚀 Testing burst operation with mixed costs...');
logger.info('\n🚀 Testing burst operation with mixed costs...');
const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, {
const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, { method: 'POST',
method: 'POST', headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
body: JSON.stringify({ operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'],
operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'], burstSize: 30,
burstSize: 30 }),
}) });
});
const burstResult = await burstResponse.json();
const burstResult = await burstResponse.json(); logger.info('Burst test result:', burstResult);
logger.info('Burst test result:', burstResult);
// Wait for jobs to process
// Wait for jobs to process logger.info('\n⏳ Waiting 10 seconds for jobs to process...');
logger.info('\n⏳ Waiting 10 seconds for jobs to process...'); await new Promise(resolve => setTimeout(resolve, 10000));
await new Promise(resolve => setTimeout(resolve, 10000));
// Test individual operations with different costs
// Test individual operations with different costs logger.info('\n📊 Testing individual operations:');
logger.info('\n📊 Testing individual operations:');
// Test cheap operation (1 point)
// Test cheap operation (1 point) logger.info('\n1️⃣ Testing fetch-daily-prices (1 point each)...');
logger.info('\n1️⃣ Testing fetch-daily-prices (1 point each)...'); for (let i = 0; i < 5; i++) {
for (let i = 0; i < 5; i++) { const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, { method: 'POST',
method: 'POST', headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ test: true, index: i }),
body: JSON.stringify({ test: true, index: i }) });
}); logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); }
}
// Test medium cost operation (10 points)
// Test medium cost operation (10 points) logger.info('\n🔟 Testing fetch-fundamentals (10 points each)...');
logger.info('\n🔟 Testing fetch-fundamentals (10 points each)...'); for (let i = 0; i < 3; i++) {
for (let i = 0; i < 3; i++) { const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, { method: 'POST',
method: 'POST', headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ test: true, index: i }),
body: JSON.stringify({ test: true, index: i }) });
}); logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); }
}
// Test expensive operation (50 points)
// Test expensive operation (50 points) logger.info('\n💰 Testing fetch-news (50 points each, custom limits)...');
logger.info('\n💰 Testing fetch-news (50 points each, custom limits)...'); for (let i = 0; i < 2; i++) {
for (let i = 0; i < 2; i++) { const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, { method: 'POST',
method: 'POST', headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ test: true, index: i }),
body: JSON.stringify({ test: true, index: i }) });
}); logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); }
}
logger.info('\n✅ Test completed!');
logger.info('\n✅ Test completed!'); logger.info('Check the data-ingestion service logs to see rate limiting in action.');
logger.info('Check the data-ingestion service logs to see rate limiting in action.'); }
}
// Health check before running tests
// Health check before running tests async function checkService() {
async function checkService() { try {
try { const response = await fetch('http://localhost:3001/health');
const response = await fetch('http://localhost:3001/health'); if (!response.ok) {
if (!response.ok) { throw new Error('Service not healthy');
throw new Error('Service not healthy'); }
} return true;
return true; } catch (_error) {
} catch (error) { logger.error('Data ingestion service not running. Start it with: bun run dev');
logger.error('Data ingestion service not running. Start it with: bun run dev'); return false;
return false; }
} }
}
async function main() {
async function main() { if (await checkService()) {
if (await checkService()) { await testAdvancedRateLimits();
await testAdvancedRateLimits(); }
} }
}
main().catch(error => {
main().catch(error => { logger.error('Test failed:', error);
logger.error('Test failed:', error); process.exit(1);
process.exit(1); });
});

View file

@ -1,156 +1,163 @@
/** /**
* Test script to verify intraday crawl data flow * Test script to verify intraday crawl data flow
*/ */
import { OperationTracker, OperationRegistry } from '../src/shared/operation-manager'; import { OperationRegistry, OperationTracker } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types'; import type { DataIngestionServices } from '../src/types';
async function testIntradayDataFlow() { async function testIntradayDataFlow() {
console.log('=== Testing Intraday Data Flow ===\n'); console.log('=== Testing Intraday Data Flow ===\n');
// Mock services // Mock services
const mockServices: DataIngestionServices = { const mockServices: DataIngestionServices = {
mongodb: { mongodb: {
collection: (name: string) => ({ collection: (name: string) => ({
find: () => ({ find: () => ({
toArray: async () => { toArray: async () => {
console.log(`Mock: Query collection ${name}`); console.log(`Mock: Query collection ${name}`);
if (name === 'qmSymbols') { if (name === 'qmSymbols') {
return [{ return [
symbol: 'X', {
symbolId: 123456, symbol: 'X',
qmSearchCode: 'X:NYSE', symbolId: 123456,
exchange: 'NYSE', qmSearchCode: 'X:NYSE',
operations: { exchange: 'NYSE',
intraday_bars: { operations: {
lastRunAt: new Date('2024-01-01'), intraday_bars: {
lastSuccessAt: new Date('2024-01-01'), lastRunAt: new Date('2024-01-01'),
status: 'success', lastSuccessAt: new Date('2024-01-01'),
crawlState: { status: 'success',
finished: false, crawlState: {
oldestDateReached: new Date('2023-01-01'), finished: false,
newestDateReached: new Date('2024-01-01'), oldestDateReached: new Date('2023-01-01'),
lastProcessedDate: new Date('2023-06-15'), newestDateReached: new Date('2024-01-01'),
totalDaysProcessed: 180 lastProcessedDate: new Date('2023-06-15'),
} totalDaysProcessed: 180,
} },
} },
}]; },
} },
return []; ];
} }
}), return [];
createIndex: async () => ({ ok: 1 }) },
}), }),
find: async (collection: string, filter: any, options?: any) => { createIndex: async () => ({ ok: 1 }),
console.log(`Mock: Direct find on ${collection}`, { filter, options }); }),
return [{ find: async (collection: string, filter: any, options?: any) => {
symbol: 'X', console.log(`Mock: Direct find on ${collection}`, { filter, options });
qmSearchCode: 'X:NYSE', return [
exchange: 'NYSE', {
operations: { symbol: 'X',
intraday_bars: { qmSearchCode: 'X:NYSE',
crawlState: { exchange: 'NYSE',
finished: false, operations: {
oldestDateReached: new Date('2023-01-01'), intraday_bars: {
newestDateReached: new Date('2024-01-01') crawlState: {
} finished: false,
} oldestDateReached: new Date('2023-01-01'),
} newestDateReached: new Date('2024-01-01'),
}]; },
} },
} as any, },
logger: { },
info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, JSON.stringify(data, null, 2)), ];
error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''), },
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''), } as any,
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || '') logger: {
} info: (msg: string, data?: any) =>
} as DataIngestionServices; console.log(`[INFO] ${msg}`, JSON.stringify(data, null, 2)),
error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''),
// Create registry and provider warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''),
const registry = new OperationRegistry(mockServices as any); debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
},
// Mock provider } as DataIngestionServices;
const mockProvider = {
getProviderConfig: () => ({ // Create registry and provider
name: 'qm', const _registry = new OperationRegistry(mockServices as any);
collectionName: 'qmSymbols',
symbolField: 'qmSearchCode' // Mock provider
}), const mockProvider = {
getOperations: () => [{ getProviderConfig: () => ({
name: 'intraday_bars', name: 'qm',
type: 'intraday_crawl' as const, collectionName: 'qmSymbols',
defaultStaleHours: 1 symbolField: 'qmSearchCode',
}], }),
validateOperation: () => true, getOperations: () => [
getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }), {
getDefaultStaleHours: () => 1, name: 'intraday_bars',
initialize: async () => {}, type: 'intraday_crawl' as const,
beforeOperationUpdate: async () => {}, defaultStaleHours: 1,
afterOperationUpdate: async () => {} },
}; ],
validateOperation: () => true,
const tracker = new OperationTracker(mockServices as any, mockProvider as any); getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }),
await tracker.initialize(); getDefaultStaleHours: () => 1,
initialize: async () => {},
// Test 1: Get symbols for intraday crawl beforeOperationUpdate: async () => {},
console.log('\nTest 1: Get symbols for intraday crawl with symbol filter'); afterOperationUpdate: async () => {},
const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { };
limit: 10,
targetOldestDate: new Date('2020-01-01'), const tracker = new OperationTracker(mockServices as any, mockProvider as any);
includeNewDataGaps: true, await tracker.initialize();
symbolFilter: { symbol: 'X' }
}); // Test 1: Get symbols for intraday crawl
console.log('\nTest 1: Get symbols for intraday crawl with symbol filter');
console.log(`\nFound ${symbols.length} symbols:`); const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
symbols.forEach(sym => { limit: 10,
console.log({ targetOldestDate: new Date('2020-01-01'),
symbol: sym.symbol, includeNewDataGaps: true,
qmSearchCode: sym.qmSearchCode, symbolFilter: { symbol: 'X' },
exchange: sym.exchange, });
gaps: sym.gaps,
crawlState: sym.operationStatus?.crawlState console.log(`\nFound ${symbols.length} symbols:`);
}); symbols.forEach(sym => {
}); console.log({
symbol: sym.symbol,
// Test 2: Verify data preservation qmSearchCode: sym.qmSearchCode,
console.log('\n\nTest 2: Verify data is preserved through mapping'); exchange: sym.exchange,
const testSymbol = symbols[0]; gaps: sym.gaps,
if (testSymbol) { crawlState: sym.operationStatus?.crawlState,
console.log('Original data:'); });
console.log({ });
symbol: testSymbol.symbol,
hasGaps: !!testSymbol.gaps, // Test 2: Verify data preservation
gaps: testSymbol.gaps, console.log('\n\nTest 2: Verify data is preserved through mapping');
hasOperationStatus: !!testSymbol.operationStatus, const testSymbol = symbols[0];
crawlState: testSymbol.operationStatus?.crawlState if (testSymbol) {
}); console.log('Original data:');
console.log({
// Simulate mapping symbol: testSymbol.symbol,
const mapped = { hasGaps: !!testSymbol.gaps,
...testSymbol, gaps: testSymbol.gaps,
symbol: 'X', hasOperationStatus: !!testSymbol.operationStatus,
exchange: 'NYSE', crawlState: testSymbol.operationStatus?.crawlState,
qmSearchCode: 'X:NYSE', });
gaps: testSymbol.gaps,
operationStatus: testSymbol.operationStatus // Simulate mapping
}; const mapped = {
...testSymbol,
console.log('\nAfter mapping:'); symbol: 'X',
console.log({ exchange: 'NYSE',
symbol: mapped.symbol, qmSearchCode: 'X:NYSE',
exchange: mapped.exchange, gaps: testSymbol.gaps,
qmSearchCode: mapped.qmSearchCode, operationStatus: testSymbol.operationStatus,
hasGaps: !!mapped.gaps, };
gaps: mapped.gaps,
hasOperationStatus: !!mapped.operationStatus, console.log('\nAfter mapping:');
crawlState: mapped.operationStatus?.crawlState console.log({
}); symbol: mapped.symbol,
} exchange: mapped.exchange,
qmSearchCode: mapped.qmSearchCode,
console.log('\n=== Tests Complete ==='); hasGaps: !!mapped.gaps,
} gaps: mapped.gaps,
hasOperationStatus: !!mapped.operationStatus,
// Run tests crawlState: mapped.operationStatus?.crawlState,
testIntradayDataFlow().catch(console.error); });
}
console.log('\n=== Tests Complete ===');
}
// Run tests
testIntradayDataFlow().catch(console.error);

View file

@ -1,139 +1,139 @@
/** /**
* Examples of modifying existing functions to only work with symbol 'X' * Examples of modifying existing functions to only work with symbol 'X'
*/ */
import { OperationTracker } from '../src/shared/operation-manager'; import { OperationTracker } from '../src/shared/operation-manager';
// Example 1: Modified getStaleSymbols to only return symbol X // Example 1: Modified getStaleSymbols to only return symbol X
async function getStaleSymbolsOnlyX( async function getStaleSymbolsOnlyX(
operationTracker: OperationTracker, operationTracker: OperationTracker,
providerName: string, providerName: string,
operationName: string, operationName: string,
options: any = {} options: any = {}
) { ) {
// Method 1: Add symbolFilter to options // Method 1: Add symbolFilter to options
const modifiedOptions = { const modifiedOptions = {
...options, ...options,
symbolFilter: { symbol: 'X' } symbolFilter: { symbol: 'X' },
}; };
return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions); return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions);
} }
// Example 2: Modified sophisticated backtest function for symbol X only // Example 2: Modified sophisticated backtest function for symbol X only
async function runSophisticatedBacktestOnlyX(orchestrator: any) { async function _runSophisticatedBacktestOnlyX(orchestrator: any) {
const symbols = ['X']; // Only test symbol X const symbols = ['X']; // Only test symbol X
const backtestConfig = { const backtestConfig = {
symbols, symbols,
startDate: new Date('2023-01-01'), startDate: new Date('2023-01-01'),
endDate: new Date('2024-01-01'), endDate: new Date('2024-01-01'),
strategies: ['momentum', 'mean_reversion'], strategies: ['momentum', 'mean_reversion'],
// ... rest of config // ... rest of config
}; };
return orchestrator.runBacktest(backtestConfig); return orchestrator.runBacktest(backtestConfig);
} }
// Example 3: Modified schedule function to only process symbol X // Example 3: Modified schedule function to only process symbol X
async function scheduleOperationsOnlyX(handler: any) { async function _scheduleOperationsOnlyX(handler: any) {
// Get all symbols that need updates, then filter for X // Get all symbols that need updates, then filter for X
const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', { const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: 24, minHoursSinceRun: 24,
limit: 1000 limit: 1000,
}); });
// Filter to only include symbol X // Filter to only include symbol X
const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:')); const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:'));
if (symbolXOnly.length > 0) { if (symbolXOnly.length > 0) {
const symbolData = await handler.mongodb.find('qmSymbols', { const symbolData = await handler.mongodb.find('qmSymbols', {
qmSearchCode: symbolXOnly[0] qmSearchCode: symbolXOnly[0],
}); });
if (symbolData.length > 0) { if (symbolData.length > 0) {
await handler.scheduleOperation('update-prices', { await handler.scheduleOperation('update-prices', {
symbol: symbolData[0].symbol, symbol: symbolData[0].symbol,
symbolId: symbolData[0].symbolId, symbolId: symbolData[0].symbolId,
qmSearchCode: symbolData[0].qmSearchCode qmSearchCode: symbolData[0].qmSearchCode,
}); });
} }
} }
} }
// Example 4: Modified intraday crawl for symbol X only // Example 4: Modified intraday crawl for symbol X only
async function crawlIntradayOnlyX(handler: any) { async function _crawlIntradayOnlyX(handler: any) {
// Direct approach - just process symbol X // Direct approach - just process symbol X
const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' }); const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' });
if (symbolX) { if (symbolX) {
return handler.crawlIntradayData({ return handler.crawlIntradayData({
symbol: symbolX.symbol, symbol: symbolX.symbol,
symbolId: symbolX.symbolId, symbolId: symbolX.symbolId,
qmSearchCode: symbolX.qmSearchCode, qmSearchCode: symbolX.qmSearchCode,
mode: 'full', mode: 'full',
targetOldestDate: new Date('2020-01-01') targetOldestDate: new Date('2020-01-01'),
}); });
} }
} }
// Example 5: Test wrapper that ensures only symbol X is processed // Example 5: Test wrapper that ensures only symbol X is processed
function createSymbolXTestWrapper(originalFunction: Function) { function createSymbolXTestWrapper(originalFunction: Function) {
return async function(...args: any[]) { return async function (...args: any[]) {
// Check if first argument has symbol property // Check if first argument has symbol property
if (args[0] && typeof args[0] === 'object') { if (args[0] && typeof args[0] === 'object') {
// If it's a symbol-specific call, only proceed if symbol is X // If it's a symbol-specific call, only proceed if symbol is X
if (args[0].symbol && args[0].symbol !== 'X') { if (args[0].symbol && args[0].symbol !== 'X') {
console.log(`Skipping symbol ${args[0].symbol} - only testing X`); console.log(`Skipping symbol ${args[0].symbol} - only testing X`);
return { success: false, message: 'Test mode - only symbol X allowed' }; return { success: false, message: 'Test mode - only symbol X allowed' };
} }
// If it's a batch operation, filter to only X // If it's a batch operation, filter to only X
if (args[0].symbols && Array.isArray(args[0].symbols)) { if (args[0].symbols && Array.isArray(args[0].symbols)) {
args[0].symbols = args[0].symbols.filter((s: string) => s === 'X'); args[0].symbols = args[0].symbols.filter((s: string) => s === 'X');
} }
} }
// Call original function with potentially modified args // Call original function with potentially modified args
return originalFunction.apply(this, args); return originalFunction.apply(this, args);
}; };
} }
// Example usage // Example usage
async function demonstrateUsage() { async function demonstrateUsage() {
console.log('=== Demonstration of Symbol X Only Modifications ===\n'); console.log('=== Demonstration of Symbol X Only Modifications ===\n');
// Mock tracker for demonstration // Mock tracker for demonstration
const mockTracker = { const mockTracker = {
getStaleSymbols: async (provider: string, operation: string, options: any) => { getStaleSymbols: async (provider: string, operation: string, options: any) => {
console.log(`Getting stale symbols with options:`, options); console.log(`Getting stale symbols with options:`, options);
if (options.symbolFilter?.symbol === 'X') { if (options.symbolFilter?.symbol === 'X') {
return ['X:NYSE']; return ['X:NYSE'];
} }
return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ']; return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ'];
} },
} as any; } as any;
// Test the modified function // Test the modified function
console.log('1. Testing getStaleSymbols with X filter:'); console.log('1. Testing getStaleSymbols with X filter:');
const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', { const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', {
minHoursSinceRun: 24 minHoursSinceRun: 24,
}); });
console.log('Results:', xOnlySymbols); console.log('Results:', xOnlySymbols);
console.log('\n2. Example of wrapper usage:'); console.log('\n2. Example of wrapper usage:');
const originalUpdate = async (input: any) => { const originalUpdate = async (input: any) => {
console.log(`Processing symbol: ${input.symbol}`); console.log(`Processing symbol: ${input.symbol}`);
return { success: true, symbol: input.symbol }; return { success: true, symbol: input.symbol };
}; };
const wrappedUpdate = createSymbolXTestWrapper(originalUpdate); const wrappedUpdate = createSymbolXTestWrapper(originalUpdate);
await wrappedUpdate({ symbol: 'X', symbolId: 123 }); await wrappedUpdate({ symbol: 'X', symbolId: 123 });
await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped
console.log('\n=== Demonstration Complete ==='); console.log('\n=== Demonstration Complete ===');
} }
// Run demonstration // Run demonstration
demonstrateUsage().catch(console.error); demonstrateUsage().catch(console.error);

View file

@ -1,118 +1,122 @@
/** /**
* Test script specifically for symbol X operations * Test script specifically for symbol X operations
*/ */
import { QMHandler } from '../src/handlers/qm/qm.handler'; import '../src/handlers/qm/qm.handler';
import { OperationTracker } from '../src/shared/operation-manager'; import { OperationTracker } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types'; import type { DataIngestionServices } from '../src/types';
// Simple test to check operations for symbol X // Simple test to check operations for symbol X
async function testSymbolXOperations() { async function testSymbolXOperations() {
console.log('=== Testing Operations for Symbol X ===\n'); console.log('=== Testing Operations for Symbol X ===\n');
// Mock minimal services needed // Mock minimal services needed
const mockServices: Partial<DataIngestionServices> = { const mockServices: Partial<DataIngestionServices> = {
mongodb: { mongodb: {
collection: (name: string) => ({ collection: (name: string) => ({
find: () => ({ find: () => ({
toArray: async () => { toArray: async () => {
console.log(`Querying collection: ${name}`); console.log(`Querying collection: ${name}`);
if (name === 'qmSymbols') { if (name === 'qmSymbols') {
return [{ return [
symbol: 'X', {
symbolId: 123456, symbol: 'X',
qmSearchCode: 'X:NYSE', symbolId: 123456,
exchange: 'NYSE', qmSearchCode: 'X:NYSE',
name: 'United States Steel Corporation' exchange: 'NYSE',
}]; name: 'United States Steel Corporation',
} },
return []; ];
} }
}), return [];
findOne: async (query: any) => { },
console.log(`Finding one in ${name}:`, query); }),
return null; findOne: async (query: any) => {
}, console.log(`Finding one in ${name}:`, query);
updateOne: async (filter: any, update: any, options: any) => { return null;
console.log(`Updating ${name}:`, { filter, update }); },
return { modifiedCount: 1 }; updateOne: async (filter: any, update: any, _options: any) => {
} console.log(`Updating ${name}:`, { filter, update });
}), return { modifiedCount: 1 };
find: async (collection: string, query: any) => { },
console.log(`Direct find on ${collection}:`, query); }),
if (collection === 'qmSymbols' && query.symbol === 'X') { find: async (collection: string, query: any) => {
return [{ console.log(`Direct find on ${collection}:`, query);
symbol: 'X', if (collection === 'qmSymbols' && query.symbol === 'X') {
symbolId: 123456, return [
qmSearchCode: 'X:NYSE' {
}]; symbol: 'X',
} symbolId: 123456,
return []; qmSearchCode: 'X:NYSE',
} },
} as any, ];
logger: { }
info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, data || ''), return [];
error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''), },
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''), } as any,
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || '') logger: {
} info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, data || ''),
} as DataIngestionServices; error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''),
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''),
// Test 1: Check stale operations for symbol X debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
console.log('Test 1: Get stale operations for symbol X'); },
console.log('------------------------------------------'); } as DataIngestionServices;
const tracker = new OperationTracker(mockServices as any); // Test 1: Check stale operations for symbol X
console.log('Test 1: Get stale operations for symbol X');
try { console.log('------------------------------------------');
// Check each operation type
const operations = [ const tracker = new OperationTracker(mockServices as any);
'symbol_info',
'price_update', try {
'intraday_bars', // Check each operation type
'financials_update_quarterly', const operations = [
'financials_update_annual', 'symbol_info',
'events_update', 'price_update',
'filings_update', 'intraday_bars',
'insiders_update', 'financials_update_quarterly',
'news_update' 'financials_update_annual',
]; 'events_update',
'filings_update',
for (const operation of operations) { 'insiders_update',
console.log(`\nChecking ${operation}:`); 'news_update',
];
const staleSymbols = await tracker.getStaleSymbols('qm', operation, {
minHoursSinceRun: 0, // Get all symbols regardless of last run for (const operation of operations) {
limit: 10, console.log(`\nChecking ${operation}:`);
symbolFilter: { symbol: 'X' } // Only get symbol X
}); const staleSymbols = await tracker.getStaleSymbols('qm', operation, {
minHoursSinceRun: 0, // Get all symbols regardless of last run
console.log(`Found ${staleSymbols.length} stale symbols:`, staleSymbols); limit: 10,
} symbolFilter: { symbol: 'X' }, // Only get symbol X
} catch (error) { });
console.error('Error checking stale symbols:', error);
} console.log(`Found ${staleSymbols.length} stale symbols:`, staleSymbols);
}
// Test 2: Check intraday crawl status for symbol X } catch (error) {
console.log('\n\nTest 2: Check intraday crawl status for symbol X'); console.error('Error checking stale symbols:', error);
console.log('------------------------------------------------'); }
try { // Test 2: Check intraday crawl status for symbol X
const symbolsForCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { console.log('\n\nTest 2: Check intraday crawl status for symbol X');
limit: 10, console.log('------------------------------------------------');
symbolFilter: { symbol: 'X' }
}); try {
const symbolsForCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
console.log(`Found ${symbolsForCrawl.length} symbols for intraday crawl`); limit: 10,
if (symbolsForCrawl.length > 0) { symbolFilter: { symbol: 'X' },
console.log('Symbol details:', JSON.stringify(symbolsForCrawl[0], null, 2)); });
}
} catch (error) { console.log(`Found ${symbolsForCrawl.length} symbols for intraday crawl`);
console.error('Error checking intraday crawl:', error); if (symbolsForCrawl.length > 0) {
} console.log('Symbol details:', JSON.stringify(symbolsForCrawl[0], null, 2));
}
console.log('\n=== Tests Complete ==='); } catch (error) {
} console.error('Error checking intraday crawl:', error);
}
// Run the test
testSymbolXOperations().catch(console.error); console.log('\n=== Tests Complete ===');
}
// Run the test
testSymbolXOperations().catch(console.error);

View file

@ -24,7 +24,8 @@
"@stock-bot/shutdown": "*", "@stock-bot/shutdown": "*",
"@stock-bot/handlers": "*", "@stock-bot/handlers": "*",
"@stock-bot/di": "*", "@stock-bot/di": "*",
"hono": "^4.0.0" "hono": "^4.0.0",
"@stock-bot/invariants": "workspace:*"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5.0.0" "typescript": "^5.0.0"

View file

@ -3,7 +3,7 @@
* Configures dependency injection for the data pipeline service * Configures dependency injection for the data pipeline service
*/ */
import type { AppConfig } from '@stock-bot/config'; import type { UnifiedAppConfig } from '@stock-bot/config';
import type { IServiceContainer } from '@stock-bot/handlers'; import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
@ -13,7 +13,7 @@ const logger = getLogger('data-pipeline-container');
* Configure the service container for data pipeline workloads * Configure the service container for data pipeline workloads
*/ */
export function setupServiceContainer( export function setupServiceContainer(
config: AppConfig, config: UnifiedAppConfig,
container: IServiceContainer container: IServiceContainer
): IServiceContainer { ): IServiceContainer {
logger.info('Configuring data pipeline service container...'); logger.info('Configuring data pipeline service container...');

View file

@ -26,7 +26,7 @@ class ExchangesHandler extends BaseHandler {
async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise<unknown> { async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise<unknown> {
const finalPayload = payload || { clearFirst: true }; const finalPayload = payload || { clearFirst: true };
this.log('info', 'Starting sync of all exchanges', finalPayload); this.log('info', 'Starting sync of all exchanges', finalPayload);
return syncAllExchanges(finalPayload, this.services); return syncAllExchanges(finalPayload, this);
} }
/** /**
@ -39,7 +39,7 @@ class ExchangesHandler extends BaseHandler {
}) })
async syncQMExchanges(): Promise<unknown> { async syncQMExchanges(): Promise<unknown> {
this.log('info', 'Starting QM exchanges sync...'); this.log('info', 'Starting QM exchanges sync...');
return syncQMExchanges({}, this.services); return syncQMExchanges({}, this);
} }
/** /**
@ -52,7 +52,7 @@ class ExchangesHandler extends BaseHandler {
}) })
async syncIBExchanges(): Promise<unknown> { async syncIBExchanges(): Promise<unknown> {
this.log('info', 'Starting IB exchanges sync...'); this.log('info', 'Starting IB exchanges sync...');
return syncIBExchanges({}, this.services); return syncIBExchanges({}, this);
} }
/** /**
@ -65,7 +65,7 @@ class ExchangesHandler extends BaseHandler {
}) })
async syncQMProviderMappings(): Promise<unknown> { async syncQMProviderMappings(): Promise<unknown> {
this.log('info', 'Starting QM provider mappings sync...'); this.log('info', 'Starting QM provider mappings sync...');
return syncQMProviderMappings({}, this.services); return syncQMProviderMappings({}, this);
} }
/** /**
@ -76,7 +76,7 @@ class ExchangesHandler extends BaseHandler {
type?: 'exchanges' | 'provider_mappings' | 'all'; type?: 'exchanges' | 'provider_mappings' | 'all';
}): Promise<unknown> { }): Promise<unknown> {
this.log('warn', 'Clearing PostgreSQL data', payload); this.log('warn', 'Clearing PostgreSQL data', payload);
return clearPostgreSQLData(payload, this.services); return clearPostgreSQLData(payload, this);
} }
/** /**
@ -85,7 +85,7 @@ class ExchangesHandler extends BaseHandler {
@Operation('get-exchange-stats') @Operation('get-exchange-stats')
async getExchangeStats(): Promise<unknown> { async getExchangeStats(): Promise<unknown> {
this.log('info', 'Getting exchange statistics...'); this.log('info', 'Getting exchange statistics...');
return getExchangeStats({}, this.services); return getExchangeStats({}, this);
} }
/** /**
@ -94,7 +94,7 @@ class ExchangesHandler extends BaseHandler {
@Operation('get-provider-mapping-stats') @Operation('get-provider-mapping-stats')
async getProviderMappingStats(): Promise<unknown> { async getProviderMappingStats(): Promise<unknown> {
this.log('info', 'Getting provider mapping statistics...'); this.log('info', 'Getting provider mapping statistics...');
return getProviderMappingStats({}, this.services); return getProviderMappingStats({}, this);
} }
/** /**
@ -103,7 +103,7 @@ class ExchangesHandler extends BaseHandler {
@Operation('enhanced-sync-status') @Operation('enhanced-sync-status')
async getEnhancedSyncStatus(): Promise<unknown> { async getEnhancedSyncStatus(): Promise<unknown> {
this.log('info', 'Getting enhanced sync status...'); this.log('info', 'Getting enhanced sync status...');
return getSyncStatus({}, this.services); return getSyncStatus({}, this);
} }
} }

View file

@ -1,5 +1,6 @@
import type { IServiceContainer } from '@stock-bot/handlers'; import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-clear-postgresql-data'); const logger = getLogger('enhanced-sync-clear-postgresql-data');
@ -15,7 +16,7 @@ export async function clearPostgreSQLData(
logger.info('Clearing existing PostgreSQL data...'); logger.info('Clearing existing PostgreSQL data...');
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction for atomic operations // Start transaction for atomic operations
await postgresClient.query('BEGIN'); await postgresClient.query('BEGIN');
@ -29,9 +30,9 @@ export async function clearPostgreSQLData(
'SELECT COUNT(*) as count FROM provider_mappings' 'SELECT COUNT(*) as count FROM provider_mappings'
); );
const exchangesCleared = parseInt(exchangeCountResult.rows[0].count); const exchangesCleared = parseInt(at(exchangeCountResult.rows, 0).count);
const symbolsCleared = parseInt(symbolCountResult.rows[0].count); const symbolsCleared = parseInt(at(symbolCountResult.rows, 0).count);
const mappingsCleared = parseInt(mappingCountResult.rows[0].count); const mappingsCleared = parseInt(at(mappingCountResult.rows, 0).count);
// Clear data in correct order (respect foreign keys) // Clear data in correct order (respect foreign keys)
await postgresClient.query('DELETE FROM provider_mappings'); await postgresClient.query('DELETE FROM provider_mappings');
@ -53,7 +54,7 @@ export async function clearPostgreSQLData(
return { exchangesCleared, symbolsCleared, mappingsCleared }; return { exchangesCleared, symbolsCleared, mappingsCleared };
} catch (error) { } catch (error) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK'); await postgresClient.query('ROLLBACK');
logger.error('Failed to clear PostgreSQL data', { error }); logger.error('Failed to clear PostgreSQL data', { error });
throw error; throw error;

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncStatus } from '../../../types/job-payloads'; import type { JobPayload, SyncStatus } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-status'); const logger = getLogger('enhanced-sync-status');
@ -11,14 +11,14 @@ export async function getSyncStatus(
logger.info('Getting comprehensive sync status...'); logger.info('Getting comprehensive sync status...');
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
SELECT provider, data_type as "dataType", last_sync_at as "lastSyncAt", SELECT provider, data_type as "dataType", last_sync_at as "lastSyncAt",
last_sync_count as "lastSyncCount", sync_errors as "syncErrors" last_sync_count as "lastSyncCount", sync_errors as "syncErrors"
FROM sync_status FROM sync_status
ORDER BY provider, data_type ORDER BY provider, data_type
`; `;
const result = await postgresClient.query(query); const result = await postgresClient.query<SyncStatus>(query);
logger.info(`Retrieved sync status for ${result.rows.length} entries`); logger.info(`Retrieved sync status for ${result.rows.length} entries`);
return result.rows; return result.rows;

View file

@ -1,5 +1,6 @@
import type { IServiceContainer } from '@stock-bot/handlers'; import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-exchange-stats'); const logger = getLogger('enhanced-sync-exchange-stats');
@ -18,7 +19,7 @@ export async function getExchangeStats(
logger.info('Getting exchange statistics...'); logger.info('Getting exchange statistics...');
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
SELECT SELECT
COUNT(*) as total_exchanges, COUNT(*) as total_exchanges,
@ -27,10 +28,10 @@ export async function getExchangeStats(
COUNT(DISTINCT currency) as currencies COUNT(DISTINCT currency) as currencies
FROM exchanges FROM exchanges
`; `;
const result = await postgresClient.query(query); const result = await postgresClient.query<ExchangeStats>(query);
logger.info('Retrieved exchange statistics'); logger.info('Retrieved exchange statistics');
return result.rows[0]; return at(result.rows, 0);
} catch (error) { } catch (error) {
logger.error('Failed to get exchange statistics', { error }); logger.error('Failed to get exchange statistics', { error });
throw error; throw error;

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-provider-mapping-stats'); const logger = getLogger('enhanced-sync-provider-mapping-stats');
@ -20,7 +20,7 @@ export async function getProviderMappingStats(
logger.info('Getting provider mapping statistics...'); logger.info('Getting provider mapping statistics...');
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
SELECT SELECT
provider, provider,
@ -33,7 +33,7 @@ export async function getProviderMappingStats(
GROUP BY provider GROUP BY provider
ORDER BY provider ORDER BY provider
`; `;
const result = await postgresClient.query(query); const result = await postgresClient.query<ProviderMappingStats>(query);
logger.info('Retrieved provider mapping statistics'); logger.info('Retrieved provider mapping statistics');
return result.rows; return result.rows;

View file

@ -1,5 +1,5 @@
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services'; import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-qm-exchanges'); const logger = getLogger('sync-qm-exchanges');
@ -11,8 +11,8 @@ export async function syncQMExchanges(
logger.info('Starting QM exchanges sync...'); logger.info('Starting QM exchanges sync...');
try { try {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// 1. Get all QM exchanges from MongoDB // 1. Get all QM exchanges from MongoDB
const qmExchanges = await mongoClient.find('qmExchanges', {}); const qmExchanges = await mongoClient.find('qmExchanges', {});
@ -64,10 +64,10 @@ interface Exchange {
async function findExchange( async function findExchange(
exchangeCode: string, exchangeCode: string,
postgresClient: IServiceContainer['postgres'] postgresClient: NonNullable<IServiceContainer['postgres']>
): Promise<Exchange | null> { ): Promise<Exchange | null> {
const query = 'SELECT * FROM exchanges WHERE code = $1'; const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [exchangeCode]); const result = await postgresClient.query<Exchange>(query, [exchangeCode]);
return result.rows[0] || null; return result.rows[0] || null;
} }
@ -81,7 +81,7 @@ interface QMExchange {
async function createExchange( async function createExchange(
qmExchange: QMExchange, qmExchange: QMExchange,
postgresClient: IServiceContainer['postgres'] postgresClient: NonNullable<IServiceContainer['postgres']>
): Promise<void> { ): Promise<void> {
const query = ` const query = `
INSERT INTO exchanges (code, name, country, currency, visible) INSERT INTO exchanges (code, name, country, currency, visible)
@ -101,7 +101,7 @@ async function createExchange(
async function updateExchange( async function updateExchange(
exchangeId: string, exchangeId: string,
qmExchange: QMExchange, qmExchange: QMExchange,
postgresClient: IServiceContainer['postgres'] postgresClient: NonNullable<IServiceContainer['postgres']>
): Promise<void> { ): Promise<void> {
const query = ` const query = `
UPDATE exchanges UPDATE exchanges
@ -122,7 +122,7 @@ async function updateSyncStatus(
provider: string, provider: string,
dataType: string, dataType: string,
count: number, count: number,
postgresClient: IServiceContainer['postgres'] postgresClient: NonNullable<IServiceContainer['postgres']>
): Promise<void> { ): Promise<void> {
const query = ` const query = `
UPDATE sync_status UPDATE sync_status

View file

@ -1,5 +1,6 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncResult } from '../../../types/job-payloads'; import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-all-exchanges'); const logger = getLogger('enhanced-sync-all-exchanges');
@ -20,7 +21,7 @@ export async function syncAllExchanges(
}; };
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Clear existing data if requested // Clear existing data if requested
if (clearFirst) { if (clearFirst) {
@ -46,14 +47,14 @@ export async function syncAllExchanges(
logger.info('Comprehensive exchange sync completed', result); logger.info('Comprehensive exchange sync completed', result);
return result; return result;
} catch (error) { } catch (error) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK'); await postgresClient.query('ROLLBACK');
logger.error('Comprehensive exchange sync failed', { error }); logger.error('Comprehensive exchange sync failed', { error });
throw error; throw error;
} }
} }
async function clearPostgreSQLData(postgresClient: any): Promise<void> { async function clearPostgreSQLData(postgresClient: PostgresClient): Promise<void> {
logger.info('Clearing existing PostgreSQL data...'); logger.info('Clearing existing PostgreSQL data...');
// Clear data in correct order (respect foreign keys) // Clear data in correct order (respect foreign keys)
@ -70,7 +71,7 @@ async function clearPostgreSQLData(postgresClient: any): Promise<void> {
} }
async function syncEODExchanges(container: IServiceContainer): Promise<SyncResult> { async function syncEODExchanges(container: IServiceContainer): Promise<SyncResult> {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const exchanges = await mongoClient.find('eodExchanges', { active: true }); const exchanges = await mongoClient.find('eodExchanges', { active: true });
const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 };
@ -99,7 +100,7 @@ async function syncEODExchanges(container: IServiceContainer): Promise<SyncResul
} }
async function syncIBExchanges(container: IServiceContainer): Promise<SyncResult> { async function syncIBExchanges(container: IServiceContainer): Promise<SyncResult> {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const exchanges = await mongoClient.find('ibExchanges', {}); const exchanges = await mongoClient.find('ibExchanges', {});
const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 };
@ -140,7 +141,7 @@ async function createProviderExchangeMapping(
return; return;
} }
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists // Check if mapping already exists
const existingMapping = await findProviderExchangeMapping( const existingMapping = await findProviderExchangeMapping(
@ -162,6 +163,10 @@ async function createProviderExchangeMapping(
container container
); );
if (!masterExchange) {
throw new Error('Master exchange was not created or resolved');
}
// Create the provider exchange mapping // Create the provider exchange mapping
const query = ` const query = `
INSERT INTO provider_exchange_mappings INSERT INTO provider_exchange_mappings
@ -188,8 +193,8 @@ async function findOrCreateMasterExchange(
countryCode: string | null, countryCode: string | null,
currency: string | null, currency: string | null,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match // First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container); let masterExchange = await findExchangeByCode(providerCode, container);
@ -244,16 +249,16 @@ async function findProviderExchangeMapping(
provider: string, provider: string,
providerExchangeCode: string, providerExchangeCode: string,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = const query =
'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2';
const result = await postgresClient.query(query, [provider, providerExchangeCode]); const result = await postgresClient.query(query, [provider, providerExchangeCode]);
return result.rows[0] || null; return result.rows[0] || null;
} }
async function findExchangeByCode(code: string, container: IServiceContainer): Promise<any> { async function findExchangeByCode(code: string, container: IServiceContainer) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM exchanges WHERE code = $1'; const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [code]); const result = await postgresClient.query(query, [code]);
return result.rows[0] || null; return result.rows[0] || null;
@ -263,7 +268,7 @@ async function updateSyncStatus(
provider: string, provider: string,
dataType: string, dataType: string,
count: number, count: number,
postgresClient: any postgresClient: PostgresClient
): Promise<void> { ): Promise<void> {
const query = ` const query = `
INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors)

View file

@ -1,13 +1,13 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { MasterExchange } from '@stock-bot/mongodb'; import type { MasterExchange } from '@stock-bot/mongodb';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-ib-exchanges'); const logger = getLogger('sync-ib-exchanges');
interface IBExchange { interface IBExchange {
id?: string; id?: string;
_id?: any; _id?: unknown;
name?: string; name?: string;
code?: string; code?: string;
country_code?: string; country_code?: string;
@ -21,7 +21,7 @@ export async function syncIBExchanges(
logger.info('Syncing IB exchanges from database...'); logger.info('Syncing IB exchanges from database...');
try { try {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase(); const db = mongoClient.getDatabase();
// Filter by country code US and CA // Filter by country code US and CA
@ -69,7 +69,7 @@ async function createOrUpdateMasterExchange(
ibExchange: IBExchange, ibExchange: IBExchange,
container: IServiceContainer container: IServiceContainer
): Promise<void> { ): Promise<void> {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase(); const db = mongoClient.getDatabase();
const collection = db.collection<MasterExchange>('masterExchanges'); const collection = db.collection<MasterExchange>('masterExchanges');

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncResult } from '../../../types/job-payloads'; import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-qm-provider-mappings'); const logger = getLogger('enhanced-sync-qm-provider-mappings');
@ -19,8 +19,8 @@ export async function syncQMProviderMappings(
}; };
try { try {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction // Start transaction
await postgresClient.query('BEGIN'); await postgresClient.query('BEGIN');
@ -79,7 +79,7 @@ export async function syncQMProviderMappings(
logger.info('QM provider exchange mappings sync completed', result); logger.info('QM provider exchange mappings sync completed', result);
return result; return result;
} catch (error) { } catch (error) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK'); await postgresClient.query('ROLLBACK');
logger.error('QM provider exchange mappings sync failed', { error }); logger.error('QM provider exchange mappings sync failed', { error });
throw error; throw error;
@ -99,7 +99,7 @@ async function createProviderExchangeMapping(
return; return;
} }
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists // Check if mapping already exists
const existingMapping = await findProviderExchangeMapping( const existingMapping = await findProviderExchangeMapping(
@ -121,6 +121,10 @@ async function createProviderExchangeMapping(
container container
); );
if (!masterExchange) {
throw new Error('Master exchange was not created or resolved');
}
// Create the provider exchange mapping // Create the provider exchange mapping
const query = ` const query = `
INSERT INTO provider_exchange_mappings INSERT INTO provider_exchange_mappings
@ -145,8 +149,8 @@ async function findProviderExchangeMapping(
provider: string, provider: string,
providerExchangeCode: string, providerExchangeCode: string,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = const query =
'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2';
const result = await postgresClient.query(query, [provider, providerExchangeCode]); const result = await postgresClient.query(query, [provider, providerExchangeCode]);
@ -159,8 +163,8 @@ async function findOrCreateMasterExchange(
countryCode: string | null, countryCode: string | null,
currency: string | null, currency: string | null,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match // First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container); let masterExchange = await findExchangeByCode(providerCode, container);
@ -211,8 +215,8 @@ function getBasicExchangeMapping(providerCode: string): string | null {
return mappings[providerCode.toUpperCase()] || null; return mappings[providerCode.toUpperCase()] || null;
} }
async function findExchangeByCode(code: string, container: IServiceContainer): Promise<any> { async function findExchangeByCode(code: string, container: IServiceContainer) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM exchanges WHERE code = $1'; const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [code]); const result = await postgresClient.query(query, [code]);
return result.rows[0] || null; return result.rows[0] || null;

View file

@ -1,3 +1,4 @@
import type { HandlerInitializationContext } from '@stock-bot/di';
/** /**
* Handler registration for data pipeline service * Handler registration for data pipeline service
*/ */
@ -13,7 +14,10 @@ const logger = getLogger('pipeline-handler-init');
/** /**
* Initialize and register all handlers * Initialize and register all handlers
*/ */
export async function initializeAllHandlers(container: IServiceContainer): Promise<void> { export async function initializeAllHandlers(
_container: IServiceContainer,
context: HandlerInitializationContext
): Promise<void> {
logger.info('Initializing data pipeline handlers...'); logger.info('Initializing data pipeline handlers...');
try { try {
@ -22,7 +26,7 @@ export async function initializeAllHandlers(container: IServiceContainer): Promi
for (const Handler of handlers) { for (const Handler of handlers) {
try { try {
const instance = new Handler(container); context.handlerScanner.registerHandlerClass(Handler, { serviceName: 'data-pipeline' });
// Register the handler instance if needed // Register the handler instance if needed
logger.info(`Registered handler: ${Handler.name}`); logger.info(`Registered handler: ${Handler.name}`);
} catch (error) { } catch (error) {

View file

@ -1,5 +1,8 @@
import type { IServiceContainer } from '@stock-bot/handlers'; import type { Document } from 'mongodb';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-qm-symbols'); const logger = getLogger('sync-qm-symbols');
@ -11,8 +14,8 @@ export async function syncQMSymbols(
logger.info('Starting QM symbols sync...'); logger.info('Starting QM symbols sync...');
try { try {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// 1. Get all QM symbols from MongoDB // 1. Get all QM symbols from MongoDB
const qmSymbols = await mongoClient.find('qmSymbols', {}); const qmSymbols = await mongoClient.find('qmSymbols', {});
@ -69,7 +72,10 @@ export async function syncQMSymbols(
} }
// Helper functions // Helper functions
async function resolveExchange(exchangeCode: string, postgresClient: any): Promise<string | null> { async function resolveExchange(
exchangeCode: string,
postgresClient: PostgresClient
): Promise<string | null> {
if (!exchangeCode) { if (!exchangeCode) {
return null; return null;
} }
@ -94,16 +100,16 @@ async function resolveExchange(exchangeCode: string, postgresClient: any): Promi
return result.rows[0]?.id || null; return result.rows[0]?.id || null;
} }
async function findSymbol(symbol: string, exchangeId: string, postgresClient: any): Promise<any> { async function findSymbol(symbol: string, exchangeId: string, postgresClient: PostgresClient) {
const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2'; const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2';
const result = await postgresClient.query(query, [symbol, exchangeId]); const result = await postgresClient.query(query, [symbol, exchangeId]);
return result.rows[0] || null; return result.rows[0] || null;
} }
async function createSymbol( async function createSymbol(
qmSymbol: any, qmSymbol: Document,
exchangeId: string, exchangeId: string,
postgresClient: any postgresClient: PostgresClient
): Promise<string> { ): Promise<string> {
const query = ` const query = `
INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
@ -119,10 +125,14 @@ async function createSymbol(
qmSymbol.currency || 'USD', qmSymbol.currency || 'USD',
]); ]);
return result.rows[0].id; return at(result.rows, 0).id;
} }
async function updateSymbol(symbolId: string, qmSymbol: any, postgresClient: any): Promise<void> { async function updateSymbol(
symbolId: string,
qmSymbol: Document,
postgresClient: PostgresClient
): Promise<void> {
const query = ` const query = `
UPDATE symbols UPDATE symbols
SET company_name = COALESCE($2, company_name), SET company_name = COALESCE($2, company_name),
@ -143,8 +153,8 @@ async function updateSymbol(symbolId: string, qmSymbol: any, postgresClient: any
async function upsertProviderMapping( async function upsertProviderMapping(
symbolId: string, symbolId: string,
provider: string, provider: string,
qmSymbol: any, qmSymbol: Document,
postgresClient: any postgresClient: PostgresClient
): Promise<void> { ): Promise<void> {
const query = ` const query = `
INSERT INTO provider_mappings INSERT INTO provider_mappings
@ -169,7 +179,7 @@ async function updateSyncStatus(
provider: string, provider: string,
dataType: string, dataType: string,
count: number, count: number,
postgresClient: any postgresClient: PostgresClient
): Promise<void> { ): Promise<void> {
const query = ` const query = `
UPDATE sync_status UPDATE sync_status

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads'; import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-status'); const logger = getLogger('sync-status');
@ -11,7 +11,7 @@ export async function getSyncStatus(
logger.info('Getting sync status...'); logger.info('Getting sync status...');
try { try {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM sync_status ORDER BY provider, data_type'; const query = 'SELECT * FROM sync_status ORDER BY provider, data_type';
const result = await postgresClient.query(query); const result = await postgresClient.query(query);

View file

@ -1,5 +1,8 @@
import type { IServiceContainer } from '@stock-bot/handlers'; import type { Document } from 'mongodb';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
import type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncResult } from '../../../types/job-payloads'; import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-symbols-from-provider'); const logger = getLogger('enhanced-sync-symbols-from-provider');
@ -26,8 +29,8 @@ export async function syncSymbolsFromProvider(
}; };
try { try {
const mongoClient = container.mongodb; const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
// Clear existing data if requested (only symbols and mappings, keep exchanges) // Clear existing data if requested (only symbols and mappings, keep exchanges)
if (clearFirst) { if (clearFirst) {
@ -76,21 +79,26 @@ export async function syncSymbolsFromProvider(
} }
// Update sync status // Update sync status
await updateSyncStatus(provider, 'symbols', result.processed, container.postgres); await updateSyncStatus(
provider,
'symbols',
result.processed,
requireServices(container, 'postgres').postgres
);
await postgresClient.query('COMMIT'); await postgresClient.query('COMMIT');
logger.info(`${provider} symbols sync completed`, result); logger.info(`${provider} symbols sync completed`, result);
return result; return result;
} catch (error) { } catch (error) {
await container.postgres.query('ROLLBACK'); await requireServices(container, 'postgres').postgres.query('ROLLBACK');
logger.error(`${provider} symbols sync failed`, { error }); logger.error(`${provider} symbols sync failed`, { error });
throw error; throw error;
} }
} }
async function processSingleSymbol( async function processSingleSymbol(
symbol: any, symbol: Document,
provider: string, provider: string,
result: SyncResult, result: SyncResult,
container: IServiceContainer container: IServiceContainer
@ -137,8 +145,8 @@ async function findActiveProviderExchangeMapping(
provider: string, provider: string,
providerExchangeCode: string, providerExchangeCode: string,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
SELECT pem.*, e.code as master_exchange_code SELECT pem.*, e.code as master_exchange_code
FROM provider_exchange_mappings pem FROM provider_exchange_mappings pem
@ -153,19 +161,19 @@ async function findSymbolByCodeAndExchange(
symbol: string, symbol: string,
exchangeId: string, exchangeId: string,
container: IServiceContainer container: IServiceContainer
): Promise<any> { ) {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2'; const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2';
const result = await postgresClient.query(query, [symbol, exchangeId]); const result = await postgresClient.query(query, [symbol, exchangeId]);
return result.rows[0] || null; return result.rows[0] || null;
} }
async function createSymbol( async function createSymbol(
symbol: any, symbol: Document,
exchangeId: string, exchangeId: string,
container: IServiceContainer container: IServiceContainer
): Promise<string> { ): Promise<string> {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5)
@ -180,15 +188,15 @@ async function createSymbol(
symbol.currency || 'USD', symbol.currency || 'USD',
]); ]);
return result.rows[0].id; return at(result.rows, 0).id;
} }
async function updateSymbol( async function updateSymbol(
symbolId: string, symbolId: string,
symbol: any, symbol: Document,
container: IServiceContainer container: IServiceContainer
): Promise<void> { ): Promise<void> {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
UPDATE symbols UPDATE symbols
SET company_name = COALESCE($2, company_name), SET company_name = COALESCE($2, company_name),
@ -209,10 +217,10 @@ async function updateSymbol(
async function upsertProviderMapping( async function upsertProviderMapping(
symbolId: string, symbolId: string,
provider: string, provider: string,
symbol: any, symbol: Document,
container: IServiceContainer container: IServiceContainer
): Promise<void> { ): Promise<void> {
const postgresClient = container.postgres; const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = ` const query = `
INSERT INTO provider_mappings INSERT INTO provider_mappings
(symbol_id, provider, provider_symbol, provider_exchange, last_seen) (symbol_id, provider, provider_symbol, provider_exchange, last_seen)
@ -236,7 +244,7 @@ async function updateSyncStatus(
provider: string, provider: string,
dataType: string, dataType: string,
count: number, count: number,
postgresClient: any postgresClient: PostgresClient
): Promise<void> { ): Promise<void> {
const query = ` const query = `
INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors)

View file

@ -24,7 +24,7 @@ class SymbolsHandler extends BaseHandler {
}) })
async syncQMSymbols(): Promise<{ processed: number; created: number; updated: number }> { async syncQMSymbols(): Promise<{ processed: number; created: number; updated: number }> {
this.log('info', 'Starting QM symbols sync...'); this.log('info', 'Starting QM symbols sync...');
return syncQMSymbols({}, this.services); return syncQMSymbols({}, this);
} }
/** /**
@ -55,7 +55,7 @@ class SymbolsHandler extends BaseHandler {
@Operation('sync-status') @Operation('sync-status')
async getSyncStatus(): Promise<unknown> { async getSyncStatus(): Promise<unknown> {
this.log('info', 'Getting symbol sync status...'); this.log('info', 'Getting symbol sync status...');
return getSyncStatus({}, this.services); return getSyncStatus({}, this);
} }
/** /**
@ -66,7 +66,7 @@ class SymbolsHandler extends BaseHandler {
clearFirst?: boolean; clearFirst?: boolean;
}): Promise<unknown> { }): Promise<unknown> {
this.log('info', 'Syncing symbols from provider', { provider: payload.provider }); this.log('info', 'Syncing symbols from provider', { provider: payload.provider });
return syncSymbolsFromProvider(payload, this.services); return syncSymbolsFromProvider(payload, this);
} }
} }

View file

@ -44,8 +44,7 @@ const app = new ServiceApplication(
// Custom lifecycle hooks // Custom lifecycle hooks
onContainerReady: container => { onContainerReady: container => {
// Setup service-specific configuration // Setup service-specific configuration
const enhancedContainer = setupServiceContainer(config, container); setupServiceContainer(config, container);
return enhancedContainer;
}, },
onStarted: _port => { onStarted: _port => {
const logger = getLogger('data-pipeline'); const logger = getLogger('data-pipeline');
@ -55,7 +54,7 @@ const app = new ServiceApplication(
); );
// Container factory function // Container factory function
async function createContainer(config: any) { async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) {
const { ServiceContainerBuilder } = await import('@stock-bot/di'); const { ServiceContainerBuilder } = await import('@stock-bot/di');
const builder = new ServiceContainerBuilder(); const builder = new ServiceContainerBuilder();

View file

@ -13,12 +13,6 @@ import { createSyncRoutes } from './sync.routes';
export function createRoutes(container: IServiceContainer): Hono { export function createRoutes(container: IServiceContainer): Hono {
const app = new Hono(); const app = new Hono();
// Add container to context for all routes
app.use('*', async (c, next) => {
c.set('container', container);
await next();
});
// Mount routes // Mount routes
app.route('/health', healthRoutes); app.route('/health', healthRoutes);
app.route('/sync', createSyncRoutes(container)); app.route('/sync', createSyncRoutes(container));

View file

@ -1,4 +1,6 @@
export interface JobPayload { export interface JobPayload {
provider?: string;
clearFirst?: boolean;
[key: string]: unknown; [key: string]: unknown;
} }

View file

@ -1,473 +1,415 @@
use napi::bindgen_prelude::*; use crate::backtest::{BacktestConfig, BacktestEngine as RustBacktestEngine, Signal, Strategy};
use napi_derive::napi; use crate::{MarketUpdate, TradingMode};
use std::sync::Arc; use chrono::{DateTime, Utc};
use parking_lot::Mutex; use napi::bindgen_prelude::*;
use crate::backtest::{ use napi_derive::napi;
BacktestEngine as RustBacktestEngine, use parking_lot::Mutex;
BacktestConfig, use std::sync::Arc;
Strategy, Signal,
}; #[napi]
use crate::{TradingMode, MarketUpdate}; pub struct BacktestEngine {
use chrono::{DateTime, Utc}; inner: Arc<Mutex<Option<RustBacktestEngine>>>,
}
#[napi]
pub struct BacktestEngine { #[napi]
inner: Arc<Mutex<Option<RustBacktestEngine>>>, impl BacktestEngine {
} #[napi(constructor)]
pub fn new(config: napi::JsObject, env: Env) -> Result<Self> {
#[napi] let config = parse_backtest_config(config)?;
impl BacktestEngine {
#[napi(constructor)] // Create mode
pub fn new(config: napi::JsObject, env: Env) -> Result<Self> { let mode = TradingMode::Backtest {
let config = parse_backtest_config(config)?; start_time: config.start_time,
end_time: config.end_time,
// Create mode speed_multiplier: 0.0, // Max speed
let mode = TradingMode::Backtest { };
start_time: config.start_time,
end_time: config.end_time, // Create components
speed_multiplier: 0.0, // Max speed let time_provider = crate::core::create_time_provider(&mode);
}; let market_data_source = crate::core::create_market_data_source(&mode);
let execution_handler = crate::core::create_execution_handler(&mode);
// Create components
let time_provider = crate::core::create_time_provider(&mode); let engine = RustBacktestEngine::new(
let market_data_source = crate::core::create_market_data_source(&mode); config,
let execution_handler = crate::core::create_execution_handler(&mode); mode,
time_provider,
let engine = RustBacktestEngine::new( market_data_source,
config, execution_handler,
mode, );
time_provider,
market_data_source, Ok(Self {
execution_handler, inner: Arc::new(Mutex::new(Some(engine))),
); })
}
Ok(Self {
inner: Arc::new(Mutex::new(Some(engine))), #[napi]
}) pub fn add_typescript_strategy(
} &mut self,
_name: String,
#[napi] _id: String,
pub fn add_typescript_strategy( _parameters: napi::JsObject,
&mut self, _callback: napi::JsFunction,
name: String, ) -> Result<()> {
id: String, Err(Error::from_reason(
parameters: napi::JsObject, "TypeScript strategy callbacks are not supported by the native engine",
_callback: napi::JsFunction, ))
) -> Result<()> { }
eprintln!("Adding strategy: {}", name);
#[napi]
// For now, we'll add a native Rust SMA strategy pub fn add_native_strategy(
// In the future, we'll implement proper TypeScript callback support &mut self,
let fast_period: usize = parameters.get_named_property::<f64>("fastPeriod") strategy_type: String,
.unwrap_or(5.0) as usize; name: String,
let slow_period: usize = parameters.get_named_property::<f64>("slowPeriod") id: String,
.unwrap_or(15.0) as usize; parameters: napi::JsObject,
) -> Result<()> {
if let Some(engine) = self.inner.lock().as_mut() { if let Some(engine) = self.inner.lock().as_mut() {
engine.add_strategy(Box::new(SimpleSMAStrategy::new( match strategy_type.as_str() {
name.clone(), "sma_crossover" => {
id, let fast_period: usize = parameters
fast_period, .get_named_property::<f64>("fastPeriod")
slow_period, .unwrap_or(5.0) as usize;
))); let slow_period: usize = parameters
eprintln!("Strategy '{}' added with fast={}, slow={}", name, fast_period, slow_period); .get_named_property::<f64>("slowPeriod")
} .unwrap_or(15.0) as usize;
Ok(()) if fast_period == 0 || fast_period >= slow_period {
} return Err(Error::from_reason(
"SMA periods must satisfy 0 < fastPeriod < slowPeriod",
#[napi] ));
pub fn add_native_strategy( }
&mut self, engine.add_strategy(Box::new(SimpleSMAStrategy::new(
strategy_type: String, name.clone(),
name: String, id,
id: String, fast_period,
parameters: napi::JsObject, slow_period,
) -> Result<()> { )));
eprintln!("Adding native Rust strategy: {} ({})", name, strategy_type); }
"mean_reversion" => {
if let Some(engine) = self.inner.lock().as_mut() { let lookback_period: usize = parameters
match strategy_type.as_str() { .get_named_property::<f64>("lookbackPeriod")
"sma_crossover" => { .unwrap_or(20.0) as usize;
let fast_period: usize = parameters.get_named_property::<f64>("fastPeriod") let entry_threshold: f64 = parameters
.unwrap_or(5.0) as usize; .get_named_property::<f64>("entryThreshold")
let slow_period: usize = parameters.get_named_property::<f64>("slowPeriod") .unwrap_or(2.0);
.unwrap_or(15.0) as usize; let position_size: f64 = parameters
.get_named_property::<f64>("positionSize")
engine.add_strategy(Box::new(SimpleSMAStrategy::new( .unwrap_or(100.0);
name.clone(),
id, engine.add_strategy(Box::new(
fast_period, crate::strategies::MeanReversionFixedStrategy::new(
slow_period, name.clone(),
))); id,
} lookback_period,
"mean_reversion" => { entry_threshold,
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod") position_size,
.unwrap_or(20.0) as usize; ),
let entry_threshold: f64 = parameters.get_named_property::<f64>("entryThreshold") ));
.unwrap_or(2.0); }
let position_size: f64 = parameters.get_named_property::<f64>("positionSize") "momentum" => {
.unwrap_or(100.0); let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
engine.add_strategy(Box::new(crate::strategies::MeanReversionFixedStrategy::new( .unwrap_or(14.0) as usize;
name.clone(), let momentum_threshold: f64 = parameters
id, .get_named_property::<f64>("momentumThreshold")
lookback_period, .unwrap_or(5.0);
entry_threshold, let position_size: f64 = parameters
position_size, .get_named_property::<f64>("positionSize")
))); .unwrap_or(100.0);
}
"momentum" => { engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod") name.clone(),
.unwrap_or(14.0) as usize; id,
let momentum_threshold: f64 = parameters.get_named_property::<f64>("momentumThreshold") lookback_period,
.unwrap_or(5.0); momentum_threshold,
let position_size: f64 = parameters.get_named_property::<f64>("positionSize") position_size,
.unwrap_or(100.0); )));
}
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new( "pairs_trading" => {
name.clone(), let pair_a: String = parameters.get_named_property::<String>("pairA")?;
id, let pair_b: String = parameters.get_named_property::<String>("pairB")?;
lookback_period, let lookback_period: usize = parameters
momentum_threshold, .get_named_property::<f64>("lookbackPeriod")
position_size, .unwrap_or(20.0) as usize;
))); let entry_threshold: f64 = parameters
} .get_named_property::<f64>("entryThreshold")
"pairs_trading" => { .unwrap_or(2.0);
let pair_a: String = parameters.get_named_property::<String>("pairA")?; let position_size: f64 = parameters
let pair_b: String = parameters.get_named_property::<String>("pairB")?; .get_named_property::<f64>("positionSize")
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod") .unwrap_or(100.0);
.unwrap_or(20.0) as usize;
let entry_threshold: f64 = parameters.get_named_property::<f64>("entryThreshold") engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
.unwrap_or(2.0); name.clone(),
let position_size: f64 = parameters.get_named_property::<f64>("positionSize") id,
.unwrap_or(100.0); pair_a,
pair_b,
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new( lookback_period,
name.clone(), entry_threshold,
id, position_size,
pair_a, )));
pair_b, }
lookback_period, _ => {
entry_threshold, return Err(Error::from_reason(format!(
position_size, "Unknown strategy type: {}",
))); strategy_type
} )));
_ => { }
return Err(Error::from_reason(format!("Unknown strategy type: {}", strategy_type))); }
} }
}
eprintln!("Native strategy '{}' added successfully", name); Ok(())
} }
Ok(()) #[napi]
} pub fn run(&mut self) -> Result<String> {
let mut engine = self
#[napi] .inner
pub fn run(&mut self) -> Result<String> { .lock()
eprintln!("=== BACKTEST RUN START ==="); .take()
let mut engine = self.inner.lock().take() .ok_or_else(|| Error::from_reason("Engine already consumed"))?;
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
// Config and strategies are private, skip detailed logging
// Config and strategies are private, skip detailed logging
// Run the backtest synchronously for now
// Run the backtest synchronously for now let runtime =
let runtime = tokio::runtime::Runtime::new() tokio::runtime::Runtime::new().map_err(|e| Error::from_reason(e.to_string()))?;
.map_err(|e| Error::from_reason(e.to_string()))?;
let result = runtime
let result = runtime.block_on(engine.run()) .block_on(engine.run())
.map_err(|e| { .map_err(|e| Error::from_reason(e))?;
eprintln!("ERROR: Backtest engine failed: {}", e); for (symbol, data) in &result.ohlc_data {}
Error::from_reason(e)
})?; // Return result as JSON
serde_json::to_string(&result).map_err(|e| Error::from_reason(e.to_string()))
eprintln!("=== BACKTEST RUN COMPLETE ==="); }
eprintln!("Total trades: {}", result.trades.len());
eprintln!("Equity points: {}", result.equity.len()); #[napi]
eprintln!("OHLC data symbols: {:?}", result.ohlc_data.keys().collect::<Vec<_>>()); pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> {
for (symbol, data) in &result.ohlc_data { // Convert JS objects to MarketData
eprintln!(" {}: {} bars", symbol, data.len()); let market_data: Vec<MarketUpdate> = data
} .into_iter()
.filter_map(|obj| parse_market_data(obj).ok())
// Return result as JSON .collect();
serde_json::to_string(&result)
.map_err(|e| Error::from_reason(e.to_string())) // Load data into the historical data source
} if let Some(engine) = self.inner.lock().as_ref() {
// Access the market data source through the engine
#[napi] let mut data_source = engine.market_data_source.write();
pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> { if let Some(historical_source) = data_source
eprintln!("load_market_data called with {} items", data.len()); .as_any_mut()
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>(
// Convert JS objects to MarketData ) {
let market_data: Vec<MarketUpdate> = data.into_iter() historical_source.load_data(market_data);
.filter_map(|obj| parse_market_data(obj).ok()) } else {
.collect(); }
} else {
eprintln!("Parsed {} valid market data items", market_data.len()); }
// Load data into the historical data source Ok(())
if let Some(engine) = self.inner.lock().as_ref() { }
// Access the market data source through the engine }
let mut data_source = engine.market_data_source.write();
if let Some(historical_source) = data_source.as_any_mut() fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>() { let name: String = obj.get_named_property("name")?;
eprintln!("Loading data into HistoricalDataSource"); let symbols: Vec<String> = obj.get_named_property("symbols")?;
historical_source.load_data(market_data); let start_date: String = obj.get_named_property("startDate")?;
eprintln!("Data loaded successfully"); let end_date: String = obj.get_named_property("endDate")?;
} else { let initial_capital: f64 = obj.get_named_property("initialCapital")?;
eprintln!("ERROR: Could not downcast to HistoricalDataSource"); let commission: f64 = obj.get_named_property("commission")?;
} let slippage: f64 = obj.get_named_property("slippage")?;
} else { let data_frequency: String = obj.get_named_property("dataFrequency")?;
eprintln!("ERROR: Engine not found"); let strategy: Option<String> = obj.get_named_property("strategy").ok();
}
Ok(BacktestConfig {
Ok(()) name,
} strategy,
} symbols,
start_time: DateTime::parse_from_rfc3339(&start_date)
.map_err(|e| Error::from_reason(e.to_string()))?
fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> { .with_timezone(&Utc),
let name: String = obj.get_named_property("name")?; end_time: DateTime::parse_from_rfc3339(&end_date)
let symbols: Vec<String> = obj.get_named_property("symbols")?; .map_err(|e| Error::from_reason(e.to_string()))?
let start_date: String = obj.get_named_property("startDate")?; .with_timezone(&Utc),
let end_date: String = obj.get_named_property("endDate")?; initial_capital,
let initial_capital: f64 = obj.get_named_property("initialCapital")?; commission,
let commission: f64 = obj.get_named_property("commission")?; slippage,
let slippage: f64 = obj.get_named_property("slippage")?; data_frequency,
let data_frequency: String = obj.get_named_property("dataFrequency")?; })
let strategy: Option<String> = obj.get_named_property("strategy").ok(); }
Ok(BacktestConfig { fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
name, let symbol: String = obj.get_named_property("symbol")?;
strategy, let timestamp: i64 = obj.get_named_property("timestamp")?;
symbols, let data_type: String = obj.get_named_property("type")?;
start_time: DateTime::parse_from_rfc3339(&start_date)
.map_err(|e| Error::from_reason(e.to_string()))? let data = if data_type == "bar" {
.with_timezone(&Utc), crate::MarketDataType::Bar(crate::Bar {
end_time: DateTime::parse_from_rfc3339(&end_date) open: obj.get_named_property("open")?,
.map_err(|e| Error::from_reason(e.to_string()))? high: obj.get_named_property("high")?,
.with_timezone(&Utc), low: obj.get_named_property("low")?,
initial_capital, close: obj.get_named_property("close")?,
commission, volume: obj.get_named_property("volume")?,
slippage, vwap: obj.get_named_property("vwap").ok(),
data_frequency, })
}) } else {
} return Err(Error::from_reason("Unsupported market data type"));
};
fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
let symbol: String = obj.get_named_property("symbol")?; Ok(crate::MarketUpdate {
let timestamp: i64 = obj.get_named_property("timestamp")?; symbol,
let data_type: String = obj.get_named_property("type")?; timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
let data = if data_type == "bar" { data,
crate::MarketDataType::Bar(crate::Bar { })
open: obj.get_named_property("open")?, }
high: obj.get_named_property("high")?,
low: obj.get_named_property("low")?, // Simple SMA Strategy for testing
close: obj.get_named_property("close")?, struct SimpleSMAStrategy {
volume: obj.get_named_property("volume")?, name: String,
vwap: obj.get_named_property("vwap").ok(), id: String,
}) fast_period: usize,
} else { slow_period: usize,
eprintln!("Unsupported market data type: {}", data_type); price_history: std::collections::HashMap<String, Vec<f64>>,
return Err(Error::from_reason("Unsupported market data type")); positions: std::collections::HashMap<String, f64>,
}; }
// First few items impl SimpleSMAStrategy {
static mut COUNT: usize = 0; fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self {
unsafe { Self {
if COUNT < 3 { name,
eprintln!("Parsed market data: symbol={}, timestamp={}, close={}", id,
symbol, timestamp, fast_period,
if let crate::MarketDataType::Bar(ref bar) = data { bar.close } else { 0.0 }); slow_period,
COUNT += 1; price_history: std::collections::HashMap::new(),
} positions: std::collections::HashMap::new(),
} }
}
Ok(crate::MarketUpdate { }
symbol,
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0) impl Strategy for SimpleSMAStrategy {
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?, fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
data, let mut signals = Vec::new();
})
} // Check if it's bar data
if let crate::MarketDataType::Bar(bar) = &data.data {
// Simple SMA Strategy for testing let symbol = &data.symbol;
struct SimpleSMAStrategy { let price = bar.close;
name: String,
id: String, // Update price history
fast_period: usize, let history = self
slow_period: usize, .price_history
price_history: std::collections::HashMap<String, Vec<f64>>, .entry(symbol.clone())
positions: std::collections::HashMap<String, f64>, .or_insert_with(Vec::new);
} history.push(price);
impl SimpleSMAStrategy { // Keep only necessary history (need one extra for previous SMA calculation)
fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self { if history.len() > self.slow_period + 1 {
eprintln!("Creating SimpleSMAStrategy: name={}, fast={}, slow={}", name, fast_period, slow_period); history.remove(0);
Self { }
name,
id, // Need enough data
fast_period, if history.len() >= self.slow_period {
slow_period, // Calculate SMAs
price_history: std::collections::HashMap::new(), let fast_sma = history[history.len() - self.fast_period..]
positions: std::collections::HashMap::new(), .iter()
} .sum::<f64>()
} / self.fast_period as f64;
} let slow_sma = history[history.len() - self.slow_period..]
.iter()
impl Strategy for SimpleSMAStrategy { .sum::<f64>()
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> { / self.slow_period as f64;
// Count calls
static mut CALL_COUNT: usize = 0; // Previous SMAs (if we have enough history)
unsafe { if history.len() > self.slow_period {
CALL_COUNT += 1; let prev_history = &history[..history.len() - 1];
if CALL_COUNT % 100 == 1 { let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..]
eprintln!("SimpleSMAStrategy.on_market_data called {} times", CALL_COUNT); .iter()
} .sum::<f64>()
} / self.fast_period as f64;
let prev_slow_sma =
let mut signals = Vec::new(); prev_history.iter().sum::<f64>() / prev_history.len() as f64;
// Check if it's bar data let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
if let crate::MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol; // Golden cross - buy signal
let price = bar.close; if prev_fast_sma <= prev_slow_sma
&& fast_sma > slow_sma
// Update price history && current_position <= 0.0
let history = self.price_history.entry(symbol.clone()).or_insert_with(Vec::new); {
history.push(price); signals.push(Signal {
symbol: symbol.clone(),
// Debug: Log first few prices signal_type: crate::backtest::SignalType::Buy,
if history.len() <= 3 { strength: 1.0,
eprintln!("Price history for {}: {:?}", symbol, history); quantity: Some(100.0), // Fixed quantity for testing
} else if history.len() == 10 || history.len() == 15 { reason: Some("Golden cross".to_string()),
eprintln!("Price history length for {}: {} bars", symbol, history.len()); metadata: None,
} });
}
// Keep only necessary history (need one extra for previous SMA calculation) // Death cross - sell signal
if history.len() > self.slow_period + 1 { else if prev_fast_sma >= prev_slow_sma
history.remove(0); && fast_sma < slow_sma
} && current_position >= 0.0
{
// Need enough data signals.push(Signal {
if history.len() >= self.slow_period { symbol: symbol.clone(),
// Debug when we first have enough data signal_type: crate::backtest::SignalType::Sell,
if history.len() == self.slow_period { strength: 1.0,
eprintln!("Now have enough data for {}: {} bars", symbol, history.len()); quantity: Some(100.0), // Fixed quantity for testing
} reason: Some("Death cross".to_string()),
// Calculate SMAs metadata: None,
let fast_sma = history[history.len() - self.fast_period..].iter().sum::<f64>() / self.fast_period as f64; });
let slow_sma = history.iter().sum::<f64>() / history.len() as f64; }
}
// Debug: Log SMAs periodically }
if history.len() % 10 == 0 || (history.len() > self.slow_period && history.len() < self.slow_period + 5) { }
eprintln!("SMAs for {}: fast={:.2}, slow={:.2}, price={:.2}, history_len={}",
symbol, fast_sma, slow_sma, price, history.len()); signals
}
// Also log if they're close to crossing
let diff = (fast_sma - slow_sma).abs(); fn on_fill(&mut self, symbol: &str, quantity: f64, _price: f64, side: &str) {
let pct_diff = diff / slow_sma * 100.0; let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0);
if pct_diff < 1.0 { let new_pos = if side == "buy" {
eprintln!(" -> SMAs are close! Difference: {:.4} ({:.2}%)", diff, pct_diff); current_pos + quantity
} } else {
} current_pos - quantity
};
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period { if new_pos.abs() < 0.0001 {
// Debug: First time checking for crossovers self.positions.remove(symbol);
if history.len() == self.slow_period + 1 { } else {
eprintln!("Starting crossover checks for {}", symbol); self.positions.insert(symbol.to_string(), new_pos);
} }
let prev_history = &history[..history.len() - 1]; }
let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..].iter().sum::<f64>() / self.fast_period as f64;
let prev_slow_sma = prev_history.iter().sum::<f64>() / prev_history.len() as f64; fn get_name(&self) -> &str {
&self.name
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0); }
// Golden cross - buy signal fn get_parameters(&self) -> serde_json::Value {
if prev_fast_sma <= prev_slow_sma && fast_sma > slow_sma && current_position <= 0.0 { serde_json::json!({
signals.push(Signal { "fast_period": self.fast_period,
symbol: symbol.clone(), "slow_period": self.slow_period
signal_type: crate::backtest::SignalType::Buy, })
strength: 1.0, }
quantity: Some(100.0), // Fixed quantity for testing }
reason: Some("Golden cross".to_string()),
metadata: None, // Error handling for threadsafe functions
}); struct ErrorStrategy;
self.positions.insert(symbol.clone(), 1.0);
eprintln!("Generated BUY signal for {} at price {}", symbol, price); impl From<napi::Error> for ErrorStrategy {
} fn from(_e: napi::Error) -> Self {
ErrorStrategy
// Death cross - sell signal }
else if prev_fast_sma >= prev_slow_sma && fast_sma < slow_sma && current_position >= 0.0 { }
signals.push(Signal {
symbol: symbol.clone(), // Helper to convert NAPI parameters to JSON
signal_type: crate::backtest::SignalType::Sell, fn napi_params_to_json(obj: napi::JsObject) -> Result<serde_json::Value> {
strength: 1.0, // For now, just extract the common parameters
quantity: Some(100.0), // Fixed quantity for testing let fast_period = obj.get_named_property::<f64>("fastPeriod").unwrap_or(5.0);
reason: Some("Death cross".to_string()), let slow_period = obj.get_named_property::<f64>("slowPeriod").unwrap_or(15.0);
metadata: None,
}); Ok(serde_json::json!({
self.positions.insert(symbol.clone(), -1.0); "fastPeriod": fast_period,
eprintln!("Generated SELL signal for {} at price {}", symbol, price); "slowPeriod": slow_period
} }))
} }
} else {
// Debug: Log when we don't have enough data
if history.len() == 1 || history.len() == 10 || history.len() == 20 {
eprintln!("Not enough data for {}: {} bars (need {})", symbol, history.len(), self.slow_period);
}
}
}
signals
}
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) {
eprintln!("🔸 SMA Strategy - Fill received: {} {} @ ${:.2} - {}", quantity, symbol, price, side);
let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0);
let new_pos = if side == "buy" { current_pos + quantity } else { current_pos - quantity };
eprintln!(" Position change: {} -> {}", current_pos, new_pos);
if new_pos.abs() < 0.0001 {
self.positions.remove(symbol);
eprintln!(" Position closed");
} else {
self.positions.insert(symbol.to_string(), new_pos);
}
}
fn get_name(&self) -> &str {
&self.name
}
fn get_parameters(&self) -> serde_json::Value {
serde_json::json!({
"fast_period": self.fast_period,
"slow_period": self.slow_period
})
}
}
// Error handling for threadsafe functions
struct ErrorStrategy;
impl From<napi::Error> for ErrorStrategy {
fn from(_e: napi::Error) -> Self {
ErrorStrategy
}
}
// Helper to convert NAPI parameters to JSON
fn napi_params_to_json(obj: napi::JsObject) -> Result<serde_json::Value> {
// For now, just extract the common parameters
let fast_period = obj.get_named_property::<f64>("fastPeriod").unwrap_or(5.0);
let slow_period = obj.get_named_property::<f64>("slowPeriod").unwrap_or(15.0);
Ok(serde_json::json!({
"fastPeriod": fast_period,
"slowPeriod": slow_period
}))
}

View file

@ -1,229 +1,231 @@
use super::{Indicator, IncrementalIndicator, IndicatorResult, IndicatorError, PriceData}; use super::ema::EMA;
use super::ema::EMA; use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData};
/// Moving Average Convergence Divergence (MACD) Indicator /// Moving Average Convergence Divergence (MACD) Indicator
/// ///
/// MACD = Fast EMA - Slow EMA /// MACD = Fast EMA - Slow EMA
/// Signal = EMA of MACD /// Signal = EMA of MACD
/// Histogram = MACD - Signal /// Histogram = MACD - Signal
pub struct MACD { pub struct MACD {
fast_period: usize, fast_period: usize,
slow_period: usize, slow_period: usize,
signal_period: usize, signal_period: usize,
fast_ema: EMA, fast_ema: EMA,
slow_ema: EMA, slow_ema: EMA,
signal_ema: EMA, signal_ema: EMA,
macd_value: Option<f64>, macd_value: Option<f64>,
} }
impl MACD { impl MACD {
pub fn new(fast_period: usize, slow_period: usize, signal_period: usize) -> Result<Self, IndicatorError> { pub fn new(
if fast_period == 0 || slow_period == 0 || signal_period == 0 { fast_period: usize,
return Err(IndicatorError::InvalidParameter( slow_period: usize,
"All periods must be greater than 0".to_string() signal_period: usize,
)); ) -> Result<Self, IndicatorError> {
} if fast_period == 0 || slow_period == 0 || signal_period == 0 {
return Err(IndicatorError::InvalidParameter(
if fast_period >= slow_period { "All periods must be greater than 0".to_string(),
return Err(IndicatorError::InvalidParameter( ));
"Fast period must be less than slow period".to_string() }
));
} if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
Ok(Self { "Fast period must be less than slow period".to_string(),
fast_period, ));
slow_period, }
signal_period,
fast_ema: EMA::new(fast_period)?, Ok(Self {
slow_ema: EMA::new(slow_period)?, fast_period,
signal_ema: EMA::new(signal_period)?, slow_period,
macd_value: None, signal_period,
}) fast_ema: EMA::new(fast_period)?,
} slow_ema: EMA::new(slow_period)?,
signal_ema: EMA::new(signal_period)?,
/// Standard MACD with 12, 26, 9 periods macd_value: None,
pub fn standard() -> Result<Self, IndicatorError> { })
Self::new(12, 26, 9) }
}
/// Standard MACD with 12, 26, 9 periods
/// Calculate MACD for a series of values pub fn standard() -> Result<Self, IndicatorError> {
pub fn calculate_series( Self::new(12, 26, 9)
values: &[f64], }
fast_period: usize,
slow_period: usize, /// Calculate MACD for a series of values
signal_period: usize pub fn calculate_series(
) -> Result<(Vec<f64>, Vec<f64>, Vec<f64>), IndicatorError> { values: &[f64],
if fast_period >= slow_period { fast_period: usize,
return Err(IndicatorError::InvalidParameter( slow_period: usize,
"Fast period must be less than slow period".to_string() signal_period: usize,
)); ) -> Result<(Vec<f64>, Vec<f64>, Vec<f64>), IndicatorError> {
} if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
if values.len() < slow_period { "Fast period must be less than slow period".to_string(),
return Err(IndicatorError::InsufficientData { ));
required: slow_period, }
actual: values.len(),
}); if values.len() < slow_period {
} return Err(IndicatorError::InsufficientData {
required: slow_period,
// Calculate EMAs actual: values.len(),
let fast_ema = EMA::calculate_series(values, fast_period)?; });
let slow_ema = EMA::calculate_series(values, slow_period)?; }
// Calculate MACD line // Calculate EMAs
let mut macd_line = Vec::with_capacity(slow_ema.len()); let fast_ema = EMA::calculate_series(values, fast_period)?;
for i in 0..slow_ema.len() { let slow_ema = EMA::calculate_series(values, slow_period)?;
// Align indices - slow EMA starts later
let fast_idx = i + (slow_period - fast_period); // Calculate MACD line
macd_line.push(fast_ema[fast_idx] - slow_ema[i]); let mut macd_line = Vec::with_capacity(slow_ema.len());
} for i in 0..slow_ema.len() {
// Both EMA series are aligned to the complete input series.
// Calculate signal line (EMA of MACD) macd_line.push(fast_ema[i] - slow_ema[i]);
let signal_line = if macd_line.len() >= signal_period { }
EMA::calculate_series(&macd_line, signal_period)?
} else { // Calculate signal line (EMA of MACD)
vec![] let signal_line = if macd_line.len() >= signal_period {
}; EMA::calculate_series(&macd_line, signal_period)?
} else {
// Calculate histogram vec![]
let mut histogram = Vec::with_capacity(signal_line.len()); };
for i in 0..signal_line.len() {
// Align indices // Calculate histogram
let macd_idx = i + (macd_line.len() - signal_line.len()); let mut histogram = Vec::with_capacity(signal_line.len());
histogram.push(macd_line[macd_idx] - signal_line[i]); for i in 0..signal_line.len() {
} // Align indices
let macd_idx = i + (macd_line.len() - signal_line.len());
Ok((macd_line, signal_line, histogram)) histogram.push(macd_line[macd_idx] - signal_line[i]);
} }
}
Ok((macd_line, signal_line, histogram))
impl Indicator for MACD { }
fn calculate(&mut self, data: &PriceData) -> Result<IndicatorResult, IndicatorError> { }
let values = &data.close;
impl Indicator for MACD {
let (macd, signal, histogram) = Self::calculate_series( fn calculate(&mut self, data: &PriceData) -> Result<IndicatorResult, IndicatorError> {
values, let values = &data.close;
self.fast_period,
self.slow_period, let (macd, signal, histogram) = Self::calculate_series(
self.signal_period values,
)?; self.fast_period,
self.slow_period,
Ok(IndicatorResult::MACD { self.signal_period,
macd, )?;
signal,
histogram, Ok(IndicatorResult::MACD {
}) macd,
} signal,
histogram,
fn reset(&mut self) { })
self.fast_ema.reset(); }
self.slow_ema.reset();
self.signal_ema.reset(); fn reset(&mut self) {
self.macd_value = None; self.fast_ema.reset();
} self.slow_ema.reset();
self.signal_ema.reset();
fn is_ready(&self) -> bool { self.macd_value = None;
self.fast_ema.is_ready() && self.slow_ema.is_ready() && self.signal_ema.is_ready() }
}
} fn is_ready(&self) -> bool {
self.fast_ema.is_ready() && self.slow_ema.is_ready() && self.signal_ema.is_ready()
impl IncrementalIndicator for MACD { }
fn update(&mut self, value: f64) -> Result<Option<f64>, IndicatorError> { }
// Update both EMAs
let fast_result = self.fast_ema.update(value)?; impl IncrementalIndicator for MACD {
let slow_result = self.slow_ema.update(value)?; fn update(&mut self, value: f64) -> Result<Option<f64>, IndicatorError> {
// Update both EMAs
// Calculate MACD if both EMAs are ready let fast_result = self.fast_ema.update(value)?;
if let (Some(fast), Some(slow)) = (fast_result, slow_result) { let slow_result = self.slow_ema.update(value)?;
let macd = fast - slow;
self.macd_value = Some(macd); // Calculate MACD if both EMAs are ready
if let (Some(fast), Some(slow)) = (fast_result, slow_result) {
// Update signal line let macd = fast - slow;
if let Some(signal) = self.signal_ema.update(macd)? { self.macd_value = Some(macd);
// Return histogram value
Ok(Some(macd - signal)) // Update signal line
} else { if let Some(signal) = self.signal_ema.update(macd)? {
Ok(None) // Return histogram value
} Ok(Some(macd - signal))
} else { } else {
Ok(None) Ok(None)
} }
} } else {
Ok(None)
fn current(&self) -> Option<f64> { }
// Return current histogram value }
if let (Some(fast), Some(slow), Some(signal)) = (
self.fast_ema.current(), fn current(&self) -> Option<f64> {
self.slow_ema.current(), // Return current histogram value
self.signal_ema.current() if let (Some(fast), Some(slow), Some(signal)) = (
) { self.fast_ema.current(),
let macd = fast - slow; self.slow_ema.current(),
Some(macd - signal) self.signal_ema.current(),
} else { ) {
None let macd = fast - slow;
} Some(macd - signal)
} } else {
} None
}
/// Structure to hold all MACD values for incremental updates }
pub struct MACDValues { }
pub macd: f64,
pub signal: f64, /// Structure to hold all MACD values for incremental updates
pub histogram: f64, pub struct MACDValues {
} pub macd: f64,
pub signal: f64,
impl MACD { pub histogram: f64,
/// Get all current MACD values }
pub fn current_values(&self) -> Option<MACDValues> {
if let (Some(fast), Some(slow), Some(signal)) = ( impl MACD {
self.fast_ema.current(), /// Get all current MACD values
self.slow_ema.current(), pub fn current_values(&self) -> Option<MACDValues> {
self.signal_ema.current() if let (Some(fast), Some(slow), Some(signal)) = (
) { self.fast_ema.current(),
let macd = fast - slow; self.slow_ema.current(),
Some(MACDValues { self.signal_ema.current(),
macd, ) {
signal, let macd = fast - slow;
histogram: macd - signal, Some(MACDValues {
}) macd,
} else { signal,
None histogram: macd - signal,
} })
} } else {
} None
}
#[cfg(test)] }
mod tests { }
use super::*;
#[cfg(test)]
#[test] mod tests {
fn test_macd_calculation() { use super::*;
let values = vec![
10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, #[test]
14.0, 14.5, 15.0, 14.5, 14.0, 13.5, 13.0, 12.5, fn test_macd_calculation() {
12.0, 11.5, 11.0, 10.5, 10.0, 10.5, 11.0, 11.5, let values = vec![
12.0, 12.5, 13.0, 13.5, 14.0, 14.5 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 14.5, 14.0, 13.5,
]; 13.0, 12.5, 12.0, 11.5, 11.0, 10.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
14.0, 14.5,
let (macd, signal, histogram) = MACD::calculate_series(&values, 12, 26, 9).unwrap(); ];
// Should have values after slow period let (macd, signal, histogram) = MACD::calculate_series(&values, 12, 26, 9).unwrap();
assert!(!macd.is_empty());
assert!(!signal.is_empty()); // Should have values after slow period
assert!(!histogram.is_empty()); assert!(!macd.is_empty());
assert!(!signal.is_empty());
// Histogram should equal MACD - Signal assert!(!histogram.is_empty());
for i in 0..histogram.len() {
let expected = macd[macd.len() - histogram.len() + i] - signal[i]; // Histogram should equal MACD - Signal
assert!((histogram[i] - expected).abs() < 1e-10); for i in 0..histogram.len() {
} let expected = macd[macd.len() - histogram.len() + i] - signal[i];
} assert!((histogram[i] - expected).abs() < 1e-10);
}
#[test] }
fn test_standard_macd() {
let macd = MACD::standard().unwrap(); #[test]
assert_eq!(macd.fast_period, 12); fn test_standard_macd() {
assert_eq!(macd.slow_period, 26); let macd = MACD::standard().unwrap();
assert_eq!(macd.signal_period, 9); assert_eq!(macd.fast_period, 12);
} assert_eq!(macd.slow_period, 26);
} assert_eq!(macd.signal_period, 9);
}
}

View file

@ -1,272 +1,278 @@
/** /**
* Advanced Risk Management Examples * Advanced Risk Management Examples
* Demonstrates orderbook analytics, portfolio risk, and bet sizing * Demonstrates orderbook analytics, portfolio risk, and bet sizing
*/ */
import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine'; import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine';
import { getLogger } from '@stock-bot/logger'; import { getLogger } from '@stock-bot/logger';
const logger = getLogger('AdvancedRiskExample'); const _logger = getLogger('AdvancedRiskExample');
// Example 1: Orderbook Analytics // Example 1: Orderbook Analytics
async function orderbookAnalyticsExample() { async function orderbookAnalyticsExample() {
console.log('\n=== Orderbook Analytics Example ==='); console.log('\n=== Orderbook Analytics Example ===');
const engine = new TradingEngine('paper', { startingCapital: 100000 }); const engine = new TradingEngine('paper', { startingCapital: 100000 });
const obAnalyzer = new OrderbookAnalyzer(); const obAnalyzer = new OrderbookAnalyzer();
// Update orderbook with some data // Update orderbook with some data
const symbol = 'AAPL'; const symbol = 'AAPL';
engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200); engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200);
engine.updateQuote(symbol, 149.90, 150.10, 800, 900); engine.updateQuote(symbol, 149.9, 150.1, 800, 900);
engine.updateQuote(symbol, 149.85, 150.15, 600, 700); engine.updateQuote(symbol, 149.85, 150.15, 600, 700);
// Get orderbook snapshot // Get orderbook snapshot
const snapshotJson = engine.getOrderbookSnapshot(symbol, 10); const snapshotJson = engine.getOrderbookSnapshot(symbol, 10);
const snapshot = JSON.parse(snapshotJson); const _snapshot = JSON.parse(snapshotJson);
// Analyze orderbook // Analyze orderbook
const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson); const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson);
const analytics = JSON.parse(analyticsJson); const analytics = JSON.parse(analyticsJson);
console.log('Orderbook Analytics:'); console.log('Orderbook Analytics:');
console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`); console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`);
console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`); console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`);
console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`); console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`);
console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`); console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`); console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
// Calculate liquidity profile // Calculate liquidity profile
const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson); const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson);
const profile = JSON.parse(profileJson); const profile = JSON.parse(profileJson);
console.log('\nLiquidity Profile:'); console.log('\nLiquidity Profile:');
console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`); console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`);
console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`); console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`);
// Calculate market impact for a $10,000 buy order // Calculate market impact for a $10,000 buy order
const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true); const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true);
const impact = JSON.parse(impactJson); const impact = JSON.parse(impactJson);
console.log('\nMarket Impact ($10k buy):'); console.log('\nMarket Impact ($10k buy):');
console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`); console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`); console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`);
console.log(` Slippage: $${impact.slippage.toFixed(2)}`); console.log(` Slippage: $${impact.slippage.toFixed(2)}`);
console.log(` Levels Consumed: ${impact.levels_consumed}`); console.log(` Levels Consumed: ${impact.levels_consumed}`);
} }
// Example 2: Portfolio Risk Analysis // Example 2: Portfolio Risk Analysis
async function portfolioRiskExample() { async function portfolioRiskExample() {
console.log('\n=== Portfolio Risk Analysis Example ==='); console.log('\n=== Portfolio Risk Analysis Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback
// Update historical returns for portfolio symbols // Update historical returns for portfolio symbols
const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META']; const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'];
// Simulate some returns data (in practice, load from historical data) // Simulate some returns data (in practice, load from historical data)
for (const symbol of symbols) { for (const symbol of symbols) {
const returns = generateRandomReturns(252); const returns = generateRandomReturns(252);
riskAnalyzer.updateReturns(symbol, returns); riskAnalyzer.updateReturns(symbol, returns);
} }
// Current positions // Current positions
const positions = [ const positions = [
{ symbol: 'AAPL', quantity: 100, avgPrice: 150 }, { symbol: 'AAPL', quantity: 100, avgPrice: 150 },
{ symbol: 'GOOGL', quantity: 50, avgPrice: 140 }, { symbol: 'GOOGL', quantity: 50, avgPrice: 140 },
{ symbol: 'MSFT', quantity: 75, avgPrice: 380 }, { symbol: 'MSFT', quantity: 75, avgPrice: 380 },
{ symbol: 'AMZN', quantity: 40, avgPrice: 170 }, { symbol: 'AMZN', quantity: 40, avgPrice: 170 },
{ symbol: 'META', quantity: 60, avgPrice: 480 } { symbol: 'META', quantity: 60, avgPrice: 480 },
]; ];
// Current prices // Current prices
const prices = { const prices = {
AAPL: 155, AAPL: 155,
GOOGL: 145, GOOGL: 145,
MSFT: 390, MSFT: 390,
AMZN: 175, AMZN: 175,
META: 490 META: 490,
}; };
// Calculate portfolio risk // Calculate portfolio risk
const riskJson = riskAnalyzer.calculatePortfolioRisk( const riskJson = riskAnalyzer.calculatePortfolioRisk(
JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])), JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])),
JSON.stringify(prices) JSON.stringify(prices)
); );
const risk = JSON.parse(riskJson); const risk = JSON.parse(riskJson);
console.log('Portfolio Risk Metrics:'); console.log('Portfolio Risk Metrics:');
console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`); console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`);
console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`); console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`);
console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`); console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`);
console.log('\nConcentration Metrics:'); console.log('\nConcentration Metrics:');
console.log(` Herfindahl Index: ${risk.concentration_risk.herfindahl_index.toFixed(3)}`); console.log(` Herfindahl Index: ${risk.concentration_risk.herfindahl_index.toFixed(3)}`);
console.log(` Effective Positions: ${risk.concentration_risk.effective_number_of_positions.toFixed(1)}`); console.log(
console.log(` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%`); ` Effective Positions: ${risk.concentration_risk.effective_number_of_positions.toFixed(1)}`
);
console.log('\nCorrelation Analysis:'); console.log(
console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`); ` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%`
console.log(` Max Correlation: ${risk.correlation_matrix.max_correlation[0]} vs ${risk.correlation_matrix.max_correlation[1]} = ${risk.correlation_matrix.max_correlation[2].toFixed(3)}`); );
console.log(` Clustering Score: ${risk.correlation_matrix.clustering_score.toFixed(3)}`);
console.log('\nCorrelation Analysis:');
console.log('\nStress Test Results:'); console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`);
for (const [scenario, loss] of Object.entries(risk.stress_test_results)) { console.log(
console.log(` ${scenario}: $${(loss as number).toFixed(2)}`); ` Max Correlation: ${risk.correlation_matrix.max_correlation[0]} vs ${risk.correlation_matrix.max_correlation[1]} = ${risk.correlation_matrix.max_correlation[2].toFixed(3)}`
} );
} console.log(` Clustering Score: ${risk.correlation_matrix.clustering_score.toFixed(3)}`);
// Example 3: Dynamic Bet Sizing console.log('\nStress Test Results:');
async function betSizingExample() { for (const [scenario, loss] of Object.entries(risk.stress_test_results)) {
console.log('\n=== Dynamic Bet Sizing Example ==='); console.log(` ${scenario}: $${(loss as number).toFixed(2)}`);
}
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); }
// Scenario 1: Strong signal in trending market // Example 3: Dynamic Bet Sizing
console.log('\nScenario 1: Strong Signal, Trending Market'); async function betSizingExample() {
let positionSize = riskAnalyzer.calculatePositionSize( console.log('\n=== Dynamic Bet Sizing Example ===');
0.8, // signal_strength
0.9, // signal_confidence const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
0.015, // volatility (1.5% daily)
0.8, // liquidity_score // Scenario 1: Strong signal in trending market
0.02, // current_drawdown (2%) console.log('\nScenario 1: Strong Signal, Trending Market');
150, // price let positionSize = riskAnalyzer.calculatePositionSize(
145, // stop_loss 0.8, // signal_strength
'trending' 0.9, // signal_confidence
); 0.015, // volatility (1.5% daily)
0.8, // liquidity_score
let size = JSON.parse(positionSize); 0.02, // current_drawdown (2%)
console.log(` Shares: ${size.shares}`); 150, // price
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`); 145, // stop_loss
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`); 'trending'
console.log(' Adjustments:'); );
for (const adj of size.adjustments) {
console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`); let size = JSON.parse(positionSize);
} console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
// Scenario 2: Weak signal in high volatility console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
console.log('\nScenario 2: Weak Signal, High Volatility'); console.log(' Adjustments:');
positionSize = riskAnalyzer.calculatePositionSize( for (const adj of size.adjustments) {
0.3, // signal_strength console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`);
0.5, // signal_confidence }
0.03, // volatility (3% daily)
0.6, // liquidity_score // Scenario 2: Weak signal in high volatility
0.15, // current_drawdown (15%) console.log('\nScenario 2: Weak Signal, High Volatility');
150, // price positionSize = riskAnalyzer.calculatePositionSize(
null, // no stop_loss 0.3, // signal_strength
'high_volatility' 0.5, // signal_confidence
); 0.03, // volatility (3% daily)
0.6, // liquidity_score
size = JSON.parse(positionSize); 0.15, // current_drawdown (15%)
console.log(` Shares: ${size.shares}`); 150, // price
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`); null, // no stop_loss
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`); 'high_volatility'
);
// Calculate optimal stop loss
const supportLevels = [148, 145, 142, 140]; size = JSON.parse(positionSize);
const optimalStop = riskAnalyzer.calculateOptimalStopLoss( console.log(` Shares: ${size.shares}`);
150, // entry_price console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
0.015, // volatility console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
supportLevels,
2.5, // atr // Calculate optimal stop loss
true // is_long const supportLevels = [148, 145, 142, 140];
); const optimalStop = riskAnalyzer.calculateOptimalStopLoss(
150, // entry_price
console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`); 0.015, // volatility
} supportLevels,
2.5, // atr
// Example 4: Integrated Risk Management in Trading true // is_long
async function integratedTradingExample() { );
console.log('\n=== Integrated Risk Management Example ===');
console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`);
const engine = new TradingEngine('backtest', { }
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
endTime: Date.now(), // Example 4: Integrated Risk Management in Trading
speedMultiplier: 1 async function integratedTradingExample() {
}); console.log('\n=== Integrated Risk Management Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); const engine = new TradingEngine('backtest', {
const obAnalyzer = new OrderbookAnalyzer(); startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
endTime: Date.now(),
// Simulate a trading decision speedMultiplier: 1,
const symbol = 'AAPL'; });
// 1. Check orderbook liquidity const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500); const obAnalyzer = new OrderbookAnalyzer();
const snapshot = engine.getOrderbookSnapshot(symbol, 10);
const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot)); // Simulate a trading decision
const symbol = 'AAPL';
console.log('Pre-trade Analysis:');
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`); // 1. Check orderbook liquidity
console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`); engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500);
console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`); const snapshot = engine.getOrderbookSnapshot(symbol, 10);
const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot));
// 2. Calculate position size based on current conditions
const positionSizeJson = riskAnalyzer.calculatePositionSize( console.log('Pre-trade Analysis:');
0.7, // signal_strength console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
0.8, // signal_confidence console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`);
0.018, // volatility console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
analytics.liquidity_score, // from orderbook
0.05, // current_drawdown // 2. Calculate position size based on current conditions
150, // price const positionSizeJson = riskAnalyzer.calculatePositionSize(
147, // stop_loss 0.7, // signal_strength
'trending' 0.8, // signal_confidence
); 0.018, // volatility
analytics.liquidity_score, // from orderbook
const positionSize = JSON.parse(positionSizeJson); 0.05, // current_drawdown
console.log(`\nPosition Sizing:`); 150, // price
console.log(` Recommended Shares: ${positionSize.shares}`); 147, // stop_loss
console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`); 'trending'
);
// 3. Check market impact before placing order
const orderValue = positionSize.shares * 150; const positionSize = JSON.parse(positionSizeJson);
const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true)); console.log(`\nPosition Sizing:`);
console.log(` Recommended Shares: ${positionSize.shares}`);
console.log(`\nExpected Market Impact:`); console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`);
console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`); // 3. Check market impact before placing order
const orderValue = positionSize.shares * 150;
// 4. Risk check const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true));
const riskCheck = engine.checkRisk({
id: '123', console.log(`\nExpected Market Impact:`);
symbol: symbol, console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`);
side: 'buy', console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`);
quantity: positionSize.shares,
orderType: 'market', // 4. Risk check
timeInForce: 'DAY' const riskCheck = engine.checkRisk({
}); id: '123',
symbol: symbol,
const riskResult = JSON.parse(riskCheck); side: 'buy',
console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`); quantity: positionSize.shares,
if (!riskResult.passed) { orderType: 'market',
console.log(' Violations:', riskResult.violations); timeInForce: 'DAY',
} });
}
const riskResult = JSON.parse(riskCheck);
// Helper function to generate random returns console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`);
function generateRandomReturns(length: number): number[] { if (!riskResult.passed) {
const returns: number[] = []; console.log(' Violations:', riskResult.violations);
for (let i = 0; i < length; i++) { }
// Generate returns with mean 0.0005 (0.05%) and std dev 0.02 (2%) }
const return_ = (Math.random() - 0.5) * 0.04 + 0.0005;
returns.push(return_); // Helper function to generate random returns
} function generateRandomReturns(length: number): number[] {
return returns; const returns: number[] = [];
} for (let i = 0; i < length; i++) {
// Generate returns with mean 0.0005 (0.05%) and std dev 0.02 (2%)
// Run all examples const return_ = (Math.random() - 0.5) * 0.04 + 0.0005;
async function runExamples() { returns.push(return_);
try { }
await orderbookAnalyticsExample(); return returns;
await portfolioRiskExample(); }
await betSizingExample();
await integratedTradingExample(); // Run all examples
} catch (error) { async function runExamples() {
console.error('Error running examples:', error); try {
} await orderbookAnalyticsExample();
} await portfolioRiskExample();
await betSizingExample();
// Execute if running directly await integratedTradingExample();
if (require.main === module) { } catch (error) {
runExamples(); console.error('Error running examples:', error);
} }
}
// Execute if running directly
if (require.main === module) {
runExamples();
}

View file

@ -1,113 +1,93 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { createExampleRuntime } from './example-runtime';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager'; async function debugPositionTracking() {
import { MarketDataService } from '../src/services/MarketDataService'; // Create service container with detailed logging
import { ExecutionService } from '../src/services/ExecutionService'; const {
import { IServiceContainer } from '@stock-bot/di'; container,
storageService,
async function debugPositionTracking() { marketDataService: _marketDataService,
// Create service container with detailed logging modeManager,
const container: IServiceContainer = { strategyManager,
logger: { } = await createExampleRuntime();
info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), // Initialize backtest mode with full config
warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args), await modeManager.initializeMode({
debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args), mode: 'backtest',
} as any, startDate: '2023-06-01T00:00:00Z',
custom: {} endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging
}; speed: 'max',
symbols: ['AAPL'],
// Initialize services initialCapital: 100000,
const storageService = new StorageService(); dataFrequency: '1d',
const marketDataService = new MarketDataService(container); strategy: 'sma-crossover',
const executionService = new ExecutionService(container); });
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container); // Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Set services in container
container.custom = { // Listen to strategy events for debugging
MarketDataService: marketDataService, strategyManager.on('order', (orderEvent: unknown) => {
ExecutionService: executionService, console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
ModeManager: modeManager, });
StorageService: storageService
}; // Configure backtest
const config = {
// Initialize backtest mode with full config mode: 'backtest' as const,
await modeManager.initializeMode({ name: 'Position Tracking Debug',
mode: 'backtest', strategy: 'sma-crossover',
startDate: '2023-06-01T00:00:00Z', symbols: ['AAPL'],
endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging startDate: '2023-06-01T00:00:00Z',
speed: 'max', endDate: '2023-09-01T00:00:00Z',
symbols: ['AAPL'], initialCapital: 100000,
initialCapital: 100000, commission: 0.001,
dataFrequency: '1d', slippage: 0.0001,
strategy: 'sma-crossover' dataFrequency: '1d' as const,
}); speed: 'max' as const,
};
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager); console.log('Starting position tracking debug...\n');
// Listen to strategy events for debugging try {
strategyManager.on('order', (orderEvent: any) => { const result = await backtestEngine.runBacktest(config);
console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
}); console.log('\n=== FINAL RESULTS ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Configure backtest console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
const config = {
mode: 'backtest' as const, console.log('\n=== TRADE DETAILS ===');
name: 'Position Tracking Debug', let buyCount = 0;
strategy: 'sma-crossover', let sellCount = 0;
symbols: ['AAPL'],
startDate: '2023-06-01T00:00:00Z', result.trades.forEach((trade, i) => {
endDate: '2023-09-01T00:00:00Z', console.log(`\nTrade ${i + 1}:`);
initialCapital: 100000, console.log(` Symbol: ${trade.symbol}`);
commission: 0.001, console.log(` Side: ${trade.side}`);
slippage: 0.0001, console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
dataFrequency: '1d' as const, console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
speed: 'max' as const console.log(` Quantity: ${trade.quantity}`);
}; console.log(` P&L: $${trade.pnl.toFixed(2)}`);
console.log('Starting position tracking debug...\n'); if (trade.side === 'buy') {
buyCount++;
try { } else if (trade.side === 'sell') {
const result = await backtestEngine.runBacktest(config); sellCount++;
}
console.log('\n=== FINAL RESULTS ==='); });
console.log(`Total Trades: ${result.metrics.totalTrades}`);
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); console.log(`\n=== TRADE SIDE SUMMARY ===`);
console.log(`Buy trades: ${buyCount}`);
console.log('\n=== TRADE DETAILS ==='); console.log(`Sell trades: ${sellCount}`);
let buyCount = 0;
let sellCount = 0; // Check final positions
console.log('\n=== FINAL POSITIONS ===');
result.trades.forEach((trade, i) => { result.positions.forEach(pos => {
console.log(`\nTrade ${i + 1}:`); console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`);
console.log(` Symbol: ${trade.symbol}`); });
console.log(` Side: ${trade.side}`); } catch (error) {
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); console.error('Debug failed:', error);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); }
console.log(` Quantity: ${trade.quantity}`); }
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
// Run the debug
if (trade.side === 'buy') buyCount++; debugPositionTracking().catch(console.error);
else if (trade.side === 'sell') sellCount++;
});
console.log(`\n=== TRADE SIDE SUMMARY ===`);
console.log(`Buy trades: ${buyCount}`);
console.log(`Sell trades: ${sellCount}`);
// Check final positions
console.log('\n=== FINAL POSITIONS ===');
result.positions.forEach(pos => {
console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`);
});
} catch (error) {
console.error('Debug failed:', error);
}
}
// Run the debug
debugPositionTracking().catch(console.error);

View file

@ -1,129 +1,130 @@
import { TradingEngine } from '@stock-bot/engine'; import { TradingEngine } from '@stock-bot/engine';
import type { ClosedTrade } from '../src/backtest/native-result';
async function debugRustShortTrades() {
// Create engine config for backtest mode async function debugRustShortTrades() {
const engineConfig = { // Create engine config for backtest mode
startTime: new Date('2023-01-01').getTime(), const engineConfig = {
endTime: new Date('2023-02-01').getTime(), startTime: new Date('2023-01-01').getTime(),
speedMultiplier: 0 endTime: new Date('2023-02-01').getTime(),
}; speedMultiplier: 0,
};
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
console.log('1. Creating TradingEngine in backtest mode...');
const engine = new TradingEngine('backtest', engineConfig); console.log('1. Creating TradingEngine in backtest mode...');
const engine = new TradingEngine('backtest', engineConfig);
// Simulate opening a short position
console.log('\n2. Submitting SELL order to open short position...'); // Simulate opening a short position
const sellOrder = { console.log('\n2. Submitting SELL order to open short position...');
id: 'sell-order-001', const sellOrder = {
symbol: 'TEST', id: 'sell-order-001',
side: 'sell', symbol: 'TEST',
quantity: 100, side: 'sell',
orderType: 'market', quantity: 100,
timeInForce: 'DAY' orderType: 'market',
}; timeInForce: 'DAY',
const sellOrderId = engine.submitOrder(sellOrder); };
console.log(` Sell order ID: ${sellOrderId}`); const sellOrderId = engine.submitOrder(sellOrder);
console.log(` Sell order ID: ${sellOrderId}`);
// Process the sell fill
console.log('\n3. Processing SELL fill...'); // Process the sell fill
const sellFillResult = engine.processFillWithMetadata( console.log('\n3. Processing SELL fill...');
'TEST', // symbol const sellFillResult = engine.processFillWithMetadata(
50.0, // price 'TEST', // symbol
100, // quantity 50.0, // price
'sell', // side 100, // quantity
0.1, // commission 'sell', // side
sellOrderId, // orderId 0.1, // commission
'debug-strategy' // strategyId sellOrderId, // orderId
); 'debug-strategy' // strategyId
console.log(` Fill result: ${sellFillResult}`); );
console.log(` Fill result: ${sellFillResult}`);
// Check positions
console.log('\n4. Checking positions after SELL...'); // Check positions
const positionsAfterSell = engine.getPosition('TEST'); console.log('\n4. Checking positions after SELL...');
console.log(' Position:', positionsAfterSell); const positionsAfterSell = engine.getPosition('TEST');
console.log(' Position:', positionsAfterSell);
// Check open trades
const openTradesAfterSell = JSON.parse(engine.getOpenTrades()); // Check open trades
console.log(' Open trades:', openTradesAfterSell.length); const openTradesAfterSell = JSON.parse(engine.getOpenTrades());
if (openTradesAfterSell.length > 0) { console.log(' Open trades:', openTradesAfterSell.length);
console.log(' First open trade:', openTradesAfterSell[0]); if (openTradesAfterSell.length > 0) {
} console.log(' First open trade:', openTradesAfterSell[0]);
}
// Check closed trades
const closedTradesAfterSell = JSON.parse(engine.getClosedTrades()); // Check closed trades
console.log(' Closed trades:', closedTradesAfterSell.length); const closedTradesAfterSell = JSON.parse(engine.getClosedTrades());
console.log(' Closed trades:', closedTradesAfterSell.length);
// Now close the short with a buy order
console.log('\n5. Submitting BUY order to close short position...'); // Now close the short with a buy order
const buyOrder = { console.log('\n5. Submitting BUY order to close short position...');
id: 'buy-order-001', const buyOrder = {
symbol: 'TEST', id: 'buy-order-001',
side: 'buy', symbol: 'TEST',
quantity: 100, side: 'buy',
orderType: 'market', quantity: 100,
timeInForce: 'DAY' orderType: 'market',
}; timeInForce: 'DAY',
const buyOrderId = engine.submitOrder(buyOrder); };
console.log(` Buy order ID: ${buyOrderId}`); const buyOrderId = engine.submitOrder(buyOrder);
console.log(` Buy order ID: ${buyOrderId}`);
// Process the buy fill
console.log('\n6. Processing BUY fill...'); // Process the buy fill
const buyFillResult = engine.processFillWithMetadata( console.log('\n6. Processing BUY fill...');
'TEST', // symbol const buyFillResult = engine.processFillWithMetadata(
48.0, // price (profit on short) 'TEST', // symbol
100, // quantity 48.0, // price (profit on short)
'buy', // side 100, // quantity
0.1, // commission 'buy', // side
buyOrderId, // orderId 0.1, // commission
'debug-strategy' // strategyId buyOrderId, // orderId
); 'debug-strategy' // strategyId
console.log(` Fill result: ${buyFillResult}`); );
console.log(` Fill result: ${buyFillResult}`);
// Check positions after closing
console.log('\n7. Checking positions after BUY...'); // Check positions after closing
const positionsAfterBuy = engine.getPosition('TEST'); console.log('\n7. Checking positions after BUY...');
console.log(' Position:', positionsAfterBuy); const positionsAfterBuy = engine.getPosition('TEST');
console.log(' Position:', positionsAfterBuy);
// Check open trades after closing
const openTradesAfterBuy = JSON.parse(engine.getOpenTrades()); // Check open trades after closing
console.log(' Open trades:', openTradesAfterBuy.length); const openTradesAfterBuy = JSON.parse(engine.getOpenTrades());
console.log(' Open trades:', openTradesAfterBuy.length);
// Check closed trades after closing - THIS IS WHERE WE SHOULD SEE THE SHORT TRADE
const closedTradesAfterBuy = JSON.parse(engine.getClosedTrades()); // Check closed trades after closing - THIS IS WHERE WE SHOULD SEE THE SHORT TRADE
console.log(' Closed trades:', closedTradesAfterBuy.length); const closedTradesAfterBuy = JSON.parse(engine.getClosedTrades());
console.log(' Closed trades:', closedTradesAfterBuy.length);
if (closedTradesAfterBuy.length > 0) {
console.log('\n8. Closed trade details:'); if (closedTradesAfterBuy.length > 0) {
closedTradesAfterBuy.forEach((trade: any, i: number) => { console.log('\n8. Closed trade details:');
console.log(` Trade ${i + 1}:`); closedTradesAfterBuy.forEach((trade: ClosedTrade, i: number) => {
console.log(` ID: ${trade.id}`); console.log(` Trade ${i + 1}:`);
console.log(` Side: ${trade.side}`); console.log(` ID: ${trade.id}`);
console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`); console.log(` Side: ${trade.side}`);
console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`); console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`);
console.log(` P&L: ${trade.pnl} (${trade.pnl_percent}%)`); console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`);
console.log(` Quantity: ${trade.quantity}`); console.log(` P&L: ${trade.pnl} (${trade.pnl_percent}%)`);
}); console.log(` Quantity: ${trade.quantity}`);
} else { });
console.log('\n❌ ERROR: No closed trades found! Short trade was not recorded.'); } else {
} console.log('\n❌ ERROR: No closed trades found! Short trade was not recorded.');
}
// Also check trade history
console.log('\n9. Trade history:'); // Also check trade history
const tradeHistory = JSON.parse(engine.getTradeHistory()); console.log('\n9. Trade history:');
tradeHistory.forEach((trade: any, i: number) => { const tradeHistory = JSON.parse(engine.getTradeHistory());
console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`); tradeHistory.forEach((trade: ClosedTrade, i: number) => {
}); console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
});
// Check totals
console.log('\n10. Summary:'); // Check totals
console.log(` Total trades: ${engine.getTradeCount()}`); console.log('\n10. Summary:');
console.log(` Closed trades: ${engine.getClosedTradeCount()}`); console.log(` Total trades: ${engine.getTradeCount()}`);
const [realizedPnl, unrealizedPnl] = engine.getTotalPnl(); console.log(` Closed trades: ${engine.getClosedTradeCount()}`);
console.log(` Realized P&L: ${realizedPnl}`); const [realizedPnl, unrealizedPnl] = engine.getTotalPnl();
console.log(` Unrealized P&L: ${unrealizedPnl}`); console.log(` Realized P&L: ${realizedPnl}`);
} console.log(` Unrealized P&L: ${unrealizedPnl}`);
}
// Run the debug
debugRustShortTrades().catch(console.error); // Run the debug
debugRustShortTrades().catch(console.error);

View file

@ -0,0 +1,33 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import { defined } from '@stock-bot/invariants';
import { registerOrchestratorServices } from '../src/container';
import type { OrchestratorServices } from '../src/types';
/** Offline examples explicitly opt into seeded synthetic data. No provider credentials are used. */
export async function createExampleRuntime() {
const di = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
await registerOrchestratorServices(di, {
initializeMode: false,
allowSyntheticData: true,
syntheticSeed: 42,
});
const container = di.resolve('serviceContainer') as OrchestratorServices;
return {
container,
storageService: defined(container.custom?.StorageService),
marketDataService: defined(container.custom?.MarketDataService),
executionService: defined(container.custom?.ExecutionService),
modeManager: defined(container.custom?.ModeManager),
strategyManager: defined(container.custom?.StrategyManager),
};
}

View file

@ -1,161 +1,138 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { createExampleRuntime } from './example-runtime';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager'; // Modify the data generation to ensure we get both golden and death crosses
import { MarketDataService } from '../src/services/MarketDataService'; function generateMockDataWithBothCrosses() {
import { ExecutionService } from '../src/services/ExecutionService'; const data = [];
import { IServiceContainer } from '@stock-bot/di'; const startDate = new Date('2023-01-01');
let price = 150;
// Modify the data generation to ensure we get both golden and death crosses
function generateMockDataWithBothCrosses() { // Create 365 days of data with clear trends
const data = []; for (let i = 0; i < 365; i++) {
const startDate = new Date('2023-01-01'); const date = new Date(startDate);
let price = 150; date.setDate(date.getDate() + i);
// Create 365 days of data with clear trends // Create alternating trends every ~30 days
for (let i = 0; i < 365; i++) { const cycleDay = i % 60;
const date = new Date(startDate); if (cycleDay < 30) {
date.setDate(date.getDate() + i); // Uptrend - will create golden crosses
price += Math.random() * 2 - 0.5; // Bias upward
// Create alternating trends every ~30 days } else {
const cycleDay = i % 60; // Downtrend - will create death crosses
if (cycleDay < 30) { price -= Math.random() * 2 - 0.5; // Bias downward
// Uptrend - will create golden crosses }
price += Math.random() * 2 - 0.5; // Bias upward
} else { // Add some volatility
// Downtrend - will create death crosses const dayChange = (Math.random() - 0.5) * 4;
price -= Math.random() * 2 - 0.5; // Bias downward price = Math.max(100, Math.min(200, price + dayChange));
}
data.push({
// Add some volatility timestamp: date.toISOString(),
const dayChange = (Math.random() - 0.5) * 4; open: price - Math.random() * 2,
price = Math.max(100, Math.min(200, price + dayChange)); high: price + Math.random() * 2,
low: price - Math.random() * 2,
data.push({ close: price,
timestamp: date.toISOString(), volume: Math.floor(Math.random() * 10000000) + 5000000,
open: price - Math.random() * 2, });
high: price + Math.random() * 2, }
low: price - Math.random() * 2,
close: price, return data;
volume: Math.floor(Math.random() * 10000000) + 5000000 }
});
} async function forceBothTradeTypes() {
// Create service container with minimal logging
return data; const { container, storageService, marketDataService, modeManager, strategyManager } =
} await createExampleRuntime();
async function forceBothTradeTypes() { // Override the mock data generation
// Create service container with minimal logging const _originalGenerateMockData = marketDataService.generateMockData;
const container: IServiceContainer = { marketDataService.generateMockData = function (
logger: { _symbol: string,
info: (msg: string, ...args: any[]) => { _startDate: string,
if (msg.includes('cross detected') || msg.includes('Generated') || msg.includes('Position update')) { _endDate: string
console.log('[INFO]', msg, ...args); ) {
} console.log('Generating mock data with forced crossovers...');
}, return generateMockDataWithBothCrosses();
error: console.error, };
warn: () => {},
debug: () => {}, // Initialize backtest mode
} as any, await modeManager.initializeMode({
custom: {} mode: 'backtest',
}; startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
// Initialize services speed: 'max',
const storageService = new StorageService(); symbols: ['AAPL'],
const marketDataService = new MarketDataService(container); initialCapital: 100000,
const executionService = new ExecutionService(container); dataFrequency: '1d',
const modeManager = new ModeManager(container, marketDataService, executionService, storageService); strategy: 'sma-crossover',
const strategyManager = new StrategyManager(container); });
container.custom = { // Create backtest engine
MarketDataService: marketDataService, const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
ExecutionService: executionService,
ModeManager: modeManager, // Configure backtest
StorageService: storageService const config = {
}; mode: 'backtest' as const,
name: 'Force Both Trade Types',
// Override the mock data generation strategy: 'sma-crossover',
const originalGenerateMockData = marketDataService.generateMockData; symbols: ['AAPL'],
marketDataService.generateMockData = function(symbol: string, startDate: string, endDate: string) { startDate: '2023-01-01T00:00:00Z',
console.log('Generating mock data with forced crossovers...'); endDate: '2024-01-01T00:00:00Z',
return generateMockDataWithBothCrosses(); initialCapital: 100000,
}; commission: 0.001,
slippage: 0.0001,
// Initialize backtest mode dataFrequency: '1d' as const,
await modeManager.initializeMode({ speed: 'max' as const,
mode: 'backtest', };
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z', console.log('=== TESTING WITH FORCED CROSSOVERS ===\n');
speed: 'max',
symbols: ['AAPL'], try {
initialCapital: 100000, const result = await backtestEngine.runBacktest(config);
dataFrequency: '1d',
strategy: 'sma-crossover' console.log('\n=== BACKTEST COMPLETE ===');
}); console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Create backtest engine // Analyze trades
const backtestEngine = new BacktestEngine(container, storageService, strategyManager); let longTrades = 0;
let shortTrades = 0;
// Configure backtest
const config = { result.trades.forEach(trade => {
mode: 'backtest' as const, if (trade.side === 'buy') {
name: 'Force Both Trade Types', longTrades++;
strategy: 'sma-crossover', console.log(`\nLONG trade found:`);
symbols: ['AAPL'], console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
startDate: '2023-01-01T00:00:00Z', console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
endDate: '2024-01-01T00:00:00Z', console.log(` P&L: $${trade.pnl.toFixed(2)}`);
initialCapital: 100000, } else {
commission: 0.001, shortTrades++;
slippage: 0.0001, console.log(`\nSHORT trade found:`);
dataFrequency: '1d' as const, console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
speed: 'max' as const console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
}; console.log(` P&L: $${trade.pnl.toFixed(2)}`);
}
console.log('=== TESTING WITH FORCED CROSSOVERS ===\n'); });
try { console.log('\n=== FINAL SUMMARY ===');
const result = await backtestEngine.runBacktest(config); console.log(`LONG trades: ${longTrades}`);
console.log(`SHORT trades: ${shortTrades}`);
console.log('\n=== BACKTEST COMPLETE ==='); console.log(`Total trades: ${result.metrics.totalTrades}`);
console.log(`Total Trades: ${result.metrics.totalTrades}`);
if (longTrades > 0 && shortTrades > 0) {
// Analyze trades console.log('\n✅ SUCCESS: Both long and short trades are working!');
let longTrades = 0; } else {
let shortTrades = 0; console.log('\n❌ ISSUE: Missing trade types');
if (longTrades === 0) {
result.trades.forEach((trade) => { console.log(' - No long trades found');
if (trade.side === 'buy') { }
longTrades++; if (shortTrades === 0) {
console.log(`\nLONG trade found:`); console.log(' - No short trades found');
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); }
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); }
console.log(` P&L: $${trade.pnl.toFixed(2)}`); } catch (error) {
} else { console.error('Test failed:', error);
shortTrades++; }
console.log(`\nSHORT trade found:`); }
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); // Run the test
console.log(` P&L: $${trade.pnl.toFixed(2)}`); forceBothTradeTypes().catch(console.error);
}
});
console.log('\n=== FINAL SUMMARY ===');
console.log(`LONG trades: ${longTrades}`);
console.log(`SHORT trades: ${shortTrades}`);
console.log(`Total trades: ${result.metrics.totalTrades}`);
if (longTrades > 0 && shortTrades > 0) {
console.log('\n✅ SUCCESS: Both long and short trades are working!');
} else {
console.log('\n❌ ISSUE: Missing trade types');
if (longTrades === 0) console.log(' - No long trades found');
if (shortTrades === 0) console.log(' - No short trades found');
}
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the test
forceBothTradeTypes().catch(console.error);

View file

@ -1,217 +1,238 @@
/** import { defined } from '@stock-bot/invariants';
* Examples of using the Rust-based Technical Analysis library /**
*/ * Examples of using the Rust-based Technical Analysis library
*/
import { IncrementalIndicators, SignalGenerator, TechnicalAnalysis } from '../src/indicators/TechnicalAnalysis';
import {
// Example 1: Basic indicator calculations IncrementalIndicators,
async function basicIndicatorExample() { SignalGenerator,
console.log('=== Basic Indicator Example ==='); TechnicalAnalysis,
} from '../src/indicators/TechnicalAnalysis';
const ta = new TechnicalAnalysis();
// Example 1: Basic indicator calculations
// Sample price data async function basicIndicatorExample() {
const prices = [ console.log('=== Basic Indicator Example ===');
100, 102, 101, 103, 105, 104, 106, 108, 107, 109,
111, 110, 112, 114, 113, 115, 117, 116, 118, 120 const ta = new TechnicalAnalysis();
];
// Sample price data
// Calculate various indicators const prices = [
const sma10 = ta.sma(prices, 10); 100, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111, 110, 112, 114, 113, 115, 117, 116, 118,
const ema10 = ta.ema(prices, 10); 120,
const rsi14 = ta.rsi(prices, 14); ];
console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`); // Calculate various indicators
console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`); const sma10 = ta.sma(prices, 10);
console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`); const ema10 = ta.ema(prices, 10);
const rsi14 = ta.rsi(prices, 14);
// Latest values
console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`); console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`); console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`); console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`);
}
// Latest values
// Example 2: Real-time streaming indicators console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`);
async function streamingIndicatorExample() { console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`);
console.log('\n=== Streaming Indicator Example ==='); console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`);
}
const manager = new IncrementalIndicators();
// Example 2: Real-time streaming indicators
// Create indicators async function streamingIndicatorExample() {
manager.createSMA('sma_fast', 5); console.log('\n=== Streaming Indicator Example ===');
manager.createSMA('sma_slow', 10);
manager.createEMA('ema', 10); const manager = new IncrementalIndicators();
manager.createRSI('rsi', 14);
// Create indicators
// Simulate real-time price updates manager.createSMA('sma_fast', 5);
console.log('Processing real-time price updates...'); manager.createSMA('sma_slow', 10);
for (let i = 0; i < 20; i++) { manager.createEMA('ema', 10);
const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2; manager.createRSI('rsi', 14);
const smaFast = manager.update('sma_fast', price); // Simulate real-time price updates
const smaSlow = manager.update('sma_slow', price); console.log('Processing real-time price updates...');
const ema = manager.update('ema', price); for (let i = 0; i < 20; i++) {
const rsi = manager.update('rsi', price); const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2;
if (i >= 14) { // Once we have enough data const smaFast = manager.update('sma_fast', price);
console.log(`Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}`); const smaSlow = manager.update('sma_slow', price);
} const ema = manager.update('ema', price);
} const rsi = manager.update('rsi', price);
}
if (i >= 14) {
// Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic) // Once we have enough data
async function complexIndicatorExample() { console.log(
console.log('\n=== Complex Indicator Example ==='); `Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}`
);
const ta = new TechnicalAnalysis(); }
}
// Generate more realistic price data }
const generatePrices = (count: number) => {
const prices = { close: [], high: [], low: [], volume: [] } as any; // Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic)
let basePrice = 100; async function complexIndicatorExample() {
console.log('\n=== Complex Indicator Example ===');
for (let i = 0; i < count; i++) {
const change = (Math.random() - 0.5) * 2; const ta = new TechnicalAnalysis();
basePrice += change;
const high = basePrice + Math.random() * 1; // Generate more realistic price data
const low = basePrice - Math.random() * 1; const generatePrices = (count: number) => {
const close = low + Math.random() * (high - low); const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
close: [],
prices.close.push(close); high: [],
prices.high.push(high); low: [],
prices.low.push(low); volume: [],
prices.volume.push(Math.random() * 1000000 + 500000); };
} let basePrice = 100;
return prices; for (let i = 0; i < count; i++) {
}; const change = (Math.random() - 0.5) * 2;
basePrice += change;
const prices = generatePrices(50); const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
// Calculate MACD const close = low + Math.random() * (high - low);
const macd = ta.macd(prices.close);
console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`); prices.close.push(close);
console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`); prices.high.push(high);
console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`); prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
// Calculate Bollinger Bands }
const bb = ta.bollingerBands(prices.close, 20, 2);
const currentPrice = prices.close[prices.close.length - 1]; return prices;
const bbPercent = (currentPrice - TechnicalAnalysis.latest(bb.lower)!) / };
(TechnicalAnalysis.latest(bb.upper)! - TechnicalAnalysis.latest(bb.lower)!);
const prices = generatePrices(50);
console.log(`\nBollinger Bands:`);
console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`); // Calculate MACD
console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`); const macd = ta.macd(prices.close);
console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`); console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`);
console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`); console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`);
console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`);
// Calculate Stochastic
const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3); // Calculate Bollinger Bands
console.log(`\nStochastic:`); const bb = ta.bollingerBands(prices.close, 20, 2);
console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`); const currentPrice = prices.close[prices.close.length - 1];
console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`); const bbPercent =
(currentPrice - defined(TechnicalAnalysis.latest(bb.lower))) /
// Calculate ATR (defined(TechnicalAnalysis.latest(bb.upper)) - defined(TechnicalAnalysis.latest(bb.lower)));
const atr = ta.atr(prices.high, prices.low, prices.close, 14);
console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`); console.log(`\nBollinger Bands:`);
} console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`);
console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`);
// Example 4: Trading signal generation console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`);
async function signalGenerationExample() { console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`);
console.log('\n=== Signal Generation Example ===');
// Calculate Stochastic
const generator = new SignalGenerator(); const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3);
console.log(`\nStochastic:`);
// Generate trending market data console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`);
const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => { console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`);
const prices = { close: [], high: [], low: [], volume: [] } as any;
let basePrice = 100; // Calculate ATR
const atr = ta.atr(prices.high, prices.low, prices.close, 14);
for (let i = 0; i < count; i++) { console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`);
const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0; }
const noise = (Math.random() - 0.5) * 2;
basePrice += trendComponent + noise; // Example 4: Trading signal generation
async function signalGenerationExample() {
const high = basePrice + Math.random() * 1; console.log('\n=== Signal Generation Example ===');
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low); const generator = new SignalGenerator();
prices.close.push(close); // Generate trending market data
prices.high.push(high); const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => {
prices.low.push(low); const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
prices.volume.push(Math.random() * 1000000 + 500000); close: [],
} high: [],
low: [],
return prices; volume: [],
}; };
let basePrice = 100;
// Test different market conditions
const scenarios = [ for (let i = 0; i < count; i++) {
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') }, const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0;
{ name: 'Downtrend', data: generateTrendingPrices(50, 'down') }, const noise = (Math.random() - 0.5) * 2;
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') } basePrice += trendComponent + noise;
];
const high = basePrice + Math.random() * 1;
for (const scenario of scenarios) { const low = basePrice - Math.random() * 1;
const signal = generator.generateSignals('TEST', scenario.data, Date.now()); const close = low + Math.random() * (high - low);
console.log(`\n${scenario.name} Market:`);
console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`); prices.close.push(close);
console.log(`Reason: ${signal.reason}`); prices.high.push(high);
console.log(`Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`); prices.low.push(low);
} prices.volume.push(Math.random() * 1000000 + 500000);
} }
// Example 5: Crossover detection return prices;
async function crossoverExample() { };
console.log('\n=== Crossover Detection Example ===');
// Test different market conditions
const ta = new TechnicalAnalysis(); const scenarios = [
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') },
// Generate price data with clear trend changes { name: 'Downtrend', data: generateTrendingPrices(50, 'down') },
const prices: number[] = []; { name: 'Sideways', data: generateTrendingPrices(50, 'sideways') },
for (let i = 0; i < 100; i++) { ];
if (i < 30) {
prices.push(100 + i * 0.3); // Uptrend for (const scenario of scenarios) {
} else if (i < 60) { const signal = generator.generateSignals('TEST', scenario.data, Date.now());
prices.push(109 - (i - 30) * 0.3); // Downtrend console.log(`\n${scenario.name} Market:`);
} else { console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`);
prices.push(100 + (i - 60) * 0.2); // Uptrend again console.log(`Reason: ${signal.reason}`);
} console.log(
} `Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`
);
// Calculate moving averages }
const fastMA = ta.sma(prices, 10); }
const slowMA = ta.sma(prices, 20);
// Example 5: Crossover detection
// Detect crossovers async function crossoverExample() {
console.log('Checking for crossovers in the last 10 bars:'); console.log('\n=== Crossover Detection Example ===');
for (let i = Math.max(0, fastMA.length - 10); i < fastMA.length; i++) {
const fast = fastMA.slice(0, i + 1); const ta = new TechnicalAnalysis();
const slow = slowMA.slice(0, i + 1);
// Generate price data with clear trend changes
if (TechnicalAnalysis.crossover(fast, slow)) { const prices: number[] = [];
console.log(`Bullish crossover at index ${i + 20}`); for (let i = 0; i < 100; i++) {
} else if (TechnicalAnalysis.crossunder(fast, slow)) { if (i < 30) {
console.log(`Bearish crossover at index ${i + 20}`); prices.push(100 + i * 0.3); // Uptrend
} } else if (i < 60) {
} prices.push(109 - (i - 30) * 0.3); // Downtrend
} } else {
prices.push(100 + (i - 60) * 0.2); // Uptrend again
// Run all examples }
async function runExamples() { }
try {
await basicIndicatorExample(); // Calculate moving averages
await streamingIndicatorExample(); const fastMA = ta.sma(prices, 10);
await complexIndicatorExample(); const slowMA = ta.sma(prices, 20);
await signalGenerationExample();
await crossoverExample(); // Detect crossovers
} catch (error) { console.log('Checking for crossovers in the last 10 bars:');
console.error('Error running examples:', error); for (let i = Math.max(0, fastMA.length - 10); i < fastMA.length; i++) {
} const fast = fastMA.slice(0, i + 1);
} const slow = slowMA.slice(0, i + 1);
// Execute if running directly if (TechnicalAnalysis.crossover(fast, slow)) {
if (require.main === module) { console.log(`Bullish crossover at index ${i + 20}`);
runExamples(); } else if (TechnicalAnalysis.crossunder(fast, slow)) {
} console.log(`Bearish crossover at index ${i + 20}`);
}
}
}
// Run all examples
async function runExamples() {
try {
await basicIndicatorExample();
await streamingIndicatorExample();
await complexIndicatorExample();
await signalGenerationExample();
await crossoverExample();
} catch (error) {
console.error('Error running examples:', error);
}
}
// Execute if running directly
if (require.main === module) {
runExamples();
}

View file

@ -1,99 +1,75 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { createExampleRuntime } from './example-runtime';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager'; async function showOrderFlow() {
import { MarketDataService } from '../src/services/MarketDataService'; // Create service container
import { ExecutionService } from '../src/services/ExecutionService'; const {
import { IServiceContainer } from '@stock-bot/di'; container,
storageService,
async function showOrderFlow() { marketDataService: _marketDataService,
// Create service container modeManager,
const container: IServiceContainer = { strategyManager,
logger: { } = await createExampleRuntime();
info: (msg: string, ...args: any[]) => {
// Only log order-related messages // Initialize backtest mode
if (msg.includes('order') || msg.includes('Order') || msg.includes('Filling') || msg.includes('cross detected')) { await modeManager.initializeMode({
console.log('[INFO]', msg, ...args); mode: 'backtest',
} startDate: '2023-07-01T00:00:00Z',
}, endDate: '2023-08-01T00:00:00Z', // Just 1 month
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), speed: 'max',
warn: (msg: string, ...args: any[]) => {}, symbols: ['AAPL'],
debug: (msg: string, ...args: any[]) => {}, initialCapital: 100000,
} as any, dataFrequency: '1d',
custom: {} strategy: 'sma-crossover',
}; });
// Initialize services // Create backtest engine
const storageService = new StorageService(); const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container); // Configure backtest
const modeManager = new ModeManager(container, marketDataService, executionService, storageService); const config = {
const strategyManager = new StrategyManager(container); mode: 'backtest' as const,
name: 'Order Flow Demo',
// Set services in container strategy: 'sma-crossover',
container.custom = { symbols: ['AAPL'],
MarketDataService: marketDataService, startDate: '2023-07-01T00:00:00Z',
ExecutionService: executionService, endDate: '2023-08-01T00:00:00Z',
ModeManager: modeManager, initialCapital: 100000,
StorageService: storageService commission: 0.001,
}; slippage: 0.0001,
dataFrequency: '1d' as const,
// Initialize backtest mode speed: 'max' as const,
await modeManager.initializeMode({ };
mode: 'backtest',
startDate: '2023-07-01T00:00:00Z', console.log('\n=== ORDER FLOW DEMONSTRATION ===\n');
endDate: '2023-08-01T00:00:00Z', // Just 1 month console.log('This will show the actual BUY and SELL orders being generated and executed:\n');
speed: 'max',
symbols: ['AAPL'], try {
initialCapital: 100000, const result = await backtestEngine.runBacktest(config);
dataFrequency: '1d',
strategy: 'sma-crossover' console.log('\n=== COMPLETED TRADES (Round-trips) ===');
}); console.log('Note: Each trade below represents a BUY order (entry) + SELL order (exit):\n');
// Create backtest engine result.trades.forEach((trade, i) => {
const backtestEngine = new BacktestEngine(container, storageService, strategyManager); console.log(`Trade ${i + 1}:`);
console.log(
// Configure backtest ` Opened with: BUY order on ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`
const config = { );
mode: 'backtest' as const, console.log(
name: 'Order Flow Demo', ` Closed with: SELL order on ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`
strategy: 'sma-crossover', );
symbols: ['AAPL'], console.log(` Trade type: ${trade.side === 'buy' ? 'LONG' : 'SHORT'} position`);
startDate: '2023-07-01T00:00:00Z', console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)\n`);
endDate: '2023-08-01T00:00:00Z', });
initialCapital: 100000,
commission: 0.001, console.log('Summary:');
slippage: 0.0001, console.log(`- Total completed trades: ${result.metrics.totalTrades}`);
dataFrequency: '1d' as const, console.log(`- Each trade = 1 BUY order + 1 SELL order`);
speed: 'max' as const console.log(`- Total orders executed: ${result.metrics.totalTrades * 2}`);
}; } catch (error) {
console.error('Failed:', error);
console.log('\n=== ORDER FLOW DEMONSTRATION ===\n'); }
console.log('This will show the actual BUY and SELL orders being generated and executed:\n'); }
try { // Run the demo
const result = await backtestEngine.runBacktest(config); showOrderFlow().catch(console.error);
console.log('\n=== COMPLETED TRADES (Round-trips) ===');
console.log('Note: Each trade below represents a BUY order (entry) + SELL order (exit):\n');
result.trades.forEach((trade, i) => {
console.log(`Trade ${i + 1}:`);
console.log(` Opened with: BUY order on ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Closed with: SELL order on ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` Trade type: ${trade.side === 'buy' ? 'LONG' : 'SHORT'} position`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)\n`);
});
console.log('Summary:');
console.log(`- Total completed trades: ${result.metrics.totalTrades}`);
console.log(`- Each trade = 1 BUY order + 1 SELL order`);
console.log(`- Total orders executed: ${result.metrics.totalTrades * 2}`);
} catch (error) {
console.error('Failed:', error);
}
}
// Run the demo
showOrderFlow().catch(console.error);

View file

@ -1,115 +1,92 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { getLogger } from '@stock-bot/logger';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StorageService } from '../src/services/StorageService'; import { createExampleRuntime } from './example-runtime';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService'; const _logger = getLogger('BacktestTest');
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di'; async function runSimpleBacktest() {
import { getLogger } from '@stock-bot/logger'; // Create service container
const {
const logger = getLogger('BacktestTest'); container,
storageService,
async function runSimpleBacktest() { marketDataService: _marketDataService,
// Create service container modeManager,
const container: IServiceContainer = { strategyManager,
logger: { } = await createExampleRuntime();
info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), // Initialize backtest mode with full config
warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args), await modeManager.initializeMode({
debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args), mode: 'backtest',
} as any, startDate: '2023-01-01T00:00:00Z',
custom: {} endDate: '2024-01-01T00:00:00Z',
}; speed: 'max',
symbols: ['AAPL'],
// Initialize services initialCapital: 100000,
const storageService = new StorageService(); dataFrequency: '1d',
const marketDataService = new MarketDataService(container); strategy: 'sma-crossover',
const executionService = new ExecutionService(container); });
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container); // Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Set services in container
container.custom = { // Configure backtest - shorter period for faster testing
MarketDataService: marketDataService, const config = {
ExecutionService: executionService, mode: 'backtest' as const, // Add mode field
ModeManager: modeManager, name: 'SMA Crossover Test',
StorageService: storageService strategy: 'sma-crossover',
}; symbols: ['AAPL'], // Just one symbol for simplicity
startDate: '2023-01-01T00:00:00Z', // ISO datetime format
// Initialize backtest mode with full config endDate: '2024-01-01T00:00:00Z', // ISO datetime format
await modeManager.initializeMode({ initialCapital: 100000,
mode: 'backtest', commission: 0.001,
startDate: '2023-01-01T00:00:00Z', slippage: 0.0001,
endDate: '2024-01-01T00:00:00Z', dataFrequency: '1d' as const,
speed: 'max', speed: 'max' as const,
symbols: ['AAPL'], };
initialCapital: 100000,
dataFrequency: '1d', console.log('Starting backtest with configuration:', config);
strategy: 'sma-crossover'
}); try {
const result = await backtestEngine.runBacktest(config);
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager); console.log('\n=== BACKTEST RESULTS ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Configure backtest - shorter period for faster testing console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
const config = { console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
mode: 'backtest' as const, // Add mode field console.log(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
name: 'SMA Crossover Test', console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`);
strategy: 'sma-crossover',
symbols: ['AAPL'], // Just one symbol for simplicity console.log('\n=== TRADE HISTORY ===');
startDate: '2023-01-01T00:00:00Z', // ISO datetime format if (result.trades.length === 0) {
endDate: '2024-01-01T00:00:00Z', // ISO datetime format console.log('No trades were executed!');
initialCapital: 100000, } else {
commission: 0.001, result.trades.forEach((trade, i) => {
slippage: 0.0001, console.log(`\nTrade ${i + 1}:`);
dataFrequency: '1d' as const, console.log(` Symbol: ${trade.symbol}`);
speed: 'max' as const console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
}; console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
console.log('Starting backtest with configuration:', config); });
}
try {
const result = await backtestEngine.runBacktest(config); // Show some equity curve data
console.log('\n=== EQUITY CURVE (first and last 5 points) ===');
console.log('\n=== BACKTEST RESULTS ==='); const equityCurve = result.equity;
console.log(`Total Trades: ${result.metrics.totalTrades}`); if (equityCurve.length > 0) {
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); equityCurve.slice(0, 5).forEach(point => {
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); console.log(`${point.date}: $${point.value.toFixed(2)}`);
console.log(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`); });
console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`); if (equityCurve.length > 10) {
console.log('...');
console.log('\n=== TRADE HISTORY ==='); equityCurve.slice(-5).forEach(point => {
if (result.trades.length === 0) { console.log(`${point.date}: $${point.value.toFixed(2)}`);
console.log('No trades were executed!'); });
} else { }
result.trades.forEach((trade, i) => { }
console.log(`\nTrade ${i + 1}:`); } catch (error) {
console.log(` Symbol: ${trade.symbol}`); console.error('Backtest failed:', error);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); }
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); }
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
}); // Run the test
} runSimpleBacktest().catch(console.error);
// Show some equity curve data
console.log('\n=== EQUITY CURVE (first and last 5 points) ===');
const equityCurve = result.equity;
if (equityCurve.length > 0) {
equityCurve.slice(0, 5).forEach(point => {
console.log(`${point.date}: $${point.value.toFixed(2)}`);
});
if (equityCurve.length > 10) {
console.log('...');
equityCurve.slice(-5).forEach(point => {
console.log(`${point.date}: $${point.value.toFixed(2)}`);
});
}
}
} catch (error) {
console.error('Backtest failed:', error);
}
}
// Run the test
runSimpleBacktest().catch(console.error);

View file

@ -1,286 +1,299 @@
#!/usr/bin/env bun #!/usr/bin/env bun
/** /**
* Example of running a sophisticated backtest with all advanced features * Example of running a sophisticated backtest with all advanced features
*/ */
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { AnalyticsService } from '../src/services/AnalyticsService';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { StorageService } from '../src/services/StorageService';
import { StorageService } from '../src/services/StorageService'; import { StrategyManager } from '../src/strategies/StrategyManager';
import { AnalyticsService } from '../src/services/AnalyticsService'; import '../src/strategies/examples/MeanReversionStrategy';
import { MeanReversionStrategy } from '../src/strategies/examples/MeanReversionStrategy'; import '../src/strategies/examples/MLEnhancedStrategy';
import { MLEnhancedStrategy } from '../src/strategies/examples/MLEnhancedStrategy'; import { logger } from '@stock-bot/logger';
import { logger } from '@stock-bot/logger';
async function runSophisticatedBacktest() {
async function runSophisticatedBacktest() { // Initialize services
// Initialize services const storageService = new StorageService();
const storageService = new StorageService(); await storageService.initialize({ mode: 'backtest' });
await storageService.initialize({ mode: 'backtest' });
const analyticsService = new AnalyticsService({
const analyticsService = new AnalyticsService({ analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003',
analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003' });
});
const strategyManager = new StrategyManager();
const strategyManager = new StrategyManager();
// Create backtest engine
// Create backtest engine const backtestEngine = new BacktestEngine(storageService, strategyManager);
const backtestEngine = new BacktestEngine(storageService, strategyManager);
// Configure backtest with advanced options
// Configure backtest with advanced options const config = {
const config = { mode: 'backtest' as const,
mode: 'backtest' as const, startDate: '2023-01-01T00:00:00Z',
startDate: '2023-01-01T00:00:00Z', endDate: '2023-12-31T23:59:59Z',
endDate: '2023-12-31T23:59:59Z', symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'],
symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'], initialCapital: 1_000_000,
initialCapital: 1_000_000, dataFrequency: '5m' as const, // 5-minute bars for detailed analysis
dataFrequency: '5m' as const, // 5-minute bars for detailed analysis
// Advanced fill model configuration
// Advanced fill model configuration fillModel: {
fillModel: { slippage: 'realistic' as const,
slippage: 'realistic' as const, marketImpact: true,
marketImpact: true, partialFills: true,
partialFills: true, // Use sophisticated market impact models
// Use sophisticated market impact models impactModel: 'AlmgrenChriss',
impactModel: 'AlmgrenChriss', // Model hidden liquidity and dark pools
// Model hidden liquidity and dark pools includeHiddenLiquidity: true,
includeHiddenLiquidity: true, darkPoolParticipation: 0.2, // 20% of volume in dark pools
darkPoolParticipation: 0.2, // 20% of volume in dark pools // Realistic latency simulation
// Realistic latency simulation latencyMs: {
latencyMs: { mean: 1,
mean: 1, std: 0.5,
std: 0.5, tail: 10, // Occasional high latency
tail: 10 // Occasional high latency },
} },
},
// Risk limits
// Risk limits riskLimits: {
riskLimits: { maxPositionSize: 100_000,
maxPositionSize: 100_000, maxDailyLoss: 50_000,
maxDailyLoss: 50_000, maxDrawdown: 0.2, // 20% max drawdown
maxDrawdown: 0.20, // 20% max drawdown maxLeverage: 2.0,
maxLeverage: 2.0, maxConcentration: 0.3, // Max 30% in single position
maxConcentration: 0.30 // Max 30% in single position },
},
// Transaction costs
// Transaction costs costs: {
costs: { commission: 0.0005, // 5 bps
commission: 0.0005, // 5 bps borrowRate: 0.03, // 3% annual for shorts
borrowRate: 0.03, // 3% annual for shorts slippageModel: 'volumeDependent',
slippageModel: 'volumeDependent' },
},
// Strategies to test
// Strategies to test strategies: [
strategies: [ {
{ id: 'mean_reversion_1',
id: 'mean_reversion_1', name: 'Mean Reversion Strategy',
name: 'Mean Reversion Strategy', type: 'MeanReversion',
type: 'MeanReversion', enabled: true,
enabled: true, allocation: 0.5,
allocation: 0.5, symbols: ['AAPL', 'GOOGL', 'MSFT'],
symbols: ['AAPL', 'GOOGL', 'MSFT'], parameters: {
parameters: { lookback: 20,
lookback: 20, entryZScore: 2.0,
entryZScore: 2.0, exitZScore: 0.5,
exitZScore: 0.5, minVolume: 1_000_000,
minVolume: 1_000_000, stopLoss: 0.05, // 5% stop loss
stopLoss: 0.05 // 5% stop loss },
} },
}, {
{ id: 'ml_enhanced_1',
id: 'ml_enhanced_1', name: 'ML Enhanced Strategy',
name: 'ML Enhanced Strategy', type: 'MLEnhanced',
type: 'MLEnhanced', enabled: true,
enabled: true, allocation: 0.5,
allocation: 0.5, symbols: ['AMZN', 'TSLA'],
symbols: ['AMZN', 'TSLA'], parameters: {
parameters: { modelPath: './models/ml_strategy_v1',
modelPath: './models/ml_strategy_v1', updateFrequency: 1440, // Daily retraining
updateFrequency: 1440, // Daily retraining minConfidence: 0.6,
minConfidence: 0.6 },
} },
} ],
] };
};
logger.info('Starting sophisticated backtest...');
logger.info('Starting sophisticated backtest...');
try {
try { // Run the backtest
// Run the backtest const result = await backtestEngine.runBacktest(config);
const result = await backtestEngine.runBacktest(config);
logger.info('Backtest completed successfully');
logger.info('Backtest completed successfully'); logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`);
logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`); logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`);
logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`); logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`);
logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`);
// Run statistical validation
// Run statistical validation logger.info('Running statistical validation...');
logger.info('Running statistical validation...'); const validationResult = await analyticsService.validateBacktest({
const validationResult = await analyticsService.validateBacktest({ backtestId: result.id,
backtestId: result.id, returns: result.dailyReturns,
returns: result.dailyReturns, trades: result.trades,
trades: result.trades, parameters: extractParameters(config.strategies),
parameters: extractParameters(config.strategies) });
});
if (validationResult.is_overfit) {
if (validationResult.is_overfit) { logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!');
logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!'); logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`);
logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`); logger.warn('Recommendations:');
logger.warn('Recommendations:'); validationResult.recommendations.forEach(rec => {
validationResult.recommendations.forEach(rec => { logger.warn(` - ${rec}`);
logger.warn(` - ${rec}`); });
}); } else {
} else { logger.info('✅ Backtest passed statistical validation');
logger.info('✅ Backtest passed statistical validation'); logger.info(`PSR: ${validationResult.psr.toFixed(3)}`);
logger.info(`PSR: ${validationResult.psr.toFixed(3)}`); logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`);
logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`); }
}
// Generate comprehensive report
// Generate comprehensive report logger.info('Generating performance report...');
logger.info('Generating performance report...'); const report = await backtestEngine.exportResults('html');
const report = await backtestEngine.exportResults('html');
// Save report
// Save report const fs = require('fs');
const fs = require('fs'); const reportPath = `./reports/backtest_${result.id}.html`;
const reportPath = `./reports/backtest_${result.id}.html`; fs.writeFileSync(reportPath, report);
fs.writeFileSync(reportPath, report); logger.info(`Report saved to: ${reportPath}`);
logger.info(`Report saved to: ${reportPath}`);
// Advanced analytics
// Advanced analytics logger.info('Running advanced analytics...');
logger.info('Running advanced analytics...');
// Factor attribution
// Factor attribution const factorAnalysis = await analyticsService.analyzeFactors({
const factorAnalysis = await analyticsService.analyzeFactors({ returns: result.dailyReturns,
returns: result.dailyReturns, positions: result.finalPositions,
positions: result.finalPositions, marketReturns: await getMarketReturns(config.startDate, config.endDate),
marketReturns: await getMarketReturns(config.startDate, config.endDate) });
});
logger.info('Factor Attribution:');
logger.info('Factor Attribution:'); logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`);
logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`); logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`);
logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`); logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`);
logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`);
// Transaction cost analysis
// Transaction cost analysis const tcaReport = await analyticsService.analyzeTCA({
const tcaReport = await analyticsService.analyzeTCA({ trades: result.trades,
trades: result.trades, orders: result.orders,
orders: result.orders });
});
logger.info('Transaction Cost Analysis:');
logger.info('Transaction Cost Analysis:'); logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`);
logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`); logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`);
logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`); logger.info(
logger.info(` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps`); ` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps`
);
// Performance by time period
const periodAnalysis = analyzeByPeriod(result); // Performance by time period
logger.info('Performance by Period:'); const periodAnalysis = analyzeByPeriod(result);
Object.entries(periodAnalysis).forEach(([period, metrics]) => { logger.info('Performance by Period:');
logger.info(` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})`); Object.entries(periodAnalysis).forEach(([period, metrics]) => {
}); logger.info(
` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})`
// Strategy correlation analysis );
if (config.strategies.length > 1) { });
const correlations = await calculateStrategyCorrelations(result);
logger.info('Strategy Correlations:'); // Strategy correlation analysis
correlations.forEach(({ pair, correlation }) => { if (config.strategies.length > 1) {
logger.info(` ${pair}: ${correlation.toFixed(3)}`); const correlations = await calculateStrategyCorrelations(result);
}); logger.info('Strategy Correlations:');
} correlations.forEach(({ pair, correlation }) => {
logger.info(` ${pair}: ${correlation.toFixed(3)}`);
// Monte Carlo simulation });
logger.info('Running Monte Carlo simulation...'); }
const monteCarloResults = await runMonteCarloSimulation(result, 1000);
logger.info(`Monte Carlo 95% VaR: ${monteCarloResults.var95.toFixed(2)}%`); // Monte Carlo simulation
logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`); logger.info('Running Monte Carlo simulation...');
const monteCarloResults = await runMonteCarloSimulation(result, 1000);
// Walk-forward analysis suggestion logger.info(`Monte Carlo 95% VaR: ${monteCarloResults.var95.toFixed(2)}%`);
if (result.performance.totalTrades > 100) { logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`);
logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation');
logger.info('Example: bun run examples/walk-forward-analysis.ts'); // Walk-forward analysis suggestion
} if (result.performance.totalTrades > 100) {
logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation');
} catch (error) { logger.info('Example: bun run examples/walk-forward-analysis.ts');
logger.error('Backtest failed:', error); }
} finally { } catch (error) {
await storageService.shutdown(); logger.error('Backtest failed:', error);
} } finally {
} await storageService.shutdown();
}
// Helper functions }
function extractParameters(strategies: any[]): Record<string, any> { // Helper functions
const params: Record<string, any> = {};
strategies.forEach(strategy => { function extractParameters(
Object.entries(strategy.parameters).forEach(([key, value]) => { strategies: { id: string; parameters: Record<string, unknown> }[]
params[`${strategy.id}_${key}`] = value; ): Record<string, unknown> {
}); const params: Record<string, unknown> = {};
}); strategies.forEach(strategy => {
return params; Object.entries(strategy.parameters).forEach(([key, value]) => {
} params[`${strategy.id}_${key}`] = value;
});
async function getMarketReturns(startDate: string, endDate: string): Promise<number[]> { });
// In real implementation, would fetch SPY or market index returns return params;
// For demo, return synthetic market returns }
const days = Math.floor((new Date(endDate).getTime() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24));
return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02); async function getMarketReturns(startDate: string, endDate: string): Promise<number[]> {
} // In real implementation, would fetch SPY or market index returns
// For demo, return synthetic market returns
function analyzeByPeriod(result: any): Record<string, { return: number; sharpe: number }> { const days = Math.floor(
const periods = { (new Date(endDate).getTime() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24)
'Q1': { start: 0, end: 63 }, );
'Q2': { start: 63, end: 126 }, return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02);
'Q3': { start: 126, end: 189 }, }
'Q4': { start: 189, end: 252 }
}; function analyzeByPeriod(result: {
dailyReturns: number[];
const analysis: Record<string, { return: number; sharpe: number }> = {}; }): Record<string, { return: number; sharpe: number }> {
const periods = {
Object.entries(periods).forEach(([name, { start, end }]) => { Q1: { start: 0, end: 63 },
const periodReturns = result.dailyReturns.slice(start, end); Q2: { start: 63, end: 126 },
if (periodReturns.length > 0) { Q3: { start: 126, end: 189 },
const avgReturn = periodReturns.reduce((a, b) => a + b, 0) / periodReturns.length; Q4: { start: 189, end: 252 },
const std = Math.sqrt(periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length); };
analysis[name] = { const analysis: Record<string, { return: number; sharpe: number }> = {};
return: avgReturn * periodReturns.length * 100,
sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0 Object.entries(periods).forEach(([name, { start, end }]) => {
}; const periodReturns = result.dailyReturns.slice(start, end);
} if (periodReturns.length > 0) {
}); const avgReturn = periodReturns.reduce((a, b) => a + b, 0) / periodReturns.length;
const std = Math.sqrt(
return analysis; periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length
} );
async function calculateStrategyCorrelations(result: any): Promise<Array<{ pair: string; correlation: number }>> { analysis[name] = {
// In real implementation, would calculate actual strategy return correlations return: avgReturn * periodReturns.length * 100,
// For demo, return sample correlations sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0,
return [ };
{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 } }
]; });
}
return analysis;
async function runMonteCarloSimulation(result: any, numSims: number): Promise<{ var95: number; cvar95: number }> { }
const returns = result.dailyReturns;
const simulatedReturns: number[] = []; async function calculateStrategyCorrelations(_result: {
dailyReturns: number[];
for (let i = 0; i < numSims; i++) { }): Promise<Array<{ pair: string; correlation: number }>> {
// Bootstrap resample returns // In real implementation, would calculate actual strategy return correlations
let cumReturn = 0; // For demo, return sample correlations
for (let j = 0; j < returns.length; j++) { return [{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }];
const randomIndex = Math.floor(Math.random() * returns.length); }
cumReturn += returns[randomIndex];
} async function runMonteCarloSimulation(
simulatedReturns.push(cumReturn * 100); result: { dailyReturns: number[] },
} numSims: number
): Promise<{ var95: number; cvar95: number }> {
// Calculate VaR and CVaR const returns = result.dailyReturns;
simulatedReturns.sort((a, b) => a - b); const simulatedReturns: number[] = [];
const index95 = Math.floor(numSims * 0.05);
const var95 = Math.abs(simulatedReturns[index95]); for (let i = 0; i < numSims; i++) {
const cvar95 = Math.abs(simulatedReturns.slice(0, index95).reduce((a, b) => a + b, 0) / index95); // Bootstrap resample returns
let cumReturn = 0;
return { var95, cvar95 }; for (let j = 0; j < returns.length; j++) {
} const randomIndex = Math.floor(Math.random() * returns.length);
cumReturn += returns[randomIndex];
// Run the backtest }
runSophisticatedBacktest().catch(console.error); simulatedReturns.push(cumReturn * 100);
}
// Calculate VaR and CVaR
simulatedReturns.sort((a, b) => a - b);
const index95 = Math.floor(numSims * 0.05);
const var95 = Math.abs(simulatedReturns[index95]);
const cvar95 = Math.abs(simulatedReturns.slice(0, index95).reduce((a, b) => a + b, 0) / index95);
return { var95, cvar95 };
}
// Run the backtest
runSophisticatedBacktest().catch(console.error);

View file

@ -1,103 +1,84 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { createExampleRuntime } from './example-runtime';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager'; async function testShortTrades() {
import { MarketDataService } from '../src/services/MarketDataService'; // Create service container
import { ExecutionService } from '../src/services/ExecutionService'; const {
import { IServiceContainer } from '@stock-bot/di'; container,
storageService,
async function testShortTrades() { marketDataService: _marketDataService,
// Create service container modeManager,
const container: IServiceContainer = { strategyManager,
logger: { } = await createExampleRuntime();
info: () => {},
error: console.error, // Initialize backtest mode
warn: () => {}, await modeManager.initializeMode({
debug: () => {}, mode: 'backtest',
} as any, startDate: '2023-01-01T00:00:00Z',
custom: {} endDate: '2024-01-01T00:00:00Z',
}; speed: 'max',
symbols: ['AAPL'],
// Initialize services initialCapital: 100000,
const storageService = new StorageService(); dataFrequency: '1d',
const marketDataService = new MarketDataService(container); strategy: 'sma-crossover',
const executionService = new ExecutionService(container); });
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container); // Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
container.custom = {
MarketDataService: marketDataService, // Configure backtest
ExecutionService: executionService, const config = {
ModeManager: modeManager, mode: 'backtest' as const,
StorageService: storageService name: 'Short Trade Test',
}; strategy: 'sma-crossover',
symbols: ['AAPL'],
// Initialize backtest mode startDate: '2023-01-01T00:00:00Z',
await modeManager.initializeMode({ endDate: '2024-01-01T00:00:00Z',
mode: 'backtest', initialCapital: 100000,
startDate: '2023-01-01T00:00:00Z', commission: 0.001,
endDate: '2024-01-01T00:00:00Z', slippage: 0.0001,
speed: 'max', dataFrequency: '1d' as const,
symbols: ['AAPL'], speed: 'max' as const,
initialCapital: 100000, };
dataFrequency: '1d',
strategy: 'sma-crossover' console.log('Testing short trade recording...\n');
});
try {
// Create backtest engine const result = await backtestEngine.runBacktest(config);
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
console.log('=== BACKTEST RESULTS ===');
// Configure backtest console.log(`Total Trades: ${result.metrics.totalTrades}`);
const config = { console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
mode: 'backtest' as const, console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
name: 'Short Trade Test',
strategy: 'sma-crossover', // Count long vs short trades
symbols: ['AAPL'], let longTrades = 0;
startDate: '2023-01-01T00:00:00Z', let shortTrades = 0;
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000, console.log('\n=== TRADE BREAKDOWN ===');
commission: 0.001, result.trades.forEach((trade, i) => {
slippage: 0.0001, const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
dataFrequency: '1d' as const, if (trade.side === 'buy') {
speed: 'max' as const longTrades++;
}; } else {
shortTrades++;
console.log('Testing short trade recording...\n'); }
try { console.log(`Trade ${i + 1} (${tradeType}):`);
const result = await backtestEngine.runBacktest(config); console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log('=== BACKTEST RESULTS ==='); console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
console.log(`Total Trades: ${result.metrics.totalTrades}`); console.log('');
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); });
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
console.log('=== TRADE TYPE SUMMARY ===');
// Count long vs short trades console.log(`Long trades: ${longTrades}`);
let longTrades = 0; console.log(`Short trades: ${shortTrades}`);
let shortTrades = 0; console.log(`Total trades: ${result.metrics.totalTrades}`);
} catch (error) {
console.log('\n=== TRADE BREAKDOWN ==='); console.error('Test failed:', error);
result.trades.forEach((trade, i) => { }
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT'; }
if (trade.side === 'buy') longTrades++;
else shortTrades++; // Run the test
testShortTrades().catch(console.error);
console.log(`Trade ${i + 1} (${tradeType}):`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
console.log('');
});
console.log('=== TRADE TYPE SUMMARY ===');
console.log(`Long trades: ${longTrades}`);
console.log(`Short trades: ${shortTrades}`);
console.log(`Total trades: ${result.metrics.totalTrades}`);
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the test
testShortTrades().catch(console.error);

View file

@ -1,188 +1,139 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import type { StrategyFill } from '../src/services/ExecutionService';
import { StorageService } from '../src/services/StorageService'; import type { OrderRequest } from '../src/types';
import { ModeManager } from '../src/core/ModeManager'; import { createExampleRuntime } from './example-runtime';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService'; async function traceShortPositions() {
import { IServiceContainer } from '@stock-bot/di'; let orderCount = 0;
let fillCount = 0;
async function traceShortPositions() { const orderTracker: (OrderRequest & { count: number })[] = [];
let orderCount = 0; const fillTracker: StrategyFill[] = [];
let fillCount = 0;
const orderTracker: any[] = []; // Create service container with detailed logging
const fillTracker: any[] = []; const { container, storageService, modeManager, strategyManager } = await createExampleRuntime();
strategyManager.on('order', (event: { order: OrderRequest }) => {
// Create service container with detailed logging orderTracker.push({ ...event.order, count: ++orderCount });
const container: IServiceContainer = { });
logger: { strategyManager.on('fill', (fill: StrategyFill) => {
info: (msg: string, ...args: any[]) => { fillCount++;
// Log all order and fill events fillTracker.push(fill);
if (msg.includes('order') || msg.includes('Order') || });
msg.includes('fill') || msg.includes('Fill') ||
msg.includes('position') || msg.includes('Position')) { // Listen to strategy events
console.log('[INFO]', msg, ...args); strategyManager.on('signal', (signal: unknown) => {
} console.log('\n🎯 STRATEGY SIGNAL:', signal);
});
// Track order submissions
if (msg.includes('Submitting order')) { // Initialize backtest mode
orderCount++; await modeManager.initializeMode({
const orderData = args[0]; mode: 'backtest',
orderTracker.push({ startDate: '2023-06-01T00:00:00Z',
count: orderCount, endDate: '2023-09-01T00:00:00Z', // 3 months
symbol: orderData.symbol, speed: 'max',
side: orderData.side, symbols: ['AAPL'],
quantity: orderData.quantity, initialCapital: 100000,
type: orderData.type dataFrequency: '1d',
}); strategy: 'sma-crossover',
console.log(`\n🔵 ORDER #${orderCount}:`, orderData.side.toUpperCase(), orderData.symbol); });
}
// Create backtest engine
// Track fills const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
if (msg.includes('Order filled')) {
fillCount++; // Configure backtest
const fillData = args[0]; const config = {
fillTracker.push({ mode: 'backtest' as const,
count: fillCount, name: 'Short Position Trace',
orderId: fillData.orderId, strategy: 'sma-crossover',
symbol: fillData.symbol, symbols: ['AAPL'],
side: fillData.side, startDate: '2023-06-01T00:00:00Z',
price: fillData.price, endDate: '2023-09-01T00:00:00Z',
quantity: fillData.quantity initialCapital: 100000,
}); commission: 0.001,
console.log(`\n🟢 FILL #${fillCount}:`, fillData.side.toUpperCase(), fillData.symbol, '@', fillData.price); slippage: 0.0001,
} dataFrequency: '1d' as const,
}, speed: 'max' as const,
error: console.error, };
warn: () => {},
debug: () => {}, console.log('=== TRACING SHORT POSITION FLOW ===\n');
} as any,
custom: {} try {
}; const result = await backtestEngine.runBacktest(config);
// Initialize services console.log('\n=== ORDER/FILL TRACKING SUMMARY ===');
const storageService = new StorageService(); console.log(`Total orders submitted: ${orderCount}`);
const marketDataService = new MarketDataService(container); console.log(`Total fills executed: ${fillCount}`);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService); // Analyze order flow
const strategyManager = new StrategyManager(container); let buyOrders = 0;
let sellOrders = 0;
container.custom = { orderTracker.forEach(order => {
MarketDataService: marketDataService, if (order.side === 'buy') {
ExecutionService: executionService, buyOrders++;
ModeManager: modeManager, } else {
StorageService: storageService sellOrders++;
}; }
});
// Listen to strategy events
strategyManager.on('signal', (signal: any) => { console.log(`\nOrder breakdown:`);
console.log('\n🎯 STRATEGY SIGNAL:', signal); console.log(`- BUY orders: ${buyOrders}`);
}); console.log(`- SELL orders: ${sellOrders}`);
// Initialize backtest mode // Check for short positions
await modeManager.initializeMode({ console.log('\n=== LOOKING FOR SHORT PATTERNS ===');
mode: 'backtest', console.log('(A short position starts with a SELL and closes with a BUY)\n');
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // 3 months let potentialShorts = 0;
speed: 'max', for (let i = 0; i < orderTracker.length - 1; i++) {
symbols: ['AAPL'], if (orderTracker[i].side === 'sell') {
initialCapital: 100000, // Look for subsequent buy to close
dataFrequency: '1d', for (let j = i + 1; j < orderTracker.length; j++) {
strategy: 'sma-crossover' if (orderTracker[j].side === 'buy' && orderTracker[j].symbol === orderTracker[i].symbol) {
}); potentialShorts++;
console.log(`Potential short trade found:`);
// Create backtest engine console.log(` Open: Order #${orderTracker[i].count} (SELL)`);
const backtestEngine = new BacktestEngine(container, storageService, strategyManager); console.log(` Close: Order #${orderTracker[j].count} (BUY)`);
break;
// Configure backtest }
const config = { }
mode: 'backtest' as const, }
name: 'Short Position Trace', }
strategy: 'sma-crossover',
symbols: ['AAPL'], console.log(`\nPotential short trades identified: ${potentialShorts}`);
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // Final results
initialCapital: 100000, console.log('\n=== BACKTEST RESULTS ===');
commission: 0.001, console.log(`Total closed trades: ${result.metrics.totalTrades}`);
slippage: 0.0001,
dataFrequency: '1d' as const, let longTrades = 0;
speed: 'max' as const let shortTrades = 0;
};
result.trades.forEach((trade, i) => {
console.log('=== TRACING SHORT POSITION FLOW ===\n'); const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') {
try { longTrades++;
const result = await backtestEngine.runBacktest(config); } else {
shortTrades++;
console.log('\n=== ORDER/FILL TRACKING SUMMARY ==='); }
console.log(`Total orders submitted: ${orderCount}`);
console.log(`Total fills executed: ${fillCount}`); console.log(`\nTrade ${i + 1} (${tradeType}):`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
// Analyze order flow console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
let buyOrders = 0; console.log(` P&L: $${trade.pnl.toFixed(2)}`);
let sellOrders = 0; });
orderTracker.forEach(order => {
if (order.side === 'buy') buyOrders++; console.log('\n=== FINAL SUMMARY ===');
else sellOrders++; console.log(`Long trades recorded: ${longTrades}`);
}); console.log(`Short trades recorded: ${shortTrades}`);
console.log(`Expected short trades (from order flow): ${potentialShorts}`);
console.log(`\nOrder breakdown:`);
console.log(`- BUY orders: ${buyOrders}`); if (shortTrades < potentialShorts) {
console.log(`- SELL orders: ${sellOrders}`); console.log('\n❌ ISSUE: Not all short trades were recorded in closed trades!');
console.log('This suggests the Rust core trade matching logic may have an issue.');
// Check for short positions }
console.log('\n=== LOOKING FOR SHORT PATTERNS ==='); } catch (error) {
console.log('(A short position starts with a SELL and closes with a BUY)\n'); console.error('Trace failed:', error);
}
let potentialShorts = 0; }
for (let i = 0; i < orderTracker.length - 1; i++) {
if (orderTracker[i].side === 'sell') { // Run the trace
// Look for subsequent buy to close traceShortPositions().catch(console.error);
for (let j = i + 1; j < orderTracker.length; j++) {
if (orderTracker[j].side === 'buy' && orderTracker[j].symbol === orderTracker[i].symbol) {
potentialShorts++;
console.log(`Potential short trade found:`);
console.log(` Open: Order #${orderTracker[i].count} (SELL)`);
console.log(` Close: Order #${orderTracker[j].count} (BUY)`);
break;
}
}
}
}
console.log(`\nPotential short trades identified: ${potentialShorts}`);
// Final results
console.log('\n=== BACKTEST RESULTS ===');
console.log(`Total closed trades: ${result.metrics.totalTrades}`);
let longTrades = 0;
let shortTrades = 0;
result.trades.forEach((trade, i) => {
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') longTrades++;
else shortTrades++;
console.log(`\nTrade ${i + 1} (${tradeType}):`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
});
console.log('\n=== FINAL SUMMARY ===');
console.log(`Long trades recorded: ${longTrades}`);
console.log(`Short trades recorded: ${shortTrades}`);
console.log(`Expected short trades (from order flow): ${potentialShorts}`);
if (shortTrades < potentialShorts) {
console.log('\n❌ ISSUE: Not all short trades were recorded in closed trades!');
console.log('This suggests the Rust core trade matching logic may have an issue.');
}
} catch (error) {
console.error('Trace failed:', error);
}
}
// Run the trace
traceShortPositions().catch(console.error);

View file

@ -1,133 +1,115 @@
import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager'; import { createExampleRuntime } from './example-runtime';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager'; async function verifyBothTradeTypes() {
import { MarketDataService } from '../src/services/MarketDataService'; // Create service container
import { ExecutionService } from '../src/services/ExecutionService'; const {
import { IServiceContainer } from '@stock-bot/di'; container,
storageService,
async function verifyBothTradeTypes() { marketDataService: _marketDataService,
// Create service container modeManager,
const container: IServiceContainer = { strategyManager,
logger: { } = await createExampleRuntime();
info: console.log,
error: console.error, // Initialize backtest mode
warn: console.warn, await modeManager.initializeMode({
debug: console.log, mode: 'backtest',
} as any, startDate: '2023-01-01T00:00:00Z',
custom: {} endDate: '2024-01-01T00:00:00Z',
}; speed: 'max',
symbols: ['AAPL'],
// Initialize services initialCapital: 100000,
const storageService = new StorageService(); dataFrequency: '1d',
const marketDataService = new MarketDataService(container); strategy: 'sma-crossover',
const executionService = new ExecutionService(container); });
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container); // Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
container.custom = {
MarketDataService: marketDataService, // Configure backtest
ExecutionService: executionService, const config = {
ModeManager: modeManager, mode: 'backtest' as const,
StorageService: storageService name: 'Trade Type Verification',
}; strategy: 'sma-crossover',
symbols: ['AAPL'],
// Initialize backtest mode startDate: '2023-01-01T00:00:00Z',
await modeManager.initializeMode({ endDate: '2024-01-01T00:00:00Z',
mode: 'backtest', initialCapital: 100000,
startDate: '2023-01-01T00:00:00Z', commission: 0.001,
endDate: '2024-01-01T00:00:00Z', slippage: 0.0001,
speed: 'max', dataFrequency: '1d' as const,
symbols: ['AAPL'], speed: 'max' as const,
initialCapital: 100000, };
dataFrequency: '1d',
strategy: 'sma-crossover' console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');
});
try {
// Create backtest engine const result = await backtestEngine.runBacktest(config);
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
console.log('=== BACKTEST COMPLETE ===');
// Configure backtest console.log(`Total Trades: ${result.metrics.totalTrades}`);
const config = { console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
mode: 'backtest' as const, console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
name: 'Trade Type Verification',
strategy: 'sma-crossover', // Analyze trades
symbols: ['AAPL'], let longTrades = 0;
startDate: '2023-01-01T00:00:00Z', let shortTrades = 0;
endDate: '2024-01-01T00:00:00Z', let longPnL = 0;
initialCapital: 100000, let shortPnL = 0;
commission: 0.001,
slippage: 0.0001, console.log('\n=== DETAILED TRADE ANALYSIS ===');
dataFrequency: '1d' as const, result.trades.forEach((trade, i) => {
speed: 'max' as const const isLong = trade.side === 'buy';
}; const tradeType = isLong ? 'LONG' : 'SHORT';
console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n'); if (isLong) {
longTrades++;
try { longPnL += trade.pnl;
const result = await backtestEngine.runBacktest(config); } else {
shortTrades++;
console.log('=== BACKTEST COMPLETE ==='); shortPnL += trade.pnl;
console.log(`Total Trades: ${result.metrics.totalTrades}`); }
console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); console.log(`\nTrade ${i + 1}:`);
console.log(` Type: ${tradeType} position`);
// Analyze trades console.log(` Opening side: ${trade.side.toUpperCase()}`);
let longTrades = 0; console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
let shortTrades = 0; console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
let longPnL = 0; console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
let shortPnL = 0;
// Explain the trade flow
console.log('\n=== DETAILED TRADE ANALYSIS ==='); if (isLong) {
result.trades.forEach((trade, i) => { console.log(` Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`);
const isLong = trade.side === 'buy'; } else {
const tradeType = isLong ? 'LONG' : 'SHORT'; console.log(` Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`);
}
if (isLong) { });
longTrades++;
longPnL += trade.pnl; console.log('\n=== SUMMARY BY TRADE TYPE ===');
} else { console.log(`LONG trades: ${longTrades}`);
shortTrades++; console.log(` - Total P&L from longs: $${longPnL.toFixed(2)}`);
shortPnL += trade.pnl; console.log(
} ` - Average P&L per long: $${longTrades > 0 ? (longPnL / longTrades).toFixed(2) : '0.00'}`
);
console.log(`\nTrade ${i + 1}:`);
console.log(` Type: ${tradeType} position`); console.log(`\nSHORT trades: ${shortTrades}`);
console.log(` Opening side: ${trade.side.toUpperCase()}`); console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); console.log(
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); ` - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}`
console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`); );
// Explain the trade flow console.log(`\nTotal trades: ${result.metrics.totalTrades}`);
if (isLong) {
console.log(` Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`); if (longTrades === 0) {
} else { console.log('\n⚠️ WARNING: No long trades found!');
console.log(` Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`); }
} if (shortTrades === 0) {
}); console.log('\n⚠️ WARNING: No short trades found!');
}
console.log('\n=== SUMMARY BY TRADE TYPE ==='); } catch (error) {
console.log(`LONG trades: ${longTrades}`); console.error('Test failed:', error);
console.log(` - Total P&L from longs: $${longPnL.toFixed(2)}`); }
console.log(` - Average P&L per long: $${longTrades > 0 ? (longPnL / longTrades).toFixed(2) : '0.00'}`); }
console.log(`\nSHORT trades: ${shortTrades}`); // Run the verification
console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`); verifyBothTradeTypes().catch(console.error);
console.log(` - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}`);
console.log(`\nTotal trades: ${result.metrics.totalTrades}`);
if (longTrades === 0) {
console.log('\n⚠️ WARNING: No long trades found!');
}
if (shortTrades === 0) {
console.log('\n⚠️ WARNING: No short trades found!');
}
} catch (error) {
console.error('Test failed:', error);
}
}
// Run the verification
verifyBothTradeTypes().catch(console.error);

View file

@ -6,7 +6,7 @@
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"dev": "bun --watch src/index.ts", "dev": "bun --watch src/index.ts",
"build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node", "build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
"start": "bun dist/index.js", "start": "bun dist/index.js",
"test": "bun test", "test": "bun test",
"test:indicators": "bun test tests/indicators.test.ts", "test:indicators": "bun test tests/indicators.test.ts",
@ -31,7 +31,11 @@
"zod": "^3.22.0", "zod": "^3.22.0",
"uuid": "^9.0.0", "uuid": "^9.0.0",
"axios": "^1.6.0", "axios": "^1.6.0",
"simple-statistics": "^7.8.3" "simple-statistics": "^7.8.3",
"@stock-bot/services": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/invariants": "workspace:*"
}, },
"peerDependencies": { "peerDependencies": {
"@tensorflow/tfjs-node": "^4.0.0" "@tensorflow/tfjs-node": "^4.0.0"
@ -43,6 +47,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^20.0.0", "@types/node": "^20.0.0",
"typescript": "^5.0.0" "typescript": "^5.0.0",
"@tensorflow/tfjs-node": "^4.0.0"
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,179 +1,215 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import { z } from 'zod'; import { z } from 'zod';
import { IServiceContainer } from '@stock-bot/di'; import { AnalyticsService } from '../../services/AnalyticsService';
import { AnalyticsService } from '../../services/AnalyticsService'; import type { OrchestratorServices as IServiceContainer } from '../../types';
const DateRangeSchema = z.object({ const DateRangeSchema = z.object({
startDate: z.string().datetime(), startDate: z.string().datetime(),
endDate: z.string().datetime() endDate: z.string().datetime(),
}); });
const OptimizationRequestSchema = z.object({ const OptimizationRequestSchema = z.object({
symbols: z.array(z.string()), symbols: z.array(z.string()),
returns: z.array(z.array(z.number())), returns: z.array(z.array(z.number())),
constraints: z.object({ constraints: z
minWeight: z.number().optional(), .object({
maxWeight: z.number().optional(), minWeight: z.number().optional(),
targetReturn: z.number().optional(), maxWeight: z.number().optional(),
maxRisk: z.number().optional() targetReturn: z.number().optional(),
}).optional() maxRisk: z.number().optional(),
}); })
.optional(),
export function createAnalyticsRoutes(container: IServiceContainer): Hono { });
const app = new Hono();
const analyticsService = container.custom?.AnalyticsService as AnalyticsService; export function createAnalyticsRoutes(container: IServiceContainer): Hono {
const app = new Hono();
// Get performance metrics const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
app.get('/performance/:portfolioId', async (c) => {
try { // Get performance metrics
const portfolioId = c.req.param('portfolioId'); app.get('/performance/:portfolioId', async c => {
const query = c.req.query(); try {
const portfolioId = c.req.param('portfolioId');
const { startDate, endDate } = DateRangeSchema.parse({ const query = c.req.query();
startDate: query.start_date,
endDate: query.end_date const { startDate, endDate } = DateRangeSchema.parse({
}); startDate: query.start_date,
endDate: query.end_date,
const metrics = await analyticsService.getPerformanceMetrics( });
portfolioId,
new Date(startDate), const metrics = await analyticsService.getPerformanceMetrics(
new Date(endDate) portfolioId,
); new Date(startDate),
new Date(endDate)
return c.json(metrics); );
} catch (error) {
if (error instanceof z.ZodError) { return c.json(metrics);
return c.json({ } catch (error) {
error: 'Invalid date range', if (error instanceof z.ZodError) {
details: error.errors return c.json(
}, 400); {
} error: 'Invalid date range',
details: error.errors,
container.logger.error('Error getting performance metrics:', error); },
return c.json({ 400
error: error instanceof Error ? error.message : 'Failed to get performance metrics' );
}, 500); }
}
}); container.logger.error('Error getting performance metrics:', error);
return c.json(
// Portfolio optimization {
app.post('/optimize', async (c) => { error: error instanceof Error ? error.message : 'Failed to get performance metrics',
try { },
const body = await c.req.json(); 500
const request = OptimizationRequestSchema.parse(body); );
}
const result = await analyticsService.optimizePortfolio({ });
returns: request.returns,
constraints: request.constraints // Portfolio optimization
}); app.post('/optimize', async c => {
try {
return c.json(result); const body = await c.req.json();
} catch (error) { const request = OptimizationRequestSchema.parse(body);
if (error instanceof z.ZodError) {
return c.json({ const result = await analyticsService.optimizePortfolio({
error: 'Invalid optimization request', returns: request.returns,
details: error.errors constraints: request.constraints,
}, 400); });
}
return c.json(result);
container.logger.error('Error optimizing portfolio:', error); } catch (error) {
return c.json({ if (error instanceof z.ZodError) {
error: error instanceof Error ? error.message : 'Failed to optimize portfolio' return c.json(
}, 500); {
} error: 'Invalid optimization request',
}); details: error.errors,
},
// Get risk metrics 400
app.get('/risk/:portfolioId', async (c) => { );
try { }
const portfolioId = c.req.param('portfolioId');
const metrics = await analyticsService.getRiskMetrics(portfolioId); container.logger.error('Error optimizing portfolio:', error);
return c.json(
return c.json(metrics); {
} catch (error) { error: error instanceof Error ? error.message : 'Failed to optimize portfolio',
container.logger.error('Error getting risk metrics:', error); },
return c.json({ 500
error: error instanceof Error ? error.message : 'Failed to get risk metrics' );
}, 500); }
} });
});
// Get risk metrics
// Market regime detection app.get('/risk/:portfolioId', async c => {
app.get('/regime', async (c) => { try {
try { const portfolioId = c.req.param('portfolioId');
const regime = await analyticsService.detectMarketRegime(); const metrics = await analyticsService.getRiskMetrics(portfolioId);
return c.json({ return c.json(metrics);
regime, } catch (error) {
timestamp: new Date().toISOString() container.logger.error('Error getting risk metrics:', error);
}); return c.json(
} catch (error) { {
container.logger.error('Error detecting market regime:', error); error: error instanceof Error ? error.message : 'Failed to get risk metrics',
return c.json({ },
error: error instanceof Error ? error.message : 'Failed to detect market regime' 500
}, 500); );
} }
}); });
// Calculate correlation matrix // Market regime detection
app.post('/correlation', async (c) => { app.get('/regime', async c => {
try { try {
const body = await c.req.json(); const regime = await analyticsService.detectMarketRegime();
const { symbols } = z.object({
symbols: z.array(z.string()).min(2) return c.json({
}).parse(body); regime,
timestamp: new Date().toISOString(),
const matrix = await analyticsService.calculateCorrelationMatrix(symbols); });
} catch (error) {
return c.json({ container.logger.error('Error detecting market regime:', error);
symbols, return c.json(
matrix {
}); error: error instanceof Error ? error.message : 'Failed to detect market regime',
} catch (error) { },
if (error instanceof z.ZodError) { 500
return c.json({ );
error: 'Invalid correlation request', }
details: error.errors });
}, 400);
} // Calculate correlation matrix
app.post('/correlation', async c => {
container.logger.error('Error calculating correlation:', error); try {
return c.json({ const body = await c.req.json();
error: error instanceof Error ? error.message : 'Failed to calculate correlation' const { symbols } = z
}, 500); .object({
} symbols: z.array(z.string()).min(2),
}); })
.parse(body);
// ML model prediction
app.post('/predict', async (c) => { const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
try {
const body = await c.req.json(); return c.json({
const { modelId, features } = z.object({ symbols,
modelId: z.string(), matrix,
features: z.record(z.number()) });
}).parse(body); } catch (error) {
if (error instanceof z.ZodError) {
const prediction = await analyticsService.predictWithModel(modelId, features); return c.json(
{
if (prediction) { error: 'Invalid correlation request',
return c.json(prediction); details: error.errors,
} else { },
return c.json({ error: 'Model not found or prediction failed' }, 404); 400
} );
} catch (error) { }
if (error instanceof z.ZodError) {
return c.json({ container.logger.error('Error calculating correlation:', error);
error: 'Invalid prediction request', return c.json(
details: error.errors {
}, 400); error: error instanceof Error ? error.message : 'Failed to calculate correlation',
} },
500
container.logger.error('Error making prediction:', error); );
return c.json({ }
error: error instanceof Error ? error.message : 'Failed to make prediction' });
}, 500);
} // ML model prediction
}); app.post('/predict', async c => {
try {
return app; const body = await c.req.json();
} const { modelId, features } = z
.object({
modelId: z.string(),
features: z.record(z.number()),
})
.parse(body);
const prediction = await analyticsService.predictWithModel(modelId, features);
if (prediction) {
return c.json(prediction);
} else {
return c.json({ error: 'Model not found or prediction failed' }, 404);
}
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid prediction request',
details: error.errors,
},
400
);
}
container.logger.error('Error making prediction:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to make prediction',
},
500
);
}
});
return app;
}

View file

@ -1,245 +1,278 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import { z } from 'zod'; import { z } from 'zod';
import { IServiceContainer } from '@stock-bot/di'; import { defined } from '@stock-bot/invariants';
import { BacktestConfigSchema } from '../../types'; import { ModeManager } from '../../core/ModeManager';
import { BacktestEngine } from '../../backtest/BacktestEngine'; import type { OrchestratorServices as IServiceContainer } from '../../types';
import { ModeManager } from '../../core/ModeManager'; import { BacktestConfigSchema } from '../../types';
const BacktestIdSchema = z.object({ const _BacktestIdSchema = z.object({
backtestId: z.string() backtestId: z.string(),
}); });
export function createBacktestRoutes(container: IServiceContainer): Hono { export function createBacktestRoutes(container: IServiceContainer): Hono {
const app = new Hono(); const app = new Hono();
const backtestEngine = container.custom?.BacktestEngine as BacktestEngine; const backtestEngine = defined(container.custom?.BacktestEngine);
const modeManager = container.custom?.ModeManager as ModeManager; const modeManager = container.custom?.ModeManager as ModeManager;
// Default POST to / is the same as /run for backward compatibility // Default POST to / is the same as /run for backward compatibility
app.post('/', async (c) => { app.post('/', async c => {
try { try {
const body = await c.req.json(); const body = await c.req.json();
const config = BacktestConfigSchema.parse(body); const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode // Initialize backtest mode
await modeManager.initializeMode(config); await modeManager.initializeMode(config);
// Run backtest // Run backtest
const result = await backtestEngine.runBacktest(config); const result = await backtestEngine.runBacktest(config);
return c.json(result, 201); return c.json(result, 201);
} catch (error) { } catch (error) {
if (error instanceof z.ZodError) { if (error instanceof z.ZodError) {
return c.json({ return c.json(
error: 'Invalid backtest configuration', {
details: error.errors error: 'Invalid backtest configuration',
}, 400); details: error.errors,
} },
400
container.logger.error('Error running backtest:', error); );
return c.json({ }
error: error instanceof Error ? error.message : 'Failed to run backtest'
}, 500); container.logger.error('Error running backtest:', error);
} return c.json(
}); {
error: error instanceof Error ? error.message : 'Failed to run backtest',
// Run new backtest (same as above but at /run) },
app.post('/run', async (c) => { 500
try { );
const body = await c.req.json(); }
const config = BacktestConfigSchema.parse(body); });
// Initialize backtest mode // Run new backtest (same as above but at /run)
await modeManager.initializeMode(config); app.post('/run', async c => {
try {
// Run backtest const body = await c.req.json();
const result = await backtestEngine.runBacktest(config); const config = BacktestConfigSchema.parse(body);
return c.json(result, 201); // Initialize backtest mode
} catch (error) { await modeManager.initializeMode(config);
if (error instanceof z.ZodError) {
return c.json({ // Run backtest
error: 'Invalid backtest configuration', const result = await backtestEngine.runBacktest(config);
details: error.errors
}, 400); return c.json(result, 201);
} } catch (error) {
if (error instanceof z.ZodError) {
container.logger.error('Error running backtest:', error); return c.json(
return c.json({ {
error: error instanceof Error ? error.message : 'Failed to run backtest' error: 'Invalid backtest configuration',
}, 500); details: error.errors,
} },
}); 400
);
// Stop running backtest }
app.post('/stop', async (c) => {
try { container.logger.error('Error running backtest:', error);
await backtestEngine.stopBacktest(); return c.json(
{
return c.json({ error: error instanceof Error ? error.message : 'Failed to run backtest',
message: 'Backtest stop requested', },
timestamp: new Date().toISOString() 500
}); );
} catch (error) { }
container.logger.error('Error stopping backtest:', error); });
return c.json({
error: error instanceof Error ? error.message : 'Failed to stop backtest' // Stop running backtest
}, 500); app.post('/stop', async c => {
} try {
}); await backtestEngine.stopBacktest();
// Pause running backtest return c.json({
app.post('/pause', async (c) => { message: 'Backtest stop requested',
try { timestamp: new Date().toISOString(),
await backtestEngine.pauseBacktest(); });
} catch (error) {
return c.json({ container.logger.error('Error stopping backtest:', error);
message: 'Backtest paused', return c.json(
timestamp: new Date().toISOString() {
}); error: error instanceof Error ? error.message : 'Failed to stop backtest',
} catch (error) { },
container.logger.error('Error pausing backtest:', error); 500
return c.json({ );
error: error instanceof Error ? error.message : 'Failed to pause backtest' }
}, 500); });
}
}); // Pause running backtest
app.post('/pause', async c => {
// Resume paused backtest try {
app.post('/resume', async (c) => { await backtestEngine.pauseBacktest();
try {
await backtestEngine.resumeBacktest(); return c.json({
message: 'Backtest paused',
return c.json({ timestamp: new Date().toISOString(),
message: 'Backtest resumed', });
timestamp: new Date().toISOString() } catch (error) {
}); container.logger.error('Error pausing backtest:', error);
} catch (error) { return c.json(
container.logger.error('Error resuming backtest:', error); {
return c.json({ error: error instanceof Error ? error.message : 'Failed to pause backtest',
error: error instanceof Error ? error.message : 'Failed to resume backtest' },
}, 500); 500
} );
}); }
});
// Set backtest speed
app.post('/speed', async (c) => { // Resume paused backtest
try { app.post('/resume', async c => {
const body = await c.req.json(); try {
const speed = body.speed ?? 1; await backtestEngine.resumeBacktest();
backtestEngine.setSpeedMultiplier(speed); return c.json({
message: 'Backtest resumed',
return c.json({ timestamp: new Date().toISOString(),
message: 'Backtest speed updated', });
speed: speed === null ? 'unlimited' : speed, } catch (error) {
timestamp: new Date().toISOString() container.logger.error('Error resuming backtest:', error);
}); return c.json(
} catch (error) { {
container.logger.error('Error setting backtest speed:', error); error: error instanceof Error ? error.message : 'Failed to resume backtest',
return c.json({ },
error: error instanceof Error ? error.message : 'Failed to set speed' 500
}, 500); );
} }
}); });
// Get backtest progress // Set backtest speed
app.get('/progress', async (c) => { app.post('/speed', async c => {
try { try {
const status = backtestEngine.getStatus(); const body = await c.req.json();
const speed = body.speed ?? 1;
return c.json({
status: status.isPaused ? 'paused' : (status.isRunning ? 'running' : 'idle'), backtestEngine.setSpeedMultiplier(speed);
progress: status.progress,
currentTime: new Date(status.currentTime).toISOString(), return c.json({
isRunning: status.isRunning, message: 'Backtest speed updated',
isPaused: status.isPaused speed: speed === null ? 'unlimited' : speed,
}); timestamp: new Date().toISOString(),
} catch (error) { });
container.logger.error('Error getting backtest progress:', error); } catch (error) {
return c.json({ container.logger.error('Error setting backtest speed:', error);
error: error instanceof Error ? error.message : 'Failed to get progress' return c.json(
}, 500); {
} error: error instanceof Error ? error.message : 'Failed to set speed',
}); },
500
// Stream backtest events (Server-Sent Events) );
app.get('/stream', async (c) => { }
c.header('Content-Type', 'text/event-stream'); });
c.header('Cache-Control', 'no-cache');
c.header('Connection', 'keep-alive'); // Get backtest progress
app.get('/progress', async c => {
const stream = new ReadableStream({ try {
start(controller) { const status = backtestEngine.getStatus();
// Listen for backtest events
const onProgress = (data: any) => { return c.json({
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`); status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
}; progress: status.progress,
currentTime: new Date(status.currentTime).toISOString(),
const onComplete = (data: any) => { isRunning: status.isRunning,
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`); isPaused: status.isPaused,
controller.close(); });
}; } catch (error) {
container.logger.error('Error getting backtest progress:', error);
backtestEngine.on('progress', onProgress); return c.json(
backtestEngine.on('complete', onComplete); {
error: error instanceof Error ? error.message : 'Failed to get progress',
// Cleanup on close },
c.req.raw.signal.addEventListener('abort', () => { 500
backtestEngine.off('progress', onProgress); );
backtestEngine.off('complete', onComplete); }
controller.close(); });
});
} // Stream backtest events (Server-Sent Events)
}); app.get('/stream', async c => {
c.header('Content-Type', 'text/event-stream');
return new Response(stream); c.header('Cache-Control', 'no-cache');
}); c.header('Connection', 'keep-alive');
// Validate backtest configuration const stream = new ReadableStream({
app.post('/validate', async (c) => { start(controller) {
try { // Listen for backtest events
const body = await c.req.json(); const onProgress = (data: unknown) => {
const config = BacktestConfigSchema.parse(body); controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
};
// Additional validation logic
const validation = { const onComplete = (data: unknown) => {
valid: true, controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
warnings: [] as string[], controller.close();
estimatedDuration: 0 };
};
backtestEngine.on('progress', onProgress);
// Check data availability backtestEngine.on('complete', onComplete);
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate); // Cleanup on close
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24); c.req.raw.signal.addEventListener('abort', () => {
backtestEngine.off('progress', onProgress);
if (days > 365) { backtestEngine.off('complete', onComplete);
validation.warnings.push('Large date range may take significant time to process'); controller.close();
} });
},
if (config.symbols.length > 100) { });
validation.warnings.push('Large number of symbols may impact performance');
} return new Response(stream);
});
// Estimate duration (simplified)
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds // Validate backtest configuration
app.post('/validate', async c => {
return c.json(validation); try {
} catch (error) { const body = await c.req.json();
if (error instanceof z.ZodError) { const config = BacktestConfigSchema.parse(body);
return c.json({
valid: false, // Additional validation logic
error: 'Invalid configuration', const validation = {
details: error.errors valid: true,
}, 400); warnings: [] as string[],
} estimatedDuration: 0,
};
return c.json({
valid: false, // Check data availability
error: error instanceof Error ? error.message : 'Validation failed' const startDate = new Date(config.startDate);
}, 500); const endDate = new Date(config.endDate);
} const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
});
if (days > 365) {
return app; validation.warnings.push('Large date range may take significant time to process');
} }
if (config.symbols.length > 100) {
validation.warnings.push('Large number of symbols may impact performance');
}
// Estimate duration (simplified)
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds
return c.json(validation);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
valid: false,
error: 'Invalid configuration',
details: error.errors,
},
400
);
}
return c.json(
{
valid: false,
error: error instanceof Error ? error.message : 'Validation failed',
},
500
);
}
});
return app;
}

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