mirror of
https://github.com/NoFxAiOS/nofx.git
synced 2026-07-11 06:46:59 +08:00
feat(hyperliquid): add stock symbol market data support
- Add Hyperliquid/XYZ symbol normalization tests and backend coverage - Extend kline and market data lookup paths for US stock symbols - Wire frontend data API types for stock-oriented market requests
This commit is contained in:
@@ -8,6 +8,8 @@ import (
|
||||
"net/http"
|
||||
"nofx/logger"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -17,19 +19,43 @@ const (
|
||||
cacheDuration = 24 * time.Hour // Cache for 24 hours
|
||||
)
|
||||
|
||||
// CoinInfo represents basic coin information
|
||||
// CoinInfo represents basic Hyperliquid market information.
|
||||
type CoinInfo struct {
|
||||
Symbol string `json:"symbol"`
|
||||
Volume24h float64 `json:"volume_24h"` // 24h volume in USD
|
||||
Symbol string `json:"symbol"`
|
||||
Volume24h float64 `json:"volume_24h"` // 24h notional volume in USD
|
||||
MarkPrice float64 `json:"mark_price"`
|
||||
PrevDayPrice float64 `json:"prev_day_price,omitempty"`
|
||||
Change24hPct float64 `json:"change_24h_pct,omitempty"`
|
||||
MaxLeverage int `json:"max_leverage,omitempty"`
|
||||
SzDecimals int `json:"sz_decimals,omitempty"`
|
||||
}
|
||||
|
||||
// XYZCategory returns the NOFX product category for a Hyperliquid XYZ base symbol.
|
||||
func XYZCategory(baseSymbol string) string {
|
||||
baseSymbol = strings.ToUpper(strings.TrimSpace(strings.TrimPrefix(baseSymbol, "xyz:")))
|
||||
switch baseSymbol {
|
||||
case "TSLA", "NVDA", "AAPL", "MSFT", "GOOGL", "GOOG", "AMZN", "META", "NFLX", "AMD", "INTC", "COIN", "MSTR", "PLTR", "HOOD", "CRCL", "SNDK", "MU", "SMSN", "DRAM", "SKHX", "BABA", "ASML", "AVGO", "IONQ", "RGTI", "RKLB", "SMCI", "MARA", "RIOT", "MRVL", "SNOW", "CRM", "ORCL", "ADBE", "PYPL", "SHOP", "UBER", "SPOT", "ABNB", "RDDT", "ARM", "SOFI", "XYZ", "LVMH", "PDD", "NVO", "SONY", "DIS", "WMT", "NKE", "JPM", "BAC", "V", "MA", "JNJ", "PG", "UNH", "HD", "XOM", "CVX", "TM", "RACE", "VOW3", "BMW", "MBG":
|
||||
return "stock"
|
||||
case "GOLD", "SILVER", "COPPER", "NATGAS", "URANIUM", "ALUMINIUM", "PLATINUM", "PALLADIUM", "BRENTOIL", "CL", "CORN", "WHEAT", "TTF":
|
||||
return "commodity"
|
||||
case "SPX", "NDX", "DJI", "VIX", "DAX", "FTSE", "NIKKEI", "HSI", "CSI300", "XYZ100", "XYZ25", "XYZ50":
|
||||
return "index"
|
||||
case "EUR", "GBP", "JPY", "AUD", "CAD", "CHF", "MXN", "BRL", "TRY", "ZAR", "CNH", "KRW":
|
||||
return "forex"
|
||||
case "OPENAI", "ANTHROPIC", "SPACEX", "STRIPE", "FIGMA", "DATBRICKS", "PERPLEXITY", "XAI", "BYTEDANCE", "REVOLUT":
|
||||
return "pre_ipo"
|
||||
default:
|
||||
return "stock"
|
||||
}
|
||||
}
|
||||
|
||||
// CoinProvider provides Hyperliquid coin lists
|
||||
type CoinProvider struct {
|
||||
mu sync.RWMutex
|
||||
allCoins []CoinInfo
|
||||
mainCoins []CoinInfo
|
||||
lastUpdated time.Time
|
||||
httpClient *http.Client
|
||||
mu sync.RWMutex
|
||||
allCoins []CoinInfo
|
||||
mainCoins []CoinInfo
|
||||
lastUpdated time.Time
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -50,76 +76,105 @@ func GetProvider() *CoinProvider {
|
||||
// metaResponse represents the response from Hyperliquid meta endpoint
|
||||
type metaResponse struct {
|
||||
Universe []struct {
|
||||
Name string `json:"name"`
|
||||
Name string `json:"name"`
|
||||
SzDecimals int `json:"szDecimals"`
|
||||
MaxLeverage int `json:"maxLeverage"`
|
||||
} `json:"universe"`
|
||||
}
|
||||
|
||||
// assetCtx represents asset context with volume data
|
||||
// assetCtx represents asset context with market data.
|
||||
type assetCtx struct {
|
||||
DayNtlVlm string `json:"dayNtlVlm"` // 24h notional volume
|
||||
MarkPx string `json:"markPx"`
|
||||
PrevDayPx string `json:"prevDayPx"`
|
||||
}
|
||||
|
||||
// fetchCoins fetches all coins from Hyperliquid API and sorts by volume
|
||||
func (p *CoinProvider) fetchCoins(ctx context.Context) error {
|
||||
// Request metaAndAssetCtxs to get both coin names and volume data
|
||||
reqBody := []byte(`{"type": "metaAndAssetCtxs"}`)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", hyperliquidInfoURL,
|
||||
func fetchPerpDexCoins(ctx context.Context, client *http.Client, dex string) ([]CoinInfo, error) {
|
||||
reqPayload := map[string]string{"type": "metaAndAssetCtxs"}
|
||||
if dex != "" {
|
||||
reqPayload["dex"] = dex
|
||||
}
|
||||
reqBody, err := json.Marshal(reqPayload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encode request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", hyperliquidInfoURL,
|
||||
bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := p.httpClient.Do(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch coin data: %w", err)
|
||||
return nil, fmt.Errorf("failed to fetch coin data: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("API returned status %d", resp.StatusCode)
|
||||
return nil, fmt.Errorf("API returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Response is an array: [meta, [assetCtxs...]]
|
||||
var rawResp []json.RawMessage
|
||||
if err := json.NewDecoder(resp.Body).Decode(&rawResp); err != nil {
|
||||
return fmt.Errorf("failed to decode response: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
if len(rawResp) < 2 {
|
||||
return fmt.Errorf("unexpected response format")
|
||||
return nil, fmt.Errorf("unexpected response format")
|
||||
}
|
||||
|
||||
// Parse meta
|
||||
var meta metaResponse
|
||||
if err := json.Unmarshal(rawResp[0], &meta); err != nil {
|
||||
return fmt.Errorf("failed to parse meta: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse meta: %w", err)
|
||||
}
|
||||
|
||||
// Parse asset contexts
|
||||
var ctxs []assetCtx
|
||||
if err := json.Unmarshal(rawResp[1], &ctxs); err != nil {
|
||||
return fmt.Errorf("failed to parse asset contexts: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse asset contexts: %w", err)
|
||||
}
|
||||
|
||||
// Build coin list with volume
|
||||
var coins []CoinInfo
|
||||
coins := make([]CoinInfo, 0, len(meta.Universe))
|
||||
for i, u := range meta.Universe {
|
||||
var vol float64
|
||||
var vol, mark, prevDay, change24hPct float64
|
||||
if i < len(ctxs) {
|
||||
fmt.Sscanf(ctxs[i].DayNtlVlm, "%f", &vol)
|
||||
vol, _ = strconv.ParseFloat(ctxs[i].DayNtlVlm, 64)
|
||||
mark, _ = strconv.ParseFloat(ctxs[i].MarkPx, 64)
|
||||
prevDay, _ = strconv.ParseFloat(ctxs[i].PrevDayPx, 64)
|
||||
if prevDay > 0 && mark > 0 {
|
||||
change24hPct = ((mark - prevDay) / prevDay) * 100
|
||||
}
|
||||
}
|
||||
coins = append(coins, CoinInfo{
|
||||
Symbol: u.Name,
|
||||
Volume24h: vol,
|
||||
Symbol: u.Name,
|
||||
Volume24h: vol,
|
||||
MarkPrice: mark,
|
||||
PrevDayPrice: prevDay,
|
||||
Change24hPct: change24hPct,
|
||||
MaxLeverage: u.MaxLeverage,
|
||||
SzDecimals: u.SzDecimals,
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by volume descending
|
||||
sort.Slice(coins, func(i, j int) bool {
|
||||
return coins[i].Volume24h > coins[j].Volume24h
|
||||
})
|
||||
return coins, nil
|
||||
}
|
||||
|
||||
// GetPerpDexCoins fetches current tradable USDC perp assets for a given Hyperliquid dex.
|
||||
func GetPerpDexCoins(ctx context.Context, dex string) ([]CoinInfo, error) {
|
||||
return fetchPerpDexCoins(ctx, &http.Client{Timeout: 30 * time.Second}, dex)
|
||||
}
|
||||
|
||||
// fetchCoins fetches all default Hyperliquid crypto coins and sorts by volume
|
||||
func (p *CoinProvider) fetchCoins(ctx context.Context) error {
|
||||
coins, err := fetchPerpDexCoins(ctx, p.httpClient, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
@@ -134,7 +189,7 @@ func (p *CoinProvider) fetchCoins(ctx context.Context) error {
|
||||
p.lastUpdated = time.Now()
|
||||
|
||||
logger.Infof("✅ Hyperliquid coin list updated: %d total coins, top 20 by volume cached", len(coins))
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -195,7 +250,7 @@ func GetAllCoinSymbols(ctx context.Context) ([]string, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
symbols := make([]string, len(coins))
|
||||
for i, c := range coins {
|
||||
symbols[i] = c.Symbol
|
||||
@@ -209,7 +264,7 @@ func GetMainCoinSymbols(ctx context.Context, limit int) ([]string, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
symbols := make([]string, len(coins))
|
||||
for i, c := range coins {
|
||||
symbols[i] = c.Symbol
|
||||
|
||||
@@ -18,16 +18,16 @@ const (
|
||||
|
||||
// Candle represents a single OHLCV candle from Hyperliquid
|
||||
type Candle struct {
|
||||
OpenTime int64 `json:"t"` // Open time in milliseconds
|
||||
CloseTime int64 `json:"T"` // Close time in milliseconds
|
||||
Symbol string `json:"s"` // Coin symbol
|
||||
Interval string `json:"i"` // Interval
|
||||
Open string `json:"o"` // Open price
|
||||
High string `json:"h"` // High price
|
||||
Low string `json:"l"` // Low price
|
||||
Close string `json:"c"` // Close price
|
||||
Volume string `json:"v"` // Volume in base unit
|
||||
TradeCount int `json:"n"` // Number of trades
|
||||
OpenTime int64 `json:"t"` // Open time in milliseconds
|
||||
CloseTime int64 `json:"T"` // Close time in milliseconds
|
||||
Symbol string `json:"s"` // Coin symbol
|
||||
Interval string `json:"i"` // Interval
|
||||
Open string `json:"o"` // Open price
|
||||
High string `json:"h"` // High price
|
||||
Low string `json:"l"` // Low price
|
||||
Close string `json:"c"` // Close price
|
||||
Volume string `json:"v"` // Volume in base unit
|
||||
TradeCount int `json:"n"` // Number of trades
|
||||
}
|
||||
|
||||
// CandleRequest represents the request for candleSnapshot
|
||||
@@ -230,21 +230,117 @@ type Meta struct {
|
||||
|
||||
// AssetInfo represents information about a single asset
|
||||
type AssetInfo struct {
|
||||
Name string `json:"name"`
|
||||
SzDecimals int `json:"szDecimals"`
|
||||
MaxLeverage int `json:"maxLeverage"`
|
||||
Name string `json:"name"`
|
||||
SzDecimals int `json:"szDecimals"`
|
||||
MaxLeverage int `json:"maxLeverage"`
|
||||
}
|
||||
|
||||
// NormalizeCoin normalizes coin name for Hyperliquid API
|
||||
// Examples:
|
||||
// - "BTCUSDT" -> "BTC"
|
||||
// - "TSLA-USDC" -> "TSLA"
|
||||
// - "TESLA-USDC" -> "TSLA"
|
||||
// - "SAMSUNG-USDC" -> "SMSN"
|
||||
// - "xyz:TSLA" -> "TSLA"
|
||||
// - "BTC" -> "BTC"
|
||||
func NormalizeCoin(symbol string) string {
|
||||
return NormalizeCoinBase(symbol)
|
||||
}
|
||||
|
||||
// XYZDisplayNameToCoin maps user-facing product labels back to Hyperliquid xyz coin names.
|
||||
// Hyperliquid routes candles/orders by short names (for example xyz:SMSN), while NOFX
|
||||
// shows full names (for example SAMSUNG-USDC) in the UI.
|
||||
var XYZDisplayNameToCoin = map[string]string{
|
||||
"TESLA": "TSLA",
|
||||
"NVIDIA": "NVDA",
|
||||
"ROBINHOOD": "HOOD",
|
||||
"INTEL": "INTC",
|
||||
"PALANTIR": "PLTR",
|
||||
"COINBASE": "COIN",
|
||||
"APPLE": "AAPL",
|
||||
"MICROSOFT": "MSFT",
|
||||
"ORACLE": "ORCL",
|
||||
"GOOGLE": "GOOGL",
|
||||
"ALPHABET": "GOOGL",
|
||||
"AMAZON": "AMZN",
|
||||
"MICRON": "MU",
|
||||
"SANDISK": "SNDK",
|
||||
"MICROSTRATEGY": "MSTR",
|
||||
"CIRCLE": "CRCL",
|
||||
"NETFLIX": "NFLX",
|
||||
"COSTCO": "COST",
|
||||
"ELI-LILLY": "LLY",
|
||||
"SK-HYNIX": "SKHX",
|
||||
"SKHYNIX": "SKHX",
|
||||
"TSMC": "TSM",
|
||||
"RIVIAN": "RIVN",
|
||||
"ALIBABA": "BABA",
|
||||
"CRUDE-OIL": "CL",
|
||||
"CRUDEOIL": "CL",
|
||||
"NATURAL-GAS": "NATGAS",
|
||||
"NATURALGAS": "NATGAS",
|
||||
"SAMSUNG": "SMSN",
|
||||
"USA-RARE-EARTH": "USAR",
|
||||
"USARAREEARTH": "USAR",
|
||||
"COREWEAVE": "CRWV",
|
||||
"DOLLAR-INDEX": "DXY",
|
||||
"DOLLARINDEX": "DXY",
|
||||
"GAMESTOP": "GME",
|
||||
"KOREA-200": "KR200",
|
||||
"KOREA200": "KR200",
|
||||
"JAPAN-225": "JP225",
|
||||
"JAPAN225": "JP225",
|
||||
"SOUTH-KOREA-ETF": "EWY",
|
||||
"SOUTHKOREAETF": "EWY",
|
||||
"JAPAN-ETF": "EWJ",
|
||||
"JAPANETF": "EWJ",
|
||||
"BRENT-OIL": "BRENTOIL",
|
||||
"BRENTOIL": "BRENTOIL",
|
||||
"HIMS-HERS": "HIMS",
|
||||
"HIMSHERS": "HIMS",
|
||||
"S&P-500": "SP500",
|
||||
"SP-500": "SP500",
|
||||
"SP500": "SP500",
|
||||
"DRAFTKINGS": "DKNG",
|
||||
"LITECOIN": "LITE",
|
||||
"ENERGY-SECTOR-ETF": "XLE",
|
||||
"ENERGYSECTORETF": "XLE",
|
||||
"TTF-GAS": "TTF",
|
||||
"TTFGAS": "TTF",
|
||||
"BLACKSTONE": "BX",
|
||||
"MARVELL": "MRVL",
|
||||
"ROCKET-LAB": "RKLB",
|
||||
"ROCKETLAB": "RKLB",
|
||||
"VOLATILITY": "VOL",
|
||||
"COINBASE-PRE-IPO": "CBRS",
|
||||
"COINBASEPREIPO": "CBRS",
|
||||
"BRAZIL-ETF": "EWZ",
|
||||
"BRAZILETF": "EWZ",
|
||||
"ZOOM": "ZM",
|
||||
"NIFTY-50": "NIFTY",
|
||||
"NIFTY50": "NIFTY",
|
||||
"TAIWAN-ETF": "EWT",
|
||||
"TAIWANETF": "EWT",
|
||||
"SPACEX-PRE-IPO": "SPCX",
|
||||
"SPACEXPREIPO": "SPCX",
|
||||
"IBOVESPA": "IBOV",
|
||||
}
|
||||
|
||||
func NormalizeXYZAlias(base string) string {
|
||||
base = strings.ToUpper(strings.TrimSpace(base))
|
||||
base = strings.TrimPrefix(base, "XYZ:")
|
||||
base = strings.TrimSuffix(base, "-USDC")
|
||||
base = strings.TrimSuffix(base, "-USD")
|
||||
if mapped, ok := XYZDisplayNameToCoin[base]; ok {
|
||||
return mapped
|
||||
}
|
||||
compact := strings.NewReplacer(" ", "", "_", "", ".", "", "/", "", "&", "AND").Replace(base)
|
||||
if mapped, ok := XYZDisplayNameToCoin[compact]; ok {
|
||||
return mapped
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// MapTimeframe maps common timeframe strings to Hyperliquid format
|
||||
func MapTimeframe(interval string) string {
|
||||
switch interval {
|
||||
@@ -379,18 +475,26 @@ func IsXYZAsset(symbol string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// Check newer xyz assets that are represented by full display-name aliases in NOFX.
|
||||
for _, s := range XYZDisplayNameToCoin {
|
||||
if s == coin {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NormalizeCoinBase removes common suffixes to get base symbol
|
||||
func NormalizeCoinBase(symbol string) string {
|
||||
symbol = strings.ToUpper(strings.TrimSpace(symbol))
|
||||
hasXYZPrefix := strings.HasPrefix(symbol, "XYZ:")
|
||||
// Remove xyz: prefix if present
|
||||
if strings.HasPrefix(symbol, "xyz:") {
|
||||
return strings.TrimPrefix(symbol, "xyz:")
|
||||
if hasXYZPrefix {
|
||||
return NormalizeXYZAlias(strings.TrimPrefix(symbol, "XYZ:"))
|
||||
}
|
||||
// Remove -USDC suffix
|
||||
if strings.HasSuffix(symbol, "-USDC") {
|
||||
return strings.TrimSuffix(symbol, "-USDC")
|
||||
return NormalizeXYZAlias(strings.TrimSuffix(symbol, "-USDC"))
|
||||
}
|
||||
// Remove USDT suffix
|
||||
if strings.HasSuffix(symbol, "USDT") {
|
||||
@@ -400,14 +504,15 @@ func NormalizeCoinBase(symbol string) string {
|
||||
if strings.HasSuffix(symbol, "USD") {
|
||||
return strings.TrimSuffix(symbol, "USD")
|
||||
}
|
||||
return symbol
|
||||
return NormalizeXYZAlias(symbol)
|
||||
}
|
||||
|
||||
// FormatCoinForAPI formats the coin name for Hyperliquid API
|
||||
// Stock perps need xyz:SYMBOL format, crypto uses plain symbol
|
||||
func FormatCoinForAPI(symbol string) string {
|
||||
hasExplicitXYZ := strings.HasPrefix(strings.ToLower(strings.TrimSpace(symbol)), "xyz:")
|
||||
base := NormalizeCoinBase(symbol)
|
||||
if IsXYZAsset(base) {
|
||||
if hasExplicitXYZ || IsXYZAsset(base) {
|
||||
return "xyz:" + base
|
||||
}
|
||||
return base
|
||||
|
||||
@@ -159,6 +159,10 @@ func TestNormalizeCoin(t *testing.T) {
|
||||
{"BTCUSDT", "BTC"},
|
||||
{"BTCUSD", "BTC"},
|
||||
{"TSLA-USDC", "TSLA"},
|
||||
{"TESLA-USDC", "TSLA"},
|
||||
{"SMSN-USDC", "SMSN"},
|
||||
{"SAMSUNG-USDC", "SMSN"},
|
||||
{"xyz:SMSN", "SMSN"},
|
||||
{"AAPL-USDC", "AAPL"},
|
||||
{"ETH", "ETH"},
|
||||
{"ETHUSDT", "ETH"},
|
||||
@@ -204,6 +208,10 @@ func TestFormatCoinForAPI(t *testing.T) {
|
||||
{"ETH", "ETH"},
|
||||
{"TSLA", "xyz:TSLA"},
|
||||
{"TSLA-USDC", "xyz:TSLA"},
|
||||
{"TESLA-USDC", "xyz:TSLA"},
|
||||
{"SMSN-USDC", "xyz:SMSN"},
|
||||
{"SAMSUNG-USDC", "xyz:SMSN"},
|
||||
{"xyz:SMSN", "xyz:SMSN"},
|
||||
{"xyz:TSLA", "xyz:TSLA"},
|
||||
{"NVDA", "xyz:NVDA"},
|
||||
{"GOLD", "xyz:GOLD"},
|
||||
|
||||
Reference in New Issue
Block a user