Files
server/order.js

92 lines
3.4 KiB
JavaScript

import {orderFilled, orderStatuses, vaultOpenOrders, vaultRecentlyClosedOrders} from "./cache.js"
import {sql} from "./db.js";
export function sendVaultOrders( socket, chainId, vault ) {
Promise.all([
vaultOpenOrders.get(chainId, vault, '[]'),
vaultRecentlyClosedOrders.get(chainId, vault, '[]'),
archivedOrders(chainId, vault),
]).then(async (got)=>{
const [openIndexes, closedIndexes, recents] = got
console.log('vault open orders', openIndexes)
console.log('vault closed orders', closedIndexes)
const statuses = {}
const indexes = [...JSON.parse(openIndexes), ...JSON.parse(closedIndexes)]
if( openIndexes !== null ) {
for (const orderIndex of indexes) {
// there is a race condition here since we need multiple queries to get the complete order status,
// so we check for nulls and exclude such an order, since it was deleted and no longer active.
const status = await orderStatus(chainId, vault, orderIndex)
if (status !== null)
statuses[orderIndex] = status
}
}
console.log('vault archived orders', recents)
const proms = []
for( let [orderIndex, status] of recents ) {
if( !(orderIndex in statuses) ) {
// only write the database version if there's no open order in the memcache
const orderKey = `${vault}|${orderIndex.toString().padStart(5,'0')}`
proms.push(fillOrderStatus(chainId, orderKey, status))
statuses[orderIndex] = status
}
}
await Promise.all(proms)
const result = []
for( const index of Object.keys(statuses).sort())
result.push([parseInt(index), statuses[index]])
socket.emit('os', chainId, vault, result)
})
}
export function unsubVaultOrders( socket, chainId, vault ) {
console.log('todo: unsubVaultOrders') // todo
}
export async function orderStatus( chainId, vault, orderIndex ) {
const orderKey = `${vault}|${orderIndex}`
let status = await orderStatuses.get(chainId, orderKey)
if( status !== null ) {
status = JSON.parse(status)
await fillOrderStatus(chainId, orderKey, status)
}
return status
}
async function fillOrderStatus( chainId, orderKey, status ) {
const fills = await orderFilled.get(chainId, orderKey)
if (fills !== null)
applyFills(status, JSON.parse(fills))
}
export async function archivedOrders(chainId, vault, limit=25 ) {
const query = await sql(
`select oi.order_index, sd.value
from seriesdict sd,
orderindex oi
where oi.chain = ${chainId}
and oi.vault = '${vault}'
and sd.series = 'o'
and sd.key = concat('${vault}', '|', to_char(oi.order_index, 'FM00000'))
order by oi.order_index desc
limit ${limit}`
)
const result = []
for( const {order_index, value} of query.rows)
result.push([order_index,JSON.parse(value)])
return result
}
function applyFills( orderStatus, filled ) {
// console.log('apply fills', orderStatus, filled)
orderStatus[5] = filled[0][0]
orderStatus[6] = filled[0][1]
for( const i in filled[1] ) {
const [filledIn, filledOut] = filled[1][i]
orderStatus[7][i] = filledIn
orderStatus[8][i] = filledOut
}
// console.log('applied fills', orderStatus)
}