refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@trumpsignal/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./*": "./src/*.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"viem": "^2.17.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
export interface ExitParams {
|
||||
stop_loss_pct: number
|
||||
trailing_stop_pct: number | null
|
||||
trailing_activate_at_pct: number | null
|
||||
take_profit_pct: number | null
|
||||
max_hold_hours: number
|
||||
}
|
||||
export interface SimBar {
|
||||
time_ms: number
|
||||
open: number
|
||||
high: number
|
||||
low: number
|
||||
close: number
|
||||
}
|
||||
export function simulateExit(candles: SimBar[], side: string, p: ExitParams) {
|
||||
let peak = 0,
|
||||
trough = 0,
|
||||
armed = false
|
||||
const entry = candles[0]?.open ?? 0,
|
||||
long = side === 'long',
|
||||
pct = (price: number) => ((price - entry) / entry) * (long ? 1 : -1) * 100
|
||||
const result = (reason: string, exit_price: number, bars: number, pnl_pct: number) => ({
|
||||
reason,
|
||||
exit_price,
|
||||
bars,
|
||||
peak_pct: peak,
|
||||
trough_pct: trough,
|
||||
pnl_pct,
|
||||
})
|
||||
if (!candles.length || entry <= 0)
|
||||
return result(!candles.length ? 'no_data' : 'bad_entry', 0, 0, 0)
|
||||
for (let i = 0; i < candles.length; i++) {
|
||||
const b = candles[i],
|
||||
good = pct(long ? b.high : b.low),
|
||||
bad = pct(long ? b.low : b.high)
|
||||
peak = Math.max(peak, good)
|
||||
trough = Math.min(trough, bad)
|
||||
if (bad <= -p.stop_loss_pct)
|
||||
return result(
|
||||
'stop_loss',
|
||||
entry * (1 + ((long ? -1 : 1) * p.stop_loss_pct) / 100),
|
||||
i + 1,
|
||||
-p.stop_loss_pct,
|
||||
)
|
||||
if (p.trailing_stop_pct != null && p.trailing_activate_at_pct != null) {
|
||||
if (peak >= p.trailing_activate_at_pct) armed = true
|
||||
if (armed && peak - bad >= p.trailing_stop_pct) {
|
||||
const gain = peak - p.trailing_stop_pct
|
||||
return result('trailing_stop', entry * (1 + ((long ? 1 : -1) * gain) / 100), i + 1, gain)
|
||||
}
|
||||
}
|
||||
if (p.take_profit_pct != null && good >= p.take_profit_pct)
|
||||
return result(
|
||||
'take_profit',
|
||||
entry * (1 + ((long ? 1 : -1) * p.take_profit_pct) / 100),
|
||||
i + 1,
|
||||
p.take_profit_pct,
|
||||
)
|
||||
}
|
||||
const exit = candles.at(-1)!.close
|
||||
return result('max_hold', exit, candles.length, pct(exit))
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
const average = (a: readonly number[]) => a.reduce((s, v) => s + v, 0) / a.length
|
||||
export function sma(a: readonly number[], n: number): number | null {
|
||||
return a.length < n ? null : average(a.slice(-n))
|
||||
}
|
||||
export function ema(a: readonly number[], n: number): number | null {
|
||||
if (a.length < n) return null
|
||||
let out = average(a.slice(0, n))
|
||||
const k = 2 / (n + 1)
|
||||
for (const v of a.slice(n)) out = v * k + out * (1 - k)
|
||||
return out
|
||||
}
|
||||
export function ahr999(daily: readonly number[], now = Date.now()): number | null {
|
||||
if (daily.length < 200 || daily.at(-1)! <= 0) return null
|
||||
const gm = Math.exp(daily.slice(-200).reduce((s, c) => s + (c > 0 ? Math.log(c) : 0), 0) / 200),
|
||||
age = Math.max(1, Math.floor((now - Date.UTC(2009, 0, 3)) / 86400000)),
|
||||
growth = 10 ** (5.84 * Math.log10(age) - 17.01)
|
||||
return daily.at(-1)! ** 2 / gm / growth
|
||||
}
|
||||
export function bottomConfluence(
|
||||
daily: readonly number[],
|
||||
weekly: readonly number[],
|
||||
now = Date.now(),
|
||||
) {
|
||||
const ah = ahr999(daily, now),
|
||||
wma = sma(weekly, 200),
|
||||
em = ema(daily, 150),
|
||||
sm = sma(daily, 471),
|
||||
scaled = sm == null ? null : sm * 0.745,
|
||||
price = daily.at(-1) ?? null
|
||||
const a = ah != null && ah < 0.45,
|
||||
b = price != null && wma != null && price <= wma * 1.05,
|
||||
c = em != null && scaled != null && em <= scaled,
|
||||
votes = Number(a) + Number(b) + Number(c)
|
||||
return {
|
||||
fired: votes >= 2,
|
||||
votes,
|
||||
ahr999: ah,
|
||||
a_value: a,
|
||||
b_200wma: b,
|
||||
c_pi_cycle: c,
|
||||
detail: {
|
||||
ahr999: ah,
|
||||
ahr999_threshold: 0.45,
|
||||
price,
|
||||
wma200: wma,
|
||||
wma200_band: wma == null ? null : wma * 1.05,
|
||||
pi_ema150: em,
|
||||
pi_sma471_scaled: scaled,
|
||||
votes,
|
||||
signals: { ahr999_value: a, below_200wma: b, pi_cycle_bottom: c },
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
export interface BreakoutCandle {
|
||||
close: number
|
||||
volume: number
|
||||
tbr: number
|
||||
}
|
||||
export function breakoutSignal(raw: BreakoutCandle[]) {
|
||||
const bars = raw.slice(0, -1)
|
||||
if (bars.length < 60) return null
|
||||
const mean = (a: number[]) => a.reduce((s, v) => s + v, 0) / a.length,
|
||||
closes = bars.map((b) => b.close),
|
||||
std = (a: number[]) => {
|
||||
const m = mean(a)
|
||||
return Math.sqrt(mean(a.map((n) => (n - m) ** 2)))
|
||||
},
|
||||
window = closes.slice(-20),
|
||||
mid = mean(window),
|
||||
sd = std(window),
|
||||
upper = mid + 2 * sd,
|
||||
width = mid > 0 ? (4 * sd) / mid : 0,
|
||||
widths = []
|
||||
for (let i = bars.length - 60; i < bars.length; i++) {
|
||||
const w = closes.slice(Math.max(0, i - 19), i + 1)
|
||||
if (w.length < 20) continue
|
||||
const m = mean(w)
|
||||
widths.push(m > 0 ? (4 * std(w)) / m : 0)
|
||||
}
|
||||
if (!widths.length) return null
|
||||
const rank = (widths.filter((w) => w < width).length / widths.length) * 100,
|
||||
vol = mean(bars.slice(-21, -1).map((b) => b.volume)),
|
||||
last = bars.at(-1)!
|
||||
return rank < 20 && vol > 0 && last.volume > 2.5 * vol && last.tbr > 0.6 && last.close > upper
|
||||
? {
|
||||
bb_width_pct: Math.round(rank * 10) / 10,
|
||||
vol_mult: Math.round((last.volume / vol) * 100) / 100,
|
||||
tbr: Math.round(last.tbr * 1000) / 1000,
|
||||
close: last.close,
|
||||
bb_upper: Math.round(upper * 10000) / 10000,
|
||||
}
|
||||
: null
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/** Fernet wire compatibility with the existing Python enc:v1 / enc:v2 rows. */
|
||||
import {
|
||||
createHash,
|
||||
createHmac,
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
pbkdf2,
|
||||
randomBytes,
|
||||
timingSafeEqual,
|
||||
} from 'node:crypto'
|
||||
import { promisify } from 'node:util'
|
||||
const derive = promisify(pbkdf2)
|
||||
const cache = new Map<string, Buffer>()
|
||||
const base64url = (bytes: Buffer) =>
|
||||
bytes.toString('base64').replace(/\+/g, '-').replace(/\//g, '_')
|
||||
function checkKek(kek: string) {
|
||||
if (kek.length < 32) throw new Error('ENCRYPTION_KEY must contain at least 32 characters')
|
||||
}
|
||||
async function keyFor(kek: string, salt?: Buffer) {
|
||||
checkKek(kek)
|
||||
if (!salt) return createHash('sha256').update(kek).digest()
|
||||
const id = createHash('sha256').update(kek).update(salt).digest('hex')
|
||||
const cached = cache.get(id)
|
||||
if (cached) return cached
|
||||
const key = await derive(kek, salt, 600_000, 32, 'sha256')
|
||||
if (cache.size >= 4096) cache.clear()
|
||||
cache.set(id, key)
|
||||
return key
|
||||
}
|
||||
function encodeToken(plaintext: string, key: Buffer): string {
|
||||
const iv = randomBytes(16)
|
||||
const header = Buffer.alloc(9)
|
||||
header[0] = 0x80
|
||||
header.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)), 1)
|
||||
const cipher = createCipheriv('aes-128-cbc', key.subarray(16), iv)
|
||||
const data = Buffer.concat([header, iv, cipher.update(plaintext, 'utf8'), cipher.final()])
|
||||
return base64url(
|
||||
Buffer.concat([data, createHmac('sha256', key.subarray(0, 16)).update(data).digest()]),
|
||||
)
|
||||
}
|
||||
export function decodeToken(token: string, key: Buffer): string {
|
||||
const raw = Buffer.from(token, 'base64url')
|
||||
if (raw.length < 73 || raw[0] !== 0x80 || (raw.length - 57) % 16 !== 0)
|
||||
throw new Error('Malformed Fernet token')
|
||||
const data = raw.subarray(0, -32)
|
||||
const mac = createHmac('sha256', key.subarray(0, 16)).update(data).digest()
|
||||
if (!timingSafeEqual(raw.subarray(-32), mac)) throw new Error('HL key decryption failed')
|
||||
const decipher = createDecipheriv('aes-128-cbc', key.subarray(16), raw.subarray(9, 25))
|
||||
return Buffer.concat([decipher.update(raw.subarray(25, -32)), decipher.final()]).toString('utf8')
|
||||
}
|
||||
export async function encryptApiKey(plaintext: string, kek: string): Promise<string> {
|
||||
const salt = randomBytes(16)
|
||||
return `enc:v2:${base64url(salt)}:${encodeToken(plaintext, await keyFor(kek, salt))}`
|
||||
}
|
||||
export async function decryptApiKey(
|
||||
stored: string,
|
||||
kek: string,
|
||||
environment: string,
|
||||
): Promise<string> {
|
||||
if (!stored) throw new Error('Empty API key')
|
||||
if (stored.startsWith('enc:v2:')) {
|
||||
const [, , salt, token, ...rest] = stored.split(':')
|
||||
if (!salt || !token || rest.length) throw new Error('Malformed enc:v2 blob')
|
||||
const bytes = Buffer.from(salt, 'base64url')
|
||||
if (bytes.length !== 16) throw new Error('Malformed salt')
|
||||
return decodeToken(token, await keyFor(kek, bytes))
|
||||
}
|
||||
if (stored.startsWith('enc:v1:')) return decodeToken(stored.slice(7), await keyFor(kek))
|
||||
if (environment === 'production') throw new Error('Legacy plaintext key requires migration')
|
||||
return stored
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
const ACTION_MARKERS = [
|
||||
'statement of',
|
||||
'statement by',
|
||||
'executive order',
|
||||
'announcing',
|
||||
'today i signed',
|
||||
'i have signed',
|
||||
'i hereby',
|
||||
'effective immediately',
|
||||
'effective today',
|
||||
'have agreed',
|
||||
'has agreed',
|
||||
'was signed',
|
||||
'have signed',
|
||||
'have implemented',
|
||||
'have imposed',
|
||||
'have authorized',
|
||||
'we have had',
|
||||
'have successfully',
|
||||
'just imposed',
|
||||
'just signed',
|
||||
'ordered the suspension of',
|
||||
'ordered the cancellation of',
|
||||
'ordered the deployment of',
|
||||
'just announced',
|
||||
'strategic reserve',
|
||||
'tariff',
|
||||
'sanctions on',
|
||||
'ceasefire signed',
|
||||
'rate cut',
|
||||
'rate hike',
|
||||
'sec approval',
|
||||
'sec has approved',
|
||||
'supreme court ruled',
|
||||
'doj filed',
|
||||
]
|
||||
const FUTURE_TENSE_BLOCKERS = [
|
||||
'i will',
|
||||
'we will',
|
||||
"i'm thinking",
|
||||
'considering',
|
||||
'looking at',
|
||||
'may consider',
|
||||
'could be',
|
||||
'had a conversation',
|
||||
'had conversations',
|
||||
'had a great call',
|
||||
'had a great meeting',
|
||||
'spoke with',
|
||||
'talked with',
|
||||
'met with',
|
||||
'i just had excellent',
|
||||
'most points were agreed',
|
||||
"we're close to",
|
||||
'still working on',
|
||||
]
|
||||
const DEDUP_WINDOW_HOURS = 48
|
||||
const DEDUP_KEYWORD_THRESHOLD = 3
|
||||
const TOPIC_KEYWORDS = [
|
||||
'iran',
|
||||
'iranian',
|
||||
'hormuz',
|
||||
'strait of hormuz',
|
||||
'strait of iran',
|
||||
'the strait',
|
||||
'israel',
|
||||
'gaza',
|
||||
'lebanon',
|
||||
'hezbollah',
|
||||
'syria',
|
||||
'yemen',
|
||||
'houthi',
|
||||
'ukraine',
|
||||
'russia',
|
||||
'putin',
|
||||
'zelensky',
|
||||
'kyiv',
|
||||
'china',
|
||||
'chinese',
|
||||
'xi jinping',
|
||||
'taiwan',
|
||||
'north korea',
|
||||
'kim jong',
|
||||
'tariff',
|
||||
'tariffs',
|
||||
'fed',
|
||||
'fomc',
|
||||
'powell',
|
||||
'interest rate',
|
||||
'rate cut',
|
||||
'rate hike',
|
||||
'cpi',
|
||||
'inflation',
|
||||
'bitcoin',
|
||||
'btc',
|
||||
'ethereum',
|
||||
'crypto',
|
||||
'sec',
|
||||
'strategic reserve',
|
||||
'pakistan',
|
||||
'india',
|
||||
]
|
||||
const _STOP_WORDS = [
|
||||
'the',
|
||||
'a',
|
||||
'an',
|
||||
'of',
|
||||
'to',
|
||||
'and',
|
||||
'or',
|
||||
'in',
|
||||
'on',
|
||||
'at',
|
||||
'is',
|
||||
'are',
|
||||
'was',
|
||||
'were',
|
||||
'be',
|
||||
'been',
|
||||
'have',
|
||||
'has',
|
||||
'had',
|
||||
'will',
|
||||
'i',
|
||||
'we',
|
||||
'you',
|
||||
'they',
|
||||
'this',
|
||||
'that',
|
||||
'with',
|
||||
'for',
|
||||
'by',
|
||||
'from',
|
||||
'my',
|
||||
'our',
|
||||
'your',
|
||||
'their',
|
||||
'it',
|
||||
'its',
|
||||
'as',
|
||||
'but',
|
||||
'not',
|
||||
'just',
|
||||
'very',
|
||||
'more',
|
||||
'most',
|
||||
'than',
|
||||
'also',
|
||||
'would',
|
||||
'could',
|
||||
'should',
|
||||
'do',
|
||||
'does',
|
||||
'did',
|
||||
'new',
|
||||
'now',
|
||||
'get',
|
||||
'got',
|
||||
'make',
|
||||
'made',
|
||||
'go',
|
||||
'going',
|
||||
'go',
|
||||
'want',
|
||||
'want',
|
||||
'know',
|
||||
'like',
|
||||
'really',
|
||||
'us',
|
||||
'u',
|
||||
'said',
|
||||
'say',
|
||||
'says',
|
||||
]
|
||||
const TOPIC_HEAD_CHARS = 200
|
||||
const DEDUP_TOPIC_MIN = 2
|
||||
function topics(text: string): Set<string> {
|
||||
const head = text.slice(0, TOPIC_HEAD_CHARS).toLowerCase()
|
||||
const raw = TOPIC_KEYWORDS.filter((k) => head.includes(k))
|
||||
return new Set(raw.filter((a) => !raw.some((b) => a !== b && b.includes(a))))
|
||||
}
|
||||
function tokens(text: string): Set<string> {
|
||||
return new Set(
|
||||
(text.toLowerCase().match(/[a-z]{4,}/g) ?? []).filter((w) => !_STOP_WORDS.includes(w)),
|
||||
)
|
||||
}
|
||||
function overlap(a: Set<string>, b: Set<string>): number {
|
||||
return [...a].filter((v) => b.has(v)).length
|
||||
}
|
||||
export function entryFilter(
|
||||
text: string,
|
||||
recentTexts: readonly string[],
|
||||
): { passed: boolean; reason: string } {
|
||||
const lower = text.toLowerCase()
|
||||
const marker = ACTION_MARKERS.find((m) => lower.includes(m))
|
||||
if (!marker) return { passed: false, reason: 'no_action_marker' }
|
||||
const blocker = FUTURE_TENSE_BLOCKERS.find((m) => lower.slice(0, 200).includes(m))
|
||||
if (blocker) return { passed: false, reason: 'future_tense: ' + blocker }
|
||||
const ts = topics(text)
|
||||
const words = tokens(text)
|
||||
for (const prior of recentTexts) {
|
||||
if (overlap(ts, topics(prior)) >= DEDUP_TOPIC_MIN)
|
||||
return { passed: false, reason: 'duplicate_topic' }
|
||||
const shared = overlap(words, tokens(prior))
|
||||
if (
|
||||
words.size >= DEDUP_KEYWORD_THRESHOLD &&
|
||||
shared >= DEDUP_KEYWORD_THRESHOLD &&
|
||||
shared / words.size >= 0.5
|
||||
)
|
||||
return { passed: false, reason: 'duplicate_tokens' }
|
||||
}
|
||||
return { passed: true, reason: 'ok: ' + marker }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export interface Funding {
|
||||
time_ms: number
|
||||
rate: number
|
||||
}
|
||||
const mean = (a: number[]) => a.reduce((s, v) => s + v, 0) / a.length
|
||||
const round = (n: number, d = 2) => Math.round(n * 10 ** d) / 10 ** d
|
||||
export function cadenceHours(funding: Funding[]): number {
|
||||
if (funding.length < 2) return 8
|
||||
const sample = funding.slice(-11)
|
||||
return mean(sample.slice(1).map((v, i) => (v.time_ms - sample[i].time_ms) / 3600000))
|
||||
}
|
||||
export function fundingReversal(
|
||||
funding: Funding[],
|
||||
daily: { close: number }[],
|
||||
): { fired: boolean; debug: Record<string, unknown> } {
|
||||
const no = (reason: string, extra: Record<string, unknown> = {}) => ({
|
||||
fired: false,
|
||||
debug: { reason, ...extra },
|
||||
})
|
||||
if (funding.length < 2) return no('insufficient_funding_history', { cycles: funding.length })
|
||||
const cadence = cadenceHours(funding),
|
||||
days = (funding.at(-1)!.time_ms - funding[0].time_ms) / 86400000
|
||||
if (days < 14)
|
||||
return no('insufficient_coverage_days', { actual_days: round(days, 1), min_required: 14 })
|
||||
const rates = funding.map((f) => f.rate),
|
||||
sum = rates.reduce((s, v) => s + v, 0),
|
||||
avg = mean(rates),
|
||||
threshold = (0.03 * days) / 30
|
||||
const direction = sum > threshold ? 'short' : sum < -threshold ? 'buy' : null
|
||||
if (!direction)
|
||||
return no('no_extreme', {
|
||||
cumulative_funding_pct: round(sum * 100, 3),
|
||||
scaled_threshold_pct: round(threshold * 100, 3),
|
||||
coverage_days: round(days, 1),
|
||||
})
|
||||
if (!avg) return no('degenerate_avg')
|
||||
const recent = mean(
|
||||
rates.slice(-Math.min(rates.length, Math.max(3, Math.floor(24 / Math.max(cadence, 0.01))))),
|
||||
),
|
||||
ratio = Math.abs(recent) / Math.abs(avg)
|
||||
if (ratio > 0.5)
|
||||
return no('funding_still_extreme', { revert_ratio: round(ratio), needed_below: 0.5, direction })
|
||||
if (daily.length < 8) return no('insufficient_price_history', { have: daily.length, need: 8 })
|
||||
const first = daily.at(-8)!.close,
|
||||
last = daily.at(-1)!.close
|
||||
if (!first) return no('bad_first_close')
|
||||
const change = ((last - first) / first) * 100
|
||||
if (direction === 'buy' && change < 3)
|
||||
return no('price_not_yet_recovering', { pct_7d: round(change), direction })
|
||||
if (direction === 'short' && change > -3)
|
||||
return no('price_not_yet_falling', { pct_7d: round(change), direction })
|
||||
return {
|
||||
fired: true,
|
||||
debug: {
|
||||
direction,
|
||||
cum_funding_30d_pct: round(sum * 100, 3),
|
||||
recent_avg_cycle_pct: round(recent * 100, 4),
|
||||
revert_ratio: round(ratio),
|
||||
price_7d_pct: round(change),
|
||||
trigger_close: round(last, 4),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
type Values = Partial<
|
||||
Record<
|
||||
| 'ahr999'
|
||||
| 'altcoin_season_index'
|
||||
| 'fear_greed'
|
||||
| 'btc_dominance_pct'
|
||||
| 'eth_btc_ratio'
|
||||
| 'stablecoin_supply_usd'
|
||||
| 'etf_flow_net_usd_1d'
|
||||
| 'btc_open_interest_usd',
|
||||
number | null
|
||||
>
|
||||
>
|
||||
export function computeComposite(v: Values): readonly [number | null, string | null] {
|
||||
const present = (n: number | null | undefined, fn: (n: number) => number): number | null =>
|
||||
n == null ? null : fn(n)
|
||||
const pairs: [number, number | null][] = [
|
||||
[0.2, present(v.ahr999, (n) => (n < 0.45 ? 1 : n > 1.2 ? -1 : 1 - (2 * (n - 0.45)) / 0.75))],
|
||||
[0.1, present(v.altcoin_season_index, (n) => (n >= 75 ? 0.7 : n <= 25 ? 0.3 : (n - 50) / 50))],
|
||||
[0.2, present(v.fear_greed, (n) => (50 - n) / 50)],
|
||||
[0.05, present(v.btc_dominance_pct, (n) => (n >= 60 || n <= 40 ? -0.3 : 0))],
|
||||
[
|
||||
0.15,
|
||||
present(v.eth_btc_ratio, (n) =>
|
||||
n >= 0.04 ? 0.7 : n <= 0.025 ? -0.7 : ((n - 0.0325) / 0.0075) * 0.7,
|
||||
),
|
||||
],
|
||||
[
|
||||
0.2,
|
||||
present(
|
||||
v.etf_flow_net_usd_1d,
|
||||
(n) =>
|
||||
Math.sign(n) *
|
||||
(Math.abs(n) >= 500e6 ? 1 : Math.abs(n) >= 200e6 ? 0.7 : Math.abs(n) >= 50e6 ? 0.4 : 0.1),
|
||||
),
|
||||
],
|
||||
]
|
||||
// Supply and OI have no direction/trend signal in the legacy scorer and are excluded.
|
||||
let weight = 0,
|
||||
sum = 0
|
||||
for (const [w, s] of pairs)
|
||||
if (s != null) {
|
||||
weight += w
|
||||
sum += w * s
|
||||
}
|
||||
if (!weight) return [null, null]
|
||||
const score = (sum / weight) * 100
|
||||
return [
|
||||
Math.round(score * 10) / 10,
|
||||
score >= 60
|
||||
? 'BULL'
|
||||
: score >= 20
|
||||
? 'BULLISH'
|
||||
: score > -20
|
||||
? 'NEUTRAL'
|
||||
: score > -60
|
||||
? 'BEARISH'
|
||||
: 'BEAR',
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
export const SYSTEM_2_SOURCES = ['btc_bottom_reversal'] as const
|
||||
export const SYSTEM_1_SOURCES = ['truth'] as const
|
||||
export const SUPPORTED_TRADING_SOURCES = ['truth', 'btc_bottom_reversal'] as const
|
||||
export const TRUMP_MIN_CONFIDENCE = 88 as const
|
||||
export const TRUMP_COOLDOWN_HOURS = 12 as const
|
||||
export const TRUMP_MIN_HOLD_MINUTES = 30 as const
|
||||
export const TRUMP_STOP_LOSS_PCT = 1.5 as const
|
||||
export const TRUMP_MAX_HOLD_HOURS = 6 as const
|
||||
export const _CATEGORY_EXITS = {
|
||||
rsi_extreme_reversal: {
|
||||
stop_loss_pct: 8.0,
|
||||
trailing_activate_at_pct: 15.0,
|
||||
trailing_stop_pct: 6.0,
|
||||
max_hold_hours: 1440,
|
||||
},
|
||||
sma_reclaim: {
|
||||
stop_loss_pct: 6.0,
|
||||
trailing_activate_at_pct: 12.0,
|
||||
trailing_stop_pct: 5.0,
|
||||
max_hold_hours: 2160,
|
||||
invalidation: 'below_entry',
|
||||
},
|
||||
funding_extreme_reversal: {
|
||||
stop_loss_pct: 4.0,
|
||||
trailing_activate_at_pct: 10.0,
|
||||
trailing_stop_pct: 5.0,
|
||||
max_hold_hours: 720,
|
||||
time_stop_hours: 240,
|
||||
},
|
||||
btc_bottom_reversal_long: {
|
||||
stop_loss_pct: 35.0,
|
||||
trailing_activate_at_pct: null,
|
||||
trailing_stop_pct: null,
|
||||
max_hold_hours: 12960,
|
||||
invalidation: null,
|
||||
stop_ladder: [
|
||||
[20.0, -12.0],
|
||||
[40.0, 0.0],
|
||||
[70.0, 25.0],
|
||||
[110.0, 55.0],
|
||||
[160.0, 95.0],
|
||||
],
|
||||
},
|
||||
vcp_breakout: {
|
||||
stop_loss_pct: 3.0,
|
||||
trailing_activate_at_pct: 6.0,
|
||||
trailing_stop_pct: 2.5,
|
||||
max_hold_hours: 168,
|
||||
time_stop_hours: 48,
|
||||
},
|
||||
} as const
|
||||
export const _SYSTEM_2_DEFAULT = {
|
||||
stop_loss_pct: 5.0,
|
||||
trailing_activate_at_pct: 10.0,
|
||||
trailing_stop_pct: 4.0,
|
||||
max_hold_hours: 336,
|
||||
time_stop_hours: 120,
|
||||
} as const
|
||||
export const SYS2_DEFAULT_LEVERAGE = 2 as const
|
||||
export const SYS2_MIN_LEVERAGE = 1 as const
|
||||
export const SYS2_MAX_LEVERAGE = 10 as const
|
||||
export const SYS2_MAX_STOP_PCT = 35.0 as const
|
||||
export const SYS2_LIQ_BUFFER = 0.85 as const
|
||||
export const SYS2_MODE_STANDARD = 'standard' as const
|
||||
export const SYS2_MODE_AGGRESSIVE = 'aggressive' as const
|
||||
export const SYS2_MODES = ['standard', 'aggressive'] as const
|
||||
export const SYS2_MODE_DEFAULT_LEV = { standard: 2, aggressive: 8 } as const
|
||||
export const SYS2_DERISK_FRACTIONS = [0.6, 0.8, 1.0] as const
|
||||
export const SYS2_ADDON_PEAK_TRIGGERS = [25.0, 50.0, 85.0, 140.0, 220.0] as const
|
||||
export const SYS2_ADDON_FRACTIONS = [0.3, 0.2, 0.1, 0.1, 0.05] as const
|
||||
export const SYS2_AGGR_ADDON_PEAK_TRIGGERS = [15.0, 35.0, 60.0, 100.0, 160.0] as const
|
||||
export const SYS2_AGGR_ADDON_FRACTIONS = [0.5, 0.4, 0.3, 0.2, 0.1] as const
|
||||
export const SYS2_AGGR_DERISK_STEP_FRACS = [0.25, 0.25, 0.5] as const
|
||||
export const SYS2_STD_DERISK_STEP_FRACS = [
|
||||
0.3333333333333333, 0.3333333333333333, 0.3333333333333333,
|
||||
] as const
|
||||
export const SYS2_PEAK_TRAIL_START_PCT = 80.0 as const
|
||||
export const SYS2_PEAK_TRAIL_DD = 0.3 as const
|
||||
export const SYS2_AGGR_PEAK_TRAIL_START_PCT = 60.0 as const
|
||||
export const SYS2_AGGR_PEAK_TRAIL_DD = 0.42 as const
|
||||
export const _CATEGORY_SIZE_BASE = {
|
||||
rsi_extreme_reversal: 2.5,
|
||||
sma_reclaim: 2.0,
|
||||
funding_extreme_reversal: 1.4,
|
||||
btc_bottom_reversal_long: 2.3,
|
||||
vcp_breakout: 1.0,
|
||||
} as const
|
||||
export const _SYSTEM_2_SIZE_BASE_DEFAULT = 1.2 as const
|
||||
export const SYSTEM_2_SIZE_CAP = 4.0 as const
|
||||
export const SYS2_MAX_CONCURRENT = 3 as const
|
||||
export const SYS2_MAX_OPEN_NOTIONAL_MULT = 8.0 as const
|
||||
export type System2Mode = 'standard' | 'aggressive'
|
||||
export function normalizeMode(mode?: string | null): System2Mode {
|
||||
return mode?.trim().toLowerCase() === 'aggressive' ? 'aggressive' : 'standard'
|
||||
}
|
||||
export function effectiveLeverage(value?: number | null, mode?: string | null): number {
|
||||
return value == null || !Number.isFinite(value)
|
||||
? SYS2_MODE_DEFAULT_LEV[normalizeMode(mode)]
|
||||
: Math.max(1, Math.min(10, Math.trunc(value)))
|
||||
}
|
||||
export function protectiveStopPct(leverage: number): number {
|
||||
return Math.round(Math.min(35, (0.85 * 100) / effectiveLeverage(leverage)) * 100) / 100
|
||||
}
|
||||
export function approximateLiquidationPct(leverage: number): number {
|
||||
return Math.round((100 / effectiveLeverage(leverage)) * 100) / 100
|
||||
}
|
||||
export function isSystem2(source: string): boolean {
|
||||
return (SYSTEM_2_SOURCES as readonly string[]).includes(source.toLowerCase())
|
||||
}
|
||||
export function isSupportedTradingSource(source: string): boolean {
|
||||
return (SUPPORTED_TRADING_SOURCES as readonly string[]).includes(source.toLowerCase())
|
||||
}
|
||||
export function exitProfile(category?: string | null) {
|
||||
return (
|
||||
_CATEGORY_EXITS[category?.toLowerCase() as keyof typeof _CATEGORY_EXITS] ?? _SYSTEM_2_DEFAULT
|
||||
)
|
||||
}
|
||||
export function stopLadder(
|
||||
category?: string | null,
|
||||
): readonly (readonly [number, number])[] | null {
|
||||
const p = exitProfile(category)
|
||||
return 'stop_ladder' in p ? p.stop_ladder : null
|
||||
}
|
||||
export function addonLadder(mode?: string | null): [number, number, boolean][] {
|
||||
const aggressive = normalizeMode(mode) === 'aggressive'
|
||||
const triggers = aggressive ? SYS2_AGGR_ADDON_PEAK_TRIGGERS : SYS2_ADDON_PEAK_TRIGGERS
|
||||
const fractions = aggressive ? SYS2_AGGR_ADDON_FRACTIONS : SYS2_ADDON_FRACTIONS
|
||||
return triggers.map((t, i) => [t, fractions[i], i === triggers.length - 1])
|
||||
}
|
||||
export function peakTrail(mode?: string | null): readonly [number, number] {
|
||||
return normalizeMode(mode) === 'aggressive'
|
||||
? [SYS2_AGGR_PEAK_TRAIL_START_PCT, SYS2_AGGR_PEAK_TRAIL_DD]
|
||||
: [SYS2_PEAK_TRAIL_START_PCT, SYS2_PEAK_TRAIL_DD]
|
||||
}
|
||||
export function deriskLadder(leverage: number, mode?: string | null): [number, number, boolean][] {
|
||||
const p = protectiveStopPct(leverage)
|
||||
const steps =
|
||||
normalizeMode(mode) === 'aggressive' ? SYS2_AGGR_DERISK_STEP_FRACS : SYS2_STD_DERISK_STEP_FRACS
|
||||
return SYS2_DERISK_FRACTIONS.map((f, i) => [
|
||||
Math.round(-f * p * 10000) / 10000,
|
||||
steps[i],
|
||||
i === 2,
|
||||
])
|
||||
}
|
||||
export function system2SizeMultiplier(category: string | null, confidence: number): number {
|
||||
const base =
|
||||
_CATEGORY_SIZE_BASE[category?.toLowerCase() as keyof typeof _CATEGORY_SIZE_BASE] ??
|
||||
_SYSTEM_2_SIZE_BASE_DEFAULT
|
||||
return (
|
||||
Math.round(Math.min(base * (1 + Math.max(0, confidence - 70) / 50), SYSTEM_2_SIZE_CAP) * 100) /
|
||||
100
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { verifyMessage, isAddress, type Hex } from 'viem'
|
||||
export function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value)
|
||||
if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']'
|
||||
return (
|
||||
'{' +
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((k) => JSON.stringify(k) + ':' + canonicalJson((value as Record<string, unknown>)[k]))
|
||||
.join(',') +
|
||||
'}'
|
||||
)
|
||||
}
|
||||
export function bodyHash(body: unknown): string {
|
||||
return body == null ? '-' : createHash('sha256').update(canonicalJson(body)).digest('hex')
|
||||
}
|
||||
export function buildMessage(
|
||||
action: string,
|
||||
wallet: string,
|
||||
timestamp: number,
|
||||
body: unknown,
|
||||
): string {
|
||||
return `TrumpSignal · ${action}\nwallet: ${wallet.toLowerCase()}\ntimestamp: ${timestamp}\nbody: ${bodyHash(body)}`
|
||||
}
|
||||
export interface ReplayStore {
|
||||
claim(signature: string, expiresAt: number): Promise<boolean>
|
||||
}
|
||||
export async function verifySignedRequest(
|
||||
input: {
|
||||
action: string
|
||||
wallet: string
|
||||
timestamp: number
|
||||
signature: string
|
||||
body: unknown
|
||||
allowReplay?: boolean
|
||||
},
|
||||
replay: ReplayStore,
|
||||
now = Date.now(),
|
||||
): Promise<void> {
|
||||
if (!isAddress(input.wallet) || !Number.isSafeInteger(input.timestamp))
|
||||
throw new Error('Invalid signed envelope')
|
||||
if (input.timestamp > now + 30_000 || now - input.timestamp > 300_000)
|
||||
throw new Error('Signed request expired or clock skew too large')
|
||||
const valid = await verifyMessage({
|
||||
address: input.wallet,
|
||||
message: buildMessage(input.action, input.wallet, input.timestamp, input.body),
|
||||
signature: input.signature as Hex,
|
||||
})
|
||||
if (!valid) throw new Error('Signature does not match wallet')
|
||||
if (!input.allowReplay && !(await replay.claim(input.signature.toLowerCase(), now + 300_000)))
|
||||
throw new Error('Signature already used (replay blocked)')
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
export function evaluateSmaReclaim(bars: { close: number; volume: number }[]): {
|
||||
fired: boolean
|
||||
debug: Record<string, unknown>
|
||||
} {
|
||||
const no = (reason: string, extra: Record<string, unknown> = {}) => ({
|
||||
fired: false,
|
||||
debug: { reason, ...extra },
|
||||
})
|
||||
if (bars.length < 232) return no('insufficient_data', { bars: bars.length })
|
||||
const smas: (number | null)[] = bars.map(() => null)
|
||||
let sum = bars.slice(0, 200).reduce((s, b) => s + b.close, 0)
|
||||
smas[199] = sum / 200
|
||||
for (let i = 200; i < bars.length; i++) {
|
||||
sum += bars[i].close - bars[i - 200].close
|
||||
smas[i] = sum / 200
|
||||
}
|
||||
const close = bars.at(-1)!.close,
|
||||
sma = smas.at(-1)!
|
||||
if (sma == null) return no('sma_not_computable')
|
||||
if (close < sma) return no('shorts_disabled', { close, sma })
|
||||
if (close === sma) return no('on_sma_no_cross', { close, sma })
|
||||
for (let i = 2; i <= 31; i++) {
|
||||
const prior = smas.at(-i)
|
||||
if (prior == null) return no('sma_history_incomplete')
|
||||
if (bars.at(-i)!.close >= prior) return no('regime_period_too_short', { broke_at_day: i })
|
||||
}
|
||||
const avg = bars.slice(-31, -1).reduce((s, b) => s + b.volume, 0) / 30
|
||||
if (avg <= 0) return no('no_volume_baseline')
|
||||
const ratio = bars.at(-1)!.volume / avg
|
||||
if (ratio < 1.3) return no('weak_volume', { vol_ratio: ratio })
|
||||
return {
|
||||
fired: true,
|
||||
debug: {
|
||||
direction: 'buy',
|
||||
close,
|
||||
sma_200: sma,
|
||||
gap_pct: (Math.abs(close - sma) / sma) * 100,
|
||||
streak_days: 30,
|
||||
vol_ratio: ratio,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user