npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

flow-trading-core

v1.0.2

Published

Reusable core trading functionality - WebSocket, API, market data

Readme

@trading-core/core

Reusable core trading functionality for building trading frontends. Extract your business logic from UI concerns and reuse across multiple frontends, mobile apps, and different brands.

🚀 Features

  • WebSocket Management - Automatic reconnection, subscription handling, message routing
  • REST API Client - Type-safe API calls for market data, orderbooks, trades
  • DEX Configuration - Multi-DEX support with market status management
  • React Hooks - Ready-to-use hooks for common trading functionality
  • Utilities - Price formatting, symbol parsing, orderbook processing
  • TypeScript First - Full type safety and excellent DX

📦 What's Included

Services (Framework-agnostic)

import { 
  TradingAPI,           // REST API client
  TradingWebSocket,     // WebSocket client  
  DEXConfigManager      // Multi-DEX configuration
} from '@trading-core/core';

React Hooks

import {
  useWebSocket,         // WebSocket connection management
  useMarketData,        // Market info, price subscriptions  
  useOrderbook          // Orderbook data & real-time updates
} from '@trading-core/core';

Utilities

import {
  formatPrice,          // Price formatting
  formatPercentChange,  // Percentage formatting
  parseSymbol,          // Symbol parsing (vntls:vOAI)
  processOrderbookData  // Orderbook processing
} from '@trading-core/core';

🏗️ Architecture

┌─────────────────────────────────────┐
│           Your Frontend             │  ← UI, Styling, Routing
├─────────────────────────────────────┤
│        React Hooks Layer           │  ← useMarketData, useOrderbook
├─────────────────────────────────────┤  
│         Services Layer             │  ← TradingAPI, WebSocket
├─────────────────────────────────────┤
│      Utilities & Types             │  ← Formatters, Parsers, Types
└─────────────────────────────────────┘

🎯 Quick Start

1. Install

npm install @trading-core/core

2. Configure DEXs

// src/config/dex.ts
import { DEXConfigs, createDEXConfigManager } from '@trading-core/core';

const DEX_CONFIGS: DEXConfigs = {
  vntls: {
    name: 'vntls',
    displayName: 'Ventuals DEX',
    apiUrl: 'http://localhost:3000',
    wsUrl: 'ws://localhost:3000/ws',
    defaultMarket: 'vntls:vOAI',
    markets: ['vntls:vOAI', 'vntls:vSPACEX', 'vntls:vCURSOR'],
    inactiveMarkets: ['vntls:vSTRIPE'] // Coming soon markets
  }
};

export const dexConfig = createDEXConfigManager(DEX_CONFIGS, 'vntls');

3. Initialize Services

// src/services/trading.ts
import { TradingAPI, TradingWebSocket } from '@trading-core/core';
import { dexConfig } from '../config/dex';

export const api = new TradingAPI({ 
  baseUrl: dexConfig.getConfig().apiUrl 
});

export const websocket = new TradingWebSocket({ 
  url: dexConfig.getConfig().wsUrl 
});

4. Use in Components

// src/components/TradingDashboard.tsx
import React from 'react';
import { useMarketData, useOrderbook, formatPrice } from '@trading-core/core';
import { api, websocket } from '../services/trading';
import { dexConfig } from '../config/dex';

export function TradingDashboard() {
  const {
    currentSymbol,
    currentPrice,
    switchSymbol,
    markets
  } = useMarketData({
    api,
    websocket,
    dexConfig,
    currentDEX: 'vntls'
  });

  const { asks, bids, spread } = useOrderbook({
    symbol: currentSymbol,
    api,
    websocket
  });

  return (
    <div>
      <h1>Current Price: {formatPrice(currentPrice)}</h1>
      <div>Spread: {formatPrice(spread)}</div>
      
      {/* Your custom UI components */}
      <YourOrderBookComponent asks={asks} bids={bids} />
      <YourMarketSelector 
        markets={markets}
        onSelect={switchSymbol}
        dexConfig={dexConfig}
      />
    </div>
  );
}

🔧 API Reference

TradingAPI

const api = new TradingAPI({
  baseUrl: 'http://localhost:3000',
  timeout: 10000,
  enableLogging: true
});

// Methods
await api.getMarkets()              // Get all markets
await api.getMarketInfo(symbol)     // Get market details
await api.getOrderbook(symbol, 20)  // Get orderbook
await api.getKlines(symbol, '1h')   // Get candlestick data

TradingWebSocket

const ws = new TradingWebSocket({
  url: 'ws://localhost:3000/ws',
  reconnectDelay: 5000,
  maxReconnectAttempts: 5,
  enableLogging: true
});

// Methods
await ws.connect()
ws.subscribe('vntls:vOAI', 'ticker')
ws.unsubscribe('vntls:vOAI', 'ticker')  
ws.addMessageHandler(handleMessage)
ws.disconnect()

useMarketData Hook

const {
  markets,           // Market[] - Available markets
  currentSymbol,     // string - Current trading symbol
  currentPrice,      // number - Real-time price
  marketInfo,        // MarketInfo | null - Market details
  isConnected,       // boolean - WebSocket status
  switchSymbol,      // (symbol: string) => void
  switchDEX,         // (dex: DEXType) => void
  loadMarkets        // () => Promise<void>
} = useMarketData({
  api,
  websocket,
  dexConfig,
  currentDEX: 'vntls'
});

useOrderbook Hook

const {
  asks,              // OrderbookEntry[] - Ask orders
  bids,              // OrderbookEntry[] - Bid orders  
  spread,            // number - Bid-ask spread
  isLoading,         // boolean - Loading state
  error,             // string | null - Error message
  reload             // () => Promise<void> - Reload data
} = useOrderbook({
  symbol: 'vntls:vOAI',
  api,
  websocket,
  limit: 20
});

🎨 Frontend Integration Examples

Different UI Styles

// Desktop Trading Terminal
<DesktopOrderBook asks={asks} bids={bids} theme="dark" />

// Mobile Trading App  
<MobileOrderBook asks={asks} bids={bids} theme="light" />

// Admin Dashboard
<AdminMarketOverview markets={markets} />

Different Frameworks

// React
const { asks, bids } = useOrderbook({ symbol, api, websocket });

// Vue (using core services directly)
const api = new TradingAPI(config);
const orderbook = await api.getOrderbook(symbol);

// Angular (using core services directly)  
this.websocket = new TradingWebSocket(config);
this.websocket.subscribe(symbol, 'ticker');

🔄 Migration Guide

From Existing Codebase

  1. Extract Configuration

    // Before: Hard-coded in components
    const API_URL = 'http://localhost:3000';
       
    // After: Centralized config
    const dexConfig = createDEXConfigManager(configs, 'vntls');
  2. Replace Direct API Calls

    // Before: Custom fetch logic
    const response = await fetch('/markets');
       
    // After: Use TradingAPI
    const markets = await api.getMarkets();
  3. Simplify WebSocket Management

    // Before: Manual WebSocket handling
    const ws = new WebSocket(url);
    ws.onmessage = handleMessage;
       
    // After: Use hook
    const { isConnected } = useWebSocket({ config });

🧪 Development

# Build package
npm run build

# Watch mode
npm run dev

# Clean dist
npm run clean

📝 License

MIT - Build awesome trading interfaces! 🚀