This commit is contained in:
Boki 2026-10-20 18:36:19 -04:00
parent 879e9b4228
commit c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions

16
.env.example Normal file
View file

@ -0,0 +1,16 @@
# Generate each token independently: openssl rand -hex 32
# Tokens stay on the server; never put them in VITE_* variables or URLs.
STOCK_BOT_ADMIN_TOKEN=
STOCK_BOT_SERVICE_TOKEN=
# Optional read-only dashboard/API access.
STOCK_BOT_READ_TOKEN=
STOCK_BOT_HTTP_HOST=127.0.0.1
STOCK_BOT_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
# Explicit loopback-only development escape hatch. Forbidden in production.
STOCK_BOT_AUTH_DISABLED=false
NODE_ENV=development
# Provider credentials are optional; configure only the providers you enable.
EOD_API_KEY=
QM_USERNAME=
QM_PASSWORD=
IB_ACCOUNT=

8
.gitignore vendored
View file

@ -1,3 +1,11 @@
# Environment files (the two private local-development configs are intentionally tracked)
.env
.env.*
!/.env
!/apps/stock/web-app/.env
!.env.example
!.env.*.example
# Dependencies
node_modules/
.pnp

View file

@ -21,6 +21,14 @@ include:
repository-check:
stage: test
image: rust:1.88-bookworm
services:
- name: postgres:16-alpine
alias: postgres
variables:
POSTGRES_DB: stock_bot_safety
POSTGRES_USER: fixture
POSTGRES_PASSWORD: fixture
PIPELINE_TEST_DATABASE_URL: postgres://fixture:fixture@postgres:5432/stock_bot_safety
before_script:
- apt-get update && apt-get install -y --no-install-recommends nodejs unzip
- curl -fsSL https://bun.sh/install | bash -s "bun-v1.2.17"
@ -28,3 +36,4 @@ repository-check:
- bun install --frozen-lockfile
script:
- bun run check
- bun run test:postgres

View file

@ -19,16 +19,16 @@ bun run check
The root build selects every buildable leaf workspace, including all stock services and the
native engine. `bun run build --dry=json` shows the actual Turbo task plan.
| Command | Scope |
| ------------------------ | ------------------------------------------------------------------------------------------- |
| `bun run build:libs` | Build shared libraries in dependency order |
| `bun run build --clean` | Force every workspace build without cached results |
| `bun run typecheck` | Check library, stock application, and tool source directly |
| `bun run test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate |
| Command | Scope |
| -------------------------- | ------------------------------------------------------------------------------------------------------- |
| `bun run build:libs` | Build shared libraries in dependency order |
| `bun run build --clean` | Force every workspace build without cached results |
| `bun run typecheck` | Check library, stock application, and tool source directly |
| `bun run test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate |
`check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined.
The larger existing `bun run test` suite is separate:
@ -136,3 +136,69 @@ reads, missing data, duplicate/concurrent requests, failed persistence/rollback,
responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests
use an in-process PostgreSQL emulator and the real transaction manager, not a live database.
Durable queued dispatch and recovery after an orchestrator crash remain follow-up work.
## HTTP access and secrets
HTTP services now fail closed unless server-side access tokens are configured. Use the
root `.env` (`.env.example` documents the settings) and set independent `STOCK_BOT_ADMIN_TOKEN` and
`STOCK_BOT_SERVICE_TOKEN` values (at least 32 characters; generate each with
`openssl rand -hex 32`). An optional distinct `STOCK_BOT_READ_TOKEN` permits read-only
access. The same service token must be available to internal HTTP clients and servers.
Never put these tokens in `VITE_*` settings, URLs, source files, or logs.
CLI clients use `Authorization: Bearer <token>`. The dashboard sign-in exchanges an
admin/read token for a signed one-hour HttpOnly, SameSite=Strict cookie; it does not store
the token in localStorage or include it in the bundle. Production cookies require HTTPS.
Read-only access cannot mutate data; all mutation/admin operations require admin/service
access. Internal services do not accept browser cookies. WebSocket upgrades authenticate
and validate browser Origin. Session-key rotation invalidates issued cookies; logout clears
the browser cookie (copied cookies remain valid until expiry or key rotation). This is an
operator-access boundary, not a multi-user identity/tenant system.
Dashboard/API URLs must be same-site for the strict cookie policy. In local development,
use matching hostnames (`localhost` for both, or `127.0.0.1` for both), not a mixture.
`STOCK_BOT_HTTP_HOST` defaults to `127.0.0.1`. Set it explicitly for containers. Set
`STOCK_BOT_ALLOWED_ORIGINS` to an exact comma-separated list of trusted frontend origins;
production same-origin requests are supported, and reverse-proxy deployments must include
the public HTTPS origin. Wildcard/null origins are rejected. For isolated local demos only,
`STOCK_BOT_AUTH_DISABLED=true` is allowed on a loopback development/test listener, never
in production. Health endpoints remain public. TLS termination and external rate limiting
belong at the deployment boundary; do not expose development services directly.
The root `.env` and `apps/stock/web-app/.env` are intentionally tracked for this private,
local-development repository. Other environment files remain ignored;
`bun run audit:secrets` rejects unexpected tracked environment files outside these two
explicit exceptions (WCAG excluded). It is not a complete secret scanner. Keep production
credentials out of these files. Committed values remain in Git history; rotate any real
credentials before sharing the repository or if access changes. Logging still redacts
sensitive fields, bearer tokens, credentialed URLs, and sensitive URL query parameters.
Development database/admin-UI Compose ports bind to loopback; existing containers must
be recreated for changed port bindings to take effect.
## Pipeline safety
Routine exchange/symbol/provider-mapping syncs are non-destructive. Legacy
`clearFirst: true` requests are rejected; scheduled exchange syncs no longer reset data.
The transactional sync paths share one checked-out PostgreSQL connection and one
transaction-scoped advisory lock. SQL errors roll back the whole batch and sync status,
and existing curated exchange/provider mappings are preserved. Do not add pooled
`query('BEGIN')` calls: use a transaction-scoped repository.
Reference-data reset is a separate admin maintenance operation. Send a JSON body to
`POST /api/pipeline/clear/postgresql` with an explicit `type` (`provider_mappings`,
`exchanges`, or `all`) and `confirmation: "DELETE STOCK REFERENCE DATA:<type>"`.
There is no default scope. A mapping-only reset deletes symbol-provider mappings only;
an exchange-only reset fails atomically if symbols still reference exchanges; `all`
deletes reference mappings, symbols, and exchanges in foreign-key order. These resets do
not delete backtest history, prices, or trading records. The dashboard requires typing
the matching confirmation. Generic queue access remains administrator-only.
`bun run test:native` is part of `bun run check`. The stochastic tests explicitly cover
warm-up (14-bar K plus 3-value D needs 16 bars), invalid periods, golden values, and
incremental/batch parity; no synthetic D values are produced before warm-up completes.
`bun run test:postgres` additionally requires `PIPELINE_TEST_DATABASE_URL` pointing to a
**disposable database whose name starts with `stock_bot_safety`**. It creates/drops isolated
test schemas and verifies real rollback, foreign-key constraints, idempotency, and competing
transaction locking. CI provisions that database and runs this additional gate. It is
separate from the infrastructure-free `check`; never point tests at production.

View file

@ -3,7 +3,7 @@
* Simplified entry point using ServiceApplication framework
*/
import { ServiceApplication } from '@stock-bot/di';
import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
@ -12,16 +12,22 @@ import { initializeAllHandlers } from './handlers';
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('dataIngestion');
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
// Log the full configuration
const logger = getLogger('data-ingestion');
logger.info('Service configuration:', config);
logger.info('Service configuration:', {
service: 'data-ingestion',
port: config.service.port,
environment: config.environment,
});
// Create service application
const app = new ServiceApplication(
config,
{
serviceName: 'data-ingestion',
hostname: security.hostname,
enableHandlers: true,
enableScheduledJobs: true,
corsConfig: {
@ -41,6 +47,7 @@ const app = new ServiceApplication(
},
{
// Lifecycle hooks if needed
onAppReady: app => security.mount(app),
onStarted: _port => {
const logger = getLogger('data-ingestion');
logger.info('Data ingestion service startup initiated with ServiceApplication framework');

View file

@ -12,6 +12,7 @@
"clean": "rm -rf dist"
},
"dependencies": {
"@stock-bot/types": "workspace:*",
"@stock-bot/services": "workspace:*",
"@stock-bot/cache": "*",
"@stock-bot/config": "*",

View file

@ -24,7 +24,7 @@ class ExchangesHandler extends BaseHandler {
description: 'Weekly full exchange sync on Sunday at midnight',
})
async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise<unknown> {
const finalPayload = payload || { clearFirst: true };
const finalPayload = payload ?? {};
this.log('info', 'Starting sync of all exchanges', finalPayload);
return syncAllExchanges(finalPayload, this);
}
@ -74,6 +74,7 @@ class ExchangesHandler extends BaseHandler {
@Operation('clear-postgresql-data')
async clearPostgreSQLData(payload: {
type?: 'exchanges' | 'provider_mappings' | 'all';
confirmation?: string;
}): Promise<unknown> {
this.log('warn', 'Clearing PostgreSQL data', payload);
return clearPostgreSQLData(payload, this);

View file

@ -1,62 +1,12 @@
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
parseResetRequest,
PipelineSyncRepository,
} from '../../../repositories/PipelineSyncRepository';
import type { JobPayload } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-clear-postgresql-data');
export async function clearPostgreSQLData(
payload: JobPayload,
container: IServiceContainer
): Promise<{
exchangesCleared: number;
symbolsCleared: number;
mappingsCleared: number;
}> {
logger.info('Clearing existing PostgreSQL data...');
try {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction for atomic operations
await postgresClient.query('BEGIN');
// Get counts before clearing
const exchangeCountResult = await postgresClient.query(
'SELECT COUNT(*) as count FROM exchanges'
);
const symbolCountResult = await postgresClient.query('SELECT COUNT(*) as count FROM symbols');
const mappingCountResult = await postgresClient.query(
'SELECT COUNT(*) as count FROM provider_mappings'
);
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');
await postgresClient.query('DELETE FROM symbols');
await postgresClient.query('DELETE FROM exchanges');
// Reset sync status
await postgresClient.query(
'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL'
);
await postgresClient.query('COMMIT');
logger.info('PostgreSQL data cleared successfully', {
exchangesCleared,
symbolsCleared,
mappingsCleared,
});
return { exchangesCleared, symbolsCleared, mappingsCleared };
} catch (error) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('Failed to clear PostgreSQL data', { error });
throw error;
}
export async function clearPostgreSQLData(payload: JobPayload, container: IServiceContainer) {
const scope = parseResetRequest(payload);
const { postgres } = requireServices(container, 'postgres');
return PipelineSyncRepository.transaction(postgres, repository => repository.reset(scope));
}

View file

@ -1,293 +1,52 @@
import { getLogger } from '@stock-bot/logger';
import type { PostgresClient } from '@stock-bot/services';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
PipelineSyncRepository,
rejectDestructiveSync,
} from '../../../repositories/PipelineSyncRepository';
import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-all-exchanges');
export async function syncAllExchanges(
payload: JobPayload,
container: IServiceContainer
): Promise<SyncResult> {
const clearFirst = payload.clearFirst || true;
logger.info('Starting comprehensive exchange sync...', { clearFirst });
const result: SyncResult = {
processed: 0,
created: 0,
updated: 0,
skipped: 0,
errors: 0,
};
try {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Clear existing data if requested
if (clearFirst) {
await clearPostgreSQLData(postgresClient);
rejectDestructiveSync(payload);
const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres');
// Fetch first: no SQL connection or write lock is held across provider-storage reads.
const [eod, ib] = await Promise.all([
mongodb.find('eodExchanges', { active: true }),
mongodb.find('ibExchanges', {}),
]);
return PipelineSyncRepository.transaction(postgres, async repository => {
const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 };
const rows = [
...eod.map(row => ({
provider: 'eod',
code: row.Code,
name: row.Name,
country: row.CountryISO2,
currency: row.Currency,
confidence: 0.95,
})),
...ib.map(row => ({
provider: 'ib',
code: row.exchange_id,
name: row.name,
country: row.country_code,
currency: row.currency,
confidence: 0.85,
})),
];
for (const row of rows) {
result.processed++;
if (!row.code) {
result.skipped++;
continue;
}
const outcome = await repository.syncExchange(row);
result[outcome]++;
}
// Start transaction for atomic operations
await postgresClient.query('BEGIN');
// 1. Sync from EOD exchanges (comprehensive global data)
const eodResult = await syncEODExchanges(container);
mergeResults(result, eodResult);
// 2. Sync from IB exchanges (detailed asset information)
const ibResult = await syncIBExchanges(container);
mergeResults(result, ibResult);
// 3. Update sync status
await updateSyncStatus('all', 'exchanges', result.processed, postgresClient);
await postgresClient.query('COMMIT');
logger.info('Comprehensive exchange sync completed', result);
// Any SQL failure aborts the entire sync, including status; never swallow errors in a transaction.
await repository.updateStatus('all', 'exchanges', result.processed);
return result;
} catch (error) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('Comprehensive exchange sync failed', { error });
throw error;
}
}
async function clearPostgreSQLData(postgresClient: PostgresClient): Promise<void> {
logger.info('Clearing existing PostgreSQL data...');
// Clear data in correct order (respect foreign keys)
await postgresClient.query('DELETE FROM provider_mappings');
await postgresClient.query('DELETE FROM symbols');
await postgresClient.query('DELETE FROM exchanges');
// Reset sync status
await postgresClient.query(
'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL'
);
logger.info('PostgreSQL data cleared successfully');
}
async function syncEODExchanges(container: IServiceContainer): Promise<SyncResult> {
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 };
for (const exchange of exchanges) {
try {
// Create provider exchange mapping for EOD
await createProviderExchangeMapping(
'eod', // provider
exchange.Code,
exchange.Name,
exchange.CountryISO2,
exchange.Currency,
0.95, // very high confidence for EOD data
container
);
result.processed++;
result.created++; // Count as created mapping
} catch (error) {
logger.error('Failed to process EOD exchange', { error, exchange });
result.errors++;
}
}
return result;
}
async function syncIBExchanges(container: IServiceContainer): Promise<SyncResult> {
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 };
for (const exchange of exchanges) {
try {
// Create provider exchange mapping for IB
await createProviderExchangeMapping(
'ib', // provider
exchange.exchange_id,
exchange.name,
exchange.country_code,
'USD', // IB doesn't specify currency, default to USD
0.85, // good confidence for IB data
container
);
result.processed++;
result.created++; // Count as created mapping
} catch (error) {
logger.error('Failed to process IB exchange', { error, exchange });
result.errors++;
}
}
return result;
}
async function createProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
providerExchangeName: string,
countryCode: string | null,
currency: string | null,
confidence: number,
container: IServiceContainer
): Promise<void> {
if (!providerExchangeCode) {
return;
}
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists
const existingMapping = await findProviderExchangeMapping(
provider,
providerExchangeCode,
container
);
if (existingMapping) {
// Don't override existing mappings to preserve manual work
return;
}
// Find or create master exchange
const masterExchange = await findOrCreateMasterExchange(
providerExchangeCode,
providerExchangeName,
countryCode,
currency,
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
(provider, provider_exchange_code, provider_exchange_name, master_exchange_id,
country_code, currency, confidence, active, auto_mapped)
VALUES ($1, $2, $3, $4, $5, $6, $7, false, true)
ON CONFLICT (provider, provider_exchange_code) DO NOTHING
`;
await postgresClient.query(query, [
provider,
providerExchangeCode,
providerExchangeName,
masterExchange.id,
countryCode,
currency,
confidence,
]);
}
async function findOrCreateMasterExchange(
providerCode: string,
providerName: string,
countryCode: string | null,
currency: string | null,
container: IServiceContainer
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container);
if (masterExchange) {
return masterExchange;
}
// Try to find by similar codes (basic mapping)
const basicMapping = getBasicExchangeMapping(providerCode);
if (basicMapping) {
masterExchange = await findExchangeByCode(basicMapping, container);
if (masterExchange) {
return masterExchange;
}
}
// Create new master exchange (inactive by default)
const query = `
INSERT INTO exchanges (code, name, country, currency, active)
VALUES ($1, $2, $3, $4, false)
ON CONFLICT (code) DO UPDATE SET
name = COALESCE(EXCLUDED.name, exchanges.name),
country = COALESCE(EXCLUDED.country, exchanges.country),
currency = COALESCE(EXCLUDED.currency, exchanges.currency)
RETURNING id, code, name, country, currency
`;
const result = await postgresClient.query(query, [
providerCode,
providerName || providerCode,
countryCode || 'US',
currency || 'USD',
]);
return result.rows[0];
}
function getBasicExchangeMapping(providerCode: string): string | null {
const mappings: Record<string, string> = {
NYE: 'NYSE',
NAS: 'NASDAQ',
TO: 'TSX',
LN: 'LSE',
LON: 'LSE',
};
return mappings[providerCode.toUpperCase()] || null;
}
async function findProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
) {
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) {
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;
}
async function updateSyncStatus(
provider: string,
dataType: string,
count: number,
postgresClient: PostgresClient
): Promise<void> {
const query = `
INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors)
VALUES ($1, $2, NOW(), $3, NULL)
ON CONFLICT (provider, data_type)
DO UPDATE SET
last_sync_at = NOW(),
last_sync_count = EXCLUDED.last_sync_count,
sync_errors = NULL,
updated_at = NOW()
`;
await postgresClient.query(query, [provider, dataType, count]);
}
function mergeResults(target: SyncResult, source: SyncResult): void {
target.processed += source.processed;
target.created += source.created;
target.updated += source.updated;
target.skipped += source.skipped;
target.errors += source.errors;
});
}

