Unify simulation order execution and persist paper accounting
This commit is contained in:
parent
7dec0be3b4
commit
63c3856797
37 changed files with 3901 additions and 3043 deletions
|
|
@ -0,0 +1,113 @@
|
|||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import type { Account, Fill, StoredOrder } from './model';
|
||||
import {
|
||||
ExecutionConflictError,
|
||||
type ExecutionRepository,
|
||||
type ExecutionTransaction,
|
||||
} from './repository';
|
||||
|
||||
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]
|
||||
);
|
||||
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');
|
||||
}
|
||||
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;
|
||||
},
|
||||
});
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue