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

@sschepis/stock-bot

v0.1.2

Published

Self-contained RL trading bot with DQN, PER, and market simulation

Readme

stock-bot

A self-contained reinforcement learning trading bot engine written in pure TypeScript. No ML framework dependencies — just math.

Features

  • Deep Q-Network (DQN) with Double DQN, Prioritized Experience Replay (PER), n-step returns, and Polyak-averaged target networks
  • Pure TypeScript neural network — flat Float64Array buffers, He initialization, Adam optimizer, gradient clipping
  • 8-action extended action space: HOLD, BUY_LO/MD/HI, SELL_LO/MD/HI, CLOSE with leverage tiers
  • Fractal market simulator using fBM (Hosking method) + GARCH(1,1) + Merton jump-diffusion + Markov regime switching
  • 14 technical indicators with both batch and incremental (O(1) per candle) computation
  • Genetic algorithm hyperparameter optimization with tournament selection, crossover, and mutation
  • Trading constraints system — reverse-only, min-hold, cooldown, conviction threshold, loss budget, asymmetric sizing
  • Provider interfaces for plugging in live market feeds, trade executors, L2 data, and storage backends
  • Zero runtime dependencies — only typescript and vitest as dev dependencies

Installation

npm install @sschepis/stock-bot

Quick Start

import { DQNAgent, Market, TickSimulator, MemoryStorageProvider } from '@sschepis/stock-bot';

// Create a DQN agent
const agent = new DQNAgent({
  stateSize: 21,
  hiddenLayers: [48, 32],
  learningRate: 0.001,
  gamma: 0.95,
});

// Create a simulated market
const market = new Market();

// Run a training loop
for (let tick = 0; tick < 1000; tick++) {
  market.tick();
  const state = market.getFeatures(null);
  const action = agent.getAction(state, false, 0);
  const reward = 0; // compute your reward
  const nextState = market.getFeatures(null);
  agent.store(state, action, reward, nextState, false);
  agent.train();
}

// Save the trained agent
const storage = new MemoryStorageProvider();
agent.saveToStorage(storage, 'my-agent');

Architecture

stock-bot/
├── src/
│   ├── core/           # RL engine, neural net, market sim, indicators
│   ├── engines/        # Physics-based market analysis engines
│   ├── trading/        # Orchestrator logic, step functions, fast training
│   └── providers/      # Pluggable interfaces for external services
├── tests/              # 252 tests across 12 files
├── docs/               # Detailed documentation
└── examples/           # Ready-to-run usage examples

Core Modules

| Module | Description | |--------|-------------| | NeuralNet | Feedforward MLP with flat Float64Array storage, ReLU hidden layers, Adam optimizer | | DQNAgent | Double DQN with PER, n-step returns, Welford z-score normalization, streak scaling | | PrioritizedReplayBuffer | Sum-tree based O(log n) prioritized sampling with importance-weight correction | | Market | Market simulator with candle formation, regime detection, L2 book features | | TickSimulator | Fractal price generator: fBM + GARCH + jumps + regime switching | | TradingConstraints | Behavioral constraint system with 10 configurable rules | | IncrementalIndicators | O(1) per-candle incremental RSI, MACD, Bollinger, ATR, Stochastic, ADX, VWAP, OBV | | BayesianOptimizer | GA-based hyperparameter optimization with elitism and tournament selection |

Provider Interfaces

The library uses a provider pattern to decouple from external services:

  • StorageProvider — Replaces localStorage. Ships with MemoryStorageProvider (in-memory Map).
  • MarketFeedProvider — Interface for live price/candle feeds
  • TradeExecutorProvider — Interface for executing trades on an exchange
  • L2DataProvider — Interface for Level 2 order book data

Action Space

The agent operates over 8 actions with leverage tiers:

| Index | Action | Leverage | |-------|--------|----------| | 0 | HOLD | 0x | | 1 | BUY_LO | 0.25x | | 2 | BUY_MD | 0.60x | | 3 | BUY_HI | 1.00x | | 4 | SELL_LO | 0.25x | | 5 | SELL_MD | 0.60x | | 6 | SELL_HI | 1.00x | | 7 | CLOSE | 0x |

Market Regimes

The tick simulator supports 8 preset regimes:

  • trending_up / trending_down — Hurst > 0.5, directional drift
  • mean_revert — Hurst < 0.5, gravity toward equilibrium
  • volatile — High GARCH alpha, frequent jumps
  • calm — Low volatility, tight spread
  • random_walk — Hurst = 0.5, no drift
  • liquidation_cascade — Extreme vol + negative drift
  • accumulation — Low vol mean-reversion
  • cycle — Auto-rotates through trending → volatile → trending_down → mean_revert

Testing

npm test           # Run all 252 tests
npm run test:watch # Watch mode

Tests cover:

  • Unit tests for every core module
  • Integration tests for end-to-end training loops
  • Learning convergence tests (XOR learning, directional preference, danger avoidance)
  • Serialization round-trip tests
  • Provider interface tests

Documentation

See the docs/ folder:

Examples

See the examples/ folder:

License

MIT