commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
|
|
@ -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
|
||||
21
.prettierrc
21
.prettierrc
|
|
@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
39
README.md
39
README.md
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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']),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -35,17 +35,23 @@ 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) => {
|
||||
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: any) => e.exchange === channel.exchange)) {
|
||||
exchanges.push({
|
||||
exchange: channel.exchange,
|
||||
countryCode: 'CA',
|
||||
});
|
||||
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,
|
||||
name: channel.title,
|
||||
|
|
@ -61,7 +67,8 @@ export async function getChannels(this: CeoHandler, payload: number | undefined)
|
|||
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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 * * *', {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { at } from '@stock-bot/utils';
|
||||
import type { EodHandler } from '../eod.handler';
|
||||
import { EOD_CONFIG } from '../shared';
|
||||
|
||||
|
|
@ -18,68 +19,82 @@ export async function scheduleFetchCorporateActions(
|
|||
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 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
|
||||
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
|
||||
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
|
||||
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)) {
|
||||
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`);
|
||||
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];
|
||||
const { symbol } = at(staleSymbolsDividends, i);
|
||||
|
||||
await this.scheduleOperation('fetch-corporate-actions', {
|
||||
await this.scheduleOperation(
|
||||
'fetch-corporate-actions',
|
||||
{
|
||||
eodSearchCode: symbol.eodSearchCode,
|
||||
actionType: 'dividends'
|
||||
}, {
|
||||
actionType: 'dividends',
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000
|
||||
delay: 5000,
|
||||
},
|
||||
delay: i * 200 // Stagger jobs by 200ms per symbol
|
||||
});
|
||||
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];
|
||||
const { symbol } = at(staleSymbolsSplits, i);
|
||||
|
||||
await this.scheduleOperation('fetch-corporate-actions', {
|
||||
await this.scheduleOperation(
|
||||
'fetch-corporate-actions',
|
||||
{
|
||||
eodSearchCode: symbol.eodSearchCode,
|
||||
actionType: 'splits'
|
||||
}, {
|
||||
actionType: 'splits',
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000
|
||||
delay: 5000,
|
||||
},
|
||||
delay: (i * 200) + 100 // Offset splits by 100ms from dividends
|
||||
});
|
||||
delay: i * 200 + 100, // Offset splits by 100ms from dividends
|
||||
}
|
||||
);
|
||||
jobsScheduled++;
|
||||
}
|
||||
|
||||
|
|
@ -87,7 +102,7 @@ export async function scheduleFetchCorporateActions(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
jobsScheduled
|
||||
jobsScheduled,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to schedule corporate actions fetch jobs', { error });
|
||||
|
|
@ -109,7 +124,7 @@ export async function fetchCorporateActions(
|
|||
try {
|
||||
// Lookup symbol using eodSearchCode
|
||||
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
|
||||
eodSearchCode: eodSearchCode
|
||||
eodSearchCode: eodSearchCode,
|
||||
});
|
||||
|
||||
if (!symbolDoc) {
|
||||
|
|
@ -119,7 +134,7 @@ export async function fetchCorporateActions(
|
|||
|
||||
symbol = symbolDoc.Code;
|
||||
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
|
||||
const country = symbolDoc.Country;
|
||||
const _country = symbolDoc.Country;
|
||||
|
||||
logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`);
|
||||
|
||||
|
|
@ -159,8 +174,8 @@ export async function fetchCorporateActions(
|
|||
samples: data.slice(0, 3).map(record => ({
|
||||
date: record.date,
|
||||
value: record.value || record.split || record.amount,
|
||||
...record
|
||||
}))
|
||||
...record,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -171,8 +186,8 @@ export async function fetchCorporateActions(
|
|||
{
|
||||
$set: {
|
||||
[`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(),
|
||||
[`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false
|
||||
}
|
||||
[`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -187,18 +202,17 @@ export async function fetchCorporateActions(
|
|||
...record,
|
||||
actionType,
|
||||
updatedAt: new Date(),
|
||||
source: 'eod'
|
||||
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']
|
||||
);
|
||||
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';
|
||||
|
|
@ -208,15 +222,17 @@ export async function fetchCorporateActions(
|
|||
metadata: {
|
||||
actionType: actionType,
|
||||
exchange: exchange,
|
||||
hasData: result.insertedCount > 0
|
||||
}
|
||||
hasData: result.insertedCount > 0,
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`);
|
||||
logger.info(
|
||||
`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
recordsCount: result.insertedCount
|
||||
recordsCount: result.insertedCount,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch corporate actions', { error, symbol, exchange, actionType });
|
||||
|
|
@ -225,7 +241,7 @@ export async function fetchCorporateActions(
|
|||
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)
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
|
||||
throw error;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { at } from '@stock-bot/utils';
|
||||
import type { EodHandler } from '../eod.handler';
|
||||
import { EOD_CONFIG } from '../shared';
|
||||
|
||||
interface BulkFundamentalsInput {
|
||||
eodSearchCodes: string[];
|
||||
}
|
||||
|
|
@ -20,14 +22,17 @@ export async function scheduleFetchFundamentals(
|
|||
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
|
||||
});
|
||||
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
|
||||
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) {
|
||||
|
|
@ -45,31 +50,35 @@ export async function scheduleFetchFundamentals(
|
|||
etfSamples: etfs.slice(0, 5).map(e => ({
|
||||
symbol: e.symbol.Code,
|
||||
exchange: e.symbol.Exchange,
|
||||
name: e.symbol.Name
|
||||
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
|
||||
}))
|
||||
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
|
||||
}, {
|
||||
const { symbol: etf } = at(etfs, i);
|
||||
await this.scheduleOperation(
|
||||
'fetch-single-fundamentals',
|
||||
{
|
||||
eodSearchCode: etf.eodSearchCode,
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 10000
|
||||
delay: 10000,
|
||||
},
|
||||
delay: jobsScheduled * 1000 // Stagger by 1 second
|
||||
});
|
||||
delay: jobsScheduled * 1000, // Stagger by 1 second
|
||||
}
|
||||
);
|
||||
jobsScheduled++;
|
||||
}
|
||||
|
||||
|
|
@ -86,16 +95,20 @@ export async function scheduleFetchFundamentals(
|
|||
// Convert to array of eodSearchCodes
|
||||
const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode);
|
||||
|
||||
await this.scheduleOperation('fetch-bulk-fundamentals', {
|
||||
eodSearchCodes: eodSearchCodes
|
||||
}, {
|
||||
await this.scheduleOperation(
|
||||
'fetch-bulk-fundamentals',
|
||||
{
|
||||
eodSearchCodes: eodSearchCodes,
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 10000
|
||||
delay: 10000,
|
||||
},
|
||||
delay: jobsScheduled * 5000 // Stagger batches by 5 seconds
|
||||
});
|
||||
delay: jobsScheduled * 5000, // Stagger batches by 5 seconds
|
||||
}
|
||||
);
|
||||
|
||||
jobsScheduled++;
|
||||
logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`);
|
||||
|
|
@ -105,7 +118,7 @@ export async function scheduleFetchFundamentals(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
jobsScheduled
|
||||
jobsScheduled,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to schedule fundamentals fetch jobs', { error });
|
||||
|
|
@ -124,9 +137,12 @@ export async function fetchBulkFundamentals(
|
|||
logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length });
|
||||
|
||||
// Lookup all symbols
|
||||
const symbolDocs = await this.mongodb.collection('eodSymbols').find({
|
||||
eodSearchCode: { $in: eodSearchCodes }
|
||||
}).toArray();
|
||||
const symbolDocs = await this.mongodb
|
||||
.collection('eodSymbols')
|
||||
.find({
|
||||
eodSearchCode: { $in: eodSearchCodes },
|
||||
})
|
||||
.toArray();
|
||||
|
||||
if (symbolDocs.length === 0) {
|
||||
logger.error('No symbols found for provided eodSearchCodes');
|
||||
|
|
@ -141,7 +157,8 @@ export async function fetchBulkFundamentals(
|
|||
|
||||
// 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 exchangeGroups = symbolDocs.reduce(
|
||||
(acc, symbolDoc) => {
|
||||
const exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
|
||||
const eodSearchCode = symbolDoc.eodSearchCode;
|
||||
|
||||
|
|
@ -151,7 +168,9 @@ export async function fetchBulkFundamentals(
|
|||
// eodSearchCode already has the correct format (e.g., AAPL.US)
|
||||
acc[exchange].push(eodSearchCode);
|
||||
return acc;
|
||||
}, {} as Record<string, string[]>);
|
||||
},
|
||||
{} as Record<string, string[]>
|
||||
);
|
||||
|
||||
let totalProcessed = 0;
|
||||
|
||||
|
|
@ -166,14 +185,16 @@ export async function fetchBulkFundamentals(
|
|||
logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, {
|
||||
exchange,
|
||||
count: symbolList.length,
|
||||
samples: symbolList.slice(0, 5)
|
||||
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}`);
|
||||
throw new Error(
|
||||
`EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
|
@ -197,7 +218,8 @@ export async function fetchBulkFundamentals(
|
|||
const [symbol, exchangeSuffix] = symbolExchange.split('.');
|
||||
|
||||
// Find the original symbol doc to get the actual exchange code
|
||||
const symbolDoc = symbolDocs.find(doc =>
|
||||
const symbolDoc = symbolDocs.find(
|
||||
doc =>
|
||||
doc.Code === symbol &&
|
||||
(doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix)
|
||||
);
|
||||
|
|
@ -217,7 +239,7 @@ export async function fetchBulkFundamentals(
|
|||
eodSearchCode,
|
||||
...fundamentals,
|
||||
updatedAt: new Date(),
|
||||
source: 'eod'
|
||||
source: 'eod',
|
||||
};
|
||||
|
||||
fundamentalsToSave.push(fundamentalsWithMetadata);
|
||||
|
|
@ -226,24 +248,27 @@ export async function fetchBulkFundamentals(
|
|||
|
||||
if (fundamentalsToSave.length > 0) {
|
||||
// Save fundamentals to MongoDB
|
||||
const result = await this.mongodb.batchUpsert(
|
||||
'eodFundamentals',
|
||||
fundamentalsToSave,
|
||||
['eodSearchCode']
|
||||
);
|
||||
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', {
|
||||
return this.operationRegistry.updateOperation(
|
||||
'eod',
|
||||
eodSearchCode,
|
||||
'fundamentals_update',
|
||||
{
|
||||
status: 'success',
|
||||
recordCount: 1,
|
||||
metadata: {
|
||||
hasData: true,
|
||||
exchange: exchange
|
||||
exchange: exchange,
|
||||
},
|
||||
}
|
||||
});
|
||||
);
|
||||
});
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
|
@ -255,16 +280,16 @@ export async function fetchBulkFundamentals(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
symbolsProcessed: totalProcessed
|
||||
symbolsProcessed: totalProcessed,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch bulk fundamentals', { error });
|
||||
|
||||
// Mark all symbols as failed
|
||||
const failPromises = eodSearchCodes.map((eodSearchCode) => {
|
||||
const failPromises = eodSearchCodes.map(eodSearchCode => {
|
||||
return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
|
||||
status: 'failure',
|
||||
error: error.message
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -287,7 +312,7 @@ export async function fetchSingleFundamentals(
|
|||
try {
|
||||
// Lookup symbol using eodSearchCode
|
||||
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
|
||||
eodSearchCode: eodSearchCode
|
||||
eodSearchCode: eodSearchCode,
|
||||
});
|
||||
|
||||
if (!symbolDoc) {
|
||||
|
|
@ -297,7 +322,7 @@ export async function fetchSingleFundamentals(
|
|||
|
||||
symbol = symbolDoc.Code;
|
||||
exchange = symbolDoc.eodExchange || symbolDoc.Exchange;
|
||||
const country = symbolDoc.Country;
|
||||
const _country = symbolDoc.Country;
|
||||
|
||||
logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`);
|
||||
|
||||
|
|
@ -317,7 +342,9 @@ export async function fetchSingleFundamentals(
|
|||
const response = await fetch(url.toString());
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`);
|
||||
throw new Error(
|
||||
`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
const fundamentals = await response.json();
|
||||
|
|
@ -335,7 +362,7 @@ export async function fetchSingleFundamentals(
|
|||
eodSearchCode,
|
||||
...fundamentals,
|
||||
updatedAt: new Date(),
|
||||
source: 'eod'
|
||||
source: 'eod',
|
||||
};
|
||||
|
||||
// Save to MongoDB
|
||||
|
|
@ -352,15 +379,15 @@ export async function fetchSingleFundamentals(
|
|||
metadata: {
|
||||
hasData: true,
|
||||
exchange: exchange,
|
||||
saved: result.insertedCount > 0
|
||||
}
|
||||
saved: result.insertedCount > 0,
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`Successfully saved fundamentals for ${symbol}.${exchange}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
saved: result.insertedCount > 0
|
||||
saved: result.insertedCount > 0,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch single fundamentals', { error, symbol, exchange });
|
||||
|
|
@ -368,7 +395,7 @@ export async function fetchSingleFundamentals(
|
|||
// Update operation tracker with failure
|
||||
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', {
|
||||
status: 'failure',
|
||||
error: error.message
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
|
||||
throw error;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
|
||||
import type { Document } from 'mongodb';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { OperationUpdate } from '../../../shared/operation-manager/types';
|
||||
import type { EodHandler } from '../eod.handler';
|
||||
import { EOD_CONFIG } from '../shared';
|
||||
|
||||
|
|
@ -27,7 +29,7 @@ interface ScheduleIntradayConfig {
|
|||
const MAX_DAYS_PER_INTERVAL = {
|
||||
'1m': 120,
|
||||
'5m': 600,
|
||||
'1h': 7200
|
||||
'1h': 7200,
|
||||
};
|
||||
|
||||
// Default exchanges to process for intraday data
|
||||
|
|
@ -44,8 +46,8 @@ export async function scheduleIntradayCrawl(
|
|||
config: {
|
||||
exchanges: config?.exchanges, //|| DEFAULT_INTRADAY_EXCHANGES,
|
||||
symbolTypes: config?.symbolTypes || 'all',
|
||||
limit: config?.limit || 'unlimited'
|
||||
}
|
||||
limit: config?.limit || 'unlimited',
|
||||
},
|
||||
});
|
||||
|
||||
// Check if operation registry is initialized
|
||||
|
|
@ -56,25 +58,27 @@ export async function scheduleIntradayCrawl(
|
|||
|
||||
logger.debug('Operation registry status:', {
|
||||
hasRegistry: !!this.operationRegistry,
|
||||
hasProvider: this.operationRegistry.hasProvider ? this.operationRegistry.hasProvider('eod') : 'no hasProvider method'
|
||||
hasProvider: this.operationRegistry.hasProvider
|
||||
? this.operationRegistry.hasProvider('eod')
|
||||
: 'no hasProvider method',
|
||||
});
|
||||
|
||||
// Use OperationTracker to find symbols needing intraday crawl
|
||||
const intervals: Array<'1m' | '5m' | '1h'> = ['1m', '5m', '1h'];
|
||||
const operationNames: string[] = ['intraday_1m', 'intraday_5m', 'intraday_1h'];
|
||||
|
||||
const allSymbolsForCrawl: any[] = [];
|
||||
const allSymbolsForCrawl: Document[] = [];
|
||||
|
||||
// Get symbols needing crawl for each interval
|
||||
for (let i = 0; i < intervals.length; i++) {
|
||||
const interval = intervals[i];
|
||||
const operationName = operationNames[i]!; // Non-null assertion since we know the array has 3 elements
|
||||
const operationName = defined(operationNames[i]); // Non-null assertion since we know the array has 3 elements
|
||||
|
||||
// Use getStaleSymbols to find symbols needing intraday updates
|
||||
logger.debug(`Getting stale symbols for ${operationName}...`);
|
||||
|
||||
// Get symbols with all filters applied at the database level
|
||||
const targetExchanges = config?.exchanges //|| DEFAULT_INTRADAY_EXCHANGES;
|
||||
const targetExchanges = config?.exchanges; //|| DEFAULT_INTRADAY_EXCHANGES;
|
||||
const desiredLimit = config?.limit || 1000000;
|
||||
|
||||
const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', operationName, {
|
||||
|
|
@ -99,12 +103,15 @@ export async function scheduleIntradayCrawl(
|
|||
// 1. Have never been processed (!operationStatus)
|
||||
// 2. Are not finished (!operationStatus.finished)
|
||||
// 3. Are finished but need new data (newest date > 1 day old)
|
||||
const needsNewData = operationStatus?.finished && operationStatus?.newestDateReached &&
|
||||
new Date(operationStatus.newestDateReached) < new Date(Date.now() - 30* 24 * 60 * 60 * 1000);
|
||||
const needsNewData =
|
||||
operationStatus?.finished &&
|
||||
operationStatus?.newestDateReached &&
|
||||
new Date(operationStatus.newestDateReached) <
|
||||
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
if (!operationStatus || !operationStatus.finished || needsNewData) {
|
||||
// Calculate initial date range for the job
|
||||
const maxDays = MAX_DAYS_PER_INTERVAL[interval];
|
||||
const maxDays = MAX_DAYS_PER_INTERVAL[interval ?? '5m'];
|
||||
let toDate = new Date();
|
||||
let fromDate = new Date();
|
||||
let isInitial = true;
|
||||
|
|
@ -127,7 +134,7 @@ export async function scheduleIntradayCrawl(
|
|||
lastSuccess: staleSymbol.lastSuccess,
|
||||
fromDate: fromDate,
|
||||
toDate: toDate,
|
||||
isInitial: isInitial
|
||||
isInitial: isInitial,
|
||||
});
|
||||
|
||||
logger.debug(`Added ${symbol.Code}.${symbol.Exchange} for ${interval} crawl`, {
|
||||
|
|
@ -135,7 +142,7 @@ export async function scheduleIntradayCrawl(
|
|||
finished: operationStatus?.finished,
|
||||
needsNewData,
|
||||
dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`,
|
||||
isInitial
|
||||
isInitial,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -146,12 +153,14 @@ export async function scheduleIntradayCrawl(
|
|||
return { success: true, jobsScheduled: 0 };
|
||||
}
|
||||
|
||||
logger.info(`Found ${allSymbolsForCrawl.length} symbol/interval combinations needing intraday data`, {
|
||||
logger.info(
|
||||
`Found ${allSymbolsForCrawl.length} symbol/interval combinations needing intraday data`,
|
||||
{
|
||||
count: allSymbolsForCrawl.length,
|
||||
byInterval: {
|
||||
'1m': allSymbolsForCrawl.filter(s => s.interval === '1m').length,
|
||||
'5m': allSymbolsForCrawl.filter(s => s.interval === '5m').length,
|
||||
'1h': allSymbolsForCrawl.filter(s => s.interval === '1h').length
|
||||
'1h': allSymbolsForCrawl.filter(s => s.interval === '1h').length,
|
||||
},
|
||||
symbols: allSymbolsForCrawl.map(s => ({
|
||||
symbol: s.symbol.Code,
|
||||
|
|
@ -162,9 +171,10 @@ export async function scheduleIntradayCrawl(
|
|||
dateRange: `${s.fromDate.toISOString().split('T')[0]} to ${s.toDate.toISOString().split('T')[0]}`,
|
||||
isInitial: s.isInitial,
|
||||
lastRun: s.lastRun ? new Date(s.lastRun).toISOString() : 'never',
|
||||
lastSuccess: s.lastSuccess ? new Date(s.lastSuccess).toISOString() : 'never'
|
||||
}))
|
||||
});
|
||||
lastSuccess: s.lastSuccess ? new Date(s.lastSuccess).toISOString() : 'never',
|
||||
})),
|
||||
}
|
||||
);
|
||||
|
||||
let jobsScheduled = 0;
|
||||
|
||||
|
|
@ -173,26 +183,32 @@ export async function scheduleIntradayCrawl(
|
|||
const { symbol, interval, fromDate, toDate, isInitial } = item;
|
||||
|
||||
// Create jobId based on whether it's initial or continuation
|
||||
const dateStr = isInitial ? 'initial' : `${fromDate.toISOString().split('T')[0]}-${toDate.toISOString().split('T')[0]}`;
|
||||
const dateStr = isInitial
|
||||
? 'initial'
|
||||
: `${fromDate.toISOString().split('T')[0]}-${toDate.toISOString().split('T')[0]}`;
|
||||
const jobId = `crawl-intraday-${symbol.eodSearchCode}-${interval}-${dateStr}`;
|
||||
|
||||
try {
|
||||
await this.scheduleOperation('crawl-intraday', {
|
||||
await this.scheduleOperation(
|
||||
'crawl-intraday',
|
||||
{
|
||||
eodSearchCode: symbol.eodSearchCode,
|
||||
interval,
|
||||
fromDate,
|
||||
toDate,
|
||||
isInitial
|
||||
}, {
|
||||
isInitial,
|
||||
},
|
||||
{
|
||||
jobId,
|
||||
priority: isInitial ? 5 : 3, // Initial crawl jobs get lower priority
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 10000
|
||||
delay: 10000,
|
||||
},
|
||||
delay: jobsScheduled * 500 // Stagger jobs by 500ms
|
||||
});
|
||||
delay: jobsScheduled * 500, // Stagger jobs by 500ms
|
||||
}
|
||||
);
|
||||
jobsScheduled++;
|
||||
|
||||
logger.debug(`Scheduled crawl job`, {
|
||||
|
|
@ -201,10 +217,10 @@ export async function scheduleIntradayCrawl(
|
|||
exchange: symbol.Exchange,
|
||||
interval,
|
||||
dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`,
|
||||
isInitial
|
||||
isInitial,
|
||||
});
|
||||
} catch (error: any) {
|
||||
if (error?.message?.includes('Job already exists')) {
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('Job already exists')) {
|
||||
logger.debug(`Job already exists: ${jobId}`);
|
||||
} else {
|
||||
throw error;
|
||||
|
|
@ -216,7 +232,7 @@ export async function scheduleIntradayCrawl(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
jobsScheduled
|
||||
jobsScheduled,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to schedule intraday crawl jobs', { error });
|
||||
|
|
@ -229,12 +245,18 @@ export async function crawlIntraday(
|
|||
input: CrawlIntradayInput
|
||||
): Promise<{ success: boolean; recordsProcessed: number; finished: boolean }> {
|
||||
const logger = this.logger;
|
||||
const { eodSearchCode, interval, fromDate: providedFromDate, toDate: providedToDate, isInitial } = input;
|
||||
const {
|
||||
eodSearchCode,
|
||||
interval,
|
||||
fromDate: providedFromDate,
|
||||
toDate: providedToDate,
|
||||
isInitial,
|
||||
} = input;
|
||||
|
||||
try {
|
||||
// Lookup symbol using eodSearchCode
|
||||
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
|
||||
eodSearchCode: eodSearchCode
|
||||
eodSearchCode: eodSearchCode,
|
||||
});
|
||||
|
||||
if (!symbolDoc) {
|
||||
|
|
@ -251,14 +273,14 @@ export async function crawlIntraday(
|
|||
exchange,
|
||||
interval,
|
||||
country,
|
||||
eodSearchCode
|
||||
eodSearchCode,
|
||||
});
|
||||
|
||||
logger.debug('Found symbol document', {
|
||||
symbol,
|
||||
exchange,
|
||||
hasOperations: !!symbolDoc.operations,
|
||||
operationKeys: Object.keys(symbolDoc.operations || {})
|
||||
operationKeys: Object.keys(symbolDoc.operations || {}),
|
||||
});
|
||||
|
||||
// Get operation status from tracker
|
||||
|
|
@ -269,7 +291,7 @@ export async function crawlIntraday(
|
|||
hasOperationStatus: !!symbolDoc.operations?.[operationName],
|
||||
operationStatus: operationStatus,
|
||||
lastProcessedDate: operationStatus.lastProcessedDate,
|
||||
finished: operationStatus.finished
|
||||
finished: operationStatus.finished,
|
||||
});
|
||||
|
||||
// Determine date range for this batch
|
||||
|
|
@ -284,7 +306,7 @@ export async function crawlIntraday(
|
|||
logger.info(`Using provided date range for ${symbol}.${exchange} - ${interval}`, {
|
||||
fromDate: fromDate.toISOString(),
|
||||
toDate: toDate.toISOString(),
|
||||
isInitial
|
||||
isInitial,
|
||||
});
|
||||
} else {
|
||||
// Fallback to original logic (for backward compatibility)
|
||||
|
|
@ -303,11 +325,13 @@ export async function crawlIntraday(
|
|||
logger.info(`Calculated date range for ${symbol}.${exchange} - ${interval}`, {
|
||||
fromDate: fromDate.toISOString(),
|
||||
toDate: toDate.toISOString(),
|
||||
basedOn: operationStatus.lastProcessedDate ? 'lastProcessedDate' : 'current date'
|
||||
basedOn: operationStatus.lastProcessedDate ? 'lastProcessedDate' : 'current date',
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`Fetching intraday batch for ${symbol}.${exchange} - ${interval} from ${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, {
|
||||
logger.info(
|
||||
`Fetching intraday batch for ${symbol}.${exchange} - ${interval} from ${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`,
|
||||
{
|
||||
symbol,
|
||||
exchange,
|
||||
interval,
|
||||
|
|
@ -316,25 +340,26 @@ export async function crawlIntraday(
|
|||
maxDays,
|
||||
operationStatus: {
|
||||
lastProcessedDate: operationStatus.lastProcessedDate,
|
||||
totalDaysProcessed: operationStatus.totalDaysProcessed || 0
|
||||
totalDaysProcessed: operationStatus.totalDaysProcessed || 0,
|
||||
},
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
// Fetch data for this batch
|
||||
const result = await fetchIntraday.call(this, {
|
||||
eodSearchCode,
|
||||
interval,
|
||||
fromDate,
|
||||
toDate
|
||||
toDate,
|
||||
});
|
||||
|
||||
// Prepare update data
|
||||
const updateData: any = {
|
||||
const updateData: OperationUpdate = {
|
||||
status: 'partial',
|
||||
recordCount: result.recordsSaved,
|
||||
finished: false,
|
||||
lastProcessedDate: fromDate, // Store the fromDate so next batch continues from here
|
||||
totalDaysProcessed: (operationStatus.totalDaysProcessed || 0) + maxDays
|
||||
totalDaysProcessed: (operationStatus.totalDaysProcessed || 0) + maxDays,
|
||||
};
|
||||
|
||||
// Set oldest date reached
|
||||
|
|
@ -359,25 +384,31 @@ export async function crawlIntraday(
|
|||
// No data returned from API - we've reached the end
|
||||
updateData.finished = true;
|
||||
updateData.status = 'success';
|
||||
logger.info(`Intraday crawl finished for ${symbol}.${exchange} - ${interval} (no more data available)`, {
|
||||
logger.info(
|
||||
`Intraday crawl finished for ${symbol}.${exchange} - ${interval} (no more data available)`,
|
||||
{
|
||||
symbol,
|
||||
exchange,
|
||||
interval,
|
||||
oldestDate: updateData.oldestDateReached?.toISOString(),
|
||||
newestDate: updateData.newestDateReached?.toISOString(),
|
||||
totalDaysProcessed: updateData.totalDaysProcessed,
|
||||
noDataReturned: true
|
||||
});
|
||||
noDataReturned: true,
|
||||
}
|
||||
);
|
||||
} else if (result.recordsSaved === 0 && result.recordsFetched > 0) {
|
||||
// Data was fetched but all records already exist - continue crawling
|
||||
logger.info(`All ${result.recordsFetched} records already exist for ${symbol}.${exchange} - ${interval}, continuing crawl`, {
|
||||
logger.info(
|
||||
`All ${result.recordsFetched} records already exist for ${symbol}.${exchange} - ${interval}, continuing crawl`,
|
||||
{
|
||||
symbol,
|
||||
exchange,
|
||||
interval,
|
||||
fromDate: fromDate.toISOString(),
|
||||
toDate: toDate.toISOString(),
|
||||
recordsFetched: result.recordsFetched
|
||||
});
|
||||
recordsFetched: result.recordsFetched,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Update operation tracker
|
||||
|
|
@ -385,7 +416,7 @@ export async function crawlIntraday(
|
|||
status: updateData.status,
|
||||
recordCount: result.recordsSaved,
|
||||
lastProcessedDate: updateData.lastProcessedDate,
|
||||
finished: updateData.finished
|
||||
finished: updateData.finished ?? false,
|
||||
});
|
||||
|
||||
await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, updateData);
|
||||
|
|
@ -402,22 +433,26 @@ export async function crawlIntraday(
|
|||
const dateStr = `${nextFromDate.toISOString().split('T')[0]}-${nextToDate.toISOString().split('T')[0]}`;
|
||||
const jobId = `crawl-intraday-${eodSearchCode}-${interval}-${dateStr}`;
|
||||
|
||||
await this.scheduleOperation('crawl-intraday', {
|
||||
await this.scheduleOperation(
|
||||
'crawl-intraday',
|
||||
{
|
||||
eodSearchCode,
|
||||
interval,
|
||||
fromDate: nextFromDate,
|
||||
toDate: nextToDate,
|
||||
isInitial: false
|
||||
}, {
|
||||
isInitial: false,
|
||||
},
|
||||
{
|
||||
jobId,
|
||||
priority: 3, // Continuation jobs get higher priority (3) than initial jobs (5)
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 10000
|
||||
delay: 10000,
|
||||
},
|
||||
delay: 5000 // Wait 5 seconds before next batch
|
||||
});
|
||||
delay: 5000, // Wait 5 seconds before next batch
|
||||
}
|
||||
);
|
||||
|
||||
logger.info(`Scheduled next intraday batch for ${symbol}.${exchange} - ${interval}`, {
|
||||
symbol,
|
||||
|
|
@ -427,20 +462,20 @@ export async function crawlIntraday(
|
|||
currentBatch: {
|
||||
from: fromDate.toISOString().split('T')[0],
|
||||
to: toDate.toISOString().split('T')[0],
|
||||
recordsSaved: result.recordsSaved
|
||||
recordsSaved: result.recordsSaved,
|
||||
},
|
||||
nextBatch: {
|
||||
from: nextFromDate.toISOString().split('T')[0],
|
||||
to: nextToDate.toISOString().split('T')[0]
|
||||
to: nextToDate.toISOString().split('T')[0],
|
||||
},
|
||||
totalDaysProcessed: updateData.totalDaysProcessed
|
||||
totalDaysProcessed: updateData.totalDaysProcessed,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
recordsProcessed: result.recordsSaved,
|
||||
finished: updateData.finished
|
||||
finished: updateData.finished ?? false,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to crawl intraday data', { error, eodSearchCode, interval });
|
||||
|
|
@ -462,7 +497,7 @@ export async function fetchIntraday(
|
|||
try {
|
||||
// Lookup symbol using eodSearchCode
|
||||
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
|
||||
eodSearchCode: eodSearchCode
|
||||
eodSearchCode: eodSearchCode,
|
||||
});
|
||||
|
||||
if (!symbolDoc) {
|
||||
|
|
@ -481,7 +516,7 @@ export async function fetchIntraday(
|
|||
from: fromDate?.toISOString().split('T')[0],
|
||||
to: toDate?.toISOString().split('T')[0],
|
||||
country,
|
||||
url: `https://eodhd.com/api/intraday/${symbol}.${exchange}`
|
||||
url: `https://eodhd.com/api/intraday/${symbol}.${exchange}`,
|
||||
});
|
||||
|
||||
// Get API key
|
||||
|
|
@ -539,28 +574,27 @@ export async function fetchIntraday(
|
|||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
source: 'eod'
|
||||
source: 'eod',
|
||||
}));
|
||||
|
||||
// Save to MongoDB - use timestamp and eodSearchCode as unique identifier
|
||||
const collectionName = `eodIntraday${interval.toUpperCase()}`;
|
||||
const result = await this.mongodb.batchUpsert(
|
||||
collectionName,
|
||||
recordsWithMetadata,
|
||||
['timestamp', 'eodSearchCode']
|
||||
);
|
||||
const result = await this.mongodb.batchUpsert(collectionName, recordsWithMetadata, [
|
||||
'timestamp',
|
||||
'eodSearchCode',
|
||||
]);
|
||||
|
||||
logger.info(`Saved ${result.insertedCount} intraday records`, {
|
||||
symbol,
|
||||
exchange,
|
||||
interval,
|
||||
collection: collectionName
|
||||
collection: collectionName,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
recordsSaved: result.insertedCount,
|
||||
recordsFetched: data.length
|
||||
recordsFetched: data.length,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch intraday data', { error, symbol, exchange, interval });
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { EodHandler } from '../eod.handler';
|
||||
import { EOD_CONFIG } from '../shared';
|
||||
import { persistEodPrices } from '../shared/price-storage';
|
||||
|
||||
interface FetchPricesInput {
|
||||
eodSearchCode: string;
|
||||
|
|
@ -15,7 +16,7 @@ export async function scheduleFetchPrices(
|
|||
|
||||
// Use OperationTracker to find stale symbols
|
||||
const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'price_update', {
|
||||
limit: 100000 // Higher limit to process all symbols
|
||||
limit: 100000, // Higher limit to process all symbols
|
||||
});
|
||||
|
||||
if (!staleSymbols || staleSymbols.length === 0) {
|
||||
|
|
@ -28,8 +29,8 @@ export async function scheduleFetchPrices(
|
|||
symbol: s.symbol.Code,
|
||||
exchange: s.symbol.Exchange,
|
||||
name: s.symbol.Name,
|
||||
lastUpdate: s.lastRun
|
||||
}))
|
||||
lastUpdate: s.lastRun,
|
||||
})),
|
||||
});
|
||||
|
||||
let jobsScheduled = 0;
|
||||
|
|
@ -47,24 +48,28 @@ export async function scheduleFetchPrices(
|
|||
name: symbol.Name,
|
||||
lastUpdate: staleSymbol.lastRun,
|
||||
delay: i * 100,
|
||||
jobId
|
||||
jobId,
|
||||
});
|
||||
|
||||
try {
|
||||
await this.scheduleOperation('fetch-prices', {
|
||||
eodSearchCode: symbol.eodSearchCode
|
||||
}, {
|
||||
await this.scheduleOperation(
|
||||
'fetch-prices',
|
||||
{
|
||||
eodSearchCode: symbol.eodSearchCode,
|
||||
},
|
||||
{
|
||||
jobId,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000
|
||||
delay: 5000,
|
||||
},
|
||||
delay: i * 100 // Stagger jobs by 100ms per symbol to avoid rate limit spikes
|
||||
});
|
||||
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')) {
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('Job already exists')) {
|
||||
logger.debug(`Job already exists: ${jobId}`);
|
||||
} else {
|
||||
throw error;
|
||||
|
|
@ -76,7 +81,7 @@ export async function scheduleFetchPrices(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
jobsScheduled
|
||||
jobsScheduled,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to schedule price fetch jobs', { error });
|
||||
|
|
@ -98,7 +103,7 @@ export async function fetchPrices(
|
|||
try {
|
||||
// Lookup symbol using eodSearchCode
|
||||
const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({
|
||||
eodSearchCode: eodSearchCode
|
||||
eodSearchCode: eodSearchCode,
|
||||
});
|
||||
|
||||
if (!symbolDoc) {
|
||||
|
|
@ -141,29 +146,14 @@ export async function fetchPrices(
|
|||
logger.debug(`Price data range for ${eodSearchCode}:`, {
|
||||
oldest: priceData[0].date,
|
||||
newest: priceData[priceData.length - 1].date,
|
||||
count: priceData.length
|
||||
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']
|
||||
const result = await persistEodPrices(
|
||||
this.mongodb,
|
||||
{ symbol, exchange, eodSearchCode },
|
||||
priceData
|
||||
);
|
||||
|
||||
// Update operation tracker instead of directly updating the symbol
|
||||
|
|
@ -173,15 +163,15 @@ export async function fetchPrices(
|
|||
recordCount: priceData.length,
|
||||
metadata: {
|
||||
insertedCount: result.insertedCount,
|
||||
updatedCount: priceData.length - result.insertedCount
|
||||
}
|
||||
updatedCount: priceData.length - result.insertedCount,
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
priceCount: result.insertedCount
|
||||
priceCount: result.insertedCount,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to fetch or save prices', { error, symbol, exchange });
|
||||
|
|
@ -189,7 +179,7 @@ export async function fetchPrices(
|
|||
// Update operation tracker with failure
|
||||
await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', {
|
||||
status: 'failure',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
|
||||
throw error;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ interface FetchSymbolsInput {
|
|||
delisted: boolean;
|
||||
}
|
||||
|
||||
|
||||
export async function scheduleFetchSymbols(
|
||||
this: BaseHandler<DataIngestionServices>
|
||||
): Promise<{ success: boolean; jobsCreated: number }> {
|
||||
|
|
@ -25,7 +24,7 @@ export async function scheduleFetchSymbols(
|
|||
}
|
||||
|
||||
logger.info(`Found ${exchanges.length} exchanges to process`, {
|
||||
exchanges: exchanges.map((e: any) => ({ code: e.Code, name: e.Name, country: e.Country }))
|
||||
exchanges: exchanges.map(e => ({ code: e.Code, name: e.Name, country: e.Country })),
|
||||
});
|
||||
|
||||
let jobsCreated = 0;
|
||||
|
|
@ -35,29 +34,37 @@ export async function scheduleFetchSymbols(
|
|||
const exchangeCode = exchange.Code;
|
||||
|
||||
// Job for active symbols
|
||||
await this.scheduleOperation('fetch-symbols', {
|
||||
await this.scheduleOperation(
|
||||
'fetch-symbols',
|
||||
{
|
||||
exchangeCode,
|
||||
delisted: false
|
||||
}, {
|
||||
delisted: false,
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000
|
||||
delay: 5000,
|
||||
},
|
||||
}
|
||||
});
|
||||
);
|
||||
jobsCreated++;
|
||||
|
||||
// Job for delisted symbols
|
||||
await this.scheduleOperation('fetch-symbols', {
|
||||
await this.scheduleOperation(
|
||||
'fetch-symbols',
|
||||
{
|
||||
exchangeCode,
|
||||
delisted: true
|
||||
}, {
|
||||
delisted: true,
|
||||
},
|
||||
{
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000
|
||||
delay: 5000,
|
||||
},
|
||||
}
|
||||
});
|
||||
);
|
||||
jobsCreated++;
|
||||
}
|
||||
|
||||
|
|
@ -65,7 +72,7 @@ export async function scheduleFetchSymbols(
|
|||
|
||||
return {
|
||||
success: true,
|
||||
jobsCreated
|
||||
jobsCreated,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to schedule symbol fetch jobs', { error });
|
||||
|
|
@ -111,7 +118,9 @@ export async function fetchSymbols(
|
|||
throw new Error('Invalid response format from EOD API - expected array');
|
||||
}
|
||||
|
||||
logger.info(`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
|
||||
logger.info(
|
||||
`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`
|
||||
);
|
||||
|
||||
// Log some sample symbols
|
||||
if (symbols.length > 0) {
|
||||
|
|
@ -120,8 +129,8 @@ export async function fetchSymbols(
|
|||
samples: symbols.slice(0, 5).map(s => ({
|
||||
symbol: s.Code,
|
||||
name: s.Name,
|
||||
type: s.Type
|
||||
}))
|
||||
type: s.Type,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -134,17 +143,17 @@ export async function fetchSymbols(
|
|||
}));
|
||||
|
||||
// Save to MongoDB - use Code as unique identifier along with exchange
|
||||
const result = await this.mongodb.batchUpsert(
|
||||
'eodSymbols',
|
||||
symbolsWithMetadata,
|
||||
['eodSearchCode']
|
||||
);
|
||||
const result = await this.mongodb.batchUpsert('eodSymbols', symbolsWithMetadata, [
|
||||
'eodSearchCode',
|
||||
]);
|
||||
|
||||
logger.info(`Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`);
|
||||
logger.info(
|
||||
`Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
count: result.insertedCount
|
||||
count: result.insertedCount,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch or save symbols', { error, exchangeCode, delisted });
|
||||
|
|
|
|||
|
|
@ -4,9 +4,11 @@ import {
|
|||
Handler,
|
||||
Operation,
|
||||
RateLimit,
|
||||
ScheduledOperation
|
||||
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,
|
||||
|
|
@ -22,7 +24,7 @@ import {
|
|||
scheduleFetchFundamentals,
|
||||
scheduleFetchPrices,
|
||||
scheduleFetchSymbols,
|
||||
scheduleIntradayCrawl
|
||||
scheduleIntradayCrawl,
|
||||
} from './actions';
|
||||
import { createEODOperationRegistry } from './shared';
|
||||
|
||||
|
|
@ -41,14 +43,15 @@ import { createEODOperationRegistry } from './shared';
|
|||
],
|
||||
})
|
||||
export class EodHandler extends BaseHandler<DataIngestionServices> {
|
||||
static operationRegistry?: OperationRegistry;
|
||||
public operationRegistry!: OperationRegistry;
|
||||
|
||||
constructor(services: any) {
|
||||
super(services);
|
||||
constructor(services: IServiceContainer) {
|
||||
super(resolveIngestionServices(services, 'eod'));
|
||||
|
||||
// Use pre-initialized registry if available, otherwise create new one
|
||||
if ((EodHandler as any).operationRegistry) {
|
||||
this.operationRegistry = (EodHandler as any).operationRegistry;
|
||||
if (EodHandler.operationRegistry) {
|
||||
this.operationRegistry = EodHandler.operationRegistry;
|
||||
this.logger.info('Using pre-initialized EOD operation registry');
|
||||
} else {
|
||||
// Fallback: Initialize operation registry with EOD provider
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
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';
|
||||
import {
|
||||
BaseOperationProvider,
|
||||
OperationRegistry,
|
||||
type OperationConfig,
|
||||
type ProviderConfig,
|
||||
} from '../../../shared/operation-manager';
|
||||
|
||||
/**
|
||||
* EOD operation definitions
|
||||
|
|
@ -13,7 +19,7 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
name: 'exchange_update',
|
||||
type: 'standard',
|
||||
description: 'Update exchange list',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
|
||||
// Symbol data
|
||||
|
|
@ -21,7 +27,7 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
name: 'symbol_update',
|
||||
type: 'standard',
|
||||
description: 'Update symbol list for exchange',
|
||||
defaultStaleHours: 24 // Daily
|
||||
defaultStaleHours: 24, // Daily
|
||||
},
|
||||
|
||||
// Price data
|
||||
|
|
@ -29,7 +35,7 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
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
|
||||
defaultStaleHours: 24 * 7, // Weekly - EOD's schedule-fetch-prices runs for symbols not updated in last week
|
||||
},
|
||||
|
||||
// Intraday data
|
||||
|
|
@ -38,21 +44,21 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
type: 'intraday_crawl',
|
||||
description: 'Crawl 1-minute intraday data',
|
||||
requiresFinishedFlag: true,
|
||||
defaultStaleHours: 50000 // Daily check for new data
|
||||
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
|
||||
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
|
||||
defaultStaleHours: 50000, // Daily check for new data
|
||||
},
|
||||
|
||||
// Fundamental data
|
||||
|
|
@ -60,7 +66,7 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
name: 'fundamentals_update',
|
||||
type: 'standard',
|
||||
description: 'Update fundamental data',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
|
||||
// Corporate actions
|
||||
|
|
@ -68,13 +74,13 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
name: 'dividends_update',
|
||||
type: 'standard',
|
||||
description: 'Update dividend data',
|
||||
defaultStaleHours: 24 * 30 // Monthly
|
||||
defaultStaleHours: 24 * 30, // Monthly
|
||||
},
|
||||
{
|
||||
name: 'splits_update',
|
||||
type: 'standard',
|
||||
description: 'Update stock split data',
|
||||
defaultStaleHours: 24 * 30 // Monthly
|
||||
defaultStaleHours: 24 * 30, // Monthly
|
||||
},
|
||||
|
||||
// Symbol changes
|
||||
|
|
@ -82,8 +88,8 @@ export const EOD_OPERATIONS: OperationConfig[] = [
|
|||
name: 'symbol_change_update',
|
||||
type: 'standard',
|
||||
description: 'Update symbol change history',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
}
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
@ -95,7 +101,7 @@ export class EODOperationProvider extends BaseOperationProvider {
|
|||
name: 'eod',
|
||||
collectionName: 'eodSymbols',
|
||||
symbolField: 'eodSearchCode',
|
||||
description: 'EOD Historical Data provider'
|
||||
description: 'EOD Historical Data provider',
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -108,9 +114,12 @@ export class EODOperationProvider extends BaseOperationProvider {
|
|||
* Create and initialize EOD operation registry
|
||||
*/
|
||||
export async function createEODOperationRegistry(
|
||||
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 EODOperationProvider({ mongodb, logger });
|
||||
await registry.registerProvider(provider);
|
||||
|
|
|
|||
|
|
@ -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']);
|
||||
}
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { HandlerInitializationContext } from '@stock-bot/di';
|
||||
/**
|
||||
* Handler initialization for data-ingestion service
|
||||
* Uses explicit imports for bundling compatibility
|
||||
|
|
@ -5,33 +6,38 @@
|
|||
|
||||
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');
|
||||
|
|
@ -45,7 +51,7 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
|
|||
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 });
|
||||
}
|
||||
|
|
@ -55,7 +61,7 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
|
|||
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 });
|
||||
}
|
||||
|
|
@ -63,16 +69,25 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer)
|
|||
// 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,7 +112,7 @@ 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(),
|
||||
|
|
@ -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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { Document } from 'mongodb';
|
||||
/**
|
||||
* QM Events Actions - Fetch and update dividends, splits, and earnings together
|
||||
*/
|
||||
|
|
@ -53,7 +54,6 @@ export async function updateEvents(
|
|||
symbol: qmSearchCode,
|
||||
});
|
||||
|
||||
|
||||
// TODO: Update with correct events endpoint
|
||||
const apiUrl = `${QM_CONFIG.EVENTS_URL}?${searchParams.toString()}`;
|
||||
|
||||
|
|
@ -79,16 +79,19 @@ export async function updateEvents(
|
|||
// 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,
|
||||
|
|
@ -101,10 +104,14 @@ export async function updateEvents(
|
|||
}
|
||||
|
||||
// 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,
|
||||
|
|
@ -117,10 +124,14 @@ export async function updateEvents(
|
|||
}
|
||||
|
||||
// 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,
|
||||
|
|
@ -138,14 +149,14 @@ export async function updateEvents(
|
|||
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}`, {
|
||||
symbol,
|
||||
dividendCount,
|
||||
splitCount,
|
||||
earningsCount
|
||||
earningsCount,
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -155,10 +166,9 @@ export async function updateEvents(
|
|||
data: {
|
||||
dividends: dividendCount,
|
||||
splits: splitCount,
|
||||
earnings: earningsCount
|
||||
}
|
||||
earnings: earningsCount,
|
||||
},
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
// Update session failure stats
|
||||
if (session.uuid) {
|
||||
|
|
@ -167,19 +177,19 @@ export async function updateEvents(
|
|||
|
||||
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'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -207,7 +217,7 @@ export async function scheduleEventsUpdates(
|
|||
// 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,14 +237,18 @@ export async function scheduleEventsUpdates(
|
|||
// Schedule individual update jobs for each symbol
|
||||
for (const item of staleSymbols) {
|
||||
try {
|
||||
await this.scheduleOperation('update-events', {
|
||||
await this.scheduleOperation(
|
||||
'update-events',
|
||||
{
|
||||
symbol: item.symbol.symbol,
|
||||
exchange: item.symbol.exchange,
|
||||
qmSearchCode: item.symbol.qmSearchCode
|
||||
}, {
|
||||
qmSearchCode: item.symbol.qmSearchCode,
|
||||
},
|
||||
{
|
||||
priority: 4,
|
||||
delay: queued * 0.05 // 1.5 seconds between jobs
|
||||
});
|
||||
delay: queued * 0.05, // 1.5 seconds between jobs
|
||||
}
|
||||
);
|
||||
|
||||
queued++;
|
||||
} catch (error) {
|
||||
|
|
@ -246,13 +260,13 @@ 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 });
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
@ -52,11 +56,11 @@ 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);
|
||||
|
|
@ -72,7 +76,7 @@ export async function updateFilings(
|
|||
// 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,17 +91,24 @@ 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', {
|
||||
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
|
||||
}, {
|
||||
totalPages: filingsData.results.totalCount / filingsData.results.count + 1,
|
||||
},
|
||||
{
|
||||
priority: 5, // Lower priority than financial data
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Update session success stats
|
||||
|
|
@ -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}`, {
|
||||
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,10 +160,9 @@ 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) {
|
||||
|
|
@ -161,18 +171,18 @@ export async function updateFilings(
|
|||
|
||||
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'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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,14 +243,18 @@ export async function scheduleFilingsUpdates(
|
|||
// Schedule individual update jobs for each symbol
|
||||
for (const doc of symbolDocs) {
|
||||
try {
|
||||
await this.scheduleOperation('update-filings', {
|
||||
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) {
|
||||
|
|
@ -248,13 +266,13 @@ 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 });
|
||||
|
|
|
|||
|
|
@ -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,7 +26,7 @@ export async function updateFinancials(
|
|||
success: boolean;
|
||||
qmSearchCode: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { symbol, exchange, qmSearchCode, reportType, lastRecordDate } = input;
|
||||
|
||||
|
|
@ -69,7 +71,8 @@ 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 {
|
||||
reports = financialData?.results?.Company.Report || [];
|
||||
|
|
@ -80,42 +83,49 @@ 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'}`, {
|
||||
await this.operationRegistry.updateOperation(
|
||||
'qm',
|
||||
qmSearchCode,
|
||||
`financials_update_${reportType === 'Q' ? 'quarterly' : 'annual'}`,
|
||||
{
|
||||
status: 'success',
|
||||
lastRecordDate: new Date(),
|
||||
recordCount: reports.length
|
||||
});
|
||||
recordCount: reports.length,
|
||||
}
|
||||
);
|
||||
|
||||
this.logger.info(`Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`, {
|
||||
this.logger.info(
|
||||
`Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`,
|
||||
{
|
||||
qmSearchCode,
|
||||
statementCount: reports.length
|
||||
});
|
||||
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) {
|
||||
|
|
@ -124,18 +134,23 @@ export async function updateFinancials(
|
|||
|
||||
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'}`, {
|
||||
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'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -161,28 +176,41 @@ export async function scheduleFinancialsUpdates(
|
|||
|
||||
try {
|
||||
// Get symbols that need updating for both quarterly and annual
|
||||
const staleSymbolsQ = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_quarterly', {
|
||||
const staleSymbolsQ = await this.operationRegistry.getStaleSymbols(
|
||||
'qm',
|
||||
'financials_update_quarterly',
|
||||
{
|
||||
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default
|
||||
limit
|
||||
});
|
||||
const staleSymbolsA = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_annual', {
|
||||
limit,
|
||||
}
|
||||
);
|
||||
const staleSymbolsA = await this.operationRegistry.getStaleSymbols(
|
||||
'qm',
|
||||
'financials_update_annual',
|
||||
{
|
||||
minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default
|
||||
limit
|
||||
});
|
||||
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) {
|
||||
|
|
@ -190,7 +218,7 @@ export async function scheduleFinancialsUpdates(
|
|||
if (!symbolsNeedingUpdates.has(key)) {
|
||||
symbolsNeedingUpdates.set(key, { quarterly: true, annual: false, item });
|
||||
} else {
|
||||
symbolsNeedingUpdates.get(key)!.quarterly = true;
|
||||
defined(symbolsNeedingUpdates.get(key)).quarterly = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -200,7 +228,7 @@ export async function scheduleFinancialsUpdates(
|
|||
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', {
|
||||
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
|
||||
});
|
||||
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', {
|
||||
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
|
||||
});
|
||||
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,13 +296,13 @@ 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 });
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ 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
|
||||
|
|
@ -23,7 +24,7 @@ export async function updateInsiders(
|
|||
success: boolean;
|
||||
symbol: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { symbol, symbolId, qmSearchCode, lookbackDays = 365 } = input;
|
||||
|
||||
|
|
@ -54,7 +55,7 @@ export async function updateInsiders(
|
|||
startDate: startDate.toISOString().split('T')[0],
|
||||
endDate: endDate.toISOString().split('T')[0],
|
||||
includeOptions: 'true',
|
||||
pageSize: '100'
|
||||
pageSize: '100',
|
||||
} as Record<string, string>);
|
||||
|
||||
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/insiders.json?${searchParams.toString()}`;
|
||||
|
|
@ -69,14 +70,15 @@ export async function updateInsiders(
|
|||
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const insiderData = await response.json();
|
||||
const insiderData = (await response.json()) as { transactions?: QMInsiderTransaction[] };
|
||||
|
||||
// Update session success stats
|
||||
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
|
||||
|
||||
// Process and store insider data
|
||||
if (insiderData && insiderData.transactions && insiderData.transactions.length > 0) {
|
||||
const processedTransactions = insiderData.transactions.map((transaction: any) => ({
|
||||
const processedTransactions = insiderData.transactions.map(transaction => ({
|
||||
source: 'qm',
|
||||
symbol,
|
||||
symbolId,
|
||||
transactionDate: new Date(transaction.transactionDate),
|
||||
|
|
@ -84,14 +86,14 @@ export async function updateInsiders(
|
|||
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,
|
||||
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()
|
||||
updated_at: new Date(),
|
||||
}));
|
||||
|
||||
// Store in MongoDB
|
||||
|
|
@ -102,21 +104,21 @@ export async function updateInsiders(
|
|||
);
|
||||
|
||||
// Calculate summary statistics
|
||||
const totalBuys = processedTransactions.filter((t: any) =>
|
||||
t.transactionType === 'Buy' || t.transactionType === 'Purchase'
|
||||
const totalBuys = processedTransactions.filter(
|
||||
t => t.transactionType === 'Buy' || t.transactionType === 'Purchase'
|
||||
).length;
|
||||
|
||||
const totalSells = processedTransactions.filter((t: any) =>
|
||||
t.transactionType === 'Sell' || t.transactionType === 'Sale'
|
||||
const totalSells = processedTransactions.filter(
|
||||
t => 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);
|
||||
.filter(t => t.transactionType === 'Buy' || t.transactionType === 'Purchase')
|
||||
.reduce((sum, t) => 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);
|
||||
.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', {
|
||||
|
|
@ -129,8 +131,8 @@ export async function updateInsiders(
|
|||
totalBuyValue,
|
||||
totalSellValue,
|
||||
netValue: totalBuyValue - totalSellValue,
|
||||
uniqueInsiders: new Set(processedTransactions.map((t: any) => t.insiderName)).size
|
||||
}
|
||||
uniqueInsiders: new Set(processedTransactions.map(t => t.insiderName)).size,
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.info('Insider transactions updated successfully', {
|
||||
|
|
@ -138,7 +140,7 @@ export async function updateInsiders(
|
|||
transactionCount: processedTransactions.length,
|
||||
totalBuys,
|
||||
totalSells,
|
||||
netValue: totalBuyValue - totalSellValue
|
||||
netValue: totalBuyValue - totalSellValue,
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -151,8 +153,8 @@ export async function updateInsiders(
|
|||
totalSells,
|
||||
totalBuyValue,
|
||||
totalSellValue,
|
||||
netValue: totalBuyValue - totalSellValue
|
||||
}
|
||||
netValue: totalBuyValue - totalSellValue,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
// No insider data
|
||||
|
|
@ -161,17 +163,16 @@ export async function updateInsiders(
|
|||
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', {
|
||||
status: 'success',
|
||||
lastRecordDate: endDate,
|
||||
recordCount: 0
|
||||
recordCount: 0,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
symbol,
|
||||
message: 'No insider transactions found',
|
||||
data: { count: 0 }
|
||||
data: { count: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Update session failure stats
|
||||
if (session.uuid) {
|
||||
|
|
@ -180,19 +181,19 @@ export async function updateInsiders(
|
|||
|
||||
this.logger.error('Error fetching insider transactions', {
|
||||
symbol,
|
||||
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, 'insiders_update', {
|
||||
status: 'failure',
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
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'}`
|
||||
message: `Failed to fetch insider transactions: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -221,7 +222,7 @@ export async function scheduleInsidersUpdates(
|
|||
// Get symbols that need insider updates
|
||||
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'insiders_update', {
|
||||
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
|
||||
limit
|
||||
limit,
|
||||
});
|
||||
|
||||
if (staleSymbols.length === 0) {
|
||||
|
|
@ -229,7 +230,7 @@ export async function scheduleInsidersUpdates(
|
|||
return {
|
||||
message: 'No symbols need insider updates',
|
||||
symbolsQueued: 0,
|
||||
errors: 0
|
||||
errors: 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -246,14 +247,18 @@ export async function scheduleInsidersUpdates(
|
|||
continue;
|
||||
}
|
||||
|
||||
await this.scheduleOperation('update-insiders', {
|
||||
await this.scheduleOperation(
|
||||
'update-insiders',
|
||||
{
|
||||
symbol: item.symbol.symbol,
|
||||
symbolId: item.symbol.symbolId,
|
||||
qmSearchCode: item.symbol.qmSearchCode
|
||||
}, {
|
||||
qmSearchCode: item.symbol.qmSearchCode,
|
||||
},
|
||||
{
|
||||
priority: 5, // Medium priority
|
||||
delay: symbolsQueued * 1000 // 1 second between jobs
|
||||
});
|
||||
delay: symbolsQueued * 1000, // 1 second between jobs
|
||||
}
|
||||
);
|
||||
|
||||
symbolsQueued++;
|
||||
} catch (error) {
|
||||
|
|
@ -264,13 +269,13 @@ export async function scheduleInsidersUpdates(
|
|||
|
||||
this.logger.info('Insider update scheduling completed', {
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
});
|
||||
|
||||
return {
|
||||
message: `Scheduled insider updates for ${symbolsQueued} symbols`,
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('Insider scheduling failed', { error });
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { Document } from 'mongodb';
|
||||
/**
|
||||
* 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 { 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';
|
||||
|
|
@ -13,11 +14,10 @@ interface IntradayCrawlInput {
|
|||
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
|
||||
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)
|
||||
*/
|
||||
|
|
@ -31,7 +31,7 @@ export async function crawlIntradayData(
|
|||
exchange: string;
|
||||
qmSearchCode: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const {
|
||||
symbol,
|
||||
|
|
@ -39,7 +39,7 @@ export async function crawlIntradayData(
|
|||
qmSearchCode,
|
||||
targetOldestDate = '1960-01-01', // Default to ~5 years of data
|
||||
existingCrawlState,
|
||||
gaps
|
||||
gaps,
|
||||
} = input;
|
||||
|
||||
this.logger.info('Starting intraday crawl', {
|
||||
|
|
@ -47,7 +47,7 @@ export async function crawlIntradayData(
|
|||
exchange,
|
||||
targetOldestDate,
|
||||
hasExistingState: !!existingCrawlState,
|
||||
gaps
|
||||
gaps,
|
||||
});
|
||||
|
||||
const sessionManager = QMSessionManager.getInstance();
|
||||
|
|
@ -62,18 +62,18 @@ export async function crawlIntradayData(
|
|||
|
||||
try {
|
||||
// Use passed crawl state if available, otherwise query for it
|
||||
let currentCrawlState: CrawlState;
|
||||
let currentCrawlState: Partial<OperationStatus>;
|
||||
|
||||
if (existingCrawlState) {
|
||||
currentCrawlState = existingCrawlState;
|
||||
} else {
|
||||
// Only query if not passed
|
||||
const symbolData = await this.mongodb.findOne('qmSymbols', {
|
||||
qmSearchCode
|
||||
qmSearchCode,
|
||||
});
|
||||
|
||||
currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || {
|
||||
finished: false
|
||||
finished: false,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +91,6 @@ export async function crawlIntradayData(
|
|||
// console.log('Current week before adjustment:', currentWeek);
|
||||
}
|
||||
|
||||
|
||||
// Get the Sunday of the current week
|
||||
currentWeek = getLastWeek(currentWeek);
|
||||
|
||||
|
|
@ -106,7 +105,7 @@ export async function crawlIntradayData(
|
|||
qmSearchCode,
|
||||
symbol,
|
||||
exchange,
|
||||
message: 'Intraday crawl already complete'
|
||||
message: 'Intraday crawl already complete',
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -114,7 +113,7 @@ export async function crawlIntradayData(
|
|||
let weeksProcessed = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
const endOfWeek = new Date(currentWeek)
|
||||
const endOfWeek = new Date(currentWeek);
|
||||
endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday
|
||||
// Build API request for the week
|
||||
const searchParams = new URLSearchParams({
|
||||
|
|
@ -149,18 +148,21 @@ export async function crawlIntradayData(
|
|||
// 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}`, {
|
||||
this.logger.info(
|
||||
`Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`,
|
||||
{
|
||||
qmSearchCode,
|
||||
currentWeek,
|
||||
records: barsLength
|
||||
});
|
||||
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) => ({
|
||||
const processedBars = barsData.map((bar: Document) => ({
|
||||
...bar,
|
||||
qmSearchCode,
|
||||
symbol,
|
||||
|
|
@ -168,25 +170,19 @@ export async function crawlIntradayData(
|
|||
timestamp: new Date(bar.startdatetime || bar.date || bar.datetime),
|
||||
}));
|
||||
|
||||
await this.mongodb.batchUpsert(
|
||||
'qmIntraday',
|
||||
processedBars,
|
||||
['qmSearchCode', 'timestamp']
|
||||
);
|
||||
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', {
|
||||
const finished = barsData === null && nextWeek < new Date('2024-01-01');
|
||||
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
|
||||
status: 'success',
|
||||
crawlState: {
|
||||
finished: finished,
|
||||
finished,
|
||||
oldestDateReached: currentCrawlState.oldestDateReached,
|
||||
lastProcessedDate: currentWeek
|
||||
}
|
||||
lastProcessedDate: currentWeek,
|
||||
});
|
||||
|
||||
// Calculate next week to process (previous Sunday)
|
||||
|
|
@ -194,17 +190,21 @@ export async function crawlIntradayData(
|
|||
// console.log(barsData === null , existingCrawlState);
|
||||
if (!finished) {
|
||||
currentCrawlState.lastProcessedDate = nextWeek;
|
||||
await this.scheduleOperation('crawl-intraday-data', {
|
||||
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
|
||||
}, {
|
||||
gaps: gaps,
|
||||
},
|
||||
{
|
||||
priority: 4, // Standard priority for backward crawls
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -217,19 +217,18 @@ export async function crawlIntradayData(
|
|||
totalRecords,
|
||||
weeksProcessed,
|
||||
nextWeek: nextWeek.toISOString().split('T')[0],
|
||||
errors: errors.length > 0 ? errors : undefined
|
||||
}
|
||||
}
|
||||
|
||||
errors: errors.length > 0 ? errors : undefined,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('Intraday crawl failed', {
|
||||
symbol,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
|
||||
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', {
|
||||
status: 'failure',
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -237,7 +236,7 @@ export async function crawlIntradayData(
|
|||
symbol,
|
||||
exchange,
|
||||
qmSearchCode,
|
||||
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -246,7 +245,7 @@ export async function crawlIntradayData(
|
|||
symbol,
|
||||
exchange,
|
||||
qmSearchCode,
|
||||
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -267,61 +266,54 @@ export async function scheduleIntradayCrawls(
|
|||
symbolsQueued: number;
|
||||
errors: number;
|
||||
}> {
|
||||
const {
|
||||
limit = 999999999,
|
||||
targetOldestDate = '1960-01-01',
|
||||
priorityMode = 'all'
|
||||
} = input;
|
||||
const { limit = 999999999, targetOldestDate = '1960-01-01', priorityMode = 'all' } = input;
|
||||
|
||||
this.logger.info('Scheduling intraday crawls', {
|
||||
limit,
|
||||
targetOldestDate,
|
||||
priorityMode
|
||||
priorityMode,
|
||||
});
|
||||
|
||||
try {
|
||||
// Get symbols based on priority mode
|
||||
let symbolsToProcess: any[] = [];
|
||||
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', {
|
||||
symbolsToProcess = await this.mongodb.find(
|
||||
'qmSymbols',
|
||||
{
|
||||
'operations.intraday_bars': { $exists: false },
|
||||
active: { $ne: false }
|
||||
}, {
|
||||
active: { $ne: false },
|
||||
},
|
||||
{
|
||||
limit,
|
||||
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 }
|
||||
});
|
||||
projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 },
|
||||
}
|
||||
);
|
||||
break;
|
||||
|
||||
case 'incomplete':
|
||||
// Get symbols with incomplete crawls
|
||||
symbolsToProcess = await tracker.getSymbolsForIntradayCrawl(
|
||||
'intraday_bars',
|
||||
{
|
||||
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',
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
@ -329,28 +321,34 @@ export async function scheduleIntradayCrawls(
|
|||
return {
|
||||
message: `No symbols found for priority mode: ${priorityMode}`,
|
||||
symbolsQueued: 0,
|
||||
errors: 0
|
||||
errors: 0,
|
||||
};
|
||||
}
|
||||
|
||||
this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', {
|
||||
count: symbolsToProcess.length,
|
||||
firstSymbol: symbolsToProcess[0] ? {
|
||||
firstSymbol: symbolsToProcess[0]
|
||||
? {
|
||||
symbol: symbolsToProcess[0].symbol,
|
||||
gaps: symbolsToProcess[0].gaps,
|
||||
hasOperationStatus: !!symbolsToProcess[0].operationStatus,
|
||||
crawlState: symbolsToProcess[0].operationStatus?.crawlState
|
||||
} : null
|
||||
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 }
|
||||
});
|
||||
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 => {
|
||||
|
|
@ -359,7 +357,7 @@ export async function scheduleIntradayCrawls(
|
|||
return {
|
||||
...full,
|
||||
gaps: sp.gaps, // Preserve gap information
|
||||
operationStatus: sp.operationStatus // Preserve original operation status
|
||||
operationStatus: sp.operationStatus, // Preserve original operation status
|
||||
};
|
||||
}
|
||||
return sp;
|
||||
|
|
@ -368,34 +366,39 @@ export async function scheduleIntradayCrawls(
|
|||
|
||||
this.logger.info('After mapping, symbols to process', {
|
||||
count: symbolsToProcess.length,
|
||||
firstSymbol: symbolsToProcess[0] ? {
|
||||
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
|
||||
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', {
|
||||
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
|
||||
}, {
|
||||
gaps: doc.gaps,
|
||||
},
|
||||
{
|
||||
priority: 6, // Standard priority for backward crawls
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
symbolsQueued++;
|
||||
} catch (error) {
|
||||
|
|
@ -407,15 +410,14 @@ export async function scheduleIntradayCrawls(
|
|||
this.logger.info('Intraday crawl scheduling completed', {
|
||||
priorityMode,
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
});
|
||||
|
||||
return {
|
||||
message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`,
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('Intraday crawl scheduling failed', { error });
|
||||
throw error;
|
||||
|
|
|
|||
|
|
@ -6,22 +6,7 @@ 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;
|
||||
}
|
||||
import type { QMNewsArticle } from '../shared/types';
|
||||
|
||||
/**
|
||||
* Update news for a single symbol
|
||||
|
|
@ -39,7 +24,7 @@ export async function updateSymbolNews(
|
|||
success: boolean;
|
||||
symbol: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input;
|
||||
|
||||
|
|
@ -70,7 +55,7 @@ export async function updateSymbolNews(
|
|||
startDate: startDate.toISOString().split('T')[0],
|
||||
endDate: endDate.toISOString().split('T')[0],
|
||||
includeContent: 'true',
|
||||
pageSize: '50'
|
||||
pageSize: '50',
|
||||
} as Record<string, string>);
|
||||
|
||||
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`;
|
||||
|
|
@ -85,15 +70,16 @@ export async function updateSymbolNews(
|
|||
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const newsData = await response.json();
|
||||
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: any) => ({
|
||||
articleId: article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`,
|
||||
const processedArticles = newsData.articles.map(article => ({
|
||||
articleId:
|
||||
article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`,
|
||||
symbol,
|
||||
symbolId,
|
||||
publishedDate: new Date(article.publishedDate),
|
||||
|
|
@ -103,13 +89,15 @@ export async function updateSymbolNews(
|
|||
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,
|
||||
sentiment: article.sentiment
|
||||
? {
|
||||
score: Number(article.sentiment.score) || 0,
|
||||
label: article.sentiment.label || 'neutral',
|
||||
}
|
||||
: null,
|
||||
imageUrl: article.imageUrl,
|
||||
isSymbolSpecific: true,
|
||||
updated_at: new Date()
|
||||
updated_at: new Date(),
|
||||
}));
|
||||
|
||||
// Store in MongoDB
|
||||
|
|
@ -120,7 +108,7 @@ export async function updateSymbolNews(
|
|||
);
|
||||
|
||||
// Calculate sentiment summary
|
||||
const sentimentCounts = processedArticles.reduce((acc: any, article: any) => {
|
||||
const sentimentCounts = processedArticles.reduce<Record<string, number>>((acc, article) => {
|
||||
if (article.sentiment) {
|
||||
acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1;
|
||||
}
|
||||
|
|
@ -134,19 +122,23 @@ export async function updateSymbolNews(
|
|||
recordCount: processedArticles.length,
|
||||
metadata: {
|
||||
sentimentCounts,
|
||||
uniqueSources: new Set(processedArticles.map((a: any) => a.source)).size,
|
||||
uniqueSources: new Set(processedArticles.map(a => 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
|
||||
)
|
||||
}
|
||||
.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
|
||||
sentimentCounts,
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -156,8 +148,8 @@ export async function updateSymbolNews(
|
|||
data: {
|
||||
count: processedArticles.length,
|
||||
sentimentCounts,
|
||||
sources: new Set(processedArticles.map((a: any) => a.source)).size
|
||||
}
|
||||
sources: new Set(processedArticles.map(a => a.source)).size,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
// No news found
|
||||
|
|
@ -166,17 +158,16 @@ export async function updateSymbolNews(
|
|||
await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', {
|
||||
status: 'success',
|
||||
lastRecordDate: endDate,
|
||||
recordCount: 0
|
||||
recordCount: 0,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
symbol,
|
||||
message: 'No news articles found',
|
||||
data: { count: 0 }
|
||||
data: { count: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Update session failure stats
|
||||
if (session.uuid) {
|
||||
|
|
@ -185,19 +176,19 @@ export async function updateSymbolNews(
|
|||
|
||||
this.logger.error('Error fetching symbol news', {
|
||||
symbol,
|
||||
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, 'news_update', {
|
||||
status: 'failure',
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
symbol,
|
||||
message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -215,7 +206,7 @@ export async function updateGeneralNews(
|
|||
): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input;
|
||||
|
||||
|
|
@ -245,7 +236,7 @@ export async function updateGeneralNews(
|
|||
startDateTime: startDate.toISOString(),
|
||||
endDateTime: endDate.toISOString(),
|
||||
includeContent: 'true',
|
||||
pageSize: '100'
|
||||
pageSize: '100',
|
||||
} as Record<string, string>);
|
||||
|
||||
const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`;
|
||||
|
|
@ -260,15 +251,16 @@ export async function updateGeneralNews(
|
|||
throw new Error(`QM API request failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const newsData = await response.json();
|
||||
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: any) => ({
|
||||
articleId: article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`,
|
||||
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),
|
||||
|
|
@ -276,15 +268,17 @@ export async function updateGeneralNews(
|
|||
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,
|
||||
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()
|
||||
updated_at: new Date(),
|
||||
}));
|
||||
|
||||
// Store in MongoDB
|
||||
|
|
@ -295,8 +289,8 @@ export async function updateGeneralNews(
|
|||
);
|
||||
|
||||
// Find high-importance articles
|
||||
const highImportanceCount = processedArticles.filter((a: any) =>
|
||||
a.importance === 'high' || a.isMarketMoving
|
||||
const highImportanceCount = processedArticles.filter(
|
||||
a => a.importance === 'high' || a.isMarketMoving
|
||||
).length;
|
||||
|
||||
// Update a general tracking document
|
||||
|
|
@ -309,8 +303,8 @@ export async function updateGeneralNews(
|
|||
lastRecordCount: processedArticles.length,
|
||||
highImportanceCount,
|
||||
categories,
|
||||
updated_at: new Date()
|
||||
}
|
||||
updated_at: new Date(),
|
||||
},
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
|
|
@ -318,7 +312,7 @@ export async function updateGeneralNews(
|
|||
this.logger.info('General news updated successfully', {
|
||||
articleCount: processedArticles.length,
|
||||
highImportanceCount,
|
||||
categories
|
||||
categories,
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -328,8 +322,8 @@ export async function updateGeneralNews(
|
|||
count: processedArticles.length,
|
||||
highImportanceCount,
|
||||
categories,
|
||||
sources: new Set(processedArticles.map((a: any) => a.source)).size
|
||||
}
|
||||
sources: new Set(processedArticles.map(a => a.source)).size,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
// No news found
|
||||
|
|
@ -338,10 +332,9 @@ export async function updateGeneralNews(
|
|||
return {
|
||||
success: true,
|
||||
message: 'No general news articles found',
|
||||
data: { count: 0 }
|
||||
data: { count: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Update session failure stats
|
||||
if (session.uuid) {
|
||||
|
|
@ -349,12 +342,12 @@ export async function updateGeneralNews(
|
|||
}
|
||||
|
||||
this.logger.error('Error fetching general news', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -383,7 +376,7 @@ export async function scheduleSymbolNewsUpdates(
|
|||
// Get symbols that need news updates
|
||||
const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', {
|
||||
minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun,
|
||||
limit
|
||||
limit,
|
||||
});
|
||||
|
||||
if (staleSymbols.length === 0) {
|
||||
|
|
@ -391,7 +384,7 @@ export async function scheduleSymbolNewsUpdates(
|
|||
return {
|
||||
message: 'No symbols need news updates',
|
||||
symbolsQueued: 0,
|
||||
errors: 0
|
||||
errors: 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -408,14 +401,18 @@ export async function scheduleSymbolNewsUpdates(
|
|||
continue;
|
||||
}
|
||||
|
||||
await this.scheduleOperation('update-symbol-news', {
|
||||
await this.scheduleOperation(
|
||||
'update-symbol-news',
|
||||
{
|
||||
symbol: item.symbol.symbol,
|
||||
symbolId: item.symbol.symbolId,
|
||||
qmSearchCode: item.symbol.qmSearchCode
|
||||
}, {
|
||||
qmSearchCode: item.symbol.qmSearchCode,
|
||||
},
|
||||
{
|
||||
priority: 4, // Lower priority than price data
|
||||
delay: symbolsQueued * 500 // 0.5 seconds between jobs
|
||||
});
|
||||
delay: symbolsQueued * 500, // 0.5 seconds between jobs
|
||||
}
|
||||
);
|
||||
|
||||
symbolsQueued++;
|
||||
} catch (error) {
|
||||
|
|
@ -426,13 +423,13 @@ export async function scheduleSymbolNewsUpdates(
|
|||
|
||||
this.logger.info('Symbol news update scheduling completed', {
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
});
|
||||
|
||||
return {
|
||||
message: `Scheduled news updates for ${symbolsQueued} symbols`,
|
||||
symbolsQueued,
|
||||
errors
|
||||
errors,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('Symbol news scheduling failed', { error });
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { Document } from 'mongodb';
|
||||
/**
|
||||
* QM Prices Actions - Fetch and update daily price data
|
||||
*/
|
||||
|
|
@ -23,7 +24,7 @@ export async function updatePrices(
|
|||
success: boolean;
|
||||
qmSearchCode: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { qmSearchCode, lastRecordDate, symbol, exchange } = input;
|
||||
|
||||
|
|
@ -44,7 +45,9 @@ export async function updatePrices(
|
|||
// Build API request for daily prices
|
||||
const searchParams = new URLSearchParams({
|
||||
zeroTradeDays: 'false',
|
||||
start: lastRecordDate ? new Date(lastRecordDate).toISOString().split('T')[0] + '' : '1960-01-01',
|
||||
start: lastRecordDate
|
||||
? new Date(lastRecordDate).toISOString().split('T')[0] + ''
|
||||
: '1960-01-01',
|
||||
interval: '1',
|
||||
marketSession: 'mkt',
|
||||
freq: 'day',
|
||||
|
|
@ -79,19 +82,19 @@ export async function updatePrices(
|
|||
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,22 +109,21 @@ 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', {
|
||||
qmSearchCode,
|
||||
priceCount: priceData.length,
|
||||
latestDate
|
||||
latestDate,
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
@ -130,18 +132,17 @@ export async function updatePrices(
|
|||
message: `Prices updated for ${qmSearchCode}`,
|
||||
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) {
|
||||
|
|
@ -150,18 +151,18 @@ export async function updatePrices(
|
|||
|
||||
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'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -189,7 +190,7 @@ export async function schedulePriceUpdates(
|
|||
// 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', {
|
||||
await this.scheduleOperation(
|
||||
'update-prices',
|
||||
{
|
||||
qmSearchCode: item.symbol.qmSearchCode,
|
||||
lastRecordDate: item.operations?.price_update?.lastRecordDate,
|
||||
symbol: item.symbol.symbol,
|
||||
exchange: item.symbol.exchange
|
||||
}, {
|
||||
exchange: item.symbol.exchange,
|
||||
},
|
||||
{
|
||||
priority: 7, // High priority for price data
|
||||
delay: queued * 100 // 0.1 seconds between jobs
|
||||
});
|
||||
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,13 +236,13 @@ 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 });
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
@ -59,22 +61,22 @@ export async function updateExchangeStats(
|
|||
|
||||
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
|
||||
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');
|
||||
|
|
@ -260,7 +268,7 @@ export async function updateExchangeStatsAndDeduplicate(
|
|||
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 });
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export async function updateSymbolInfo(
|
|||
success: boolean;
|
||||
qmSearchCode: string;
|
||||
message: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}> {
|
||||
const { qmSearchCode } = input;
|
||||
|
||||
|
|
@ -66,18 +66,21 @@ export async function updateSymbolInfo(
|
|||
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,7 +88,7 @@ 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}`, {
|
||||
|
|
@ -102,10 +105,9 @@ 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) {
|
||||
|
|
@ -114,18 +116,18 @@ export async function updateSymbolInfo(
|
|||
|
||||
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'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -154,7 +156,7 @@ export async function scheduleSymbolInfoUpdates(
|
|||
// 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,13 +176,17 @@ 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
|
||||
}, {
|
||||
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) {
|
||||
|
|
@ -192,13 +198,13 @@ 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 });
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { Document } from 'mongodb';
|
||||
/**
|
||||
* QM Symbol Actions - Symbol search and spider operations
|
||||
*/
|
||||
|
|
@ -31,21 +32,25 @@ 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', {
|
||||
await this.scheduleOperation(
|
||||
'spider-symbols',
|
||||
{
|
||||
prefix: letter,
|
||||
depth: 1,
|
||||
source: 'qm',
|
||||
maxDepth
|
||||
}, {
|
||||
priority: 5
|
||||
});
|
||||
maxDepth,
|
||||
},
|
||||
{
|
||||
priority: 5,
|
||||
}
|
||||
);
|
||||
jobsCreated++;
|
||||
}
|
||||
|
||||
this.logger.info('Created root spider jobs', { jobsCreated });
|
||||
return {
|
||||
message: `Queued ${jobsCreated} root jobs (A-Z)`,
|
||||
jobsCreated
|
||||
jobsCreated,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -57,15 +62,19 @@ export async function spiderSymbol(
|
|||
this.logger.debug('No symbols found for prefix', { prefix });
|
||||
return {
|
||||
message: `No symbols found for prefix: ${prefix}`,
|
||||
symbolsFound: 0
|
||||
symbolsFound: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await this.mongodb?.batchUpsert('qmSymbols', symbols, ['qmSearchCode']);
|
||||
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
|
||||
count: symbols.length,
|
||||
});
|
||||
|
||||
// Extract and store unique exchanges
|
||||
|
|
@ -84,7 +93,7 @@ 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
|
||||
count: exchanges.length,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -97,14 +106,18 @@ export async function spiderSymbol(
|
|||
if (symbols.length >= 50) {
|
||||
for (let i = 0; i < 26; i++) {
|
||||
const nextPrefix = prefix + String.fromCharCode(65 + i);
|
||||
await this.scheduleOperation('spider-symbols', {
|
||||
await this.scheduleOperation(
|
||||
'spider-symbols',
|
||||
{
|
||||
prefix: nextPrefix,
|
||||
depth: depth + 1,
|
||||
source: 'qm',
|
||||
maxDepth
|
||||
}, {
|
||||
priority: Math.max(1, 5 - depth)
|
||||
});
|
||||
maxDepth,
|
||||
},
|
||||
{
|
||||
priority: Math.max(1, 5 - depth),
|
||||
}
|
||||
);
|
||||
jobsCreated++;
|
||||
}
|
||||
}
|
||||
|
|
@ -112,20 +125,19 @@ export async function spiderSymbol(
|
|||
return {
|
||||
message: `Found ${symbols.length} symbols for ${prefix}, queued ${jobsCreated} child jobs`,
|
||||
symbolsFound: symbols.length,
|
||||
jobsCreated
|
||||
jobsCreated,
|
||||
};
|
||||
}
|
||||
|
||||
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,7 +149,7 @@ 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 });
|
||||
|
|
@ -163,7 +175,7 @@ export async function searchSymbols(
|
|||
searchType: 'symbol',
|
||||
showFree: 'false',
|
||||
showHisa: 'false',
|
||||
webmasterId: '500'
|
||||
webmasterId: '500',
|
||||
});
|
||||
|
||||
const apiUrl = `${QM_CONFIG.LOOKUP_URL}?${searchParams.toString()}`;
|
||||
|
|
@ -184,7 +196,8 @@ export async function searchSymbols(
|
|||
await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid);
|
||||
|
||||
// Process symbol data
|
||||
const processedSymbols = Array.isArray(symbols) ? symbols.map((symbol: any) => {
|
||||
const processedSymbols = Array.isArray(symbols)
|
||||
? symbols.map((symbol: Document) => {
|
||||
const { exchangeCode, exchangeShortName, ...rest } = symbol;
|
||||
return {
|
||||
...rest,
|
||||
|
|
@ -193,15 +206,15 @@ export async function searchSymbols(
|
|||
qmSearchCode: symbol.symbol,
|
||||
symbol: (symbol.symbol as string)?.split(':')[0],
|
||||
};
|
||||
}) : [];
|
||||
})
|
||||
: [];
|
||||
|
||||
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) {
|
||||
|
|
@ -210,7 +223,7 @@ export async function searchSymbols(
|
|||
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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,12 +212,12 @@ 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
|
||||
});
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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,7 +19,7 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
name: 'symbol_info',
|
||||
type: 'standard',
|
||||
description: 'Update symbol metadata',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
|
||||
// Price data
|
||||
|
|
@ -21,14 +27,14 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
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
|
||||
|
|
@ -36,13 +42,13 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
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
|
||||
|
|
@ -50,7 +56,7 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
name: 'events_update',
|
||||
type: 'standard',
|
||||
description: 'Update events (earnings, dividends, splits)',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
|
||||
// Filings
|
||||
|
|
@ -58,7 +64,7 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
name: 'filings_update',
|
||||
type: 'standard',
|
||||
description: 'Update SEC filings',
|
||||
defaultStaleHours: 24 // Daily
|
||||
defaultStaleHours: 24, // Daily
|
||||
},
|
||||
|
||||
// Insider trading
|
||||
|
|
@ -66,7 +72,7 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
name: 'insiders_update',
|
||||
type: 'standard',
|
||||
description: 'Update insider transactions',
|
||||
defaultStaleHours: 24 * 7 // Weekly
|
||||
defaultStaleHours: 24 * 7, // Weekly
|
||||
},
|
||||
|
||||
// News
|
||||
|
|
@ -74,8 +80,8 @@ export const QM_OPERATIONS: OperationConfig[] = [
|
|||
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,9 +106,12 @@ 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);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -277,7 +275,7 @@ export class QMSessionManagerRedis {
|
|||
this.logger?.debug(`Incremented failed calls for session`, {
|
||||
sessionUuid,
|
||||
failedCalls: session.failedCalls,
|
||||
sessionId
|
||||
sessionId,
|
||||
});
|
||||
} else {
|
||||
this.logger?.warn(`Session not found`, { sessionUuid, sessionId });
|
||||
|
|
@ -300,7 +298,7 @@ export class QMSessionManagerRedis {
|
|||
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 = {
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ 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();
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
}, {
|
||||
const staleUrls = await mongodb?.find(
|
||||
'teUrls',
|
||||
{
|
||||
$or: [{ lastCrawled: { $exists: false } }, { lastCrawled: { $lt: cutoff } }],
|
||||
skipReason: { $exists: false },
|
||||
},
|
||||
{
|
||||
sort: { lastCrawled: 1 },
|
||||
projection: { url: 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 }, {
|
||||
const { url } = at(staleUrls, i);
|
||||
await this.scheduleOperation(
|
||||
'te-spider',
|
||||
{ url },
|
||||
{
|
||||
jobId: `spider-${url.replace(/\//g, '-')}`,
|
||||
priority: 8,
|
||||
delay: i * 200
|
||||
});
|
||||
delay: i * 200,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return { scheduled: staleUrls.length };
|
||||
|
|
|
|||
|
|
@ -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,25 +61,35 @@ export async function dataFetch(
|
|||
|
||||
if (!serie?.data?.length) {
|
||||
logger.warn(`No data points decoded for ${teSymbol}`);
|
||||
await mongodb?.updateOne('teUrls', { url }, {
|
||||
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 }, {
|
||||
await mongodb?.updateOne(
|
||||
'teData',
|
||||
{ teSymbol },
|
||||
{
|
||||
$set: {
|
||||
teSymbol,
|
||||
name: serie.name,
|
||||
|
|
@ -86,12 +103,16 @@ 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(existing.data.map((p: any) => [p.d, p.v]));
|
||||
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);
|
||||
}
|
||||
|
|
@ -99,16 +120,23 @@ export async function dataFetch(
|
|||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([d, v]) => ({ d, v }));
|
||||
|
||||
await mongodb?.updateOne('teData', { teSymbol }, {
|
||||
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 +150,25 @@ export async function dataFetch(
|
|||
lastUpdated: new Date(),
|
||||
},
|
||||
$setOnInsert: { createdAt: new Date() },
|
||||
}, { upsert: true });
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const totalPoints = dataPoints.length + forecastPoints.length;
|
||||
|
||||
await mongodb?.updateOne('teUrls', { url }, {
|
||||
await mongodb?.updateOne(
|
||||
'teUrls',
|
||||
{ url },
|
||||
{
|
||||
$set: {
|
||||
lastDataFetch: new Date(),
|
||||
lastDataFetchUpdate: teDoc.teLastUpdate,
|
||||
lastDataFetchCount: totalPoints,
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
return { success: true, recordCount: totalPoints };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}`,
|
||||
|
|
|
|||
|
|
@ -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,10 +28,16 @@ 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
|
||||
$(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') || '';
|
||||
|
|
@ -41,6 +47,7 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number
|
|||
indicators.push({ group, slug, name, url: href });
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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,15 +107,28 @@ 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 }, {
|
||||
await mongodb?.updateOne(
|
||||
'teMarketData',
|
||||
{ teSymbol },
|
||||
{
|
||||
$set: {
|
||||
teSymbol,
|
||||
name: serie?.name,
|
||||
|
|
@ -120,13 +146,23 @@ export async function marketDataFetch(
|
|||
lastUpdated: 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 }, {
|
||||
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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
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;
|
||||
|
||||
|
|
@ -31,8 +34,8 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
$set: {
|
||||
lastCrawled: new Date(),
|
||||
foundLinks: 0,
|
||||
error: true
|
||||
}
|
||||
error: true,
|
||||
},
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
|
|
@ -74,14 +77,16 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
|
||||
// Extract JSON metadata - use a more flexible regex
|
||||
match = html.match(/TEChartsMeta = (\[[\s\S]*?\]);/);
|
||||
const teChartsMeta = match ? (() => {
|
||||
const teChartsMeta = match
|
||||
? (() => {
|
||||
try {
|
||||
return JSON.parse(match[1]);
|
||||
return JSON.parse(at(match, 1));
|
||||
} catch (e) {
|
||||
logger.warn('Failed to parse TEChartsMeta:', e);
|
||||
logger.warn('Failed to parse TEChartsMeta', { error: e });
|
||||
return undefined;
|
||||
}
|
||||
})() : undefined;
|
||||
})()
|
||||
: undefined;
|
||||
|
||||
// Extract symbol data
|
||||
match = html.match(/symbol = '([^']+)'/);
|
||||
|
|
@ -98,10 +103,22 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
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:', {
|
||||
|
|
@ -119,7 +136,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
symbol,
|
||||
symbolType,
|
||||
teChartsDatasource,
|
||||
teChartToken
|
||||
teChartToken,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -130,10 +147,23 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
// 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));
|
||||
}
|
||||
|
|
@ -160,7 +190,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
}
|
||||
|
||||
// Clean the path
|
||||
path = path.split('?')[0].split('#')[0];
|
||||
path = at(at(path.split('?'), 0).split('#'), 0);
|
||||
|
||||
// Basic filtering
|
||||
if (shouldCrawl(path)) {
|
||||
|
|
@ -173,10 +203,10 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
|
||||
// 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
|
||||
|
|
@ -226,12 +256,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
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[] = [];
|
||||
|
|
@ -243,8 +268,8 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
$setOnInsert: {
|
||||
url,
|
||||
createdAt: new Date(),
|
||||
source: urlPath
|
||||
}
|
||||
source: urlPath,
|
||||
},
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
|
|
@ -257,11 +282,15 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom
|
|||
// 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 }, {
|
||||
await this.scheduleOperation(
|
||||
'te-spider',
|
||||
{ url },
|
||||
{
|
||||
jobId: `spider-${url.replace(/\//g, '-')}`,
|
||||
priority: 10,
|
||||
delay: Math.floor(Math.random() * 10000) // Spread requests over 10 seconds
|
||||
});
|
||||
delay: Math.floor(Math.random() * 10000), // Spread requests over 10 seconds
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return urls;
|
||||
|
|
@ -280,13 +309,13 @@ async function fetchPage(this: TeHandler, url: string): Promise<string | null> {
|
|||
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) {
|
||||
|
|
@ -295,7 +324,6 @@ async function fetchPage(this: TeHandler, url: string): Promise<string | null> {
|
|||
|
||||
// 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) {
|
||||
|
|
@ -317,7 +345,9 @@ function shouldCrawl(url: string): boolean {
|
|||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -47,8 +47,8 @@ export interface TeMkCdnSerie {
|
|||
sector: string;
|
||||
industry: string;
|
||||
frequency: string;
|
||||
/** Each point: [epoch, value, pctChange, absChange] */
|
||||
data: Array<[number, number, number | null, number | null]>;
|
||||
/** 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 */
|
||||
|
|
|
|||
|
|
@ -1,22 +1,33 @@
|
|||
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) {
|
||||
|
|
@ -26,14 +37,14 @@ 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: {
|
||||
name: 'crawl_status_idx',
|
||||
background: true
|
||||
}
|
||||
background: true,
|
||||
},
|
||||
},
|
||||
// Unique index on URL to prevent duplicates
|
||||
{
|
||||
|
|
@ -41,8 +52,8 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
|
|||
options: {
|
||||
name: 'url_unique_idx',
|
||||
unique: true,
|
||||
background: true
|
||||
}
|
||||
background: true,
|
||||
},
|
||||
},
|
||||
// Index for finding URLs by symbol
|
||||
{
|
||||
|
|
@ -50,8 +61,8 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
|
|||
options: {
|
||||
name: 'symbol_idx',
|
||||
sparse: true,
|
||||
background: true
|
||||
}
|
||||
background: true,
|
||||
},
|
||||
},
|
||||
// Index for skip reason filtering
|
||||
{
|
||||
|
|
@ -59,16 +70,16 @@ export class TeHandler extends BaseHandler<DataIngestionServices> {
|
|||
options: {
|
||||
name: 'skip_reason_idx',
|
||||
sparse: true,
|
||||
background: true
|
||||
}
|
||||
background: true,
|
||||
},
|
||||
},
|
||||
// Compound index for efficient batch queries
|
||||
{
|
||||
indexSpec: { lastCrawled: 1, skipReason: 1 },
|
||||
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
|
||||
|
|
|
|||
|
|
@ -1,16 +1,19 @@
|
|||
import type { TradingViewHandler } from '../tradingview.handler';
|
||||
import { TradingViewExchange } from '../shared/types';
|
||||
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> {
|
||||
export async function fetchExchanges(
|
||||
handler: TradingViewHandler
|
||||
): Promise<TradingViewExchange[] | null> {
|
||||
const { logger, mongodb } = handler;
|
||||
|
||||
if (!mongodb?.db) {
|
||||
if (!mongodb) {
|
||||
logger.error('MongoDB not available');
|
||||
return null;
|
||||
}
|
||||
|
||||
const db = mongodb.db;
|
||||
const db = mongodb.getDatabase();
|
||||
|
||||
try {
|
||||
// 1. Fetch the HTML page
|
||||
|
|
@ -23,7 +26,7 @@ export async function fetchExchanges(handler: TradingViewHandler): Promise<Tradi
|
|||
logger.debug('Response status:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
url: response.url
|
||||
url: response.url,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -54,36 +57,49 @@ export async function fetchExchanges(handler: TradingViewHandler): Promise<Tradi
|
|||
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>/);
|
||||
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 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());
|
||||
dataTypes.push(at(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],
|
||||
exchange: at(descriptionMatch, 1)
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '_')
|
||||
.replace(/[()]/g, ''),
|
||||
name: at(exchangeNameMatch, 1),
|
||||
description: at(descriptionMatch, 1),
|
||||
dataType: dataTypes,
|
||||
countryCode: countryFlagMatch[1].toUpperCase(),
|
||||
countryCode: at(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();
|
||||
exchange.countryName = at(countryNameMatch, 1).trim();
|
||||
} else if (exchangeMatch) {
|
||||
// Use alt text to extract country name
|
||||
const parts = exchangeMatch[1].split(' ');
|
||||
const parts = at(exchangeMatch, 1).split(' ');
|
||||
if (parts.length > 1) {
|
||||
exchange.countryName = parts[0];
|
||||
exchange.countryName = at(parts, 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export interface TradingViewRawExchange {
|
|||
country: string;
|
||||
country_name: string;
|
||||
popularity_rank?: number;
|
||||
[key: string]: any; // Other fields we don't need
|
||||
[key: string]: unknown; // Other fields we don't need
|
||||
}
|
||||
|
||||
export interface ExchangeGroup {
|
||||
|
|
@ -29,7 +29,7 @@ export interface ExchangeGroup {
|
|||
|
||||
export interface TradingViewData {
|
||||
locale: string;
|
||||
user: any;
|
||||
user: unknown;
|
||||
is_authenticated: boolean;
|
||||
exchanges: ExchangeGroup[];
|
||||
currency: string;
|
||||
|
|
|
|||
|
|
@ -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 } from './actions';
|
||||
|
||||
@Disabled()
|
||||
@Handler('tradingview')
|
||||
export class TradingViewHandler extends BaseHandler {
|
||||
constructor(services: any) {
|
||||
super(services);
|
||||
constructor(services: IServiceContainer) {
|
||||
super(resolveIngestionServices(services, 'tradingview'));
|
||||
}
|
||||
|
||||
@Operation('fetch-exchanges')
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import type { Document } from 'mongodb';
|
||||
/**
|
||||
* Base class for operation providers
|
||||
*/
|
||||
|
||||
import type { Logger, MongoDBClient } from '@stock-bot/services';
|
||||
import type {
|
||||
OperationComponentOptions,
|
||||
OperationConfig,
|
||||
OperationUpdate,
|
||||
ProviderConfig,
|
||||
OperationComponentOptions
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
|
|
@ -78,7 +79,7 @@ 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];
|
||||
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -166,8 +167,8 @@ export abstract class BaseOperationProvider {
|
|||
operations: operations.map(op => ({
|
||||
name: op.name,
|
||||
type: op.type,
|
||||
defaultStaleHours: op.defaultStaleHours
|
||||
}))
|
||||
defaultStaleHours: op.defaultStaleHours,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
/**
|
||||
|
|
@ -56,10 +58,7 @@ 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,14 +238,15 @@ 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)
|
||||
const firstOpStats =
|
||||
operations.length > 0
|
||||
? await tracker.getOperationStats(at(operations, 0).name)
|
||||
: { totalSymbols: 0, processedSymbols: 0 };
|
||||
|
||||
// Sum processed symbols across all operations
|
||||
|
|
@ -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,8 +285,7 @@ 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 }
|
||||
}, {
|
||||
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
|
||||
}
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -68,18 +67,18 @@ export class OperationTracker {
|
|||
// Index for finding stale symbols
|
||||
{
|
||||
[`operations.${operation.name}.lastSuccessAt`]: 1,
|
||||
[symbolField]: 1
|
||||
[symbolField]: 1,
|
||||
},
|
||||
// Index for finding by last record date
|
||||
{
|
||||
[`operations.${operation.name}.lastRecordDate`]: 1,
|
||||
[symbolField]: 1
|
||||
[symbolField]: 1,
|
||||
},
|
||||
// Index for operation status
|
||||
{
|
||||
[`operations.${operation.name}.status`]: 1,
|
||||
[symbolField]: 1
|
||||
}
|
||||
[symbolField]: 1,
|
||||
},
|
||||
];
|
||||
|
||||
// Add crawl-specific indexes for crawl operations
|
||||
|
|
@ -87,15 +86,15 @@ export class OperationTracker {
|
|||
indexes.push(
|
||||
{
|
||||
[`operations.${operation.name}.finished`]: 1,
|
||||
[symbolField]: 1
|
||||
[symbolField]: 1,
|
||||
},
|
||||
{
|
||||
[`operations.${operation.name}.newestDateReached`]: 1,
|
||||
[symbolField]: 1
|
||||
[symbolField]: 1,
|
||||
},
|
||||
{
|
||||
[`operations.${operation.name}.oldestDateReached`]: 1,
|
||||
[symbolField]: 1
|
||||
[symbolField]: 1,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -106,21 +105,27 @@ export class OperationTracker {
|
|||
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;
|
||||
|
|
@ -133,12 +138,12 @@ export class OperationTracker {
|
|||
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;
|
||||
}
|
||||
|
|
@ -160,12 +165,12 @@ export class OperationTracker {
|
|||
// 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();
|
||||
|
||||
|
|
@ -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,7 +357,14 @@ 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,
|
||||
|
|
@ -358,24 +372,26 @@ export class OperationTracker {
|
|||
activeOnly = true,
|
||||
symbolFilter,
|
||||
exchanges,
|
||||
delisted
|
||||
delisted,
|
||||
} = options;
|
||||
|
||||
this.provider.validateOperation(operationName);
|
||||
|
||||
const cutoffDate = options.notRunSince || (() => {
|
||||
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) {
|
||||
|
|
@ -404,14 +420,14 @@ export class OperationTracker {
|
|||
const symbols = await this.mongodb.find(collectionName, filter, {
|
||||
limit,
|
||||
projection: {}, // Return all fields
|
||||
sort: { [`operations.${operationName}.lastSuccessAt`]: 1 }
|
||||
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,9 +528,9 @@ 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) {
|
||||
|
|
@ -523,7 +539,7 @@ export class OperationTracker {
|
|||
yesterday.setHours(0, 0, 0, 0);
|
||||
|
||||
orConditions.push({
|
||||
[`operations.${operationName}.newestDateReached`]: { $lt: yesterday }
|
||||
[`operations.${operationName}.newestDateReached`]: { $lt: yesterday },
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -537,11 +553,11 @@ 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 => {
|
||||
|
|
@ -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 } };
|
||||
});
|
||||
}
|
||||
|
|
@ -585,11 +601,15 @@ export class OperationTracker {
|
|||
): 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;
|
||||
|
|
@ -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],
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -669,45 +689,38 @@ export class OperationTracker {
|
|||
|
||||
const collection = this.mongodb.collection(collectionName);
|
||||
|
||||
const [
|
||||
total,
|
||||
processed,
|
||||
successful,
|
||||
failed,
|
||||
staleStats,
|
||||
crawlStats,
|
||||
recordStats
|
||||
] = await Promise.all([
|
||||
const [total, processed, successful, failed, staleStats, crawlStats, recordStats] =
|
||||
await Promise.all([
|
||||
// Total symbols
|
||||
collection.countDocuments({}),
|
||||
|
||||
// Processed symbols
|
||||
collection.countDocuments({
|
||||
[`operations.${operationName}`]: { $exists: true }
|
||||
[`operations.${operationName}`]: { $exists: true },
|
||||
}),
|
||||
|
||||
// Successful symbols
|
||||
collection.countDocuments({
|
||||
[`operations.${operationName}.status`]: 'success'
|
||||
[`operations.${operationName}.status`]: 'success',
|
||||
}),
|
||||
|
||||
// Failed symbols
|
||||
collection.countDocuments({
|
||||
[`operations.${operationName}.status`]: 'failure'
|
||||
[`operations.${operationName}.status`]: 'failure',
|
||||
}),
|
||||
|
||||
// Stale symbols
|
||||
this.countStaleSymbols(operationName, operation.defaultStaleHours || 24),
|
||||
|
||||
// Crawl stats (if applicable)
|
||||
(operation.type === 'crawl' || operation.type === 'intraday_crawl')
|
||||
operation.type === 'crawl' || operation.type === 'intraday_crawl'
|
||||
? collection.countDocuments({
|
||||
[`operations.${operationName}.finished`]: true
|
||||
[`operations.${operationName}.finished`]: true,
|
||||
})
|
||||
: Promise.resolve(undefined),
|
||||
|
||||
// Average records
|
||||
this.calculateAverageRecords(operationName)
|
||||
this.calculateAverageRecords(operationName),
|
||||
]);
|
||||
|
||||
const result: OperationStats = {
|
||||
|
|
@ -715,7 +728,7 @@ export class OperationTracker {
|
|||
processedSymbols: processed,
|
||||
staleSymbols: staleStats,
|
||||
successfulSymbols: successful,
|
||||
failedSymbols: failed
|
||||
failedSymbols: failed,
|
||||
};
|
||||
|
||||
if (crawlStats !== undefined) {
|
||||
|
|
@ -742,8 +755,8 @@ export class OperationTracker {
|
|||
return collection.countDocuments({
|
||||
$or: [
|
||||
{ [`operations.${operationName}.lastSuccessAt`]: { $lt: staleDate } },
|
||||
{ [`operations.${operationName}`]: { $exists: false } }
|
||||
]
|
||||
{ [`operations.${operationName}`]: { $exists: false } },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -754,22 +767,24 @@ export class OperationTracker {
|
|||
const { collectionName } = this.provider.getProviderConfig();
|
||||
const collection = this.mongodb.collection(collectionName);
|
||||
|
||||
const aggregation = await collection.aggregate([
|
||||
const aggregation = await collection
|
||||
.aggregate([
|
||||
{
|
||||
$match: {
|
||||
[`operations.${operationName}.recordCount`]: { $exists: true }
|
||||
}
|
||||
[`operations.${operationName}.recordCount`]: { $exists: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
avgRecords: { $avg: `$operations.${operationName}.recordCount` }
|
||||
}
|
||||
}
|
||||
]).toArray();
|
||||
avgRecords: { $avg: `$operations.${operationName}.recordCount` },
|
||||
},
|
||||
},
|
||||
])
|
||||
.toArray();
|
||||
|
||||
if (aggregation.length > 0 && aggregation[0].avgRecords) {
|
||||
return Math.round(aggregation[0].avgRecords);
|
||||
if (aggregation.length > 0 && at(aggregation, 0).avgRecords) {
|
||||
return Math.round(at(aggregation, 0).avgRecords);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -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,7 +41,7 @@ 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 */
|
||||
|
|
@ -89,7 +89,7 @@ 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 */
|
||||
|
|
@ -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>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
#!/usr/bin/env bun
|
||||
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('test-advanced-rate-limit');
|
||||
|
|
@ -23,8 +22,8 @@ async function testAdvancedRateLimits() {
|
|||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'],
|
||||
burstSize: 30
|
||||
})
|
||||
burstSize: 30,
|
||||
}),
|
||||
});
|
||||
|
||||
const burstResult = await burstResponse.json();
|
||||
|
|
@ -43,7 +42,7 @@ async function testAdvancedRateLimits() {
|
|||
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 })
|
||||
body: JSON.stringify({ test: true, index: i }),
|
||||
});
|
||||
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
|
@ -54,7 +53,7 @@ async function testAdvancedRateLimits() {
|
|||
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ test: true, index: i })
|
||||
body: JSON.stringify({ test: true, index: i }),
|
||||
});
|
||||
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
|
@ -65,7 +64,7 @@ async function testAdvancedRateLimits() {
|
|||
const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ test: true, index: i })
|
||||
body: JSON.stringify({ test: true, index: i }),
|
||||
});
|
||||
logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
|
@ -82,7 +81,7 @@ async function checkService() {
|
|||
throw new Error('Service not healthy');
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
logger.error('Data ingestion service not running. Start it with: bun run dev');
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
* Test script to verify intraday crawl data flow
|
||||
*/
|
||||
|
||||
import { OperationTracker, OperationRegistry } from '../src/shared/operation-manager';
|
||||
import { OperationRegistry, OperationTracker } from '../src/shared/operation-manager';
|
||||
import type { DataIngestionServices } from '../src/types';
|
||||
|
||||
async function testIntradayDataFlow() {
|
||||
|
|
@ -16,7 +16,8 @@ async function testIntradayDataFlow() {
|
|||
toArray: async () => {
|
||||
console.log(`Mock: Query collection ${name}`);
|
||||
if (name === 'qmSymbols') {
|
||||
return [{
|
||||
return [
|
||||
{
|
||||
symbol: 'X',
|
||||
symbolId: 123456,
|
||||
qmSearchCode: 'X:NYSE',
|
||||
|
|
@ -31,20 +32,22 @@ async function testIntradayDataFlow() {
|
|||
oldestDateReached: new Date('2023-01-01'),
|
||||
newestDateReached: new Date('2024-01-01'),
|
||||
lastProcessedDate: new Date('2023-06-15'),
|
||||
totalDaysProcessed: 180
|
||||
}
|
||||
}
|
||||
}
|
||||
}];
|
||||
totalDaysProcessed: 180,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
},
|
||||
}),
|
||||
createIndex: async () => ({ ok: 1 })
|
||||
createIndex: async () => ({ ok: 1 }),
|
||||
}),
|
||||
find: async (collection: string, filter: any, options?: any) => {
|
||||
console.log(`Mock: Direct find on ${collection}`, { filter, options });
|
||||
return [{
|
||||
return [
|
||||
{
|
||||
symbol: 'X',
|
||||
qmSearchCode: 'X:NYSE',
|
||||
exchange: 'NYSE',
|
||||
|
|
@ -53,42 +56,46 @@ async function testIntradayDataFlow() {
|
|||
crawlState: {
|
||||
finished: false,
|
||||
oldestDateReached: new Date('2023-01-01'),
|
||||
newestDateReached: new Date('2024-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)),
|
||||
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 || '')
|
||||
}
|
||||
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
|
||||
},
|
||||
} as DataIngestionServices;
|
||||
|
||||
// Create registry and provider
|
||||
const registry = new OperationRegistry(mockServices as any);
|
||||
const _registry = new OperationRegistry(mockServices as any);
|
||||
|
||||
// Mock provider
|
||||
const mockProvider = {
|
||||
getProviderConfig: () => ({
|
||||
name: 'qm',
|
||||
collectionName: 'qmSymbols',
|
||||
symbolField: 'qmSearchCode'
|
||||
symbolField: 'qmSearchCode',
|
||||
}),
|
||||
getOperations: () => [{
|
||||
getOperations: () => [
|
||||
{
|
||||
name: 'intraday_bars',
|
||||
type: 'intraday_crawl' as const,
|
||||
defaultStaleHours: 1
|
||||
}],
|
||||
defaultStaleHours: 1,
|
||||
},
|
||||
],
|
||||
validateOperation: () => true,
|
||||
getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }),
|
||||
getDefaultStaleHours: () => 1,
|
||||
initialize: async () => {},
|
||||
beforeOperationUpdate: async () => {},
|
||||
afterOperationUpdate: async () => {}
|
||||
afterOperationUpdate: async () => {},
|
||||
};
|
||||
|
||||
const tracker = new OperationTracker(mockServices as any, mockProvider as any);
|
||||
|
|
@ -100,7 +107,7 @@ async function testIntradayDataFlow() {
|
|||
limit: 10,
|
||||
targetOldestDate: new Date('2020-01-01'),
|
||||
includeNewDataGaps: true,
|
||||
symbolFilter: { symbol: 'X' }
|
||||
symbolFilter: { symbol: 'X' },
|
||||
});
|
||||
|
||||
console.log(`\nFound ${symbols.length} symbols:`);
|
||||
|
|
@ -110,7 +117,7 @@ async function testIntradayDataFlow() {
|
|||
qmSearchCode: sym.qmSearchCode,
|
||||
exchange: sym.exchange,
|
||||
gaps: sym.gaps,
|
||||
crawlState: sym.operationStatus?.crawlState
|
||||
crawlState: sym.operationStatus?.crawlState,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -124,7 +131,7 @@ async function testIntradayDataFlow() {
|
|||
hasGaps: !!testSymbol.gaps,
|
||||
gaps: testSymbol.gaps,
|
||||
hasOperationStatus: !!testSymbol.operationStatus,
|
||||
crawlState: testSymbol.operationStatus?.crawlState
|
||||
crawlState: testSymbol.operationStatus?.crawlState,
|
||||
});
|
||||
|
||||
// Simulate mapping
|
||||
|
|
@ -134,7 +141,7 @@ async function testIntradayDataFlow() {
|
|||
exchange: 'NYSE',
|
||||
qmSearchCode: 'X:NYSE',
|
||||
gaps: testSymbol.gaps,
|
||||
operationStatus: testSymbol.operationStatus
|
||||
operationStatus: testSymbol.operationStatus,
|
||||
};
|
||||
|
||||
console.log('\nAfter mapping:');
|
||||
|
|
@ -145,7 +152,7 @@ async function testIntradayDataFlow() {
|
|||
hasGaps: !!mapped.gaps,
|
||||
gaps: mapped.gaps,
|
||||
hasOperationStatus: !!mapped.operationStatus,
|
||||
crawlState: mapped.operationStatus?.crawlState
|
||||
crawlState: mapped.operationStatus?.crawlState,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,14 +14,14 @@ async function getStaleSymbolsOnlyX(
|
|||
// Method 1: Add symbolFilter to options
|
||||
const modifiedOptions = {
|
||||
...options,
|
||||
symbolFilter: { symbol: 'X' }
|
||||
symbolFilter: { symbol: 'X' },
|
||||
};
|
||||
|
||||
return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions);
|
||||
}
|
||||
|
||||
// Example 2: Modified sophisticated backtest function for symbol X only
|
||||
async function runSophisticatedBacktestOnlyX(orchestrator: any) {
|
||||
async function _runSophisticatedBacktestOnlyX(orchestrator: any) {
|
||||
const symbols = ['X']; // Only test symbol X
|
||||
|
||||
const backtestConfig = {
|
||||
|
|
@ -36,11 +36,11 @@ async function runSophisticatedBacktestOnlyX(orchestrator: any) {
|
|||
}
|
||||
|
||||
// Example 3: Modified schedule function to only process symbol X
|
||||
async function scheduleOperationsOnlyX(handler: any) {
|
||||
async function _scheduleOperationsOnlyX(handler: any) {
|
||||
// Get all symbols that need updates, then filter for X
|
||||
const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', {
|
||||
minHoursSinceRun: 24,
|
||||
limit: 1000
|
||||
limit: 1000,
|
||||
});
|
||||
|
||||
// Filter to only include symbol X
|
||||
|
|
@ -48,21 +48,21 @@ async function scheduleOperationsOnlyX(handler: any) {
|
|||
|
||||
if (symbolXOnly.length > 0) {
|
||||
const symbolData = await handler.mongodb.find('qmSymbols', {
|
||||
qmSearchCode: symbolXOnly[0]
|
||||
qmSearchCode: symbolXOnly[0],
|
||||
});
|
||||
|
||||
if (symbolData.length > 0) {
|
||||
await handler.scheduleOperation('update-prices', {
|
||||
symbol: symbolData[0].symbol,
|
||||
symbolId: symbolData[0].symbolId,
|
||||
qmSearchCode: symbolData[0].qmSearchCode
|
||||
qmSearchCode: symbolData[0].qmSearchCode,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Example 4: Modified intraday crawl for symbol X only
|
||||
async function crawlIntradayOnlyX(handler: any) {
|
||||
async function _crawlIntradayOnlyX(handler: any) {
|
||||
// Direct approach - just process symbol X
|
||||
const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' });
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ async function crawlIntradayOnlyX(handler: any) {
|
|||
symbolId: symbolX.symbolId,
|
||||
qmSearchCode: symbolX.qmSearchCode,
|
||||
mode: 'full',
|
||||
targetOldestDate: new Date('2020-01-01')
|
||||
targetOldestDate: new Date('2020-01-01'),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -111,13 +111,13 @@ async function demonstrateUsage() {
|
|||
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
|
||||
minHoursSinceRun: 24,
|
||||
});
|
||||
console.log('Results:', xOnlySymbols);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
* Test script specifically for symbol X operations
|
||||
*/
|
||||
|
||||
import { QMHandler } from '../src/handlers/qm/qm.handler';
|
||||
import '../src/handlers/qm/qm.handler';
|
||||
import { OperationTracker } from '../src/shared/operation-manager';
|
||||
import type { DataIngestionServices } from '../src/types';
|
||||
|
||||
|
|
@ -18,44 +18,48 @@ async function testSymbolXOperations() {
|
|||
toArray: async () => {
|
||||
console.log(`Querying collection: ${name}`);
|
||||
if (name === 'qmSymbols') {
|
||||
return [{
|
||||
return [
|
||||
{
|
||||
symbol: 'X',
|
||||
symbolId: 123456,
|
||||
qmSearchCode: 'X:NYSE',
|
||||
exchange: 'NYSE',
|
||||
name: 'United States Steel Corporation'
|
||||
}];
|
||||
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) => {
|
||||
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 [{
|
||||
return [
|
||||
{
|
||||
symbol: 'X',
|
||||
symbolId: 123456,
|
||||
qmSearchCode: 'X:NYSE'
|
||||
}];
|
||||
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 || '')
|
||||
}
|
||||
debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''),
|
||||
},
|
||||
} as DataIngestionServices;
|
||||
|
||||
// Test 1: Check stale operations for symbol X
|
||||
|
|
@ -75,7 +79,7 @@ async function testSymbolXOperations() {
|
|||
'events_update',
|
||||
'filings_update',
|
||||
'insiders_update',
|
||||
'news_update'
|
||||
'news_update',
|
||||
];
|
||||
|
||||
for (const operation of operations) {
|
||||
|
|
@ -84,7 +88,7 @@ async function testSymbolXOperations() {
|
|||
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
|
||||
symbolFilter: { symbol: 'X' }, // Only get symbol X
|
||||
});
|
||||
|
||||
console.log(`Found ${staleSymbols.length} stale symbols:`, staleSymbols);
|
||||
|
|
@ -100,7 +104,7 @@ async function testSymbolXOperations() {
|
|||
try {
|
||||
const symbolsForCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', {
|
||||
limit: 10,
|
||||
symbolFilter: { symbol: 'X' }
|
||||
symbolFilter: { symbol: 'X' },
|
||||
});
|
||||
|
||||
console.log(`Found ${symbolsForCrawl.length} symbols for intraday crawl`);
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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...');
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
export interface JobPayload {
|
||||
provider?: string;
|
||||
clearFirst?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,14 +1,10 @@
|
|||
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 std::sync::Arc;
|
||||
use parking_lot::Mutex;
|
||||
use crate::backtest::{
|
||||
BacktestEngine as RustBacktestEngine,
|
||||
BacktestConfig,
|
||||
Strategy, Signal,
|
||||
};
|
||||
use crate::{TradingMode, MarketUpdate};
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct BacktestEngine {
|
||||
|
|
@ -49,31 +45,14 @@ impl BacktestEngine {
|
|||
#[napi]
|
||||
pub fn add_typescript_strategy(
|
||||
&mut self,
|
||||
name: String,
|
||||
id: String,
|
||||
parameters: napi::JsObject,
|
||||
_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(())
|
||||
Err(Error::from_reason(
|
||||
"TypeScript strategy callbacks are not supported by the native engine",
|
||||
))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
|
|
@ -84,16 +63,21 @@ impl BacktestEngine {
|
|||
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")
|
||||
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")
|
||||
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,
|
||||
|
|
@ -102,27 +86,35 @@ impl BacktestEngine {
|
|||
)));
|
||||
}
|
||||
"mean_reversion" => {
|
||||
let lookback_period: usize = parameters.get_named_property::<f64>("lookbackPeriod")
|
||||
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")
|
||||
let entry_threshold: f64 = parameters
|
||||
.get_named_property::<f64>("entryThreshold")
|
||||
.unwrap_or(2.0);
|
||||
let position_size: f64 = parameters.get_named_property::<f64>("positionSize")
|
||||
let position_size: f64 = parameters
|
||||
.get_named_property::<f64>("positionSize")
|
||||
.unwrap_or(100.0);
|
||||
|
||||
engine.add_strategy(Box::new(crate::strategies::MeanReversionFixedStrategy::new(
|
||||
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")
|
||||
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")
|
||||
let momentum_threshold: f64 = parameters
|
||||
.get_named_property::<f64>("momentumThreshold")
|
||||
.unwrap_or(5.0);
|
||||
let position_size: f64 = parameters.get_named_property::<f64>("positionSize")
|
||||
let position_size: f64 = parameters
|
||||
.get_named_property::<f64>("positionSize")
|
||||
.unwrap_or(100.0);
|
||||
|
||||
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
|
||||
|
|
@ -136,11 +128,14 @@ impl BacktestEngine {
|
|||
"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")
|
||||
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")
|
||||
let entry_threshold: f64 = parameters
|
||||
.get_named_property::<f64>("entryThreshold")
|
||||
.unwrap_or(2.0);
|
||||
let position_size: f64 = parameters.get_named_property::<f64>("positionSize")
|
||||
let position_size: f64 = parameters
|
||||
.get_named_property::<f64>("positionSize")
|
||||
.unwrap_or(100.0);
|
||||
|
||||
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
|
||||
|
|
@ -154,10 +149,12 @@ impl BacktestEngine {
|
|||
)));
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::from_reason(format!("Unknown strategy type: {}", strategy_type)));
|
||||
return Err(Error::from_reason(format!(
|
||||
"Unknown strategy type: {}",
|
||||
strategy_type
|
||||
)));
|
||||
}
|
||||
}
|
||||
eprintln!("Native strategy '{}' added successfully", name);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
@ -165,67 +162,53 @@ impl BacktestEngine {
|
|||
|
||||
#[napi]
|
||||
pub fn run(&mut self) -> Result<String> {
|
||||
eprintln!("=== BACKTEST RUN START ===");
|
||||
let mut engine = self.inner.lock().take()
|
||||
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 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());
|
||||
}
|
||||
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()))
|
||||
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()
|
||||
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");
|
||||
if let Some(historical_source) = data_source
|
||||
.as_any_mut()
|
||||
.downcast_mut::<crate::core::market_data_sources::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")?;
|
||||
|
|
@ -269,21 +252,9 @@ fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
|
|||
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)
|
||||
|
|
@ -304,7 +275,6 @@ struct SimpleSMAStrategy {
|
|||
|
||||
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,
|
||||
|
|
@ -318,15 +288,6 @@ impl SimpleSMAStrategy {
|
|||
|
||||
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
|
||||
|
|
@ -335,16 +296,12 @@ impl Strategy for SimpleSMAStrategy {
|
|||
let price = bar.close;
|
||||
|
||||
// Update price history
|
||||
let history = self.price_history.entry(symbol.clone()).or_insert_with(Vec::new);
|
||||
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);
|
||||
|
|
@ -352,41 +309,33 @@ impl Strategy for SimpleSMAStrategy {
|
|||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
// 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 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 {
|
||||
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,
|
||||
|
|
@ -395,12 +344,12 @@ impl Strategy for SimpleSMAStrategy {
|
|||
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 {
|
||||
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,
|
||||
|
|
@ -409,31 +358,24 @@ impl Strategy for SimpleSMAStrategy {
|
|||
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);
|
||||
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 };
|
||||
|
||||
eprintln!(" Position change: {} -> {}", current_pos, new_pos);
|
||||
let new_pos = if side == "buy" {
|
||||
current_pos + quantity
|
||||
} else {
|
||||
current_pos - quantity
|
||||
};
|
||||
|
||||
if new_pos.abs() < 0.0001 {
|
||||
self.positions.remove(symbol);
|
||||
eprintln!(" Position closed");
|
||||
} else {
|
||||
self.positions.insert(symbol.to_string(), new_pos);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use super::{Indicator, IncrementalIndicator, IndicatorResult, IndicatorError, PriceData};
|
||||
use super::ema::EMA;
|
||||
use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData};
|
||||
|
||||
/// Moving Average Convergence Divergence (MACD) Indicator
|
||||
///
|
||||
|
|
@ -17,16 +17,20 @@ pub struct MACD {
|
|||
}
|
||||
|
||||
impl MACD {
|
||||
pub fn new(fast_period: usize, slow_period: usize, signal_period: usize) -> Result<Self, IndicatorError> {
|
||||
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()
|
||||
"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()
|
||||
"Fast period must be less than slow period".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
|
|
@ -51,11 +55,11 @@ impl MACD {
|
|||
values: &[f64],
|
||||
fast_period: usize,
|
||||
slow_period: usize,
|
||||
signal_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()
|
||||
"Fast period must be less than slow period".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
|
|
@ -73,9 +77,8 @@ impl MACD {
|
|||
// 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]);
|
||||
// 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)
|
||||
|
|
@ -105,7 +108,7 @@ impl Indicator for MACD {
|
|||
values,
|
||||
self.fast_period,
|
||||
self.slow_period,
|
||||
self.signal_period
|
||||
self.signal_period,
|
||||
)?;
|
||||
|
||||
Ok(IndicatorResult::MACD {
|
||||
|
|
@ -155,7 +158,7 @@ impl IncrementalIndicator for MACD {
|
|||
if let (Some(fast), Some(slow), Some(signal)) = (
|
||||
self.fast_ema.current(),
|
||||
self.slow_ema.current(),
|
||||
self.signal_ema.current()
|
||||
self.signal_ema.current(),
|
||||
) {
|
||||
let macd = fast - slow;
|
||||
Some(macd - signal)
|
||||
|
|
@ -178,7 +181,7 @@ impl MACD {
|
|||
if let (Some(fast), Some(slow), Some(signal)) = (
|
||||
self.fast_ema.current(),
|
||||
self.slow_ema.current(),
|
||||
self.signal_ema.current()
|
||||
self.signal_ema.current(),
|
||||
) {
|
||||
let macd = fast - slow;
|
||||
Some(MACDValues {
|
||||
|
|
@ -199,10 +202,9 @@ mod tests {
|
|||
#[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
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('AdvancedRiskExample');
|
||||
const _logger = getLogger('AdvancedRiskExample');
|
||||
|
||||
// Example 1: Orderbook Analytics
|
||||
async function orderbookAnalyticsExample() {
|
||||
|
|
@ -18,12 +18,12 @@ async function orderbookAnalyticsExample() {
|
|||
// 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.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);
|
||||
const _snapshot = JSON.parse(snapshotJson);
|
||||
|
||||
// Analyze orderbook
|
||||
const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson);
|
||||
|
|
@ -76,7 +76,7 @@ async function portfolioRiskExample() {
|
|||
{ symbol: 'GOOGL', quantity: 50, avgPrice: 140 },
|
||||
{ symbol: 'MSFT', quantity: 75, avgPrice: 380 },
|
||||
{ symbol: 'AMZN', quantity: 40, avgPrice: 170 },
|
||||
{ symbol: 'META', quantity: 60, avgPrice: 480 }
|
||||
{ symbol: 'META', quantity: 60, avgPrice: 480 },
|
||||
];
|
||||
|
||||
// Current prices
|
||||
|
|
@ -85,7 +85,7 @@ async function portfolioRiskExample() {
|
|||
GOOGL: 145,
|
||||
MSFT: 390,
|
||||
AMZN: 175,
|
||||
META: 490
|
||||
META: 490,
|
||||
};
|
||||
|
||||
// Calculate portfolio risk
|
||||
|
|
@ -102,12 +102,18 @@ async function portfolioRiskExample() {
|
|||
|
||||
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(
|
||||
` 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(
|
||||
` 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:');
|
||||
|
|
@ -182,7 +188,7 @@ async function integratedTradingExample() {
|
|||
const engine = new TradingEngine('backtest', {
|
||||
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
|
||||
endTime: Date.now(),
|
||||
speedMultiplier: 1
|
||||
speedMultiplier: 1,
|
||||
});
|
||||
|
||||
const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252);
|
||||
|
|
@ -233,7 +239,7 @@ async function integratedTradingExample() {
|
|||
side: 'buy',
|
||||
quantity: positionSize.shares,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY'
|
||||
timeInForce: 'DAY',
|
||||
});
|
||||
|
||||
const riskResult = JSON.parse(riskCheck);
|
||||
|
|
|
|||
|
|
@ -1,37 +1,15 @@
|
|||
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 { createExampleRuntime } from './example-runtime';
|
||||
|
||||
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
|
||||
};
|
||||
const {
|
||||
container,
|
||||
storageService,
|
||||
marketDataService: _marketDataService,
|
||||
modeManager,
|
||||
strategyManager,
|
||||
} = await createExampleRuntime();
|
||||
|
||||
// Initialize backtest mode with full config
|
||||
await modeManager.initializeMode({
|
||||
|
|
@ -42,14 +20,14 @@ async function debugPositionTracking() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
|
||||
|
||||
// Listen to strategy events for debugging
|
||||
strategyManager.on('order', (orderEvent: any) => {
|
||||
strategyManager.on('order', (orderEvent: unknown) => {
|
||||
console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent);
|
||||
});
|
||||
|
||||
|
|
@ -65,7 +43,7 @@ async function debugPositionTracking() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('Starting position tracking debug...\n');
|
||||
|
|
@ -90,8 +68,11 @@ async function debugPositionTracking() {
|
|||
console.log(` Quantity: ${trade.quantity}`);
|
||||
console.log(` P&L: $${trade.pnl.toFixed(2)}`);
|
||||
|
||||
if (trade.side === 'buy') buyCount++;
|
||||
else if (trade.side === 'sell') sellCount++;
|
||||
if (trade.side === 'buy') {
|
||||
buyCount++;
|
||||
} else if (trade.side === 'sell') {
|
||||
sellCount++;
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\n=== TRADE SIDE SUMMARY ===`);
|
||||
|
|
@ -103,7 +84,6 @@ async function debugPositionTracking() {
|
|||
result.positions.forEach(pos => {
|
||||
console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Debug failed:', error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
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
|
||||
speedMultiplier: 0,
|
||||
};
|
||||
|
||||
console.log('=== RUST CORE SHORT TRADE DEBUG ===\n');
|
||||
|
|
@ -21,7 +22,7 @@ async function debugRustShortTrades() {
|
|||
side: 'sell',
|
||||
quantity: 100,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY'
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
const sellOrderId = engine.submitOrder(sellOrder);
|
||||
console.log(` Sell order ID: ${sellOrderId}`);
|
||||
|
|
@ -63,7 +64,7 @@ async function debugRustShortTrades() {
|
|||
side: 'buy',
|
||||
quantity: 100,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY'
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
const buyOrderId = engine.submitOrder(buyOrder);
|
||||
console.log(` Buy order ID: ${buyOrderId}`);
|
||||
|
|
@ -96,7 +97,7 @@ async function debugRustShortTrades() {
|
|||
|
||||
if (closedTradesAfterBuy.length > 0) {
|
||||
console.log('\n8. Closed trade details:');
|
||||
closedTradesAfterBuy.forEach((trade: any, i: number) => {
|
||||
closedTradesAfterBuy.forEach((trade: ClosedTrade, i: number) => {
|
||||
console.log(` Trade ${i + 1}:`);
|
||||
console.log(` ID: ${trade.id}`);
|
||||
console.log(` Side: ${trade.side}`);
|
||||
|
|
@ -112,7 +113,7 @@ async function debugRustShortTrades() {
|
|||
// Also check trade history
|
||||
console.log('\n9. Trade history:');
|
||||
const tradeHistory = JSON.parse(engine.getTradeHistory());
|
||||
tradeHistory.forEach((trade: any, i: number) => {
|
||||
tradeHistory.forEach((trade: ClosedTrade, i: number) => {
|
||||
console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`);
|
||||
});
|
||||
|
||||
|
|
|
|||
33
apps/stock/orchestrator/examples/example-runtime.ts
Normal file
33
apps/stock/orchestrator/examples/example-runtime.ts
Normal 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),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,10 +1,5 @@
|
|||
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 { createExampleRuntime } from './example-runtime';
|
||||
|
||||
// Modify the data generation to ensure we get both golden and death crosses
|
||||
function generateMockDataWithBothCrosses() {
|
||||
|
|
@ -37,7 +32,7 @@ function generateMockDataWithBothCrosses() {
|
|||
high: price + Math.random() * 2,
|
||||
low: price - Math.random() * 2,
|
||||
close: price,
|
||||
volume: Math.floor(Math.random() * 10000000) + 5000000
|
||||
volume: Math.floor(Math.random() * 10000000) + 5000000,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -46,37 +41,16 @@ function generateMockDataWithBothCrosses() {
|
|||
|
||||
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
|
||||
};
|
||||
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) {
|
||||
const _originalGenerateMockData = marketDataService.generateMockData;
|
||||
marketDataService.generateMockData = function (
|
||||
_symbol: string,
|
||||
_startDate: string,
|
||||
_endDate: string
|
||||
) {
|
||||
console.log('Generating mock data with forced crossovers...');
|
||||
return generateMockDataWithBothCrosses();
|
||||
};
|
||||
|
|
@ -90,7 +64,7 @@ async function forceBothTradeTypes() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -108,7 +82,7 @@ async function forceBothTradeTypes() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('=== TESTING WITH FORCED CROSSOVERS ===\n');
|
||||
|
|
@ -123,7 +97,7 @@ async function forceBothTradeTypes() {
|
|||
let longTrades = 0;
|
||||
let shortTrades = 0;
|
||||
|
||||
result.trades.forEach((trade) => {
|
||||
result.trades.forEach(trade => {
|
||||
if (trade.side === 'buy') {
|
||||
longTrades++;
|
||||
console.log(`\nLONG trade found:`);
|
||||
|
|
@ -148,10 +122,13 @@ async function forceBothTradeTypes() {
|
|||
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');
|
||||
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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
/**
|
||||
* Examples of using the Rust-based Technical Analysis library
|
||||
*/
|
||||
|
||||
import { IncrementalIndicators, SignalGenerator, TechnicalAnalysis } from '../src/indicators/TechnicalAnalysis';
|
||||
import {
|
||||
IncrementalIndicators,
|
||||
SignalGenerator,
|
||||
TechnicalAnalysis,
|
||||
} from '../src/indicators/TechnicalAnalysis';
|
||||
|
||||
// Example 1: Basic indicator calculations
|
||||
async function basicIndicatorExample() {
|
||||
|
|
@ -12,8 +17,8 @@ async function basicIndicatorExample() {
|
|||
|
||||
// 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
|
||||
100, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111, 110, 112, 114, 113, 115, 117, 116, 118,
|
||||
120,
|
||||
];
|
||||
|
||||
// Calculate various indicators
|
||||
|
|
@ -53,8 +58,11 @@ async function streamingIndicatorExample() {
|
|||
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)}`);
|
||||
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)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -67,7 +75,12 @@ async function complexIndicatorExample() {
|
|||
|
||||
// Generate more realistic price data
|
||||
const generatePrices = (count: number) => {
|
||||
const prices = { close: [], high: [], low: [], volume: [] } as any;
|
||||
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
|
||||
close: [],
|
||||
high: [],
|
||||
low: [],
|
||||
volume: [],
|
||||
};
|
||||
let basePrice = 100;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
|
|
@ -97,8 +110,9 @@ async function complexIndicatorExample() {
|
|||
// 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)!);
|
||||
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)}`);
|
||||
|
|
@ -125,7 +139,12 @@ async function signalGenerationExample() {
|
|||
|
||||
// Generate trending market data
|
||||
const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => {
|
||||
const prices = { close: [], high: [], low: [], volume: [] } as any;
|
||||
const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = {
|
||||
close: [],
|
||||
high: [],
|
||||
low: [],
|
||||
volume: [],
|
||||
};
|
||||
let basePrice = 100;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
|
|
@ -150,7 +169,7 @@ async function signalGenerationExample() {
|
|||
const scenarios = [
|
||||
{ name: 'Uptrend', data: generateTrendingPrices(50, 'up') },
|
||||
{ name: 'Downtrend', data: generateTrendingPrices(50, 'down') },
|
||||
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') }
|
||||
{ name: 'Sideways', data: generateTrendingPrices(50, 'sideways') },
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
|
|
@ -158,7 +177,9 @@ async function signalGenerationExample() {
|
|||
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)}`);
|
||||
console.log(
|
||||
`Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,42 +1,15 @@
|
|||
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 { createExampleRuntime } from './example-runtime';
|
||||
|
||||
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
|
||||
};
|
||||
const {
|
||||
container,
|
||||
storageService,
|
||||
marketDataService: _marketDataService,
|
||||
modeManager,
|
||||
strategyManager,
|
||||
} = await createExampleRuntime();
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode({
|
||||
|
|
@ -47,7 +20,7 @@ async function showOrderFlow() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -65,7 +38,7 @@ async function showOrderFlow() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('\n=== ORDER FLOW DEMONSTRATION ===\n');
|
||||
|
|
@ -79,8 +52,12 @@ async function showOrderFlow() {
|
|||
|
||||
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(
|
||||
` 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`);
|
||||
});
|
||||
|
|
@ -89,7 +66,6 @@ async function showOrderFlow() {
|
|||
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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,40 +1,18 @@
|
|||
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';
|
||||
import { BacktestEngine } from '../src/backtest/BacktestEngine';
|
||||
import { createExampleRuntime } from './example-runtime';
|
||||
|
||||
const logger = getLogger('BacktestTest');
|
||||
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
|
||||
};
|
||||
const {
|
||||
container,
|
||||
storageService,
|
||||
marketDataService: _marketDataService,
|
||||
modeManager,
|
||||
strategyManager,
|
||||
} = await createExampleRuntime();
|
||||
|
||||
// Initialize backtest mode with full config
|
||||
await modeManager.initializeMode({
|
||||
|
|
@ -45,7 +23,7 @@ async function runSimpleBacktest() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -63,7 +41,7 @@ async function runSimpleBacktest() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('Starting backtest with configuration:', config);
|
||||
|
|
@ -105,7 +83,6 @@ async function runSimpleBacktest() {
|
|||
});
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Backtest failed:', error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,13 +3,12 @@
|
|||
/**
|
||||
* 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 { 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() {
|
||||
|
|
@ -18,7 +17,7 @@ async function runSophisticatedBacktest() {
|
|||
await storageService.initialize({ mode: 'backtest' });
|
||||
|
||||
const analyticsService = new AnalyticsService({
|
||||
analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003'
|
||||
analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003',
|
||||
});
|
||||
|
||||
const strategyManager = new StrategyManager();
|
||||
|
|
@ -49,24 +48,24 @@ async function runSophisticatedBacktest() {
|
|||
latencyMs: {
|
||||
mean: 1,
|
||||
std: 0.5,
|
||||
tail: 10 // Occasional high latency
|
||||
}
|
||||
tail: 10, // Occasional high latency
|
||||
},
|
||||
},
|
||||
|
||||
// Risk limits
|
||||
riskLimits: {
|
||||
maxPositionSize: 100_000,
|
||||
maxDailyLoss: 50_000,
|
||||
maxDrawdown: 0.20, // 20% max drawdown
|
||||
maxDrawdown: 0.2, // 20% max drawdown
|
||||
maxLeverage: 2.0,
|
||||
maxConcentration: 0.30 // Max 30% in single position
|
||||
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'
|
||||
slippageModel: 'volumeDependent',
|
||||
},
|
||||
|
||||
// Strategies to test
|
||||
|
|
@ -83,8 +82,8 @@ async function runSophisticatedBacktest() {
|
|||
entryZScore: 2.0,
|
||||
exitZScore: 0.5,
|
||||
minVolume: 1_000_000,
|
||||
stopLoss: 0.05 // 5% stop loss
|
||||
}
|
||||
stopLoss: 0.05, // 5% stop loss
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'ml_enhanced_1',
|
||||
|
|
@ -96,10 +95,10 @@ async function runSophisticatedBacktest() {
|
|||
parameters: {
|
||||
modelPath: './models/ml_strategy_v1',
|
||||
updateFrequency: 1440, // Daily retraining
|
||||
minConfidence: 0.6
|
||||
}
|
||||
}
|
||||
]
|
||||
minConfidence: 0.6,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
logger.info('Starting sophisticated backtest...');
|
||||
|
|
@ -119,7 +118,7 @@ async function runSophisticatedBacktest() {
|
|||
backtestId: result.id,
|
||||
returns: result.dailyReturns,
|
||||
trades: result.trades,
|
||||
parameters: extractParameters(config.strategies)
|
||||
parameters: extractParameters(config.strategies),
|
||||
});
|
||||
|
||||
if (validationResult.is_overfit) {
|
||||
|
|
@ -152,7 +151,7 @@ async function runSophisticatedBacktest() {
|
|||
const factorAnalysis = await analyticsService.analyzeFactors({
|
||||
returns: result.dailyReturns,
|
||||
positions: result.finalPositions,
|
||||
marketReturns: await getMarketReturns(config.startDate, config.endDate)
|
||||
marketReturns: await getMarketReturns(config.startDate, config.endDate),
|
||||
});
|
||||
|
||||
logger.info('Factor Attribution:');
|
||||
|
|
@ -163,19 +162,23 @@ async function runSophisticatedBacktest() {
|
|||
// Transaction cost analysis
|
||||
const tcaReport = await analyticsService.analyzeTCA({
|
||||
trades: result.trades,
|
||||
orders: result.orders
|
||||
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`);
|
||||
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)})`);
|
||||
logger.info(
|
||||
` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})`
|
||||
);
|
||||
});
|
||||
|
||||
// Strategy correlation analysis
|
||||
|
|
@ -198,7 +201,6 @@ async function runSophisticatedBacktest() {
|
|||
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 {
|
||||
|
|
@ -208,8 +210,10 @@ async function runSophisticatedBacktest() {
|
|||
|
||||
// Helper functions
|
||||
|
||||
function extractParameters(strategies: any[]): Record<string, any> {
|
||||
const params: Record<string, any> = {};
|
||||
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;
|
||||
|
|
@ -221,16 +225,20 @@ function extractParameters(strategies: any[]): Record<string, any> {
|
|||
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));
|
||||
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 }> {
|
||||
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 }
|
||||
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 }> = {};
|
||||
|
|
@ -239,11 +247,13 @@ function analyzeByPeriod(result: any): Record<string, { return: number; sharpe:
|
|||
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);
|
||||
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
|
||||
sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
|
@ -251,15 +261,18 @@ function analyzeByPeriod(result: any): Record<string, { return: number; sharpe:
|
|||
return analysis;
|
||||
}
|
||||
|
||||
async function calculateStrategyCorrelations(result: any): Promise<Array<{ pair: string; correlation: number }>> {
|
||||
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 }
|
||||
];
|
||||
return [{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }];
|
||||
}
|
||||
|
||||
async function runMonteCarloSimulation(result: any, numSims: number): Promise<{ var95: number; cvar95: number }> {
|
||||
async function runMonteCarloSimulation(
|
||||
result: { dailyReturns: number[] },
|
||||
numSims: number
|
||||
): Promise<{ var95: number; cvar95: number }> {
|
||||
const returns = result.dailyReturns;
|
||||
const simulatedReturns: number[] = [];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,36 +1,15 @@
|
|||
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 { createExampleRuntime } from './example-runtime';
|
||||
|
||||
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
|
||||
};
|
||||
const {
|
||||
container,
|
||||
storageService,
|
||||
marketDataService: _marketDataService,
|
||||
modeManager,
|
||||
strategyManager,
|
||||
} = await createExampleRuntime();
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode({
|
||||
|
|
@ -41,7 +20,7 @@ async function testShortTrades() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -59,7 +38,7 @@ async function testShortTrades() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('Testing short trade recording...\n');
|
||||
|
|
@ -79,8 +58,11 @@ async function testShortTrades() {
|
|||
console.log('\n=== TRADE BREAKDOWN ===');
|
||||
result.trades.forEach((trade, i) => {
|
||||
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
|
||||
if (trade.side === 'buy') longTrades++;
|
||||
else shortTrades++;
|
||||
if (trade.side === 'buy') {
|
||||
longTrades++;
|
||||
} else {
|
||||
shortTrades++;
|
||||
}
|
||||
|
||||
console.log(`Trade ${i + 1} (${tradeType}):`);
|
||||
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
|
||||
|
|
@ -93,7 +75,6 @@ async function testShortTrades() {
|
|||
console.log(`Long trades: ${longTrades}`);
|
||||
console.log(`Short trades: ${shortTrades}`);
|
||||
console.log(`Total trades: ${result.metrics.totalTrades}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Test failed:', error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,80 +1,26 @@
|
|||
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 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: any[] = [];
|
||||
const fillTracker: any[] = [];
|
||||
const orderTracker: (OrderRequest & { count: number })[] = [];
|
||||
const fillTracker: StrategyFill[] = [];
|
||||
|
||||
// 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
|
||||
const { container, storageService, modeManager, strategyManager } = await createExampleRuntime();
|
||||
strategyManager.on('order', (event: { order: OrderRequest }) => {
|
||||
orderTracker.push({ ...event.order, count: ++orderCount });
|
||||
});
|
||||
console.log(`\n🔵 ORDER #${orderCount}:`, orderData.side.toUpperCase(), orderData.symbol);
|
||||
}
|
||||
|
||||
// Track fills
|
||||
if (msg.includes('Order filled')) {
|
||||
strategyManager.on('fill', (fill: StrategyFill) => {
|
||||
fillCount++;
|
||||
const fillData = args[0];
|
||||
fillTracker.push({
|
||||
count: fillCount,
|
||||
orderId: fillData.orderId,
|
||||
symbol: fillData.symbol,
|
||||
side: fillData.side,
|
||||
price: fillData.price,
|
||||
quantity: fillData.quantity
|
||||
fillTracker.push(fill);
|
||||
});
|
||||
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) => {
|
||||
strategyManager.on('signal', (signal: unknown) => {
|
||||
console.log('\n🎯 STRATEGY SIGNAL:', signal);
|
||||
});
|
||||
|
||||
|
|
@ -87,7 +33,7 @@ async function traceShortPositions() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -105,7 +51,7 @@ async function traceShortPositions() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('=== TRACING SHORT POSITION FLOW ===\n');
|
||||
|
|
@ -121,8 +67,11 @@ async function traceShortPositions() {
|
|||
let buyOrders = 0;
|
||||
let sellOrders = 0;
|
||||
orderTracker.forEach(order => {
|
||||
if (order.side === 'buy') buyOrders++;
|
||||
else sellOrders++;
|
||||
if (order.side === 'buy') {
|
||||
buyOrders++;
|
||||
} else {
|
||||
sellOrders++;
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nOrder breakdown:`);
|
||||
|
|
@ -160,8 +109,11 @@ async function traceShortPositions() {
|
|||
|
||||
result.trades.forEach((trade, i) => {
|
||||
const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT';
|
||||
if (trade.side === 'buy') longTrades++;
|
||||
else shortTrades++;
|
||||
if (trade.side === 'buy') {
|
||||
longTrades++;
|
||||
} else {
|
||||
shortTrades++;
|
||||
}
|
||||
|
||||
console.log(`\nTrade ${i + 1} (${tradeType}):`);
|
||||
console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`);
|
||||
|
|
@ -178,7 +130,6 @@ async function traceShortPositions() {
|
|||
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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,36 +1,15 @@
|
|||
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 { createExampleRuntime } from './example-runtime';
|
||||
|
||||
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
|
||||
};
|
||||
const {
|
||||
container,
|
||||
storageService,
|
||||
marketDataService: _marketDataService,
|
||||
modeManager,
|
||||
strategyManager,
|
||||
} = await createExampleRuntime();
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode({
|
||||
|
|
@ -41,7 +20,7 @@ async function verifyBothTradeTypes() {
|
|||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
strategy: 'sma-crossover',
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
|
|
@ -59,7 +38,7 @@ async function verifyBothTradeTypes() {
|
|||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d' as const,
|
||||
speed: 'max' as const
|
||||
speed: 'max' as const,
|
||||
};
|
||||
|
||||
console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n');
|
||||
|
|
@ -109,11 +88,15 @@ async function verifyBothTradeTypes() {
|
|||
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(
|
||||
` - 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(
|
||||
` - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}`
|
||||
);
|
||||
|
||||
console.log(`\nTotal trades: ${result.metrics.totalTrades}`);
|
||||
|
||||
|
|
@ -123,7 +106,6 @@ async function verifyBothTradeTypes() {
|
|||
if (shortTrades === 0) {
|
||||
console.log('\n⚠️ WARNING: No short trades found!');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Test failed:', error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import * as stats from 'simple-statistics';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/utils';
|
||||
|
||||
const logger = getLogger('PerformanceAnalyzer');
|
||||
import * as stats from 'simple-statistics';
|
||||
|
||||
export interface Trade {
|
||||
entryTime: Date;
|
||||
|
|
@ -134,7 +136,10 @@ export class PerformanceAnalyzer {
|
|||
// Risk-adjusted returns
|
||||
const sharpeRatio = this.calculateSharpeRatio(annualizedReturn, volatility);
|
||||
const sortinoRatio = this.calculateSortinoRatio(annualizedReturn, downVolatility);
|
||||
const calmarRatio = drawdownAnalysis.maxDrawdown > 0 ? annualizedReturn / (drawdownAnalysis.maxDrawdown * 100) : 0;
|
||||
const calmarRatio =
|
||||
drawdownAnalysis.maxDrawdown > 0
|
||||
? annualizedReturn / (drawdownAnalysis.maxDrawdown * 100)
|
||||
: 0;
|
||||
const informationRatio = this.calculateInformationRatio();
|
||||
|
||||
// Trade statistics
|
||||
|
|
@ -179,7 +184,7 @@ export class PerformanceAnalyzer {
|
|||
kurtosis,
|
||||
tailRatio,
|
||||
kellyFraction,
|
||||
optimalLeverage
|
||||
optimalLeverage,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -194,17 +199,17 @@ export class PerformanceAnalyzer {
|
|||
maxDrawdownDuration: 0,
|
||||
underwaterCurve: [],
|
||||
drawdownPeriods: [],
|
||||
currentDrawdown: 0
|
||||
currentDrawdown: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let peak = this.equityCurve[0].value;
|
||||
let peak = at(this.equityCurve, 0).value;
|
||||
let maxDrawdown = 0;
|
||||
let currentDrawdownStart: Date | null = null;
|
||||
let drawdownPeriods: DrawdownAnalysis['drawdownPeriods'] = [];
|
||||
const drawdownPeriods: DrawdownAnalysis['drawdownPeriods'] = [];
|
||||
|
||||
for (let i = 0; i < this.equityCurve.length; i++) {
|
||||
const point = this.equityCurve[i];
|
||||
const point = at(this.equityCurve, i);
|
||||
|
||||
if (point.value > peak) {
|
||||
// New peak - end current drawdown if any
|
||||
|
|
@ -214,7 +219,7 @@ export class PerformanceAnalyzer {
|
|||
end: point.date,
|
||||
depth: maxDrawdown,
|
||||
duration: this.daysBetween(currentDrawdownStart, point.date),
|
||||
recovery: i
|
||||
recovery: i,
|
||||
};
|
||||
drawdownPeriods.push(period);
|
||||
currentDrawdownStart = null;
|
||||
|
|
@ -236,7 +241,7 @@ export class PerformanceAnalyzer {
|
|||
}
|
||||
|
||||
// Handle ongoing drawdown
|
||||
const currentDrawdown = drawdowns[drawdowns.length - 1];
|
||||
const currentDrawdown = at(drawdowns, drawdowns.length - 1);
|
||||
|
||||
// Calculate max drawdown duration
|
||||
const maxDrawdownDuration = Math.max(
|
||||
|
|
@ -249,7 +254,7 @@ export class PerformanceAnalyzer {
|
|||
maxDrawdownDuration,
|
||||
currentDrawdown: Math.abs(currentDrawdown),
|
||||
drawdownPeriods,
|
||||
underwaterCurve
|
||||
underwaterCurve,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -260,7 +265,7 @@ export class PerformanceAnalyzer {
|
|||
|
||||
// Calculate beta using linear regression
|
||||
const regression = stats.linearRegression(
|
||||
this.dailyReturns.map((r, i) => [benchmarkReturns[i], r])
|
||||
this.dailyReturns.map((r, i) => [at(benchmarkReturns, i), r])
|
||||
);
|
||||
const beta = regression.m;
|
||||
const alpha = regression.b * 252; // Annualized
|
||||
|
|
@ -273,23 +278,27 @@ export class PerformanceAnalyzer {
|
|||
const treynorRatio = beta !== 0 ? excessReturn / beta : 0;
|
||||
|
||||
// Tracking error
|
||||
const returnDiffs = this.dailyReturns.map((r, i) => r - benchmarkReturns[i]);
|
||||
const returnDiffs = this.dailyReturns.map((r, i) => r - at(benchmarkReturns, i));
|
||||
const trackingError = stats.standardDeviation(returnDiffs) * Math.sqrt(252);
|
||||
|
||||
// Up/down capture
|
||||
const upDays = benchmarkReturns
|
||||
.map((r, i) => r > 0 ? { bench: r, port: this.dailyReturns[i] } : null)
|
||||
.map((r, i) => (r > 0 ? { bench: r, port: this.dailyReturns[i] } : null))
|
||||
.filter(d => d !== null) as Array<{ bench: number; port: number }>;
|
||||
|
||||
const downDays = benchmarkReturns
|
||||
.map((r, i) => r < 0 ? { bench: r, port: this.dailyReturns[i] } : null)
|
||||
.map((r, i) => (r < 0 ? { bench: r, port: this.dailyReturns[i] } : null))
|
||||
.filter(d => d !== null) as Array<{ bench: number; port: number }>;
|
||||
|
||||
const upCapture = upDays.length > 0 ?
|
||||
stats.mean(upDays.map(d => d.port)) / stats.mean(upDays.map(d => d.bench)) : 0;
|
||||
const upCapture =
|
||||
upDays.length > 0
|
||||
? stats.mean(upDays.map(d => d.port)) / stats.mean(upDays.map(d => d.bench))
|
||||
: 0;
|
||||
|
||||
const downCapture = downDays.length > 0 ?
|
||||
stats.mean(downDays.map(d => d.port)) / stats.mean(downDays.map(d => d.bench)) : 0;
|
||||
const downCapture =
|
||||
downDays.length > 0
|
||||
? stats.mean(downDays.map(d => d.port)) / stats.mean(downDays.map(d => d.bench))
|
||||
: 0;
|
||||
|
||||
return {
|
||||
alpha,
|
||||
|
|
@ -298,7 +307,7 @@ export class PerformanceAnalyzer {
|
|||
treynorRatio,
|
||||
trackingError,
|
||||
upCapture,
|
||||
downCapture
|
||||
downCapture,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -309,18 +318,19 @@ export class PerformanceAnalyzer {
|
|||
const dailyEquity = new Map<string, { date: Date; value: number }>();
|
||||
|
||||
for (const point of this.equityCurve) {
|
||||
const dateKey = point.date.toISOString().split('T')[0];
|
||||
const dateKey = at(point.date.toISOString().split('T'), 0);
|
||||
dailyEquity.set(dateKey, point); // This will keep the last value of each day
|
||||
}
|
||||
|
||||
// Convert to sorted array
|
||||
const dailyPoints = Array.from(dailyEquity.values())
|
||||
.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||
const dailyPoints = Array.from(dailyEquity.values()).sort(
|
||||
(a, b) => a.date.getTime() - b.date.getTime()
|
||||
);
|
||||
|
||||
// Calculate returns from daily points
|
||||
for (let i = 1; i < dailyPoints.length; i++) {
|
||||
const prevValue = dailyPoints[i - 1].value;
|
||||
const currValue = dailyPoints[i].value;
|
||||
const prevValue = at(dailyPoints, i - 1).value;
|
||||
const currValue = at(dailyPoints, i).value;
|
||||
if (prevValue > 0) {
|
||||
this.dailyReturns.push((currValue - prevValue) / prevValue);
|
||||
}
|
||||
|
|
@ -328,7 +338,7 @@ export class PerformanceAnalyzer {
|
|||
}
|
||||
|
||||
private calculateTotalReturn(): number {
|
||||
const finalValue = this.equityCurve[this.equityCurve.length - 1].value;
|
||||
const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value;
|
||||
return ((finalValue - this.initialCapital) / this.initialCapital) * 100;
|
||||
}
|
||||
|
||||
|
|
@ -339,26 +349,32 @@ export class PerformanceAnalyzer {
|
|||
}
|
||||
|
||||
private calculateCAGR(): number {
|
||||
const finalValue = this.equityCurve[this.equityCurve.length - 1].value;
|
||||
const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value;
|
||||
const years = this.getYears();
|
||||
return (Math.pow(finalValue / this.initialCapital, 1 / years) - 1) * 100;
|
||||
}
|
||||
|
||||
private calculateVolatility(): number {
|
||||
if (this.dailyReturns.length === 0) return 0;
|
||||
if (this.dailyReturns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Return volatility as a decimal percentage (not multiplied by 100)
|
||||
return stats.standardDeviation(this.dailyReturns) * Math.sqrt(252);
|
||||
}
|
||||
|
||||
private calculateDownsideVolatility(): number {
|
||||
const negativeReturns = this.dailyReturns.filter(r => r < 0);
|
||||
if (negativeReturns.length === 0) return 0;
|
||||
if (negativeReturns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Return volatility as a decimal percentage (not multiplied by 100)
|
||||
return stats.standardDeviation(negativeReturns) * Math.sqrt(252);
|
||||
}
|
||||
|
||||
private calculateVaR(): { var95: number; cvar95: number } {
|
||||
if (this.dailyReturns.length === 0) return { var95: 0, cvar95: 0 };
|
||||
if (this.dailyReturns.length === 0) {
|
||||
return { var95: 0, cvar95: 0 };
|
||||
}
|
||||
|
||||
const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b);
|
||||
const index95 = Math.floor(sortedReturns.length * 0.05);
|
||||
|
|
@ -368,22 +384,34 @@ export class PerformanceAnalyzer {
|
|||
return { var95: 0, cvar95: 0 };
|
||||
}
|
||||
|
||||
const var95 = Math.abs(sortedReturns[index95]) * 100;
|
||||
const var95 = Math.abs(at(sortedReturns, index95)) * 100;
|
||||
const tailReturns = sortedReturns.slice(0, index95);
|
||||
const cvar95 = tailReturns.length > 0 ? Math.abs(stats.mean(tailReturns)) * 100 : 0;
|
||||
|
||||
return { var95, cvar95 };
|
||||
}
|
||||
|
||||
private calculateSharpeRatio(annualReturn: number, volatility: number, riskFree: number = 2): number {
|
||||
if (volatility === 0) return 0;
|
||||
private calculateSharpeRatio(
|
||||
annualReturn: number,
|
||||
volatility: number,
|
||||
riskFree: number = 2
|
||||
): number {
|
||||
if (volatility === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Both annualReturn and volatility should be in percentage form
|
||||
const volatilityPct = volatility * 100;
|
||||
return (annualReturn - riskFree) / volatilityPct;
|
||||
}
|
||||
|
||||
private calculateSortinoRatio(annualReturn: number, downVolatility: number, riskFree: number = 2): number {
|
||||
if (downVolatility === 0) return 0;
|
||||
private calculateSortinoRatio(
|
||||
annualReturn: number,
|
||||
downVolatility: number,
|
||||
riskFree: number = 2
|
||||
): number {
|
||||
if (downVolatility === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Both annualReturn and downVolatility should be in percentage form
|
||||
const downVolatilityPct = downVolatility * 100;
|
||||
return (annualReturn - riskFree) / downVolatilityPct;
|
||||
|
|
@ -394,10 +422,14 @@ export class PerformanceAnalyzer {
|
|||
return 0;
|
||||
}
|
||||
|
||||
const excessReturns = this.dailyReturns.map((r, i) => r - this.benchmarkReturns![i]);
|
||||
const excessReturns = this.dailyReturns.map(
|
||||
(r, i) => r - at(defined(this.benchmarkReturns), i)
|
||||
);
|
||||
const trackingError = stats.standardDeviation(excessReturns);
|
||||
|
||||
if (trackingError === 0) return 0;
|
||||
if (trackingError === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const avgExcessReturn = stats.mean(excessReturns);
|
||||
return (avgExcessReturn * 252) / (trackingError * Math.sqrt(252));
|
||||
|
|
@ -419,7 +451,7 @@ export class PerformanceAnalyzer {
|
|||
maxConsecutiveWins: 0,
|
||||
maxConsecutiveLosses: 0,
|
||||
largestWin: 0,
|
||||
largestLoss: 0
|
||||
largestLoss: 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -429,7 +461,9 @@ export class PerformanceAnalyzer {
|
|||
const losses = validTrades.filter(t => t.pnl < 0);
|
||||
|
||||
// Log trade analysis for debugging
|
||||
logger.debug(`Trade Analysis: Total=${this.trades.length}, Valid=${validTrades.length}, Wins=${wins.length}, Losses=${losses.length}`);
|
||||
logger.debug(
|
||||
`Trade Analysis: Total=${this.trades.length}, Valid=${validTrades.length}, Wins=${wins.length}, Losses=${losses.length}`
|
||||
);
|
||||
|
||||
const totalWins = wins.reduce((sum, t) => sum + t.pnl, 0);
|
||||
const totalLosses = Math.abs(losses.reduce((sum, t) => sum + t.pnl, 0));
|
||||
|
|
@ -439,7 +473,7 @@ export class PerformanceAnalyzer {
|
|||
|
||||
const winRate = validTrades.length > 0 ? (wins.length / validTrades.length) * 100 : 0;
|
||||
const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;
|
||||
const expectancy = (winRate / 100 * avgWin) - ((100 - winRate) / 100 * avgLoss);
|
||||
const expectancy = (winRate / 100) * avgWin - ((100 - winRate) / 100) * avgLoss;
|
||||
const payoffRatio = avgLoss > 0 ? avgWin / avgLoss : 0;
|
||||
|
||||
// Holding period analysis
|
||||
|
|
@ -471,7 +505,7 @@ export class PerformanceAnalyzer {
|
|||
maxConsecutiveWins,
|
||||
maxConsecutiveLosses,
|
||||
largestWin,
|
||||
largestLoss
|
||||
largestLoss,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -495,24 +529,29 @@ export class PerformanceAnalyzer {
|
|||
|
||||
// Kurtosis
|
||||
const kurtSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 4), 0);
|
||||
const kurtosis = (n * (n + 1) / ((n - 1) * (n - 2) * (n - 3))) * kurtSum -
|
||||
const kurtosis =
|
||||
((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * kurtSum -
|
||||
(3 * (n - 1) * (n - 1)) / ((n - 2) * (n - 3));
|
||||
|
||||
return { skewness, kurtosis };
|
||||
}
|
||||
|
||||
private calculateTailRatio(): number {
|
||||
if (this.dailyReturns.length < 20) return 0;
|
||||
if (this.dailyReturns.length < 20) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sorted = [...this.dailyReturns].sort((a, b) => b - a);
|
||||
const percentile95 = sorted[Math.floor(sorted.length * 0.05)];
|
||||
const percentile5 = sorted[Math.floor(sorted.length * 0.95)];
|
||||
const percentile95 = at(sorted, Math.floor(sorted.length * 0.05));
|
||||
const percentile5 = at(sorted, Math.floor(sorted.length * 0.95));
|
||||
|
||||
return Math.abs(percentile5) > 0 ? percentile95 / Math.abs(percentile5) : 0;
|
||||
}
|
||||
|
||||
private calculateKellyCriterion(tradeStats: Partial<PerformanceMetrics>):
|
||||
{ kellyFraction: number; optimalLeverage: number } {
|
||||
private calculateKellyCriterion(tradeStats: Partial<PerformanceMetrics>): {
|
||||
kellyFraction: number;
|
||||
optimalLeverage: number;
|
||||
} {
|
||||
const winRate = (tradeStats.winRate || 0) / 100;
|
||||
const payoffRatio = tradeStats.payoffRatio || 0;
|
||||
|
||||
|
|
@ -536,13 +575,18 @@ export class PerformanceAnalyzer {
|
|||
|
||||
return {
|
||||
kellyFraction: conservativeKelly,
|
||||
optimalLeverage
|
||||
optimalLeverage,
|
||||
};
|
||||
}
|
||||
|
||||
private calculateConsecutiveStats(): { maxConsecutiveWins: number; maxConsecutiveLosses: number } {
|
||||
let maxWins = 0, maxLosses = 0;
|
||||
let currentWins = 0, currentLosses = 0;
|
||||
private calculateConsecutiveStats(): {
|
||||
maxConsecutiveWins: number;
|
||||
maxConsecutiveLosses: number;
|
||||
} {
|
||||
let maxWins = 0,
|
||||
maxLosses = 0;
|
||||
let currentWins = 0,
|
||||
currentLosses = 0;
|
||||
|
||||
for (const trade of this.trades) {
|
||||
if (trade.pnl > 0) {
|
||||
|
|
@ -560,16 +604,20 @@ export class PerformanceAnalyzer {
|
|||
}
|
||||
|
||||
private getYears(): number {
|
||||
if (this.equityCurve.length < 2) return 1;
|
||||
const start = this.equityCurve[0].date;
|
||||
const end = this.equityCurve[this.equityCurve.length - 1].date;
|
||||
if (this.equityCurve.length < 2) {
|
||||
return 1;
|
||||
}
|
||||
const start = at(this.equityCurve, 0).date;
|
||||
const end = at(this.equityCurve, this.equityCurve.length - 1).date;
|
||||
return this.daysBetween(start, end) / 365;
|
||||
}
|
||||
|
||||
private getTradingDays(): number {
|
||||
if (this.equityCurve.length < 2) return 0;
|
||||
const start = this.equityCurve[0].date;
|
||||
const end = this.equityCurve[this.equityCurve.length - 1].date;
|
||||
if (this.equityCurve.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
const start = at(this.equityCurve, 0).date;
|
||||
const end = at(this.equityCurve, this.equityCurve.length - 1).date;
|
||||
return this.daysBetween(start, end) * (252 / 365); // Approximate trading days
|
||||
}
|
||||
|
||||
|
|
@ -610,13 +658,13 @@ export class PerformanceAnalyzer {
|
|||
kurtosis: 0,
|
||||
tailRatio: 0,
|
||||
kellyFraction: 0,
|
||||
optimalLeverage: 1
|
||||
optimalLeverage: 1,
|
||||
};
|
||||
}
|
||||
|
||||
exportReport(): string {
|
||||
const metrics = this.analyze();
|
||||
const drawdowns = this.analyzeDrawdowns();
|
||||
const _drawdowns = this.analyzeDrawdowns();
|
||||
|
||||
return `
|
||||
# Performance Report
|
||||
|
|
|
|||
|
|
@ -1,22 +1,24 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { AnalyticsService } from '../../services/AnalyticsService';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../../types';
|
||||
|
||||
const DateRangeSchema = z.object({
|
||||
startDate: z.string().datetime(),
|
||||
endDate: 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({
|
||||
constraints: z
|
||||
.object({
|
||||
minWeight: z.number().optional(),
|
||||
maxWeight: z.number().optional(),
|
||||
targetReturn: z.number().optional(),
|
||||
maxRisk: z.number().optional()
|
||||
}).optional()
|
||||
maxRisk: z.number().optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
||||
|
|
@ -24,14 +26,14 @@ export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
|||
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
|
||||
|
||||
// Get performance metrics
|
||||
app.get('/performance/:portfolioId', async (c) => {
|
||||
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
|
||||
endDate: query.end_date,
|
||||
});
|
||||
|
||||
const metrics = await analyticsService.getPerformanceMetrics(
|
||||
|
|
@ -43,48 +45,60 @@ export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
|||
return c.json(metrics);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid date range',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get performance metrics',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Portfolio optimization
|
||||
app.post('/optimize', async (c) => {
|
||||
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
|
||||
constraints: request.constraints,
|
||||
});
|
||||
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid optimization request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to optimize portfolio',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Get risk metrics
|
||||
app.get('/risk/:portfolioId', async (c) => {
|
||||
app.get('/risk/:portfolioId', async c => {
|
||||
try {
|
||||
const portfolioId = c.req.param('portfolioId');
|
||||
const metrics = await analyticsService.getRiskMetrics(portfolioId);
|
||||
|
|
@ -92,66 +106,82 @@ export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
|||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get risk metrics',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Market regime detection
|
||||
app.get('/regime', async (c) => {
|
||||
app.get('/regime', async c => {
|
||||
try {
|
||||
const regime = await analyticsService.detectMarketRegime();
|
||||
|
||||
return c.json({
|
||||
regime,
|
||||
timestamp: new Date().toISOString()
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to detect market regime',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Calculate correlation matrix
|
||||
app.post('/correlation', async (c) => {
|
||||
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 { symbols } = z
|
||||
.object({
|
||||
symbols: z.array(z.string()).min(2),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
|
||||
|
||||
return c.json({
|
||||
symbols,
|
||||
matrix
|
||||
matrix,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid correlation request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to calculate correlation',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// ML model prediction
|
||||
app.post('/predict', async (c) => {
|
||||
app.post('/predict', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { modelId, features } = z.object({
|
||||
const { modelId, features } = z
|
||||
.object({
|
||||
modelId: z.string(),
|
||||
features: z.record(z.number())
|
||||
}).parse(body);
|
||||
features: z.record(z.number()),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
const prediction = await analyticsService.predictWithModel(modelId, features);
|
||||
|
||||
|
|
@ -162,16 +192,22 @@ export function createAnalyticsRoutes(container: IServiceContainer): Hono {
|
|||
}
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid prediction request',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
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 c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to make prediction',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { BacktestConfigSchema } from '../../types';
|
||||
import { BacktestEngine } from '../../backtest/BacktestEngine';
|
||||
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()
|
||||
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 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) => {
|
||||
app.post('/', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
|
@ -29,21 +29,27 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest'
|
||||
}, 500);
|
||||
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) => {
|
||||
app.post('/run', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
|
@ -57,72 +63,87 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
error: 'Invalid backtest configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
container.logger.error('Error running backtest:', error);
|
||||
return c.json({
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest'
|
||||
}, 500);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to run backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Stop running backtest
|
||||
app.post('/stop', async (c) => {
|
||||
app.post('/stop', async c => {
|
||||
try {
|
||||
await backtestEngine.stopBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest stop requested',
|
||||
timestamp: new Date().toISOString()
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to stop backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Pause running backtest
|
||||
app.post('/pause', async (c) => {
|
||||
app.post('/pause', async c => {
|
||||
try {
|
||||
await backtestEngine.pauseBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest paused',
|
||||
timestamp: new Date().toISOString()
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to pause backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Resume paused backtest
|
||||
app.post('/resume', async (c) => {
|
||||
app.post('/resume', async c => {
|
||||
try {
|
||||
await backtestEngine.resumeBacktest();
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest resumed',
|
||||
timestamp: new Date().toISOString()
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to resume backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Set backtest speed
|
||||
app.post('/speed', async (c) => {
|
||||
app.post('/speed', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const speed = body.speed ?? 1;
|
||||
|
|
@ -132,38 +153,44 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
return c.json({
|
||||
message: 'Backtest speed updated',
|
||||
speed: speed === null ? 'unlimited' : speed,
|
||||
timestamp: new Date().toISOString()
|
||||
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);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to set speed',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest progress
|
||||
app.get('/progress', async (c) => {
|
||||
app.get('/progress', async c => {
|
||||
try {
|
||||
const status = backtestEngine.getStatus();
|
||||
|
||||
return c.json({
|
||||
status: status.isPaused ? 'paused' : (status.isRunning ? 'running' : 'idle'),
|
||||
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
|
||||
progress: status.progress,
|
||||
currentTime: new Date(status.currentTime).toISOString(),
|
||||
isRunning: status.isRunning,
|
||||
isPaused: status.isPaused
|
||||
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);
|
||||
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) => {
|
||||
app.get('/stream', async c => {
|
||||
c.header('Content-Type', 'text/event-stream');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
c.header('Connection', 'keep-alive');
|
||||
|
|
@ -171,11 +198,11 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
// Listen for backtest events
|
||||
const onProgress = (data: any) => {
|
||||
const onProgress = (data: unknown) => {
|
||||
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
const onComplete = (data: any) => {
|
||||
const onComplete = (data: unknown) => {
|
||||
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
|
||||
controller.close();
|
||||
};
|
||||
|
|
@ -189,14 +216,14 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
backtestEngine.off('complete', onComplete);
|
||||
controller.close();
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream);
|
||||
});
|
||||
|
||||
// Validate backtest configuration
|
||||
app.post('/validate', async (c) => {
|
||||
app.post('/validate', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const config = BacktestConfigSchema.parse(body);
|
||||
|
|
@ -205,7 +232,7 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
const validation = {
|
||||
valid: true,
|
||||
warnings: [] as string[],
|
||||
estimatedDuration: 0
|
||||
estimatedDuration: 0,
|
||||
};
|
||||
|
||||
// Check data availability
|
||||
|
|
@ -227,17 +254,23 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
return c.json(validation);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
valid: false,
|
||||
error: 'Invalid configuration',
|
||||
details: error.errors
|
||||
}, 400);
|
||||
details: error.errors,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
return c.json(
|
||||
{
|
||||
valid: false,
|
||||
error: error instanceof Error ? error.message : 'Validation failed'
|
||||
}, 500);
|
||||
error: error instanceof Error ? error.message : 'Validation failed',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue