stock-bot/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts

213 lines
8.9 KiB
TypeScript

import type { PostgresClient } from '@stock-bot/services';
import { refuseCanonicalAccount } from './canonical-paper';
import type { Account, Fill, StoredOrder } from './model';
import {
ExecutionConflictError,
type ExecutionRepository,
type ExecutionTransaction,
} from './repository';
import {
canonicalJson,
type MarketInput,
type StrategyCheckpoint,
type StrategyJournalPayload,
type StrategyOrderIntent,
} from './strategy-recovery';
export class PostgresExecutionRepository implements ExecutionRepository {
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
async initialize(id: string, initial: Account) {
await this.postgres.transaction(async client => {
await client.query(
`INSERT INTO simulation_accounts (id, state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING`,
[id, JSON.stringify(initial)]
);
const result = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[id]
);
refuseCanonicalAccount(result.rows[0].state);
const account: Account = result.rows[0].state;
if (account.initialCapital !== initial.initialCapital) {
throw new ExecutionConflictError(
'Existing account capital differs; use a new account ID, not an implicit reset'
);
}
Object.assign(account, {
limits: initial.limits,
commission: initial.commission,
slippage: initial.slippage,
maxQuoteAgeMs: initial.maxQuoteAgeMs,
});
await client.query('UPDATE simulation_accounts SET state = $2::jsonb WHERE id = $1', [
id,
JSON.stringify(account),
]);
});
}
transact<T>(id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
return this.postgres.transaction(async client => {
const state = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[id]
);
if (!state.rows[0]) {
throw new Error('Execution account is not initialized');
}
refuseCanonicalAccount(state.rows[0].state);
const readOrder = async (column: 'id' | 'client_order_id', key: string) => {
const result = await client.query(
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`,
[id, key]
);
return result.rows[0]?.payload as StoredOrder | undefined;
};
const result = await work({
account: state.rows[0].state as Account,
findOrder: key => readOrder('client_order_id', key),
getOrder: key => readOrder('id', key),
async openOrders() {
const result = await client.query(
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND status IN ('accepted','partiallyFilled') ORDER BY created_at,id`,
[id]
);
return result.rows.map(r => r.payload as StoredOrder);
},
async putOrder(order) {
await client.query(
`INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload)
VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[
order.report.orderId,
id,
order.report.clientOrderId,
order.report.status,
JSON.stringify(order),
]
);
},
async insertFill(orderId: string, fill: Fill) {
const inserted = await client.query(
`INSERT INTO simulation_fills (account_id,id,order_id,payload)
VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
[id, fill.id, orderId, JSON.stringify(fill)]
);
return inserted.rows.length > 0;
},
async recordEvent(eventId, hash) {
const inserted = await client.query(
`INSERT INTO simulation_events (account_id,id,fingerprint)
VALUES ($1,$2,$3) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
[id, eventId, hash]
);
if (inserted.rows.length) {
return true;
}
const previous = await client.query(
'SELECT fingerprint FROM simulation_events WHERE account_id = $1 AND id = $2',
[id, eventId]
);
if (previous.rows[0]?.fingerprint !== hash) {
throw new ExecutionConflictError('Conflicting market event identity');
}
return false;
},
async appendJournal(payload: StrategyJournalPayload) {
const account = state.rows[0].state as Account;
const sequence = (account.strategySequence ?? 0) + 1;
if (!Number.isSafeInteger(sequence)) {
throw new Error('Strategy journal sequence exhausted');
}
account.strategySequence = sequence;
await client.query(
'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)',
[id, sequence, JSON.stringify(payload)]
);
},
async nextJournal(cursor) {
const result = await client.query(
'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence LIMIT 1',
[id, cursor]
);
const row = result.rows[0];
if (!row) {
return undefined;
}
const sequence = Number(row.sequence);
if (!Number.isSafeInteger(sequence)) {
throw new Error('Invalid strategy journal sequence');
}
return { sequence, payload: row.payload as StrategyJournalPayload };
},
async strategies() {
const result = await client.query(
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"',
[id]
);
return result.rows.map(row => row.payload as StrategyCheckpoint);
},
async putStrategy(checkpoint) {
await client.query(
`INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)
ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`,
[id, checkpoint.strategyId, JSON.stringify(checkpoint)]
);
},
async nextIntent() {
const result = await client.query(
`SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence,strategy_id COLLATE "C",client_order_id COLLATE "C" LIMIT 1`,
[id]
);
return result.rows[0]?.payload as StrategyOrderIntent | undefined;
},
async putIntent(intent) {
const previous = await client.query(
'SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND client_order_id = $2',
[id, intent.clientOrderId]
);
const old = previous.rows[0]?.payload as StrategyOrderIntent | undefined;
if (
old &&
(old.strategyId !== intent.strategyId ||
old.sequence !== intent.sequence ||
canonicalJson(old.request) !== canonicalJson(intent.request) ||
(old.status === 'dispatched' && intent.status !== 'dispatched'))
) {
throw new ExecutionConflictError('Conflicting strategy order intent');
}
await client.query(
`INSERT INTO simulation_strategy_intents (account_id,client_order_id,strategy_id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5,$6::jsonb)
ON CONFLICT (account_id,client_order_id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[
id,
intent.clientOrderId,
intent.strategyId,
intent.sequence,
intent.status,
JSON.stringify(intent),
]
);
},
async nextInput() {
const result = await client.query(
`SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1`,
[id]
);
return result.rows[0]?.payload as MarketInput | undefined;
},
async putInput(input) {
await client.query(
`INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[id, input.id, input.sequence, input.status, JSON.stringify(input)]
);
},
});
await client.query(
'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1',
[id, JSON.stringify(state.rows[0].state)]
);
return result;
});
}
}