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,
"bracketSameLine": false,
"quoteProps": "as-needed",
"plugins": ["@ianvs/prettier-plugin-sort-imports"],
"plugins": [
"@ianvs/prettier-plugin-sort-imports"
],
"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)$",
"<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
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.
```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 test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contract tests, tooling 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;
they are not suppressed or baselined. The larger existing `bun run test` suite is separate:
`check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined.
The larger existing `bun run test` suite is separate:
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
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
strategy; install it when using that strategy.
changing Rust APIs. TensorFlow is loaded only when starting the optional ML 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
@ -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
`container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`.
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
.object({
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'),
dataResolutions: z.array(z.string()).default(['1m', '5m', '15m', '1h', '1d']),
})

View file

@ -29,7 +29,8 @@
"@stock-bot/proxy": "*",
"hono": "^4.0.0",
"pako": "^2.1.0",
"cheerio": "^1.0.0"
"cheerio": "^1.0.0",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {
"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 totalChannels = results.channel_categories[0].total_channels;
const totalPages = Math.ceil(totalChannels / channels.length);
const exchanges: { exchange: string; countryCode: string }[] = [];
const symbols = channels.map((channel: any) => {
// check if exchange is in the exchanges array object
if (!exchanges.find((e: any) => e.exchange === channel.exchange)) {
exchanges.push({
const exchanges: { exchange: string; countryCode: string; source: string }[] = [];
const symbols = channels.map(
(channel: {
exchange: string;
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,
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('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}`);
return { page, totalPages };
} catch (error: any) {
} catch (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 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 proxy = this.proxy?.getProxy();
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}`);
}
const data = await response.json();
const data = (await response.json()) as {
spiels: Array<Record<string, unknown> & { timestamp: number }>;
};
const spielCount = data.spiels.length;
if (spielCount === 0) {
@ -56,7 +62,8 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
// Extract timestamps clearly
const oldestPostInBatch = data.spiels[0]?.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,
spiel: spiel.spiel,
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;
// 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) {
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
// 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`);
await this.scheduleOperation(
'get-posts',
@ -171,12 +182,12 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P
this.logger.info(`Successfully processed channel ${ceoId}`);
return { ceoId, spielCount, timestamp };
} catch (error: any) {
} catch (error) {
this.logger.error(`Failed to process individual symbol ${symbol}`, {
error,
ceoId,
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 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 proxy = this.proxy?.getProxy();
if (!proxy) {

View file

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

View file

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

View file

@ -1,233 +1,249 @@
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';
interface FetchCorporateActionsInput {
eodSearchCode: string;
actionType: 'dividends' | 'splits';
}
export async function scheduleFetchCorporateActions(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling corporate actions fetch jobs');
// 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', {
limit: 50000 // Get all symbols needing update
});
const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', {
limit: 50000 // Get all symbols needing update
});
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbolsDividends = allStaleDividends.filter(item =>
canadianExchanges.includes(item.symbol.Exchange) &&
item.symbol.delisted === false
); // Remove the slice limit to process all symbols
const staleSymbolsSplits = allStaleSplits.filter(item =>
canadianExchanges.includes(item.symbol.Exchange) &&
item.symbol.delisted === false
); // Remove the slice limit to process all symbols
if ((!staleSymbolsDividends || staleSymbolsDividends.length === 0) &&
(!staleSymbolsSplits || staleSymbolsSplits.length === 0)) {
logger.info('No symbols need corporate actions update');
return { success: true, jobsScheduled: 0 };
}
logger.info(`Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update`);
let jobsScheduled = 0;
// Schedule dividends jobs
for (let i = 0; i < staleSymbolsDividends.length; i++) {
const { symbol } = staleSymbolsDividends[i];
await this.scheduleOperation('fetch-corporate-actions', {
eodSearchCode: symbol.eodSearchCode,
actionType: 'dividends'
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000
},
delay: i * 200 // Stagger jobs by 200ms per symbol
});
jobsScheduled++;
}
// Schedule splits jobs
for (let i = 0; i < staleSymbolsSplits.length; i++) {
const { symbol } = staleSymbolsSplits[i];
await this.scheduleOperation('fetch-corporate-actions', {
eodSearchCode: symbol.eodSearchCode,
actionType: 'splits'
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000
},
delay: (i * 200) + 100 // Offset splits by 100ms from dividends
});
jobsScheduled++;
}
logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`);
return {
success: true,
jobsScheduled
};
} catch (error) {
logger.error('Failed to schedule corporate actions fetch jobs', { error });
throw error;
}
}
export async function fetchCorporateActions(
this: EodHandler,
input: FetchCorporateActionsInput
): Promise<{ success: boolean; recordsCount: number }> {
const logger = this.logger;
const { eodSearchCode, actionType } = input;
// Declare variables for catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const country = symbolDoc.Country;
logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`);
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL based on action type
// 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}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// EOD returns an array of corporate actions
if (!Array.isArray(data)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`);
// Log sample records if any
if (data.length > 0) {
logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, {
count: data.length,
samples: data.slice(0, 3).map(record => ({
date: record.date,
value: record.value || record.split || record.amount,
...record
}))
});
}
if (data.length === 0) {
// Update symbol to indicate we checked but found no data
await this.mongodb.collection('eodSymbols').updateOne(
{ eodSearchCode: eodSearchCode },
{
$set: {
[`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(),
[`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false
}
}
);
return { success: true, recordsCount: 0 };
}
// Add metadata to each record
const recordsWithMetadata = data.map(record => ({
symbol,
exchange,
eodSearchCode,
...record,
actionType,
updatedAt: new Date(),
source: 'eod'
}));
// Determine collection name based on action type
const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits';
// Save to MongoDB - use date and eodSearchCode as unique identifier
const result = await this.mongodb.batchUpsert(
collectionName,
recordsWithMetadata,
['date', 'eodSearchCode']
);
// Update operation tracker based on action type
const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update';
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, {
status: 'success',
recordCount: result.insertedCount,
metadata: {
actionType: actionType,
exchange: exchange,
hasData: result.insertedCount > 0
}
});
logger.info(`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`);
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;
}
}
import { at } from '@stock-bot/utils';
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';
interface FetchCorporateActionsInput {
eodSearchCode: string;
actionType: 'dividends' | 'splits';
}
export async function scheduleFetchCorporateActions(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling corporate actions fetch jobs');
// 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',
{
limit: 50000, // Get all symbols needing update
}
);
const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', {
limit: 50000, // Get all symbols needing update
});
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbolsDividends = allStaleDividends.filter(
item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
); // Remove the slice limit to process all symbols
const staleSymbolsSplits = allStaleSplits.filter(
item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
); // Remove the slice limit to process all symbols
if (
(!staleSymbolsDividends || staleSymbolsDividends.length === 0) &&
(!staleSymbolsSplits || staleSymbolsSplits.length === 0)
) {
logger.info('No symbols need corporate actions update');
return { success: true, jobsScheduled: 0 };
}
logger.info(
`Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update`
);
let jobsScheduled = 0;
// Schedule dividends jobs
for (let i = 0; i < staleSymbolsDividends.length; i++) {
const { symbol } = at(staleSymbolsDividends, i);
await this.scheduleOperation(
'fetch-corporate-actions',
{
eodSearchCode: symbol.eodSearchCode,
actionType: 'dividends',
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000,
},
delay: i * 200, // Stagger jobs by 200ms per symbol
}
);
jobsScheduled++;
}
// Schedule splits jobs
for (let i = 0; i < staleSymbolsSplits.length; i++) {
const { symbol } = at(staleSymbolsSplits, i);
await this.scheduleOperation(
'fetch-corporate-actions',
{
eodSearchCode: symbol.eodSearchCode,
actionType: 'splits',
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000,
},
delay: i * 200 + 100, // Offset splits by 100ms from dividends
}
);
jobsScheduled++;
}
logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`);
return {
success: true,
jobsScheduled,
};
} catch (error) {
logger.error('Failed to schedule corporate actions fetch jobs', { error });
throw error;
}
}
export async function fetchCorporateActions(
this: EodHandler,
input: FetchCorporateActionsInput
): Promise<{ success: boolean; recordsCount: number }> {
const logger = this.logger;
const { eodSearchCode, actionType } = input;
// Declare variables for catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode,
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const _country = symbolDoc.Country;
logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`);
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL based on action type
// 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}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// EOD returns an array of corporate actions
if (!Array.isArray(data)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`);
// Log sample records if any
if (data.length > 0) {
logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, {
count: data.length,
samples: data.slice(0, 3).map(record => ({
date: record.date,
value: record.value || record.split || record.amount,
...record,
})),
});
}
if (data.length === 0) {
// Update symbol to indicate we checked but found no data
await this.mongodb.collection('eodSymbols').updateOne(
{ eodSearchCode: eodSearchCode },
{
$set: {
[`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(),
[`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false,
},
}
);
return { success: true, recordsCount: 0 };
}
// Add metadata to each record
const recordsWithMetadata = data.map(record => ({
symbol,
exchange,
eodSearchCode,
...record,
actionType,
updatedAt: new Date(),
source: 'eod',
}));
// Determine collection name based on action type
const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits';
// Save to MongoDB - use date and eodSearchCode as unique identifier
const result = await this.mongodb.batchUpsert(collectionName, recordsWithMetadata, [
'date',
'eodSearchCode',
]);
// Update operation tracker based on action type
const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update';
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, {
status: 'success',
recordCount: result.insertedCount,
metadata: {
actionType: actionType,
exchange: exchange,
hasData: result.insertedCount > 0,
},
});
logger.info(
`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`
);
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 { EOD_CONFIG } from '../shared';
interface BulkFundamentalsInput {
eodSearchCodes: string[];
}
interface FetchSingleFundamentalsInput {
eodSearchCode: string;
}
export async function scheduleFetchFundamentals(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling fundamentals fetch jobs');
// Get Canadian exchanges for now
const canadianExchanges = ['TO', 'V', 'CN', 'NEO'];
// Use OperationTracker to find stale symbols
const allStaleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'fundamentals_update', {
limit: 50000 // Get all symbols needing update
});
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbols = allStaleSymbols.filter(item =>
canadianExchanges.includes(item.symbol.Exchange) &&
item.symbol.delisted === false
); // Remove the slice limit to process all symbols
if (!staleSymbols || staleSymbols.length === 0) {
logger.info('No symbols need fundamentals update');
return { success: true, jobsScheduled: 0 };
}
logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`);
// Separate ETFs from regular stocks
const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF');
const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF');
logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, {
etfSamples: etfs.slice(0, 5).map(e => ({
symbol: e.symbol.Code,
exchange: e.symbol.Exchange,
name: e.symbol.Name
})),
nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({
symbol: s.symbol.Code,
exchange: s.symbol.Exchange,
name: s.symbol.Name,
type: s.symbol.Type
}))
});
let jobsScheduled = 0;
// Schedule individual jobs for ETFs
for (let i = 0; i < etfs.length; i++) {
const { symbol: etf } = etfs[i];
await this.scheduleOperation('fetch-single-fundamentals', {
eodSearchCode: etf.eodSearchCode
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 10000
},
delay: jobsScheduled * 1000 // Stagger by 1 second
});
jobsScheduled++;
}
if (etfs.length > 0) {
logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`);
}
// Create batches of 500 symbols for non-ETFs
const batchSize = 500; // EOD allows up to 500 symbols per bulk request
for (let i = 0; i < nonEtfs.length; i += batchSize) {
const batch = nonEtfs.slice(i, i + batchSize);
// Convert to array of eodSearchCodes
const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode);
await this.scheduleOperation('fetch-bulk-fundamentals', {
eodSearchCodes: eodSearchCodes
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 10000
},
delay: jobsScheduled * 5000 // Stagger batches by 5 seconds
});
jobsScheduled++;
logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`);
}
logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`);
return {
success: true,
jobsScheduled
};
} catch (error) {
logger.error('Failed to schedule fundamentals fetch jobs', { error });
throw error;
}
}
export async function fetchBulkFundamentals(
this: EodHandler,
input: BulkFundamentalsInput
): Promise<{ success: boolean; symbolsProcessed: number }> {
const logger = this.logger;
const { eodSearchCodes } = input;
try {
logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length });
// Lookup all symbols
const symbolDocs = await this.mongodb.collection('eodSymbols').find({
eodSearchCode: { $in: eodSearchCodes }
}).toArray();
if (symbolDocs.length === 0) {
logger.error('No symbols found for provided eodSearchCodes');
return { success: true, symbolsProcessed: 0 };
}
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Group symbols by actual exchange for API endpoint
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
const exchangeGroups = symbolDocs.reduce((acc, symbolDoc) => {
const exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const eodSearchCode = symbolDoc.eodSearchCode;
if (!acc[exchange]) {
acc[exchange] = [];
}
// eodSearchCode already has the correct format (e.g., AAPL.US)
acc[exchange].push(eodSearchCode);
return acc;
}, {} as Record<string, string[]>);
let totalProcessed = 0;
// Process each exchange group
for (const [exchange, symbolList] of Object.entries(exchangeGroups)) {
// Build URL - using the exchange as the endpoint
const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
url.searchParams.append('symbols', symbolList.join(','));
logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, {
exchange,
count: symbolList.length,
samples: symbolList.slice(0, 5)
});
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// 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');
}
// Process each symbol's fundamentals
const fundamentalsToSave = [];
const symbolsToUpdate = [];
for (const [symbolExchange, fundamentals] of Object.entries(data)) {
if (!fundamentals || typeof fundamentals !== 'object') {
logger.warn(`No fundamentals data for ${symbolExchange}`);
continue;
}
// Extract symbol and exchange from the key
const [symbol, exchangeSuffix] = symbolExchange.split('.');
// Find the original symbol doc to get the actual exchange code
const symbolDoc = symbolDocs.find(doc =>
doc.Code === symbol &&
(doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix)
);
if (!symbolDoc) {
logger.warn(`Could not find symbol doc for ${symbolExchange}`);
continue;
}
const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const eodSearchCode = symbolDoc.eodSearchCode;
// Add metadata
const fundamentalsWithMetadata = {
symbol,
exchange: actualExchange,
eodSearchCode,
...fundamentals,
updatedAt: new Date(),
source: 'eod'
};
fundamentalsToSave.push(fundamentalsWithMetadata);
symbolsToUpdate.push({ eodSearchCode });
}
if (fundamentalsToSave.length > 0) {
// Save fundamentals to MongoDB
const result = await this.mongodb.batchUpsert(
'eodFundamentals',
fundamentalsToSave,
['eodSearchCode']
);
logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`);
// Update operation tracker for each symbol
const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => {
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'success',
recordCount: 1,
metadata: {
hasData: true,
exchange: exchange
}
});
});
await Promise.all(updatePromises);
totalProcessed += fundamentalsToSave.length;
}
}
logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`);
return {
success: true,
symbolsProcessed: totalProcessed
};
} catch (error) {
logger.error('Failed to fetch bulk fundamentals', { error });
// Mark all symbols as failed
const failPromises = eodSearchCodes.map((eodSearchCode) => {
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'failure',
error: error.message
});
});
await Promise.all(failPromises);
throw error;
}
}
export async function fetchSingleFundamentals(
this: EodHandler,
input: FetchSingleFundamentalsInput
): Promise<{ success: boolean; saved: boolean }> {
const logger = this.logger;
const { eodSearchCode } = input;
// Declare variables for catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const country = symbolDoc.Country;
logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`);
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL for single fundamentals endpoint
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`);
}
const fundamentals = await response.json();
// Check if we got valid data
if (!fundamentals || typeof fundamentals !== 'object') {
logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`);
return { success: true, saved: false };
}
// Add metadata
const fundamentalsWithMetadata = {
symbol,
exchange,
eodSearchCode,
...fundamentals,
updatedAt: new Date(),
source: 'eod'
};
// Save to MongoDB
const result = await this.mongodb.batchUpsert(
'eodFundamentals',
[fundamentalsWithMetadata],
['eodSearchCode']
);
// 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.message
});
throw error;
}
}
import { at } from '@stock-bot/utils';
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';
interface BulkFundamentalsInput {
eodSearchCodes: string[];
}
interface FetchSingleFundamentalsInput {
eodSearchCode: string;
}
export async function scheduleFetchFundamentals(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
try {
logger.info('Scheduling fundamentals fetch jobs');
// Get Canadian exchanges for now
const canadianExchanges = ['TO', 'V', 'CN', 'NEO'];
// Use OperationTracker to find stale symbols
const allStaleSymbols = await this.operationRegistry.getStaleSymbols(
'eod',
'fundamentals_update',
{
limit: 50000, // Get all symbols needing update
}
);
// Filter for Canadian exchanges and non-delisted symbols
const staleSymbols = allStaleSymbols.filter(
item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false
); // Remove the slice limit to process all symbols
if (!staleSymbols || staleSymbols.length === 0) {
logger.info('No symbols need fundamentals update');
return { success: true, jobsScheduled: 0 };
}
logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`);
// Separate ETFs from regular stocks
const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF');
const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF');
logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, {
etfSamples: etfs.slice(0, 5).map(e => ({
symbol: e.symbol.Code,
exchange: e.symbol.Exchange,
name: e.symbol.Name,
})),
nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({
symbol: s.symbol.Code,
exchange: s.symbol.Exchange,
name: s.symbol.Name,
type: s.symbol.Type,
})),
});
let jobsScheduled = 0;
// Schedule individual jobs for ETFs
for (let i = 0; i < etfs.length; i++) {
const { symbol: etf } = at(etfs, i);
await this.scheduleOperation(
'fetch-single-fundamentals',
{
eodSearchCode: etf.eodSearchCode,
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 10000,
},
delay: jobsScheduled * 1000, // Stagger by 1 second
}
);
jobsScheduled++;
}
if (etfs.length > 0) {
logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`);
}
// Create batches of 500 symbols for non-ETFs
const batchSize = 500; // EOD allows up to 500 symbols per bulk request
for (let i = 0; i < nonEtfs.length; i += batchSize) {
const batch = nonEtfs.slice(i, i + batchSize);
// Convert to array of eodSearchCodes
const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode);
await this.scheduleOperation(
'fetch-bulk-fundamentals',
{
eodSearchCodes: eodSearchCodes,
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 10000,
},
delay: jobsScheduled * 5000, // Stagger batches by 5 seconds
}
);
jobsScheduled++;
logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`);
}
logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`);
return {
success: true,
jobsScheduled,
};
} catch (error) {
logger.error('Failed to schedule fundamentals fetch jobs', { error });
throw error;
}
}
export async function fetchBulkFundamentals(
this: EodHandler,
input: BulkFundamentalsInput
): Promise<{ success: boolean; symbolsProcessed: number }> {
const logger = this.logger;
const { eodSearchCodes } = input;
try {
logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length });
// Lookup all symbols
const symbolDocs = await this.mongodb
.collection('eodSymbols')
.find({
eodSearchCode: { $in: eodSearchCodes },
})
.toArray();
if (symbolDocs.length === 0) {
logger.error('No symbols found for provided eodSearchCodes');
return { success: true, symbolsProcessed: 0 };
}
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Group symbols by actual exchange for API endpoint
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
const exchangeGroups = symbolDocs.reduce(
(acc, symbolDoc) => {
const exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const eodSearchCode = symbolDoc.eodSearchCode;
if (!acc[exchange]) {
acc[exchange] = [];
}
// eodSearchCode already has the correct format (e.g., AAPL.US)
acc[exchange].push(eodSearchCode);
return acc;
},
{} as Record<string, string[]>
);
let totalProcessed = 0;
// Process each exchange group
for (const [exchange, symbolList] of Object.entries(exchangeGroups)) {
// Build URL - using the exchange as the endpoint
const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
url.searchParams.append('symbols', symbolList.join(','));
logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, {
exchange,
count: symbolList.length,
samples: symbolList.slice(0, 5),
});
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(
`EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`
);
}
const data = await response.json();
// 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');
}
// Process each symbol's fundamentals
const fundamentalsToSave = [];
const symbolsToUpdate = [];
for (const [symbolExchange, fundamentals] of Object.entries(data)) {
if (!fundamentals || typeof fundamentals !== 'object') {
logger.warn(`No fundamentals data for ${symbolExchange}`);
continue;
}
// Extract symbol and exchange from the key
const [symbol, exchangeSuffix] = symbolExchange.split('.');
// Find the original symbol doc to get the actual exchange code
const symbolDoc = symbolDocs.find(
doc =>
doc.Code === symbol &&
(doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix)
);
if (!symbolDoc) {
logger.warn(`Could not find symbol doc for ${symbolExchange}`);
continue;
}
const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const eodSearchCode = symbolDoc.eodSearchCode;
// Add metadata
const fundamentalsWithMetadata = {
symbol,
exchange: actualExchange,
eodSearchCode,
...fundamentals,
updatedAt: new Date(),
source: 'eod',
};
fundamentalsToSave.push(fundamentalsWithMetadata);
symbolsToUpdate.push({ eodSearchCode });
}
if (fundamentalsToSave.length > 0) {
// Save fundamentals to MongoDB
const result = await this.mongodb.batchUpsert('eodFundamentals', fundamentalsToSave, [
'eodSearchCode',
]);
logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`);
// Update operation tracker for each symbol
const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => {
return this.operationRegistry.updateOperation(
'eod',
eodSearchCode,
'fundamentals_update',
{
status: 'success',
recordCount: 1,
metadata: {
hasData: true,
exchange: exchange,
},
}
);
});
await Promise.all(updatePromises);
totalProcessed += fundamentalsToSave.length;
}
}
logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`);
return {
success: true,
symbolsProcessed: totalProcessed,
};
} catch (error) {
logger.error('Failed to fetch bulk fundamentals', { error });
// Mark all symbols as failed
const failPromises = eodSearchCodes.map(eodSearchCode => {
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
status: 'failure',
error: error instanceof Error ? error.message : String(error),
});
});
await Promise.all(failPromises);
throw error;
}
}
export async function fetchSingleFundamentals(
this: EodHandler,
input: FetchSingleFundamentalsInput
): Promise<{ success: boolean; saved: boolean }> {
const logger = this.logger;
const { eodSearchCode } = input;
// Declare variables for catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode,
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
const _country = symbolDoc.Country;
logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`);
// Get API key
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL for single fundamentals endpoint
// eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US)
const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch data
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(
`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`
);
}
const fundamentals = await response.json();
// Check if we got valid data
if (!fundamentals || typeof fundamentals !== 'object') {
logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`);
return { success: true, saved: false };
}
// Add metadata
const fundamentalsWithMetadata = {
symbol,
exchange,
eodSearchCode,
...fundamentals,
updatedAt: new Date(),
source: 'eod',
};
// Save to MongoDB
const result = await this.mongodb.batchUpsert(
'eodFundamentals',
[fundamentalsWithMetadata],
['eodSearchCode']
);
// 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 { EOD_CONFIG } from '../shared';
interface FetchPricesInput {
eodSearchCode: string;
}
export async function scheduleFetchPrices(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
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', {
limit: 100000 // Higher limit to process all symbols
});
if (!staleSymbols || staleSymbols.length === 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 => ({
symbol: s.symbol.Code,
exchange: s.symbol.Exchange,
name: s.symbol.Name,
lastUpdate: s.lastRun
}))
});
let jobsScheduled = 0;
// Schedule jobs with staggered delays
for (let i = 0; i < staleSymbols.length; i++) {
const staleSymbol = staleSymbols[i];
if (!staleSymbol || !staleSymbol.symbol) {
logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol });
continue;
}
const { symbol } = staleSymbol;
const jobId = `fetch-prices-${symbol.eodSearchCode}`;
logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, {
name: symbol.Name,
lastUpdate: staleSymbol.lastRun,
delay: i * 100,
jobId
});
try {
await this.scheduleOperation('fetch-prices', {
eodSearchCode: symbol.eodSearchCode
}, {
jobId,
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000
},
delay: i * 100 // Stagger jobs by 100ms per symbol to avoid rate limit spikes
});
jobsScheduled++;
} catch (error: any) {
if (error?.message?.includes('Job already exists')) {
logger.debug(`Job already exists: ${jobId}`);
} else {
throw error;
}
}
}
logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`);
return {
success: true,
jobsScheduled
};
} catch (error) {
logger.error('Failed to schedule price fetch jobs', { error });
throw error;
}
}
export async function fetchPrices(
this: EodHandler,
input: FetchPricesInput
): Promise<{ success: boolean; priceCount: number }> {
const logger = this.logger;
const { eodSearchCode } = input;
// Declare variables that need to be accessible in catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.Exchange;
logger.info(`Fetching prices for ${eodSearchCode}`);
// Get API key from config
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch price data from EOD API
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`);
}
const priceData = await response.json();
// EOD returns an array of historical prices
if (!Array.isArray(priceData)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`);
// Log date range of prices
if (priceData.length > 0) {
logger.debug(`Price data range for ${eodSearchCode}:`, {
oldest: priceData[0].date,
newest: priceData[priceData.length - 1].date,
count: priceData.length
});
}
// Add metadata to each price record
const pricesWithMetadata = priceData.map(price => ({
symbol,
exchange,
eodSearchCode,
date: price.date,
open: price.open,
high: price.high,
low: price.low,
close: price.close,
adjustedClose: price.adjusted_close,
volume: price.volume,
}));
// Save to MongoDB - use date and eodSearchCode as unique identifier
const result = await this.mongodb.batchUpsert(
'eodPrices',
pricesWithMetadata,
['date', 'eodSearchCode']
);
// Update operation tracker instead of directly updating the symbol
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
status: 'success',
lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null,
recordCount: priceData.length,
metadata: {
insertedCount: result.insertedCount,
updatedCount: priceData.length - result.insertedCount
}
});
logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`);
return {
success: true,
priceCount: result.insertedCount
};
} 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;
}
}
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';
import { persistEodPrices } from '../shared/price-storage';
interface FetchPricesInput {
eodSearchCode: string;
}
export async function scheduleFetchPrices(
this: EodHandler
): Promise<{ success: boolean; jobsScheduled: number }> {
const logger = this.logger;
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', {
limit: 100000, // Higher limit to process all symbols
});
if (!staleSymbols || staleSymbols.length === 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 => ({
symbol: s.symbol.Code,
exchange: s.symbol.Exchange,
name: s.symbol.Name,
lastUpdate: s.lastRun,
})),
});
let jobsScheduled = 0;
// Schedule jobs with staggered delays
for (let i = 0; i < staleSymbols.length; i++) {
const staleSymbol = staleSymbols[i];
if (!staleSymbol || !staleSymbol.symbol) {
logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol });
continue;
}
const { symbol } = staleSymbol;
const jobId = `fetch-prices-${symbol.eodSearchCode}`;
logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, {
name: symbol.Name,
lastUpdate: staleSymbol.lastRun,
delay: i * 100,
jobId,
});
try {
await this.scheduleOperation(
'fetch-prices',
{
eodSearchCode: symbol.eodSearchCode,
},
{
jobId,
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000,
},
delay: i * 100, // Stagger jobs by 100ms per symbol to avoid rate limit spikes
}
);
jobsScheduled++;
} catch (error) {
if (error instanceof Error && error.message.includes('Job already exists')) {
logger.debug(`Job already exists: ${jobId}`);
} else {
throw error;
}
}
}
logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`);
return {
success: true,
jobsScheduled,
};
} catch (error) {
logger.error('Failed to schedule price fetch jobs', { error });
throw error;
}
}
export async function fetchPrices(
this: EodHandler,
input: FetchPricesInput
): Promise<{ success: boolean; priceCount: number }> {
const logger = this.logger;
const { eodSearchCode } = input;
// Declare variables that need to be accessible in catch block
let symbol: string = '';
let exchange: string = '';
try {
// Lookup symbol using eodSearchCode
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
eodSearchCode: eodSearchCode,
});
if (!symbolDoc) {
logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`);
throw new Error(`Symbol not found: ${eodSearchCode}`);
}
symbol = symbolDoc.Code;
exchange = symbolDoc.Exchange;
logger.info(`Fetching prices for ${eodSearchCode}`);
// Get API key from config
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
// Fetch price data from EOD API
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`);
}
const priceData = await response.json();
// EOD returns an array of historical prices
if (!Array.isArray(priceData)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`);
// Log date range of prices
if (priceData.length > 0) {
logger.debug(`Price data range for ${eodSearchCode}:`, {
oldest: priceData[0].date,
newest: priceData[priceData.length - 1].date,
count: priceData.length,
});
}
const result = await persistEodPrices(
this.mongodb,
{ symbol, exchange, eodSearchCode },
priceData
);
// Update operation tracker instead of directly updating the symbol
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
status: 'success',
lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null,
recordCount: priceData.length,
metadata: {
insertedCount: result.insertedCount,
updatedCount: priceData.length - result.insertedCount,
},
});
logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`);
return {
success: true,
priceCount: result.insertedCount,
};
} 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 { DataIngestionServices } from '../../../types';
import { EOD_CONFIG } from '../shared';
interface FetchSymbolsInput {
exchangeCode: string;
delisted: boolean;
}
export async function scheduleFetchSymbols(
this: BaseHandler<DataIngestionServices>
): Promise<{ success: boolean; jobsCreated: number }> {
const logger = this.logger;
try {
logger.info('Starting symbol fetch job scheduling');
// Get all exchanges from MongoDB
const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray();
if (!exchanges || exchanges.length === 0) {
logger.warn('No exchanges found in database - run fetch-exchanges first');
return { success: true, jobsCreated: 0 };
}
logger.info(`Found ${exchanges.length} exchanges to process`, {
exchanges: exchanges.map((e: any) => ({ code: e.Code, name: e.Name, country: e.Country }))
});
let jobsCreated = 0;
// Create jobs for each exchange - both active and delisted symbols
for (const exchange of exchanges) {
const exchangeCode = exchange.Code;
// Job for active symbols
await this.scheduleOperation('fetch-symbols', {
exchangeCode,
delisted: false
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000
}
});
jobsCreated++;
// Job for delisted symbols
await this.scheduleOperation('fetch-symbols', {
exchangeCode,
delisted: true
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000
}
});
jobsCreated++;
}
logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`);
return {
success: true,
jobsCreated
};
} catch (error) {
logger.error('Failed to schedule symbol fetch jobs', { error });
throw error;
}
}
export async function fetchSymbols(
this: BaseHandler<DataIngestionServices>,
input: FetchSymbolsInput
): Promise<{ success: boolean; count: number }> {
const logger = this.logger;
const { exchangeCode, delisted } = input;
try {
logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
// Get API key from config
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL with query parameters
const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
if (delisted) {
url.searchParams.append('delisted', '1');
}
// Fetch symbols from EOD API using Bun fetch
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`);
}
const symbols = await response.json();
if (!Array.isArray(symbols)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
// Log some sample symbols
if (symbols.length > 0) {
logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, {
count: symbols.length,
samples: symbols.slice(0, 5).map(s => ({
symbol: s.Code,
name: s.Name,
type: s.Type
}))
});
}
// Add metadata to each symbol
const symbolsWithMetadata = symbols.map(symbol => ({
...symbol,
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,
}));
// Save to MongoDB - use Code as unique identifier along with exchange
const result = await this.mongodb.batchUpsert(
'eodSymbols',
symbolsWithMetadata,
['eodSearchCode']
);
logger.info(`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;
}
}
import type { BaseHandler } from '@stock-bot/handlers';
import type { DataIngestionServices } from '../../../types';
import { EOD_CONFIG } from '../shared';
interface FetchSymbolsInput {
exchangeCode: string;
delisted: boolean;
}
export async function scheduleFetchSymbols(
this: BaseHandler<DataIngestionServices>
): Promise<{ success: boolean; jobsCreated: number }> {
const logger = this.logger;
try {
logger.info('Starting symbol fetch job scheduling');
// Get all exchanges from MongoDB
const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray();
if (!exchanges || exchanges.length === 0) {
logger.warn('No exchanges found in database - run fetch-exchanges first');
return { success: true, jobsCreated: 0 };
}
logger.info(`Found ${exchanges.length} exchanges to process`, {
exchanges: exchanges.map(e => ({ code: e.Code, name: e.Name, country: e.Country })),
});
let jobsCreated = 0;
// Create jobs for each exchange - both active and delisted symbols
for (const exchange of exchanges) {
const exchangeCode = exchange.Code;
// Job for active symbols
await this.scheduleOperation(
'fetch-symbols',
{
exchangeCode,
delisted: false,
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000,
},
}
);
jobsCreated++;
// Job for delisted symbols
await this.scheduleOperation(
'fetch-symbols',
{
exchangeCode,
delisted: true,
},
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 5000,
},
}
);
jobsCreated++;
}
logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`);
return {
success: true,
jobsCreated,
};
} catch (error) {
logger.error('Failed to schedule symbol fetch jobs', { error });
throw error;
}
}
export async function fetchSymbols(
this: BaseHandler<DataIngestionServices>,
input: FetchSymbolsInput
): Promise<{ success: boolean; count: number }> {
const logger = this.logger;
const { exchangeCode, delisted } = input;
try {
logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
// Get API key from config
const apiKey = EOD_CONFIG.API_TOKEN;
if (!apiKey) {
throw new Error('EOD API key not configured');
}
// Build URL with query parameters
const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`);
url.searchParams.append('api_token', apiKey);
url.searchParams.append('fmt', 'json');
if (delisted) {
url.searchParams.append('delisted', '1');
}
// Fetch symbols from EOD API using Bun fetch
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`);
}
const symbols = await response.json();
if (!Array.isArray(symbols)) {
throw new Error('Invalid response format from EOD API - expected array');
}
logger.info(
`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`
);
// Log some sample symbols
if (symbols.length > 0) {
logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, {
count: symbols.length,
samples: symbols.slice(0, 5).map(s => ({
symbol: s.Code,
name: s.Name,
type: s.Type,
})),
});
}
// Add metadata to each symbol
const symbolsWithMetadata = symbols.map(symbol => ({
...symbol,
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,
}));
// Save to MongoDB - use Code as unique identifier along with exchange
const result = await this.mongodb.batchUpsert('eodSymbols', symbolsWithMetadata, [
'eodSearchCode',
]);
logger.info(
`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 {
BaseHandler,
Disabled,
Handler,
Operation,
RateLimit,
ScheduledOperation
} from '@stock-bot/handlers';
import type { OperationRegistry } from '../../shared/operation-manager';
import type { DataIngestionServices } from '../../types';
import {
crawlIntraday,
fetchBulkFundamentals,
fetchCorporateActions,
fetchExchanges,
fetchIntraday,
fetchPrices,
fetchSingleFundamentals,
fetchSymbolChangeHistory,
fetchSymbols,
scheduleFetchCorporateActions,
scheduleFetchFundamentals,
scheduleFetchPrices,
scheduleFetchSymbols,
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
* Operations can specify just a cost to use handler limits, or override with custom limits
*/
@Handler('eod')
@Disabled()
@RateLimit({
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;
constructor(services: any) {
super(services);
// Use pre-initialized registry if available, otherwise create new one
if ((EodHandler as any).operationRegistry) {
this.operationRegistry = (EodHandler as any).operationRegistry;
this.logger.info('Using pre-initialized EOD operation registry');
} else {
// Fallback: Initialize operation registry with EOD provider
createEODOperationRegistry(this.mongodb, this.logger)
.then(registry => {
this.operationRegistry = registry;
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')
@ScheduledOperation('fetch-exchanges', '0 0 * * 0')
@RateLimit(1) // 1 point per call
fetchExchanges = fetchExchanges;
/**
* Schedule symbol fetching for all exchanges
* Runs daily at 1 AM
*/
@Operation('schedule-fetch-symbols')
@ScheduledOperation('schedule-fetch-symbols', '0 1 * * *')
@RateLimit(1) // 1 point for scheduling
scheduleFetchSymbols = scheduleFetchSymbols;
/**
* Fetch symbols for a specific exchange
* Called by schedule-fetch-symbols for each exchange
*/
@Operation('fetch-symbols')
@RateLimit(1) // 1 point per exchange
fetchSymbols = fetchSymbols;
/**
* Schedule price fetching for all symbols not updated in last week
* Runs daily at 2 AM
*/
@Operation('schedule-fetch-prices')
@ScheduledOperation('schedule-fetch-prices', '0 2 * * *')
@RateLimit(1) // 1 point for scheduling
scheduleFetchPrices = scheduleFetchPrices;
/**
* Fetch historical prices for a specific symbol
* Called by schedule-fetch-prices for each symbol
*/
@Operation('fetch-prices')
@RateLimit(1) // 1 point per price fetch
fetchPrices = fetchPrices;
/**
* Schedule intraday crawl for symbols needing intraday data
* Runs daily at 3 AM
*/
@Operation('schedule-intraday-crawl')
@ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', {
immediately: true,
})
@RateLimit(1) // 1 point for scheduling
scheduleIntradayCrawl = scheduleIntradayCrawl;
/**
* Crawl intraday data for a specific symbol and interval
* Handles resumption and batch processing
*/
@Operation('crawl-intraday')
@RateLimit(5) // 5 points per crawl batch
crawlIntraday = crawlIntraday;
/**
* Fetch intraday data for a specific date range
* Called by crawl-intraday
*/
@Operation('fetch-intraday')
@RateLimit(5) // 5 points per intraday fetch
fetchIntraday = fetchIntraday;
/**
* Schedule bulk fundamentals fetch for symbols
* DISABLED - Not scheduled automatically
*/
@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
scheduleFetchFundamentals = scheduleFetchFundamentals;
/**
* Fetch fundamentals for up to 500 symbols in bulk
* Called by schedule-fetch-fundamentals for non-ETFs
*/
@Operation('fetch-bulk-fundamentals')
@RateLimit(600) // 100 base + up to 500 symbols = 600 points max
fetchBulkFundamentals = fetchBulkFundamentals;
/**
* Fetch fundamentals for a single symbol
* Called by schedule-fetch-fundamentals for ETFs
*/
@Operation('fetch-single-fundamentals')
@RateLimit(10) // 10 points per single fundamentals fetch
fetchSingleFundamentals = fetchSingleFundamentals;
/**
* Fetch symbol change history
* Runs weekly on Mondays at 5 AM
*/
@Operation('fetch-symbol-change-history')
@ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1')
@RateLimit(5) // 5 points per request
fetchSymbolChangeHistory = fetchSymbolChangeHistory;
/**
* Schedule corporate actions (dividends and splits) fetch
* DISABLED - Corporate actions likely come with fundamentals
*/
@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
scheduleFetchCorporateActions = scheduleFetchCorporateActions;
/**
* Fetch dividends or splits for a specific symbol
* Called by schedule-fetch-corporate-actions
*/
@Operation('fetch-corporate-actions')
@RateLimit(10) // 10 points per fetch
fetchCorporateActions = fetchCorporateActions;
}
import {
BaseHandler,
Disabled,
Handler,
Operation,
RateLimit,
ScheduledOperation,
} from '@stock-bot/handlers';
import type { IServiceContainer } from '@stock-bot/services';
import type { OperationRegistry } from '../../shared/operation-manager';
import { resolveIngestionServices } from '../../types';
import type { DataIngestionServices } from '../../types';
import {
crawlIntraday,
fetchBulkFundamentals,
fetchCorporateActions,
fetchExchanges,
fetchIntraday,
fetchPrices,
fetchSingleFundamentals,
fetchSymbolChangeHistory,
fetchSymbols,
scheduleFetchCorporateActions,
scheduleFetchFundamentals,
scheduleFetchPrices,
scheduleFetchSymbols,
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
* Operations can specify just a cost to use handler limits, or override with custom limits
*/
@Handler('eod')
@Disabled()
@RateLimit({
limits: [
{ points: 900, duration: 60 }, // 1000 points per minute
{ points: 100500, duration: 86400 }, // 100,500 points per day
],
})
export class EodHandler extends BaseHandler<DataIngestionServices> {
static operationRegistry?: OperationRegistry;
public operationRegistry!: OperationRegistry;
constructor(services: IServiceContainer) {
super(resolveIngestionServices(services, 'eod'));
// Use pre-initialized registry if available, otherwise create new one
if (EodHandler.operationRegistry) {
this.operationRegistry = EodHandler.operationRegistry;
this.logger.info('Using pre-initialized EOD operation registry');
} else {
// Fallback: Initialize operation registry with EOD provider
createEODOperationRegistry(this.mongodb, this.logger)
.then(registry => {
this.operationRegistry = registry;
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')
@ScheduledOperation('fetch-exchanges', '0 0 * * 0')
@RateLimit(1) // 1 point per call
fetchExchanges = fetchExchanges;
/**
* Schedule symbol fetching for all exchanges
* Runs daily at 1 AM
*/
@Operation('schedule-fetch-symbols')
@ScheduledOperation('schedule-fetch-symbols', '0 1 * * *')
@RateLimit(1) // 1 point for scheduling
scheduleFetchSymbols = scheduleFetchSymbols;
/**
* Fetch symbols for a specific exchange
* Called by schedule-fetch-symbols for each exchange
*/
@Operation('fetch-symbols')
@RateLimit(1) // 1 point per exchange
fetchSymbols = fetchSymbols;
/**
* Schedule price fetching for all symbols not updated in last week
* Runs daily at 2 AM
*/
@Operation('schedule-fetch-prices')
@ScheduledOperation('schedule-fetch-prices', '0 2 * * *')
@RateLimit(1) // 1 point for scheduling
scheduleFetchPrices = scheduleFetchPrices;
/**
* Fetch historical prices for a specific symbol
* Called by schedule-fetch-prices for each symbol
*/
@Operation('fetch-prices')
@RateLimit(1) // 1 point per price fetch
fetchPrices = fetchPrices;
/**
* Schedule intraday crawl for symbols needing intraday data
* Runs daily at 3 AM
*/
@Operation('schedule-intraday-crawl')
@ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', {
immediately: true,
})
@RateLimit(1) // 1 point for scheduling
scheduleIntradayCrawl = scheduleIntradayCrawl;
/**
* Crawl intraday data for a specific symbol and interval
* Handles resumption and batch processing
*/
@Operation('crawl-intraday')
@RateLimit(5) // 5 points per crawl batch
crawlIntraday = crawlIntraday;
/**
* Fetch intraday data for a specific date range
* Called by crawl-intraday
*/
@Operation('fetch-intraday')
@RateLimit(5) // 5 points per intraday fetch
fetchIntraday = fetchIntraday;
/**
* Schedule bulk fundamentals fetch for symbols
* DISABLED - Not scheduled automatically
*/
@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
scheduleFetchFundamentals = scheduleFetchFundamentals;
/**
* Fetch fundamentals for up to 500 symbols in bulk
* Called by schedule-fetch-fundamentals for non-ETFs
*/
@Operation('fetch-bulk-fundamentals')
@RateLimit(600) // 100 base + up to 500 symbols = 600 points max
fetchBulkFundamentals = fetchBulkFundamentals;
/**
* Fetch fundamentals for a single symbol
* Called by schedule-fetch-fundamentals for ETFs
*/
@Operation('fetch-single-fundamentals')
@RateLimit(10) // 10 points per single fundamentals fetch
fetchSingleFundamentals = fetchSingleFundamentals;
/**
* Fetch symbol change history
* Runs weekly on Mondays at 5 AM
*/
@Operation('fetch-symbol-change-history')
@ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1')
@RateLimit(5) // 5 points per request
fetchSymbolChangeHistory = fetchSymbolChangeHistory;
/**
* Schedule corporate actions (dividends and splits) fetch
* DISABLED - Corporate actions likely come with fundamentals
*/
@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
scheduleFetchCorporateActions = scheduleFetchCorporateActions;
/**
* Fetch dividends or splits for a specific symbol
* Called by schedule-fetch-corporate-actions
*/
@Operation('fetch-corporate-actions')
@RateLimit(10) // 10 points per fetch
fetchCorporateActions = fetchCorporateActions;
}

View file

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

View file

@ -1,4 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { requireServices } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config';
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...', {
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', {
totalSymbols: symbols.length,
});

View file

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

View file

@ -1,3 +1,4 @@
import type { HandlerInitializationContext } from '@stock-bot/di';
/**
* Handler initialization for data-ingestion service
* Uses explicit imports for bundling compatibility
@ -5,74 +6,88 @@
import { getLogger } from '@stock-bot/logger';
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)
// These imports trigger the decorator metadata to be set
import { CeoHandler } from './ceo/ceo.handler';
import { EodHandler } from './eod/eod.handler';
import { createEODOperationRegistry } from './eod/shared';
import { IbHandler } from './ib/ib.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 { 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
const logger = getLogger('handler-init');
// Global operation registries that handlers will reference
let eodOperationRegistry: any;
let qmOperationRegistry: any;
let eodOperationRegistry: OperationRegistry | undefined;
let qmOperationRegistry: OperationRegistry | undefined;
/**
* Initialize and register all handlers
* 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
*/
export async function initializeAllHandlers(serviceContainer: IServiceContainer): Promise<void> {
export async function initializeAllHandlers(
serviceContainer: IServiceContainer,
context: HandlerInitializationContext
): Promise<void> {
try {
// Initialize operation registries first
logger.info('Initializing operation registries');
const mongodb = serviceContainer.mongodb;
const operationLogger = serviceContainer.logger;
// Create operation registries
try {
eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger);
logger.info('EOD operation registry created');
// Attach to handler class so instances can access it
(EodHandler as any).operationRegistry = eodOperationRegistry;
EodHandler.operationRegistry = eodOperationRegistry;
} catch (error) {
logger.error('Failed to create EOD operation registry', { error });
}
try {
qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger);
logger.info('QM operation registry created');
// Attach to handler class so instances can access it
(QMHandler as any).operationRegistry = qmOperationRegistry;
QMHandler.operationRegistry = qmOperationRegistry;
} catch (error) {
logger.error('Failed to create QM operation registry', { error });
}
// The HandlerScanner in the DI container will handle the actual registration
// 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', {
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
for (const HandlerClass of handlers) {
const metadata = (HandlerClass as any).__handlerMetadata;
const metadata = HandlerClass.extractMetadata();
logger.info(`Handler ${HandlerClass.name} metadata`, {
hasMetadata: !!metadata,
handlerName: metadata?.name,
@ -82,11 +97,11 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
}
// 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
const scanner = diContainer.resolve('handlerScanner');
const scanner = context.handlerScanner;
if (scanner?.registerHandlerClass) {
for (const HandlerClass of handlers) {
scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' });
@ -97,13 +112,13 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
}
// Also check the handler registry directly
const handlerRegistry = diContainer.resolve('handlerRegistry');
const handlerRegistry = context.handlerRegistry;
if (handlerRegistry) {
logger.info('Handler registry state after registration', {
registeredHandlers: handlerRegistry.getHandlerNames(),
handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size,
});
// Initialize handlers that have onInit method
// We need to instantiate handlers and call their onInit
for (const HandlerClass of handlers) {
@ -111,7 +126,8 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
// Create handler instance with service container
const handlerInstance = new HandlerClass(serviceContainer);
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}`);
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
*/
@ -30,7 +31,7 @@ export async function updateEvents(
};
}> {
const { symbol, exchange, qmSearchCode } = input;
this.logger.info(`Fetching events ${qmSearchCode}`, { symbol, exchange, qmSearchCode });
const sessionManager = QMSessionManager.getInstance();
@ -39,7 +40,7 @@ export async function updateEvents(
// 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 session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM events ${qmSearchCode}`);
}
@ -50,10 +51,9 @@ export async function updateEvents(
earnings: 'true',
splits: 'true',
dividends: 'true',
symbol: qmSearchCode,
symbol: qmSearchCode,
});
// TODO: Update with correct events endpoint
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}`);
}
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
let dividendCount = 0;
let splitCount = 0;
let earningsCount = 0;
// 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(
'qmDividends',
results.dividends[0].dividend.map((dividend: any) => ({
results.dividends[0].dividend.map((dividend: Document) => ({
...dividend,
symbol,
exchange,
qmSearchCode,
reportDate: new Date(dividend.date),
})),
['qmSearchCode','reportDate']
['qmSearchCode', 'reportDate']
);
dividendCount = results.dividends[0].dividend.length;
}
// 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(
'qmSplits',
results.splits[0].split.map((split: any) => ({
results.splits[0].split.map((split: Document) => ({
...split,
symbol,
exchange,
qmSearchCode,
reportDate: new Date(split.date),
})),
['qmSearchCode','reportDate']
['qmSearchCode', 'reportDate']
);
splitCount = results.splits[0].split.length;
}
// 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(
'qmEarnings',
results.earnings[0].earning.map((earning: any) => ({
results.earnings[0].earning.map((earning: Document) => ({
...earning,
symbol,
exchange,
qmSearchCode,
reportDate: new Date(earning.reportDate[0]),
})),
['qmSearchCode','reportDate']
['qmSearchCode', 'reportDate']
);
earningsCount = results.earnings[0].earning.length;
}
// Update tracking for events
const updateTime = new Date();
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', {
status: 'success',
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,
dividendCount,
splitCount,
earningsCount
earningsCount,
});
return {
success: true,
symbol,
message: `Events updated for ${qmSearchCode}`,
data: {
data: {
dividends: dividendCount,
splits: splitCount,
earnings: earningsCount
}
earnings: earningsCount,
},
};
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching events', {
this.logger.error('Error fetching events', {
symbol,
error: error instanceof Error ? error.message : 'Unknown error'
error: error instanceof Error ? error.message : 'Unknown error',
});
// Track failure for events
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', {
status: 'failure'
status: 'failure',
});
return {
success: false,
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;
}> {
const { limit = 100000, forceUpdate = false } = input;
this.logger.info('Scheduling events updates', { limit, forceUpdate });
try {
// Get symbols that need events updates
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'events_update', {
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly
limit
limit,
});
if (staleSymbols.length === 0) {
@ -215,7 +225,7 @@ export async function scheduleEventsUpdates(
return {
message: 'No symbols need events updates',
symbolsQueued: 0,
errors: 0
errors: 0,
};
}
@ -227,15 +237,19 @@ export async function scheduleEventsUpdates(
// Schedule individual update jobs for each symbol
for (const item of staleSymbols) {
try {
await this.scheduleOperation('update-events', {
symbol: item.symbol.symbol,
exchange: item.symbol.exchange,
qmSearchCode: item.symbol.qmSearchCode
}, {
priority: 4,
delay: queued * 0.05 // 1.5 seconds between jobs
});
await this.scheduleOperation(
'update-events',
{
symbol: item.symbol.symbol,
exchange: item.symbol.exchange,
qmSearchCode: item.symbol.qmSearchCode,
},
{
priority: 4,
delay: queued * 0.05, // 1.5 seconds between jobs
}
);
queued++;
} catch (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', {
symbolsQueued: queued,
errors,
total: staleSymbols.length
total: staleSymbols.length,
});
return {
message: `Scheduled events updates for ${queued} symbols`,
symbolsQueued: queued,
errors
errors,
};
} catch (error) {
this.logger.error('Events scheduling failed', { error });
throw error;
}
}
}

View file

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

View file

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

View file

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

View file

@ -1,423 +1,425 @@
/**
* 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 { QMHandler } from '../qm.handler';
import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';
interface IntradayCrawlInput {
symbol: string;
exchange: string;
qmSearchCode: string;
targetOldestDate?: string; // ISO date string for how far back to crawl
existingCrawlState?: CrawlState; // 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)
*/
export async function crawlIntradayData(
this: QMHandler,
input: IntradayCrawlInput,
_context?: ExecutionContext
): Promise<{
success: boolean;
symbol: string;
exchange: string;
qmSearchCode: string;
message: string;
data?: any;
}> {
const {
symbol,
exchange,
qmSearchCode,
targetOldestDate = '1960-01-01', // Default to ~5 years of data
existingCrawlState,
gaps
} = input;
this.logger.info('Starting intraday crawl', {
symbol,
exchange,
targetOldestDate,
hasExistingState: !!existingCrawlState,
gaps
});
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
const sessionId = QM_SESSION_IDS.PRICES;
const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM intraday`);
}
try {
// Use passed crawl state if available, otherwise query for it
let currentCrawlState: CrawlState;
if (existingCrawlState) {
currentCrawlState = existingCrawlState;
} else {
// Only query if not passed
const symbolData = await this.mongodb.findOne('qmSymbols', {
qmSearchCode
});
currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || {
finished: false
};
}
// Determine starting point for crawl
let currentWeek: Date;
if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) {
// Start from oldest date reached
currentWeek = new Date(currentCrawlState.oldestDateReached);
} else if (currentCrawlState.lastProcessedDate) {
// Resume from last processed date
currentWeek = new Date(currentCrawlState.lastProcessedDate);
} else {
// New crawl, start from today
currentWeek = new Date();
// console.log('Current week before adjustment:', currentWeek);
}
// Get the Sunday of the current week
currentWeek = getLastWeek(currentWeek);
const targetOldest = new Date(targetOldestDate);
targetOldest.setHours(0, 0, 0, 0);
// Check if already finished
if (currentCrawlState.finished || currentWeek <= targetOldest) {
this.logger.info('Intraday crawl already complete', { symbol });
return {
success: true,
qmSearchCode,
symbol,
exchange,
message: 'Intraday crawl already complete'
};
}
let totalRecords = 0;
let weeksProcessed = 0;
const errors: string[] = [];
const endOfWeek = new Date(currentWeek)
endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday
// Build API request for the week
const searchParams = new URLSearchParams({
adjType:'none',
adjusted:'true',
freq:'day',
interval:'1',
marketSession:'mkt',
pathName:'/demo/portal/company-quotes.php',
qmodTool:'InteractiveChart',
start: currentWeek.toISOString().split('T')[0],
end: endOfWeek.toISOString().split('T')[0], // Next Sunday
symbol: qmSearchCode,
unadjusted:'false',
webmasterId:'500',
zeroTradeDays:'false',
} as Record<string, string>);
try {
const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const barsResults = await response.json();
// Parse the results based on the API response structure
const barsData = barsResults.results?.intraday?.[0]?.interval || null;
const barsLength = barsData !== null ? barsData.length : 0;
this.logger.info(`Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`, {
qmSearchCode,
currentWeek,
records: barsLength
});
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store data if we got any
if (barsData !== null && barsLength > 0) {
const processedBars = barsData.map((bar: any) => ({
...bar,
qmSearchCode,
symbol,
exchange,
timestamp: new Date(bar.startdatetime || bar.date || bar.datetime),
}));
await this.mongodb.batchUpsert(
'qmIntraday',
processedBars,
['qmSearchCode', 'timestamp']
);
totalRecords += barsLength;
}
weeksProcessed = 1;
const nextWeek = getLastWeek(new Date(currentWeek));
const finished = (barsData === null) && nextWeek < new Date('2024-01-01')
this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
status: 'success',
crawlState: {
finished: finished,
oldestDateReached: currentCrawlState.oldestDateReached,
lastProcessedDate: currentWeek
}
});
// Calculate next week to process (previous Sunday)
// console.log(barsData === null , existingCrawlState);
if(!finished) {
currentCrawlState.lastProcessedDate = nextWeek;
await this.scheduleOperation('crawl-intraday-data', {
symbol: symbol,
exchange: exchange,
qmSearchCode: qmSearchCode,
targetOldestDate,
// Pass existing crawl state and gaps to avoid re-querying
existingCrawlState: currentCrawlState,
gaps: gaps
}, {
priority: 4, // Standard priority for backward crawls
});
}
return {
success: true,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`,
data: {
totalRecords,
weeksProcessed,
nextWeek: nextWeek.toISOString().split('T')[0],
errors: errors.length > 0 ? errors : undefined
}
}
} catch (error) {
this.logger.error('Intraday crawl failed', {
symbol,
error: error instanceof Error ? error.message : 'Unknown error'
});
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
status: 'failure',
error: error instanceof Error ? error.message : 'Unknown error'
});
return {
success: false,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}catch (error) {
return {
success: false,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
/**
* Schedule intraday crawls for multiple symbols
*/
export async function scheduleIntradayCrawls(
this: QMHandler,
input: {
limit?: number;
targetOldestDate?: string;
priorityMode?: 'never_run' | 'incomplete' | 'all';
} = {},
_context?: ExecutionContext
): Promise<{
message: string;
symbolsQueued: number;
errors: number;
}> {
const {
limit = 999999999,
targetOldestDate = '1960-01-01',
priorityMode = 'all'
} = input;
this.logger.info('Scheduling intraday crawls', {
limit,
targetOldestDate,
priorityMode
});
try {
// Get symbols based on priority mode
let symbolsToProcess: any[] = [];
const tracker = this.operationRegistry.getTracker('qm');
switch (priorityMode) {
case 'never_run':
// Get symbols that have never been crawled
symbolsToProcess = await this.mongodb.find('qmSymbols', {
'operations.intraday_bars': { $exists: false },
active: { $ne: false }
}, {
limit,
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 }
});
break;
case 'incomplete':
// Get symbols with incomplete crawls
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl(
'intraday_bars',
{
limit,
targetOldestDate: new Date(targetOldestDate),
includeNewDataGaps: false, // Only backward gaps
// symbolFilter: { symbol: 'ETU' } // Filter for testing
}
);
break;
case 'all':
default:
// Get all symbols that need any processing
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl(
'intraday_bars',
{
limit,
targetOldestDate: new Date(targetOldestDate),
includeNewDataGaps: false, // Only backward gaps since we removed forward crawling
// symbolFilter: { symbol: 'AAPL' } // Filter for testing
}
);
break;
}
if (symbolsToProcess.length === 0) {
return {
message: `No symbols found for priority mode: ${priorityMode}`,
symbolsQueued: 0,
errors: 0
};
}
this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', {
count: symbolsToProcess.length,
firstSymbol: symbolsToProcess[0] ? {
symbol: symbolsToProcess[0].symbol,
gaps: symbolsToProcess[0].gaps,
hasOperationStatus: !!symbolsToProcess[0].operationStatus,
crawlState: symbolsToProcess[0].operationStatus?.crawlState
} : null
});
// Get full symbol data if needed
if (priorityMode !== 'never_run') {
const qmSearchCodes = symbolsToProcess.map(s => s.symbol);
const fullSymbols = await this.mongodb.find('qmSymbols', {
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 => {
const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol);
if (full) {
return {
...full,
gaps: sp.gaps, // Preserve gap information
operationStatus: sp.operationStatus // Preserve original operation status
};
}
return sp;
});
}
this.logger.info('After mapping, symbols to process', {
count: symbolsToProcess.length,
firstSymbol: symbolsToProcess[0] ? {
symbol: symbolsToProcess[0].symbol,
exchange: symbolsToProcess[0].exchange,
qmSearchCode: symbolsToProcess[0].qmSearchCode,
gaps: symbolsToProcess[0].gaps,
hasOperationStatus: !!symbolsToProcess[0].operationStatus,
crawlState: symbolsToProcess[0].operationStatus?.crawlState
} : null
});
let symbolsQueued = 0;
let errors = 0;
// Schedule crawl jobs
for (const doc of symbolsToProcess) {
try {
await this.scheduleOperation('crawl-intraday-data', {
symbol: doc.symbol,
exchange: doc.exchange,
qmSearchCode: doc.qmSearchCode,
targetOldestDate,
// Pass existing crawl state and gaps to avoid re-querying
existingCrawlState: doc.operationStatus?.crawlState,
gaps: doc.gaps
}, {
priority: 6, // Standard priority for backward crawls
});
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
});
return {
message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`,
symbolsQueued,
errors
};
} catch (error) {
this.logger.error('Intraday crawl scheduling failed', { error });
throw error;
}
}
import type { Document } from 'mongodb';
/**
* QM Intraday Crawl Actions - Sophisticated crawling with resumption support
*/
import type { ExecutionContext } from '@stock-bot/handlers';
import type { OperationStatus } from '../../../shared/operation-manager/types';
import type { QMHandler } from '../qm.handler';
import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';
interface IntradayCrawlInput {
symbol: string;
exchange: string;
qmSearchCode: string;
targetOldestDate?: string; // ISO date string for how far back to crawl
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)
*/
export async function crawlIntradayData(
this: QMHandler,
input: IntradayCrawlInput,
_context?: ExecutionContext
): Promise<{
success: boolean;
symbol: string;
exchange: string;
qmSearchCode: string;
message: string;
data?: unknown;
}> {
const {
symbol,
exchange,
qmSearchCode,
targetOldestDate = '1960-01-01', // Default to ~5 years of data
existingCrawlState,
gaps,
} = input;
this.logger.info('Starting intraday crawl', {
symbol,
exchange,
targetOldestDate,
hasExistingState: !!existingCrawlState,
gaps,
});
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
const sessionId = QM_SESSION_IDS.PRICES;
const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM intraday`);
}
try {
// Use passed crawl state if available, otherwise query for it
let currentCrawlState: Partial<OperationStatus>;
if (existingCrawlState) {
currentCrawlState = existingCrawlState;
} else {
// Only query if not passed
const symbolData = await this.mongodb.findOne('qmSymbols', {
qmSearchCode,
});
currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || {
finished: false,
};
}
// Determine starting point for crawl
let currentWeek: Date;
if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) {
// Start from oldest date reached
currentWeek = new Date(currentCrawlState.oldestDateReached);
} else if (currentCrawlState.lastProcessedDate) {
// Resume from last processed date
currentWeek = new Date(currentCrawlState.lastProcessedDate);
} else {
// New crawl, start from today
currentWeek = new Date();
// console.log('Current week before adjustment:', currentWeek);
}
// Get the Sunday of the current week
currentWeek = getLastWeek(currentWeek);
const targetOldest = new Date(targetOldestDate);
targetOldest.setHours(0, 0, 0, 0);
// Check if already finished
if (currentCrawlState.finished || currentWeek <= targetOldest) {
this.logger.info('Intraday crawl already complete', { symbol });
return {
success: true,
qmSearchCode,
symbol,
exchange,
message: 'Intraday crawl already complete',
};
}
let totalRecords = 0;
let weeksProcessed = 0;
const errors: string[] = [];
const endOfWeek = new Date(currentWeek);
endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday
// Build API request for the week
const searchParams = new URLSearchParams({
adjType: 'none',
adjusted: 'true',
freq: 'day',
interval: '1',
marketSession: 'mkt',
pathName: '/demo/portal/company-quotes.php',
qmodTool: 'InteractiveChart',
start: currentWeek.toISOString().split('T')[0],
end: endOfWeek.toISOString().split('T')[0], // Next Sunday
symbol: qmSearchCode,
unadjusted: 'false',
webmasterId: '500',
zeroTradeDays: 'false',
} as Record<string, string>);
try {
const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const barsResults = await response.json();
// Parse the results based on the API response structure
const barsData = barsResults.results?.intraday?.[0]?.interval || null;
const barsLength = barsData !== null ? barsData.length : 0;
this.logger.info(
`Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`,
{
qmSearchCode,
currentWeek,
records: barsLength,
}
);
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store data if we got any
if (barsData !== null && barsLength > 0) {
const processedBars = barsData.map((bar: Document) => ({
...bar,
qmSearchCode,
symbol,
exchange,
timestamp: new Date(bar.startdatetime || bar.date || bar.datetime),
}));
await this.mongodb.batchUpsert('qmIntraday', processedBars, ['qmSearchCode', 'timestamp']);
totalRecords += barsLength;
}
weeksProcessed = 1;
const nextWeek = getLastWeek(new Date(currentWeek));
const finished = barsData === null && nextWeek < new Date('2024-01-01');
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
status: 'success',
finished,
oldestDateReached: currentCrawlState.oldestDateReached,
lastProcessedDate: currentWeek,
});
// Calculate next week to process (previous Sunday)
// console.log(barsData === null , existingCrawlState);
if (!finished) {
currentCrawlState.lastProcessedDate = nextWeek;
await this.scheduleOperation(
'crawl-intraday-data',
{
symbol: symbol,
exchange: exchange,
qmSearchCode: qmSearchCode,
targetOldestDate,
// Pass existing crawl state and gaps to avoid re-querying
existingCrawlState: currentCrawlState,
gaps: gaps,
},
{
priority: 4, // Standard priority for backward crawls
}
);
}
return {
success: true,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`,
data: {
totalRecords,
weeksProcessed,
nextWeek: nextWeek.toISOString().split('T')[0],
errors: errors.length > 0 ? errors : undefined,
},
};
} catch (error) {
this.logger.error('Intraday crawl failed', {
symbol,
error: error instanceof Error ? error.message : 'Unknown error',
});
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
status: 'failure',
error: error instanceof Error ? error.message : 'Unknown error',
});
return {
success: false,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
} catch (error) {
return {
success: false,
symbol,
exchange,
qmSearchCode,
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}
/**
* Schedule intraday crawls for multiple symbols
*/
export async function scheduleIntradayCrawls(
this: QMHandler,
input: {
limit?: number;
targetOldestDate?: string;
priorityMode?: 'never_run' | 'incomplete' | 'all';
} = {},
_context?: ExecutionContext
): Promise<{
message: string;
symbolsQueued: number;
errors: number;
}> {
const { limit = 999999999, targetOldestDate = '1960-01-01', priorityMode = 'all' } = input;
this.logger.info('Scheduling intraday crawls', {
limit,
targetOldestDate,
priorityMode,
});
try {
// Get symbols based on priority mode
let symbolsToProcess: Document[] = [];
const tracker = this.operationRegistry.getTracker('qm');
switch (priorityMode) {
case 'never_run':
// Get symbols that have never been crawled
symbolsToProcess = await this.mongodb.find(
'qmSymbols',
{
'operations.intraday_bars': { $exists: false },
active: { $ne: false },
},
{
limit,
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 },
}
);
break;
case 'incomplete':
// Get symbols with incomplete crawls
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit,
targetOldestDate: new Date(targetOldestDate),
includeNewDataGaps: false, // Only backward gaps
// symbolFilter: { symbol: 'ETU' } // Filter for testing
});
break;
case 'all':
default:
// Get all symbols that need any processing
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit,
targetOldestDate: new Date(targetOldestDate),
includeNewDataGaps: false, // Only backward gaps since we removed forward crawling
// symbolFilter: { symbol: 'AAPL' } // Filter for testing
});
break;
}
if (symbolsToProcess.length === 0) {
return {
message: `No symbols found for priority mode: ${priorityMode}`,
symbolsQueued: 0,
errors: 0,
};
}
this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', {
count: symbolsToProcess.length,
firstSymbol: symbolsToProcess[0]
? {
symbol: symbolsToProcess[0].symbol,
gaps: symbolsToProcess[0].gaps,
hasOperationStatus: !!symbolsToProcess[0].operationStatus,
crawlState: symbolsToProcess[0].operationStatus?.crawlState,
}
: null,
});
// Get full symbol data if needed
if (priorityMode !== 'never_run') {
const qmSearchCodes = symbolsToProcess.map(s => s.symbol);
const fullSymbols = await this.mongodb.find(
'qmSymbols',
{
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 => {
const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol);
if (full) {
return {
...full,
gaps: sp.gaps, // Preserve gap information
operationStatus: sp.operationStatus, // Preserve original operation status
};
}
return sp;
});
}
this.logger.info('After mapping, symbols to process', {
count: symbolsToProcess.length,
firstSymbol: symbolsToProcess[0]
? {
symbol: symbolsToProcess[0].symbol,
exchange: symbolsToProcess[0].exchange,
qmSearchCode: symbolsToProcess[0].qmSearchCode,
gaps: symbolsToProcess[0].gaps,
hasOperationStatus: !!symbolsToProcess[0].operationStatus,
crawlState: symbolsToProcess[0].operationStatus?.crawlState,
}
: null,
});
let symbolsQueued = 0;
let errors = 0;
// Schedule crawl jobs
for (const doc of symbolsToProcess) {
try {
await this.scheduleOperation(
'crawl-intraday-data',
{
symbol: doc.symbol,
exchange: doc.exchange,
qmSearchCode: doc.qmSearchCode,
targetOldestDate,
// Pass existing crawl state and gaps to avoid re-querying
existingCrawlState: doc.operationStatus?.crawlState,
gaps: doc.gaps,
},
{
priority: 6, // Standard priority for backward crawls
}
);
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,
});
return {
message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`,
symbolsQueued,
errors,
};
} 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
*/
import type { ExecutionContext } from '@stock-bot/handlers';
import type { QMHandler } from '../qm.handler';
import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';
interface NewsArticle {
id: string;
publishedDate: Date;
title: string;
summary: string;
source: string;
url: string;
symbols?: string[];
categories?: string[];
sentiment?: {
score: number;
label: string; // positive, negative, neutral
};
imageUrl?: string;
}
/**
* Update news for a single symbol
*/
export async function updateSymbolNews(
this: QMHandler,
input: {
symbol: string;
symbolId: number;
qmSearchCode: string;
lookbackDays?: number;
},
_context?: ExecutionContext
): Promise<{
success: boolean;
symbol: string;
message: string;
data?: any;
}> {
const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input;
this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays });
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
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 news`);
}
try {
// Calculate date range
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - lookbackDays);
// Build API request for symbol news
const searchParams = new URLSearchParams({
symbol: symbol,
symbolId: symbolId.toString(),
qmodTool: 'News',
webmasterId: '500',
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
includeContent: 'true',
pageSize: '50'
} as Record<string, string>);
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const newsData = await response.json();
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store news data
if (newsData && newsData.articles && newsData.articles.length > 0) {
const processedArticles = newsData.articles.map((article: any) => ({
articleId: article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`,
symbol,
symbolId,
publishedDate: new Date(article.publishedDate),
title: article.title,
summary: article.summary || article.content?.substring(0, 500),
source: article.source || 'Unknown',
url: article.url,
symbols: article.symbols || [symbol],
categories: article.categories || [],
sentiment: article.sentiment ? {
score: parseFloat(article.sentiment.score) || 0,
label: article.sentiment.label || 'neutral'
} : null,
imageUrl: article.imageUrl,
isSymbolSpecific: true,
updated_at: new Date()
}));
// Store in MongoDB
await this.mongodb.batchUpsert(
'qmNews',
processedArticles,
['articleId'] // Unique key
);
// Calculate sentiment summary
const sentimentCounts = processedArticles.reduce((acc: any, article: any) => {
if (article.sentiment) {
acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1;
}
return acc;
}, {});
// Update operation tracking
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'success',
lastRecordDate: endDate,
recordCount: processedArticles.length,
metadata: {
sentimentCounts,
uniqueSources: new Set(processedArticles.map((a: any) => a.source)).size,
avgSentimentScore: processedArticles
.filter((a: any) => a.sentiment?.score)
.reduce((sum: number, a: any, i: number, arr: any[]) =>
i === arr.length - 1 ? (sum + a.sentiment.score) / arr.length : sum + a.sentiment.score, 0
)
}
});
this.logger.info('Symbol news updated successfully', {
symbol,
articleCount: processedArticles.length,
sentimentCounts
});
return {
success: true,
symbol,
message: `Updated ${processedArticles.length} news articles`,
data: {
count: processedArticles.length,
sentimentCounts,
sources: new Set(processedArticles.map((a: any) => a.source)).size
}
};
} else {
// No news found
this.logger.info('No news articles found', { symbol });
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'success',
lastRecordDate: endDate,
recordCount: 0
});
return {
success: true,
symbol,
message: 'No news articles found',
data: { count: 0 }
};
}
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching symbol news', {
symbol,
error: error instanceof Error ? error.message : 'Unknown error'
});
// Update operation tracking for failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'failure',
error: error instanceof Error ? error.message : 'Unknown error'
});
return {
success: false,
symbol,
message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
/**
* Update general market news
*/
export async function updateGeneralNews(
this: QMHandler,
input: {
categories?: string[];
lookbackMinutes?: number;
} = {},
_context?: ExecutionContext
): Promise<{
success: boolean;
message: string;
data?: any;
}> {
const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input;
this.logger.info('Fetching general news', { categories, lookbackMinutes });
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
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 general news`);
}
try {
// Calculate time range
const endDate = new Date();
const startDate = new Date();
startDate.setMinutes(startDate.getMinutes() - lookbackMinutes);
// Build API request for general news
const searchParams = new URLSearchParams({
qmodTool: 'MarketNews',
webmasterId: '500',
categories: categories.join(','),
startDateTime: startDate.toISOString(),
endDateTime: endDate.toISOString(),
includeContent: 'true',
pageSize: '100'
} as Record<string, string>);
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const newsData = await response.json();
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store general news
if (newsData && newsData.articles && newsData.articles.length > 0) {
const processedArticles = newsData.articles.map((article: any) => ({
articleId: article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`,
publishedDate: new Date(article.publishedDate),
title: article.title,
summary: article.summary || article.content?.substring(0, 500),
source: article.source || 'Unknown',
url: article.url,
symbols: article.symbols || [],
categories: article.categories || categories,
sentiment: article.sentiment ? {
score: parseFloat(article.sentiment.score) || 0,
label: article.sentiment.label || 'neutral'
} : null,
imageUrl: article.imageUrl,
isSymbolSpecific: false,
isMarketMoving: article.isMarketMoving || false,
importance: article.importance || 'medium',
updated_at: new Date()
}));
// Store in MongoDB
await this.mongodb.batchUpsert(
'qmNews',
processedArticles,
['articleId'] // Unique key
);
// Find high-importance articles
const highImportanceCount = processedArticles.filter((a: any) =>
a.importance === 'high' || a.isMarketMoving
).length;
// Update a general tracking document
await this.mongodb.updateOne(
'qmOperationStats',
{ operation: 'general_news_update' },
{
$set: {
lastRunAt: new Date(),
lastRecordCount: processedArticles.length,
highImportanceCount,
categories,
updated_at: new Date()
}
},
{ upsert: true }
);
this.logger.info('General news updated successfully', {
articleCount: processedArticles.length,
highImportanceCount,
categories
});
return {
success: true,
message: `Updated ${processedArticles.length} general news articles`,
data: {
count: processedArticles.length,
highImportanceCount,
categories,
sources: new Set(processedArticles.map((a: any) => a.source)).size
}
};
} else {
// No news found
this.logger.info('No general news articles found');
return {
success: true,
message: 'No general news articles found',
data: { count: 0 }
};
}
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching general news', {
error: error instanceof Error ? error.message : 'Unknown error'
});
return {
success: false,
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
/**
* Schedule symbol news updates
*/
export async function scheduleSymbolNewsUpdates(
this: QMHandler,
input: {
limit?: number;
minHoursSinceRun?: number;
forceUpdate?: boolean;
} = {},
_context?: ExecutionContext
): Promise<{
message: string;
symbolsQueued: number;
errors: number;
}> {
const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input;
this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate });
try {
// Get symbols that need news updates
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', {
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
limit
});
if (staleSymbols.length === 0) {
this.logger.info('No symbols need news updates');
return {
message: 'No symbols need news updates',
symbolsQueued: 0,
errors: 0
};
}
this.logger.info(`Found ${staleSymbols.length} symbols for news updates`);
let symbolsQueued = 0;
let errors = 0;
// Schedule update jobs
for (const item of staleSymbols) {
try {
if (!item.symbol.symbolId) {
this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`);
continue;
}
await this.scheduleOperation('update-symbol-news', {
symbol: item.symbol.symbol,
symbolId: item.symbol.symbolId,
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 });
errors++;
}
}
this.logger.info('Symbol news update scheduling completed', {
symbolsQueued,
errors
});
return {
message: `Scheduled news updates for ${symbolsQueued} symbols`,
symbolsQueued,
errors
};
} catch (error) {
this.logger.error('Symbol news scheduling failed', { error });
throw error;
}
}
/**
* QM News Actions - Fetch symbol-specific and general market news
*/
import type { ExecutionContext } from '@stock-bot/handlers';
import type { QMHandler } from '../qm.handler';
import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';
import type { QMNewsArticle } from '../shared/types';
/**
* Update news for a single symbol
*/
export async function updateSymbolNews(
this: QMHandler,
input: {
symbol: string;
symbolId: number;
qmSearchCode: string;
lookbackDays?: number;
},
_context?: ExecutionContext
): Promise<{
success: boolean;
symbol: string;
message: string;
data?: unknown;
}> {
const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input;
this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays });
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
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 news`);
}
try {
// Calculate date range
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - lookbackDays);
// Build API request for symbol news
const searchParams = new URLSearchParams({
symbol: symbol,
symbolId: symbolId.toString(),
qmodTool: 'News',
webmasterId: '500',
startDate: startDate.toISOString().split('T')[0],
endDate: endDate.toISOString().split('T')[0],
includeContent: 'true',
pageSize: '50',
} as Record<string, string>);
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const newsData = (await response.json()) as { articles?: QMNewsArticle[] };
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store news data
if (newsData && newsData.articles && newsData.articles.length > 0) {
const processedArticles = newsData.articles.map(article => ({
articleId:
article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`,
symbol,
symbolId,
publishedDate: new Date(article.publishedDate),
title: article.title,
summary: article.summary || article.content?.substring(0, 500),
source: article.source || 'Unknown',
url: article.url,
symbols: article.symbols || [symbol],
categories: article.categories || [],
sentiment: article.sentiment
? {
score: Number(article.sentiment.score) || 0,
label: article.sentiment.label || 'neutral',
}
: null,
imageUrl: article.imageUrl,
isSymbolSpecific: true,
updated_at: new Date(),
}));
// Store in MongoDB
await this.mongodb.batchUpsert(
'qmNews',
processedArticles,
['articleId'] // Unique key
);
// Calculate sentiment summary
const sentimentCounts = processedArticles.reduce<Record<string, number>>((acc, article) => {
if (article.sentiment) {
acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1;
}
return acc;
}, {});
// Update operation tracking
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'success',
lastRecordDate: endDate,
recordCount: processedArticles.length,
metadata: {
sentimentCounts,
uniqueSources: new Set(processedArticles.map(a => a.source)).size,
avgSentimentScore: processedArticles
.filter(a => a.sentiment?.score)
.reduce(
(sum, a, i, arr) =>
i === arr.length - 1
? (sum + (a.sentiment?.score ?? 0)) / arr.length
: sum + (a.sentiment?.score ?? 0),
0
),
},
});
this.logger.info('Symbol news updated successfully', {
symbol,
articleCount: processedArticles.length,
sentimentCounts,
});
return {
success: true,
symbol,
message: `Updated ${processedArticles.length} news articles`,
data: {
count: processedArticles.length,
sentimentCounts,
sources: new Set(processedArticles.map(a => a.source)).size,
},
};
} else {
// No news found
this.logger.info('No news articles found', { symbol });
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'success',
lastRecordDate: endDate,
recordCount: 0,
});
return {
success: true,
symbol,
message: 'No news articles found',
data: { count: 0 },
};
}
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching symbol news', {
symbol,
error: error instanceof Error ? error.message : 'Unknown error',
});
// Update operation tracking for failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
status: 'failure',
error: error instanceof Error ? error.message : 'Unknown error',
});
return {
success: false,
symbol,
message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}
/**
* Update general market news
*/
export async function updateGeneralNews(
this: QMHandler,
input: {
categories?: string[];
lookbackMinutes?: number;
} = {},
_context?: ExecutionContext
): Promise<{
success: boolean;
message: string;
data?: unknown;
}> {
const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input;
this.logger.info('Fetching general news', { categories, lookbackMinutes });
const sessionManager = QMSessionManager.getInstance();
await sessionManager.initialize(this.cache, this.logger);
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 general news`);
}
try {
// Calculate time range
const endDate = new Date();
const startDate = new Date();
startDate.setMinutes(startDate.getMinutes() - lookbackMinutes);
// Build API request for general news
const searchParams = new URLSearchParams({
qmodTool: 'MarketNews',
webmasterId: '500',
categories: categories.join(','),
startDateTime: startDate.toISOString(),
endDateTime: endDate.toISOString(),
includeContent: 'true',
pageSize: '100',
} as Record<string, string>);
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: session.headers,
proxy: session.proxy,
});
if (!response.ok) {
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
}
const newsData = (await response.json()) as { articles?: QMNewsArticle[] };
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Process and store general news
if (newsData && newsData.articles && newsData.articles.length > 0) {
const processedArticles = newsData.articles.map(article => ({
articleId:
article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`,
publishedDate: new Date(article.publishedDate),
title: article.title,
summary: article.summary || article.content?.substring(0, 500),
source: article.source || 'Unknown',
url: article.url,
symbols: article.symbols || [],
categories: article.categories || categories,
sentiment: article.sentiment
? {
score: Number(article.sentiment.score) || 0,
label: article.sentiment.label || 'neutral',
}
: null,
imageUrl: article.imageUrl,
isSymbolSpecific: false,
isMarketMoving: article.isMarketMoving || false,
importance: article.importance || 'medium',
updated_at: new Date(),
}));
// Store in MongoDB
await this.mongodb.batchUpsert(
'qmNews',
processedArticles,
['articleId'] // Unique key
);
// Find high-importance articles
const highImportanceCount = processedArticles.filter(
a => a.importance === 'high' || a.isMarketMoving
).length;
// Update a general tracking document
await this.mongodb.updateOne(
'qmOperationStats',
{ operation: 'general_news_update' },
{
$set: {
lastRunAt: new Date(),
lastRecordCount: processedArticles.length,
highImportanceCount,
categories,
updated_at: new Date(),
},
},
{ upsert: true }
);
this.logger.info('General news updated successfully', {
articleCount: processedArticles.length,
highImportanceCount,
categories,
});
return {
success: true,
message: `Updated ${processedArticles.length} general news articles`,
data: {
count: processedArticles.length,
highImportanceCount,
categories,
sources: new Set(processedArticles.map(a => a.source)).size,
},
};
} else {
// No news found
this.logger.info('No general news articles found');
return {
success: true,
message: 'No general news articles found',
data: { count: 0 },
};
}
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching general news', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return {
success: false,
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}
/**
* Schedule symbol news updates
*/
export async function scheduleSymbolNewsUpdates(
this: QMHandler,
input: {
limit?: number;
minHoursSinceRun?: number;
forceUpdate?: boolean;
} = {},
_context?: ExecutionContext
): Promise<{
message: string;
symbolsQueued: number;
errors: number;
}> {
const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input;
this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate });
try {
// Get symbols that need news updates
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', {
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
limit,
});
if (staleSymbols.length === 0) {
this.logger.info('No symbols need news updates');
return {
message: 'No symbols need news updates',
symbolsQueued: 0,
errors: 0,
};
}
this.logger.info(`Found ${staleSymbols.length} symbols for news updates`);
let symbolsQueued = 0;
let errors = 0;
// Schedule update jobs
for (const item of staleSymbols) {
try {
if (!item.symbol.symbolId) {
this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`);
continue;
}
await this.scheduleOperation(
'update-symbol-news',
{
symbol: item.symbol.symbol,
symbolId: item.symbol.symbolId,
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 });
errors++;
}
}
this.logger.info('Symbol news update scheduling completed', {
symbolsQueued,
errors,
});
return {
message: `Scheduled news updates for ${symbolsQueued} symbols`,
symbolsQueued,
errors,
};
} 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
*/
@ -23,10 +24,10 @@ export async function updatePrices(
success: boolean;
qmSearchCode: string;
message: string;
data?: any;
data?: unknown;
}> {
const { qmSearchCode, lastRecordDate, symbol, exchange } = input;
this.logger.info(`Fetching daily prices ${qmSearchCode}`, { qmSearchCode });
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
const sessionId = QM_SESSION_IDS.PRICES;
const session = await sessionManager.getSession(sessionId);
if (!session || !session.uuid) {
throw new Error(`No active session found for QM prices`);
}
@ -43,16 +44,18 @@ export async function updatePrices(
try {
// Build API request for daily prices
const searchParams = new URLSearchParams({
zeroTradeDays: 'false',
start: lastRecordDate ? new Date(lastRecordDate).toISOString().split('T')[0] + '' : '1960-01-01',
interval: '1',
marketSession: 'mkt',
freq: 'day',
adjusted: 'false',
adjustmentType: 'none',
unadjusted: 'true',
datatype: 'eod',
symbol: qmSearchCode,
zeroTradeDays: 'false',
start: lastRecordDate
? new Date(lastRecordDate).toISOString().split('T')[0] + ''
: '1960-01-01',
interval: '1',
marketSession: 'mkt',
freq: 'day',
adjusted: 'false',
adjustmentType: 'none',
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
// TODO: Update with correct prices endpoint
@ -72,26 +75,26 @@ export async function updatePrices(
// Update session success stats
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
// Update symbol to track last price update
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}`);
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'success',
recordCount: priceData.length
recordCount: priceData.length,
});
return {
success: false,
qmSearchCode,
message: `No price data found for symbol ${qmSearchCode}`
message: `No price data found for symbol ${qmSearchCode}`,
};
}
// Process and store price data
if (priceData && priceData.length > 0) {
// Store prices in a separate collection
const processedPrices = priceData.map((price: any) => ({
const processedPrices = priceData.map((price: Document) => ({
...price,
symbol,
exchange,
@ -106,62 +109,60 @@ export async function updatePrices(
);
// Find the latest price date
const latestDate = processedPrices.reduce((latest: Date, price: any) =>
price.dateTime > latest ? price.dateTime : latest,
const latestDate = processedPrices.reduce(
(latest: Date, price: Document) => (price.dateTime > latest ? price.dateTime : latest),
new Date(0)
);
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'success',
lastRecordDate: latestDate,
recordCount: priceData.length
recordCount: priceData.length,
});
this.logger.info('Prices updated successfully', {
this.logger.info('Prices updated successfully', {
qmSearchCode,
priceCount: priceData.length,
latestDate
latestDate,
});
return {
success: true,
qmSearchCode,
message: `Prices updated for ${qmSearchCode}`,
data: {
data: {
count: priceData.length,
latestDate
}
latestDate,
},
};
} else {
this.logger.warn('No price data returned from API', { qmSearchCode });
return {
success: false,
qmSearchCode,
message: `No price data found for qmSearchCode ${qmSearchCode}`
message: `No price data found for qmSearchCode ${qmSearchCode}`,
};
}
} catch (error) {
// Update session failure stats
if (session.uuid) {
await sessionManager.incrementFailedCalls(sessionId, session.uuid);
}
this.logger.error('Error fetching prices', {
this.logger.error('Error fetching prices', {
qmSearchCode,
error: error instanceof Error ? error.message : 'Unknown error'
error: error instanceof Error ? error.message : 'Unknown error',
});
// Track failure
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', {
status: 'failure'
status: 'failure',
});
return {
success: false,
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;
}> {
const { limit = 50000, forceUpdate = false } = input;
this.logger.info('Scheduling price updates', { limit, forceUpdate });
try {
// Get symbols that need updating
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: forceUpdate ? 0 : 24, // Daily updates
limit
limit,
});
if (staleSymbols.length === 0) {
@ -197,7 +198,7 @@ export async function schedulePriceUpdates(
return {
message: 'No symbols need price updates',
symbolsQueued: 0,
errors: 0
errors: 0,
};
}
@ -209,19 +210,25 @@ export async function schedulePriceUpdates(
// Schedule individual update jobs for each symbol
for (const item of staleSymbols) {
try {
await this.scheduleOperation('update-prices', {
qmSearchCode: item.symbol.qmSearchCode,
lastRecordDate: item.operations?.price_update?.lastRecordDate,
symbol: item.symbol.symbol,
exchange: item.symbol.exchange
}, {
priority: 7, // High priority for price data
delay: queued * 100 // 0.1 seconds between jobs
});
await this.scheduleOperation(
'update-prices',
{
qmSearchCode: item.symbol.qmSearchCode,
lastRecordDate: item.operations?.price_update?.lastRecordDate,
symbol: item.symbol.symbol,
exchange: item.symbol.exchange,
},
{
priority: 7, // High priority for price data
delay: queued * 100, // 0.1 seconds between jobs
}
);
queued++;
} 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++;
}
}
@ -229,16 +236,16 @@ export async function schedulePriceUpdates(
this.logger.info('Price update scheduling completed', {
symbolsQueued: queued,
errors,
total: staleSymbols.length
total: staleSymbols.length,
});
return {
message: `Scheduled price updates for ${queued} symbols`,
symbolsQueued: queued,
errors
errors,
};
} catch (error) {
this.logger.error('Price scheduling failed', { error });
throw error;
}
}
}

View file

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

View file

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

View file

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

View file

@ -1,12 +1,10 @@
import {
BaseHandler,
Disabled,
Handler,
Operation,
ScheduledOperation,
} from '@stock-bot/handlers';
import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
import type { IServiceContainer } from '@stock-bot/services';
import type { OperationRegistry } from '../../shared/operation-manager';
import { resolveIngestionServices } from '../../types';
import type { DataIngestionServices } from '../../types';
import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action';
import { createQMOperationRegistry } from './shared/operation-provider';
import {
checkSessions,
createSession,
@ -27,22 +25,21 @@ import {
updateInsiders,
updatePrices,
updateSymbolInfo,
updateSymbolNews
updateSymbolNews,
} from './actions';
import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action';
import { createQMOperationRegistry } from './shared/operation-provider';
@Handler('qm')
@Disabled() // Disable by default, enable specific operations as needed
export class QMHandler extends BaseHandler<DataIngestionServices> {
static operationRegistry?: OperationRegistry;
public operationRegistry!: OperationRegistry;
constructor(services: any) {
super(services); // Handler name read from @Handler decorator
constructor(services: IServiceContainer) {
super(resolveIngestionServices(services, 'qm')); // Handler name read from @Handler decorator
// Use pre-initialized registry if available, otherwise create new one
if ((QMHandler as any).operationRegistry) {
this.operationRegistry = (QMHandler as any).operationRegistry;
if (QMHandler.operationRegistry) {
this.operationRegistry = QMHandler.operationRegistry;
this.logger.info('Using pre-initialized QM operation registry');
} else {
// Fallback: Initialize operation registry with QM provider
@ -79,7 +76,8 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('spider-symbols', '0 0 * * 0', {
priority: 9,
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;
@ -98,7 +96,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-exchange-stats-and-dedup', '0 1 * * *', {
priority: 7,
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;
@ -112,7 +110,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-symbol-info-updates', '0 */6 * * *', {
priority: 7,
immediately: false,
description: 'Check for symbols needing info updates every 6 hours'
description: 'Check for symbols needing info updates every 6 hours',
})
scheduleSymbolInfoUpdates = scheduleSymbolInfoUpdates;
@ -126,7 +124,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-financials-updates', '0 2 * * *', {
priority: 6,
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;
@ -140,7 +138,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-events-updates', '0 3 * * *', {
priority: 6,
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;
@ -154,7 +152,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-price-updates', '0 */6 * * *', {
priority: 8,
immediately: false,
description: 'Check for symbols needing price updates every 6 hours'
description: 'Check for symbols needing price updates every 6 hours',
})
schedulePriceUpdates = schedulePriceUpdates;
@ -171,11 +169,11 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-intraday-crawls-batch', '0 0 * * 0', {
priority: 5,
immediately: false,
description: 'Schedule intraday crawls for incomplete symbols every 12 hours'
description: 'Schedule intraday crawls for incomplete symbols every 12 hours',
})
scheduleIntradayCrawlsBatch = async () => {
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', {
priority: 5,
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;
@ -206,7 +204,7 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('schedule-symbol-news-updates', '0 5 * * 1', {
priority: 4,
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;
@ -214,16 +212,16 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
@ScheduledOperation('update-general-news-frequent', '*/1 * * * *', {
priority: 9,
immediately: true,
description: 'Update general market news every minute'
description: 'Update general market news every minute',
})
updateGeneralNewsFrequent = async () => {
return updateGeneralNews.call(this, {
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
*/
// @Operation('update-filings')
@ -236,4 +234,4 @@ export class QMHandler extends BaseHandler<DataIngestionServices> {
// description: 'Check for symbols needing filings updates every 8 hours'
// })
// 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
*/
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
@ -13,69 +19,69 @@ export const QM_OPERATIONS: OperationConfig[] = [
name: 'symbol_info',
type: 'standard',
description: 'Update symbol metadata',
defaultStaleHours: 24 * 7 // Weekly
defaultStaleHours: 24 * 7, // Weekly
},
// Price data
{
name: 'price_update',
type: 'standard',
description: 'Update daily price data',
defaultStaleHours: 24
defaultStaleHours: 24,
},
{
name: 'intraday_bars',
type: 'intraday_crawl',
description: 'Crawl intraday price bars from today backwards',
requiresFinishedFlag: true,
defaultStaleHours: 1 // Check every hour for new data
defaultStaleHours: 1, // Check every hour for new data
},
// Fundamental data
{
name: 'financials_update_quarterly',
type: 'standard',
description: 'Update quarterly financial statements',
defaultStaleHours: 24 * 7 // Weekly
defaultStaleHours: 24 * 7, // Weekly
},
{
name: 'financials_update_annual',
type: 'standard',
description: 'Update annual financial statements',
defaultStaleHours: 24 * 7 // Weekly
defaultStaleHours: 24 * 7, // Weekly
},
// Corporate actions
{
name: 'events_update',
type: 'standard',
description: 'Update events (earnings, dividends, splits)',
defaultStaleHours: 24 * 7 // Weekly
defaultStaleHours: 24 * 7, // Weekly
},
// Filings
{
name: 'filings_update',
type: 'standard',
description: 'Update SEC filings',
defaultStaleHours: 24 // Daily
defaultStaleHours: 24, // Daily
},
// Insider trading
{
name: 'insiders_update',
type: 'standard',
description: 'Update insider transactions',
defaultStaleHours: 24 * 7 // Weekly
defaultStaleHours: 24 * 7, // Weekly
},
// News
{
name: 'news_update',
type: 'standard',
description: 'Update symbol-specific news',
defaultStaleHours: 24 * 7 // Weekly
}
defaultStaleHours: 24 * 7, // Weekly
},
];
/**
@ -87,7 +93,7 @@ export class QMOperationProvider extends BaseOperationProvider {
name: 'qm',
collectionName: 'qmSymbols',
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
*/
export async function createQMOperationRegistry(
mongodb: any,
logger: any
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 QMOperationProvider({ mongodb, logger });
await registry.registerProvider(provider);
return registry;
}
}

View file

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

View file

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

View file

@ -12,6 +12,37 @@ export interface QMSession {
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 {
prefix: string | null; // null = root job (A-Z)
depth: number; // 1=A, 2=AA, 3=AAA, etc.
@ -62,4 +93,4 @@ export interface ExchangeStats {
symbolCount: number;
totalMarketCap: number;
avgMarketCap: number;
}
}

View file

@ -1,3 +1,4 @@
import { at } from '@stock-bot/invariants';
import type { TeHandler } from '../te.handler';
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 staleUrls = await mongodb?.find('teUrls', {
$or: [
{ lastCrawled: { $exists: false } },
{ lastCrawled: { $lt: cutoff } }
],
skipReason: { $exists: false }
}, {
sort: { lastCrawled: 1 },
projection: { url: 1 }
});
const staleUrls = await mongodb?.find(
'teUrls',
{
$or: [{ lastCrawled: { $exists: false } }, { lastCrawled: { $lt: cutoff } }],
skipReason: { $exists: false },
},
{
sort: { lastCrawled: 1 },
projection: { url: 1 },
}
);
if (!staleUrls?.length) {
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`);
for (let i = 0; i < staleUrls.length; i++) {
const { url } = staleUrls[i];
await this.scheduleOperation('te-spider', { url }, {
jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 8,
delay: i * 200
});
const { url } = at(staleUrls, i);
await this.scheduleOperation(
'te-spider',
{ url },
{
jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 8,
delay: i * 200,
}
);
}
return { scheduled: staleUrls.length };

View file

@ -5,13 +5,18 @@ import type { TeHandler } from '../te.handler';
export async function dataFetch(
this: TeHandler,
payload: TeDataFetchPayload,
payload: TeDataFetchPayload
): Promise<{ success: boolean; recordCount: number }> {
const { logger, mongodb, http, proxy } = this;
const { teSymbol, url, isInitialFetch } = payload;
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})`);
return { success: false, recordCount: 0 };
}
@ -23,7 +28,9 @@ export async function dataFetch(
}
// 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) {
cdnUrl.searchParams.set('span', 'max');
}
@ -34,7 +41,7 @@ export async function dataFetch(
const response = await http.get(cdnUrl.toString(), {
proxy: proxy?.getProxy(),
headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
});
if (!response.ok) {
@ -54,61 +61,35 @@ export async function dataFetch(
if (!serie?.data?.length) {
logger.warn(`No data points decoded for ${teSymbol}`);
await mongodb?.updateOne('teUrls', { url }, {
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 0,
},
});
await mongodb?.updateOne(
'teUrls',
{ url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 0,
},
}
);
return { success: true, recordCount: 0 };
}
// 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 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) {
// Initial: upsert the full document
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 });
} 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 }, {
await mongodb?.updateOne(
'teData',
{ teSymbol },
{
$set: {
teSymbol,
name: serie.name,
@ -122,19 +103,72 @@ export async function dataFetch(
lastUpdated: 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;
await mongodb?.updateOne('teUrls', { url }, {
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: totalPoints,
},
});
await mongodb?.updateOne(
'teUrls',
{ url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: totalPoints,
},
}
);
return { success: true, recordCount: totalPoints };
}

View file

@ -1,5 +1,5 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';
@ -10,7 +10,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number }
proxy: proxy?.getProxy(),
headers: {
'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',
},
});
@ -40,6 +40,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number }
logger.info(`Found ${countries.size} countries`);
const docs = Array.from(countries.entries()).map(([slug, name]) => ({
source: 'te',
slug,
name,
url: `/${slug}`,

View file

@ -1,5 +1,5 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';
@ -12,7 +12,7 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
proxy: proxy?.getProxy(),
headers: {
'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',
},
});
@ -28,20 +28,27 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
$('li.list-group-item.active').each((_, groupEl) => {
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) => {
if ($(li).hasClass('active')) return false; // next group
const $a = $(li).find('a[href*="/country-list/"]');
if ($a.length) {
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 });
$(groupEl)
.nextAll('li.list-group-item')
.each((_, li) => {
if ($(li).hasClass('active')) {
return false;
} // next group
const $a = $(li).find('a[href*="/country-list/"]');
if ($a.length) {
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) {
@ -50,7 +57,11 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
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`);
return { count: indicators.length };

View file

@ -24,16 +24,16 @@ interface MkDataPoint {
async function fetchMkSerie(
handler: TeHandler,
cdnBase: string,
params: Record<string, string>,
params: Record<string, string>
): Promise<TeMkCdnSerie | null> {
const url = new URL(cdnBase);
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v);
}
const response = await handler.http.get(url.toString(), {
const response = await handler.fetchMarketSeries(url.toString(), {
proxy: handler.proxy?.getProxy(),
headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT },
});
if (!response.ok) {
@ -41,18 +41,31 @@ async function fetchMkSerie(
}
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);
return decoded?.series?.[0] ?? null;
}
function toPoints(data: any[]): MkDataPoint[] {
return data.map(([t, _c, pc, ac, o, h, l, c]: number[]) => ({ t, o, h, l, c, pc, ac }));
function toPoints(data: TeMkCdnSerie['data']): MkDataPoint[] {
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[] {
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) {
map.set(p.t, p);
}
@ -61,7 +74,7 @@ function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPo
export async function marketDataFetch(
this: TeHandler,
payload: TeMarketDataFetchPayload,
payload: TeMarketDataFetchPayload
): Promise<{ success: boolean; recordCount: number }> {
const { logger, mongodb } = this;
const { teSymbol, symbolType, url, isInitialFetch } = payload;
@ -94,39 +107,62 @@ export async function marketDataFetch(
if (!daily.length && !monthly.length) {
logger.warn(`No data points decoded for ${teSymbol}:${symbolType}`);
await mongodb?.updateOne('teUrls', { url }, {
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: 0 },
});
await mongodb?.updateOne(
'teUrls',
{ url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 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 }, {
$set: {
teSymbol,
name: serie?.name,
fullName: serie?.full_name,
unit: serie?.unit,
type: serie?.type,
category,
symbolType,
ticker: serie?.ticker,
sector: serie?.sector,
industry: serie?.industry,
frequency: serie?.frequency,
daily,
monthly,
lastUpdated: new Date(),
await mongodb?.updateOne(
'teMarketData',
{ teSymbol },
{
$set: {
teSymbol,
name: serie?.name,
fullName: serie?.full_name,
unit: serie?.unit,
type: serie?.type,
category,
symbolType,
ticker: serie?.ticker,
sector: serie?.sector,
industry: serie?.industry,
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;
await mongodb?.updateOne('teUrls', { url }, {
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: totalPoints },
});
await mongodb?.updateOne(
'teUrls',
{ url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: totalPoints,
},
}
);
return { success: true, recordCount: totalPoints };
}
@ -146,13 +182,25 @@ export async function marketDataFetch(
const merged = existing?.daily ? mergePoints(existing.daily, incoming) : incoming;
await mongodb?.updateOne('teMarketData', { teSymbol }, {
$set: { daily: merged, lastUpdated: new Date() },
});
await mongodb?.updateOne(
'teMarketData',
{ teSymbol },
{
$set: { daily: merged, lastUpdated: new Date() },
}
);
await mongodb?.updateOne('teUrls', { url }, {
$set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: merged.length },
});
await mongodb?.updateOne(
'teUrls',
{ url },
{
$set: {
lastDataFetch: new Date(),
lastDataFetchUpdate: teDoc.teLastUpdate,
lastDataFetchCount: 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 { at, getRandomUserAgent } from '@stock-bot/utils';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';
export async function spiderUrl(this: TeHandler, payload: { url: string }): Promise<string[] | null> {
const { logger, mongodb, proxy, http } = this;
export async function spiderUrl(
this: TeHandler,
payload: { url: string }
): Promise<string[] | null> {
const { logger, mongodb, proxy: _proxy, http: _http } = this;
const urlPath = payload?.url || '/';
const fullUrl = TE_CONFIG.MAIN_URL + urlPath;
// 1. Check if already crawled recently (30 days)
const record = await mongodb?.findOne('teUrls', { url: urlPath });
if (record?.lastCrawled) {
@ -17,7 +20,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
return null;
}
}
// 2. Fetch the page
logger.info(`Crawling ${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(
'teUrls',
{ url: urlPath },
{
$set: {
{
$set: {
lastCrawled: new Date(),
foundLinks: 0,
error: true
}
error: true,
},
},
{ upsert: true }
);
return null;
}
// 3. Extract TE data from the HTML
let match = html.match(/var TESymbol = '([^']+)'/);
const teSymbol = match ? match[1] : undefined;
match = html.match(/TELastUpdate = '([^']+)'/);
const teLastUpdate = match ? match[1] : undefined;
match = html.match(/TEChart = '([^']+)'/);
const teChart = match ? match[1] : undefined;
match = html.match(/var TEAlertsName\s*=\s*'([^']+)'/);
const teAlertsName = match ? match[1] : undefined;
// Extract from script tags - these appear after TEChartUrl
match = html.match(/TEChartUrl = '([^']+)'/);
const teChartUrl = match ? match[1] : undefined;
match = html.match(/TECountry = '([^']+)'/);
const teCountry = match ? match[1] : undefined;
match = html.match(/TECategory = '([^']+)'/);
const teCategory = match ? match[1] : undefined;
match = html.match(/TEType = '([^']+)'/);
const teType = match ? match[1] : undefined;
match = html.match(/TEFrequency = '([^']+)'/);
const teFrequency = match ? match[1] : undefined;
// Extract array data
match = html.match(/TEForecast\s*=\s*\[([^\]]+)\]/);
const teForecast = match ? JSON.parse('[' + match[1] + ']') : undefined;
// Extract JSON metadata - use a more flexible regex
match = html.match(/TEChartsMeta = (\[[\s\S]*?\]);/);
const teChartsMeta = match ? (() => {
try {
return JSON.parse(match[1]);
} catch (e) {
logger.warn('Failed to parse TEChartsMeta:', e);
return undefined;
}
})() : undefined;
const teChartsMeta = match
? (() => {
try {
return JSON.parse(at(match, 1));
} catch (e) {
logger.warn('Failed to parse TEChartsMeta', { error: e });
return undefined;
}
})()
: undefined;
// Extract symbol data
match = html.match(/symbol = '([^']+)'/);
const symbol = match ? match[1] : undefined;
match = html.match(/symbolType = '([^']+)'/);
const symbolType = match ? match[1] : undefined;
// TEChartsDatasource is the CDN URL for chart data
match = html.match(/; var TEChartsDatasource = '([^']+)'/);
const teChartsDatasource = match ? match[1] : undefined;
match = html.match(/; var TEChartsToken = '([^']+)'/);
const teChartToken = match ? match[1] : undefined;
// Log if we found any TE data
const foundData = teSymbol || teLastUpdate || teChartUrl || teChartsDatasource ||
teChartToken || teChart || teAlertsName || teCountry ||
teCategory || teType || teFrequency || teForecast ||
teChartsMeta || symbol || symbolType;
const foundData =
teSymbol ||
teLastUpdate ||
teChartUrl ||
teChartsDatasource ||
teChartToken ||
teChart ||
teAlertsName ||
teCountry ||
teCategory ||
teType ||
teFrequency ||
teForecast ||
teChartsMeta ||
symbol ||
symbolType;
if (foundData) {
logger.debug('Found TE data:', {
teSymbol,
teLastUpdate,
logger.debug('Found TE data:', {
teSymbol,
teLastUpdate,
teChart,
teAlertsName,
teChartUrl,
@ -119,32 +136,45 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
symbol,
symbolType,
teChartsDatasource,
teChartToken
teChartToken,
});
}
// 4. Extract all links
const $ = cheerio.load(html);
const foundUrls = new Set<string>();
// Add some seed URLs if this is the root page
if (urlPath === '/') {
const seedUrls = [
'/united-states', '/china', '/eurozone', '/japan', '/united-kingdom',
'/indicators', '/calendar', '/forecasts', '/countries',
'/gdp', '/inflation', '/unemployment', '/interest-rate',
'/stocks', '/bonds', '/commodity', '/currency'
'/united-states',
'/china',
'/eurozone',
'/japan',
'/united-kingdom',
'/indicators',
'/calendar',
'/forecasts',
'/countries',
'/gdp',
'/inflation',
'/unemployment',
'/interest-rate',
'/stocks',
'/bonds',
'/commodity',
'/currency',
];
seedUrls.forEach(url => foundUrls.add(url));
}
// Extract links from the page
$('a[href]').each((_, element) => {
const href = $(element).attr('href');
if (!href) {
return;
}
// Convert to absolute path
let path: string;
if (href.startsWith('/')) {
@ -158,27 +188,27 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
} else {
return; // Skip external links
}
// Clean the path
path = path.split('?')[0].split('#')[0];
path = at(at(path.split('?'), 0).split('#'), 0);
// Basic filtering
if (shouldCrawl(path)) {
foundUrls.add(path);
}
});
const urls = Array.from(foundUrls);
logger.info(`Found ${urls.length} URLs on ${urlPath}`);
// 5. Update database
// Mark current URL as crawled with TE data if found
const updateData: any = {
const updateData: Record<string, unknown> = {
lastCrawled: new Date(),
foundLinks: urls.length,
error: false
error: false,
};
// Add TE data if found
if (teSymbol) {
updateData.teSymbol = teSymbol;
@ -193,7 +223,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
updateData.teAlertsName = teAlertsName;
}
if (teChartUrl) {
updateData.teChartUrl = teChartUrl; // Full chart URL with PNG
updateData.teChartUrl = teChartUrl; // Full chart URL with PNG
}
if (teCountry) {
updateData.teCountry = teCountry;
@ -220,31 +250,26 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
updateData.symbolType = symbolType;
}
if (teChartsDatasource) {
updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data
updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data
}
if (teChartToken) {
updateData.teChartToken = teChartToken;
}
await mongodb?.updateOne(
'teUrls',
{ url: urlPath },
{ $set: updateData },
{ upsert: true }
);
await mongodb?.updateOne('teUrls', { url: urlPath }, { $set: updateData }, { upsert: true });
// Insert new URLs (without lastCrawled so they'll be picked up for crawling)
const newUrls: string[] = [];
for (const url of urls) {
const result = await mongodb?.updateOne(
'teUrls',
{ url },
{
$setOnInsert: {
url,
{
$setOnInsert: {
url,
createdAt: new Date(),
source: urlPath
}
source: urlPath,
},
},
{ upsert: true }
);
@ -253,55 +278,58 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
newUrls.push(url);
}
}
// 6. Schedule individual jobs for each new URL
logger.info(`Scheduling ${newUrls.length} new URLs for crawling`);
for (const url of newUrls) {
await this.scheduleOperation('te-spider', { url }, {
jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 10,
delay: Math.floor(Math.random() * 10000) // Spread requests over 10 seconds
});
await this.scheduleOperation(
'te-spider',
{ url },
{
jobId: `spider-${url.replace(/\//g, '-')}`,
priority: 10,
delay: Math.floor(Math.random() * 10000), // Spread requests over 10 seconds
}
);
}
return urls;
}
// Simple fetch with retry using http service with proxy
async function fetchPage(this: TeHandler, url: string): Promise<string | null> {
const { http, proxy, logger } = this;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
// Get a proxy URL for this request
const proxyUrl = proxy?.getProxy();
const response = await http.get(url, {
proxy: proxyUrl,
headers: {
'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-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0'
}
'Cache-Control': 'max-age=0',
},
});
if (response.ok) {
return await response.text();
}
// If not OK, log the status
logger.error(`HTTP ${response.status} for ${url}`);
} catch (error) {
logger.error(`Attempt ${attempt}/3 failed for ${url}:`, error);
if (attempt === 3) {
return null;
}
// Wait before retrying (exponential backoff)
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
@ -315,18 +343,20 @@ function shouldCrawl(url: string): boolean {
if (!url || url === '/') {
return false;
}
// 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;
}
// Skip deep URLs (more than 4 levels)
const depth = (url.match(/\//g) || []).length;
if (depth > 4) {
return false;
}
// Skip common non-content pages
const skipPatterns = [
/\/api\//,
@ -343,13 +373,13 @@ function shouldCrawl(url: string): boolean {
/\/rss\//,
/#/,
];
for (const pattern of skipPatterns) {
if (pattern.test(url)) {
return false;
}
}
// Accept everything else
return true;
}
}

View file

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

View file

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

View file

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

View file

@ -1,31 +1,27 @@
import {
BaseHandler,
Disabled,
Handler,
Operation,
ScheduledOperation,
} from '@stock-bot/handlers';
import { fetchExchanges } from './actions';
@Disabled()
@Handler('tradingview')
export class TradingViewHandler extends BaseHandler {
constructor(services: any) {
super(services);
}
@Operation('fetch-exchanges')
async fetchExchanges(): Promise<unknown[] | null> {
return fetchExchanges(this);
}
@ScheduledOperation('tradingview-exchanges', '0 0 * * 0', {
priority: 5,
description: 'Fetch and update TradingView exchanges data',
immediately: false,
})
@Disabled()
async scheduledFetchExchanges(): Promise<unknown> {
return this.fetchExchanges();
}
}
import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers';
import type { IServiceContainer } from '@stock-bot/services';
import { resolveIngestionServices } from '../../types';
import { fetchExchanges } from './actions';
@Disabled()
@Handler('tradingview')
export class TradingViewHandler extends BaseHandler {
constructor(services: IServiceContainer) {
super(resolveIngestionServices(services, 'tradingview'));
}
@Operation('fetch-exchanges')
async fetchExchanges(): Promise<unknown[] | null> {
return fetchExchanges(this);
}
@ScheduledOperation('tradingview-exchanges', '0 0 * * 0', {
priority: 5,
description: 'Fetch and update TradingView exchanges data',
immediately: false,
})
@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 { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'fs';
import { join } from 'path';
import * as cheerio from 'cheerio';
import { defined } from '@stock-bot/invariants';
import { getRandomUserAgent } from '@stock-bot/utils';
import type { TtHandler } from '../tt.handler';
const BASE_URL = 'https://www.turtletrader.com';
const TMP_DIR = '/tmp/tt';
const MONTH_MAP: Record<string, string> = {
F: '01', G: '02', H: '03', J: '04', K: '05', M: '06',
N: '07', Q: '08', U: '09', V: '10', X: '11', Z: '12',
const _MONTH_MAP: Record<string, string> = {
F: '01',
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 {
@ -40,7 +51,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
$('a[href$=".zip"]').each((_, el) => {
const href = $(el).attr('href') || '';
const name = $(el).text().trim();
if (href) zipLinks.push({ href, name });
if (href) {
zipLinks.push({ href, name });
}
});
if (!zipLinks.length) {
@ -60,7 +73,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
try {
for (const { href, name } of zipLinks) {
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 extractDir = join(TMP_DIR, symbol);
@ -84,7 +97,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
// Parse each txt file
const files = readdirSync(extractDir).filter(f => f.endsWith('.txt'));
const records: any[] = [];
const records = [];
for (const file of files) {
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')) {
const trimmed = line.trim();
if (!trimmed) continue;
if (!trimmed) {
continue;
}
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({
source: 'tt',
contract,
symbol: sym,
name,
@ -128,7 +154,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe
if (records.length) {
await mongodb?.batchUpsert('ttFutures', records, ['contract', 'date']);
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

View file

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

View file

@ -5,7 +5,7 @@
import { ServiceApplication } from '@stock-bot/di';
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';
// Local imports
import { initializeAllHandlers } from './handlers';
@ -49,11 +49,11 @@ const app = new ServiceApplication(
);
// 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 container = await new ServiceContainerBuilder()
.withConfig(config)
.withConfig({ ...config, ...baseConfig })
.withOptions({
enableQuestDB: false, // Data ingestion doesn't need QuestDB yet
enableMongoDB: true,

View file

@ -21,17 +21,9 @@ export function createRoutes(services: IServiceContainer): Hono {
app.route('/api/exchanges', exchangeRoutes);
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
app.get('/api/di-test', async c => {
try {
const services = c.get('services') as IServiceContainer;
// Test MongoDB connection
const mongoStats = services.mongodb?.getPoolMetrics?.() || {
status: services.mongodb ? 'connected' : 'disabled',
@ -44,7 +36,7 @@ export function createRoutes(services: IServiceContainer): Hono {
const cacheReady = services.cache?.isReady() || false;
// Test queue
const queueStats = services.queue?.getGlobalStats() || { status: 'disabled' };
const queueStats = (await services.queueManager?.getGlobalStats()) || { status: 'disabled' };
return c.json({
success: true,
@ -58,7 +50,6 @@ export function createRoutes(services: IServiceContainer): Hono {
timestamp: new Date().toISOString(),
});
} catch (error) {
const services = c.get('services') as IServiceContainer;
services.logger.error('DI test endpoint failed', { error });
return c.json(
{

View file

@ -1,13 +1,14 @@
import type { Document } from 'mongodb';
/**
* Base class for operation providers
*/
import type { Logger, MongoDBClient } from '@stock-bot/services';
import type {
OperationConfig,
OperationUpdate,
import type {
OperationComponentOptions,
OperationConfig,
OperationUpdate,
ProviderConfig,
OperationComponentOptions
} from './types';
/**
@ -42,10 +43,10 @@ export abstract class BaseOperationProvider {
}
this.logger.info(`Initializing ${this.getProviderConfig().name} operation provider`);
// Allow providers to perform custom initialization
await this.onInitialize();
this._initialized = true;
}
@ -78,16 +79,16 @@ export abstract class BaseOperationProvider {
/**
* Get the symbol identifier value from a document
*/
getSymbolIdentifier(doc: any): string {
getSymbolIdentifier(doc: Document): string {
const { symbolField } = this.getProviderConfig();
const value = doc[symbolField];
if (!value) {
throw new Error(
`Symbol field '${symbolField}' not found in document for provider '${this.getProviderConfig().name}'`
);
}
return value;
}
@ -110,9 +111,9 @@ export abstract class BaseOperationProvider {
* Hook called before operation update (optional override)
*/
async beforeOperationUpdate(
symbol: string,
operation: string,
data: OperationUpdate
_symbol: string,
_operation: string,
_data: OperationUpdate
): Promise<void> {
// Providers can override this for custom logic
}
@ -121,9 +122,9 @@ export abstract class BaseOperationProvider {
* Hook called after operation update (optional override)
*/
async afterOperationUpdate(
symbol: string,
operation: string,
data: OperationUpdate
_symbol: string,
_operation: string,
_data: OperationUpdate
): Promise<void> {
// Providers can override this for custom logic
}
@ -157,7 +158,7 @@ export abstract class BaseOperationProvider {
logInfo(): void {
const config = this.getProviderConfig();
const operations = this.getOperations();
this.logger.info(`Provider: ${config.name}`, {
provider: config.name,
collection: config.collectionName,
@ -166,8 +167,8 @@ export abstract class BaseOperationProvider {
operations: operations.map(op => ({
name: op.name,
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
*/
import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import { BaseOperationProvider } from './BaseOperationProvider';
import { OperationTracker } from './OperationTracker';
import type {
@ -10,7 +12,7 @@ import type {
OperationConfig,
OperationStats,
OperationUpdate,
StaleSymbolOptions
StaleSymbolOptions,
} from './types';
/**
@ -45,7 +47,7 @@ export class OperationRegistry {
*/
async registerProvider(provider: BaseOperationProvider): Promise<void> {
const config = provider.getProviderConfig();
if (this.providers.has(config.name)) {
throw new Error(`Provider '${config.name}' is already registered`);
}
@ -56,11 +58,8 @@ export class OperationRegistry {
this.providers.set(config.name, provider);
// Create and initialize tracker
const tracker = new OperationTracker(
{ mongodb: this.mongodb, logger: this.logger },
provider
);
const tracker = new OperationTracker({ mongodb: this.mongodb, logger: this.logger }, provider);
await tracker.initialize();
this.trackers.set(config.name, tracker);
@ -85,7 +84,7 @@ export class OperationRegistry {
this.logger.info('Operation registry initialized', {
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,
operationName: string,
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);
return tracker.getStaleSymbols(operationName, options);
}
@ -154,10 +160,7 @@ export class OperationRegistry {
/**
* Get operation statistics
*/
async getOperationStats(
providerName: string,
operationName: string
): Promise<OperationStats> {
async getOperationStats(providerName: string, operationName: string): Promise<OperationStats> {
const tracker = this.getTracker(providerName);
return tracker.getOperationStats(operationName);
}
@ -183,7 +186,7 @@ export class OperationRegistry {
getAllOperations(): Array<{ provider: string; operations: OperationConfig[] }> {
return Array.from(this.providers.entries()).map(([name, provider]) => ({
provider: name,
operations: provider.getOperations()
operations: provider.getOperations(),
}));
}
@ -209,15 +212,15 @@ export class OperationRegistry {
const operations = provider.getOperations();
const operationStats = await Promise.all(
operations.map(async (op) => ({
operations.map(async op => ({
name: op.name,
stats: await tracker.getOperationStats(op.name)
stats: await tracker.getOperationStats(op.name),
}))
);
return {
provider: providerName,
operations: operationStats
operations: operationStats,
};
}
@ -235,15 +238,16 @@ export class OperationRegistry {
}>;
}> {
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 tracker = this.getTracker(providerName);
const operations = provider.getOperations();
// Get stats for first operation to get total symbols
const firstOpStats = operations.length > 0
? await tracker.getOperationStats(operations[0].name)
: { totalSymbols: 0, processedSymbols: 0 };
const firstOpStats =
operations.length > 0
? await tracker.getOperationStats(at(operations, 0).name)
: { totalSymbols: 0, processedSymbols: 0 };
// Sum processed symbols across all operations
let totalProcessed = 0;
@ -256,16 +260,18 @@ export class OperationRegistry {
provider: providerName,
operationCount: operations.length,
totalSymbols: firstOpStats.totalSymbols,
totalProcessed: totalProcessed
totalProcessed: totalProcessed,
};
})
);
return {
totalProviders: this.providers.size,
totalOperations: Array.from(this.providers.values())
.reduce((sum, p) => sum + p.getOperations().length, 0),
providerStats
totalOperations: Array.from(this.providers.values()).reduce(
(sum, p) => sum + p.getOperations().length,
0
),
providerStats,
};
}
@ -279,9 +285,8 @@ export class OperationRegistry {
const results: Array<{ provider: string; operation: OperationConfig }> = [];
for (const [providerName, provider] of this.providers) {
const operations = provider.getOperations()
.filter(op => op.type === type);
const operations = provider.getOperations().filter(op => op.type === type);
operations.forEach(operation => {
results.push({ provider: providerName, operation });
});
@ -297,7 +302,7 @@ export class OperationRegistry {
providerName: string,
operationName: string,
options?: StaleSymbolOptions
): Promise<Array<{ symbol: string; metadata?: any }>> {
): Promise<Array<{ symbol: string; metadata?: unknown }>> {
const provider = this.getProvider(providerName);
const tracker = this.getTracker(providerName);
const { collectionName, symbolField } = provider.getProviderConfig();
@ -310,16 +315,20 @@ export class OperationRegistry {
}
// Get full symbol data for scheduling
const symbols = await this.mongodb.find(collectionName, {
[symbolField]: { $in: staleSymbols }
}, {
projection: {
[symbolField]: 1,
symbol: 1,
exchange: 1,
// Include any other fields needed for scheduling
const symbols = await this.mongodb.find(
collectionName,
{
[symbolField]: { $in: staleSymbols },
},
{
projection: {
[symbolField]: 1,
symbol: 1,
exchange: 1,
// Include any other fields needed for scheduling
},
}
});
);
return symbols.map(doc => ({
symbol: doc[symbolField],
@ -327,7 +336,7 @@ export class OperationRegistry {
symbol: doc.symbol,
exchange: doc.exchange,
// 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
*/
import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import type { BaseOperationProvider } from './BaseOperationProvider';
import type {
BulkOperationUpdate,
@ -11,7 +13,7 @@ import type {
OperationStats,
OperationUpdate,
StaleSymbolOptions,
SymbolWithOperations
SymbolWithOperations,
} from './types';
/**
@ -23,10 +25,7 @@ export class OperationTracker {
private provider: BaseOperationProvider;
private indexesCreated: Set<string> = new Set();
constructor(
{ mongodb, logger }: OperationComponentOptions,
provider: BaseOperationProvider
) {
constructor({ mongodb, logger }: OperationComponentOptions, provider: BaseOperationProvider) {
this.mongodb = mongodb;
this.logger = logger;
this.provider = provider;
@ -49,7 +48,7 @@ export class OperationTracker {
}
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> {
const { collectionName, symbolField } = this.provider.getProviderConfig();
if (this.indexesCreated.has(operation.name)) {
return;
}
@ -66,61 +65,67 @@ export class OperationTracker {
try {
const indexes = [
// Index for finding stale symbols
{
[`operations.${operation.name}.lastSuccessAt`]: 1,
[symbolField]: 1
{
[`operations.${operation.name}.lastSuccessAt`]: 1,
[symbolField]: 1,
},
// Index for finding by last record date
{
[`operations.${operation.name}.lastRecordDate`]: 1,
[symbolField]: 1
{
[`operations.${operation.name}.lastRecordDate`]: 1,
[symbolField]: 1,
},
// Index for operation status
{
[`operations.${operation.name}.status`]: 1,
[symbolField]: 1
}
{
[`operations.${operation.name}.status`]: 1,
[symbolField]: 1,
},
];
// Add crawl-specific indexes for crawl operations
if (operation.type === 'crawl' || operation.type === 'intraday_crawl') {
indexes.push(
{
[`operations.${operation.name}.finished`]: 1,
[symbolField]: 1
{
[`operations.${operation.name}.finished`]: 1,
[symbolField]: 1,
},
{
[`operations.${operation.name}.newestDateReached`]: 1,
[symbolField]: 1
[symbolField]: 1,
},
{
[`operations.${operation.name}.oldestDateReached`]: 1,
[symbolField]: 1
[symbolField]: 1,
}
);
}
const collection = this.mongodb.collection(collectionName);
for (const indexSpec of indexes) {
try {
await collection.createIndex(indexSpec, {
background: true,
name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}`
name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}`,
});
} catch (indexError) {
// 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`, {
operation: operation.name,
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
this.logger.debug(`Index already exists`, {
operation: operation.name,
index: Object.keys(indexSpec).join('_')
index: Object.keys(indexSpec).join('_'),
});
} else {
throw indexError;
@ -129,16 +134,16 @@ export class OperationTracker {
}
this.indexesCreated.add(operation.name);
this.logger.debug(`Created indexes for operation: ${operation.name}`, {
provider: this.provider.getProviderConfig().name,
operation: operation.name,
indexCount: indexes.length
indexCount: indexes.length,
});
} catch (error) {
this.logger.error(`Failed to create indexes for operation: ${operation.name}`, {
error,
provider: this.provider.getProviderConfig().name
provider: this.provider.getProviderConfig().name,
});
throw error;
}
@ -153,19 +158,19 @@ export class OperationTracker {
data: OperationUpdate
): Promise<void> {
const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();
// Validate operation exists
this.provider.validateOperation(operationName);
// Call before hook
await this.provider.beforeOperationUpdate(symbol, operationName, data);
const update: any = {
const update: Document = {
$set: {
[`operations.${operationName}.lastRunAt`]: new Date(),
[`operations.${operationName}.status`]: data.status,
updated_at: new Date()
}
updated_at: new Date(),
},
};
// Only update lastSuccessAt on successful operations
@ -217,7 +222,7 @@ export class OperationTracker {
filter: { [symbolField]: symbol },
symbolField,
symbol,
operation: operationName
operation: operationName,
});
const updateResult = await this.mongodb.updateOne(
@ -230,7 +235,7 @@ export class OperationTracker {
matched: updateResult.matchedCount,
modified: updateResult.modifiedCount,
symbol,
operation: operationName
operation: operationName,
});
// Call after hook
@ -240,7 +245,7 @@ export class OperationTracker {
provider: providerName,
symbol,
operation: operationName,
status: data.status
status: data.status,
});
}
@ -248,7 +253,9 @@ export class OperationTracker {
* Bulk update symbol operations for performance
*/
async bulkUpdateSymbolOperations(updates: BulkOperationUpdate[]): Promise<void> {
if (updates.length === 0) {return;}
if (updates.length === 0) {
return;
}
const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();
@ -256,7 +263,7 @@ export class OperationTracker {
const operationGroups = new Map<string, BulkOperationUpdate[]>();
for (const update of updates) {
this.provider.validateOperation(update.operation);
const group = operationGroups.get(update.operation) || [];
group.push(update);
operationGroups.set(update.operation, group);
@ -269,12 +276,12 @@ export class OperationTracker {
// Build bulk operations
const bulkOps = updates.map(({ symbol, operation, data }) => {
const update: any = {
const update: Document = {
$set: {
[`operations.${operation}.lastRunAt`]: new Date(),
[`operations.${operation}.status`]: data.status,
updated_at: new Date()
}
updated_at: new Date(),
},
};
if (data.status === 'success') {
@ -323,8 +330,8 @@ export class OperationTracker {
return {
updateOne: {
filter: { [symbolField]: symbol },
update
}
update,
},
};
});
@ -340,7 +347,7 @@ export class OperationTracker {
provider: providerName,
totalUpdates: updates.length,
modified: result.modifiedCount,
operations: Array.from(operationGroups.keys())
operations: Array.from(operationGroups.keys()),
});
}
@ -350,32 +357,41 @@ export class OperationTracker {
async getStaleSymbols(
operationName: string,
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 {
limit = 1000,
excludeSymbols = [],
const {
limit = 1000,
excludeSymbols = [],
activeOnly = true,
symbolFilter,
exchanges,
delisted
delisted,
} = options;
this.provider.validateOperation(operationName);
const cutoffDate = options.notRunSince || (() => {
const date = new Date();
const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName);
date.setHours(date.getHours() - hours);
return date;
})();
const cutoffDate =
options.notRunSince ||
(() => {
const date = new Date();
const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName);
date.setHours(date.getHours() - hours);
return date;
})();
const filter: any = {
const filter: Filter<Document> = {
$or: [
{ [`operations.${operationName}.lastSuccessAt`]: { $lt: cutoffDate } },
{ [`operations.${operationName}.lastSuccessAt`]: { $exists: false } },
{ [`operations.${operationName}`]: { $exists: false } }
]
{ [`operations.${operationName}`]: { $exists: false } },
],
};
if (activeOnly) {
@ -403,15 +419,15 @@ export class OperationTracker {
const symbols = await this.mongodb.find(collectionName, filter, {
limit,
projection: { }, // Return all fields
sort: { [`operations.${operationName}.lastSuccessAt`]: 1 }
projection: {}, // Return all fields
sort: { [`operations.${operationName}.lastSuccessAt`]: 1 },
});
return symbols.map(doc => ({
symbol: doc,
lastRun: doc.operations?.[operationName]?.lastRunAt,
lastSuccess: doc.operations?.[operationName]?.lastSuccessAt,
operations: doc.operations
operations: doc.operations,
}));
}
@ -430,8 +446,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName);
const filter: any = {
active: { $ne: false }
const filter: Filter<Document> = {
active: { $ne: false },
};
if (!includeFinished) {
@ -442,17 +458,17 @@ export class OperationTracker {
limit,
projection: {
[symbolField]: 1,
[`operations.${operationName}`]: 1
[`operations.${operationName}`]: 1,
},
sort: {
[`operations.${operationName}.lastRunAt`]: 1
}
[`operations.${operationName}.lastRunAt`]: 1,
},
});
return symbols.map(doc => ({
symbol: doc[symbolField],
lastRecordDate: doc.operations?.[operationName]?.lastRecordDate,
operationStatus: doc.operations?.[operationName]
operationStatus: doc.operations?.[operationName],
}));
}
@ -469,7 +485,7 @@ export class OperationTracker {
status: 'success',
finished: true,
oldestDateReached,
newestDateReached: newestDateReached || new Date()
newestDateReached: newestDateReached || new Date(),
});
this.logger.info('Marked crawl as finished', {
@ -477,7 +493,7 @@ export class OperationTracker {
symbol,
operation: operationName,
oldestDateReached,
newestDateReached
newestDateReached,
});
}
@ -499,8 +515,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName);
// Build filter
const filter: any = {
active: { $ne: false }
const filter: Filter<Document> = {
active: { $ne: false },
};
// Add symbol filter if provided
@ -512,18 +528,18 @@ export class OperationTracker {
// 1. Have never been crawled
// 2. Are not finished
// 3. Have gaps (new data since last crawl)
const orConditions = [
const orConditions: Filter<Document>[] = [
{ [`operations.${operationName}`]: { $exists: false } },
{ [`operations.${operationName}.finished`]: { $ne: true } }
{ [`operations.${operationName}.finished`]: { $ne: true } },
];
if (includeNewDataGaps) {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
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
symbol: 1,
exchange: 1,
qmSearchCode: 1
qmSearchCode: 1,
},
sort: {
[`operations.${operationName}.lastRunAt`]: 1
}
[`operations.${operationName}.lastRunAt`]: 1,
},
});
return symbols.map(doc => {
const opStatus = doc.operations?.[operationName];
// Determine gaps (only backward since we removed forward crawling)
const gaps: { forward?: boolean; backward?: boolean } = {};
if (opStatus) {
// Only check for backward gap (historical data)
if (!opStatus.finished) {
@ -570,7 +586,7 @@ export class OperationTracker {
gaps,
// Include other potentially useful fields
exchange: doc.exchange,
qmSearchCode: doc.qmSearchCode || doc[symbolField]
qmSearchCode: doc.qmSearchCode || doc[symbolField],
} as SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } };
});
}
@ -584,19 +600,23 @@ export class OperationTracker {
targetOldestDate: Date
): Promise<boolean> {
const { collectionName, symbolField } = this.provider.getProviderConfig();
const doc = await this.mongodb.findOne(collectionName, {
[symbolField]: symbol
}, {
projection: { [`operations.${operationName}`]: 1 }
});
const doc = await this.mongodb.findOne(
collectionName,
{
[symbolField]: symbol,
},
{
projection: { [`operations.${operationName}`]: 1 },
}
);
if (!doc?.operations?.[operationName]) {
return false;
}
const opStatus = doc.operations[operationName];
// Check if explicitly marked as finished
if (opStatus.finished) {
return true;
@ -626,8 +646,8 @@ export class OperationTracker {
this.provider.validateOperation(operationName);
const filter: any = {
active: { $ne: false }
const filter: Filter<Document> = {
active: { $ne: false },
};
if (options.neverRun) {
@ -635,7 +655,7 @@ export class OperationTracker {
} else if (options.lastRecordBefore) {
filter.$or = [
{ [`operations.${operationName}.lastRecordDate`]: { $lt: options.lastRecordBefore } },
{ [`operations.${operationName}`]: { $exists: false } }
{ [`operations.${operationName}`]: { $exists: false } },
];
}
@ -644,15 +664,15 @@ export class OperationTracker {
projection: {
[symbolField]: 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 => ({
symbol: doc[symbolField],
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> {
const { collectionName } = this.provider.getProviderConfig();
const operation = this.provider.getOperation(operationName);
if (!operation) {
throw new Error(`Unknown operation: ${operationName}`);
}
const collection = this.mongodb.collection(collectionName);
const [
total,
processed,
successful,
failed,
staleStats,
crawlStats,
recordStats
] = await Promise.all([
// Total symbols
collection.countDocuments({}),
// Processed symbols
collection.countDocuments({
[`operations.${operationName}`]: { $exists: true }
}),
// Successful symbols
collection.countDocuments({
[`operations.${operationName}.status`]: 'success'
}),
// Failed symbols
collection.countDocuments({
[`operations.${operationName}.status`]: 'failure'
}),
// Stale symbols
this.countStaleSymbols(operationName, operation.defaultStaleHours || 24),
// Crawl stats (if applicable)
(operation.type === 'crawl' || operation.type === 'intraday_crawl')
? collection.countDocuments({
[`operations.${operationName}.finished`]: true
})
: Promise.resolve(undefined),
// Average records
this.calculateAverageRecords(operationName)
]);
const [total, processed, successful, failed, staleStats, crawlStats, recordStats] =
await Promise.all([
// Total symbols
collection.countDocuments({}),
// Processed symbols
collection.countDocuments({
[`operations.${operationName}`]: { $exists: true },
}),
// Successful symbols
collection.countDocuments({
[`operations.${operationName}.status`]: 'success',
}),
// Failed symbols
collection.countDocuments({
[`operations.${operationName}.status`]: 'failure',
}),
// Stale symbols
this.countStaleSymbols(operationName, operation.defaultStaleHours || 24),
// Crawl stats (if applicable)
operation.type === 'crawl' || operation.type === 'intraday_crawl'
? collection.countDocuments({
[`operations.${operationName}.finished`]: true,
})
: Promise.resolve(undefined),
// Average records
this.calculateAverageRecords(operationName),
]);
const result: OperationStats = {
totalSymbols: total,
processedSymbols: processed,
staleSymbols: staleStats,
successfulSymbols: successful,
failedSymbols: failed
failedSymbols: failed,
};
if (crawlStats !== undefined) {
@ -735,15 +748,15 @@ export class OperationTracker {
private async countStaleSymbols(operationName: string, staleHours: number): Promise<number> {
const { collectionName } = this.provider.getProviderConfig();
const collection = this.mongodb.collection(collectionName);
const staleDate = new Date();
staleDate.setHours(staleDate.getHours() - staleHours);
return collection.countDocuments({
$or: [
{ [`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> {
const { collectionName } = this.provider.getProviderConfig();
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) {
return Math.round(aggregation[0].avgRecords);
const aggregation = await collection
.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;

View file

@ -21,7 +21,7 @@ export interface OperationConfig {
/** Whether operation requires a finished flag (for crawl operations) */
requiresFinishedFlag?: boolean;
/** 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?: string;
/** Provider-specific metadata */
metadata?: Record<string, any>;
metadata?: Record<string, unknown>;
// Crawl-specific fields (used for crawl and intraday_crawl operations)
/** Whether the crawl has completed */
finished?: boolean;
@ -89,8 +89,8 @@ export interface OperationUpdate {
/** Error message for failures */
error?: string;
/** Additional metadata */
metadata?: Record<string, any>;
metadata?: Record<string, unknown>;
// Crawl-specific update fields
/** Whether the crawl has completed */
finished?: boolean;
@ -161,7 +161,7 @@ export interface OperationStats {
/** Average records per symbol */
avgRecordsPerSymbol?: number;
/** Additional provider-specific stats */
customStats?: Record<string, any>;
customStats?: Record<string, unknown>;
}
/**
@ -175,7 +175,7 @@ export interface SymbolWithOperations {
/** Full operation status */
operationStatus?: OperationStatus;
/** 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
* Defines required services for data ingestion handlers
@ -19,7 +20,22 @@ export type DataIngestionServices = ServiceTypes & {
browser: NonNullable<ServiceTypes['browser']>;
proxy: NonNullable<ServiceTypes['proxy']>;
// Optional services remain optional
postgres: ServiceTypes['postgres'];
questdb: ServiceTypes['questdb'];
globalCache: ServiceTypes['globalCache'];
postgres?: ServiceTypes['postgres'];
questdb?: ServiceTypes['questdb'];
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
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('test-advanced-rate-limit');
async function testAdvancedRateLimits() {
logger.info('Testing advanced rate limit features...');
const baseUrl = 'http://localhost:3001/api';
logger.info('\n📋 Rate Limit Configuration:');
logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day');
logger.info('fetch-daily-prices: 1 point per call');
logger.info('fetch-fundamentals: 10 points per call');
logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)');
// First test: test-burst operation
logger.info('\n🚀 Testing burst operation with mixed costs...');
const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'],
burstSize: 30
})
});
const burstResult = await burstResponse.json();
logger.info('Burst test result:', burstResult);
// Wait for jobs to process
logger.info('\n⏳ Waiting 10 seconds for jobs to process...');
await new Promise(resolve => setTimeout(resolve, 10000));
// Test individual operations with different costs
logger.info('\n📊 Testing individual operations:');
// Test cheap operation (1 point)
logger.info('\n1️⃣ Testing fetch-daily-prices (1 point each)...');
for (let i = 0; i < 5; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i })
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test medium cost operation (10 points)
logger.info('\n🔟 Testing fetch-fundamentals (10 points each)...');
for (let i = 0; i < 3; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i })
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test expensive operation (50 points)
logger.info('\n💰 Testing fetch-news (50 points each, custom limits)...');
for (let i = 0; i < 2; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i })
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
logger.info('\n✅ Test completed!');
logger.info('Check the data-ingestion service logs to see rate limiting in action.');
}
// Health check before running tests
async function checkService() {
try {
const response = await fetch('http://localhost:3001/health');
if (!response.ok) {
throw new Error('Service not healthy');
}
return true;
} catch (error) {
logger.error('Data ingestion service not running. Start it with: bun run dev');
return false;
}
}
async function main() {
if (await checkService()) {
await testAdvancedRateLimits();
}
}
main().catch(error => {
logger.error('Test failed:', error);
process.exit(1);
});
#!/usr/bin/env bun
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('test-advanced-rate-limit');
async function testAdvancedRateLimits() {
logger.info('Testing advanced rate limit features...');
const baseUrl = 'http://localhost:3001/api';
logger.info('\n📋 Rate Limit Configuration:');
logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day');
logger.info('fetch-daily-prices: 1 point per call');
logger.info('fetch-fundamentals: 10 points per call');
logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)');
// First test: test-burst operation
logger.info('\n🚀 Testing burst operation with mixed costs...');
const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'],
burstSize: 30,
}),
});
const burstResult = await burstResponse.json();
logger.info('Burst test result:', burstResult);
// Wait for jobs to process
logger.info('\n⏳ Waiting 10 seconds for jobs to process...');
await new Promise(resolve => setTimeout(resolve, 10000));
// Test individual operations with different costs
logger.info('\n📊 Testing individual operations:');
// Test cheap operation (1 point)
logger.info('\n1️⃣ Testing fetch-daily-prices (1 point each)...');
for (let i = 0; i < 5; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test medium cost operation (10 points)
logger.info('\n🔟 Testing fetch-fundamentals (10 points each)...');
for (let i = 0; i < 3; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
// Test expensive operation (50 points)
logger.info('\n💰 Testing fetch-news (50 points each, custom limits)...');
for (let i = 0; i < 2; i++) {
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: true, index: i }),
});
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
}
logger.info('\n✅ Test completed!');
logger.info('Check the data-ingestion service logs to see rate limiting in action.');
}
// Health check before running tests
async function checkService() {
try {
const response = await fetch('http://localhost:3001/health');
if (!response.ok) {
throw new Error('Service not healthy');
}
return true;
} catch (_error) {
logger.error('Data ingestion service not running. Start it with: bun run dev');
return false;
}
}
async function main() {
if (await checkService()) {
await testAdvancedRateLimits();
}
}
main().catch(error => {
logger.error('Test failed:', error);
process.exit(1);
});

View file

@ -1,156 +1,163 @@
/**
* Test script to verify intraday crawl data flow
*/
import { OperationTracker, OperationRegistry } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types';
async function testIntradayDataFlow() {
console.log('=== Testing Intraday Data Flow ===\n');
// Mock services
const mockServices: DataIngestionServices = {
mongodb: {
collection: (name: string) => ({
find: () => ({
toArray: async () => {
console.log(`Mock: Query collection ${name}`);
if (name === 'qmSymbols') {
return [{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
lastRunAt: new Date('2024-01-01'),
lastSuccessAt: new Date('2024-01-01'),
status: 'success',
crawlState: {
finished: false,
oldestDateReached: new Date('2023-01-01'),
newestDateReached: new Date('2024-01-01'),
lastProcessedDate: new Date('2023-06-15'),
totalDaysProcessed: 180
}
}
}
}];
}
return [];
}
}),
createIndex: async () => ({ ok: 1 })
}),
find: async (collection: string, filter: any, options?: any) => {
console.log(`Mock: Direct find on ${collection}`, { filter, options });
return [{
symbol: 'X',
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
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 || ''),
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || '')
}
} as DataIngestionServices;
// Create registry and provider
const registry = new OperationRegistry(mockServices as any);
// Mock provider
const mockProvider = {
getProviderConfig: () => ({
name: 'qm',
collectionName: 'qmSymbols',
symbolField: 'qmSearchCode'
}),
getOperations: () => [{
name: 'intraday_bars',
type: 'intraday_crawl' as const,
defaultStaleHours: 1
}],
validateOperation: () => true,
getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }),
getDefaultStaleHours: () => 1,
initialize: async () => {},
beforeOperationUpdate: async () => {},
afterOperationUpdate: async () => {}
};
const tracker = new OperationTracker(mockServices as any, mockProvider as any);
await tracker.initialize();
// Test 1: Get symbols for intraday crawl
console.log('\nTest 1: Get symbols for intraday crawl with symbol filter');
const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit: 10,
targetOldestDate: new Date('2020-01-01'),
includeNewDataGaps: true,
symbolFilter: { symbol: 'X' }
});
console.log(`\nFound ${symbols.length} symbols:`);
symbols.forEach(sym => {
console.log({
symbol: sym.symbol,
qmSearchCode: sym.qmSearchCode,
exchange: sym.exchange,
gaps: sym.gaps,
crawlState: sym.operationStatus?.crawlState
});
});
// Test 2: Verify data preservation
console.log('\n\nTest 2: Verify data is preserved through mapping');
const testSymbol = symbols[0];
if (testSymbol) {
console.log('Original data:');
console.log({
symbol: testSymbol.symbol,
hasGaps: !!testSymbol.gaps,
gaps: testSymbol.gaps,
hasOperationStatus: !!testSymbol.operationStatus,
crawlState: testSymbol.operationStatus?.crawlState
});
// Simulate mapping
const mapped = {
...testSymbol,
symbol: 'X',
exchange: 'NYSE',
qmSearchCode: 'X:NYSE',
gaps: testSymbol.gaps,
operationStatus: testSymbol.operationStatus
};
console.log('\nAfter mapping:');
console.log({
symbol: mapped.symbol,
exchange: mapped.exchange,
qmSearchCode: mapped.qmSearchCode,
hasGaps: !!mapped.gaps,
gaps: mapped.gaps,
hasOperationStatus: !!mapped.operationStatus,
crawlState: mapped.operationStatus?.crawlState
});
}
console.log('\n=== Tests Complete ===');
}
// Run tests
testIntradayDataFlow().catch(console.error);
/**
* Test script to verify intraday crawl data flow
*/
import { OperationRegistry, OperationTracker } from '../src/shared/operation-manager';
import type { DataIngestionServices } from '../src/types';
async function testIntradayDataFlow() {
console.log('=== Testing Intraday Data Flow ===\n');
// Mock services
const mockServices: DataIngestionServices = {
mongodb: {
collection: (name: string) => ({
find: () => ({
toArray: async () => {
console.log(`Mock: Query collection ${name}`);
if (name === 'qmSymbols') {
return [
{
symbol: 'X',
symbolId: 123456,
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
lastRunAt: new Date('2024-01-01'),
lastSuccessAt: new Date('2024-01-01'),
status: 'success',
crawlState: {
finished: false,
oldestDateReached: new Date('2023-01-01'),
newestDateReached: new Date('2024-01-01'),
lastProcessedDate: new Date('2023-06-15'),
totalDaysProcessed: 180,
},
},
},
},
];
}
return [];
},
}),
createIndex: async () => ({ ok: 1 }),
}),
find: async (collection: string, filter: any, options?: any) => {
console.log(`Mock: Direct find on ${collection}`, { filter, options });
return [
{
symbol: 'X',
qmSearchCode: 'X:NYSE',
exchange: 'NYSE',
operations: {
intraday_bars: {
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 || ''),
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
},
} as DataIngestionServices;
// Create registry and provider
const _registry = new OperationRegistry(mockServices as any);
// Mock provider
const mockProvider = {
getProviderConfig: () => ({
name: 'qm',
collectionName: 'qmSymbols',
symbolField: 'qmSearchCode',
}),
getOperations: () => [
{
name: 'intraday_bars',
type: 'intraday_crawl' as const,
defaultStaleHours: 1,
},
],
validateOperation: () => true,
getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }),
getDefaultStaleHours: () => 1,
initialize: async () => {},
beforeOperationUpdate: async () => {},
afterOperationUpdate: async () => {},
};
const tracker = new OperationTracker(mockServices as any, mockProvider as any);
await tracker.initialize();
// Test 1: Get symbols for intraday crawl
console.log('\nTest 1: Get symbols for intraday crawl with symbol filter');
const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
limit: 10,
targetOldestDate: new Date('2020-01-01'),
includeNewDataGaps: true,
symbolFilter: { symbol: 'X' },
});
console.log(`\nFound ${symbols.length} symbols:`);
symbols.forEach(sym => {
console.log({
symbol: sym.symbol,
qmSearchCode: sym.qmSearchCode,
exchange: sym.exchange,
gaps: sym.gaps,
crawlState: sym.operationStatus?.crawlState,
});
});
// Test 2: Verify data preservation
console.log('\n\nTest 2: Verify data is preserved through mapping');
const testSymbol = symbols[0];
if (testSymbol) {
console.log('Original data:');
console.log({
symbol: testSymbol.symbol,
hasGaps: !!testSymbol.gaps,
gaps: testSymbol.gaps,
hasOperationStatus: !!testSymbol.operationStatus,
crawlState: testSymbol.operationStatus?.crawlState,
});
// Simulate mapping
const mapped = {
...testSymbol,
symbol: 'X',
exchange: 'NYSE',
qmSearchCode: 'X:NYSE',
gaps: testSymbol.gaps,
operationStatus: testSymbol.operationStatus,
};
console.log('\nAfter mapping:');
console.log({
symbol: mapped.symbol,
exchange: mapped.exchange,
qmSearchCode: mapped.qmSearchCode,
hasGaps: !!mapped.gaps,
gaps: mapped.gaps,
hasOperationStatus: !!mapped.operationStatus,
crawlState: mapped.operationStatus?.crawlState,
});
}
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'
*/
import { OperationTracker } from '../src/shared/operation-manager';
// Example 1: Modified getStaleSymbols to only return symbol X
async function getStaleSymbolsOnlyX(
operationTracker: OperationTracker,
providerName: string,
operationName: string,
options: any = {}
) {
// Method 1: Add symbolFilter to options
const modifiedOptions = {
...options,
symbolFilter: { symbol: 'X' }
};
return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions);
}
// Example 2: Modified sophisticated backtest function for symbol X only
async function runSophisticatedBacktestOnlyX(orchestrator: any) {
const symbols = ['X']; // Only test symbol X
const backtestConfig = {
symbols,
startDate: new Date('2023-01-01'),
endDate: new Date('2024-01-01'),
strategies: ['momentum', 'mean_reversion'],
// ... rest of config
};
return orchestrator.runBacktest(backtestConfig);
}
// Example 3: Modified schedule function to only process symbol X
async function scheduleOperationsOnlyX(handler: any) {
// Get all symbols that need updates, then filter for X
const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: 24,
limit: 1000
});
// Filter to only include symbol X
const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:'));
if (symbolXOnly.length > 0) {
const symbolData = await handler.mongodb.find('qmSymbols', {
qmSearchCode: symbolXOnly[0]
});
if (symbolData.length > 0) {
await handler.scheduleOperation('update-prices', {
symbol: symbolData[0].symbol,
symbolId: symbolData[0].symbolId,
qmSearchCode: symbolData[0].qmSearchCode
});
}
}
}
// Example 4: Modified intraday crawl for symbol X only
async function crawlIntradayOnlyX(handler: any) {
// Direct approach - just process symbol X
const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' });
if (symbolX) {
return handler.crawlIntradayData({
symbol: symbolX.symbol,
symbolId: symbolX.symbolId,
qmSearchCode: symbolX.qmSearchCode,
mode: 'full',
targetOldestDate: new Date('2020-01-01')
});
}
}
// Example 5: Test wrapper that ensures only symbol X is processed
function createSymbolXTestWrapper(originalFunction: Function) {
return async function(...args: any[]) {
// Check if first argument has symbol property
if (args[0] && typeof args[0] === 'object') {
// If it's a symbol-specific call, only proceed if symbol is X
if (args[0].symbol && args[0].symbol !== 'X') {
console.log(`Skipping symbol ${args[0].symbol} - only testing X`);
return { success: false, message: 'Test mode - only symbol X allowed' };
}
// If it's a batch operation, filter to only X
if (args[0].symbols && Array.isArray(args[0].symbols)) {
args[0].symbols = args[0].symbols.filter((s: string) => s === 'X');
}
}
// Call original function with potentially modified args
return originalFunction.apply(this, args);
};
}
// Example usage
async function demonstrateUsage() {
console.log('=== Demonstration of Symbol X Only Modifications ===\n');
// Mock tracker for demonstration
const mockTracker = {
getStaleSymbols: async (provider: string, operation: string, options: any) => {
console.log(`Getting stale symbols with options:`, options);
if (options.symbolFilter?.symbol === 'X') {
return ['X:NYSE'];
}
return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ'];
}
} as any;
// Test the modified function
console.log('1. Testing getStaleSymbols with X filter:');
const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', {
minHoursSinceRun: 24
});
console.log('Results:', xOnlySymbols);
console.log('\n2. Example of wrapper usage:');
const originalUpdate = async (input: any) => {
console.log(`Processing symbol: ${input.symbol}`);
return { success: true, symbol: input.symbol };
};
const wrappedUpdate = createSymbolXTestWrapper(originalUpdate);
await wrappedUpdate({ symbol: 'X', symbolId: 123 });
await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped
console.log('\n=== Demonstration Complete ===');
}
// Run demonstration
demonstrateUsage().catch(console.error);
/**
* Examples of modifying existing functions to only work with symbol 'X'
*/
import { OperationTracker } from '../src/shared/operation-manager';
// Example 1: Modified getStaleSymbols to only return symbol X
async function getStaleSymbolsOnlyX(
operationTracker: OperationTracker,
providerName: string,
operationName: string,
options: any = {}
) {
// Method 1: Add symbolFilter to options
const modifiedOptions = {
...options,
symbolFilter: { symbol: 'X' },
};
return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions);
}
// Example 2: Modified sophisticated backtest function for symbol X only
async function _runSophisticatedBacktestOnlyX(orchestrator: any) {
const symbols = ['X']; // Only test symbol X
const backtestConfig = {
symbols,
startDate: new Date('2023-01-01'),
endDate: new Date('2024-01-01'),
strategies: ['momentum', 'mean_reversion'],
// ... rest of config
};
return orchestrator.runBacktest(backtestConfig);
}
// Example 3: Modified schedule function to only process symbol X
async function _scheduleOperationsOnlyX(handler: any) {
// Get all symbols that need updates, then filter for X
const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', {
minHoursSinceRun: 24,
limit: 1000,
});
// Filter to only include symbol X
const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:'));
if (symbolXOnly.length > 0) {
const symbolData = await handler.mongodb.find('qmSymbols', {
qmSearchCode: symbolXOnly[0],
});
if (symbolData.length > 0) {
await handler.scheduleOperation('update-prices', {
symbol: symbolData[0].symbol,
symbolId: symbolData[0].symbolId,
qmSearchCode: symbolData[0].qmSearchCode,
});
}
}
}
// Example 4: Modified intraday crawl for symbol X only
async function _crawlIntradayOnlyX(handler: any) {
// Direct approach - just process symbol X
const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' });
if (symbolX) {
return handler.crawlIntradayData({
symbol: symbolX.symbol,
symbolId: symbolX.symbolId,
qmSearchCode: symbolX.qmSearchCode,
mode: 'full',
targetOldestDate: new Date('2020-01-01'),
});
}
}
// Example 5: Test wrapper that ensures only symbol X is processed
function createSymbolXTestWrapper(originalFunction: Function) {
return async function (...args: any[]) {
// Check if first argument has symbol property
if (args[0] && typeof args[0] === 'object') {
// If it's a symbol-specific call, only proceed if symbol is X
if (args[0].symbol && args[0].symbol !== 'X') {
console.log(`Skipping symbol ${args[0].symbol} - only testing X`);
return { success: false, message: 'Test mode - only symbol X allowed' };
}
// If it's a batch operation, filter to only X
if (args[0].symbols && Array.isArray(args[0].symbols)) {
args[0].symbols = args[0].symbols.filter((s: string) => s === 'X');
}
}
// Call original function with potentially modified args
return originalFunction.apply(this, args);
};
}
// Example usage
async function demonstrateUsage() {
console.log('=== Demonstration of Symbol X Only Modifications ===\n');
// Mock tracker for demonstration
const mockTracker = {
getStaleSymbols: async (provider: string, operation: string, options: any) => {
console.log(`Getting stale symbols with options:`, options);
if (options.symbolFilter?.symbol === 'X') {
return ['X:NYSE'];
}
return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ'];
},
} as any;
// Test the modified function
console.log('1. Testing getStaleSymbols with X filter:');
const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', {
minHoursSinceRun: 24,
});
console.log('Results:', xOnlySymbols);
console.log('\n2. Example of wrapper usage:');
const originalUpdate = async (input: any) => {
console.log(`Processing symbol: ${input.symbol}`);
return { success: true, symbol: input.symbol };
};
const wrappedUpdate = createSymbolXTestWrapper(originalUpdate);
await wrappedUpdate({ symbol: 'X', symbolId: 123 });
await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped
console.log('\n=== Demonstration Complete ===');
}
// Run demonstration
demonstrateUsage().catch(console.error);

View file

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

View file

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

View file

@ -3,7 +3,7 @@
* 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 { getLogger } from '@stock-bot/logger';
@ -13,7 +13,7 @@ const logger = getLogger('data-pipeline-container');
* Configure the service container for data pipeline workloads
*/
export function setupServiceContainer(
config: AppConfig,
config: UnifiedAppConfig,
container: IServiceContainer
): IServiceContainer {
logger.info('Configuring data pipeline service container...');

View file

@ -26,7 +26,7 @@ class ExchangesHandler extends BaseHandler {
async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise<unknown> {
const finalPayload = payload || { clearFirst: true };
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> {
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> {
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> {
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';
}): Promise<unknown> {
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')
async getExchangeStats(): Promise<unknown> {
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')
async getProviderMappingStats(): Promise<unknown> {
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')
async getEnhancedSyncStatus(): Promise<unknown> {
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 { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-clear-postgresql-data');
@ -15,7 +16,7 @@ export async function clearPostgreSQLData(
logger.info('Clearing existing PostgreSQL data...');
try {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction for atomic operations
await postgresClient.query('BEGIN');
@ -29,9 +30,9 @@ export async function clearPostgreSQLData(
'SELECT COUNT(*) as count FROM provider_mappings'
);
const exchangesCleared = parseInt(exchangeCountResult.rows[0].count);
const symbolsCleared = parseInt(symbolCountResult.rows[0].count);
const mappingsCleared = parseInt(mappingCountResult.rows[0].count);
const exchangesCleared = parseInt(at(exchangeCountResult.rows, 0).count);
const symbolsCleared = parseInt(at(symbolCountResult.rows, 0).count);
const mappingsCleared = parseInt(at(mappingCountResult.rows, 0).count);
// Clear data in correct order (respect foreign keys)
await postgresClient.query('DELETE FROM provider_mappings');
@ -53,7 +54,7 @@ export async function clearPostgreSQLData(
return { exchangesCleared, symbolsCleared, mappingsCleared };
} catch (error) {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('Failed to clear PostgreSQL data', { error });
throw error;

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncStatus } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-status');
@ -11,14 +11,14 @@ export async function getSyncStatus(
logger.info('Getting comprehensive sync status...');
try {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
SELECT provider, data_type as "dataType", last_sync_at as "lastSyncAt",
last_sync_count as "lastSyncCount", sync_errors as "syncErrors"
FROM sync_status
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`);
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 { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-exchange-stats');
@ -18,7 +19,7 @@ export async function getExchangeStats(
logger.info('Getting exchange statistics...');
try {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
SELECT
COUNT(*) as total_exchanges,
@ -27,10 +28,10 @@ export async function getExchangeStats(
COUNT(DISTINCT currency) as currencies
FROM exchanges
`;
const result = await postgresClient.query(query);
const result = await postgresClient.query<ExchangeStats>(query);
logger.info('Retrieved exchange statistics');
return result.rows[0];
return at(result.rows, 0);
} catch (error) {
logger.error('Failed to get exchange statistics', { error });
throw error;

View file

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

View file

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

View file

@ -1,5 +1,6 @@
import type { IServiceContainer } from '@stock-bot/handlers';
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';
const logger = getLogger('enhanced-sync-all-exchanges');
@ -20,7 +21,7 @@ export async function syncAllExchanges(
};
try {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Clear existing data if requested
if (clearFirst) {
@ -46,14 +47,14 @@ export async function syncAllExchanges(
logger.info('Comprehensive exchange sync completed', result);
return result;
} catch (error) {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('Comprehensive exchange sync failed', { error });
throw error;
}
}
async function clearPostgreSQLData(postgresClient: any): Promise<void> {
async function clearPostgreSQLData(postgresClient: PostgresClient): Promise<void> {
logger.info('Clearing existing PostgreSQL data...');
// 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> {
const mongoClient = container.mongodb;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const exchanges = await mongoClient.find('eodExchanges', { active: true });
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> {
const mongoClient = container.mongodb;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const exchanges = await mongoClient.find('ibExchanges', {});
const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 };
@ -140,7 +141,7 @@ async function createProviderExchangeMapping(
return;
}
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists
const existingMapping = await findProviderExchangeMapping(
@ -162,6 +163,10 @@ async function createProviderExchangeMapping(
container
);
if (!masterExchange) {
throw new Error('Master exchange was not created or resolved');
}
// Create the provider exchange mapping
const query = `
INSERT INTO provider_exchange_mappings
@ -188,8 +193,8 @@ async function findOrCreateMasterExchange(
countryCode: string | null,
currency: string | null,
container: IServiceContainer
): Promise<any> {
const postgresClient = container.postgres;
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container);
@ -244,16 +249,16 @@ async function findProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
): Promise<any> {
const postgresClient = container.postgres;
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query =
'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2';
const result = await postgresClient.query(query, [provider, providerExchangeCode]);
return result.rows[0] || null;
}
async function findExchangeByCode(code: string, container: IServiceContainer): Promise<any> {
const postgresClient = container.postgres;
async function findExchangeByCode(code: string, container: IServiceContainer) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [code]);
return result.rows[0] || null;
@ -263,7 +268,7 @@ async function updateSyncStatus(
provider: string,
dataType: string,
count: number,
postgresClient: any
postgresClient: PostgresClient
): Promise<void> {
const query = `
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 type { MasterExchange } from '@stock-bot/mongodb';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-ib-exchanges');
interface IBExchange {
id?: string;
_id?: any;
_id?: unknown;
name?: string;
code?: string;
country_code?: string;
@ -21,7 +21,7 @@ export async function syncIBExchanges(
logger.info('Syncing IB exchanges from database...');
try {
const mongoClient = container.mongodb;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase();
// Filter by country code US and CA
@ -69,7 +69,7 @@ async function createOrUpdateMasterExchange(
ibExchange: IBExchange,
container: IServiceContainer
): Promise<void> {
const mongoClient = container.mongodb;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const db = mongoClient.getDatabase();
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 { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-qm-provider-mappings');
@ -19,8 +19,8 @@ export async function syncQMProviderMappings(
};
try {
const mongoClient = container.mongodb;
const postgresClient = container.postgres;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction
await postgresClient.query('BEGIN');
@ -79,7 +79,7 @@ export async function syncQMProviderMappings(
logger.info('QM provider exchange mappings sync completed', result);
return result;
} catch (error) {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('QM provider exchange mappings sync failed', { error });
throw error;
@ -99,7 +99,7 @@ async function createProviderExchangeMapping(
return;
}
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists
const existingMapping = await findProviderExchangeMapping(
@ -121,6 +121,10 @@ async function createProviderExchangeMapping(
container
);
if (!masterExchange) {
throw new Error('Master exchange was not created or resolved');
}
// Create the provider exchange mapping
const query = `
INSERT INTO provider_exchange_mappings
@ -145,8 +149,8 @@ async function findProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
): Promise<any> {
const postgresClient = container.postgres;
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query =
'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2';
const result = await postgresClient.query(query, [provider, providerExchangeCode]);
@ -159,8 +163,8 @@ async function findOrCreateMasterExchange(
countryCode: string | null,
currency: string | null,
container: IServiceContainer
): Promise<any> {
const postgresClient = container.postgres;
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container);
@ -211,8 +215,8 @@ function getBasicExchangeMapping(providerCode: string): string | null {
return mappings[providerCode.toUpperCase()] || null;
}
async function findExchangeByCode(code: string, container: IServiceContainer): Promise<any> {
const postgresClient = container.postgres;
async function findExchangeByCode(code: string, container: IServiceContainer) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [code]);
return result.rows[0] || null;

View file

@ -1,3 +1,4 @@
import type { HandlerInitializationContext } from '@stock-bot/di';
/**
* Handler registration for data pipeline service
*/
@ -13,7 +14,10 @@ const logger = getLogger('pipeline-handler-init');
/**
* 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...');
try {
@ -22,7 +26,7 @@ export async function initializeAllHandlers(container: IServiceContainer): Promi
for (const Handler of handlers) {
try {
const instance = new Handler(container);
context.handlerScanner.registerHandlerClass(Handler, { serviceName: 'data-pipeline' });
// Register the handler instance if needed
logger.info(`Registered handler: ${Handler.name}`);
} 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 type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-qm-symbols');
@ -11,8 +14,8 @@ export async function syncQMSymbols(
logger.info('Starting QM symbols sync...');
try {
const mongoClient = container.mongodb;
const postgresClient = container.postgres;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const { postgres: postgresClient } = requireServices(container, 'postgres');
// 1. Get all QM symbols from MongoDB
const qmSymbols = await mongoClient.find('qmSymbols', {});
@ -69,7 +72,10 @@ export async function syncQMSymbols(
}
// Helper functions
async function resolveExchange(exchangeCode: string, postgresClient: any): Promise<string | null> {
async function resolveExchange(
exchangeCode: string,
postgresClient: PostgresClient
): Promise<string | null> {
if (!exchangeCode) {
return null;
}
@ -94,16 +100,16 @@ async function resolveExchange(exchangeCode: string, postgresClient: any): Promi
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 result = await postgresClient.query(query, [symbol, exchangeId]);
return result.rows[0] || null;
}
async function createSymbol(
qmSymbol: any,
qmSymbol: Document,
exchangeId: string,
postgresClient: any
postgresClient: PostgresClient
): Promise<string> {
const query = `
INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
@ -119,10 +125,14 @@ async function createSymbol(
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 = `
UPDATE symbols
SET company_name = COALESCE($2, company_name),
@ -143,8 +153,8 @@ async function updateSymbol(symbolId: string, qmSymbol: any, postgresClient: any
async function upsertProviderMapping(
symbolId: string,
provider: string,
qmSymbol: any,
postgresClient: any
qmSymbol: Document,
postgresClient: PostgresClient
): Promise<void> {
const query = `
INSERT INTO provider_mappings
@ -169,7 +179,7 @@ async function updateSyncStatus(
provider: string,
dataType: string,
count: number,
postgresClient: any
postgresClient: PostgresClient
): Promise<void> {
const query = `
UPDATE sync_status

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('sync-status');
@ -11,7 +11,7 @@ export async function getSyncStatus(
logger.info('Getting sync status...');
try {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM sync_status ORDER BY provider, data_type';
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 type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-symbols-from-provider');
@ -26,8 +29,8 @@ export async function syncSymbolsFromProvider(
};
try {
const mongoClient = container.mongodb;
const postgresClient = container.postgres;
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Clear existing data if requested (only symbols and mappings, keep exchanges)
if (clearFirst) {
@ -76,21 +79,26 @@ export async function syncSymbolsFromProvider(
}
// 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');
logger.info(`${provider} symbols sync completed`, result);
return result;
} catch (error) {
await container.postgres.query('ROLLBACK');
await requireServices(container, 'postgres').postgres.query('ROLLBACK');
logger.error(`${provider} symbols sync failed`, { error });
throw error;
}
}
async function processSingleSymbol(
symbol: any,
symbol: Document,
provider: string,
result: SyncResult,
container: IServiceContainer
@ -137,8 +145,8 @@ async function findActiveProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
): Promise<any> {
const postgresClient = container.postgres;
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
SELECT pem.*, e.code as master_exchange_code
FROM provider_exchange_mappings pem
@ -153,19 +161,19 @@ async function findSymbolByCodeAndExchange(
symbol: string,
exchangeId: string,
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 result = await postgresClient.query(query, [symbol, exchangeId]);
return result.rows[0] || null;
}
async function createSymbol(
symbol: any,
symbol: Document,
exchangeId: string,
container: IServiceContainer
): Promise<string> {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
VALUES ($1, $2, $3, $4, $5)
@ -180,15 +188,15 @@ async function createSymbol(
symbol.currency || 'USD',
]);
return result.rows[0].id;
return at(result.rows, 0).id;
}
async function updateSymbol(
symbolId: string,
symbol: any,
symbol: Document,
container: IServiceContainer
): Promise<void> {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
UPDATE symbols
SET company_name = COALESCE($2, company_name),
@ -209,10 +217,10 @@ async function updateSymbol(
async function upsertProviderMapping(
symbolId: string,
provider: string,
symbol: any,
symbol: Document,
container: IServiceContainer
): Promise<void> {
const postgresClient = container.postgres;
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
INSERT INTO provider_mappings
(symbol_id, provider, provider_symbol, provider_exchange, last_seen)
@ -236,7 +244,7 @@ async function updateSyncStatus(
provider: string,
dataType: string,
count: number,
postgresClient: any
postgresClient: PostgresClient
): Promise<void> {
const query = `
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 }> {
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')
async getSyncStatus(): Promise<unknown> {
this.log('info', 'Getting symbol sync status...');
return getSyncStatus({}, this.services);
return getSyncStatus({}, this);
}
/**
@ -66,7 +66,7 @@ class SymbolsHandler extends BaseHandler {
clearFirst?: boolean;
}): Promise<unknown> {
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
onContainerReady: container => {
// Setup service-specific configuration
const enhancedContainer = setupServiceContainer(config, container);
return enhancedContainer;
setupServiceContainer(config, container);
},
onStarted: _port => {
const logger = getLogger('data-pipeline');
@ -55,7 +54,7 @@ const app = new ServiceApplication(
);
// 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 builder = new ServiceContainerBuilder();

View file

@ -13,12 +13,6 @@ import { createSyncRoutes } from './sync.routes';
export function createRoutes(container: IServiceContainer): 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
app.route('/health', healthRoutes);
app.route('/sync', createSyncRoutes(container));

View file

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

View file

@ -1,473 +1,415 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::sync::Arc;
use parking_lot::Mutex;
use crate::backtest::{
BacktestEngine as RustBacktestEngine,
BacktestConfig,
Strategy, Signal,
};
use crate::{TradingMode, MarketUpdate};
use chrono::{DateTime, Utc};
#[napi]
pub struct BacktestEngine {
inner: Arc<Mutex<Option<RustBacktestEngine>>>,
}
#[napi]
impl BacktestEngine {
#[napi(constructor)]
pub fn new(config: napi::JsObject, env: Env) -> Result<Self> {
let config = parse_backtest_config(config)?;
// Create mode
let mode = TradingMode::Backtest {
start_time: config.start_time,
end_time: config.end_time,
speed_multiplier: 0.0, // Max speed
};
// Create components
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);
let engine = RustBacktestEngine::new(
config,
mode,
time_provider,
market_data_source,
execution_handler,
);
Ok(Self {
inner: Arc::new(Mutex::new(Some(engine))),
})
}
#[napi]
pub fn add_typescript_strategy(
&mut self,
name: String,
id: String,
parameters: napi::JsObject,
_callback: napi::JsFunction,
) -> Result<()> {
eprintln!("Adding strategy: {}", name);
// For now, we'll add a native Rust SMA strategy
// In the future, we'll implement proper TypeScript callback support
let fast_period: usize = parameters.get_named_property::<f64>("fastPeriod")
.unwrap_or(5.0) as usize;
let slow_period: usize = parameters.get_named_property::<f64>("slowPeriod")
.unwrap_or(15.0) as usize;
if let Some(engine) = self.inner.lock().as_mut() {
engine.add_strategy(Box::new(SimpleSMAStrategy::new(
name.clone(),
id,
fast_period,
slow_period,
)));
eprintln!("Strategy '{}' added with fast={}, slow={}", name, fast_period, slow_period);
}
Ok(())
}
#[napi]
pub fn add_native_strategy(
&mut self,
strategy_type: String,
name: String,
id: String,
parameters: napi::JsObject,
) -> Result<()> {
eprintln!("Adding native Rust strategy: {} ({})", name, strategy_type);
if let Some(engine) = self.inner.lock().as_mut() {
match strategy_type.as_str() {
"sma_crossover" => {
let fast_period: usize = parameters.get_named_property::<f64>("fastPeriod")
.unwrap_or(5.0) as usize;
let slow_period: usize = parameters.get_named_property::<f64>("slowPeriod")
.unwrap_or(15.0) as usize;
engine.add_strategy(Box::new(SimpleSMAStrategy::new(
name.clone(),
id,
fast_period,
slow_period,
)));
}
"mean_reversion" => {
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod")
.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")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::MeanReversionFixedStrategy::new(
name.clone(),
id,
lookback_period,
entry_threshold,
position_size,
)));
}
"momentum" => {
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod")
.unwrap_or(14.0) as usize;
let momentum_threshold: f64 = parameters.get_named_property::<f64>("momentumThreshold")
.unwrap_or(5.0);
let position_size: f64 = parameters.get_named_property::<f64>("positionSize")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
name.clone(),
id,
lookback_period,
momentum_threshold,
position_size,
)));
}
"pairs_trading" => {
let pair_a: String = parameters.get_named_property::<String>("pairA")?;
let pair_b: String = parameters.get_named_property::<String>("pairB")?;
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod")
.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")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
name.clone(),
id,
pair_a,
pair_b,
lookback_period,
entry_threshold,
position_size,
)));
}
_ => {
return Err(Error::from_reason(format!("Unknown strategy type: {}", strategy_type)));
}
}
eprintln!("Native strategy '{}' added successfully", name);
}
Ok(())
}
#[napi]
pub fn run(&mut self) -> Result<String> {
eprintln!("=== BACKTEST RUN START ===");
let mut engine = self.inner.lock().take()
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
// Config and strategies are private, skip detailed logging
// Run the backtest synchronously for now
let runtime = tokio::runtime::Runtime::new()
.map_err(|e| Error::from_reason(e.to_string()))?;
let result = runtime.block_on(engine.run())
.map_err(|e| {
eprintln!("ERROR: Backtest engine failed: {}", e);
Error::from_reason(e)
})?;
eprintln!("=== BACKTEST RUN COMPLETE ===");
eprintln!("Total trades: {}", result.trades.len());
eprintln!("Equity points: {}", result.equity.len());
eprintln!("OHLC data symbols: {:?}", result.ohlc_data.keys().collect::<Vec<_>>());
for (symbol, data) in &result.ohlc_data {
eprintln!(" {}: {} bars", symbol, data.len());
}
// Return result as JSON
serde_json::to_string(&result)
.map_err(|e| Error::from_reason(e.to_string()))
}
#[napi]
pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> {
eprintln!("load_market_data called with {} items", data.len());
// Convert JS objects to MarketData
let market_data: Vec<MarketUpdate> = data.into_iter()
.filter_map(|obj| parse_market_data(obj).ok())
.collect();
eprintln!("Parsed {} valid market data items", market_data.len());
// Load data into the historical data source
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()
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>() {
eprintln!("Loading data into HistoricalDataSource");
historical_source.load_data(market_data);
eprintln!("Data loaded successfully");
} else {
eprintln!("ERROR: Could not downcast to HistoricalDataSource");
}
} else {
eprintln!("ERROR: Engine not found");
}
Ok(())
}
}
fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
let name: String = obj.get_named_property("name")?;
let symbols: Vec<String> = obj.get_named_property("symbols")?;
let start_date: String = obj.get_named_property("startDate")?;
let end_date: String = obj.get_named_property("endDate")?;
let initial_capital: f64 = obj.get_named_property("initialCapital")?;
let commission: f64 = obj.get_named_property("commission")?;
let slippage: f64 = obj.get_named_property("slippage")?;
let data_frequency: String = obj.get_named_property("dataFrequency")?;
let strategy: Option<String> = obj.get_named_property("strategy").ok();
Ok(BacktestConfig {
name,
strategy,
symbols,
start_time: DateTime::parse_from_rfc3339(&start_date)
.map_err(|e| Error::from_reason(e.to_string()))?
.with_timezone(&Utc),
end_time: DateTime::parse_from_rfc3339(&end_date)
.map_err(|e| Error::from_reason(e.to_string()))?
.with_timezone(&Utc),
initial_capital,
commission,
slippage,
data_frequency,
})
}
fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
let symbol: String = obj.get_named_property("symbol")?;
let timestamp: i64 = obj.get_named_property("timestamp")?;
let data_type: String = obj.get_named_property("type")?;
let data = if data_type == "bar" {
crate::MarketDataType::Bar(crate::Bar {
open: obj.get_named_property("open")?,
high: obj.get_named_property("high")?,
low: obj.get_named_property("low")?,
close: obj.get_named_property("close")?,
volume: obj.get_named_property("volume")?,
vwap: obj.get_named_property("vwap").ok(),
})
} else {
eprintln!("Unsupported market data type: {}", data_type);
return Err(Error::from_reason("Unsupported market data type"));
};
// First few items
static mut COUNT: usize = 0;
unsafe {
if COUNT < 3 {
eprintln!("Parsed market data: symbol={}, timestamp={}, close={}",
symbol, timestamp,
if let crate::MarketDataType::Bar(ref bar) = data { bar.close } else { 0.0 });
COUNT += 1;
}
}
Ok(crate::MarketUpdate {
symbol,
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
data,
})
}
// Simple SMA Strategy for testing
struct SimpleSMAStrategy {
name: String,
id: String,
fast_period: usize,
slow_period: usize,
price_history: std::collections::HashMap<String, Vec<f64>>,
positions: std::collections::HashMap<String, f64>,
}
impl SimpleSMAStrategy {
fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self {
eprintln!("Creating SimpleSMAStrategy: name={}, fast={}, slow={}", name, fast_period, slow_period);
Self {
name,
id,
fast_period,
slow_period,
price_history: std::collections::HashMap::new(),
positions: std::collections::HashMap::new(),
}
}
}
impl Strategy for SimpleSMAStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
// Count calls
static mut CALL_COUNT: usize = 0;
unsafe {
CALL_COUNT += 1;
if CALL_COUNT % 100 == 1 {
eprintln!("SimpleSMAStrategy.on_market_data called {} times", CALL_COUNT);
}
}
let mut signals = Vec::new();
// Check if it's bar data
if let crate::MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol;
let price = bar.close;
// Update price history
let history = self.price_history.entry(symbol.clone()).or_insert_with(Vec::new);
history.push(price);
// Debug: Log first few prices
if history.len() <= 3 {
eprintln!("Price history for {}: {:?}", symbol, history);
} else if history.len() == 10 || history.len() == 15 {
eprintln!("Price history length for {}: {} bars", symbol, history.len());
}
// Keep only necessary history (need one extra for previous SMA calculation)
if history.len() > self.slow_period + 1 {
history.remove(0);
}
// Need enough data
if history.len() >= self.slow_period {
// Debug when we first have enough data
if history.len() == self.slow_period {
eprintln!("Now have enough data for {}: {} bars", symbol, history.len());
}
// Calculate SMAs
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());
// Also log if they're close to crossing
let diff = (fast_sma - slow_sma).abs();
let pct_diff = diff / slow_sma * 100.0;
if pct_diff < 1.0 {
eprintln!(" -> SMAs are close! Difference: {:.4} ({:.2}%)", diff, pct_diff);
}
}
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period {
// Debug: First time checking for crossovers
if history.len() == self.slow_period + 1 {
eprintln!("Starting crossover checks for {}", symbol);
}
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;
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
// Golden cross - buy signal
if prev_fast_sma <= prev_slow_sma && fast_sma > slow_sma && current_position <= 0.0 {
signals.push(Signal {
symbol: symbol.clone(),
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,
});
self.positions.insert(symbol.clone(), 1.0);
eprintln!("Generated BUY signal for {} at price {}", symbol, price);
}
// 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(),
signal_type: crate::backtest::SignalType::Sell,
strength: 1.0,
quantity: Some(100.0), // Fixed quantity for testing
reason: Some("Death cross".to_string()),
metadata: None,
});
self.positions.insert(symbol.clone(), -1.0);
eprintln!("Generated SELL signal for {} at price {}", symbol, price);
}
}
} 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
}))
}
use crate::backtest::{BacktestConfig, BacktestEngine as RustBacktestEngine, Signal, Strategy};
use crate::{MarketUpdate, TradingMode};
use chrono::{DateTime, Utc};
use napi::bindgen_prelude::*;
use napi_derive::napi;
use parking_lot::Mutex;
use std::sync::Arc;
#[napi]
pub struct BacktestEngine {
inner: Arc<Mutex<Option<RustBacktestEngine>>>,
}
#[napi]
impl BacktestEngine {
#[napi(constructor)]
pub fn new(config: napi::JsObject, env: Env) -> Result<Self> {
let config = parse_backtest_config(config)?;
// Create mode
let mode = TradingMode::Backtest {
start_time: config.start_time,
end_time: config.end_time,
speed_multiplier: 0.0, // Max speed
};
// Create components
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);
let engine = RustBacktestEngine::new(
config,
mode,
time_provider,
market_data_source,
execution_handler,
);
Ok(Self {
inner: Arc::new(Mutex::new(Some(engine))),
})
}
#[napi]
pub fn add_typescript_strategy(
&mut self,
_name: String,
_id: String,
_parameters: napi::JsObject,
_callback: napi::JsFunction,
) -> Result<()> {
Err(Error::from_reason(
"TypeScript strategy callbacks are not supported by the native engine",
))
}
#[napi]
pub fn add_native_strategy(
&mut self,
strategy_type: String,
name: String,
id: String,
parameters: napi::JsObject,
) -> Result<()> {
if let Some(engine) = self.inner.lock().as_mut() {
match strategy_type.as_str() {
"sma_crossover" => {
let fast_period: usize = parameters
.get_named_property::<f64>("fastPeriod")
.unwrap_or(5.0) as usize;
let slow_period: usize = parameters
.get_named_property::<f64>("slowPeriod")
.unwrap_or(15.0) as usize;
if fast_period == 0 || fast_period >= slow_period {
return Err(Error::from_reason(
"SMA periods must satisfy 0 < fastPeriod < slowPeriod",
));
}
engine.add_strategy(Box::new(SimpleSMAStrategy::new(
name.clone(),
id,
fast_period,
slow_period,
)));
}
"mean_reversion" => {
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.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")
.unwrap_or(100.0);
engine.add_strategy(Box::new(
crate::strategies::MeanReversionFixedStrategy::new(
name.clone(),
id,
lookback_period,
entry_threshold,
position_size,
),
));
}
"momentum" => {
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.unwrap_or(14.0) as usize;
let momentum_threshold: f64 = parameters
.get_named_property::<f64>("momentumThreshold")
.unwrap_or(5.0);
let position_size: f64 = parameters
.get_named_property::<f64>("positionSize")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
name.clone(),
id,
lookback_period,
momentum_threshold,
position_size,
)));
}
"pairs_trading" => {
let pair_a: String = parameters.get_named_property::<String>("pairA")?;
let pair_b: String = parameters.get_named_property::<String>("pairB")?;
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.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")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
name.clone(),
id,
pair_a,
pair_b,
lookback_period,
entry_threshold,
position_size,
)));
}
_ => {
return Err(Error::from_reason(format!(
"Unknown strategy type: {}",
strategy_type
)));
}
}
}
Ok(())
}
#[napi]
pub fn run(&mut self) -> Result<String> {
let mut engine = self
.inner
.lock()
.take()
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
// Config and strategies are private, skip detailed logging
// Run the backtest synchronously for now
let runtime =
tokio::runtime::Runtime::new().map_err(|e| Error::from_reason(e.to_string()))?;
let result = runtime
.block_on(engine.run())
.map_err(|e| Error::from_reason(e))?;
for (symbol, data) in &result.ohlc_data {}
// Return result as JSON
serde_json::to_string(&result).map_err(|e| Error::from_reason(e.to_string()))
}
#[napi]
pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> {
// Convert JS objects to MarketData
let market_data: Vec<MarketUpdate> = data
.into_iter()
.filter_map(|obj| parse_market_data(obj).ok())
.collect();
// Load data into the historical data source
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()
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>(
) {
historical_source.load_data(market_data);
} else {
}
} else {
}
Ok(())
}
}
fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
let name: String = obj.get_named_property("name")?;
let symbols: Vec<String> = obj.get_named_property("symbols")?;
let start_date: String = obj.get_named_property("startDate")?;
let end_date: String = obj.get_named_property("endDate")?;
let initial_capital: f64 = obj.get_named_property("initialCapital")?;
let commission: f64 = obj.get_named_property("commission")?;
let slippage: f64 = obj.get_named_property("slippage")?;
let data_frequency: String = obj.get_named_property("dataFrequency")?;
let strategy: Option<String> = obj.get_named_property("strategy").ok();
Ok(BacktestConfig {
name,
strategy,
symbols,
start_time: DateTime::parse_from_rfc3339(&start_date)
.map_err(|e| Error::from_reason(e.to_string()))?
.with_timezone(&Utc),
end_time: DateTime::parse_from_rfc3339(&end_date)
.map_err(|e| Error::from_reason(e.to_string()))?
.with_timezone(&Utc),
initial_capital,
commission,
slippage,
data_frequency,
})
}
fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
let symbol: String = obj.get_named_property("symbol")?;
let timestamp: i64 = obj.get_named_property("timestamp")?;
let data_type: String = obj.get_named_property("type")?;
let data = if data_type == "bar" {
crate::MarketDataType::Bar(crate::Bar {
open: obj.get_named_property("open")?,
high: obj.get_named_property("high")?,
low: obj.get_named_property("low")?,
close: obj.get_named_property("close")?,
volume: obj.get_named_property("volume")?,
vwap: obj.get_named_property("vwap").ok(),
})
} else {
return Err(Error::from_reason("Unsupported market data type"));
};
Ok(crate::MarketUpdate {
symbol,
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
data,
})
}
// Simple SMA Strategy for testing
struct SimpleSMAStrategy {
name: String,
id: String,
fast_period: usize,
slow_period: usize,
price_history: std::collections::HashMap<String, Vec<f64>>,
positions: std::collections::HashMap<String, f64>,
}
impl SimpleSMAStrategy {
fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self {
Self {
name,
id,
fast_period,
slow_period,
price_history: std::collections::HashMap::new(),
positions: std::collections::HashMap::new(),
}
}
}
impl Strategy for SimpleSMAStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
let mut signals = Vec::new();
// Check if it's bar data
if let crate::MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol;
let price = bar.close;
// Update price history
let history = self
.price_history
.entry(symbol.clone())
.or_insert_with(Vec::new);
history.push(price);
// Keep only necessary history (need one extra for previous SMA calculation)
if history.len() > self.slow_period + 1 {
history.remove(0);
}
// Need enough data
if history.len() >= self.slow_period {
// Calculate SMAs
let fast_sma = history[history.len() - self.fast_period..]
.iter()
.sum::<f64>()
/ self.fast_period as f64;
let slow_sma = history[history.len() - self.slow_period..]
.iter()
.sum::<f64>()
/ self.slow_period as f64;
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period {
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;
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
// Golden cross - buy signal
if prev_fast_sma <= prev_slow_sma
&& fast_sma > slow_sma
&& current_position <= 0.0
{
signals.push(Signal {
symbol: symbol.clone(),
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,
});
}
// 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(),
signal_type: crate::backtest::SignalType::Sell,
strength: 1.0,
quantity: Some(100.0), // Fixed quantity for testing
reason: Some("Death cross".to_string()),
metadata: None,
});
}
}
}
}
signals
}
fn on_fill(&mut self, symbol: &str, quantity: f64, _price: f64, side: &str) {
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
};
if new_pos.abs() < 0.0001 {
self.positions.remove(symbol);
} 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;
/// Moving Average Convergence Divergence (MACD) Indicator
///
/// MACD = Fast EMA - Slow EMA
/// Signal = EMA of MACD
/// Histogram = MACD - Signal
pub struct MACD {
fast_period: usize,
slow_period: usize,
signal_period: usize,
fast_ema: EMA,
slow_ema: EMA,
signal_ema: EMA,
macd_value: Option<f64>,
}
impl MACD {
pub fn new(fast_period: usize, slow_period: usize, signal_period: usize) -> Result<Self, IndicatorError> {
if fast_period == 0 || slow_period == 0 || signal_period == 0 {
return Err(IndicatorError::InvalidParameter(
"All periods must be greater than 0".to_string()
));
}
if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
"Fast period must be less than slow period".to_string()
));
}
Ok(Self {
fast_period,
slow_period,
signal_period,
fast_ema: EMA::new(fast_period)?,
slow_ema: EMA::new(slow_period)?,
signal_ema: EMA::new(signal_period)?,
macd_value: None,
})
}
/// Standard MACD with 12, 26, 9 periods
pub fn standard() -> Result<Self, IndicatorError> {
Self::new(12, 26, 9)
}
/// Calculate MACD for a series of values
pub fn calculate_series(
values: &[f64],
fast_period: usize,
slow_period: usize,
signal_period: usize
) -> Result<(Vec<f64>, Vec<f64>, Vec<f64>), IndicatorError> {
if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
"Fast period must be less than slow period".to_string()
));
}
if values.len() < slow_period {
return Err(IndicatorError::InsufficientData {
required: slow_period,
actual: values.len(),
});
}
// Calculate EMAs
let fast_ema = EMA::calculate_series(values, fast_period)?;
let slow_ema = EMA::calculate_series(values, slow_period)?;
// Calculate MACD line
let mut macd_line = Vec::with_capacity(slow_ema.len());
for i in 0..slow_ema.len() {
// Align indices - slow EMA starts later
let fast_idx = i + (slow_period - fast_period);
macd_line.push(fast_ema[fast_idx] - slow_ema[i]);
}
// Calculate signal line (EMA of MACD)
let signal_line = if macd_line.len() >= signal_period {
EMA::calculate_series(&macd_line, signal_period)?
} else {
vec![]
};
// Calculate histogram
let mut histogram = Vec::with_capacity(signal_line.len());
for i in 0..signal_line.len() {
// Align indices
let macd_idx = i + (macd_line.len() - signal_line.len());
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;
let (macd, signal, histogram) = Self::calculate_series(
values,
self.fast_period,
self.slow_period,
self.signal_period
)?;
Ok(IndicatorResult::MACD {
macd,
signal,
histogram,
})
}
fn reset(&mut self) {
self.fast_ema.reset();
self.slow_ema.reset();
self.signal_ema.reset();
self.macd_value = None;
}
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)?;
let slow_result = self.slow_ema.update(value)?;
// Calculate MACD if both EMAs are ready
if let (Some(fast), Some(slow)) = (fast_result, slow_result) {
let macd = fast - slow;
self.macd_value = Some(macd);
// Update signal line
if let Some(signal) = self.signal_ema.update(macd)? {
// Return histogram value
Ok(Some(macd - signal))
} else {
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(),
self.slow_ema.current(),
self.signal_ema.current()
) {
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,
pub histogram: f64,
}
impl MACD {
/// Get all current MACD values
pub fn current_values(&self) -> Option<MACDValues> {
if let (Some(fast), Some(slow), Some(signal)) = (
self.fast_ema.current(),
self.slow_ema.current(),
self.signal_ema.current()
) {
let macd = fast - slow;
Some(MACDValues {
macd,
signal,
histogram: macd - signal,
})
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_macd_calculation() {
let values = vec![
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
assert!(!macd.is_empty());
assert!(!signal.is_empty());
assert!(!histogram.is_empty());
// Histogram should equal MACD - Signal
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();
assert_eq!(macd.fast_period, 12);
assert_eq!(macd.slow_period, 26);
assert_eq!(macd.signal_period, 9);
}
}
use super::ema::EMA;
use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData};
/// Moving Average Convergence Divergence (MACD) Indicator
///
/// MACD = Fast EMA - Slow EMA
/// Signal = EMA of MACD
/// Histogram = MACD - Signal
pub struct MACD {
fast_period: usize,
slow_period: usize,
signal_period: usize,
fast_ema: EMA,
slow_ema: EMA,
signal_ema: EMA,
macd_value: Option<f64>,
}
impl MACD {
pub fn new(
fast_period: usize,
slow_period: usize,
signal_period: usize,
) -> Result<Self, IndicatorError> {
if fast_period == 0 || slow_period == 0 || signal_period == 0 {
return Err(IndicatorError::InvalidParameter(
"All periods must be greater than 0".to_string(),
));
}
if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
"Fast period must be less than slow period".to_string(),
));
}
Ok(Self {
fast_period,
slow_period,
signal_period,
fast_ema: EMA::new(fast_period)?,
slow_ema: EMA::new(slow_period)?,
signal_ema: EMA::new(signal_period)?,
macd_value: None,
})
}
/// Standard MACD with 12, 26, 9 periods
pub fn standard() -> Result<Self, IndicatorError> {
Self::new(12, 26, 9)
}
/// Calculate MACD for a series of values
pub fn calculate_series(
values: &[f64],
fast_period: usize,
slow_period: usize,
signal_period: usize,
) -> Result<(Vec<f64>, Vec<f64>, Vec<f64>), IndicatorError> {
if fast_period >= slow_period {
return Err(IndicatorError::InvalidParameter(
"Fast period must be less than slow period".to_string(),
));
}
if values.len() < slow_period {
return Err(IndicatorError::InsufficientData {
required: slow_period,
actual: values.len(),
});
}
// Calculate EMAs
let fast_ema = EMA::calculate_series(values, fast_period)?;
let slow_ema = EMA::calculate_series(values, slow_period)?;
// Calculate MACD line
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.
macd_line.push(fast_ema[i] - slow_ema[i]);
}
// Calculate signal line (EMA of MACD)
let signal_line = if macd_line.len() >= signal_period {
EMA::calculate_series(&macd_line, signal_period)?
} else {
vec![]
};
// Calculate histogram
let mut histogram = Vec::with_capacity(signal_line.len());
for i in 0..signal_line.len() {
// Align indices
let macd_idx = i + (macd_line.len() - signal_line.len());
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;
let (macd, signal, histogram) = Self::calculate_series(
values,
self.fast_period,
self.slow_period,
self.signal_period,
)?;
Ok(IndicatorResult::MACD {
macd,
signal,
histogram,
})
}
fn reset(&mut self) {
self.fast_ema.reset();
self.slow_ema.reset();
self.signal_ema.reset();
self.macd_value = None;
}
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)?;
let slow_result = self.slow_ema.update(value)?;
// Calculate MACD if both EMAs are ready
if let (Some(fast), Some(slow)) = (fast_result, slow_result) {
let macd = fast - slow;
self.macd_value = Some(macd);
// Update signal line
if let Some(signal) = self.signal_ema.update(macd)? {
// Return histogram value
Ok(Some(macd - signal))
} else {
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(),
self.slow_ema.current(),
self.signal_ema.current(),
) {
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,
pub histogram: f64,
}
impl MACD {
/// Get all current MACD values
pub fn current_values(&self) -> Option<MACDValues> {
if let (Some(fast), Some(slow), Some(signal)) = (
self.fast_ema.current(),
self.slow_ema.current(),
self.signal_ema.current(),
) {
let macd = fast - slow;
Some(MACDValues {
macd,
signal,
histogram: macd - signal,
})
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_macd_calculation() {
let values = vec![
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
assert!(!macd.is_empty());
assert!(!signal.is_empty());
assert!(!histogram.is_empty());
// Histogram should equal MACD - Signal
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();
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
* Demonstrates orderbook analytics, portfolio risk, and bet sizing
*/
import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('AdvancedRiskExample');
// Example 1: Orderbook Analytics
async function orderbookAnalyticsExample() {
console.log('\n=== Orderbook Analytics Example ===');
const engine = new TradingEngine('paper', { startingCapital: 100000 });
const obAnalyzer = new OrderbookAnalyzer();
// Update orderbook with some data
const symbol = 'AAPL';
engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200);
engine.updateQuote(symbol, 149.90, 150.10, 800, 900);
engine.updateQuote(symbol, 149.85, 150.15, 600, 700);
// Get orderbook snapshot
const snapshotJson = engine.getOrderbookSnapshot(symbol, 10);
const snapshot = JSON.parse(snapshotJson);
// Analyze orderbook
const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson);
const analytics = JSON.parse(analyticsJson);
console.log('Orderbook Analytics:');
console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`);
console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`);
console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`);
console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
// Calculate liquidity profile
const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson);
const profile = JSON.parse(profileJson);
console.log('\nLiquidity Profile:');
console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`);
console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`);
// Calculate market impact for a $10,000 buy order
const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true);
const impact = JSON.parse(impactJson);
console.log('\nMarket Impact ($10k buy):');
console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`);
console.log(` Slippage: $${impact.slippage.toFixed(2)}`);
console.log(` Levels Consumed: ${impact.levels_consumed}`);
}
// Example 2: Portfolio Risk Analysis
async function portfolioRiskExample() {
console.log('\n=== Portfolio Risk Analysis Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback
// Update historical returns for portfolio symbols
const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'];
// Simulate some returns data (in practice, load from historical data)
for (const symbol of symbols) {
const returns = generateRandomReturns(252);
riskAnalyzer.updateReturns(symbol, returns);
}
// Current positions
const positions = [
{ symbol: 'AAPL', quantity: 100, avgPrice: 150 },
{ symbol: 'GOOGL', quantity: 50, avgPrice: 140 },
{ symbol: 'MSFT', quantity: 75, avgPrice: 380 },
{ symbol: 'AMZN', quantity: 40, avgPrice: 170 },
{ symbol: 'META', quantity: 60, avgPrice: 480 }
];
// Current prices
const prices = {
AAPL: 155,
GOOGL: 145,
MSFT: 390,
AMZN: 175,
META: 490
};
// Calculate portfolio risk
const riskJson = riskAnalyzer.calculatePortfolioRisk(
JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])),
JSON.stringify(prices)
);
const risk = JSON.parse(riskJson);
console.log('Portfolio Risk Metrics:');
console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`);
console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`);
console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`);
console.log('\nConcentration Metrics:');
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(` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%`);
console.log('\nCorrelation Analysis:');
console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`);
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('\nStress Test Results:');
for (const [scenario, loss] of Object.entries(risk.stress_test_results)) {
console.log(` ${scenario}: $${(loss as number).toFixed(2)}`);
}
}
// Example 3: Dynamic Bet Sizing
async function betSizingExample() {
console.log('\n=== Dynamic Bet Sizing Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
// Scenario 1: Strong signal in trending market
console.log('\nScenario 1: Strong Signal, Trending Market');
let positionSize = riskAnalyzer.calculatePositionSize(
0.8, // signal_strength
0.9, // signal_confidence
0.015, // volatility (1.5% daily)
0.8, // liquidity_score
0.02, // current_drawdown (2%)
150, // price
145, // stop_loss
'trending'
);
let size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
console.log(' Adjustments:');
for (const adj of size.adjustments) {
console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`);
}
// Scenario 2: Weak signal in high volatility
console.log('\nScenario 2: Weak Signal, High Volatility');
positionSize = riskAnalyzer.calculatePositionSize(
0.3, // signal_strength
0.5, // signal_confidence
0.03, // volatility (3% daily)
0.6, // liquidity_score
0.15, // current_drawdown (15%)
150, // price
null, // no stop_loss
'high_volatility'
);
size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
// Calculate optimal stop loss
const supportLevels = [148, 145, 142, 140];
const optimalStop = riskAnalyzer.calculateOptimalStopLoss(
150, // entry_price
0.015, // volatility
supportLevels,
2.5, // atr
true // is_long
);
console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`);
}
// Example 4: Integrated Risk Management in Trading
async function integratedTradingExample() {
console.log('\n=== Integrated Risk Management Example ===');
const engine = new TradingEngine('backtest', {
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
endTime: Date.now(),
speedMultiplier: 1
});
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
const obAnalyzer = new OrderbookAnalyzer();
// Simulate a trading decision
const symbol = 'AAPL';
// 1. Check orderbook liquidity
engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500);
const snapshot = engine.getOrderbookSnapshot(symbol, 10);
const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot));
console.log('Pre-trade Analysis:');
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`);
console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
// 2. Calculate position size based on current conditions
const positionSizeJson = riskAnalyzer.calculatePositionSize(
0.7, // signal_strength
0.8, // signal_confidence
0.018, // volatility
analytics.liquidity_score, // from orderbook
0.05, // current_drawdown
150, // price
147, // stop_loss
'trending'
);
const positionSize = JSON.parse(positionSizeJson);
console.log(`\nPosition Sizing:`);
console.log(` Recommended Shares: ${positionSize.shares}`);
console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`);
// 3. Check market impact before placing order
const orderValue = positionSize.shares * 150;
const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true));
console.log(`\nExpected Market Impact:`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`);
console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`);
// 4. Risk check
const riskCheck = engine.checkRisk({
id: '123',
symbol: symbol,
side: 'buy',
quantity: positionSize.shares,
orderType: 'market',
timeInForce: 'DAY'
});
const riskResult = JSON.parse(riskCheck);
console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`);
if (!riskResult.passed) {
console.log(' Violations:', riskResult.violations);
}
}
// Helper function to generate random returns
function generateRandomReturns(length: number): number[] {
const returns: number[] = [];
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_);
}
return returns;
}
// Run all examples
async function runExamples() {
try {
await orderbookAnalyticsExample();
await portfolioRiskExample();
await betSizingExample();
await integratedTradingExample();
} catch (error) {
console.error('Error running examples:', error);
}
}
// Execute if running directly
if (require.main === module) {
runExamples();
}
/**
* Advanced Risk Management Examples
* Demonstrates orderbook analytics, portfolio risk, and bet sizing
*/
import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine';
import { getLogger } from '@stock-bot/logger';
const _logger = getLogger('AdvancedRiskExample');
// Example 1: Orderbook Analytics
async function orderbookAnalyticsExample() {
console.log('\n=== Orderbook Analytics Example ===');
const engine = new TradingEngine('paper', { startingCapital: 100000 });
const obAnalyzer = new OrderbookAnalyzer();
// Update orderbook with some data
const symbol = 'AAPL';
engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200);
engine.updateQuote(symbol, 149.9, 150.1, 800, 900);
engine.updateQuote(symbol, 149.85, 150.15, 600, 700);
// Get orderbook snapshot
const snapshotJson = engine.getOrderbookSnapshot(symbol, 10);
const _snapshot = JSON.parse(snapshotJson);
// Analyze orderbook
const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson);
const analytics = JSON.parse(analyticsJson);
console.log('Orderbook Analytics:');
console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`);
console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`);
console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`);
console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
// Calculate liquidity profile
const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson);
const profile = JSON.parse(profileJson);
console.log('\nLiquidity Profile:');
console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`);
console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`);
// Calculate market impact for a $10,000 buy order
const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true);
const impact = JSON.parse(impactJson);
console.log('\nMarket Impact ($10k buy):');
console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`);
console.log(` Slippage: $${impact.slippage.toFixed(2)}`);
console.log(` Levels Consumed: ${impact.levels_consumed}`);
}
// Example 2: Portfolio Risk Analysis
async function portfolioRiskExample() {
console.log('\n=== Portfolio Risk Analysis Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback
// Update historical returns for portfolio symbols
const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'];
// Simulate some returns data (in practice, load from historical data)
for (const symbol of symbols) {
const returns = generateRandomReturns(252);
riskAnalyzer.updateReturns(symbol, returns);
}
// Current positions
const positions = [
{ symbol: 'AAPL', quantity: 100, avgPrice: 150 },
{ symbol: 'GOOGL', quantity: 50, avgPrice: 140 },
{ symbol: 'MSFT', quantity: 75, avgPrice: 380 },
{ symbol: 'AMZN', quantity: 40, avgPrice: 170 },
{ symbol: 'META', quantity: 60, avgPrice: 480 },
];
// Current prices
const prices = {
AAPL: 155,
GOOGL: 145,
MSFT: 390,
AMZN: 175,
META: 490,
};
// Calculate portfolio risk
const riskJson = riskAnalyzer.calculatePortfolioRisk(
JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])),
JSON.stringify(prices)
);
const risk = JSON.parse(riskJson);
console.log('Portfolio Risk Metrics:');
console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`);
console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`);
console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`);
console.log('\nConcentration Metrics:');
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(
` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%`
);
console.log('\nCorrelation Analysis:');
console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`);
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('\nStress Test Results:');
for (const [scenario, loss] of Object.entries(risk.stress_test_results)) {
console.log(` ${scenario}: $${(loss as number).toFixed(2)}`);
}
}
// Example 3: Dynamic Bet Sizing
async function betSizingExample() {
console.log('\n=== Dynamic Bet Sizing Example ===');
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
// Scenario 1: Strong signal in trending market
console.log('\nScenario 1: Strong Signal, Trending Market');
let positionSize = riskAnalyzer.calculatePositionSize(
0.8, // signal_strength
0.9, // signal_confidence
0.015, // volatility (1.5% daily)
0.8, // liquidity_score
0.02, // current_drawdown (2%)
150, // price
145, // stop_loss
'trending'
);
let size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
console.log(' Adjustments:');
for (const adj of size.adjustments) {
console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`);
}
// Scenario 2: Weak signal in high volatility
console.log('\nScenario 2: Weak Signal, High Volatility');
positionSize = riskAnalyzer.calculatePositionSize(
0.3, // signal_strength
0.5, // signal_confidence
0.03, // volatility (3% daily)
0.6, // liquidity_score
0.15, // current_drawdown (15%)
150, // price
null, // no stop_loss
'high_volatility'
);
size = JSON.parse(positionSize);
console.log(` Shares: ${size.shares}`);
console.log(` Notional Value: $${size.notional_value.toFixed(2)}`);
console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`);
// Calculate optimal stop loss
const supportLevels = [148, 145, 142, 140];
const optimalStop = riskAnalyzer.calculateOptimalStopLoss(
150, // entry_price
0.015, // volatility
supportLevels,
2.5, // atr
true // is_long
);
console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`);
}
// Example 4: Integrated Risk Management in Trading
async function integratedTradingExample() {
console.log('\n=== Integrated Risk Management Example ===');
const engine = new TradingEngine('backtest', {
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
endTime: Date.now(),
speedMultiplier: 1,
});
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
const obAnalyzer = new OrderbookAnalyzer();
// Simulate a trading decision
const symbol = 'AAPL';
// 1. Check orderbook liquidity
engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500);
const snapshot = engine.getOrderbookSnapshot(symbol, 10);
const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot));
console.log('Pre-trade Analysis:');
console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`);
console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`);
console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`);
// 2. Calculate position size based on current conditions
const positionSizeJson = riskAnalyzer.calculatePositionSize(
0.7, // signal_strength
0.8, // signal_confidence
0.018, // volatility
analytics.liquidity_score, // from orderbook
0.05, // current_drawdown
150, // price
147, // stop_loss
'trending'
);
const positionSize = JSON.parse(positionSizeJson);
console.log(`\nPosition Sizing:`);
console.log(` Recommended Shares: ${positionSize.shares}`);
console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`);
// 3. Check market impact before placing order
const orderValue = positionSize.shares * 150;
const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true));
console.log(`\nExpected Market Impact:`);
console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`);
console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`);
// 4. Risk check
const riskCheck = engine.checkRisk({
id: '123',
symbol: symbol,
side: 'buy',
quantity: positionSize.shares,
orderType: 'market',
timeInForce: 'DAY',
});
const riskResult = JSON.parse(riskCheck);
console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`);
if (!riskResult.passed) {
console.log(' Violations:', riskResult.violations);
}
}
// Helper function to generate random returns
function generateRandomReturns(length: number): number[] {
const returns: number[] = [];
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_);
}
return returns;
}
// Run all examples
async function runExamples() {
try {
await orderbookAnalyticsExample();
await portfolioRiskExample();
await betSizingExample();
await integratedTradingExample();
} catch (error) {
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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
async function debugPositionTracking() {
// Create service container with detailed logging
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args),
warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args),
debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args),
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
// Set services in container
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Listen to strategy events for debugging
strategyManager.on('order', (orderEvent: any) => {
console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
});
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Position Tracking Debug',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('Starting position tracking debug...\n');
try {
const result = await backtestEngine.runBacktest(config);
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 DETAILS ===');
let buyCount = 0;
let sellCount = 0;
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` Quantity: ${trade.quantity}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
if (trade.side === 'buy') buyCount++;
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function debugPositionTracking() {
// Create service container with detailed logging
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Listen to strategy events for debugging
strategyManager.on('order', (orderEvent: unknown) => {
console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
});
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Position Tracking Debug',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Starting position tracking debug...\n');
try {
const result = await backtestEngine.runBacktest(config);
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 DETAILS ===');
let buyCount = 0;
let sellCount = 0;
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`);
console.log(` Quantity: ${trade.quantity}`);
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
if (trade.side === 'buy') {
buyCount++;
} 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';
async function debugRustShortTrades() {
// Create engine config for backtest mode
const engineConfig = {
startTime: new Date('2023-01-01').getTime(),
endTime: new Date('2023-02-01').getTime(),
speedMultiplier: 0
};
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
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...');
const sellOrder = {
id: 'sell-order-001',
symbol: 'TEST',
side: 'sell',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY'
};
const sellOrderId = engine.submitOrder(sellOrder);
console.log(` Sell order ID: ${sellOrderId}`);
// Process the sell fill
console.log('\n3. Processing SELL fill...');
const sellFillResult = engine.processFillWithMetadata(
'TEST', // symbol
50.0, // price
100, // quantity
'sell', // side
0.1, // commission
sellOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${sellFillResult}`);
// Check positions
console.log('\n4. Checking positions after SELL...');
const positionsAfterSell = engine.getPosition('TEST');
console.log(' Position:', positionsAfterSell);
// Check open trades
const openTradesAfterSell = JSON.parse(engine.getOpenTrades());
console.log(' Open trades:', openTradesAfterSell.length);
if (openTradesAfterSell.length > 0) {
console.log(' First open trade:', openTradesAfterSell[0]);
}
// Check closed trades
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...');
const buyOrder = {
id: 'buy-order-001',
symbol: 'TEST',
side: 'buy',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY'
};
const buyOrderId = engine.submitOrder(buyOrder);
console.log(` Buy order ID: ${buyOrderId}`);
// Process the buy fill
console.log('\n6. Processing BUY fill...');
const buyFillResult = engine.processFillWithMetadata(
'TEST', // symbol
48.0, // price (profit on short)
100, // quantity
'buy', // side
0.1, // commission
buyOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${buyFillResult}`);
// Check positions after closing
console.log('\n7. Checking positions after BUY...');
const positionsAfterBuy = engine.getPosition('TEST');
console.log(' Position:', positionsAfterBuy);
// Check open trades after closing
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());
console.log(' Closed trades:', closedTradesAfterBuy.length);
if (closedTradesAfterBuy.length > 0) {
console.log('\n8. Closed trade details:');
closedTradesAfterBuy.forEach((trade: any, i: number) => {
console.log(` Trade ${i + 1}:`);
console.log(` ID: ${trade.id}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`);
console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`);
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.');
}
// Also check trade history
console.log('\n9. Trade history:');
const tradeHistory = JSON.parse(engine.getTradeHistory());
tradeHistory.forEach((trade: any, i: number) => {
console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
});
// Check totals
console.log('\n10. Summary:');
console.log(` Total trades: ${engine.getTradeCount()}`);
console.log(` Closed trades: ${engine.getClosedTradeCount()}`);
const [realizedPnl, unrealizedPnl] = engine.getTotalPnl();
console.log(` Realized P&L: ${realizedPnl}`);
console.log(` Unrealized P&L: ${unrealizedPnl}`);
}
// Run the debug
debugRustShortTrades().catch(console.error);
import { TradingEngine } from '@stock-bot/engine';
import type { ClosedTrade } from '../src/backtest/native-result';
async function debugRustShortTrades() {
// Create engine config for backtest mode
const engineConfig = {
startTime: new Date('2023-01-01').getTime(),
endTime: new Date('2023-02-01').getTime(),
speedMultiplier: 0,
};
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
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...');
const sellOrder = {
id: 'sell-order-001',
symbol: 'TEST',
side: 'sell',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY',
};
const sellOrderId = engine.submitOrder(sellOrder);
console.log(` Sell order ID: ${sellOrderId}`);
// Process the sell fill
console.log('\n3. Processing SELL fill...');
const sellFillResult = engine.processFillWithMetadata(
'TEST', // symbol
50.0, // price
100, // quantity
'sell', // side
0.1, // commission
sellOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${sellFillResult}`);
// Check positions
console.log('\n4. Checking positions after SELL...');
const positionsAfterSell = engine.getPosition('TEST');
console.log(' Position:', positionsAfterSell);
// Check open trades
const openTradesAfterSell = JSON.parse(engine.getOpenTrades());
console.log(' Open trades:', openTradesAfterSell.length);
if (openTradesAfterSell.length > 0) {
console.log(' First open trade:', openTradesAfterSell[0]);
}
// Check closed trades
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...');
const buyOrder = {
id: 'buy-order-001',
symbol: 'TEST',
side: 'buy',
quantity: 100,
orderType: 'market',
timeInForce: 'DAY',
};
const buyOrderId = engine.submitOrder(buyOrder);
console.log(` Buy order ID: ${buyOrderId}`);
// Process the buy fill
console.log('\n6. Processing BUY fill...');
const buyFillResult = engine.processFillWithMetadata(
'TEST', // symbol
48.0, // price (profit on short)
100, // quantity
'buy', // side
0.1, // commission
buyOrderId, // orderId
'debug-strategy' // strategyId
);
console.log(` Fill result: ${buyFillResult}`);
// Check positions after closing
console.log('\n7. Checking positions after BUY...');
const positionsAfterBuy = engine.getPosition('TEST');
console.log(' Position:', positionsAfterBuy);
// Check open trades after closing
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());
console.log(' Closed trades:', closedTradesAfterBuy.length);
if (closedTradesAfterBuy.length > 0) {
console.log('\n8. Closed trade details:');
closedTradesAfterBuy.forEach((trade: ClosedTrade, i: number) => {
console.log(` Trade ${i + 1}:`);
console.log(` ID: ${trade.id}`);
console.log(` Side: ${trade.side}`);
console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`);
console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`);
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.');
}
// Also check trade history
console.log('\n9. Trade history:');
const tradeHistory = JSON.parse(engine.getTradeHistory());
tradeHistory.forEach((trade: ClosedTrade, i: number) => {
console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
});
// Check totals
console.log('\n10. Summary:');
console.log(` Total trades: ${engine.getTradeCount()}`);
console.log(` Closed trades: ${engine.getClosedTradeCount()}`);
const [realizedPnl, unrealizedPnl] = engine.getTotalPnl();
console.log(` Realized P&L: ${realizedPnl}`);
console.log(` Unrealized P&L: ${unrealizedPnl}`);
}
// 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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
// Modify the data generation to ensure we get both golden and death crosses
function generateMockDataWithBothCrosses() {
const data = [];
const startDate = new Date('2023-01-01');
let price = 150;
// Create 365 days of data with clear trends
for (let i = 0; i < 365; i++) {
const date = new Date(startDate);
date.setDate(date.getDate() + i);
// Create alternating trends every ~30 days
const cycleDay = i % 60;
if (cycleDay < 30) {
// Uptrend - will create golden crosses
price += Math.random() * 2 - 0.5; // Bias upward
} else {
// Downtrend - will create death crosses
price -= Math.random() * 2 - 0.5; // Bias downward
}
// Add some volatility
const dayChange = (Math.random() - 0.5) * 4;
price = Math.max(100, Math.min(200, price + dayChange));
data.push({
timestamp: date.toISOString(),
open: price - Math.random() * 2,
high: price + Math.random() * 2,
low: price - Math.random() * 2,
close: price,
volume: Math.floor(Math.random() * 10000000) + 5000000
});
}
return data;
}
async function forceBothTradeTypes() {
// Create service container with minimal logging
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => {
if (msg.includes('cross detected') || msg.includes('Generated') || msg.includes('Position update')) {
console.log('[INFO]', msg, ...args);
}
},
error: console.error,
warn: () => {},
debug: () => {},
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Override the mock data generation
const originalGenerateMockData = marketDataService.generateMockData;
marketDataService.generateMockData = function(symbol: string, startDate: string, endDate: string) {
console.log('Generating mock data with forced crossovers...');
return generateMockDataWithBothCrosses();
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Force Both Trade Types',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('=== TESTING WITH FORCED CROSSOVERS ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST COMPLETE ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
result.trades.forEach((trade) => {
if (trade.side === 'buy') {
longTrades++;
console.log(`\nLONG trade 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)}`);
} else {
shortTrades++;
console.log(`\nSHORT trade 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)}`);
}
});
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
// Modify the data generation to ensure we get both golden and death crosses
function generateMockDataWithBothCrosses() {
const data = [];
const startDate = new Date('2023-01-01');
let price = 150;
// Create 365 days of data with clear trends
for (let i = 0; i < 365; i++) {
const date = new Date(startDate);
date.setDate(date.getDate() + i);
// Create alternating trends every ~30 days
const cycleDay = i % 60;
if (cycleDay < 30) {
// Uptrend - will create golden crosses
price += Math.random() * 2 - 0.5; // Bias upward
} else {
// Downtrend - will create death crosses
price -= Math.random() * 2 - 0.5; // Bias downward
}
// Add some volatility
const dayChange = (Math.random() - 0.5) * 4;
price = Math.max(100, Math.min(200, price + dayChange));
data.push({
timestamp: date.toISOString(),
open: price - Math.random() * 2,
high: price + Math.random() * 2,
low: price - Math.random() * 2,
close: price,
volume: Math.floor(Math.random() * 10000000) + 5000000,
});
}
return data;
}
async function forceBothTradeTypes() {
// Create service container with minimal logging
const { container, storageService, marketDataService, modeManager, strategyManager } =
await createExampleRuntime();
// Override the mock data generation
const _originalGenerateMockData = marketDataService.generateMockData;
marketDataService.generateMockData = function (
_symbol: string,
_startDate: string,
_endDate: string
) {
console.log('Generating mock data with forced crossovers...');
return generateMockDataWithBothCrosses();
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Force Both Trade Types',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== TESTING WITH FORCED CROSSOVERS ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST COMPLETE ===');
console.log(`Total Trades: ${result.metrics.totalTrades}`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
result.trades.forEach(trade => {
if (trade.side === 'buy') {
longTrades++;
console.log(`\nLONG trade 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)}`);
} else {
shortTrades++;
console.log(`\nSHORT trade 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)}`);
}
});
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 @@
/**
* Examples of using the Rust-based Technical Analysis library
*/
import { IncrementalIndicators, SignalGenerator, TechnicalAnalysis } from '../src/indicators/TechnicalAnalysis';
// Example 1: Basic indicator calculations
async function basicIndicatorExample() {
console.log('=== Basic Indicator Example ===');
const ta = new TechnicalAnalysis();
// Sample price data
const prices = [
100, 102, 101, 103, 105, 104, 106, 108, 107, 109,
111, 110, 112, 114, 113, 115, 117, 116, 118, 120
];
// Calculate various indicators
const sma10 = ta.sma(prices, 10);
const ema10 = ta.ema(prices, 10);
const rsi14 = ta.rsi(prices, 14);
console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`);
// Latest values
console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`);
console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`);
console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`);
}
// Example 2: Real-time streaming indicators
async function streamingIndicatorExample() {
console.log('\n=== Streaming Indicator Example ===');
const manager = new IncrementalIndicators();
// Create indicators
manager.createSMA('sma_fast', 5);
manager.createSMA('sma_slow', 10);
manager.createEMA('ema', 10);
manager.createRSI('rsi', 14);
// Simulate real-time price updates
console.log('Processing real-time price updates...');
for (let i = 0; i < 20; i++) {
const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2;
const smaFast = manager.update('sma_fast', price);
const smaSlow = manager.update('sma_slow', price);
const ema = manager.update('ema', price);
const rsi = manager.update('rsi', price);
if (i >= 14) { // Once we have enough data
console.log(`Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}`);
}
}
}
// Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic)
async function complexIndicatorExample() {
console.log('\n=== Complex Indicator Example ===');
const ta = new TechnicalAnalysis();
// Generate more realistic price data
const generatePrices = (count: number) => {
const prices = { close: [], high: [], low: [], volume: [] } as any;
let basePrice = 100;
for (let i = 0; i < count; i++) {
const change = (Math.random() - 0.5) * 2;
basePrice += change;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
const prices = generatePrices(50);
// Calculate MACD
const macd = ta.macd(prices.close);
console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`);
console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`);
console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`);
// Calculate Bollinger Bands
const bb = ta.bollingerBands(prices.close, 20, 2);
const currentPrice = prices.close[prices.close.length - 1];
const bbPercent = (currentPrice - TechnicalAnalysis.latest(bb.lower)!) /
(TechnicalAnalysis.latest(bb.upper)! - TechnicalAnalysis.latest(bb.lower)!);
console.log(`\nBollinger Bands:`);
console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`);
console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`);
console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`);
console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`);
// Calculate Stochastic
const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3);
console.log(`\nStochastic:`);
console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`);
console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`);
// Calculate ATR
const atr = ta.atr(prices.high, prices.low, prices.close, 14);
console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`);
}
// Example 4: Trading signal generation
async function signalGenerationExample() {
console.log('\n=== Signal Generation Example ===');
const generator = new SignalGenerator();
// Generate trending market data
const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => {
const prices = { close: [], high: [], low: [], volume: [] } as any;
let basePrice = 100;
for (let i = 0; i < count; i++) {
const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0;
const noise = (Math.random() - 0.5) * 2;
basePrice += trendComponent + noise;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
// Test different market conditions
const scenarios = [
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') },
{ name: 'Downtrend', data: generateTrendingPrices(50, 'down') },
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') }
];
for (const scenario of scenarios) {
const signal = generator.generateSignals('TEST', scenario.data, Date.now());
console.log(`\n${scenario.name} Market:`);
console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`);
console.log(`Reason: ${signal.reason}`);
console.log(`Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`);
}
}
// Example 5: Crossover detection
async function crossoverExample() {
console.log('\n=== Crossover Detection Example ===');
const ta = new TechnicalAnalysis();
// Generate price data with clear trend changes
const prices: number[] = [];
for (let i = 0; i < 100; i++) {
if (i < 30) {
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
}
}
// Calculate moving averages
const fastMA = ta.sma(prices, 10);
const slowMA = ta.sma(prices, 20);
// Detect crossovers
console.log('Checking for crossovers in the last 10 bars:');
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);
if (TechnicalAnalysis.crossover(fast, slow)) {
console.log(`Bullish crossover at index ${i + 20}`);
} 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();
}
import { defined } from '@stock-bot/invariants';
/**
* Examples of using the Rust-based Technical Analysis library
*/
import {
IncrementalIndicators,
SignalGenerator,
TechnicalAnalysis,
} from '../src/indicators/TechnicalAnalysis';
// Example 1: Basic indicator calculations
async function basicIndicatorExample() {
console.log('=== Basic Indicator Example ===');
const ta = new TechnicalAnalysis();
// Sample price data
const prices = [
100, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111, 110, 112, 114, 113, 115, 117, 116, 118,
120,
];
// Calculate various indicators
const sma10 = ta.sma(prices, 10);
const ema10 = ta.ema(prices, 10);
const rsi14 = ta.rsi(prices, 14);
console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`);
console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`);
// Latest values
console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`);
console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`);
console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`);
}
// Example 2: Real-time streaming indicators
async function streamingIndicatorExample() {
console.log('\n=== Streaming Indicator Example ===');
const manager = new IncrementalIndicators();
// Create indicators
manager.createSMA('sma_fast', 5);
manager.createSMA('sma_slow', 10);
manager.createEMA('ema', 10);
manager.createRSI('rsi', 14);
// Simulate real-time price updates
console.log('Processing real-time price updates...');
for (let i = 0; i < 20; i++) {
const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2;
const smaFast = manager.update('sma_fast', price);
const smaSlow = manager.update('sma_slow', price);
const ema = manager.update('ema', price);
const rsi = manager.update('rsi', price);
if (i >= 14) {
// Once we have enough data
console.log(
`Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}`
);
}
}
}
// Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic)
async function complexIndicatorExample() {
console.log('\n=== Complex Indicator Example ===');
const ta = new TechnicalAnalysis();
// Generate more realistic price data
const generatePrices = (count: number) => {
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
close: [],
high: [],
low: [],
volume: [],
};
let basePrice = 100;
for (let i = 0; i < count; i++) {
const change = (Math.random() - 0.5) * 2;
basePrice += change;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
const prices = generatePrices(50);
// Calculate MACD
const macd = ta.macd(prices.close);
console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`);
console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`);
console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`);
// Calculate Bollinger Bands
const bb = ta.bollingerBands(prices.close, 20, 2);
const currentPrice = prices.close[prices.close.length - 1];
const bbPercent =
(currentPrice - defined(TechnicalAnalysis.latest(bb.lower))) /
(defined(TechnicalAnalysis.latest(bb.upper)) - defined(TechnicalAnalysis.latest(bb.lower)));
console.log(`\nBollinger Bands:`);
console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`);
console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`);
console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`);
console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`);
// Calculate Stochastic
const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3);
console.log(`\nStochastic:`);
console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`);
console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`);
// Calculate ATR
const atr = ta.atr(prices.high, prices.low, prices.close, 14);
console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`);
}
// Example 4: Trading signal generation
async function signalGenerationExample() {
console.log('\n=== Signal Generation Example ===');
const generator = new SignalGenerator();
// Generate trending market data
const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => {
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
close: [],
high: [],
low: [],
volume: [],
};
let basePrice = 100;
for (let i = 0; i < count; i++) {
const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0;
const noise = (Math.random() - 0.5) * 2;
basePrice += trendComponent + noise;
const high = basePrice + Math.random() * 1;
const low = basePrice - Math.random() * 1;
const close = low + Math.random() * (high - low);
prices.close.push(close);
prices.high.push(high);
prices.low.push(low);
prices.volume.push(Math.random() * 1000000 + 500000);
}
return prices;
};
// Test different market conditions
const scenarios = [
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') },
{ name: 'Downtrend', data: generateTrendingPrices(50, 'down') },
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') },
];
for (const scenario of scenarios) {
const signal = generator.generateSignals('TEST', scenario.data, Date.now());
console.log(`\n${scenario.name} Market:`);
console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`);
console.log(`Reason: ${signal.reason}`);
console.log(
`Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`
);
}
}
// Example 5: Crossover detection
async function crossoverExample() {
console.log('\n=== Crossover Detection Example ===');
const ta = new TechnicalAnalysis();
// Generate price data with clear trend changes
const prices: number[] = [];
for (let i = 0; i < 100; i++) {
if (i < 30) {
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
}
}
// Calculate moving averages
const fastMA = ta.sma(prices, 10);
const slowMA = ta.sma(prices, 20);
// Detect crossovers
console.log('Checking for crossovers in the last 10 bars:');
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);
if (TechnicalAnalysis.crossover(fast, slow)) {
console.log(`Bullish crossover at index ${i + 20}`);
} 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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
async function showOrderFlow() {
// Create service container
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => {
// Only log order-related messages
if (msg.includes('order') || msg.includes('Order') || msg.includes('Filling') || msg.includes('cross detected')) {
console.log('[INFO]', msg, ...args);
}
},
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args),
warn: (msg: string, ...args: any[]) => {},
debug: (msg: string, ...args: any[]) => {},
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
// Set services in container
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z', // Just 1 month
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Order Flow Demo',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('\n=== ORDER FLOW DEMONSTRATION ===\n');
console.log('This will show the actual BUY and SELL orders being generated and executed:\n');
try {
const result = await backtestEngine.runBacktest(config);
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function showOrderFlow() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z', // Just 1 month
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Order Flow Demo',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-07-01T00:00:00Z',
endDate: '2023-08-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('\n=== ORDER FLOW DEMONSTRATION ===\n');
console.log('This will show the actual BUY and SELL orders being generated and executed:\n');
try {
const result = await backtestEngine.runBacktest(config);
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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('BacktestTest');
async function runSimpleBacktest() {
// Create service container
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args),
warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args),
debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args),
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
// Set services in container
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest - shorter period for faster testing
const config = {
mode: 'backtest' as const, // Add mode field
name: 'SMA Crossover Test',
strategy: 'sma-crossover',
symbols: ['AAPL'], // Just one symbol for simplicity
startDate: '2023-01-01T00:00:00Z', // ISO datetime format
endDate: '2024-01-01T00:00:00Z', // ISO datetime format
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('Starting backtest with configuration:', config);
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST RESULTS ===');
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(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`);
console.log('\n=== TRADE HISTORY ===');
if (result.trades.length === 0) {
console.log('No trades were executed!');
} else {
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
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)}%)`);
});
}
// 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);
import { getLogger } from '@stock-bot/logger';
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
const _logger = getLogger('BacktestTest');
async function runSimpleBacktest() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode with full config
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest - shorter period for faster testing
const config = {
mode: 'backtest' as const, // Add mode field
name: 'SMA Crossover Test',
strategy: 'sma-crossover',
symbols: ['AAPL'], // Just one symbol for simplicity
startDate: '2023-01-01T00:00:00Z', // ISO datetime format
endDate: '2024-01-01T00:00:00Z', // ISO datetime format
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Starting backtest with configuration:', config);
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== BACKTEST RESULTS ===');
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(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`);
console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`);
console.log('\n=== TRADE HISTORY ===');
if (result.trades.length === 0) {
console.log('No trades were executed!');
} else {
result.trades.forEach((trade, i) => {
console.log(`\nTrade ${i + 1}:`);
console.log(` Symbol: ${trade.symbol}`);
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)}%)`);
});
}
// 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
/**
* Example of running a sophisticated backtest with all advanced features
*/
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { AnalyticsService } from '../src/services/AnalyticsService';
import { MeanReversionStrategy } from '../src/strategies/examples/MeanReversionStrategy';
import { MLEnhancedStrategy } from '../src/strategies/examples/MLEnhancedStrategy';
import { logger } from '@stock-bot/logger';
async function runSophisticatedBacktest() {
// Initialize services
const storageService = new StorageService();
await storageService.initialize({ mode: 'backtest' });
const analyticsService = new AnalyticsService({
analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003'
});
const strategyManager = new StrategyManager();
// Create backtest engine
const backtestEngine = new BacktestEngine(storageService, strategyManager);
// Configure backtest with advanced options
const config = {
mode: 'backtest' as const,
startDate: '2023-01-01T00:00:00Z',
endDate: '2023-12-31T23:59:59Z',
symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'],
initialCapital: 1_000_000,
dataFrequency: '5m' as const, // 5-minute bars for detailed analysis
// Advanced fill model configuration
fillModel: {
slippage: 'realistic' as const,
marketImpact: true,
partialFills: true,
// Use sophisticated market impact models
impactModel: 'AlmgrenChriss',
// Model hidden liquidity and dark pools
includeHiddenLiquidity: true,
darkPoolParticipation: 0.2, // 20% of volume in dark pools
// Realistic latency simulation
latencyMs: {
mean: 1,
std: 0.5,
tail: 10 // Occasional high latency
}
},
// Risk limits
riskLimits: {
maxPositionSize: 100_000,
maxDailyLoss: 50_000,
maxDrawdown: 0.20, // 20% max drawdown
maxLeverage: 2.0,
maxConcentration: 0.30 // Max 30% in single position
},
// Transaction costs
costs: {
commission: 0.0005, // 5 bps
borrowRate: 0.03, // 3% annual for shorts
slippageModel: 'volumeDependent'
},
// Strategies to test
strategies: [
{
id: 'mean_reversion_1',
name: 'Mean Reversion Strategy',
type: 'MeanReversion',
enabled: true,
allocation: 0.5,
symbols: ['AAPL', 'GOOGL', 'MSFT'],
parameters: {
lookback: 20,
entryZScore: 2.0,
exitZScore: 0.5,
minVolume: 1_000_000,
stopLoss: 0.05 // 5% stop loss
}
},
{
id: 'ml_enhanced_1',
name: 'ML Enhanced Strategy',
type: 'MLEnhanced',
enabled: true,
allocation: 0.5,
symbols: ['AMZN', 'TSLA'],
parameters: {
modelPath: './models/ml_strategy_v1',
updateFrequency: 1440, // Daily retraining
minConfidence: 0.6
}
}
]
};
logger.info('Starting sophisticated backtest...');
try {
// Run the backtest
const result = await backtestEngine.runBacktest(config);
logger.info('Backtest completed successfully');
logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`);
logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`);
logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`);
// Run statistical validation
logger.info('Running statistical validation...');
const validationResult = await analyticsService.validateBacktest({
backtestId: result.id,
returns: result.dailyReturns,
trades: result.trades,
parameters: extractParameters(config.strategies)
});
if (validationResult.is_overfit) {
logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!');
logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`);
logger.warn('Recommendations:');
validationResult.recommendations.forEach(rec => {
logger.warn(` - ${rec}`);
});
} else {
logger.info('✅ Backtest passed statistical validation');
logger.info(`PSR: ${validationResult.psr.toFixed(3)}`);
logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`);
}
// Generate comprehensive report
logger.info('Generating performance report...');
const report = await backtestEngine.exportResults('html');
// Save report
const fs = require('fs');
const reportPath = `./reports/backtest_${result.id}.html`;
fs.writeFileSync(reportPath, report);
logger.info(`Report saved to: ${reportPath}`);
// Advanced analytics
logger.info('Running advanced analytics...');
// Factor attribution
const factorAnalysis = await analyticsService.analyzeFactors({
returns: result.dailyReturns,
positions: result.finalPositions,
marketReturns: await getMarketReturns(config.startDate, config.endDate)
});
logger.info('Factor Attribution:');
logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`);
logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`);
logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`);
// Transaction cost analysis
const tcaReport = await analyticsService.analyzeTCA({
trades: result.trades,
orders: result.orders
});
logger.info('Transaction Cost Analysis:');
logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`);
logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`);
logger.info(` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps`);
// Performance by time period
const periodAnalysis = analyzeByPeriod(result);
logger.info('Performance by Period:');
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:');
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)}%`);
logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`);
// Walk-forward analysis suggestion
if (result.performance.totalTrades > 100) {
logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation');
logger.info('Example: bun run examples/walk-forward-analysis.ts');
}
} catch (error) {
logger.error('Backtest failed:', error);
} finally {
await storageService.shutdown();
}
}
// Helper functions
function extractParameters(strategies: any[]): Record<string, any> {
const params: Record<string, any> = {};
strategies.forEach(strategy => {
Object.entries(strategy.parameters).forEach(([key, value]) => {
params[`${strategy.id}_${key}`] = value;
});
});
return params;
}
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
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);
}
function analyzeByPeriod(result: any): Record<string, { return: number; sharpe: number }> {
const periods = {
'Q1': { start: 0, end: 63 },
'Q2': { start: 63, end: 126 },
'Q3': { start: 126, end: 189 },
'Q4': { start: 189, end: 252 }
};
const analysis: Record<string, { return: number; sharpe: number }> = {};
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(periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length);
analysis[name] = {
return: avgReturn * periodReturns.length * 100,
sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0
};
}
});
return analysis;
}
async function calculateStrategyCorrelations(result: any): Promise<Array<{ pair: string; correlation: number }>> {
// In real implementation, would calculate actual strategy return correlations
// For demo, return sample correlations
return [
{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }
];
}
async function runMonteCarloSimulation(result: any, numSims: number): Promise<{ var95: number; cvar95: number }> {
const returns = result.dailyReturns;
const simulatedReturns: number[] = [];
for (let i = 0; i < numSims; i++) {
// Bootstrap resample returns
let cumReturn = 0;
for (let j = 0; j < returns.length; j++) {
const randomIndex = Math.floor(Math.random() * returns.length);
cumReturn += returns[randomIndex];
}
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);
#!/usr/bin/env bun
/**
* Example of running a sophisticated backtest with all advanced features
*/
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { AnalyticsService } from '../src/services/AnalyticsService';
import { StorageService } from '../src/services/StorageService';
import { StrategyManager } from '../src/strategies/StrategyManager';
import '../src/strategies/examples/MeanReversionStrategy';
import '../src/strategies/examples/MLEnhancedStrategy';
import { logger } from '@stock-bot/logger';
async function runSophisticatedBacktest() {
// Initialize services
const storageService = new StorageService();
await storageService.initialize({ mode: 'backtest' });
const analyticsService = new AnalyticsService({
analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003',
});
const strategyManager = new StrategyManager();
// Create backtest engine
const backtestEngine = new BacktestEngine(storageService, strategyManager);
// Configure backtest with advanced options
const config = {
mode: 'backtest' as const,
startDate: '2023-01-01T00:00:00Z',
endDate: '2023-12-31T23:59:59Z',
symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'],
initialCapital: 1_000_000,
dataFrequency: '5m' as const, // 5-minute bars for detailed analysis
// Advanced fill model configuration
fillModel: {
slippage: 'realistic' as const,
marketImpact: true,
partialFills: true,
// Use sophisticated market impact models
impactModel: 'AlmgrenChriss',
// Model hidden liquidity and dark pools
includeHiddenLiquidity: true,
darkPoolParticipation: 0.2, // 20% of volume in dark pools
// Realistic latency simulation
latencyMs: {
mean: 1,
std: 0.5,
tail: 10, // Occasional high latency
},
},
// Risk limits
riskLimits: {
maxPositionSize: 100_000,
maxDailyLoss: 50_000,
maxDrawdown: 0.2, // 20% max drawdown
maxLeverage: 2.0,
maxConcentration: 0.3, // Max 30% in single position
},
// Transaction costs
costs: {
commission: 0.0005, // 5 bps
borrowRate: 0.03, // 3% annual for shorts
slippageModel: 'volumeDependent',
},
// Strategies to test
strategies: [
{
id: 'mean_reversion_1',
name: 'Mean Reversion Strategy',
type: 'MeanReversion',
enabled: true,
allocation: 0.5,
symbols: ['AAPL', 'GOOGL', 'MSFT'],
parameters: {
lookback: 20,
entryZScore: 2.0,
exitZScore: 0.5,
minVolume: 1_000_000,
stopLoss: 0.05, // 5% stop loss
},
},
{
id: 'ml_enhanced_1',
name: 'ML Enhanced Strategy',
type: 'MLEnhanced',
enabled: true,
allocation: 0.5,
symbols: ['AMZN', 'TSLA'],
parameters: {
modelPath: './models/ml_strategy_v1',
updateFrequency: 1440, // Daily retraining
minConfidence: 0.6,
},
},
],
};
logger.info('Starting sophisticated backtest...');
try {
// Run the backtest
const result = await backtestEngine.runBacktest(config);
logger.info('Backtest completed successfully');
logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`);
logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`);
logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`);
// Run statistical validation
logger.info('Running statistical validation...');
const validationResult = await analyticsService.validateBacktest({
backtestId: result.id,
returns: result.dailyReturns,
trades: result.trades,
parameters: extractParameters(config.strategies),
});
if (validationResult.is_overfit) {
logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!');
logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`);
logger.warn('Recommendations:');
validationResult.recommendations.forEach(rec => {
logger.warn(` - ${rec}`);
});
} else {
logger.info('✅ Backtest passed statistical validation');
logger.info(`PSR: ${validationResult.psr.toFixed(3)}`);
logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`);
}
// Generate comprehensive report
logger.info('Generating performance report...');
const report = await backtestEngine.exportResults('html');
// Save report
const fs = require('fs');
const reportPath = `./reports/backtest_${result.id}.html`;
fs.writeFileSync(reportPath, report);
logger.info(`Report saved to: ${reportPath}`);
// Advanced analytics
logger.info('Running advanced analytics...');
// Factor attribution
const factorAnalysis = await analyticsService.analyzeFactors({
returns: result.dailyReturns,
positions: result.finalPositions,
marketReturns: await getMarketReturns(config.startDate, config.endDate),
});
logger.info('Factor Attribution:');
logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`);
logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`);
logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`);
// Transaction cost analysis
const tcaReport = await analyticsService.analyzeTCA({
trades: result.trades,
orders: result.orders,
});
logger.info('Transaction Cost Analysis:');
logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`);
logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`);
logger.info(
` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps`
);
// Performance by time period
const periodAnalysis = analyzeByPeriod(result);
logger.info('Performance by Period:');
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:');
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)}%`);
logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`);
// Walk-forward analysis suggestion
if (result.performance.totalTrades > 100) {
logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation');
logger.info('Example: bun run examples/walk-forward-analysis.ts');
}
} catch (error) {
logger.error('Backtest failed:', error);
} finally {
await storageService.shutdown();
}
}
// Helper functions
function extractParameters(
strategies: { id: string; parameters: Record<string, unknown> }[]
): Record<string, unknown> {
const params: Record<string, unknown> = {};
strategies.forEach(strategy => {
Object.entries(strategy.parameters).forEach(([key, value]) => {
params[`${strategy.id}_${key}`] = value;
});
});
return params;
}
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
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);
}
function analyzeByPeriod(result: {
dailyReturns: number[];
}): Record<string, { return: number; sharpe: number }> {
const periods = {
Q1: { start: 0, end: 63 },
Q2: { start: 63, end: 126 },
Q3: { start: 126, end: 189 },
Q4: { start: 189, end: 252 },
};
const analysis: Record<string, { return: number; sharpe: number }> = {};
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(
periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length
);
analysis[name] = {
return: avgReturn * periodReturns.length * 100,
sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0,
};
}
});
return analysis;
}
async function calculateStrategyCorrelations(_result: {
dailyReturns: number[];
}): Promise<Array<{ pair: string; correlation: number }>> {
// In real implementation, would calculate actual strategy return correlations
// For demo, return sample correlations
return [{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }];
}
async function runMonteCarloSimulation(
result: { dailyReturns: number[] },
numSims: number
): Promise<{ var95: number; cvar95: number }> {
const returns = result.dailyReturns;
const simulatedReturns: number[] = [];
for (let i = 0; i < numSims; i++) {
// Bootstrap resample returns
let cumReturn = 0;
for (let j = 0; j < returns.length; j++) {
const randomIndex = Math.floor(Math.random() * returns.length);
cumReturn += returns[randomIndex];
}
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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
async function testShortTrades() {
// Create service container
const container: IServiceContainer = {
logger: {
info: () => {},
error: console.error,
warn: () => {},
debug: () => {},
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Trade Test',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('Testing short trade recording...\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST RESULTS ===');
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)}%`);
// Count long vs short trades
let longTrades = 0;
let shortTrades = 0;
console.log('\n=== TRADE BREAKDOWN ===');
result.trades.forEach((trade, i) => {
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') longTrades++;
else shortTrades++;
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function testShortTrades() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Trade Test',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('Testing short trade recording...\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST RESULTS ===');
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)}%`);
// Count long vs short trades
let longTrades = 0;
let shortTrades = 0;
console.log('\n=== TRADE BREAKDOWN ===');
result.trades.forEach((trade, i) => {
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
if (trade.side === 'buy') {
longTrades++;
} else {
shortTrades++;
}
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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
async function traceShortPositions() {
let orderCount = 0;
let fillCount = 0;
const orderTracker: any[] = [];
const fillTracker: any[] = [];
// Create service container with detailed logging
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => {
// Log all order and fill events
if (msg.includes('order') || msg.includes('Order') ||
msg.includes('fill') || msg.includes('Fill') ||
msg.includes('position') || msg.includes('Position')) {
console.log('[INFO]', msg, ...args);
}
// Track order submissions
if (msg.includes('Submitting order')) {
orderCount++;
const orderData = args[0];
orderTracker.push({
count: orderCount,
symbol: orderData.symbol,
side: orderData.side,
quantity: orderData.quantity,
type: orderData.type
});
console.log(`\n🔵 ORDER #${orderCount}:`, orderData.side.toUpperCase(), orderData.symbol);
}
// Track fills
if (msg.includes('Order filled')) {
fillCount++;
const fillData = args[0];
fillTracker.push({
count: fillCount,
orderId: fillData.orderId,
symbol: fillData.symbol,
side: fillData.side,
price: fillData.price,
quantity: fillData.quantity
});
console.log(`\n🟢 FILL #${fillCount}:`, fillData.side.toUpperCase(), fillData.symbol, '@', fillData.price);
}
},
error: console.error,
warn: () => {},
debug: () => {},
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Listen to strategy events
strategyManager.on('signal', (signal: any) => {
console.log('\n🎯 STRATEGY SIGNAL:', signal);
});
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // 3 months
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Position Trace',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('=== TRACING SHORT POSITION FLOW ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== ORDER/FILL TRACKING SUMMARY ===');
console.log(`Total orders submitted: ${orderCount}`);
console.log(`Total fills executed: ${fillCount}`);
// Analyze order flow
let buyOrders = 0;
let sellOrders = 0;
orderTracker.forEach(order => {
if (order.side === 'buy') buyOrders++;
else sellOrders++;
});
console.log(`\nOrder breakdown:`);
console.log(`- BUY orders: ${buyOrders}`);
console.log(`- SELL orders: ${sellOrders}`);
// Check for short positions
console.log('\n=== LOOKING FOR SHORT PATTERNS ===');
console.log('(A short position starts with a SELL and closes with a BUY)\n');
let potentialShorts = 0;
for (let i = 0; i < orderTracker.length - 1; i++) {
if (orderTracker[i].side === 'sell') {
// Look for subsequent buy to close
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import type { StrategyFill } from '../src/services/ExecutionService';
import type { OrderRequest } from '../src/types';
import { createExampleRuntime } from './example-runtime';
async function traceShortPositions() {
let orderCount = 0;
let fillCount = 0;
const orderTracker: (OrderRequest & { count: number })[] = [];
const fillTracker: StrategyFill[] = [];
// Create service container with detailed logging
const { container, storageService, modeManager, strategyManager } = await createExampleRuntime();
strategyManager.on('order', (event: { order: OrderRequest }) => {
orderTracker.push({ ...event.order, count: ++orderCount });
});
strategyManager.on('fill', (fill: StrategyFill) => {
fillCount++;
fillTracker.push(fill);
});
// Listen to strategy events
strategyManager.on('signal', (signal: unknown) => {
console.log('\n🎯 STRATEGY SIGNAL:', signal);
});
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z', // 3 months
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Short Position Trace',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-06-01T00:00:00Z',
endDate: '2023-09-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== TRACING SHORT POSITION FLOW ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('\n=== ORDER/FILL TRACKING SUMMARY ===');
console.log(`Total orders submitted: ${orderCount}`);
console.log(`Total fills executed: ${fillCount}`);
// Analyze order flow
let buyOrders = 0;
let sellOrders = 0;
orderTracker.forEach(order => {
if (order.side === 'buy') {
buyOrders++;
} else {
sellOrders++;
}
});
console.log(`\nOrder breakdown:`);
console.log(`- BUY orders: ${buyOrders}`);
console.log(`- SELL orders: ${sellOrders}`);
// Check for short positions
console.log('\n=== LOOKING FOR SHORT PATTERNS ===');
console.log('(A short position starts with a SELL and closes with a BUY)\n');
let potentialShorts = 0;
for (let i = 0; i < orderTracker.length - 1; i++) {
if (orderTracker[i].side === 'sell') {
// Look for subsequent buy to close
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 { StrategyManager } from '../src/strategies/StrategyManager';
import { StorageService } from '../src/services/StorageService';
import { ModeManager } from '../src/core/ModeManager';
import { MarketDataService } from '../src/services/MarketDataService';
import { ExecutionService } from '../src/services/ExecutionService';
import { IServiceContainer } from '@stock-bot/di';
async function verifyBothTradeTypes() {
// Create service container
const container: IServiceContainer = {
logger: {
info: console.log,
error: console.error,
warn: console.warn,
debug: console.log,
} as any,
custom: {}
};
// Initialize services
const storageService = new StorageService();
const marketDataService = new MarketDataService(container);
const executionService = new ExecutionService(container);
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
const strategyManager = new StrategyManager(container);
container.custom = {
MarketDataService: marketDataService,
ExecutionService: executionService,
ModeManager: modeManager,
StorageService: storageService
};
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Trade Type Verification',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const
};
console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST COMPLETE ===');
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)}%`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
let longPnL = 0;
let shortPnL = 0;
console.log('\n=== DETAILED TRADE ANALYSIS ===');
result.trades.forEach((trade, i) => {
const isLong = trade.side === 'buy';
const tradeType = isLong ? 'LONG' : 'SHORT';
if (isLong) {
longTrades++;
longPnL += trade.pnl;
} else {
shortTrades++;
shortPnL += trade.pnl;
}
console.log(`\nTrade ${i + 1}:`);
console.log(` Type: ${tradeType} position`);
console.log(` Opening side: ${trade.side.toUpperCase()}`);
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)}%)`);
// Explain the trade flow
if (isLong) {
console.log(` Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`);
} else {
console.log(` Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`);
}
});
console.log('\n=== SUMMARY BY TRADE TYPE ===');
console.log(`LONG trades: ${longTrades}`);
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}`);
console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`);
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);
import { BacktestEngine } from '../src/backtest/BacktestEngine';
import { createExampleRuntime } from './example-runtime';
async function verifyBothTradeTypes() {
// Create service container
const {
container,
storageService,
marketDataService: _marketDataService,
modeManager,
strategyManager,
} = await createExampleRuntime();
// Initialize backtest mode
await modeManager.initializeMode({
mode: 'backtest',
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
speed: 'max',
symbols: ['AAPL'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover',
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Configure backtest
const config = {
mode: 'backtest' as const,
name: 'Trade Type Verification',
strategy: 'sma-crossover',
symbols: ['AAPL'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2024-01-01T00:00:00Z',
initialCapital: 100000,
commission: 0.001,
slippage: 0.0001,
dataFrequency: '1d' as const,
speed: 'max' as const,
};
console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');
try {
const result = await backtestEngine.runBacktest(config);
console.log('=== BACKTEST COMPLETE ===');
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)}%`);
// Analyze trades
let longTrades = 0;
let shortTrades = 0;
let longPnL = 0;
let shortPnL = 0;
console.log('\n=== DETAILED TRADE ANALYSIS ===');
result.trades.forEach((trade, i) => {
const isLong = trade.side === 'buy';
const tradeType = isLong ? 'LONG' : 'SHORT';
if (isLong) {
longTrades++;
longPnL += trade.pnl;
} else {
shortTrades++;
shortPnL += trade.pnl;
}
console.log(`\nTrade ${i + 1}:`);
console.log(` Type: ${tradeType} position`);
console.log(` Opening side: ${trade.side.toUpperCase()}`);
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)}%)`);
// Explain the trade flow
if (isLong) {
console.log(` Order flow: BUY ${trade.quantity} shares → SELL ${trade.quantity} shares`);
} else {
console.log(` Order flow: SELL ${trade.quantity} shares → BUY ${trade.quantity} shares`);
}
});
console.log('\n=== SUMMARY BY TRADE TYPE ===');
console.log(`LONG trades: ${longTrades}`);
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}`);
console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`);
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",
"scripts": {
"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",
"test": "bun test",
"test:indicators": "bun test tests/indicators.test.ts",
@ -31,7 +31,11 @@
"zod": "^3.22.0",
"uuid": "^9.0.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": {
"@tensorflow/tfjs-node": "^4.0.0"
@ -43,6 +47,7 @@
},
"devDependencies": {
"@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 { z } from 'zod';
import { IServiceContainer } from '@stock-bot/di';
import { AnalyticsService } from '../../services/AnalyticsService';
const DateRangeSchema = z.object({
startDate: z.string().datetime(),
endDate: z.string().datetime()
});
const OptimizationRequestSchema = z.object({
symbols: z.array(z.string()),
returns: z.array(z.array(z.number())),
constraints: z.object({
minWeight: z.number().optional(),
maxWeight: z.number().optional(),
targetReturn: z.number().optional(),
maxRisk: z.number().optional()
}).optional()
});
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
// Get performance metrics
app.get('/performance/:portfolioId', async (c) => {
try {
const portfolioId = c.req.param('portfolioId');
const query = c.req.query();
const { startDate, endDate } = DateRangeSchema.parse({
startDate: query.start_date,
endDate: query.end_date
});
const metrics = await analyticsService.getPerformanceMetrics(
portfolioId,
new Date(startDate),
new Date(endDate)
);
return c.json(metrics);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({
error: 'Invalid date range',
details: error.errors
}, 400);
}
container.logger.error('Error getting performance metrics:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to get performance metrics'
}, 500);
}
});
// Portfolio optimization
app.post('/optimize', async (c) => {
try {
const body = await c.req.json();
const request = OptimizationRequestSchema.parse(body);
const result = await analyticsService.optimizePortfolio({
returns: request.returns,
constraints: request.constraints
});
return c.json(result);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({
error: 'Invalid optimization request',
details: error.errors
}, 400);
}
container.logger.error('Error optimizing portfolio:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to optimize portfolio'
}, 500);
}
});
// Get risk metrics
app.get('/risk/:portfolioId', async (c) => {
try {
const portfolioId = c.req.param('portfolioId');
const metrics = await analyticsService.getRiskMetrics(portfolioId);
return c.json(metrics);
} catch (error) {
container.logger.error('Error getting risk metrics:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to get risk metrics'
}, 500);
}
});
// Market regime detection
app.get('/regime', async (c) => {
try {
const regime = await analyticsService.detectMarketRegime();
return c.json({
regime,
timestamp: new Date().toISOString()
});
} catch (error) {
container.logger.error('Error detecting market regime:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to detect market regime'
}, 500);
}
});
// Calculate correlation matrix
app.post('/correlation', async (c) => {
try {
const body = await c.req.json();
const { symbols } = z.object({
symbols: z.array(z.string()).min(2)
}).parse(body);
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
return c.json({
symbols,
matrix
});
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({
error: 'Invalid correlation request',
details: error.errors
}, 400);
}
container.logger.error('Error calculating correlation:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to calculate correlation'
}, 500);
}
});
// ML model prediction
app.post('/predict', async (c) => {
try {
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;
}
import { Hono } from 'hono';
import { z } from 'zod';
import { AnalyticsService } from '../../services/AnalyticsService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
const DateRangeSchema = z.object({
startDate: z.string().datetime(),
endDate: z.string().datetime(),
});
const OptimizationRequestSchema = z.object({
symbols: z.array(z.string()),
returns: z.array(z.array(z.number())),
constraints: z
.object({
minWeight: z.number().optional(),
maxWeight: z.number().optional(),
targetReturn: z.number().optional(),
maxRisk: z.number().optional(),
})
.optional(),
});
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
// Get performance metrics
app.get('/performance/:portfolioId', async c => {
try {
const portfolioId = c.req.param('portfolioId');
const query = c.req.query();
const { startDate, endDate } = DateRangeSchema.parse({
startDate: query.start_date,
endDate: query.end_date,
});
const metrics = await analyticsService.getPerformanceMetrics(
portfolioId,
new Date(startDate),
new Date(endDate)
);
return c.json(metrics);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid date range',
details: error.errors,
},
400
);
}
container.logger.error('Error getting performance metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get performance metrics',
},
500
);
}
});
// Portfolio optimization
app.post('/optimize', async c => {
try {
const body = await c.req.json();
const request = OptimizationRequestSchema.parse(body);
const result = await analyticsService.optimizePortfolio({
returns: request.returns,
constraints: request.constraints,
});
return c.json(result);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid optimization request',
details: error.errors,
},
400
);
}
container.logger.error('Error optimizing portfolio:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to optimize portfolio',
},
500
);
}
});
// Get risk metrics
app.get('/risk/:portfolioId', async c => {
try {
const portfolioId = c.req.param('portfolioId');
const metrics = await analyticsService.getRiskMetrics(portfolioId);
return c.json(metrics);
} catch (error) {
container.logger.error('Error getting risk metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get risk metrics',
},
500
);
}
});
// Market regime detection
app.get('/regime', async c => {
try {
const regime = await analyticsService.detectMarketRegime();
return c.json({
regime,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error detecting market regime:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to detect market regime',
},
500
);
}
});
// Calculate correlation matrix
app.post('/correlation', async c => {
try {
const body = await c.req.json();
const { symbols } = z
.object({
symbols: z.array(z.string()).min(2),
})
.parse(body);
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
return c.json({
symbols,
matrix,
});
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid correlation request',
details: error.errors,
},
400
);
}
container.logger.error('Error calculating correlation:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to calculate correlation',
},
500
);
}
});
// ML model prediction
app.post('/predict', async c => {
try {
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 { z } from 'zod';
import { IServiceContainer } from '@stock-bot/di';
import { BacktestConfigSchema } from '../../types';
import { BacktestEngine } from '../../backtest/BacktestEngine';
import { ModeManager } from '../../core/ModeManager';
const BacktestIdSchema = z.object({
backtestId: z.string()
});
export function createBacktestRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const backtestEngine = container.custom?.BacktestEngine as BacktestEngine;
const modeManager = container.custom?.ModeManager as ModeManager;
// Default POST to / is the same as /run for backward compatibility
app.post('/', async (c) => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({
error: 'Invalid backtest configuration',
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);
}
});
// Run new backtest (same as above but at /run)
app.post('/run', async (c) => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({
error: 'Invalid backtest configuration',
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);
}
});
// Stop running backtest
app.post('/stop', async (c) => {
try {
await backtestEngine.stopBacktest();
return c.json({
message: 'Backtest stop requested',
timestamp: new Date().toISOString()
});
} catch (error) {
container.logger.error('Error stopping backtest:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to stop backtest'
}, 500);
}
});
// Pause running backtest
app.post('/pause', async (c) => {
try {
await backtestEngine.pauseBacktest();
return c.json({
message: 'Backtest paused',
timestamp: new Date().toISOString()
});
} catch (error) {
container.logger.error('Error pausing backtest:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to pause backtest'
}, 500);
}
});
// Resume paused backtest
app.post('/resume', async (c) => {
try {
await backtestEngine.resumeBacktest();
return c.json({
message: 'Backtest resumed',
timestamp: new Date().toISOString()
});
} catch (error) {
container.logger.error('Error resuming backtest:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to resume backtest'
}, 500);
}
});
// Set backtest speed
app.post('/speed', async (c) => {
try {
const body = await c.req.json();
const speed = body.speed ?? 1;
backtestEngine.setSpeedMultiplier(speed);
return c.json({
message: 'Backtest speed updated',
speed: speed === null ? 'unlimited' : speed,
timestamp: new Date().toISOString()
});
} catch (error) {
container.logger.error('Error setting backtest speed:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to set speed'
}, 500);
}
});
// Get backtest progress
app.get('/progress', async (c) => {
try {
const status = backtestEngine.getStatus();
return c.json({
status: status.isPaused ? 'paused' : (status.isRunning ? 'running' : 'idle'),
progress: status.progress,
currentTime: new Date(status.currentTime).toISOString(),
isRunning: status.isRunning,
isPaused: status.isPaused
});
} catch (error) {
container.logger.error('Error getting backtest progress:', error);
return c.json({
error: error instanceof Error ? error.message : 'Failed to get progress'
}, 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');
const stream = new ReadableStream({
start(controller) {
// Listen for backtest events
const onProgress = (data: any) => {
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
};
const onComplete = (data: any) => {
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
controller.close();
};
backtestEngine.on('progress', onProgress);
backtestEngine.on('complete', onComplete);
// Cleanup on close
c.req.raw.signal.addEventListener('abort', () => {
backtestEngine.off('progress', onProgress);
backtestEngine.off('complete', onComplete);
controller.close();
});
}
});
return new Response(stream);
});
// Validate backtest configuration
app.post('/validate', async (c) => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Additional validation logic
const validation = {
valid: true,
warnings: [] as string[],
estimatedDuration: 0
};
// Check data availability
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
if (days > 365) {
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;
}
import { Hono } from 'hono';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { BacktestConfigSchema } from '../../types';
const _BacktestIdSchema = z.object({
backtestId: z.string(),
});
export function createBacktestRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const backtestEngine = defined(container.custom?.BacktestEngine);
const modeManager = container.custom?.ModeManager as ModeManager;
// Default POST to / is the same as /run for backward compatibility
app.post('/', async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid backtest configuration',
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
);
}
});
// Run new backtest (same as above but at /run)
app.post('/run', async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid backtest configuration',
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
);
}
});
// Stop running backtest
app.post('/stop', async c => {
try {
await backtestEngine.stopBacktest();
return c.json({
message: 'Backtest stop requested',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error stopping backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to stop backtest',
},
500
);
}
});
// Pause running backtest
app.post('/pause', async c => {
try {
await backtestEngine.pauseBacktest();
return c.json({
message: 'Backtest paused',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error pausing backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to pause backtest',
},
500
);
}
});
// Resume paused backtest
app.post('/resume', async c => {
try {
await backtestEngine.resumeBacktest();
return c.json({
message: 'Backtest resumed',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error resuming backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to resume backtest',
},
500
);
}
});
// Set backtest speed
app.post('/speed', async c => {
try {
const body = await c.req.json();
const speed = body.speed ?? 1;
backtestEngine.setSpeedMultiplier(speed);
return c.json({
message: 'Backtest speed updated',
speed: speed === null ? 'unlimited' : speed,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error setting backtest speed:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to set speed',
},
500
);
}
});
// Get backtest progress
app.get('/progress', async c => {
try {
const status = backtestEngine.getStatus();
return c.json({
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
progress: status.progress,
currentTime: new Date(status.currentTime).toISOString(),
isRunning: status.isRunning,
isPaused: status.isPaused,
});
} catch (error) {
container.logger.error('Error getting backtest progress:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get progress',
},
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');
const stream = new ReadableStream({
start(controller) {
// Listen for backtest events
const onProgress = (data: unknown) => {
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
};
const onComplete = (data: unknown) => {
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
controller.close();
};
backtestEngine.on('progress', onProgress);
backtestEngine.on('complete', onComplete);
// Cleanup on close
c.req.raw.signal.addEventListener('abort', () => {
backtestEngine.off('progress', onProgress);
backtestEngine.off('complete', onComplete);
controller.close();
});
},
});
return new Response(stream);
});
// Validate backtest configuration
app.post('/validate', async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Additional validation logic
const validation = {
valid: true,
warnings: [] as string[],
estimatedDuration: 0,
};
// Check data availability
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
if (days > 365) {
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