View file

@ -1,33 +1,20 @@
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
PipelineSyncRepository,
rejectDestructiveSync,
} from '../../../repositories/PipelineSyncRepository';
import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-qm-provider-mappings');
export async function syncQMProviderMappings(
payload: JobPayload,
container: IServiceContainer
): Promise<SyncResult> {
logger.info('Starting QM provider exchange mappings sync...');
const result: SyncResult = {
processed: 0,
created: 0,
updated: 0,
skipped: 0,
errors: 0,
};
try {
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Start transaction
await postgresClient.query('BEGIN');
// Get unique exchange combinations from QM symbols
const db = mongoClient.getDatabase();
const pipeline = [
rejectDestructiveSync(payload);
const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres');
const rows = await mongodb
.getDatabase()
.collection('qmSymbols')
.aggregate([
{
$group: {
_id: {
@ -35,8 +22,6 @@ export async function syncQMProviderMappings(
exchange: '$exchange',
countryCode: '$countryCode',
},
count: { $sum: 1 },
sampleExchange: { $first: '$exchange' },
},
},
{
@ -44,180 +29,29 @@ export async function syncQMProviderMappings(
exchangeCode: '$_id.exchangeCode',
exchange: '$_id.exchange',
countryCode: '$_id.countryCode',
count: 1,
sampleExchange: 1,
},
},
];
const qmExchanges = await db.collection('qmSymbols').aggregate(pipeline).toArray();
logger.info(`Found ${qmExchanges.length} unique QM exchange combinations`);
for (const exchange of qmExchanges) {
try {
// Create provider exchange mapping for QM
await createProviderExchangeMapping(
'qm', // provider
exchange.exchangeCode,
exchange.sampleExchange || exchange.exchangeCode,
exchange.countryCode,
exchange.countryCode === 'CA' ? 'CAD' : 'USD', // Simple currency mapping
0.8, // good confidence for QM data
container
);
result.processed++;
result.created++;
} catch (error) {
logger.error('Failed to process QM exchange mapping', { error, exchange });
result.errors++;
])
.toArray();
return PipelineSyncRepository.transaction(postgres, async repository => {
const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 };
for (const row of rows) {
result.processed++;
if (!row.exchangeCode) {
result.skipped++;
continue;
}
const outcome = await repository.syncExchange({
provider: 'qm',
code: row.exchangeCode,
name: row.exchange || row.exchangeCode,
country: row.countryCode,
currency: row.countryCode === 'CA' ? 'CAD' : 'USD',
confidence: 0.8,
});
result[outcome]++;
}
await postgresClient.query('COMMIT');
logger.info('QM provider exchange mappings sync completed', result);
await repository.updateStatus('qm', 'exchange_mappings', result.processed);
return result;
} catch (error) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
await postgresClient.query('ROLLBACK');
logger.error('QM provider exchange mappings sync failed', { error });
throw error;
}
}
async function createProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
providerExchangeName: string,
countryCode: string | null,
currency: string | null,
confidence: number,
container: IServiceContainer
): Promise<void> {
if (!providerExchangeCode) {
return;
}
const { postgres: postgresClient } = requireServices(container, 'postgres');
// Check if mapping already exists
const existingMapping = await findProviderExchangeMapping(
provider,
providerExchangeCode,
container
);
if (existingMapping) {
// Don't override existing mappings to preserve manual work
return;
}
// Find or create master exchange
const masterExchange = await findOrCreateMasterExchange(
providerExchangeCode,
providerExchangeName,
countryCode,
currency,
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
(provider, provider_exchange_code, provider_exchange_name, master_exchange_id,
country_code, currency, confidence, active, auto_mapped)
VALUES ($1, $2, $3, $4, $5, $6, $7, false, true)
ON CONFLICT (provider, provider_exchange_code) DO NOTHING
`;
await postgresClient.query(query, [
provider,
providerExchangeCode,
providerExchangeName,
masterExchange.id,
countryCode,
currency,
confidence,
]);
}
async function findProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
) {
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 findOrCreateMasterExchange(
providerCode: string,
providerName: string,
countryCode: string | null,
currency: string | null,
container: IServiceContainer
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
// First, try to find exact match
let masterExchange = await findExchangeByCode(providerCode, container);
if (masterExchange) {
return masterExchange;
}
// Try to find by similar codes (basic mapping)
const basicMapping = getBasicExchangeMapping(providerCode);
if (basicMapping) {
masterExchange = await findExchangeByCode(basicMapping, container);
if (masterExchange) {
return masterExchange;
}
}
// Create new master exchange (inactive by default)
const query = `
INSERT INTO exchanges (code, name, country, currency, active)
VALUES ($1, $2, $3, $4, false)
ON CONFLICT (code) DO UPDATE SET
name = COALESCE(EXCLUDED.name, exchanges.name),
country = COALESCE(EXCLUDED.country, exchanges.country),
currency = COALESCE(EXCLUDED.currency, exchanges.currency)
RETURNING id, code, name, country, currency
`;
const result = await postgresClient.query(query, [
providerCode,
providerName || providerCode,
countryCode || 'US',
currency || 'USD',
]);
return result.rows[0];
}
function getBasicExchangeMapping(providerCode: string): string | null {
const mappings: Record<string, string> = {
NYE: 'NYSE',
NAS: 'NASDAQ',
TO: 'TSX',
LN: 'LSE',
LON: 'LSE',
};
return mappings[providerCode.toUpperCase()] || null;
}
async function findExchangeByCode(code: string, container: IServiceContainer) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = 'SELECT * FROM exchanges WHERE code = $1';
const result = await postgresClient.query(query, [code]);
return result.rows[0] || null;
});
}

View file

@ -1,261 +1,39 @@
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 {
PipelineSyncRepository,
rejectDestructiveSync,
} from '../../../repositories/PipelineSyncRepository';
import type { JobPayload, SyncResult } from '../../../types/job-payloads';
const logger = getLogger('enhanced-sync-symbols-from-provider');
export async function syncSymbolsFromProvider(
payload: JobPayload,
container: IServiceContainer
): Promise<SyncResult> {
const provider = payload.provider;
const clearFirst = payload.clearFirst || false;
if (!provider) {
throw new Error('Provider is required in payload');
}
logger.info(`Starting ${provider} symbols sync...`, { clearFirst });
const result: SyncResult = {
processed: 0,
created: 0,
updated: 0,
skipped: 0,
errors: 0,
rejectDestructiveSync(payload);
const provider = payload.provider?.toLowerCase();
const collections: Record<string, string> = {
qm: 'qmSymbols',
eod: 'eodSymbols',
ib: 'ibSymbols',
};
try {
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) {
await postgresClient.query('BEGIN');
await postgresClient.query('DELETE FROM provider_mappings');
await postgresClient.query('DELETE FROM symbols');
await postgresClient.query('COMMIT');
logger.info('Cleared existing symbols and mappings before sync');
const collection = provider && collections[provider];
if (!provider || !collection) {
throw new Error('A supported provider (qm, eod, ib) is required');
}
const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres');
const rows = await mongodb.getDatabase().collection(collection).find({}).toArray();
return PipelineSyncRepository.transaction(postgres, async repository => {
const result: SyncResult = {
processed: rows.length,
created: 0,
updated: 0,
skipped: 0,
errors: 0,
};
for (const row of rows) {
result[await repository.syncSymbol(provider, row)]++;
}
// Start transaction
await postgresClient.query('BEGIN');
let symbols: Record<string, unknown>[] = [];
// Get symbols based on provider
const db = mongoClient.getDatabase();
switch (provider.toLowerCase()) {
case 'qm':
symbols = await db.collection('qmSymbols').find({}).toArray();
break;
case 'eod':
symbols = await db.collection('eodSymbols').find({}).toArray();
break;
case 'ib':
symbols = await db.collection('ibSymbols').find({}).toArray();
break;
default:
throw new Error(`Unsupported provider: ${provider}`);
}
logger.info(`Found ${symbols.length} ${provider} symbols to process`);
result.processed = symbols.length;
for (const symbol of symbols) {
try {
await processSingleSymbol(symbol, provider, result, container);
} catch (error) {
logger.error('Failed to process symbol', {
error,
symbol: symbol.symbol || symbol.code,
provider,
});
result.errors++;
}
}
// Update sync status
await updateSyncStatus(
provider,
'symbols',
result.processed,
requireServices(container, 'postgres').postgres
);
await postgresClient.query('COMMIT');
logger.info(`${provider} symbols sync completed`, result);
await repository.updateStatus(provider, 'symbols', result.processed);
return result;
} catch (error) {
await requireServices(container, 'postgres').postgres.query('ROLLBACK');
logger.error(`${provider} symbols sync failed`, { error });
throw error;
}
}
async function processSingleSymbol(
symbol: Document,
provider: string,
result: SyncResult,
container: IServiceContainer
): Promise<void> {
const symbolCode = symbol.symbol || symbol.code;
const exchangeCode = symbol.exchangeCode || symbol.exchange || symbol.exchange_id;
if (!symbolCode || !exchangeCode) {
result.skipped++;
return;
}
// Find active provider exchange mapping
const providerMapping = await findActiveProviderExchangeMapping(
provider,
exchangeCode,
container
);
if (!providerMapping) {
result.skipped++;
return;
}
// Check if symbol exists
const existingSymbol = await findSymbolByCodeAndExchange(
symbolCode,
providerMapping.master_exchange_id,
container
);
if (existingSymbol) {
await updateSymbol(existingSymbol.id, symbol, container);
await upsertProviderMapping(existingSymbol.id, provider, symbol, container);
result.updated++;
} else {
const newSymbolId = await createSymbol(symbol, providerMapping.master_exchange_id, container);
await upsertProviderMapping(newSymbolId, provider, symbol, container);
result.created++;
}
}
async function findActiveProviderExchangeMapping(
provider: string,
providerExchangeCode: string,
container: IServiceContainer
) {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
SELECT pem.*, e.code as master_exchange_code
FROM provider_exchange_mappings pem
JOIN exchanges e ON pem.master_exchange_id = e.id
WHERE pem.provider = $1 AND pem.provider_exchange_code = $2 AND pem.active = true
`;
const result = await postgresClient.query(query, [provider, providerExchangeCode]);
return result.rows[0] || null;
}
async function findSymbolByCodeAndExchange(
symbol: string,
exchangeId: string,
container: IServiceContainer
) {
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: Document,
exchangeId: string,
container: IServiceContainer
): Promise<string> {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`;
const result = await postgresClient.query(query, [
symbol.symbol || symbol.code,
exchangeId,
symbol.companyName || symbol.name || symbol.company_name,
symbol.countryCode || symbol.country_code || 'US',
symbol.currency || 'USD',
]);
return at(result.rows, 0).id;
}
async function updateSymbol(
symbolId: string,
symbol: Document,
container: IServiceContainer
): Promise<void> {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
UPDATE symbols
SET company_name = COALESCE($2, company_name),
country = COALESCE($3, country),
currency = COALESCE($4, currency),
updated_at = NOW()
WHERE id = $1
`;
await postgresClient.query(query, [
symbolId,
symbol.companyName || symbol.name || symbol.company_name,
symbol.countryCode || symbol.country_code,
symbol.currency,
]);
}
async function upsertProviderMapping(
symbolId: string,
provider: string,
symbol: Document,
container: IServiceContainer
): Promise<void> {
const { postgres: postgresClient } = requireServices(container, 'postgres');
const query = `
INSERT INTO provider_mappings
(symbol_id, provider, provider_symbol, provider_exchange, last_seen)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (provider, provider_symbol)
DO UPDATE SET
symbol_id = EXCLUDED.symbol_id,
provider_exchange = EXCLUDED.provider_exchange,
last_seen = NOW()
`;
await postgresClient.query(query, [
symbolId,
provider,
symbol.qmSearchCode || symbol.symbol || symbol.code,
symbol.exchangeCode || symbol.exchange || symbol.exchange_id,
]);
}
async function updateSyncStatus(
provider: string,
dataType: string,
count: number,
postgresClient: PostgresClient
): Promise<void> {
const query = `
INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors)
VALUES ($1, $2, NOW(), $3, NULL)
ON CONFLICT (provider, data_type)
DO UPDATE SET
last_sync_at = NOW(),
last_sync_count = EXCLUDED.last_sync_count,
sync_errors = NULL,
updated_at = NOW()
`;
await postgresClient.query(query, [provider, dataType, count]);
});
}

View file

@ -3,7 +3,7 @@
* Simplified entry point using ServiceApplication framework
*/
import { ServiceApplication } from '@stock-bot/di';
import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
@ -13,16 +13,22 @@ import { initializeAllHandlers } from './handlers';
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('dataPipeline');
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
// Log the full configuration
const logger = getLogger('data-pipeline');
logger.info('Service configuration:', config);
logger.info('Service configuration:', {
service: 'data-pipeline',
port: config.service.port,
environment: config.environment,
});
// Create service application
const app = new ServiceApplication(
config,
{
serviceName: 'data-pipeline',
hostname: security.hostname,
enableHandlers: true,
enableScheduledJobs: true,
corsConfig: {
@ -42,6 +48,7 @@ const app = new ServiceApplication(
},
{
// Custom lifecycle hooks
onAppReady: app => security.mount(app),
onContainerReady: container => {
// Setup service-specific configuration
setupServiceContainer(config, container);

View file

@ -0,0 +1,180 @@
import type { Document } from 'mongodb';
import type { TransactionCallback } from '@stock-bot/postgres';
import type { PostgresClient } from '@stock-bot/services';
import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types';
type SqlClient = Pick<Parameters<TransactionCallback<unknown>>[0], 'query'>;
export type ResetScope = ReferenceDataResetScope;
/** Every helper uses the same checked-out transaction connection. */
export class PipelineSyncRepository {
constructor(private readonly sql: SqlClient) {}
static async transaction<T>(
postgres: Pick<PostgresClient, 'transaction'>,
work: (repository: PipelineSyncRepository) => Promise<T>
): Promise<T> {
return postgres.transaction(async client => {
// Serialize sync/reset transactions across service instances. Released on rollback too.
await client.query('SELECT pg_advisory_xact_lock(1937007472, 1)');
return work(new PipelineSyncRepository(client));
});
}
async syncExchange(input: {
provider: string;
code: string;
name: string;
country?: string | null;
currency?: string | null;
confidence: number;
}): Promise<'created' | 'skipped'> {
const existing = await this.sql.query(
'SELECT id FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2',
[input.provider, input.code]
);
if (existing.rows.length) {
return 'skipped';
} // Preserve manually curated mappings.
const aliases: Record<string, string> = {
NYE: 'NYSE',
NAS: 'NASDAQ',
TO: 'TSX',
LN: 'LSE',
LON: 'LSE',
};
const code = aliases[input.code.toUpperCase()] ?? input.code;
const exchange = await this.sql.query<{ id: string }>(
`INSERT INTO exchanges (code, name, country, currency, active)
VALUES ($1, $2, $3, $4, false) ON CONFLICT (code) DO UPDATE SET code = EXCLUDED.code
RETURNING id`,
[code, input.name || code, input.country || 'US', input.currency || 'USD']
);
const id = exchange.rows[0]?.id;
if (!id) {
throw new Error('Master exchange could not be resolved');
}
const inserted = await this.sql.query(
`INSERT INTO provider_exchange_mappings
(provider, provider_exchange_code, provider_exchange_name, master_exchange_id,
country_code, currency, confidence, active, auto_mapped)
VALUES ($1,$2,$3,$4,$5,$6,$7,false,true)
ON CONFLICT (provider, provider_exchange_code) DO NOTHING RETURNING id`,
[
input.provider,
input.code,
input.name,
id,
input.country ?? null,
input.currency ?? null,
input.confidence,
]
);
return inserted.rows.length ? 'created' : 'skipped';
}
async syncSymbol(provider: string, symbol: Document): Promise<'created' | 'updated' | 'skipped'> {
const code = symbol.symbol || symbol.code || symbol.Code;
const exchangeCode =
symbol.exchangeCode || symbol.exchange || symbol.exchange_id || symbol.Exchange;
if (!code || !exchangeCode) {
return 'skipped';
}
const mapping = await this.sql.query<{ master_exchange_id: string }>(
`SELECT master_exchange_id FROM provider_exchange_mappings
WHERE provider = $1 AND provider_exchange_code = $2 AND active = true`,
[provider, exchangeCode]
);
const exchangeId = mapping.rows[0]?.master_exchange_id;
if (!exchangeId) {
return 'skipped';
}
const existing = await this.sql.query<{ id: string }>(
'SELECT id FROM symbols WHERE symbol = $1 AND exchange_id = $2',
[code, exchangeId]
);
const saved = await this.sql.query<{ id: string }>(
`INSERT INTO symbols (symbol, exchange_id, company_name, country, currency)
VALUES ($1,$2,$3,$4,$5) ON CONFLICT (symbol, exchange_id) DO UPDATE SET
company_name = COALESCE(EXCLUDED.company_name, symbols.company_name),
country = COALESCE(EXCLUDED.country, symbols.country),
currency = COALESCE(EXCLUDED.currency, symbols.currency), updated_at = NOW() RETURNING id`,
[
code,
exchangeId,
symbol.companyName || symbol.name || symbol.company_name || symbol.Name || null,
symbol.countryCode || symbol.country_code || symbol.Country || null,
symbol.currency || symbol.Currency || null,
]
);
const symbolId = saved.rows[0]?.id;
if (!symbolId) {
throw new Error('Symbol could not be resolved');
}
await this.sql.query(
`INSERT INTO provider_mappings (symbol_id, provider, provider_symbol, provider_exchange, last_seen)
VALUES ($1,$2,$3,$4,NOW()) ON CONFLICT (provider, provider_symbol) DO UPDATE SET
symbol_id = CASE WHEN provider_mappings.verified THEN provider_mappings.symbol_id ELSE EXCLUDED.symbol_id END,
provider_exchange = CASE WHEN provider_mappings.verified THEN provider_mappings.provider_exchange ELSE EXCLUDED.provider_exchange END,
last_seen = NOW()`,
[
symbolId,
provider,
symbol.qmSearchCode || symbol.eodSearchCode || symbol.symbol || symbol.code || symbol.Code,
exchangeCode,
]
);
return existing.rows.length ? 'updated' : 'created';
}
async updateStatus(provider: string, kind: string, count: number): Promise<void> {
await this.sql.query(
`INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors)
VALUES ($1,$2,NOW(),$3,NULL) ON CONFLICT (provider, data_type) DO UPDATE SET
last_sync_at = NOW(), last_sync_count = EXCLUDED.last_sync_count, sync_errors = NULL, updated_at = NOW()`,
[provider, kind, count]
);
}
async reset(scope: ResetScope) {
const counts = {
exchangesCleared: 0,
symbolsCleared: 0,
mappingsCleared: 0,
exchangeMappingsCleared: 0,
};
const remove = async (
table: 'provider_mappings' | 'symbols' | 'provider_exchange_mappings' | 'exchanges'
) => {
const result = await this.sql.query(`DELETE FROM ${table}`);
return result.rowCount ?? 0;
};
if (scope === 'all' || scope === 'provider_mappings') {
counts.mappingsCleared = await remove('provider_mappings');
}
if (scope === 'all') {
counts.symbolsCleared = await remove('symbols');
}
if (scope === 'all' || scope === 'exchanges') {
// FK constraints reject an exchange-only reset if symbols still reference it.
counts.exchangeMappingsCleared = await remove('provider_exchange_mappings');
counts.exchangesCleared = await remove('exchanges');
}
await this.sql.query(
'UPDATE sync_status SET last_sync_at = NULL, last_sync_count = 0, sync_errors = NULL'
);
return counts;
}
}
export function rejectDestructiveSync(payload: { clearFirst?: unknown }): void {
if (payload.clearFirst !== undefined && payload.clearFirst !== false) {
throw new Error(
'Sync is non-destructive; use the explicit, confirmed maintenance reset instead'
);
}
}
export function parseResetRequest(payload: Record<string, unknown>): ResetScope {
return parseReferenceDataResetRequest(payload).type;
}

View file

@ -1,6 +1,7 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { parseReferenceDataResetRequest } from '@stock-bot/types';
const logger = getLogger('enhanced-sync-routes');
@ -9,6 +10,9 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
// Enhanced sync endpoints
enhancedSync.post('/exchanges/all', async c => {
if (c.req.query('clear') && c.req.query('clear') !== 'false') {
return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400);
}
try {
const clearFirst = c.req.query('clear') === 'true';
const queueManager = container.queueManager;
@ -118,8 +122,14 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
});
enhancedSync.post('/clear/postgresql', async c => {
const input: unknown = await c.req.json().catch(() => null);
let payload;
try {
payload = parseReferenceDataResetRequest(input);
} catch (error) {
return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400);
}
try {
const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all';
const queueManager = container.queueManager;
if (!queueManager) {
return c.json({ success: false, error: 'Queue manager not available' }, 503);
@ -130,7 +140,7 @@ export function createEnhancedSyncRoutes(container: IServiceContainer) {
const job = await exchangesQueue.add('clear-postgresql-data', {
handler: 'exchanges',
operation: 'clear-postgresql-data',
payload: { dataType: dataType || 'all' },
payload,
});
return c.json({

View file

@ -1,297 +1,346 @@
use super::{Indicator, IncrementalIndicator, IndicatorResult, IndicatorError, PriceData};
use super::sma::SMA;
use super::common::RollingWindow;
/// Stochastic Oscillator Indicator
///
/// %K = 100 × (Close - Lowest Low) / (Highest High - Lowest Low)
/// %D = SMA of %K
pub struct Stochastic {
k_period: usize,
d_period: usize,
smooth_k: usize,
high_window: RollingWindow<f64>,
low_window: RollingWindow<f64>,
close_window: RollingWindow<f64>,
k_sma: SMA,
d_sma: SMA,
k_values: RollingWindow<f64>,
}
impl Stochastic {
pub fn new(k_period: usize, d_period: usize, smooth_k: usize) -> Result<Self, IndicatorError> {
if k_period == 0 || d_period == 0 {
return Err(IndicatorError::InvalidParameter(
"K and D periods must be greater than 0".to_string()
));
}
Ok(Self {
k_period,
d_period,
smooth_k,
high_window: RollingWindow::new(k_period),
low_window: RollingWindow::new(k_period),
close_window: RollingWindow::new(k_period),
k_sma: SMA::new(smooth_k.max(1))?,
d_sma: SMA::new(d_period)?,
k_values: RollingWindow::new(d_period),
})
}
/// Standard Fast Stochastic (14, 3)
pub fn fast() -> Result<Self, IndicatorError> {
Self::new(14, 3, 1)
}
/// Standard Slow Stochastic (14, 3, 3)
pub fn slow() -> Result<Self, IndicatorError> {
Self::new(14, 3, 3)
}
/// Calculate raw %K value
fn calculate_raw_k(high: &[f64], low: &[f64], close: f64) -> Option<f64> {
if high.is_empty() || low.is_empty() {
return None;
}
let highest = high.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let lowest = low.iter().cloned().fold(f64::INFINITY, f64::min);
let range = highest - lowest;
if range > 0.0 {
Some(100.0 * (close - lowest) / range)
} else {
Some(50.0) // If no range, return middle value
}
}
/// Calculate Stochastic for a series of price data
pub fn calculate_series(
high: &[f64],
low: &[f64],
close: &[f64],
k_period: usize,
d_period: usize,
smooth_k: usize,
) -> Result<(Vec<f64>, Vec<f64>), IndicatorError> {
if high.len() != low.len() || high.len() != close.len() {
return Err(IndicatorError::InvalidParameter(
"High, low, and close arrays must have the same length".to_string()
));
}
if high.len() < k_period {
return Err(IndicatorError::InsufficientData {
required: k_period,
actual: high.len(),
});
}
// Calculate raw %K values
let mut raw_k_values = Vec::with_capacity(high.len() - k_period + 1);
for i in k_period - 1..high.len() {
let start = i + 1 - k_period;
if let Some(k) = Self::calculate_raw_k(
&high[start..=i],
&low[start..=i],
close[i]
) {
raw_k_values.push(k);
}
}
// Smooth %K if requested
let k_values = if smooth_k > 1 {
SMA::calculate_series(&raw_k_values, smooth_k)?
} else {
raw_k_values
};
// Calculate %D (SMA of %K)
let d_values = if k_values.len() >= d_period {
SMA::calculate_series(&k_values, d_period)?
} else {
vec![]
};
Ok((k_values, d_values))
}
}
impl Indicator for Stochastic {
fn calculate(&mut self, data: &PriceData) -> Result<IndicatorResult, IndicatorError> {
if data.high.len() != data.low.len() || data.high.len() != data.close.len() {
return Err(IndicatorError::InvalidParameter(
"Price data arrays must have the same length".to_string()
));
}
let (k_values, d_values) = Self::calculate_series(
&data.high,
&data.low,
&data.close,
self.k_period,
self.d_period,
self.smooth_k,
)?;
Ok(IndicatorResult::Stochastic {
k: k_values,
d: d_values,
})
}
fn reset(&mut self) {
self.high_window.clear();
self.low_window.clear();
self.close_window.clear();
self.k_sma.reset();
self.d_sma.reset();
self.k_values.clear();
}
fn is_ready(&self) -> bool {
self.high_window.is_full() && self.d_sma.is_ready()
}
}
impl IncrementalIndicator for Stochastic {
fn update(&mut self, value: f64) -> Result<Option<f64>, IndicatorError> {
// For incremental updates, we assume value is close price
// In real usage, you'd need to provide high/low/close separately
self.high_window.push(value);
self.low_window.push(value);
self.close_window.push(value);
if self.high_window.is_full() {
// Calculate raw %K
if let Some(raw_k) = Self::calculate_raw_k(
&self.high_window.as_slice(),
&self.low_window.as_slice(),
value
) {
// Smooth %K if needed
let k_value = if self.smooth_k > 1 {
self.k_sma.update(raw_k)?
} else {
Some(raw_k)
};
if let Some(k) = k_value {
self.k_values.push(k);
// Calculate %D
if let Some(d) = self.d_sma.update(k)? {
return Ok(Some(d));
}
}
}
}
Ok(None)
}
fn current(&self) -> Option<f64> {
self.d_sma.current()
}
}
/// Structure to hold Stochastic values
pub struct StochasticValues {
pub k: f64,
pub d: f64,
}
impl Stochastic {
/// Get current %K and %D values
pub fn current_values(&self) -> Option<StochasticValues> {
if let (Some(&k), Some(d)) = (self.k_values.iter().last(), self.d_sma.current()) {
Some(StochasticValues { k, d })
} else {
None
}
}
/// Update with separate high, low, close values
pub fn update_hlc(&mut self, high: f64, low: f64, close: f64) -> Result<Option<StochasticValues>, IndicatorError> {
self.high_window.push(high);
self.low_window.push(low);
self.close_window.push(close);
if self.high_window.is_full() {
if let Some(raw_k) = Self::calculate_raw_k(
&self.high_window.as_slice(),
&self.low_window.as_slice(),
close
) {
let k_value = if self.smooth_k > 1 {
self.k_sma.update(raw_k)?
} else {
Some(raw_k)
};
if let Some(k) = k_value {
self.k_values.push(k);
if let Some(d) = self.d_sma.update(k)? {
return Ok(Some(StochasticValues { k, d }));
}
}
}
}
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stochastic_calculation() {
let high = vec![
127.01, 127.62, 126.59, 127.35, 128.17,
128.43, 127.37, 126.42, 126.90, 126.85,
125.65, 125.72, 127.16, 127.72, 127.69
];
let low = vec![
125.36, 126.16, 124.93, 126.09, 126.82,
126.48, 126.03, 124.83, 126.39, 125.72,
124.56, 124.57, 125.07, 126.86, 126.63
];
let close = vec![
125.36, 126.16, 124.93, 126.09, 126.82,
126.48, 126.03, 124.83, 126.39, 125.72,
124.56, 124.57, 125.07, 126.86, 126.63
];
let (k_values, d_values) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
assert!(!k_values.is_empty());
assert!(!d_values.is_empty());
// %K should be between 0 and 100
for k in &k_values {
assert!(*k >= 0.0 && *k <= 100.0);
}
}
#[test]
fn test_stochastic_extremes() {
// When close is at highest high, %K should be 100
let high = vec![10.0; 14];
let low = vec![5.0; 14];
let mut close = vec![7.5; 14];
close[13] = 10.0; // Last close at high
let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
assert!((k_values[0] - 100.0).abs() < 1e-10);
// When close is at lowest low, %K should be 0
close[13] = 5.0; // Last close at low
let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
assert!(k_values[0].abs() < 1e-10);
}
}
use super::common::RollingWindow;
use super::sma::SMA;
use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData};
/// Stochastic Oscillator Indicator
///
/// %K = 100 × (Close - Lowest Low) / (Highest High - Lowest Low)
/// %D = SMA of %K
pub struct Stochastic {
k_period: usize,
d_period: usize,
smooth_k: usize,
high_window: RollingWindow<f64>,
low_window: RollingWindow<f64>,
close_window: RollingWindow<f64>,
k_sma: SMA,
d_sma: SMA,
k_values: RollingWindow<f64>,
}
impl Stochastic {
pub fn new(k_period: usize, d_period: usize, smooth_k: usize) -> Result<Self, IndicatorError> {
if k_period == 0 || d_period == 0 || smooth_k == 0 {
return Err(IndicatorError::InvalidParameter(
"K, D, and smoothing periods must be greater than 0".to_string(),
));
}
Ok(Self {
k_period,
d_period,
smooth_k,
high_window: RollingWindow::new(k_period),
low_window: RollingWindow::new(k_period),
close_window: RollingWindow::new(k_period),
k_sma: SMA::new(smooth_k.max(1))?,
d_sma: SMA::new(d_period)?,
k_values: RollingWindow::new(d_period),
})
}
/// Standard Fast Stochastic (14, 3)
pub fn fast() -> Result<Self, IndicatorError> {
Self::new(14, 3, 1)
}
/// Standard Slow Stochastic (14, 3, 3)
pub fn slow() -> Result<Self, IndicatorError> {
Self::new(14, 3, 3)
}
/// Calculate raw %K value
fn calculate_raw_k(high: &[f64], low: &[f64], close: f64) -> Option<f64> {
if high.is_empty() || low.is_empty() {
return None;
}
let highest = high.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let lowest = low.iter().cloned().fold(f64::INFINITY, f64::min);
let range = highest - lowest;
if range > 0.0 {
Some(100.0 * (close - lowest) / range)
} else {
Some(50.0) // If no range, return middle value
}
}
/// Calculate Stochastic for a series of price data
pub fn calculate_series(
high: &[f64],
low: &[f64],
close: &[f64],
k_period: usize,
d_period: usize,
smooth_k: usize,
) -> Result<(Vec<f64>, Vec<f64>), IndicatorError> {
if k_period == 0 || d_period == 0 || smooth_k == 0 {
return Err(IndicatorError::InvalidParameter(
"K, D, and smoothing periods must be greater than 0".to_string(),
));
}
if high.len() != low.len() || high.len() != close.len() {
return Err(IndicatorError::InvalidParameter(
"High, low, and close arrays must have the same length".to_string(),
));
}
if high.len() < k_period {
return Err(IndicatorError::InsufficientData {
required: k_period,
actual: high.len(),
});
}
// Calculate raw %K values
let mut raw_k_values = Vec::with_capacity(high.len() - k_period + 1);
for i in k_period - 1..high.len() {
let start = i + 1 - k_period;
if let Some(k) = Self::calculate_raw_k(&high[start..=i], &low[start..=i], close[i]) {
raw_k_values.push(k);
}
}
// Smooth %K if requested
let k_values = if raw_k_values.len() < smooth_k {
vec![]
} else if smooth_k > 1 {
SMA::calculate_series(&raw_k_values, smooth_k)?
} else {
raw_k_values
};
// Calculate %D (SMA of %K)
let d_values = if k_values.len() >= d_period {
SMA::calculate_series(&k_values, d_period)?
} else {
vec![]
};
Ok((k_values, d_values))
}
}
impl Indicator for Stochastic {
fn calculate(&mut self, data: &PriceData) -> Result<IndicatorResult, IndicatorError> {
if data.high.len() != data.low.len() || data.high.len() != data.close.len() {
return Err(IndicatorError::InvalidParameter(
"Price data arrays must have the same length".to_string(),
));
}
let (k_values, d_values) = Self::calculate_series(
&data.high,
&data.low,
&data.close,
self.k_period,
self.d_period,
self.smooth_k,
)?;
Ok(IndicatorResult::Stochastic {
k: k_values,
d: d_values,
})
}
fn reset(&mut self) {
self.high_window.clear();
self.low_window.clear();
self.close_window.clear();
self.k_sma.reset();
self.d_sma.reset();
self.k_values.clear();
}
fn is_ready(&self) -> bool {
self.high_window.is_full() && self.d_sma.is_ready()
}
}
impl IncrementalIndicator for Stochastic {
fn update(&mut self, value: f64) -> Result<Option<f64>, IndicatorError> {
// For incremental updates, we assume value is close price
// In real usage, you'd need to provide high/low/close separately
self.high_window.push(value);
self.low_window.push(value);
self.close_window.push(value);
if self.high_window.is_full() {
// Calculate raw %K
if let Some(raw_k) = Self::calculate_raw_k(
&self.high_window.as_slice(),
&self.low_window.as_slice(),
value,
) {
// Smooth %K if needed
let k_value = if self.smooth_k > 1 {
self.k_sma.update(raw_k)?
} else {
Some(raw_k)
};
if let Some(k) = k_value {
self.k_values.push(k);
// Calculate %D
if let Some(d) = self.d_sma.update(k)? {
return Ok(Some(d));
}
}
}
}
Ok(None)
}
fn current(&self) -> Option<f64> {
self.d_sma.current()
}
}
/// Structure to hold Stochastic values
pub struct StochasticValues {
pub k: f64,
pub d: f64,
}
impl Stochastic {
/// Get current %K and %D values
pub fn current_values(&self) -> Option<StochasticValues> {
if let (Some(&k), Some(d)) = (self.k_values.iter().last(), self.d_sma.current()) {
Some(StochasticValues { k, d })
} else {
None
}
}
/// Update with separate high, low, close values
pub fn update_hlc(
&mut self,
high: f64,
low: f64,
close: f64,
) -> Result<Option<StochasticValues>, IndicatorError> {
self.high_window.push(high);
self.low_window.push(low);
self.close_window.push(close);
if self.high_window.is_full() {
if let Some(raw_k) = Self::calculate_raw_k(
&self.high_window.as_slice(),
&self.low_window.as_slice(),
close,
) {
let k_value = if self.smooth_k > 1 {
self.k_sma.update(raw_k)?
} else {
Some(raw_k)
};
if let Some(k) = k_value {
self.k_values.push(k);
if let Some(d) = self.d_sma.update(k)? {
return Ok(Some(StochasticValues { k, d }));
}
}
}
}
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stochastic_calculation() {
let high = vec![
127.01, 127.62, 126.59, 127.35, 128.17, 128.43, 127.37, 126.42, 126.90, 126.85, 125.65,
125.72, 127.16, 127.72, 127.69, 128.0,
];
let low = vec![
125.36, 126.16, 124.93, 126.09, 126.82, 126.48, 126.03, 124.83, 126.39, 125.72, 124.56,
124.57, 125.07, 126.86, 126.63, 126.0,
];
let close = vec![
125.36, 126.16, 124.93, 126.09, 126.82, 126.48, 126.03, 124.83, 126.39, 125.72, 124.56,
124.57, 125.07, 126.86, 126.63, 127.0,
];
let (k_values, d_values) =
Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
// 14-bar K + 3-value D needs 16 bars, not the old 15-bar fixture.
assert_eq!(k_values.len(), 3);
assert_eq!(d_values.len(), 1);
assert!((d_values[0] - k_values.iter().sum::<f64>() / 3.0).abs() < 1e-10);
let (_, warming_d) =
Stochastic::calculate_series(&high[..15], &low[..15], &close[..15], 14, 3, 1).unwrap();
assert!(warming_d.is_empty());
// %K should be between 0 and 100
for k in &k_values {
assert!(*k >= 0.0 && *k <= 100.0);
}
}
#[test]
fn test_stochastic_extremes() {
// When close is at highest high, %K should be 100
let high = vec![10.0; 14];
let low = vec![5.0; 14];
let mut close = vec![7.5; 14];
close[13] = 10.0; // Last close at high
let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
assert!((k_values[0] - 100.0).abs() < 1e-10);
// When close is at lowest low, %K should be 0
close[13] = 5.0; // Last close at low
let (k_values, _) = Stochastic::calculate_series(&high, &low, &close, 14, 3, 1).unwrap();
assert!(k_values[0].abs() < 1e-10);
}
#[test]
fn test_stochastic_invalid_periods_do_not_panic() {
for (k, d, smooth) in [(0, 3, 1), (3, 0, 1), (3, 3, 0)] {
assert!(Stochastic::new(k, d, smooth).is_err());
assert!(
Stochastic::calculate_series(&[10.0; 5], &[0.0; 5], &[5.0; 5], k, d, smooth)
.is_err()
);
}
}
#[test]
fn test_stochastic_golden_values_and_incremental_parity() {
let high = vec![10.0, 11.0, 12.0, 13.0, 14.0, 15.0];
let low = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let close = vec![5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
for smooth in [1, 2] {
let (k, d) = Stochastic::calculate_series(&high, &low, &close, 3, 2, smooth).unwrap();
for value in k.iter().chain(d.iter()) {
assert!((value - 100.0 * 7.0 / 12.0).abs() < 1e-10);
}
let mut incremental = Stochastic::new(3, 2, smooth).unwrap();
let mut actual = Vec::new();
for i in 0..high.len() {
if let Some(value) = incremental.update_hlc(high[i], low[i], close[i]).unwrap() {
actual.push(value.d);
}
}
assert_eq!(actual.len(), d.len());
for (a, b) in actual.iter().zip(d.iter()) {
assert!((a - b).abs() < 1e-10);
}
}
let (k, d) =
Stochastic::calculate_series(&high[..3], &low[..3], &close[..3], 3, 2, 2).unwrap();
assert!(k.is_empty() && d.is_empty());
}
}

View file

@ -5,6 +5,7 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
@ -12,6 +13,7 @@ import { createContainer } from './simple-container';
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('orchestrator');
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
const logger = getLogger('orchestrator');
// Get service-specific config
@ -58,6 +60,7 @@ async function main() {
credentials: config.services?.webApi?.cors?.credentials ?? true,
})
);
security.mount(app);
// Logging middleware
app.use('*', async (c, next) => {
@ -75,7 +78,8 @@ async function main() {
try {
server = Bun.serve({
port: PORT,
hostname: '0.0.0.0', // Explicitly bind to all interfaces
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
fetch: async req => {
services.logger.debug(`Incoming request: ${req.method} ${req.url}`);
try {

View file

@ -18,7 +18,11 @@ if (config.queue) {
// Log the full configuration
const logger = getLogger('web-api');
logger.info('Service configuration:', config);
logger.info('Service configuration:', {
service: 'web-api',
port: config.service.port,
environment: config.environment,
});
// Import and start WebSocket-enabled server
import('./server-with-websocket').then(({ startServerWithWebSocket }) => {

View file

@ -5,24 +5,32 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { createBacktestRoutes } from './backtest.routes';
import { createBacktestV2Routes } from './backtests-v2.routes';
import { createExchangeRoutes } from './exchange.routes';
import { createHealthRoutes } from './health.routes';
import { createMonitoringRoutes } from './monitoring.routes';
import { createPipelineRoutes } from './pipeline.routes';
import { createBacktestRoutes } from './backtest.routes';
import { createBacktestV2Routes } from './backtests-v2.routes';
export function createRoutes(container: IServiceContainer): Hono {
export function createRoutes(
container: IServiceContainer,
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
): Hono {
const app = new Hono();
// Add CORS middleware
app.use('*', cors({
origin: ['http://localhost:4200', 'http://localhost:3000', 'http://localhost:3002', 'http://localhost:5173', 'http://localhost:5174'],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
app.use(
'*',
cors({
origin: security.allowedOrigins,
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: true,
})
);
security.mount(app);
// Create routes with container
const healthRoutes = createHealthRoutes(container);

View file

@ -6,6 +6,7 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { parseReferenceDataResetRequest } from '@stock-bot/types';
import { PipelineService } from '../services/pipeline.service';
const logger = getLogger('pipeline-routes');
@ -48,6 +49,9 @@ export function createPipelineRoutes(container: IServiceContainer) {
});
pipeline.post('/exchanges/all', async c => {
if (c.req.query('clear') && c.req.query('clear') !== 'false') {
return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400);
}
try {
const clearFirst = c.req.query('clear') === 'true';
const result = await pipelineService.syncAllExchanges(clearFirst);
@ -92,9 +96,15 @@ export function createPipelineRoutes(container: IServiceContainer) {
// Clear data endpoint
pipeline.post('/clear/postgresql', async c => {
const input: unknown = await c.req.json().catch(() => null);
let reset;
try {
const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all';
const result = await pipelineService.clearPostgreSQLData(dataType || 'all');
reset = parseReferenceDataResetRequest(input);
} catch (error) {
return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400);
}
try {
const result = await pipelineService.clearPostgreSQLData(reset.type, reset.confirmation);
return c.json(result, result.success ? 200 : 503);
} catch (error) {
logger.error('Error in POST /clear/postgresql', { error });

View file

@ -1,4 +1,5 @@
import type { Server, ServerWebSocket } from 'bun';
import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import {
@ -10,13 +11,20 @@ import {
const logger = getLogger('websocket-routes');
export function createWebSocketRoute(container: IServiceContainer) {
export function createWebSocketRoute(
container: IServiceContainer,
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
) {
const wsHandler = createWebSocketHandler(container);
// Make the handler available globally for other services
setWebSocketHandler(wsHandler);
return (request: Request, server: Pick<Server, 'upgrade'>) => {
const rejection = security.authorize(request);
if (rejection) {
return rejection;
}
const url = new URL(request.url);
const runId = url.searchParams.get('runId');

View file

@ -1,3 +1,4 @@
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
@ -7,6 +8,11 @@ import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('webApi');
const security = createHttpSecurity({
...httpSecurityOptions(),
environment: config.environment,
browserSessions: true,
});
// Override queue settings for web-api (no workers needed)
if (config.queue) {
@ -17,7 +23,11 @@ if (config.queue) {
// Log the full configuration
const logger = getLogger('web-api');
logger.info('Service configuration:', config);
logger.info('Service configuration:', {
service: 'web-api',
port: config.service.port,
environment: config.environment,
});
// Container factory function
async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) {
@ -56,10 +66,10 @@ export async function startServerWithWebSocket() {
container = diContainer.resolve('serviceContainer');
// Create HTTP routes
const routes = createRoutes(container);
const routes = createRoutes(container, security);
// Create WebSocket route handler
const wsRoute = createWebSocketRoute(container);
const wsRoute = createWebSocketRoute(container, security);
// Start server with WebSocket support
const port = config.service.port || 2003;
@ -70,6 +80,8 @@ export async function startServerWithWebSocket() {
try {
server = Bun.serve<RunSocketData, {}>({
port,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
// Handle HTTP requests
async fetch(req, server) {

View file

@ -1,5 +1,6 @@
import { randomUUID as uuidv4 } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import { authenticatedServiceFetch } from '@stock-bot/di';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
@ -64,7 +65,7 @@ export class BacktestServiceV2 {
constructor(
container: IServiceContainer,
private readonly request: BacktestTransport = fetch
private readonly request: BacktestTransport = authenticatedServiceFetch
) {
this.container = requireServices(container, 'postgres');
logger.info('BacktestServiceV2 initialized');

View file

@ -6,6 +6,7 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { getFullQueueName } from '@stock-bot/queue';
import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types';
const logger = getLogger('pipeline-service');
@ -119,6 +120,9 @@ export class PipelineService {
*/
async syncAllExchanges(clearFirst: boolean = false): Promise<PipelineJobResult> {
try {
if (clearFirst) {
throw new Error('Sync is non-destructive; use the explicit maintenance reset');
}
const queueManager = this.container.queueManager;
if (!queueManager) {
return { success: false, error: 'Queue manager not available' };
@ -246,9 +250,11 @@ export class PipelineService {
* Clear PostgreSQL data
*/
async clearPostgreSQLData(
dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all'
dataType: ReferenceDataResetScope,
confirmation: string
): Promise<PipelineJobResult> {
try {
const payload = parseReferenceDataResetRequest({ type: dataType, confirmation });
const queueManager = this.container.queueManager;
if (!queueManager) {
return { success: false, error: 'Queue manager not available' };
@ -258,7 +264,7 @@ export class PipelineService {
const job = await exchangesQueue.add('clear-postgresql-data', {
handler: 'exchanges',
operation: 'clear-postgresql-data',
payload: { dataType },
payload,
});
logger.info('PostgreSQL data clear job queued', { jobId: job.id, dataType });

View file

@ -1,48 +1,54 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { Layout } from '@/components/layout';
import { BacktestDetailPageV2, BacktestListPageV2 } from '@/features/backtest';
import { DashboardPage } from '@/features/dashboard';
import { ExchangesPage } from '@/features/exchanges';
import { MonitoringPage } from '@/features/monitoring';
import { PipelinePage } from '@/features/pipeline';
import { BacktestListPageV2, BacktestDetailPageV2 } from '@/features/backtest';
import { SymbolsPage, SymbolDetailPage } from '@/features/symbols';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
import { AuthGate } from './AuthGate';
export function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Navigate to="/dashboard" replace />} />
<Route path="dashboard" element={<DashboardPage />} />
<Route path="symbols">
<Route index element={<SymbolsPage />} />
<Route path=":symbol" element={<SymbolDetailPage />} />
</Route>
<Route path="exchanges" element={<ExchangesPage />} />
<Route
path="portfolio"
element={<div className="p-4">Portfolio Page - Coming Soon</div>}
/>
<Route
path="strategies"
element={<div className="p-4">Strategies Page - Coming Soon</div>}
/>
<Route
path="analytics"
element={<div className="p-4">Analytics Page - Coming Soon</div>}
/>
<Route path="backtests">
<Route index element={<BacktestListPageV2 />} />
<Route path=":id">
<Route index element={<BacktestDetailPageV2 />} />
<Route path="run/:runId" element={<BacktestDetailPageV2 />} />
<AuthGate>
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Navigate to="/dashboard" replace />} />
<Route path="dashboard" element={<DashboardPage />} />
<Route path="symbols">
<Route index element={<SymbolsPage />} />
<Route path=":symbol" element={<SymbolDetailPage />} />
</Route>
<Route path="exchanges" element={<ExchangesPage />} />
<Route
path="portfolio"
element={<div className="p-4">Portfolio Page - Coming Soon</div>}
/>
<Route
path="strategies"
element={<div className="p-4">Strategies Page - Coming Soon</div>}
/>
<Route
path="analytics"
element={<div className="p-4">Analytics Page - Coming Soon</div>}
/>
<Route path="backtests">
<Route index element={<BacktestListPageV2 />} />
<Route path=":id">
<Route index element={<BacktestDetailPageV2 />} />
<Route path="run/:runId" element={<BacktestDetailPageV2 />} />
</Route>
</Route>
<Route
path="settings"
element={<div className="p-4">Settings Page - Coming Soon</div>}
/>
<Route path="system/monitoring" element={<MonitoringPage />} />
<Route path="system/pipeline" element={<PipelinePage />} />
</Route>
<Route path="settings" element={<div className="p-4">Settings Page - Coming Soon</div>} />
<Route path="system/monitoring" element={<MonitoringPage />} />
<Route path="system/pipeline" element={<PipelinePage />} />
</Route>
</Routes>
</BrowserRouter>
</Routes>
</BrowserRouter>
</AuthGate>
);
}

View file

@ -0,0 +1,118 @@
import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react';
import { API_BASE_URL } from '@/lib/api';
export function AuthGate({ children }: { children: ReactNode }) {
const [role, setRole] = useState<string | null>(null);
const [checking, setChecking] = useState(true);
const [token, setToken] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const checkSession = useCallback(async () => {
try {
const response = await fetch(`${API_BASE_URL}/api/auth/session`, { credentials: 'include' });
const session = await response.json();
setRole(response.ok && session.authenticated ? session.role : null);
} catch {
setError('Cannot reach the API. Check its URL and service status.');
} finally {
setChecking(false);
}
}, []);
useEffect(() => {
void checkSession();
const expired = () => setRole(null);
window.addEventListener('stock-bot-auth-required', expired);
return () => window.removeEventListener('stock-bot-auth-required', expired);
}, [checkSession]);
const signIn = async (event: FormEvent) => {
event.preventDefault();
setBusy(true);
setError('');
try {
const response = await fetch(`${API_BASE_URL}/api/auth/session`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
if (!response.ok) {
throw new Error(
response.status === 429
? 'Too many attempts. Try again in a minute.'
: 'Sign-in failed. Check your access token.'
);
}
const session = await response.json();
setRole(session.role);
} catch (failure) {
setError(failure instanceof Error ? failure.message : 'Sign-in failed');
} finally {
setToken('');
setBusy(false);
}
};
const signOut = async () => {
try {
const response = await fetch(`${API_BASE_URL}/api/auth/session`, {
method: 'DELETE',
credentials: 'include',
});
if (!response.ok) {
throw new Error('Sign-out failed');
}
setRole(null);
} catch {
setError('Sign-out failed. Please try again.');
}
};
if (checking) {
return (
<p className="p-8" role="status">
Checking access…
</p>
);
}
if (role) {
return (
<>
{children}
<div className="fixed bottom-3 right-3 z-50 rounded bg-surface p-2 text-xs border border-border">
{role === 'read' ? 'Read-only access' : 'Administrator access'}
<button className="ml-3 underline" onClick={() => void signOut()}>
Sign out
</button>
{error && (
<span role="alert" className="ml-3">
{error}
</span>
)}
</div>
</>
);
}
return (
<main className="min-h-screen flex items-center justify-center p-6">
<form onSubmit={event => void signIn(event)} className="w-full max-w-sm space-y-4">
<h1 className="text-xl">Stock Bot access</h1>
<p>Enter your administrator or read-only access token. It is not stored in your browser.</p>
<label className="block" htmlFor="access-token">
Access token
</label>
<input
id="access-token"
type="password"
autoComplete="off"
required
value={token}
onChange={event => setToken(event.target.value)}
className="w-full rounded border p-2 bg-surface"
/>
{error && <p role="alert">{error}</p>}
<button type="submit" disabled={busy} className="rounded border px-4 py-2">
{busy ? 'Signing in…' : 'Sign in'}
</button>
</form>
</main>
);
}

View file

@ -1,8 +1,7 @@
import type { BacktestRunResult } from '@stock-bot/types';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import { browserLog } from '@/utils/browserLog';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
export interface Backtest {
id: string;
name: string;

View file

@ -1,6 +1,7 @@
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import type { CandlestickData, ChartInterval, MarketData } from '../types';
const API_BASE = '/api/market-data';
const API_BASE = `${API_BASE_URL}/api/market-data`;
export class ChartDataService {
static async getHistoricalData(

View file

@ -1,3 +1,4 @@
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import type {
ApiResponse,
CreateExchangeRequest,
@ -11,8 +12,6 @@ import type {
UpdateProviderMappingRequest,
} from '../types/index';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
class ExchangeApiService {
private async request<T>(endpoint: string, options?: RequestInit): Promise<ApiResponse<T>> {
const url = `${API_BASE_URL}/api${endpoint}`;

View file

@ -1,3 +1,4 @@
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
/**
* Monitoring API Service
*/
@ -12,7 +13,6 @@ import type {
SystemOverview,
} from '../types';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
const MONITORING_BASE = `${API_BASE_URL}/api/system/monitoring`;
export const monitoringApi = {

View file

@ -96,7 +96,6 @@ export function PipelinePage() {
} = usePipeline();
const [selectedProvider, setSelectedProvider] = useState('yahoo');
const [clearFirst, setClearFirst] = useState(false);
const [clearDataType, setClearDataType] = useState<'all' | 'exchanges' | 'provider_mappings'>(
'all'
);
@ -132,7 +131,7 @@ export function PipelinePage() {
await syncQMExchanges();
break;
case 'sync-all-exchanges':
await syncAllExchanges(clearFirst);
await syncAllExchanges(false);
break;
case 'sync-qm-provider-mappings':
await syncQMProviderMappings();
@ -141,12 +140,14 @@ export function PipelinePage() {
await syncIBExchanges();
break;
case 'clear-postgresql':
if (
confirm(
`Are you sure you want to clear ${clearDataType} data? This action cannot be undone.`
)
) {
await clearPostgreSQLData(clearDataType);
{
const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`;
const confirmation = prompt(
`This permanently deletes ${clearDataType} reference data. Type ${expected} to continue.`
);
if (confirmation === expected) {
await clearPostgreSQLData(clearDataType, confirmation);
}
}
break;
}
@ -340,20 +341,6 @@ export function PipelinePage() {
</div>
)}
{op.id === 'sync-all-exchanges' && (
<div className="mb-2">
<label className="flex items-center gap-2 text-xs">
<input
type="checkbox"
checked={clearFirst}
onChange={e => setClearFirst(e.target.checked)}
className="rounded border-border text-primary-500 focus:ring-primary-500"
/>
<span className="text-text-secondary">Clear existing data first</span>
</label>
</div>
)}
<button
onClick={() => handleOperation(op)}
disabled={loading}

View file

@ -72,8 +72,8 @@ export function usePipeline() {
// Maintenance operations
const clearPostgreSQLData = useCallback(
(dataType: DataClearType = 'all') =>
executeOperation(() => pipelineApi.clearPostgreSQLData(dataType)),
(dataType: DataClearType, confirmation: string) =>
executeOperation(() => pipelineApi.clearPostgreSQLData(dataType, confirmation)),
[executeOperation]
);

View file

@ -1,10 +1,9 @@
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import type { DataClearType, PipelineJobResult, PipelineStatsResult } from '../types';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
class PipelineApiService {
private async request<T = unknown>(endpoint: string, options?: RequestInit): Promise<T> {
const url = `${API_BASE_URL}/pipeline${endpoint}`;
const url = `${API_BASE_URL}/api/pipeline${endpoint}`;
const response = await fetch(url, {
headers: {
@ -56,9 +55,11 @@ class PipelineApiService {
return this.request<PipelineJobResult>('/status');
}
async clearPostgreSQLData(dataType: DataClearType = 'all'): Promise<PipelineJobResult> {
const params = `?type=${dataType}`;
return this.request<PipelineJobResult>(`/clear/postgresql${params}`, { method: 'POST' });
async clearPostgreSQLData(type: DataClearType, confirmation: string): Promise<PipelineJobResult> {
return this.request<PipelineJobResult>('/clear/postgresql', {
method: 'POST',
body: JSON.stringify({ type, confirmation }),
});
}
// Statistics operations

View file

@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { API_BASE_URL } from '@/lib/api';
import { browserLog } from '@/utils/browserLog';
export interface WebSocketMessage {
@ -55,7 +56,10 @@ export function useWebSocket({
reconnectTimeoutRef.current = null;
}
const wsUrl = `ws://localhost:2003/ws?runId=${runId}`;
const url = new URL('/ws', API_BASE_URL);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('runId', runId);
const wsUrl = url.toString();
browserLog.log('Connecting to WebSocket:', wsUrl);
try {

View file

@ -0,0 +1,14 @@
const developmentApi = new URL(window.location.origin);
developmentApi.port = '2003';
export const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL ||
(import.meta.env.PROD ? window.location.origin : developmentApi.origin);
/** Browser credentials are HttpOnly cookies, never bundled or stored access tokens. */
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const response = await window.fetch(input, { ...init, credentials: 'include' });
if (response.status === 401) {
window.dispatchEvent(new Event('stock-bot-auth-required'));
}
return response;
}

View file

@ -12,6 +12,6 @@ export default defineConfig({
},
server: {
port: 3000,
host: true,
host: '127.0.0.1',
},
});

View file

@ -106,6 +106,7 @@
"@stock-bot/services": "workspace:*",
"@stock-bot/shutdown": "*",
"@stock-bot/stock-config": "*",
"@stock-bot/types": "workspace:*",
"hono": "^4.0.0",
},
"devDependencies": {

View file

@ -1,32 +1,32 @@
# Development override for Docker Compose
# Use: docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
version: '3.8'
services: # Development overrides for faster feedback
dragonfly:
command: >
dragonfly
--logtostderr
--maxmemory=512mb
--save_schedule=""
--bind=0.0.0.0
ports:
- "6379:6379"
postgres:
environment:
POSTGRES_DB: trading_bot_dev
POSTGRES_USER: dev_user
POSTGRES_PASSWORD: dev_pass
ports:
- "5432:5432"
# Disable monitoring in development to save resources
prometheus:
profiles:
- monitoring
grafana:
profiles:
- monitoring
# Development override for Docker Compose
# Use: docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
version: '3.8'
services: # Development overrides for faster feedback
dragonfly:
command: >
dragonfly
--logtostderr
--maxmemory=512mb
--save_schedule=""
--bind=0.0.0.0
ports:
- '127.0.0.1:6379:6379'
postgres:
environment:
POSTGRES_DB: trading_bot_dev
POSTGRES_USER: dev_user
POSTGRES_PASSWORD: dev_pass
ports:
- '127.0.0.1:5432:5432'
# Disable monitoring in development to save resources
prometheus:
profiles:
- monitoring
grafana:
profiles:
- monitoring

View file

@ -1,237 +1,237 @@
services: # Dragonfly - Redis replacement for caching and events
dragonfly:
image: docker.dragonflydb.io/dragonflydb/dragonfly:latest
container_name: trading-bot-dragonfly
ports:
- "6379:6379"
deploy:
resources:
limits:
cpus: '4.0' # Use up to 4 CPU cores
memory: 8G # Use up to 8GB RAM
reservations:
cpus: '2.0' # Reserve at least 2 CPU cores
memory: 4G # Reserve at least 4GB RAM
command:
- dragonfly
- --logtostderr
- --maxmemory=8gb
- --proactor_threads=8
- --bind=0.0.0.0
- --admin_port=6380
- --cluster_mode=emulated
- --hz=500
- --tcp_keepalive=60
- --conn_use_incoming_cpu=true
- --lock_on_hashtags
- --default_lua_flags=allow-undeclared-keys
volumes:
- dragonfly_data:/data
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network
# PostgreSQL - Operational data (orders, positions, strategies)
postgres:
image: postgres:16-alpine
container_name: trading-bot-postgres
environment:
POSTGRES_DB: trading_bot
POSTGRES_USER: trading_user
POSTGRES_PASSWORD: trading_pass_dev
POSTGRES_INITDB_ARGS: "--encoding=UTF-8"
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./database/postgres/init:/docker-entrypoint-initdb.d
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U trading_user -d trading_bot"]
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network
# QuestDB - Time-series data (OHLCV, indicators, performance)
questdb:
image: questdb/questdb:latest
container_name: trading-bot-questdb
ports:
- "9000:9000" # Web console
- "8812:8812" # PostgreSQL wire protocol
- "9009:9009" # InfluxDB line protocol
volumes:
- questdb_data:/var/lib/questdb
environment:
- QDB_TELEMETRY_ENABLED=false
restart: unless-stopped
networks:
- trading-bot-network
# MongoDB - Document storage (sentiment, raw docs, unstructured data)
mongodb:
image: mongo:7-jammy
container_name: trading-bot-mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: trading_admin
MONGO_INITDB_ROOT_PASSWORD: trading_mongo_dev
MONGO_INITDB_DATABASE: stock
ports:
- "27017:27017"
command: --wiredTigerCacheSizeGB 20
volumes:
- mongodb_data:/data/db
- ./database/mongodb/init:/docker-entrypoint-initdb.d
restart: unless-stopped
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network # Redis Insight - GUI for Dragonfly debugging
redis-insight:
image: redislabs/redisinsight:latest
container_name: trading-bot-redis-insight
ports:
- "8001:5540"
depends_on:
- dragonfly
restart: unless-stopped
networks:
- trading-bot-network
# PgAdmin - PostgreSQL GUI
pgadmin:
image: dpage/pgadmin4:latest
container_name: trading-bot-pgadmin
environment:
PGADMIN_DEFAULT_EMAIL: admin@tradingbot.com
PGADMIN_DEFAULT_PASSWORD: admin123
PGADMIN_CONFIG_SERVER_MODE: 'False'
PGADMIN_DISABLE_POSTFIX: 'true'
ports:
- "8080:80"
volumes:
- pgadmin_data:/var/lib/pgadmin
depends_on:
- postgres
restart: unless-stopped
networks:
- trading-bot-network
# Mongo Express - MongoDB GUI
mongo-express:
image: mongo-express:latest
container_name: trading-bot-mongo-express
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: trading_admin
ME_CONFIG_MONGODB_ADMINPASSWORD: trading_mongo_dev
ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_PORT: 27017
ME_CONFIG_BASICAUTH_USERNAME: admin
ME_CONFIG_BASICAUTH_PASSWORD: admin123
ports:
- "8081:8081"
depends_on:
- mongodb
restart: unless-stopped
networks:
- trading-bot-network
# Prometheus - Metrics collection
prometheus:
image: prom/prometheus:latest
container_name: trading-bot-prometheus
ports:
- "9090:9090"
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--web.enable-lifecycle'
restart: unless-stopped
networks:
- trading-bot-network
# Loki - Log aggregation
loki:
image: grafana/loki:2.9.2
container_name: trading-bot-loki
ports:
- "3100:3100"
volumes:
- loki_data:/loki
- ./monitoring/loki:/etc/loki
command: -config.file=/etc/loki/loki-config.yaml
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:3100/ready"]
interval: 30s
timeout: 10s
retries: 3
restart: unless-stopped
networks:
- trading-bot-network
# Grafana - Visualization for logs and metrics
grafana:
image: grafana/grafana:10.2.0
container_name: trading-bot-grafana
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_SECURITY_ADMIN_USER=admin
- GF_PATHS_PROVISIONING=/etc/grafana/provisioning
- GF_USERS_ALLOW_SIGN_UP=false
volumes:
- grafana_data:/var/lib/grafana
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning
depends_on:
- prometheus
- loki
restart: unless-stopped
networks:
- trading-bot-network
# Bull Board - Queue monitoring
bull-board:
image: venatum/bull-board:latest
container_name: trading-bot-bull-board
ports:
- "3001:3000"
environment:
- REDIS_HOST=dragonfly
- REDIS_PORT=6379
- REDIS_PASSWORD=
- REDIS_DB=0
- REDIS_URL=redis://dragonfly:6379/0
depends_on:
- dragonfly
restart: unless-stopped
networks:
- trading-bot-network
volumes:
postgres_data:
questdb_data:
dragonfly_data:
mongodb_data:
pgadmin_data:
prometheus_data:
grafana_data:
loki_data:
networks:
trading-bot-network:
driver: bridge
services: # Dragonfly - Redis replacement for caching and events
dragonfly:
image: docker.dragonflydb.io/dragonflydb/dragonfly:latest
container_name: trading-bot-dragonfly
ports:
- '127.0.0.1:6379:6379'
deploy:
resources:
limits:
cpus: '4.0' # Use up to 4 CPU cores
memory: 8G # Use up to 8GB RAM
reservations:
cpus: '2.0' # Reserve at least 2 CPU cores
memory: 4G # Reserve at least 4GB RAM
command:
- dragonfly
- --logtostderr
- --maxmemory=8gb
- --proactor_threads=8
- --bind=0.0.0.0
- --admin_port=6380
- --cluster_mode=emulated
- --hz=500
- --tcp_keepalive=60
- --conn_use_incoming_cpu=true
- --lock_on_hashtags
- --default_lua_flags=allow-undeclared-keys
volumes:
- dragonfly_data:/data
restart: unless-stopped
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network
# PostgreSQL - Operational data (orders, positions, strategies)
postgres:
image: postgres:16-alpine
container_name: trading-bot-postgres
environment:
POSTGRES_DB: trading_bot
POSTGRES_USER: trading_user
POSTGRES_PASSWORD: trading_pass_dev
POSTGRES_INITDB_ARGS: '--encoding=UTF-8'
ports:
- '127.0.0.1:5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/data
- ./database/postgres/init:/docker-entrypoint-initdb.d
restart: unless-stopped
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U trading_user -d trading_bot']
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network
# QuestDB - Time-series data (OHLCV, indicators, performance)
questdb:
image: questdb/questdb:latest
container_name: trading-bot-questdb
ports:
- '127.0.0.1:9000:9000' # Web console
- '127.0.0.1:8812:8812' # PostgreSQL wire protocol
- '127.0.0.1:9009:9009' # InfluxDB line protocol
volumes:
- questdb_data:/var/lib/questdb
environment:
- QDB_TELEMETRY_ENABLED=false
restart: unless-stopped
networks:
- trading-bot-network
# MongoDB - Document storage (sentiment, raw docs, unstructured data)
mongodb:
image: mongo:7-jammy
container_name: trading-bot-mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: trading_admin
MONGO_INITDB_ROOT_PASSWORD: trading_mongo_dev
MONGO_INITDB_DATABASE: stock
ports:
- '127.0.0.1:27017:27017'
command: --wiredTigerCacheSizeGB 20
volumes:
- mongodb_data:/data/db
- ./database/mongodb/init:/docker-entrypoint-initdb.d
restart: unless-stopped
healthcheck:
test: ['CMD', 'mongosh', '--eval', "db.adminCommand('ping')"]
interval: 30s
timeout: 10s
retries: 3
networks:
- trading-bot-network # Redis Insight - GUI for Dragonfly debugging
redis-insight:
image: redislabs/redisinsight:latest
container_name: trading-bot-redis-insight
ports:
- '127.0.0.1:8001:5540'
depends_on:
- dragonfly
restart: unless-stopped
networks:
- trading-bot-network
# PgAdmin - PostgreSQL GUI
pgadmin:
image: dpage/pgadmin4:latest
container_name: trading-bot-pgadmin
environment:
PGADMIN_DEFAULT_EMAIL: admin@tradingbot.com
PGADMIN_DEFAULT_PASSWORD: admin123
PGADMIN_CONFIG_SERVER_MODE: 'False'
PGADMIN_DISABLE_POSTFIX: 'true'
ports:
- '127.0.0.1:8080:80'
volumes:
- pgadmin_data:/var/lib/pgadmin
depends_on:
- postgres
restart: unless-stopped
networks:
- trading-bot-network
# Mongo Express - MongoDB GUI
mongo-express:
image: mongo-express:latest
container_name: trading-bot-mongo-express
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: trading_admin
ME_CONFIG_MONGODB_ADMINPASSWORD: trading_mongo_dev
ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_PORT: 27017
ME_CONFIG_BASICAUTH_USERNAME: admin
ME_CONFIG_BASICAUTH_PASSWORD: admin123
ports:
- '127.0.0.1:8081:8081'
depends_on:
- mongodb
restart: unless-stopped
networks:
- trading-bot-network
# Prometheus - Metrics collection
prometheus:
image: prom/prometheus:latest
container_name: trading-bot-prometheus
ports:
- '127.0.0.1:9090:9090'
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--web.enable-lifecycle'
restart: unless-stopped
networks:
- trading-bot-network
# Loki - Log aggregation
loki:
image: grafana/loki:2.9.2
container_name: trading-bot-loki
ports:
- '127.0.0.1:3100:3100'
volumes:
- loki_data:/loki
- ./monitoring/loki:/etc/loki
command: -config.file=/etc/loki/loki-config.yaml
healthcheck:
test: ['CMD', 'wget', '-q', '--spider', 'http://localhost:3100/ready']
interval: 30s
timeout: 10s
retries: 3
restart: unless-stopped
networks:
- trading-bot-network
# Grafana - Visualization for logs and metrics
grafana:
image: grafana/grafana:10.2.0
container_name: trading-bot-grafana
ports:
- '127.0.0.1:3000:3000'
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_SECURITY_ADMIN_USER=admin
- GF_PATHS_PROVISIONING=/etc/grafana/provisioning
- GF_USERS_ALLOW_SIGN_UP=false
volumes:
- grafana_data:/var/lib/grafana
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning
depends_on:
- prometheus
- loki
restart: unless-stopped
networks:
- trading-bot-network
# Bull Board - Queue monitoring
bull-board:
image: venatum/bull-board:latest
container_name: trading-bot-bull-board
ports:
- '127.0.0.1:3001:3000'
environment:
- REDIS_HOST=dragonfly
- REDIS_PORT=6379
- REDIS_PASSWORD=
- REDIS_DB=0
- REDIS_URL=redis://dragonfly:6379/0
depends_on:
- dragonfly
restart: unless-stopped
networks:
- trading-bot-network
volumes:
postgres_data:
questdb_data:
dragonfly_data:
mongodb_data:
pgadmin_data:
prometheus_data:
grafana_data:
loki_data:
networks:
trading-bot-network:
driver: bridge

View file

@ -0,0 +1,277 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import type { Hono, MiddlewareHandler } from 'hono';
type Role = 'read' | 'admin' | 'service';
export interface HttpSecurityOptions {
readToken?: string;
adminToken?: string;
serviceToken?: string;
disabled?: boolean;
environment?: string;
hostname?: string;
origins?: string[];
browserSessions?: boolean;
}
const cookieName = 'stock_bot_session';
const sessionSeconds = 3600;
const digest = (value: string) => createHash('sha256').update(value).digest();
const equal = (a: string, b: string) => timingSafeEqual(digest(a), digest(b));
export function httpSecurityOptions(env: NodeJS.ProcessEnv = process.env): HttpSecurityOptions {
return {
readToken: env.STOCK_BOT_READ_TOKEN,
adminToken: env.STOCK_BOT_ADMIN_TOKEN,
serviceToken: env.STOCK_BOT_SERVICE_TOKEN,
disabled: env.STOCK_BOT_AUTH_DISABLED === 'true',
environment: env.NODE_ENV ?? 'development',
hostname: env.STOCK_BOT_HTTP_HOST ?? '127.0.0.1',
origins: env.STOCK_BOT_ALLOWED_ORIGINS?.split(',')
.map(origin => origin.trim())
.filter(Boolean),
};
}
/** A small operator boundary, not a multi-user identity provider. Secure by default. */
export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOptions()) {
const environment = options.environment ?? 'development';
const hostname = options.hostname ?? '127.0.0.1';
const disabled = options.disabled === true;
if (
disabled &&
(environment === 'production' || !['127.0.0.1', '::1', 'localhost'].includes(hostname))
) {
throw new Error(
'Authentication may only be disabled on an explicit loopback development/test listener'
);
}
const tokens = {
read: options.readToken,
admin: options.adminToken,
service: options.serviceToken,
};
if (!disabled) {
if (!tokens.admin || !tokens.service) {
throw new Error(
'Set STOCK_BOT_ADMIN_TOKEN and STOCK_BOT_SERVICE_TOKEN before starting HTTP services'
);
}
const values = Object.values(tokens).filter((value): value is string => !!value);
if (
values.some(value => value.length < 32 || value.trim() !== value) ||
new Set(values).size !== values.length
) {
throw new Error(
'HTTP access tokens must be distinct, unpadded secrets of at least 32 characters'
);
}
}
const allowedOrigins =
options.origins ??
(environment === 'production'
? []
: [
'http://localhost:3000',
'http://localhost:4200',
'http://localhost:5173',
'http://localhost:5174',
'http://127.0.0.1:3000',
'http://127.0.0.1:5173',
]);
if (allowedOrigins.includes('*') || allowedOrigins.includes('null')) {
throw new Error('Explicit trusted HTTP origins are required');
}
const originAllowed = (request: Request) => {
const origin = request.headers.get('origin');
return !!origin && (origin === new URL(request.url).origin || allowedOrigins.includes(origin));
};
const signingKey = (role: 'read' | 'admin') => tokens[role];
const signature = (payload: string, key: string) =>
createHmac('sha256', key).update(`stock-bot-ui:${payload}`).digest('base64url');
function roleForToken(value: string): Role | undefined {
for (const role of ['read', 'admin', 'service'] as const) {
if (tokens[role] && equal(value, tokens[role])) {
return role;
}
}
return undefined;
}
function authenticate(request: Request): { role: Role; cookie: boolean } | undefined {
if (disabled) {
return { role: 'admin', cookie: false };
}
const authorization = request.headers.get('authorization');
if (authorization) {
const match = /^Bearer ([^\s]+)$/i.exec(authorization);
const role = match?.[1] ? roleForToken(match[1]) : undefined;
return role ? { role, cookie: false } : undefined;
}
if (!options.browserSessions) {
return undefined;
}
const value = request.headers
.get('cookie')
?.split(';')
.map(part => part.trim())
.find(part => part.startsWith(`${cookieName}=`))
?.slice(cookieName.length + 1);
if (!value || value.length > 512) {
return;
}
const [role, expiry, nonce, mac, extra] = value.split('.');
if (
(role !== 'read' && role !== 'admin') ||
extra ||
!nonce ||
!mac ||
!/^\d+$/.test(expiry ?? '')
) {
return;
}
const expiresAt = Number(expiry);
if (
!Number.isSafeInteger(expiresAt) ||
expiresAt <= Date.now() / 1000 ||
expiresAt > Date.now() / 1000 + sessionSeconds + 10
) {
return;
}
const key = signingKey(role);
if (!key || !equal(mac, signature(`${role}.${expiry}.${nonce}`, key))) {
return;
}
return { role, cookie: true };
}
function authorize(request: Request, admin = false): Response | undefined {
const identity = authenticate(request);
if (!identity) {
return Response.json(
{ error: 'Authentication required' },
{ status: 401, headers: { 'WWW-Authenticate': 'Bearer', 'Cache-Control': 'no-store' } }
);
}
if (admin && identity.role === 'read') {
return Response.json({ error: 'Administrator access required' }, { status: 403 });
}
const isWebSocket = request.headers.get('upgrade')?.toLowerCase() === 'websocket';
const mutates = !['GET', 'HEAD', 'OPTIONS'].includes(request.method);
// Browser sessions are CSRF-protected. WebSocket upgrades validate Origin as well.
if (
(isWebSocket && request.headers.has('origin') && !originAllowed(request)) ||
(identity.cookie && (mutates || isWebSocket) && !originAllowed(request))
) {
return Response.json({ error: 'Untrusted request origin' }, { status: 403 });
}
return undefined;
}
const middleware: MiddlewareHandler = async (context, next) => {
const path = context.req.path;
if (
path === '/health' ||
path.startsWith('/health/') ||
(options.browserSessions && path === '/api/auth/session') ||
context.req.method === 'OPTIONS'
) {
await next();
return undefined;
}
const admin =
!['GET', 'HEAD'].includes(context.req.method) ||
/^\/api\/(queue|operations|handlers)(\/|$)/.test(path);
const rejection = authorize(context.req.raw, admin);
if (rejection) {
return rejection;
}
await next();
return undefined;
};
function mount(app: Hono): void {
app.use('*', middleware);
if (!options.browserSessions) {
return;
}
const cookie = (value: string, maxAge: number) =>
`${cookieName}=${value}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${environment === 'production' ? '; Secure' : ''}`;
app.get('/api/auth/session', context => {
const identity = authenticate(context.req.raw);
context.header('Cache-Control', 'no-store');
return context.json(
{ authenticated: !!identity, role: identity?.role },
identity ? 200 : 401
);
});
let attempts = 0;
let windowStart = Date.now();
app.post('/api/auth/session', async context => {
context.header('Cache-Control', 'no-store');
if (Date.now() - windowStart > 60_000) {
attempts = 0;
windowStart = Date.now();
}
if (++attempts > 30) {
return context.json({ error: 'Too many sign-in attempts' }, 429);
}
if (context.req.header('origin') && !originAllowed(context.req.raw)) {
return context.json({ error: 'Untrusted request origin' }, 403);
}
if (!context.req.header('content-type')?.startsWith('application/json')) {
return context.json({ error: 'JSON required' }, 415);
}
const input: unknown = await context.req.json().catch(() => null);
const token =
input && typeof input === 'object' && 'token' in input && typeof input.token === 'string'
? input.token
: '';
if (token.length > 4096) {
return context.json({ error: 'Invalid access token' }, 401);
}
const role = disabled ? 'admin' : roleForToken(token);
if (!role || role === 'service') {
return context.json({ error: 'Invalid access token' }, 401);
}
const key = signingKey(role);
if (key) {
const payload = `${role}.${Math.floor(Date.now() / 1000) + sessionSeconds}.${randomBytes(16).toString('hex')}`;
context.header(
'Set-Cookie',
cookie(`${payload}.${signature(payload, key)}`, sessionSeconds)
);
}
return context.json({ authenticated: true, role });
});
app.delete('/api/auth/session', context => {
if (!originAllowed(context.req.raw)) {
return context.json({ error: 'Untrusted request origin' }, 403);
}
context.header('Set-Cookie', cookie('', 0));
context.header('Cache-Control', 'no-store');
return context.json({ authenticated: false });
});
}
return { mount, authorize, hostname, allowedOrigins };
}
export type HttpSecurity = ReturnType<typeof createHttpSecurity>;
/** Used only by server-to-server clients; never expose this token to the browser. */
export function authenticatedServiceFetch(
input: string | URL | Request,
init?: RequestInit
): Promise<Response> {
const token = process.env.STOCK_BOT_SERVICE_TOKEN;
if (!token) {
const target = new URL(input instanceof Request ? input.url : input.toString());
if (
process.env.STOCK_BOT_AUTH_DISABLED !== 'true' ||
process.env.NODE_ENV === 'production' ||
!['localhost', '127.0.0.1', '[::1]'].includes(target.hostname)
) {
throw new Error('STOCK_BOT_SERVICE_TOKEN is required for internal HTTP requests');
}
}
const headers = new Headers(input instanceof Request ? input.headers : undefined);
new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return fetch(input, { ...init, headers, redirect: 'error' });
}

View file

@ -2,6 +2,12 @@
export { ServiceApplication } from './service-application';
export { ServiceContainerBuilder } from './container/builder';
export { OperationContext } from './operation-context';
export {
createHttpSecurity,
httpSecurityOptions,
authenticatedServiceFetch,
} from './http/security';
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';
export { ServiceLifecycleManager } from './utils/lifecycle';
export { HandlerScanner } from './scanner/handler-scanner';

View file

@ -22,6 +22,7 @@ import type { HandlerScanner } from './scanner';
export interface ServiceApplicationConfig {
/** Service name for logging and identification */
serviceName: string;
hostname?: string;
/** CORS configuration - if not provided, uses permissive defaults */
corsConfig?: Parameters<typeof cors>[0];
@ -435,6 +436,8 @@ export class ServiceApplication {
// Start HTTP server
const port = this.config.service.port;
this.server = Bun.serve({
hostname: this.serviceConfig.hostname,
maxRequestBodySize: 1_048_576,
port,
fetch: this.app.fetch,
development: this.config.environment === 'development',

View file

@ -10,6 +10,7 @@
import pino from 'pino';
import pretty from 'pino-pretty';
import { redactLogValue } from './redact';
import type { LogContext, LoggerConfig, LogLevel, LogMetadata } from './types';
// Simple cache for logger instances
@ -183,12 +184,12 @@ export class Logger {
}
if (typeof message === 'string') {
this.pino[level](data, message);
this.pino[level](redactLogValue(data), redactLogValue(message) as string);
} else {
if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') {
this.pino[level]({}, `Object logged (hidden)`);
} else {
this.pino[level]({ ...data, data: message }, 'Object logged');
this.pino[level](redactLogValue({ ...data, data: message }), 'Object logged');
}
}
}

View file

@ -0,0 +1,52 @@
const sensitiveKey =
/password|passwd|secret|token|api[_-]?key|authorization|cookie|credential|private[_-]?key|session[_-]?id/i;
const hidden = '[REDACTED]';
function redactText(value: string): string {
return value
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, `$1${hidden}@`)
.replace(
/([?&](?:api[_-]?(?:key|token)|token|key|password|secret|credential|auth)=)[^&#\s]*/gi,
`$1${hidden}`
)
.replace(/\bBearer\s+[a-z0-9._~+/=-]+/gi, `Bearer ${hidden}`);
}
/** Redact without mutating callers, including error objects and circular metadata. */
export function redactLogValue(value: unknown, seen = new WeakSet<object>()): unknown {
if (typeof value === 'string') {
return redactText(value);
}
if (!value || typeof value !== 'object') {
return value;
}
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
if (value instanceof Date) {
return value.toISOString();
}
if (Buffer.isBuffer(value)) {
return '[Binary]';
}
if (Array.isArray(value)) {
return value.map(item => redactLogValue(item, seen));
}
const source =
value instanceof Error
? {
...value,
name: value.name,
message: value.message,
stack: value.stack,
cause: value.cause,
}
: value;
return Object.fromEntries(
Object.entries(source).map(([key, item]) => [
key,
sensitiveKey.test(key) ? hidden : redactLogValue(item, seen),
])
);
}

View file

@ -88,3 +88,8 @@ export type {
MemberMetadataDecorator,
ClassMemberMetadataDecorator,
} from './decorators';
export {
REFERENCE_DATA_RESET_CONFIRMATION,
parseReferenceDataResetRequest,
} from './reference-data';
export type { ReferenceDataResetRequest, ReferenceDataResetScope } from './reference-data';

View file

@ -0,0 +1,23 @@
export type ReferenceDataResetScope = 'exchanges' | 'provider_mappings' | 'all';
export interface ReferenceDataResetRequest {
type: ReferenceDataResetScope;
confirmation: string;
}
export const REFERENCE_DATA_RESET_CONFIRMATION = 'DELETE STOCK REFERENCE DATA';
/** Dependency-free validation shared by HTTP and queue consumers. No default destructive scope. */
export function parseReferenceDataResetRequest(input: unknown): ReferenceDataResetRequest {
if (
input &&
typeof input === 'object' &&
'type' in input &&
'confirmation' in input &&
(input.type === 'exchanges' || input.type === 'provider_mappings' || input.type === 'all') &&
input.confirmation === `${REFERENCE_DATA_RESET_CONFIRMATION}:${input.type}`
) {
return { type: input.type, confirmation: input.confirmation };
}
throw new Error(
'Reset requires an explicit type and matching DELETE STOCK REFERENCE DATA:<type> confirmation'
);
}

View file

@ -22,6 +22,9 @@
"coverage:ci": "bun run tools/coverage-cli/src/index.ts --reporters markdown json --fail-under",
"test:unit": "bun test test/unit",
"test:integration": "bun test test/integration/",
"test:native": "cargo test -p engine --lib --offline",
"test:postgres": "bun run scripts/test-postgres.ts",
"audit:secrets": "bun run scripts/audit-secrets.ts",
"test:e2e": "bun test test/e2e",
"test:libs": "turbo run test --filter='./libs/**'",
"test:apps": "turbo run test --filter=./apps/*/*",

32
scripts/audit-secrets.ts Normal file
View file

@ -0,0 +1,32 @@
// Explicit private local-development exceptions, not a general permission to track secrets.
const localDevelopmentEnvironmentFiles = new Set(['.env', 'apps/stock/web-app/.env']);
/** Refuse unexpected tracked environment files without printing contents or values. */
export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): string[] {
return paths.filter(path => {
if (path.startsWith('apps/wcag-ada/') || localDevelopmentEnvironmentFiles.has(path))
return false;
const name = path.split('/').at(-1) ?? '';
return (
(name === '.env' || name.startsWith('.env.')) &&
name !== '.env.example' &&
!name.endsWith('.example')
);
});
}
if (import.meta.main) {
const result = Bun.spawnSync(['git', 'ls-files', '-z']);
if (result.exitCode !== 0) throw new Error('Cannot inspect tracked files for the secret audit');
const files = unexpectedTrackedEnvironmentFiles(
new TextDecoder().decode(result.stdout).split('\0')
);
if (files.length) {
process.stderr.write(`Unexpected tracked environment files: ${files.join(', ')}\n`);
process.exitCode = 1;
} else {
process.stdout.write(
'Tracked environment-file audit passed (two local-development exceptions; WCAG excluded).\n'
);
}
}

View file

@ -2,11 +2,13 @@
import { fileURLToPath } from 'node:url';
export const checks = [
'audit:secrets',
'build',
'typecheck',
'test:contracts',
'test:tooling',
'test:integration',
'test:native',
'lint:check',
] as const;

12
scripts/test-postgres.ts Normal file
View file

@ -0,0 +1,12 @@
const url = process.env.PIPELINE_TEST_DATABASE_URL;
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error(
'Set PIPELINE_TEST_DATABASE_URL to a disposable stock_bot_safety database; tests create/drop isolated schemas'
);
}
const child = Bun.spawn([process.execPath, 'test', 'test/postgres/'], {
stdin: 'inherit',
stdout: 'inherit',
stderr: 'inherit',
});
process.exitCode = await child.exited;

View file

@ -0,0 +1,318 @@
import { readFileSync } from 'node:fs';
import { expect, test } from 'bun:test';
import { Hono } from 'hono';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes';
import { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websocket.routes';
import { createHttpSecurity, type HttpSecurityOptions } from '../../libs/core/di/src/http/security';
import { redactLogValue } from '../../libs/core/logger/src/redact';
import { parseReferenceDataResetRequest } from '../../libs/core/types/src/reference-data';
import { unexpectedTrackedEnvironmentFiles } from '../audit-secrets';
import { checks } from '../check';
const options: HttpSecurityOptions = {
readToken: 'read-fixture-token-not-a-real-credential-123456',
adminToken: 'admin-fixture-token-not-a-real-credential-123456',
serviceToken: 'service-fixture-token-not-a-real-credential-123456',
origins: ['http://ui.test'],
browserSessions: true,
};
const bearer = (token = options.adminToken!) => ({ Authorization: `Bearer ${token}` });
function fixture() {
const security = createHttpSecurity(options);
const app = new Hono();
security.mount(app);
let writes = 0;
app.get('/health', context => context.json({ status: 'ok' }));
app.get('/api/data', context => context.json({ data: [] }));
app.post('/api/write', context => {
writes++;
return context.json({ ok: true });
});
return { app, security, writes: () => writes };
}
async function login(app: Hono, token = options.adminToken!) {
const response = await app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' },
body: JSON.stringify({ token }),
});
expect(response.status).toBe(200);
return response;
}
test('HTTP security fails closed and insecure mode is loopback-development only', () => {
expect(() => createHttpSecurity({})).toThrow('STOCK_BOT_ADMIN_TOKEN');
expect(() => createHttpSecurity({ ...options, readToken: options.adminToken })).toThrow(
'distinct'
);
expect(() => createHttpSecurity({ ...options, adminToken: 'weak' })).toThrow('32');
expect(() => createHttpSecurity({ disabled: true, environment: 'production' })).toThrow(
'loopback'
);
expect(() => createHttpSecurity({ disabled: true, hostname: '0.0.0.0' })).toThrow('loopback');
expect(() => createHttpSecurity({ ...options, origins: ['*'] })).toThrow('trusted');
expect(createHttpSecurity({ disabled: true }).hostname).toBe('127.0.0.1');
});
test('anonymous/invalid access is rejected; readers cannot mutate; service/admin can', async () => {
const f = fixture();
expect((await f.app.request('/health')).status).toBe(200);
expect((await f.app.request('/api/data')).status).toBe(401);
expect((await f.app.request('/api/data', { headers: bearer('invalid') })).status).toBe(401);
expect((await f.app.request('/api/data', { headers: bearer(options.readToken) })).status).toBe(
200
);
expect(
(await f.app.request('/api/write', { method: 'POST', headers: bearer(options.readToken) }))
.status
).toBe(403);
expect(f.writes()).toBe(0);
for (const token of [options.adminToken, options.serviceToken]) {
expect(
(await f.app.request('/api/write', { method: 'POST', headers: bearer(token) })).status
).toBe(200);
}
expect(f.writes()).toBe(2);
});
test('browser login uses a signed HttpOnly cookie, with no raw credential in the response', async () => {
const f = fixture();
const response = await login(f.app);
const cookie = response.headers.get('set-cookie')!;
expect(cookie).toContain('HttpOnly');
expect(cookie).toContain('SameSite=Strict');
expect(cookie).not.toContain(options.adminToken!);
expect(await response.text()).not.toContain(options.adminToken!);
const headers = { Cookie: cookie.split(';')[0]! };
expect((await f.app.request('/api/data', { headers })).status).toBe(200);
expect((await f.app.request('/api/write', { method: 'POST', headers })).status).toBe(403);
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { ...headers, Origin: 'http://evil.test' },
})
).status
).toBe(403);
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { ...headers, Origin: 'http://ui.test' },
})
).status
).toBe(200);
expect(
(await f.app.request('/api/data', { headers: { Cookie: headers.Cookie + 'tampered' } })).status
).toBe(401);
const logout = await f.app.request('/api/auth/session', {
method: 'DELETE',
headers: { ...headers, Origin: 'http://ui.test' },
});
expect(logout.headers.get('set-cookie')).toContain('Max-Age=0');
});
test('read sessions cannot escalate, internal tokens cannot sign into the browser, and login rejects hostile origins', async () => {
const f = fixture();
const response = await login(f.app, options.readToken);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { Cookie, Origin: 'http://ui.test' },
})
).status
).toBe(403);
expect(
(await f.app.request('/api/data', { headers: { Cookie: Cookie.replace('read.', 'admin.') } }))
.status
).toBe(401);
for (const token of [options.serviceToken, 'wrong']) {
expect(
(
await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
})
).status
).toBe(401);
}
expect(
(
await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://evil.test' },
body: JSON.stringify({ token: options.adminToken }),
})
).status
).toBe(403);
});
test('production sessions are Secure and token rotation invalidates existing sessions', async () => {
const old = fixture();
const response = await login(old.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
const production = new Hono();
createHttpSecurity({ ...options, environment: 'production' }).mount(production);
const fresh = await login(production);
expect(fresh.headers.get('set-cookie')).toContain('; Secure');
const rotated = new Hono();
createHttpSecurity({
...options,
adminToken: 'rotated-fixture-credential-not-real-1234567890',
}).mount(rotated);
rotated.get('/api/data', context => context.json({}));
expect((await rotated.request('/api/data', { headers: { Cookie } })).status).toBe(401);
});
test('expired browser sessions are rejected', async () => {
const f = fixture();
const response = await login(f.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
const expiresAt = Number(Cookie.split('.')[1]);
const now = Date.now;
try {
Date.now = () => (expiresAt + 1) * 1000;
expect(
f.security.authorize(new Request('http://api.test/api/data', { headers: { Cookie } }))?.status
).toBe(401);
} finally {
Date.now = now;
}
});
test('WebSocket upgrade authenticates and validates browser origin before upgrading', async () => {
const f = fixture();
let upgraded = 0;
const route = createWebSocketRoute({ logger: getLogger('security-test') }, f.security);
const server = {
upgrade() {
upgraded++;
return true;
},
};
expect(
route(
new Request('http://api.test/ws?runId=one&token=ignored', {
headers: { Upgrade: 'websocket' },
}),
server
)?.status
).toBe(401);
const response = await login(f.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
expect(
route(
new Request('http://api.test/ws?runId=one', {
headers: { Upgrade: 'websocket', Cookie, Origin: 'http://evil.test' },
}),
server
)?.status
).toBe(403);
expect(upgraded).toBe(0);
expect(
route(
new Request('http://api.test/ws?runId=one', {
headers: { Upgrade: 'websocket', Cookie, Origin: 'http://ui.test' },
}),
server
)
).toBeUndefined();
expect(upgraded).toBe(1);
});
test('real pipeline reset route authenticates, requires admin and exact confirmation before queueing', async () => {
const jobs: unknown[] = [];
const services = {
logger: getLogger('reset-test'),
queueManager: {
getQueue() {
return {
async add(_name: string, data: unknown) {
jobs.push(data);
return { id: 'fixture' };
},
};
},
},
} as unknown as IServiceContainer;
const f = fixture();
f.app.route('/api/pipeline', createPipelineRoutes(services));
const url = '/api/pipeline/clear/postgresql';
const reset = { type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:all' };
expect((await f.app.request(url, { method: 'POST' })).status).toBe(401);
expect(
(await f.app.request(url, { method: 'POST', headers: bearer(options.readToken) })).status
).toBe(403);
expect((await f.app.request(url, { method: 'POST', headers: bearer(), body: '{}' })).status).toBe(
400
);
expect(
(
await f.app.request('/api/pipeline/exchanges/all?clear=true', {
method: 'POST',
headers: bearer(),
})
).status
).toBe(400);
expect(jobs).toHaveLength(0);
expect(
(await f.app.request(url, { method: 'POST', headers: bearer(), body: JSON.stringify(reset) }))
.status
).toBe(200);
expect(jobs).toEqual([
{ handler: 'exchanges', operation: 'clear-postgresql-data', payload: reset },
]);
expect(() =>
parseReferenceDataResetRequest({
type: 'all',
confirmation: 'DELETE STOCK REFERENCE DATA:exchanges',
})
).toThrow();
});
test('log redaction covers nested configuration, errors, cookies, bearer tokens and authenticated URLs without mutation', () => {
const source = {
password: 'private-pass',
nested: { apiKey: 'private-key', safe: 'hello' },
rows: [{ token: 'private-token' }],
error: new Error('GET https://user:private-pass@example.test/api?api_token=private-key failed'),
header: 'Bearer private-token',
cookie: 'private-cookie',
};
const output = JSON.stringify(redactLogValue(source));
for (const value of ['private-pass', 'private-key', 'private-token', 'private-cookie'])
expect(output).not.toContain(value);
expect(output).toContain('hello');
expect(source.password).toBe('private-pass');
const circular: Record<string, unknown> = {};
circular.self = circular;
expect(JSON.stringify(redactLogValue(circular))).toContain('[Circular]');
});
test('native tests and credential-file audit remain mandatory repository gates', () => {
expect(checks).toContain('test:native');
expect(checks).toContain('audit:secrets');
expect(
unexpectedTrackedEnvironmentFiles([
'.env',
'apps/stock/web-app/.env',
'.env.production',
'apps/stock/web-api/.env',
'apps/stock/web-app/.env.local',
'.env.example',
'libs/core/config/.env.example',
'apps/wcag-ada/.env',
])
).toEqual(['.env.production', 'apps/stock/web-api/.env', 'apps/stock/web-app/.env.local']);
const ci = readFileSync(new URL('../../.gitlab-ci.yml', import.meta.url), 'utf8');
expect(ci).toContain('bun run test:postgres');
for (const file of ['docker-compose.yml', 'docker-compose.dev.yml']) {
const compose = readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8');
expect(compose).not.toMatch(/^\s*-\s*["']?(?:0\.0\.0\.0:)?\d+:\d+/m);
}
});

View file

@ -0,0 +1,231 @@
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { MongoDBClient } from '@stock-bot/services';
import { clearPostgreSQLData } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations';
import { syncAllExchanges } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations';
import { syncQMProviderMappings } from '../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations';
import { syncSymbolsFromProvider } from '../../apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations';
import { PipelineSyncRepository } from '../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('pipeline-postgres-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety'))
throw new Error('A dedicated stock_bot_safety database is required');
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
await pool.query(`
CREATE TABLE exchanges (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), code text UNIQUE NOT NULL,
name text, country char(2), currency char(3), active boolean DEFAULT true);
CREATE TABLE symbols (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), symbol text, exchange_id uuid REFERENCES exchanges,
company_name text, country char(2), currency char(3), updated_at timestamptz, UNIQUE(symbol, exchange_id));
CREATE TABLE provider_exchange_mappings (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), provider text,
provider_exchange_code text, provider_exchange_name text, master_exchange_id uuid REFERENCES exchanges,
country_code text, currency text, confidence numeric, active boolean, auto_mapped boolean,
UNIQUE(provider, provider_exchange_code));
CREATE TABLE provider_mappings (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), symbol_id uuid REFERENCES symbols,
provider text, provider_symbol text, provider_exchange text, verified boolean DEFAULT false, last_seen timestamptz,
UNIQUE(provider, provider_symbol));
CREATE TABLE sync_status (provider text, data_type text, last_sync_at timestamptz, last_sync_count integer,
sync_errors text, updated_at timestamptz, UNIQUE(provider, data_type));
INSERT INTO exchanges (code,name,country,currency) VALUES ('TSX','Manually curated','CA','CAD');
INSERT INTO provider_exchange_mappings (provider,provider_exchange_code,master_exchange_id,active,auto_mapped)
SELECT 'eod','TO',id,true,false FROM exchanges;
INSERT INTO symbols (symbol,exchange_id,company_name,country,currency)
SELECT 'KEEP',id,'Original company','CA','CAD' FROM exchanges;
INSERT INTO provider_mappings (provider,provider_symbol,symbol_id,verified)
SELECT 'eod','KEEP.TO',id,true FROM symbols;
`);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const documents: Record<string, Record<string, unknown>[]> = {
eodExchanges: [],
ibExchanges: [],
eodSymbols: [],
qmSymbols: [],
};
const mongodb = {
async find(collection: string) {
return documents[collection] ?? [];
},
getDatabase() {
return {
collection(name: string) {
return {
find() {
return {
async toArray() {
return documents[name] ?? [];
},
};
},
aggregate() {
return {
async toArray() {
return documents[name] ?? [];
},
};
},
};
},
};
},
} as unknown as MongoDBClient;
const services = { logger, postgres, mongodb };
const snapshot = async () => {
const result: Record<string, unknown> = {};
for (const table of [
'exchanges',
'symbols',
'provider_mappings',
'provider_exchange_mappings',
'sync_status',
]) {
result[table] = (await pool.query(`SELECT * FROM ${table} ORDER BY 1`)).rows;
}
return result;
};
return { services, pool, postgres, documents, snapshot };
}
describe.skipIf(!url)('pipeline safety on real PostgreSQL', () => {
test('default and false syncs preserve IDs and manual mappings; replay is idempotent', async () => {
const f = await fixture();
const before = await f.snapshot();
f.documents.eodExchanges = [
{ Code: 'TO', Name: 'Provider name', CountryISO2: 'CA', Currency: 'CAD' },
{ Code: 'NEW', Name: 'New', CountryISO2: 'US', Currency: 'USD' },
];
expect((await syncAllExchanges({}, f.services)).created).toBe(1);
expect((await syncAllExchanges({ clearFirst: false }, f.services)).created).toBe(0);
const after = await f.snapshot();
expect(after.symbols).toEqual(before.symbols);
expect(after.provider_mappings).toEqual(before.provider_mappings);
expect((await f.pool.query("SELECT name FROM exchanges WHERE code = 'TSX'")).rows[0].name).toBe(
'Manually curated'
);
await expect(syncAllExchanges({ clearFirst: true }, f.services)).rejects.toThrow(
'non-destructive'
);
});
test('a failure after an earlier exchange write rolls back data and status', async () => {
const f = await fixture();
const before = await f.snapshot();
f.documents.eodExchanges = [
{ Code: 'NEW', Name: 'New', CountryISO2: 'US' },
{ Code: 'BAD', Name: 'Bad', CountryISO2: 'INVALID' },
];
await expect(syncAllExchanges({}, f.services)).rejects.toThrow();
expect(await f.snapshot()).toEqual(before);
});
test('symbol updates, mappings, and status roll back together on a later failure', async () => {
const f = await fixture();
const before = await f.snapshot();
f.documents.eodSymbols = [
{ Code: 'KEEP', Exchange: 'TO', eodSearchCode: 'KEEP.TO', Name: 'Changed', Currency: 'CAD' },
{ Code: 'BAD', Exchange: 'TO', Currency: 'TOO LONG' },
];
await expect(syncSymbolsFromProvider({ provider: 'eod' }, f.services)).rejects.toThrow();
expect(await f.snapshot()).toEqual(before);
await expect(
syncSymbolsFromProvider({ provider: 'eod', clearFirst: true }, f.services)
).rejects.toThrow('non-destructive');
});
test('QM mapping writes also roll back as one transaction', async () => {
const f = await fixture();
const before = await f.snapshot();
f.documents.qmSymbols = [
{ exchangeCode: 'NEW', countryCode: 'US' },
{ exchangeCode: 'BAD', countryCode: 'INVALID' },
];
await expect(syncQMProviderMappings({}, f.services)).rejects.toThrow();
expect(await f.snapshot()).toEqual(before);
});
test('unconfirmed reset does nothing; FK failure rolls back earlier deletes', async () => {
const f = await fixture();
const before = await f.snapshot();
await expect(clearPostgreSQLData({}, f.services)).rejects.toThrow('confirmation');
await expect(
clearPostgreSQLData(
{ type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:exchanges' },
f.services
)
).rejects.toThrow('confirmation');
await expect(
clearPostgreSQLData(
{ type: 'exchanges', confirmation: 'DELETE STOCK REFERENCE DATA:exchanges' },
f.services
)
).rejects.toThrow();
expect(await f.snapshot()).toEqual(before);
});
test('confirmed mapping-only reset respects scope; all reset respects FK ordering', async () => {
const f = await fixture();
const mappingOnly = await clearPostgreSQLData(
{ type: 'provider_mappings', confirmation: 'DELETE STOCK REFERENCE DATA:provider_mappings' },
f.services
);
expect(mappingOnly.mappingsCleared).toBe(1);
expect((await f.pool.query('SELECT * FROM symbols')).rows).toHaveLength(1);
const all = await clearPostgreSQLData(
{ type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:all' },
f.services
);
expect(all).toMatchObject({
exchangesCleared: 1,
symbolsCleared: 1,
exchangeMappingsCleared: 1,
});
});
test('competing sync/reset transactions serialize on the same advisory lock', async () => {
const f = await fixture();
let entered!: () => void;
let release!: () => void;
const ready = new Promise<void>(resolve => {
entered = resolve;
});
const gate = new Promise<void>(resolve => {
release = resolve;
});
const first = PipelineSyncRepository.transaction(f.postgres, async () => {
entered();
await gate;
});
await ready;
let secondEntered = false;
const second = PipelineSyncRepository.transaction(f.postgres, async () => {
secondEntered = true;
});
await new Promise(resolve => setTimeout(resolve, 50));
expect(secondEntered).toBe(false);
release();
await Promise.all([first, second]);
expect(secondEntered).toBe(true);
});
});