safety
This commit is contained in:
parent
879e9b4228
commit
c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
"clean": "rm -rf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/cache": "*",
|
||||
"@stock-bot/config": "*",
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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]);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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 }) => {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
118
apps/stock/web-app/src/app/AuthGate.tsx
Normal file
118
apps/stock/web-app/src/app/AuthGate.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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}`;
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
14
apps/stock/web-app/src/lib/api.ts
Normal file
14
apps/stock/web-app/src/lib/api.ts
Normal 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;
|
||||
}
|
||||
|
|
@ -12,6 +12,6 @@ export default defineConfig({
|
|||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
host: true,
|
||||
host: '127.0.0.1',
|
||||
},
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue