refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import Fastify from 'fastify'
|
||||
import rateLimit from '@fastify/rate-limit'
|
||||
import cors from '@fastify/cors'
|
||||
import websocket from '@fastify/websocket'
|
||||
import { ZodError } from 'zod'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { Services } from '@trumpsignal/backend/services'
|
||||
import { registerPosts } from './routes/posts'
|
||||
import { registerMacro } from './routes/macro'
|
||||
import { registerAccounts } from './routes/accounts'
|
||||
import { registerPositions } from './routes/positions'
|
||||
import { registerSignals } from './routes/signals'
|
||||
import { registerKol } from './routes/kol'
|
||||
import { registerTelegram } from './routes/telegram'
|
||||
import { registerDev } from './routes/dev'
|
||||
export async function createApp(c: Context, s: Services) {
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
redact: [
|
||||
'req.headers.authorization',
|
||||
'req.headers.x-sig-sig',
|
||||
'req.headers.x-ingest-key',
|
||||
'req.body.api_key',
|
||||
'req.body.signature',
|
||||
],
|
||||
},
|
||||
trustProxy: process.env.TRUSTED_PROXY
|
||||
? process.env.TRUSTED_PROXY.split(',').map((value) => value.trim())
|
||||
: false,
|
||||
bodyLimit: 1024 * 1024,
|
||||
})
|
||||
await app.register(rateLimit, { max: 120, timeWindow: '1 minute' })
|
||||
await app.register(cors, { origin: c.config.frontend_url.split(',').map((s) => s.trim()) })
|
||||
await app.register(websocket)
|
||||
app.setErrorHandler((error, req, reply) => {
|
||||
if (error instanceof ZodError)
|
||||
return reply
|
||||
.code(422)
|
||||
.send({ detail: error.issues.map((i) => ({ path: i.path, message: i.message })) })
|
||||
const code =
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'statusCode' in error &&
|
||||
typeof error.statusCode === 'number'
|
||||
? error.statusCode
|
||||
: 500
|
||||
const message = error instanceof Error ? error.message : 'Request failed'
|
||||
if (code >= 500)
|
||||
req.log.error(
|
||||
{
|
||||
err: {
|
||||
name: error instanceof Error ? error.name : 'Error',
|
||||
message: 'Server operation failed',
|
||||
},
|
||||
},
|
||||
'Request failed',
|
||||
)
|
||||
return reply.code(code).send({ detail: code >= 500 ? 'Server operation failed' : message })
|
||||
})
|
||||
await registerPosts(app, c.db)
|
||||
await registerMacro(app, c.db)
|
||||
await registerAccounts(app, c)
|
||||
await registerPositions(app, c, s.engine)
|
||||
await registerSignals(app, c, s)
|
||||
await registerKol(app, c, s.kol)
|
||||
await registerTelegram(app, c, s.telegram)
|
||||
if (c.config.environment === 'development') await registerDev(app, c, s)
|
||||
app.get('/ws', { websocket: true }, (socket) => {
|
||||
const unsub = c.events.subscribe((event) => {
|
||||
if (socket.readyState !== 1 || socket.bufferedAmount > 1024 * 1024) {
|
||||
socket.terminate()
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify(event))
|
||||
})
|
||||
const timer = setInterval(() => {
|
||||
if (socket.readyState !== 1) {
|
||||
clearInterval(timer)
|
||||
unsub()
|
||||
return
|
||||
}
|
||||
socket.ping()
|
||||
}, 30000)
|
||||
socket.on('close', () => {
|
||||
clearInterval(timer)
|
||||
unsub()
|
||||
})
|
||||
socket.on('error', () => {
|
||||
clearInterval(timer)
|
||||
unsub()
|
||||
})
|
||||
})
|
||||
app.get('/api/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }))
|
||||
app.get('/api/health/deep', async () => {
|
||||
const leader = await s.state.get<{ last_seen: number }>('worker:heartbeat', { last_seen: 0 }),
|
||||
binance = await s.state.get<{ last_tick_at?: string }>('health:binance', {}),
|
||||
cnn = await s.state.get<{ last_successful_poll_at?: string }>('health:cnn', {}),
|
||||
rss = await s.state.get<{ last_successful_poll_at?: string }>('health:rss', {}),
|
||||
problems: string[] = []
|
||||
if (Date.now() - leader.last_seen > 90000) problems.push('worker_not_running')
|
||||
if (!binance.last_tick_at || Date.now() - Date.parse(binance.last_tick_at) > 90000)
|
||||
problems.push('binance_stale')
|
||||
return {
|
||||
status: problems.length ? 'degraded' : 'ok',
|
||||
is_leader: Date.now() - leader.last_seen < 90000,
|
||||
problems,
|
||||
binance,
|
||||
truth_social: cnn,
|
||||
trumpstruth: rss,
|
||||
}
|
||||
})
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createDatabase } from '@trumpsignal/database'
|
||||
import { readConfig } from '@trumpsignal/backend/config'
|
||||
import { createContext } from '@trumpsignal/backend/context'
|
||||
import { createServices } from '@trumpsignal/backend/services'
|
||||
import { startBridge } from '@trumpsignal/backend/bridge'
|
||||
import { createApp } from './app'
|
||||
const config = readConfig(),
|
||||
database = createDatabase(config.database_url),
|
||||
context = createContext(database, config),
|
||||
services = createServices(context)
|
||||
await services.prices.backfill()
|
||||
const stopBridge = await startBridge(context),
|
||||
app = await createApp(context, services)
|
||||
let stopping = false
|
||||
async function shutdown() {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
await app.close()
|
||||
await stopBridge()
|
||||
await database.pool.end()
|
||||
await database.lockPool.end()
|
||||
}
|
||||
process.once('SIGINT', () => {
|
||||
void shutdown()
|
||||
})
|
||||
process.once('SIGTERM', () => {
|
||||
void shutdown()
|
||||
})
|
||||
await app.listen({ host: process.env.HOST ?? '0.0.0.0', port: Number(process.env.PORT ?? 8000) })
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { subscriptions } from '@trumpsignal/database'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { RawBody } from '@trumpsignal/backend/auth'
|
||||
import { requireThat, utcMs } from '@trumpsignal/backend/http'
|
||||
import {
|
||||
subscribe,
|
||||
publicUser,
|
||||
privateUser,
|
||||
setKey,
|
||||
clearAndArm,
|
||||
closedTrades,
|
||||
performance,
|
||||
subscription,
|
||||
settingsDto,
|
||||
} from '@trumpsignal/backend/accounts'
|
||||
const body = (r: FastifyRequest) => z.record(z.unknown()).parse(r.body) as RawBody
|
||||
const wallet = (r: FastifyRequest) =>
|
||||
z
|
||||
.string()
|
||||
.parse((r.params as { wallet: string }).wallet)
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
const settingsSchema = z.object({
|
||||
leverage: z.number().int().min(1).max(50),
|
||||
position_size_usd: z.number().min(5).max(10000),
|
||||
take_profit_pct: z.number().min(0.1).max(50).nullable().optional(),
|
||||
stop_loss_pct: z.number().min(0.1).max(50).nullable().optional(),
|
||||
min_confidence: z.number().int().min(0).max(100),
|
||||
daily_budget_usd: z.number().positive().max(100000).nullable().optional(),
|
||||
sys2_leverage: z.number().int().min(1).max(10).nullable().optional(),
|
||||
sys2_mode: z.enum(['standard', 'aggressive', '']).nullable().optional(),
|
||||
active_from: z.string().nullable().optional(),
|
||||
active_until: z.string().nullable().optional(),
|
||||
trump_enabled: z.boolean().nullable().optional(),
|
||||
macro_enabled: z.boolean().nullable().optional(),
|
||||
})
|
||||
export async function registerAccounts(app: FastifyInstance, c: Context) {
|
||||
app.post('/api/subscribe', async (req) => {
|
||||
const raw = body(req)
|
||||
const paper = z.boolean().optional().parse(raw.paper_mode) ?? false
|
||||
const w = await c.auth.write('subscribe', raw, paper ? { paper_mode: true } : null)
|
||||
return subscribe(c, w, paper)
|
||||
})
|
||||
app.get('/api/user/:wallet/public', async (req) => publicUser(c, wallet(req)))
|
||||
app.get('/api/user/:wallet', async (req) => {
|
||||
const w = await c.auth.read(['view_user'], wallet(req), req.headers, req.query as RawBody)
|
||||
return privateUser(c, w)
|
||||
})
|
||||
app.put('/api/user/:wallet/hl-api-key', async (req) => {
|
||||
const raw = body(req),
|
||||
key = z.string().parse(raw.api_key).trim()
|
||||
const w = await c.auth.write('set_hl_api_key', raw, { api_key: key }, wallet(req))
|
||||
return setKey(c, w, key)
|
||||
})
|
||||
app.put('/api/user/:wallet/settings', async (req) => {
|
||||
const raw = body(req),
|
||||
s = settingsSchema.parse(raw.settings)
|
||||
if (s.trump_enabled)
|
||||
requireThat(
|
||||
s.take_profit_pct != null && s.stop_loss_pct != null,
|
||||
422,
|
||||
'TP and SL required when Trump module is enabled',
|
||||
)
|
||||
const af = s.active_from ? utcMs(s.active_from) : null,
|
||||
au = s.active_until ? utcMs(s.active_until) : null
|
||||
requireThat(
|
||||
(af == null) === (au == null) &&
|
||||
(af == null || (Number.isFinite(af) && Number.isFinite(au) && au! > af)),
|
||||
422,
|
||||
'Invalid active window',
|
||||
)
|
||||
const w = await c.auth.write('set_settings', raw, raw.settings, wallet(req))
|
||||
const sub = await subscription(c, w)
|
||||
const values = {
|
||||
leverage: s.leverage,
|
||||
position_size_usd: s.position_size_usd,
|
||||
take_profit_pct: s.take_profit_pct ?? null,
|
||||
stop_loss_pct: s.stop_loss_pct ?? null,
|
||||
min_confidence: s.min_confidence,
|
||||
daily_budget_usd: s.daily_budget_usd ?? null,
|
||||
sys2_leverage: s.sys2_leverage ?? null,
|
||||
active_from: af == null ? null : new Date(af).toISOString().slice(0, -1),
|
||||
active_until: au == null ? null : new Date(au).toISOString().slice(0, -1),
|
||||
...(s.sys2_mode != null ? { sys2_mode: s.sys2_mode || 'standard' } : {}),
|
||||
...(s.trump_enabled != null ? { trump_enabled: s.trump_enabled } : {}),
|
||||
...(s.macro_enabled != null ? { macro_enabled: s.macro_enabled } : {}),
|
||||
}
|
||||
await c.db.update(subscriptions).set(values).where(eq(subscriptions.id, sub.id))
|
||||
return {
|
||||
...s,
|
||||
active_from: af == null ? null : new Date(af).toISOString(),
|
||||
active_until: au == null ? null : new Date(au).toISOString(),
|
||||
}
|
||||
})
|
||||
app.post('/api/user/:wallet/manual-window', async (req) => {
|
||||
const raw = body(req),
|
||||
hours = z.number().int().min(0).max(168).parse(raw.hours)
|
||||
const w = await c.auth.write('set_manual_window', raw, { hours }, wallet(req))
|
||||
return clearAndArm(c, w, { hours })
|
||||
})
|
||||
app.post('/api/user/:wallet/auto-trade', async (req) => {
|
||||
const raw = body(req),
|
||||
enabled = z.boolean().parse(raw.enabled)
|
||||
const w = await c.auth.write('set_auto_trade', raw, { enabled }, wallet(req))
|
||||
return clearAndArm(c, w, { enabled })
|
||||
})
|
||||
app.get('/api/trades', async (req) => {
|
||||
const q = z
|
||||
.object({
|
||||
wallet: z.string(),
|
||||
limit: z.coerce.number().int().min(1).max(500).default(20),
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
})
|
||||
.passthrough()
|
||||
.parse(req.query)
|
||||
const w = await c.auth.read(['view_trades', 'view_user'], q.wallet, req.headers, q)
|
||||
return closedTrades(c, w, q.limit, q.page)
|
||||
})
|
||||
app.get('/api/performance', async (req) => {
|
||||
const q = z
|
||||
.object({ wallet: z.string(), include_paper: z.enum(['true', 'false']).optional() })
|
||||
.passthrough()
|
||||
.parse(req.query)
|
||||
const w = await c.auth.read(['view_performance', 'view_user'], q.wallet, req.headers, q)
|
||||
return performance(c, w, q.include_paper === 'true')
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { posts, subscriptions } from '@trumpsignal/database'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { Services } from '@trumpsignal/backend/services'
|
||||
import { postDto } from '@trumpsignal/backend/post-dto'
|
||||
import { utcNow, requireThat } from '@trumpsignal/backend/http'
|
||||
import {
|
||||
backtestPost,
|
||||
backtestBatch,
|
||||
backfillImpact,
|
||||
reanalyze,
|
||||
} from '@trumpsignal/backend/operations'
|
||||
const qSchema = z.object({
|
||||
post_id: z.coerce.number().int().positive().optional(),
|
||||
stop_loss_pct: z.coerce.number().min(0.01).max(100).default(1.5),
|
||||
trailing_stop_pct: z.coerce.number().min(0).default(2.5),
|
||||
trailing_activate_at_pct: z.coerce.number().min(0).default(5),
|
||||
take_profit_pct: z.coerce.number().min(0).default(0),
|
||||
max_hold_hours: z.coerce.number().int().min(1).max(12960).default(168),
|
||||
limit: z.coerce.number().int().min(1).max(500).default(50),
|
||||
min_confidence: z.coerce.number().int().min(0).max(100).default(80),
|
||||
})
|
||||
export async function registerDev(app: FastifyInstance, c: Context, s: Services) {
|
||||
app.post('/api/dev/fake-post', async (req) => {
|
||||
const q = z
|
||||
.object({
|
||||
text: z.string().default('BITCOIN is the future of money!'),
|
||||
sentiment: z.enum(['bullish', 'bearish', 'neutral']).default('bullish'),
|
||||
})
|
||||
.parse(req.query),
|
||||
[p] = await c.db
|
||||
.insert(posts)
|
||||
.values({
|
||||
...q,
|
||||
external_id: randomBytes(16).toString('hex'),
|
||||
source: 'truth',
|
||||
published_at: utcNow(),
|
||||
ai_confidence: 88,
|
||||
relevant: true,
|
||||
price_impact_asset: 'BTC',
|
||||
price_at_post: 94230,
|
||||
price_impact_m5: 1.2,
|
||||
price_impact_m15: 2.4,
|
||||
price_impact_m1h: 3.1,
|
||||
})
|
||||
.returning()
|
||||
c.events.broadcast({ type: 'new_post', post: postDto(p) })
|
||||
return { id: p.id, text: p.text.slice(0, 80) }
|
||||
})
|
||||
app.post('/api/dev/fake-signal', async (req) => {
|
||||
const q = z
|
||||
.object({
|
||||
symbol: z.string().default('ETHUSDT'),
|
||||
close: z.coerce.number().default(1850.42),
|
||||
tbr: z.coerce.number().default(0.72),
|
||||
vol_mult: z.coerce.number().default(3.1),
|
||||
bb_pct: z.coerce.number().default(8.5),
|
||||
btc_trend: z.string().default('↑ uptrend'),
|
||||
})
|
||||
.parse(req.query),
|
||||
enabled = await s.state.get('breakout-enabled', false),
|
||||
alert = {
|
||||
type: 'funding_signal',
|
||||
...q,
|
||||
time: new Date().toISOString(),
|
||||
bb_upper: q.close * 1.002,
|
||||
enabled,
|
||||
}
|
||||
await s.state.change<unknown[]>('breakout-history', [], (history) =>
|
||||
[...history, alert].slice(-100),
|
||||
)
|
||||
if (enabled) c.events.broadcast(alert)
|
||||
return { status: enabled ? 'broadcast' : 'recorded_only (monitor OFF)', alert }
|
||||
})
|
||||
app.post('/api/dev/reanalyze', async (req) => {
|
||||
const q = z
|
||||
.object({
|
||||
limit: z.coerce.number().int().min(1).max(10000).default(500),
|
||||
dry_run: z.enum(['true', 'false']).default('false'),
|
||||
delay_secs: z.coerce.number().min(0).max(60).default(0.5),
|
||||
legacy_signals: z.enum(['true', 'false']).default('false'),
|
||||
model: z.string().optional(),
|
||||
})
|
||||
.parse(req.query),
|
||||
state = await s.state.get<{ running: boolean }>('reanalyze', { running: false })
|
||||
if (state.running) return { status: 'already_running', state }
|
||||
const options = {
|
||||
...q,
|
||||
dry_run: q.dry_run === 'true',
|
||||
legacy_signals: q.legacy_signals === 'true',
|
||||
}
|
||||
void reanalyze(c, s, options).catch(() => {})
|
||||
return { status: 'started', ...options }
|
||||
})
|
||||
app.get('/api/dev/reanalyze/status', async () =>
|
||||
s.state.get('reanalyze', { running: false, processed: 0, errors: 0 }),
|
||||
)
|
||||
app.post('/api/dev/backfill-prices', async (req) => {
|
||||
const q = z.object({ asset: z.enum(['BTC', 'ETH']).default('BTC') }).parse(req.query)
|
||||
void backfillImpact(c, q.asset).catch(() => {})
|
||||
return { status: 'started', asset: q.asset }
|
||||
})
|
||||
for (const mode of ['post', 'batch'] as const)
|
||||
app.post('/api/dev/backtest/' + mode, async (req) => {
|
||||
const q = qSchema.parse(req.query),
|
||||
params = {
|
||||
stop_loss_pct: q.stop_loss_pct,
|
||||
trailing_stop_pct: q.trailing_stop_pct || null,
|
||||
trailing_activate_at_pct: q.trailing_activate_at_pct || null,
|
||||
take_profit_pct: q.take_profit_pct || null,
|
||||
max_hold_hours: q.max_hold_hours,
|
||||
}
|
||||
if (mode === 'batch') return backtestBatch(c, q.limit, q.min_confidence, params)
|
||||
requireThat(q.post_id, 422, 'post_id required')
|
||||
const result = await backtestPost(c, q.post_id, params)
|
||||
return result ? { status: 'ok', result } : { status: 'skipped', post_id: q.post_id }
|
||||
})
|
||||
app.post('/api/dev/paper-mode', async (req) => {
|
||||
const q = z.object({ wallet: z.string(), enabled: z.enum(['true', 'false']) }).parse(req.query),
|
||||
[s] = await c.db
|
||||
.update(subscriptions)
|
||||
.set({
|
||||
paper_mode: q.enabled === 'true',
|
||||
...(q.enabled === 'false' ? { auto_trade: false } : {}),
|
||||
})
|
||||
.where(eq(subscriptions.wallet_address, q.wallet.toLowerCase().trim()))
|
||||
.returning()
|
||||
return {
|
||||
status: s ? 'ok' : 'not_found',
|
||||
wallet: q.wallet.toLowerCase().trim(),
|
||||
paper_mode: q.enabled === 'true',
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
import { and, eq, gte, desc, asc, count, sql, or, ne, isNull } from 'drizzle-orm'
|
||||
import {
|
||||
kol_posts as posts,
|
||||
kol_wallets as wallets,
|
||||
kol_holdings_snapshots as snapshots,
|
||||
kol_holding_changes as changes,
|
||||
kol_divergence as divergence,
|
||||
} from '@trumpsignal/database'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import { Kol, kolDto, parseArray } from '@trumpsignal/backend/kol'
|
||||
import { requireThat, iso } from '@trumpsignal/backend/http'
|
||||
import { requireIngestKey } from './signals'
|
||||
const query = z.object({
|
||||
handle: z.string().optional(),
|
||||
source: z.string().optional(),
|
||||
ticker: z
|
||||
.string()
|
||||
.regex(/^[A-Za-z0-9]{1,12}$/)
|
||||
.optional(),
|
||||
signal_type: z.string().optional(),
|
||||
signals_only: z.enum(['true', 'false']).optional(),
|
||||
days: z.coerce.number().int().min(1).max(365).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).default(50),
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
lookback_days: z.coerce.number().int().min(1).max(90).default(30),
|
||||
})
|
||||
const since = (days: number) => new Date(Date.now() - days * 86400000).toISOString().slice(0, -1)
|
||||
const walletDto = (w: typeof wallets.$inferSelect) => ({ ...w, added_at: iso(w.added_at) })
|
||||
export async function registerKol(app: FastifyInstance, c: Context, kol: Kol) {
|
||||
app.get('/api/kol/posts', async (req) => {
|
||||
const q = query.parse(req.query),
|
||||
scope = and(
|
||||
q.handle ? eq(posts.kol_handle, q.handle) : undefined,
|
||||
q.source ? eq(posts.source, q.source) : undefined,
|
||||
q.signals_only === 'true' ? or(isNull(posts.tier), ne(posts.tier, 'noise')) : undefined,
|
||||
q.ticker
|
||||
? sql`${posts.tickers_json}::jsonb @> ${JSON.stringify([{ ticker: q.ticker.toUpperCase() }])}::jsonb`
|
||||
: undefined,
|
||||
q.days ? gte(posts.published_at, since(q.days)) : undefined,
|
||||
)
|
||||
const [rows, totals] = await Promise.all([
|
||||
c.db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(scope)
|
||||
.orderBy(desc(posts.published_at))
|
||||
.limit(q.limit)
|
||||
.offset((q.page - 1) * q.limit),
|
||||
c.db.select({ n: count() }).from(posts).where(scope),
|
||||
])
|
||||
return { items: rows.map(kolDto), page: q.page, limit: q.limit, total: totals[0].n }
|
||||
})
|
||||
app.get<{ Params: { id: string } }>('/api/kol/posts/:id', async (req) => {
|
||||
const [p] = await c.db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(eq(posts.id, z.coerce.number().int().positive().parse(req.params.id)))
|
||||
.limit(1)
|
||||
requireThat(p, 404, 'KOL post not found')
|
||||
return { ...kolDto(p), raw_text: p.raw_text }
|
||||
})
|
||||
app.get('/api/kol/digest', async (req) => {
|
||||
const q = query.parse(req.query)
|
||||
return kol.digest(Math.min(q.days ?? 7, 90))
|
||||
})
|
||||
app.get('/api/kol/wallets', async (req) => {
|
||||
const q = query.parse(req.query),
|
||||
rows = await c.db
|
||||
.select()
|
||||
.from(wallets)
|
||||
.where(and(eq(wallets.active, true), q.handle ? eq(wallets.handle, q.handle) : undefined))
|
||||
.orderBy(asc(wallets.handle))
|
||||
return { wallets: rows.map(walletDto) }
|
||||
})
|
||||
app.post('/api/kol/wallets', async (req) => {
|
||||
requireIngestKey(c, req.headers['x-ingest-key'])
|
||||
const b = z
|
||||
.object({
|
||||
handle: z.string().min(1).max(64),
|
||||
chain: z.string().min(1).max(16),
|
||||
address: z.string().min(1).max(128),
|
||||
label: z.string().max(128).nullable().optional(),
|
||||
source_url: z.string().max(256).nullable().optional(),
|
||||
})
|
||||
.parse(req.body)
|
||||
const [row] = await c.db
|
||||
.insert(wallets)
|
||||
.values({ ...b, address: b.address.toLowerCase() })
|
||||
.onConflictDoNothing()
|
||||
.returning()
|
||||
requireThat(row, 409, 'Wallet already tracked')
|
||||
return walletDto(row)
|
||||
})
|
||||
app.get<{ Params: { id: string } }>('/api/kol/wallets/:id/snapshots', async (req) => {
|
||||
const id = z.coerce.number().int().positive().parse(req.params.id),
|
||||
q = query.parse(req.query),
|
||||
[w] = await c.db.select().from(wallets).where(eq(wallets.id, id))
|
||||
requireThat(w, 404, 'Wallet not found')
|
||||
const rows = await c.db
|
||||
.select()
|
||||
.from(snapshots)
|
||||
.where(eq(snapshots.wallet_id, id))
|
||||
.orderBy(desc(snapshots.snapshot_date))
|
||||
.limit(Math.min(q.limit, 90))
|
||||
return {
|
||||
wallet: walletDto(w),
|
||||
snapshots: rows.map((s) => ({
|
||||
id: s.id,
|
||||
wallet_id: s.wallet_id,
|
||||
snapshot_date: s.snapshot_date,
|
||||
holdings: parseArray(s.holdings_json),
|
||||
total_usd: s.total_usd,
|
||||
source: s.source,
|
||||
created_at: iso(s.created_at),
|
||||
})),
|
||||
}
|
||||
})
|
||||
app.get('/api/kol/changes', async (req) => {
|
||||
const q = query.parse(req.query),
|
||||
days = Math.min(q.days ?? 7, 90),
|
||||
cutoff = since(days),
|
||||
rows = await c.db
|
||||
.select({ change: changes, handle: wallets.handle })
|
||||
.from(changes)
|
||||
.innerJoin(wallets, eq(changes.wallet_id, wallets.id))
|
||||
.where(
|
||||
and(
|
||||
gte(changes.detected_at, cutoff),
|
||||
q.handle ? eq(wallets.handle, q.handle) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(changes.detected_at))
|
||||
.limit(200)
|
||||
return {
|
||||
window_days: days,
|
||||
since: iso(cutoff),
|
||||
count: rows.length,
|
||||
changes: rows.map(({ change, handle }) => ({
|
||||
...change,
|
||||
handle,
|
||||
detected_at: iso(change.detected_at),
|
||||
})),
|
||||
}
|
||||
})
|
||||
app.get('/api/kol/divergence', async (req) => {
|
||||
const q = query.parse(req.query),
|
||||
days = Math.min(q.days ?? 30, 180),
|
||||
cutoff = since(days),
|
||||
rows = await c.db
|
||||
.select()
|
||||
.from(divergence)
|
||||
.where(
|
||||
and(
|
||||
gte(divergence.post_at, cutoff),
|
||||
q.handle ? eq(divergence.handle, q.handle) : undefined,
|
||||
q.ticker ? eq(divergence.ticker, q.ticker.toUpperCase()) : undefined,
|
||||
q.signal_type ? eq(divergence.signal_type, q.signal_type) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(divergence.post_at), desc(divergence.created_at))
|
||||
.limit(200)
|
||||
return {
|
||||
window_days: days,
|
||||
since: iso(cutoff),
|
||||
count: rows.length,
|
||||
items: rows.map((d) => ({
|
||||
...d,
|
||||
post_at: iso(d.post_at),
|
||||
onchain_at: iso(d.onchain_at),
|
||||
created_at: iso(d.created_at),
|
||||
})),
|
||||
}
|
||||
})
|
||||
app.post('/api/kol/divergence/scan', async (req) => {
|
||||
requireIngestKey(c, req.headers['x-ingest-key'])
|
||||
const q = query.parse(req.query),
|
||||
items = await kol.divergence(q.lookback_days)
|
||||
return { new_pairs: items.length, items }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { desc, asc, gte } from 'drizzle-orm'
|
||||
import { macro_snapshots as snapshots, type createDatabase } from '@trumpsignal/database'
|
||||
import { iso } from './posts'
|
||||
const keys = [
|
||||
'ahr999',
|
||||
'altcoin_season_index',
|
||||
'fear_greed',
|
||||
'fear_greed_label',
|
||||
'btc_dominance_pct',
|
||||
'eth_btc_ratio',
|
||||
'stablecoin_supply_usd',
|
||||
'etf_flow_net_usd_1d',
|
||||
'btc_open_interest_usd',
|
||||
] as const
|
||||
function dto(row: typeof snapshots.$inferSelect) {
|
||||
return {
|
||||
date: row.snapshot_date,
|
||||
captured_at: iso(row.captured_at),
|
||||
indicators: Object.fromEntries(keys.map((k) => [k, row[k]])),
|
||||
composite_score: row.composite_score,
|
||||
regime_label: row.regime_label,
|
||||
}
|
||||
}
|
||||
export async function registerMacro(
|
||||
app: FastifyInstance,
|
||||
db: ReturnType<typeof createDatabase>['db'],
|
||||
) {
|
||||
app.get('/api/macro/snapshot', async () => {
|
||||
const [r] = await db.select().from(snapshots).orderBy(desc(snapshots.snapshot_date)).limit(1)
|
||||
return r ? { ok: true, ...dto(r) } : { ok: false, error: 'no snapshots yet — poll has not run' }
|
||||
})
|
||||
app.get<{ Querystring: { days: number } }>(
|
||||
'/api/macro/history',
|
||||
{
|
||||
schema: {
|
||||
querystring: {
|
||||
type: 'object',
|
||||
properties: { days: { type: 'integer', minimum: 1, maximum: 365, default: 30 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
async (req) => {
|
||||
const days = req.query.days
|
||||
const cutoff = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10)
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(snapshots)
|
||||
.where(gte(snapshots.snapshot_date, cutoff))
|
||||
.orderBy(asc(snapshots.snapshot_date))
|
||||
return { ok: true, days, count: rows.length, items: rows.map(dto) }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
import { and, eq, isNull, gte, isNotNull, desc } from 'drizzle-orm'
|
||||
import { bot_trades as trades } from '@trumpsignal/database'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { Engine } from '@trumpsignal/backend/engine'
|
||||
import { requireThat, round, iso, utcMs } from '@trumpsignal/backend/http'
|
||||
import type { RawBody } from '@trumpsignal/backend/auth'
|
||||
const raw = (r: FastifyRequest) => z.record(z.unknown()).parse(r.body)
|
||||
const id = (r: FastifyRequest) =>
|
||||
z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.parse((r.params as { id: string }).id)
|
||||
export async function registerPositions(app: FastifyInstance, c: Context, engine: Engine) {
|
||||
async function read(req: FastifyRequest, path = false) {
|
||||
const q = z.record(z.unknown()).parse(req.query),
|
||||
wallet = z.string().parse(path ? (req.params as { wallet: string }).wallet : q.wallet)
|
||||
return c.auth.read(['view_positions', 'view_user'], wallet, req.headers, q)
|
||||
}
|
||||
app.get('/api/positions/open', async (req) => {
|
||||
const wallet = await read(req),
|
||||
rows = await c.db
|
||||
.select()
|
||||
.from(trades)
|
||||
.where(
|
||||
and(
|
||||
eq(trades.wallet_address, wallet),
|
||||
isNull(trades.closed_at),
|
||||
isNull(trades.released_at),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(trades.opened_at))
|
||||
return {
|
||||
wallet,
|
||||
count: rows.length,
|
||||
positions: rows.map((t) => {
|
||||
const px = c.prices.latest(t.asset),
|
||||
notional = round((t.size_usd ?? 0) * (t.remaining_fraction ?? 1)),
|
||||
pct =
|
||||
px != null
|
||||
? ((px - t.entry_price) / t.entry_price) * (t.side === 'long' ? 1 : -1) * 100
|
||||
: null
|
||||
return {
|
||||
trade_id: t.id,
|
||||
asset: t.asset,
|
||||
side: t.side,
|
||||
entry_price: t.entry_price,
|
||||
current_price: px,
|
||||
size_usd: notional,
|
||||
leverage: t.leverage,
|
||||
opened_at: iso(t.opened_at),
|
||||
hold_minutes: Math.floor((Date.now() - utcMs(t.opened_at)) / 60000),
|
||||
unrealized_pct: pct == null ? null : round(pct, 3),
|
||||
unrealized_usd: pct == null || !notional ? null : round((notional * pct) / 100),
|
||||
is_paper: t.hl_order_id === 'paper',
|
||||
trigger_post_id: t.trigger_post_id,
|
||||
realized_usd: t.realized_partial_pnl_usd ? round(t.realized_partial_pnl_usd) : null,
|
||||
derisk_steps: t.derisk_steps_done,
|
||||
addon_steps: t.addon_steps_done,
|
||||
grow_mode: t.grow_mode,
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
||||
app.get('/api/positions/today', async (req) => {
|
||||
const wallet = await read(req)
|
||||
const [closed, opened] = await Promise.all([
|
||||
c.db
|
||||
.select()
|
||||
.from(trades)
|
||||
.where(
|
||||
and(
|
||||
eq(trades.wallet_address, wallet),
|
||||
gte(trades.closed_at, new Date().toISOString().slice(0, 10)),
|
||||
isNotNull(trades.pnl_usd),
|
||||
isNull(trades.released_at),
|
||||
),
|
||||
),
|
||||
c.db
|
||||
.select()
|
||||
.from(trades)
|
||||
.where(
|
||||
and(
|
||||
eq(trades.wallet_address, wallet),
|
||||
isNull(trades.closed_at),
|
||||
isNull(trades.released_at),
|
||||
),
|
||||
),
|
||||
])
|
||||
return {
|
||||
wallet,
|
||||
realized_pnl_usd: round(closed.reduce((s, t) => s + (t.pnl_usd ?? 0), 0)),
|
||||
trades_closed: closed.length,
|
||||
wins: closed.filter((t) => t.pnl_usd! > 0).length,
|
||||
losses: closed.filter((t) => t.pnl_usd! < 0).length,
|
||||
open_count: opened.length,
|
||||
open_realized_usd: round(opened.reduce((s, t) => s + t.realized_partial_pnl_usd, 0)),
|
||||
}
|
||||
})
|
||||
app.get('/api/positions/hl/:wallet', async (req) => {
|
||||
const wallet = await read(req, true),
|
||||
positions = await engine.listHl(wallet)
|
||||
return { wallet, count: positions.length, positions }
|
||||
})
|
||||
app.post('/api/positions/adopt', async (req) => {
|
||||
const body = raw(req),
|
||||
asset = z.string().min(1).parse(body.asset).trim().toUpperCase(),
|
||||
mode = z.enum(['standard', 'aggressive']).default('standard').parse(body.mode),
|
||||
wallet = await c.auth.write('adopt_position', body, { asset, mode })
|
||||
return engine.adopt(wallet, asset, mode)
|
||||
})
|
||||
app.post('/api/positions/:id/release', async (req) => {
|
||||
const body = raw(req),
|
||||
trade_id = id(req)
|
||||
requireThat(body.trade_id === trade_id, 400, 'trade_id mismatch')
|
||||
const w = await c.auth.write('release_trade', body, { trade_id })
|
||||
return engine.release(w, trade_id)
|
||||
})
|
||||
app.post('/api/positions/:id/grow', async (req) => {
|
||||
const body = raw(req),
|
||||
trade_id = id(req),
|
||||
enabled = z.boolean().parse(body.enabled)
|
||||
requireThat(body.trade_id === trade_id, 400, 'trade_id mismatch')
|
||||
const w = await c.auth.write('set_trade_grow', body, { trade_id, enabled })
|
||||
return engine.grow(w, trade_id, enabled)
|
||||
})
|
||||
app.post('/api/positions/:id/close', async (req) => {
|
||||
const body = raw(req),
|
||||
trade_id = id(req),
|
||||
w = await c.auth.write('close_trade', body, { trade_id })
|
||||
const t = await engine.close(trade_id, 'manual', true, w)
|
||||
requireThat(t.closed_at, 502, 'Position could not be closed')
|
||||
return {
|
||||
status: 'ok',
|
||||
trade_id,
|
||||
exit_price: t.exit_price,
|
||||
pnl_usd: t.pnl_usd,
|
||||
reason: 'manual',
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { and, eq, notInArray, inArray, desc, asc, count, sql, max, type SQL } from 'drizzle-orm'
|
||||
import { posts, type createDatabase } from '@trumpsignal/database'
|
||||
import { isSupportedTradingSource } from '@trumpsignal/core/signal-categories'
|
||||
type Db = ReturnType<typeof createDatabase>['db']
|
||||
type Post = typeof posts.$inferSelect
|
||||
type Query = {
|
||||
limit?: number
|
||||
page?: number
|
||||
source?: string
|
||||
source_in?: string
|
||||
source_not_in?: string
|
||||
archive_only?: boolean
|
||||
sentiment?: string
|
||||
signal?: string
|
||||
ai_scored_only?: boolean
|
||||
}
|
||||
const scored = sql`(coalesce(${posts.ai_confidence}, 0) > 0 or ${posts.ai_reasoning} is not null)`
|
||||
export function postDto(p: Post) {
|
||||
const correct = (v: number | null) =>
|
||||
v == null
|
||||
? null
|
||||
: p.signal === 'buy'
|
||||
? v > 0
|
||||
: ['short', 'sell'].includes(p.signal ?? '')
|
||||
? v < 0
|
||||
: null
|
||||
return {
|
||||
id: p.id,
|
||||
text: p.text,
|
||||
source: p.source,
|
||||
published_at: iso(p.published_at),
|
||||
sentiment: p.sentiment,
|
||||
signal: p.signal,
|
||||
ai_confidence: p.ai_confidence,
|
||||
ai_reasoning: p.ai_reasoning,
|
||||
prefilter_reason: p.prefilter_reason,
|
||||
analysis_version: p.analysis_version,
|
||||
relevant: p.relevant,
|
||||
target_asset: p.target_asset,
|
||||
category: p.category,
|
||||
expected_move_pct: p.expected_move_pct,
|
||||
invalidation_price: p.invalidation_price,
|
||||
price_impact:
|
||||
p.price_impact_asset && p.price_at_post != null
|
||||
? {
|
||||
asset: p.price_impact_asset,
|
||||
price_at_post: p.price_at_post,
|
||||
m5: p.price_impact_m5,
|
||||
m15: p.price_impact_m15,
|
||||
m1h: p.price_impact_m1h,
|
||||
correct_m5: correct(p.price_impact_m5),
|
||||
correct_m15: correct(p.price_impact_m15),
|
||||
correct_m1h: correct(p.price_impact_m1h),
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
export function iso(value: string | null): string | null {
|
||||
return value == null
|
||||
? null
|
||||
: /(?:Z|[+-]\d\d:\d\d)$/.test(value)
|
||||
? new Date(value).toISOString()
|
||||
: new Date(value + 'Z').toISOString()
|
||||
}
|
||||
const querySchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', minimum: 1, maximum: 500, default: 20 },
|
||||
page: { type: 'integer', minimum: 1, default: 1 },
|
||||
source: { type: 'string' },
|
||||
source_in: { type: 'string' },
|
||||
source_not_in: { type: 'string' },
|
||||
archive_only: { type: 'boolean', default: false },
|
||||
sentiment: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },
|
||||
signal: { type: 'string', enum: ['buy', 'short', 'actionable'] },
|
||||
ai_scored_only: { type: 'boolean', default: false },
|
||||
},
|
||||
}
|
||||
const csv = (s?: string) =>
|
||||
(s ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
export async function registerPosts(app: FastifyInstance, db: Db) {
|
||||
app.get<{ Querystring: Query }>(
|
||||
'/api/posts',
|
||||
{
|
||||
schema: { querystring: querySchema },
|
||||
config: { rateLimit: { max: 60, timeWindow: '1 minute' } },
|
||||
},
|
||||
async (req, reply) => {
|
||||
const q = req.query,
|
||||
limit = q.limit ?? 20,
|
||||
page = q.page ?? 1
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(q.source ? eq(posts.source, q.source) : undefined)
|
||||
.orderBy(desc(posts.published_at))
|
||||
.limit(limit)
|
||||
.offset((page - 1) * limit)
|
||||
reply.header('cache-control', 'public, max-age=30, stale-while-revalidate=60')
|
||||
return rows.map(postDto)
|
||||
},
|
||||
)
|
||||
app.get<{ Querystring: Query }>(
|
||||
'/api/posts-paged',
|
||||
{
|
||||
schema: { querystring: querySchema },
|
||||
config: { rateLimit: { max: 60, timeWindow: '1 minute' } },
|
||||
},
|
||||
async (req, reply) => {
|
||||
const q = req.query,
|
||||
limit = q.limit ?? 20,
|
||||
page = q.page ?? 1
|
||||
const base: SQL[] = []
|
||||
const chips: SQL[] = []
|
||||
if (q.source) {
|
||||
base.push(eq(posts.source, q.source))
|
||||
chips.push(eq(posts.source, q.source))
|
||||
} else if (csv(q.source_in).length) base.push(inArray(posts.source, csv(q.source_in)))
|
||||
const excluded = [
|
||||
...csv(q.source_not_in),
|
||||
...(q.archive_only
|
||||
? ['truth', 'btc_bottom_reversal', 'funding_reversal', 'kol_divergence']
|
||||
: []),
|
||||
]
|
||||
if (excluded.length) {
|
||||
const e = notInArray(posts.source, excluded)
|
||||
base.push(e)
|
||||
chips.push(e)
|
||||
}
|
||||
if (q.sentiment) {
|
||||
const e = eq(posts.sentiment, q.sentiment)
|
||||
base.push(e)
|
||||
chips.push(e)
|
||||
}
|
||||
const list = [...base]
|
||||
if (q.ai_scored_only) {
|
||||
list.push(scored)
|
||||
chips.push(scored)
|
||||
}
|
||||
if (q.signal)
|
||||
list.push(
|
||||
q.signal === 'actionable'
|
||||
? inArray(posts.signal, ['buy', 'short'])
|
||||
: eq(posts.signal, q.signal),
|
||||
)
|
||||
const [items, totalRows, countsRows, sources] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(and(...list))
|
||||
.orderBy(desc(posts.published_at))
|
||||
.limit(limit)
|
||||
.offset((page - 1) * limit),
|
||||
db
|
||||
.select({ n: count() })
|
||||
.from(posts)
|
||||
.where(and(...list)),
|
||||
db
|
||||
.select({
|
||||
all: count(),
|
||||
actionable: sql<number>`sum(case when ${posts.signal} in ('buy','short') then 1 else 0 end)`,
|
||||
buy: sql<number>`sum(case when ${posts.signal} = 'buy' then 1 else 0 end)`,
|
||||
short: sql<number>`sum(case when ${posts.signal} = 'short' then 1 else 0 end)`,
|
||||
off_topic: sql<number>`sum(case when ${scored} then 0 else 1 end)`,
|
||||
})
|
||||
.from(posts)
|
||||
.where(and(...base)),
|
||||
db
|
||||
.select({ source: posts.source, count: count(), latest: max(posts.published_at) })
|
||||
.from(posts)
|
||||
.where(and(...chips))
|
||||
.groupBy(posts.source)
|
||||
.orderBy(desc(count()), asc(posts.source)),
|
||||
])
|
||||
const c = countsRows[0]
|
||||
const off = Number(c.off_topic ?? 0)
|
||||
reply.header('cache-control', 'public, max-age=30, stale-while-revalidate=60')
|
||||
return {
|
||||
items: items.map(postDto),
|
||||
total: totalRows[0].n,
|
||||
page,
|
||||
limit,
|
||||
counts: {
|
||||
all: Math.max(0, Number(c.all) - (q.ai_scored_only ? off : 0)),
|
||||
actionable: Number(c.actionable ?? 0),
|
||||
buy: Number(c.buy ?? 0),
|
||||
short: Number(c.short ?? 0),
|
||||
off_topic: off,
|
||||
},
|
||||
source_counts: sources.map((s) => ({ ...s, latest: iso(s.latest) })),
|
||||
}
|
||||
},
|
||||
)
|
||||
app.get<{ Params: { id: number } }>(
|
||||
'/api/posts/:id',
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: 'object',
|
||||
properties: { id: { type: 'integer', minimum: 1 } },
|
||||
required: ['id'],
|
||||
},
|
||||
},
|
||||
},
|
||||
async (req, reply) => {
|
||||
const [p] = await db.select().from(posts).where(eq(posts.id, req.params.id)).limit(1)
|
||||
if (!p) return reply.code(404).send({ detail: 'Post not found' })
|
||||
return postDto(p)
|
||||
},
|
||||
)
|
||||
app.get('/api/signals/accuracy', async () => {
|
||||
const rows = (
|
||||
await db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(inArray(posts.signal, ['buy', 'short']))
|
||||
).filter((p) => isSupportedTradingSource(p.source))
|
||||
const bucket = () => ({ checked: 0, correct: 0 })
|
||||
const group = () => ({ m5: bucket(), m15: bucket(), m1h: bucket() })
|
||||
const overall = group()
|
||||
const by: Record<string, ReturnType<typeof group> & { count: number }> = {}
|
||||
for (const p of rows) {
|
||||
const s = p.signal!
|
||||
const g = by[s] ?? (by[s] = { ...group(), count: 0 })
|
||||
g.count++
|
||||
for (const win of ['m5', 'm15', 'm1h'] as const) {
|
||||
const v = p[`price_impact_${win}`]
|
||||
if (v == null) continue
|
||||
const ok = s === 'buy' ? v > 0 : v < 0
|
||||
for (const b of [overall[win], g[win]]) {
|
||||
b.checked++
|
||||
b.correct += Number(ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
const finish = (b: ReturnType<typeof bucket>) => ({
|
||||
...b,
|
||||
accuracy_pct: b.checked ? Math.round((b.correct / b.checked) * 1000) / 10 : null,
|
||||
})
|
||||
return {
|
||||
overall: Object.fromEntries(Object.entries(overall).map(([k, b]) => [k, finish(b)])),
|
||||
by_signal: Object.fromEntries(
|
||||
Object.entries(by).map(([s, g]) => [
|
||||
s,
|
||||
{ count: g.count, m5: finish(g.m5), m15: finish(g.m15), m1h: finish(g.m1h) },
|
||||
]),
|
||||
),
|
||||
total_directional_signals: rows.length,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { timingSafeEqual } from 'node:crypto'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
import { eq, count, max, desc } from 'drizzle-orm'
|
||||
import { posts } from '@trumpsignal/database'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { Services } from '@trumpsignal/backend/services'
|
||||
import { requireThat, iso } from '@trumpsignal/backend/http'
|
||||
import { subscription } from '@trumpsignal/backend/accounts'
|
||||
import { marketBars } from '@trumpsignal/backend/market-data'
|
||||
export function requireIngestKey(c: Context, key: unknown) {
|
||||
const expected = c.config.ingest_api_key
|
||||
requireThat(expected, 503, 'INGEST_API_KEY not configured')
|
||||
requireThat(
|
||||
typeof key === 'string' &&
|
||||
Buffer.byteLength(key) === Buffer.byteLength(expected) &&
|
||||
timingSafeEqual(Buffer.from(key), Buffer.from(expected)),
|
||||
401,
|
||||
'Invalid X-Ingest-Key',
|
||||
)
|
||||
}
|
||||
export async function registerSignals(app: FastifyInstance, c: Context, s: Services) {
|
||||
app.post('/api/signals/ingest', async (req) => {
|
||||
requireIngestKey(c, req.headers['x-ingest-key'])
|
||||
return s.pipeline.signal(req.body)
|
||||
})
|
||||
app.get('/api/signals/sources', async () => ({
|
||||
sources: (
|
||||
await c.db
|
||||
.select({ source: posts.source, count: count(), latest: max(posts.published_at) })
|
||||
.from(posts)
|
||||
.groupBy(posts.source)
|
||||
.orderBy(desc(count()))
|
||||
).map((r) => ({ ...r, latest: iso(r.latest) })),
|
||||
}))
|
||||
app.get('/api/scanners', async () => {
|
||||
const scanners = await s.scannerState.all()
|
||||
return { count: scanners.length, enabled: scanners.filter((s) => s.enabled).length, scanners }
|
||||
})
|
||||
app.post<{ Params: { name: string } }>('/api/scanners/:name/toggle', async (req) => {
|
||||
const raw = z.record(z.unknown()).parse(req.body),
|
||||
name = req.params.name,
|
||||
enabled = z.boolean().parse(raw.enabled)
|
||||
requireThat(raw.name === name, 400, 'Scanner name mismatch')
|
||||
const wallet = await c.auth.write('toggle_scanner', raw, { enabled, name })
|
||||
await subscription(c, wallet)
|
||||
const result = await s.scannerState.enabled(name, enabled)
|
||||
requireThat(result, 404, 'Unknown scanner')
|
||||
return { status: 'ok', name, enabled }
|
||||
})
|
||||
for (const action of ['disable', 'enable'] as const)
|
||||
app.post('/api/scanners/all/' + action, async (req) => {
|
||||
const raw = z.record(z.unknown()).parse(req.body),
|
||||
wallet = await c.auth.write(
|
||||
action === 'enable' ? 'scanner_revive_all' : 'scanner_kill_all',
|
||||
raw,
|
||||
null,
|
||||
)
|
||||
await subscription(c, wallet)
|
||||
const list = await s.scannerState.all()
|
||||
for (const scanner of list) await s.scannerState.enabled(scanner.name, action === 'enable')
|
||||
return { status: action === 'enable' ? 'revived' : 'killed', count: list.length }
|
||||
})
|
||||
app.get('/api/funding/snapshot', async () => s.scanners.fundingSnapshot())
|
||||
app.get('/api/signal/status', async () => ({
|
||||
enabled: await s.state.get('breakout-enabled', false),
|
||||
symbols: ['ETHUSDT', 'LINKUSDT'],
|
||||
recent_signal_count: (await s.state.get<unknown[]>('breakout-history', [])).length,
|
||||
}))
|
||||
app.get('/api/signal/history', async (req) => {
|
||||
const q = z
|
||||
.object({ limit: z.coerce.number().int().min(1).max(200).default(20) })
|
||||
.parse(req.query)
|
||||
return (await s.state.get<unknown[]>('breakout-history', []))
|
||||
.slice()
|
||||
.reverse()
|
||||
.slice(0, q.limit)
|
||||
})
|
||||
app.post('/api/signal/toggle', async (req) => {
|
||||
requireIngestKey(c, req.headers['x-ingest-key'])
|
||||
const q = z.object({ enabled: z.enum(['true', 'false']) }).parse(req.query)
|
||||
await s.state.set('breakout-enabled', q.enabled === 'true')
|
||||
return { enabled: q.enabled === 'true' }
|
||||
})
|
||||
app.get<{ Params: { asset: string } }>(
|
||||
'/api/prices/:asset',
|
||||
{ config: { rateLimit: { max: 30, timeWindow: '1 minute' } } },
|
||||
async (req, reply) => {
|
||||
const asset = z.enum(['BTC', 'ETH']).parse(req.params.asset.toUpperCase()),
|
||||
q = z
|
||||
.object({
|
||||
tf: z.enum(['1m', '5m', '15m', '1H', '4H', '1D', '1W']).default('4H'),
|
||||
limit: z.coerce.number().int().min(1).max(1000).default(200),
|
||||
})
|
||||
.parse(req.query)
|
||||
reply.header(
|
||||
'cache-control',
|
||||
q.tf === '1m'
|
||||
? 'public, max-age=5, stale-while-revalidate=10'
|
||||
: 'public, max-age=60, stale-while-revalidate=120',
|
||||
)
|
||||
if (q.tf === '1m') return c.prices.candles(asset, '1m', q.limit)
|
||||
const bars = await marketBars(c.config, asset, q.tf.toLowerCase(), q.limit)
|
||||
return bars.map(({ time_ms, ...bar }) => bar)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
import type { Context } from '@trumpsignal/backend/context'
|
||||
import type { Telegram } from '@trumpsignal/backend/telegram'
|
||||
import { requireThat } from '@trumpsignal/backend/http'
|
||||
const preferences = z.object({
|
||||
alerts_enabled: z.boolean().nullable().optional(),
|
||||
alert_trump: z.boolean().nullable().optional(),
|
||||
alert_btc_bottom: z.boolean().nullable().optional(),
|
||||
alert_funding: z.boolean().nullable().optional(),
|
||||
alert_kol_divergence: z.boolean().nullable().optional(),
|
||||
min_confidence: z.number().int().min(0).max(100).nullable().optional(),
|
||||
mute_from_hour: z.number().int().min(0).max(23).nullable().optional(),
|
||||
mute_until_hour: z.number().int().min(0).max(23).nullable().optional(),
|
||||
})
|
||||
export async function registerTelegram(app: FastifyInstance, c: Context, tg: Telegram) {
|
||||
app.get<{ Params: { wallet: string } }>('/api/telegram/:wallet/status', async (req) => {
|
||||
const wallet = req.params.wallet.toLowerCase().trim()
|
||||
let auth = false
|
||||
try {
|
||||
await c.auth.read(
|
||||
['view_telegram_status', 'view_user'],
|
||||
wallet,
|
||||
req.headers,
|
||||
req.query as Record<string, unknown>,
|
||||
)
|
||||
auth = true
|
||||
} catch {}
|
||||
return tg.status(wallet, auth)
|
||||
})
|
||||
for (const action of ['init', 'unbind', 'test'] as const)
|
||||
app.post<{ Params: { wallet: string } }>('/api/telegram/:wallet/' + action, async (req) => {
|
||||
tg.requireConfigured()
|
||||
const raw = z.record(z.unknown()).parse(req.body),
|
||||
wallet = await c.auth.write('telegram_' + action, raw, null, req.params.wallet)
|
||||
if (action === 'init') return tg.issue(wallet)
|
||||
if (action === 'unbind') return tg.unbind(wallet)
|
||||
requireThat(await tg.test(wallet), 400, 'Test failed; bind via /start first')
|
||||
return { sent: true }
|
||||
})
|
||||
app.post<{ Params: { wallet: string } }>('/api/telegram/:wallet/preferences', async (req) => {
|
||||
tg.requireConfigured()
|
||||
const raw = z.record(z.unknown()).parse(req.body),
|
||||
parsed = preferences.parse(raw),
|
||||
values = Object.fromEntries(Object.entries(parsed).filter(([, v]) => v != null))
|
||||
const wallet = await c.auth.write('telegram_prefs', raw, values, req.params.wallet)
|
||||
return tg.preferences(wallet, values)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user