2021-07-02 08:55:57 -07:00
|
|
|
import { Account, Connection, PublicKey } from '@solana/web3.js'
|
|
|
|
import { Market } from '@project-serum/serum'
|
|
|
|
import cors from 'cors'
|
|
|
|
import express from 'express'
|
|
|
|
import { Tedis, TedisPool } from 'tedis'
|
|
|
|
import { URL } from 'url'
|
|
|
|
import { decodeRecentEvents } from './events'
|
|
|
|
import { MarketConfig, Trade, TradeSide } from './interfaces'
|
|
|
|
import { RedisConfig, RedisStore, createRedisStore } from './redis'
|
|
|
|
import { resolutions, sleep } from './time'
|
2021-02-15 04:42:34 -08:00
|
|
|
|
2021-05-31 03:33:39 -07:00
|
|
|
async function collectEventQueue(m: MarketConfig, r: RedisConfig) {
|
|
|
|
const store = await createRedisStore(r, m.marketName)
|
|
|
|
const marketAddress = new PublicKey(m.marketPk)
|
|
|
|
const programKey = new PublicKey(m.programId)
|
|
|
|
const connection = new Connection(m.clusterUrl)
|
2021-07-02 08:55:57 -07:00
|
|
|
const market = await Market.load(
|
|
|
|
connection,
|
|
|
|
marketAddress,
|
|
|
|
undefined,
|
|
|
|
programKey
|
|
|
|
)
|
2021-02-15 04:42:34 -08:00
|
|
|
|
2021-05-31 03:33:39 -07:00
|
|
|
async function fetchTrades(lastSeqNum?: number): Promise<[Trade[], number]> {
|
2021-04-27 06:27:38 -07:00
|
|
|
const now = Date.now()
|
2021-07-02 08:55:57 -07:00
|
|
|
const accountInfo = await connection.getAccountInfo(
|
|
|
|
market['_decoded'].eventQueue
|
|
|
|
)
|
2021-05-31 03:33:39 -07:00
|
|
|
if (accountInfo === null) {
|
2021-07-02 08:55:57 -07:00
|
|
|
throw new Error(
|
|
|
|
`Event queue account for market ${m.marketName} not found`
|
|
|
|
)
|
2021-05-31 03:33:39 -07:00
|
|
|
}
|
2021-07-02 08:55:57 -07:00
|
|
|
const { header, events } = decodeRecentEvents(accountInfo.data, lastSeqNum)
|
|
|
|
const takerFills = events.filter(
|
|
|
|
(e) => e.eventFlags.fill && !e.eventFlags.maker
|
|
|
|
)
|
|
|
|
const trades = takerFills
|
|
|
|
.map((e) => market.parseFillEvent(e))
|
|
|
|
.map((e) => {
|
|
|
|
return {
|
|
|
|
price: e.price,
|
|
|
|
side: e.side === 'buy' ? TradeSide.Buy : TradeSide.Sell,
|
|
|
|
size: e.size,
|
|
|
|
ts: now,
|
|
|
|
}
|
|
|
|
})
|
2021-05-31 03:33:39 -07:00
|
|
|
/*
|
|
|
|
if (trades.length > 0)
|
|
|
|
console.log({e: events.map(e => e.eventFlags), takerFills, trades})
|
|
|
|
*/
|
|
|
|
return [trades, header.seqNum]
|
2021-02-15 04:42:34 -08:00
|
|
|
}
|
2021-04-06 15:10:20 -07:00
|
|
|
|
|
|
|
async function storeTrades(ts: Trade[]) {
|
|
|
|
if (ts.length > 0) {
|
2021-04-27 06:27:38 -07:00
|
|
|
console.log(m.marketName, ts.length)
|
2021-04-06 15:10:20 -07:00
|
|
|
for (let i = 0; i < ts.length; i += 1) {
|
2021-04-27 06:27:38 -07:00
|
|
|
await store.storeTrade(ts[i])
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
|
|
|
}
|
2021-04-27 06:27:38 -07:00
|
|
|
}
|
2021-02-15 04:42:34 -08:00
|
|
|
|
|
|
|
while (true) {
|
|
|
|
try {
|
2021-07-02 08:55:57 -07:00
|
|
|
const lastSeqNum = await store.loadNumber('LASTSEQ')
|
|
|
|
const [trades, currentSeqNum] = await fetchTrades(lastSeqNum)
|
2021-04-27 06:27:38 -07:00
|
|
|
storeTrades(trades)
|
2021-05-31 03:33:39 -07:00
|
|
|
store.storeNumber('LASTSEQ', currentSeqNum)
|
2021-02-15 04:42:34 -08:00
|
|
|
} catch (err) {
|
2021-07-02 08:55:57 -07:00
|
|
|
const error = err.toString().split('\n', 1)[0]
|
2021-04-27 06:27:38 -07:00
|
|
|
console.error(m.marketName, { error })
|
2021-02-15 04:42:34 -08:00
|
|
|
}
|
2021-07-02 08:55:57 -07:00
|
|
|
await sleep({
|
|
|
|
Seconds: process.env.INTERVAL ? parseInt(process.env.INTERVAL) : 10,
|
|
|
|
})
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
2021-04-27 06:27:38 -07:00
|
|
|
}
|
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
const redisUrl = new URL(process.env.REDISCLOUD_URL || 'redis://localhost:6379')
|
2021-04-27 06:27:38 -07:00
|
|
|
const host = redisUrl.hostname
|
|
|
|
const port = parseInt(redisUrl.port)
|
|
|
|
let password: string | undefined
|
2021-07-02 08:55:57 -07:00
|
|
|
if (redisUrl.password !== '') {
|
2021-04-27 06:27:38 -07:00
|
|
|
password = redisUrl.password
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
const network = 'mainnet-beta'
|
|
|
|
const clusterUrl =
|
|
|
|
process.env.RPC_ENDPOINT_URL || 'https://solana-api.projectserum.com'
|
|
|
|
const programIdV3 = '9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin'
|
2021-04-06 15:10:20 -07:00
|
|
|
|
2021-04-27 06:27:38 -07:00
|
|
|
const nativeMarketsV3: Record<string, string> = {
|
2021-07-02 08:55:57 -07:00
|
|
|
'BTC/USDT': 'C1EuT9VokAKLiW7i2ASnZUvxDoKuKkCpDDeNxAptuNe4',
|
|
|
|
'ETH/USDT': '7dLVkUfBVfCGkFhSXDCq1ukM9usathSgS716t643iFGF',
|
|
|
|
'SOL/USDT': 'HWHvQhFmJB3NUcu1aihKmrKegfVxBEHzwVX6yZCKEsi1',
|
|
|
|
'SRM/USDT': 'AtNnsY1AyRERWJ8xCskfz38YdvruWVJQUVXgScC1iPb',
|
|
|
|
'RAY/USDT': 'teE55QrL4a4QSfydR9dnHF97jgCfptpuigbb53Lo95g',
|
|
|
|
'BTC/USDC': 'A8YFbxQYFVqKZaoYJLLUVcQiWP7G2MeEgW5wsAQgMvFw',
|
|
|
|
'ETH/USDC': '4tSvZvnbyzHXLMTiFonMyxZoHmFqau1XArcRCVHLZ5gX',
|
|
|
|
'SOL/USDC': '9wFFyRfZBsuAha4YcuxcXLKwMxJR43S7fPfQLusDBzvT',
|
|
|
|
'SRM/USDC': 'ByRys5tuUWDgL73G8JBAEfkdFf8JWBzPBDHsBVQ5vbQA',
|
|
|
|
'RAY/USDC': '2xiv8A5xrJ7RnGdxXB42uFEkYHJjszEhaJyKKt4WaLep',
|
|
|
|
'MCAPS/USDC': 'GgzXqy6agt7nnfoPjAEAFpWqnUwLBK5r2acaAQqXiEM8',
|
2021-04-27 06:27:38 -07:00
|
|
|
}
|
2021-04-06 15:10:20 -07:00
|
|
|
|
2021-04-27 06:27:38 -07:00
|
|
|
const symbolsByPk = Object.assign(
|
|
|
|
{},
|
|
|
|
...Object.entries(nativeMarketsV3).map(([a, b]) => ({ [b]: a }))
|
|
|
|
)
|
2021-04-06 15:10:20 -07:00
|
|
|
|
|
|
|
function collectMarketData(programId: string, markets: Record<string, string>) {
|
2021-04-27 06:27:38 -07:00
|
|
|
Object.entries(markets).forEach((e) => {
|
|
|
|
const [marketName, marketPk] = e
|
2021-07-02 08:55:57 -07:00
|
|
|
const marketConfig = {
|
|
|
|
clusterUrl,
|
|
|
|
programId,
|
|
|
|
marketName,
|
|
|
|
marketPk,
|
|
|
|
} as MarketConfig
|
|
|
|
collectEventQueue(marketConfig, { host, port, password, db: 0 })
|
2021-04-27 06:27:38 -07:00
|
|
|
})
|
|
|
|
}
|
2021-04-06 15:10:20 -07:00
|
|
|
|
2021-04-27 06:27:38 -07:00
|
|
|
collectMarketData(programIdV3, nativeMarketsV3)
|
2021-04-06 15:10:20 -07:00
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
const max_conn = parseInt(process.env.REDIS_MAX_CONN || '') || 200
|
2021-05-04 03:36:37 -07:00
|
|
|
const redisConfig = { host, port, password, db: 0, max_conn }
|
2021-04-27 06:27:38 -07:00
|
|
|
const pool = new TedisPool(redisConfig)
|
|
|
|
|
2021-05-31 03:33:39 -07:00
|
|
|
const app = express()
|
|
|
|
app.use(cors())
|
2021-04-27 06:27:38 -07:00
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
app.get('/tv/config', async (req, res) => {
|
2021-04-27 06:27:38 -07:00
|
|
|
const response = {
|
|
|
|
supported_resolutions: Object.keys(resolutions),
|
|
|
|
supports_group_request: false,
|
|
|
|
supports_marks: false,
|
|
|
|
supports_search: true,
|
|
|
|
supports_timescale_marks: false,
|
|
|
|
}
|
|
|
|
res.send(response)
|
|
|
|
})
|
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
app.get('/tv/symbols', async (req, res) => {
|
2021-04-27 06:27:38 -07:00
|
|
|
const symbol = req.query.symbol as string
|
|
|
|
const response = {
|
|
|
|
name: symbol,
|
|
|
|
ticker: symbol,
|
|
|
|
description: symbol,
|
2021-07-02 08:55:57 -07:00
|
|
|
type: 'Spot',
|
|
|
|
session: '24x7',
|
|
|
|
exchange: 'Mango',
|
|
|
|
listed_exchange: 'Mango',
|
|
|
|
timezone: 'Etc/UTC',
|
2021-04-27 06:27:38 -07:00
|
|
|
has_intraday: true,
|
|
|
|
supported_resolutions: Object.keys(resolutions),
|
|
|
|
minmov: 1,
|
|
|
|
pricescale: 100,
|
|
|
|
}
|
|
|
|
res.send(response)
|
|
|
|
})
|
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
app.get('/tv/history', async (req, res) => {
|
2021-04-06 15:10:20 -07:00
|
|
|
// parse
|
2021-04-27 06:27:38 -07:00
|
|
|
const marketName = req.query.symbol as string
|
2021-05-21 02:14:46 -07:00
|
|
|
const marketPk = nativeMarketsV3[marketName]
|
2021-04-27 06:27:38 -07:00
|
|
|
const resolution = resolutions[req.query.resolution as string] as number
|
|
|
|
let from = parseInt(req.query.from as string) * 1000
|
|
|
|
let to = parseInt(req.query.to as string) * 1000
|
2021-04-06 15:10:20 -07:00
|
|
|
|
|
|
|
// validate
|
2021-04-27 06:27:38 -07:00
|
|
|
const validSymbol = marketPk != undefined
|
|
|
|
const validResolution = resolution != undefined
|
|
|
|
const validFrom = true || new Date(from).getFullYear() >= 2021
|
2021-04-06 15:10:20 -07:00
|
|
|
if (!(validSymbol && validResolution && validFrom)) {
|
2021-07-02 08:55:57 -07:00
|
|
|
const error = { s: 'error', validSymbol, validResolution, validFrom }
|
2021-05-31 03:33:39 -07:00
|
|
|
console.error({ marketName, error })
|
|
|
|
res.status(404).send(error)
|
2021-04-27 06:27:38 -07:00
|
|
|
return
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
|
|
|
|
2021-05-31 03:33:39 -07:00
|
|
|
// respond
|
2021-04-06 15:10:20 -07:00
|
|
|
try {
|
2021-04-27 06:27:38 -07:00
|
|
|
const conn = await pool.getTedis()
|
2021-04-06 15:10:20 -07:00
|
|
|
try {
|
2021-04-27 06:27:38 -07:00
|
|
|
const store = new RedisStore(conn, marketName)
|
2021-04-06 15:10:20 -07:00
|
|
|
|
|
|
|
// snap candle boundaries to exact hours
|
2021-04-27 06:27:38 -07:00
|
|
|
from = Math.floor(from / resolution) * resolution
|
|
|
|
to = Math.ceil(to / resolution) * resolution
|
2021-04-06 15:10:20 -07:00
|
|
|
|
|
|
|
// ensure the candle is at least one period in length
|
|
|
|
if (from == to) {
|
2021-04-27 06:27:38 -07:00
|
|
|
to += resolution
|
|
|
|
}
|
|
|
|
const candles = await store.loadCandles(resolution, from, to)
|
|
|
|
const response = {
|
2021-07-02 08:55:57 -07:00
|
|
|
s: 'ok',
|
2021-04-27 06:27:38 -07:00
|
|
|
t: candles.map((c) => c.start / 1000),
|
|
|
|
c: candles.map((c) => c.close),
|
|
|
|
o: candles.map((c) => c.open),
|
|
|
|
h: candles.map((c) => c.high),
|
|
|
|
l: candles.map((c) => c.low),
|
|
|
|
v: candles.map((c) => c.volume),
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
2021-04-27 06:27:38 -07:00
|
|
|
res.send(response)
|
|
|
|
return
|
2021-04-06 15:10:20 -07:00
|
|
|
} finally {
|
2021-04-27 06:27:38 -07:00
|
|
|
pool.putTedis(conn)
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2021-04-27 06:27:38 -07:00
|
|
|
console.error({ req, e })
|
2021-07-02 08:55:57 -07:00
|
|
|
const error = { s: 'error' }
|
2021-04-27 06:27:38 -07:00
|
|
|
res.status(500).send(error)
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
2021-04-27 06:27:38 -07:00
|
|
|
})
|
2021-02-15 04:42:34 -08:00
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
app.get('/trades/address/:marketPk', async (req, res) => {
|
2021-05-31 03:33:39 -07:00
|
|
|
// parse
|
|
|
|
const marketPk = req.params.marketPk as string
|
|
|
|
const marketName = symbolsByPk[marketPk]
|
|
|
|
|
|
|
|
// validate
|
|
|
|
const validPk = marketName != undefined
|
|
|
|
if (!validPk) {
|
2021-07-02 08:55:57 -07:00
|
|
|
const error = { s: 'error', validPk }
|
2021-05-31 03:33:39 -07:00
|
|
|
console.error({ marketPk, error })
|
|
|
|
res.status(404).send(error)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// respond
|
2021-04-06 15:10:20 -07:00
|
|
|
try {
|
2021-04-27 06:27:38 -07:00
|
|
|
const conn = await pool.getTedis()
|
2021-04-06 15:10:20 -07:00
|
|
|
try {
|
2021-04-27 06:27:38 -07:00
|
|
|
const store = new RedisStore(conn, marketName)
|
|
|
|
const trades = await store.loadRecentTrades()
|
|
|
|
const response = {
|
|
|
|
success: true,
|
|
|
|
data: trades.map((t) => {
|
|
|
|
return {
|
|
|
|
market: marketName,
|
|
|
|
marketAddress: marketPk,
|
|
|
|
price: t.price,
|
|
|
|
size: t.size,
|
2021-07-02 08:55:57 -07:00
|
|
|
side: t.side == TradeSide.Buy ? 'buy' : 'sell',
|
2021-04-27 06:27:38 -07:00
|
|
|
time: t.ts,
|
2021-07-02 08:55:57 -07:00
|
|
|
orderId: '',
|
2021-04-27 06:27:38 -07:00
|
|
|
feeCost: 0,
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
res.send(response)
|
|
|
|
return
|
2021-04-06 15:10:20 -07:00
|
|
|
} finally {
|
2021-04-27 06:27:38 -07:00
|
|
|
pool.putTedis(conn)
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2021-04-27 06:27:38 -07:00
|
|
|
console.error({ req, e })
|
2021-07-02 08:55:57 -07:00
|
|
|
const error = { s: 'error' }
|
2021-04-27 06:27:38 -07:00
|
|
|
res.status(500).send(error)
|
2021-04-06 15:10:20 -07:00
|
|
|
}
|
2021-04-27 06:27:38 -07:00
|
|
|
})
|
2021-04-06 15:10:20 -07:00
|
|
|
|
2021-07-02 08:55:57 -07:00
|
|
|
const httpPort = parseInt(process.env.PORT || '5000')
|
2021-04-27 06:27:38 -07:00
|
|
|
app.listen(httpPort)
|