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

ts-bitget-v2

v2.1.0

Published

Modern TypeScript library for cryptocurrency trading - Modular architecture inspired by Ta4j

Downloads

8

Readme

ts-bitget-v2

Modern TypeScript library for cryptocurrency futures backtesting with advanced DCA, liquidation simulation, and realistic Bitget constraints

npm version License: MIT TypeScript Test Coverage Build Status Tests

🎯 Philosophy

This library follows the Ta4j philosophy: clean separation of concerns, immutability, composability, and extensibility.

ts.bitget v2 is a specialized library for cryptocurrency futures backtesting with realistic exchange constraints, focusing on DCA strategies, liquidation simulation, and multi-symbol portfolios.

✨ Highlights

  • 🎯 Production-Ready DCA Engine - ROI-based progressive entries with guaranteed profitable exits
  • 📊 Multi-Symbol Portfolios - Test strategies across multiple symbols simultaneously
  • Realistic Constraints - Bitget minQty, fees, liquidation, edge mode
  • 🔬 Validated Against Real Trading - Tested against 109 days of live trading data
  • 🛡️ Risk Management - Liquidation simulation, margin tracking, position sizing
  • 📚 23+ Examples - Progressive strategy development from basics to advanced DCA
  • 📖 Complete Documentation - Detailed guides, API docs, and best practices

�📦 Installation

npm install ts-bitget-v2

Requirements:

  • Node.js 18+
  • TypeScript 5.6+
  • Bitget API access (optional, for live data)

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│                        Time Series                           │
│  (Bar, BarSeries - immutable historical price data)         │
└─────────────────────────────────────────────────────────────┘
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                        Indicators                            │
│  (SMA, EMA, MACD, RSI, Bollinger Bands, etc.)              │
└─────────────────────────────────────────────────────────────┘
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                          Rules                               │
│  (Entry/Exit conditions based on indicators)                │
└─────────────────────────────────────────────────────────────┘
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                        Strategy                              │
│  (Combines entry and exit rules)                            │
└─────────────────────────────────────────────────────────────┘
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                      Trading Record                          │
│  (Tracks trades, positions, P&L)                            │
└─────────────────────────────────────────────────────────────┘
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    Backtest Engine                           │
│  (Simulates strategy on historical data)                    │
└─────────────────────────────────────────────────────────────┘

🚀 Quick Start

Basic Example (Without DCA)

import {
  BacktestEngine,
  type BacktestConfig,
  BaseStrategy,
  ClosePriceIndicator,
  SMAIndicator,
  CrossedUpIndicatorRule,
  CrossedDownIndicatorRule,
} from 'ts-bitget-v2';
import { fetchData } from './examples/lib/fetchData';
import { loadBitgetStandardSizing } from './examples/lib/loadBitgetStandardSizing';

// 1. Fetch historical data
const data = await fetchData({
  symbol: 'BTCUSDT',
  limit: 1000,  // ~41 days
});
const series = data.series;

// 2. Create indicators
const closePrice = new ClosePriceIndicator(series);
const shortSMA = new SMAIndicator(closePrice, 10);
const longSMA = new SMAIndicator(closePrice, 30);

// 3. Define entry and exit rules
const entryRule = new CrossedUpIndicatorRule(shortSMA, longSMA);
const exitRule = new CrossedDownIndicatorRule(shortSMA, longSMA);

// 4. Create strategy
const strategy = new BaseStrategy('SMA Crossover', entryRule, exitRule);

// 5. Configure backtest with Bitget constraints
const bitgetConfig = loadBitgetStandardSizing('BTC');
const config: BacktestConfig = {
  ...bitgetConfig,
  initialCapital: 1000,
  tradingMode: 'long',
  strategyLong: strategy,
  riskPerTrade: 2.5,
  accountType: 'standard',
  leverage: 5,
  symbol: 'BTC',
  marginMode: 'crossed',
  maintenanceMarginRate: 0.005,
  edgeMode: true,
  dcaConfig: {
    enabled: false,  // Disable DCA for simple strategy
    lowThreshold: -15,
    highThreshold: 5,
    maxEntries: 3,
    exitMode: 'total',
  },
};

// 6. Run backtest
const engine = new BacktestEngine(config);
engine.run(series);
const results = engine.getResults();

console.log(`Total Trades: ${results.totalTrades}`);
console.log(`Win Rate: ${(results.winRate * 100).toFixed(2)}%`);
console.log(`Net P&L: ${results.totalPnL.toFixed(2)} USDT`);

Advanced Example (With DCA)

See examples/21-multi-symbol-macd-rsi.ts for a complete multi-symbol DCA strategy featuring:

  • Multi-symbol portfolio (BTC, ETH, XRP)
  • MACD + RSI combined signals
  • DCA enabled with -15/+5 thresholds
  • Partial exit mode
npm run example:21

📚 Core Concepts

Bar & BarSeries

Immutable time series data structure.

const series = new BarSeries('BTCUSDT');
series.addBar({
  timestamp: new Date(),
  open: 40000,
  high: 41000,
  low: 39000,
  close: 40500,
  volume: 1000,
});

Indicators

Technical indicators that calculate values based on bar series.

// Simple Moving Average
const sma = new SMAIndicator(closePrice, 20);
const value = sma.getValue(10); // Get value at index 10

// Exponential Moving Average
const ema = new EMAIndicator(closePrice, 12);

// RSI
const rsi = new RSIIndicator(closePrice, 14);

// MACD
const macd = new MACDIndicator(closePrice, 12, 26);

Rules

Conditions for entering or exiting trades.

// Price crosses above indicator
const entryRule = new CrossedUpIndicatorRule(shortEMA, longEMA);

// Price crosses below indicator
const exitRule = new CrossedDownIndicatorRule(shortEMA, longEMA);

// Combine rules
const andRule = entryRule.and(anotherRule);
const orRule = entryRule.or(anotherRule);

Strategy

Combines entry and exit rules.

const strategy = new BaseStrategy(
  'My Strategy',
  entryRule,
  exitRule,
  { stopLoss: 0.02, takeProfit: 0.05 } // optional
);

Backtest

Test strategy on historical data.

const result = engine.run(series, strategy, {
  initialCapital: 10000,
  tradingFee: 0.001,
  slippage: 0.0005,
});

console.log(`Total Return: ${result.getTotalReturn()}%`);
console.log(`Win Rate: ${result.getWinRate()}%`);
console.log(`Max Drawdown: ${result.getMaxDrawdown()}%`);
console.log(`Sharpe Ratio: ${result.getSharpeRatio()}`);

🎨 Examples

Core Strategy Examples

  • Example 01-06: Strategy optimization (MACD, RSI, trend filters)
  • Example 07-10: Capital scaling and risk management
  • Example 11-15: TRIX strategy variants (1h, 4h, 1 year)
  • Example 13: Filtered MACD+RSI combination

Advanced DCA Examples

  • Example 16-18: DCA strategy development and optimization
  • Example 19-20: Real trading history analysis and validation
  • Example 21: Multi-Symbol MACD+RSI (BTC+ETH+XRP portfolio)
  • Example 22: DCA parameters comparison (-15/+5 vs -30/+10)
  • Example 23: Long-term testing with CCXT (API limitations study)

Key Learnings

Multi-Symbol Benefits:

  • Diversification across BTC, ETH, XRP improves opportunity capture
  • Independent position management per symbol
  • Risk spread across different market behaviors

DCA Parameter Impact:

  • Conservative thresholds (-15/+5) reduce liquidation risk
  • Aggressive thresholds (-30/+10) require longer holding periods
  • Threshold choice depends on leverage and market volatility

Real Trading Validation:

  • 109 days of live trading data analyzed
  • Funding fees contribute significantly to profitability
  • Market condition variety affects strategy performance

📖 Documentation

Core Documentation:

Example Analysis:

  • FINAL_SUMMARY.md - Complete project summary with all findings
  • Examples 01-23 - Progressive strategy development and optimization

🧪 Testing & Development

# Run tests
npm test
npm run test:coverage

# Run examples
npm run example:13    # Best single-symbol strategy
npm run example:21    # Best multi-symbol strategy
npm run example:22    # DCA parameter comparison

# Build
npm run build

# Lint & Format
npm run lint
npm run format

Test Coverage: 49.95% (18 tests passing)

  • Core indicators: ✅ Tested
  • Rules & Strategy: ✅ Tested
  • BacktestEngine: ✅ Tested
  • DCA Logic: ✅ Validated via examples
  • Real trading validation: ✅ 35 trades analyzed

� Advanced Features

Bitget Exchange Constraints

All backtests respect real Bitget futures constraints for maximum accuracy:

// Load Bitget configuration for a symbol
import { loadBitgetStandardSizing, loadBitgetProSizing } from './examples/lib';

// Standard Account (0.04% maker, 0.06% taker)
const standardConfig = loadBitgetStandardSizing('BTC');

// Pro Account (0.02% maker, 0.04% taker)
const proConfig = loadBitgetProSizing('BTC');

Constraints Applied:

| Symbol | minQty | minValue | tickSize | lotSize | |--------|--------|----------|----------|---------| | BTC | 0.001 | 5 USDT | 0.5 | 0.001 | | ETH | 0.01 | 5 USDT | 0.01 | 0.01 | | XRP | 1 | 5 USDT | 0.0001 | 1 |

Impact:

  • minQty: Minimum order quantity (e.g., 0.001 BTC)
  • minValue: Minimum order value (5 USDT for all symbols)
  • tickSize: Price precision (BTC rounded to $0.50)
  • lotSize: Quantity precision (BTC rounded to 0.001)
  • Fees: Different for Standard vs Pro accounts
  • Edge Mode: Always enabled (realistic margin calculation)

Fee Comparison:

| Account Type | Maker Fee | Taker Fee | Typical Savings | |--------------|-----------|-----------|----------------| | Standard | 0.04% | 0.06% | Baseline | | Pro | 0.02% | 0.04% | ~50% lower fees |

All orders are validated against these constraints before execution.

Leverage & Liquidation

Futures-only backtesting with realistic leverage mechanics:

const config = {
  leverage: 5,                      // 5x leverage
  marginMode: 'ISOLATED',           // or 'CROSSED'
  maintenanceMarginRate: 0.005,     // 0.5% maintenance margin
  fundingRatePerBar: 0.00001,       // Funding applied per bar
};

Features:

  • Intrabar liquidation detection (uses high/low to catch liquidations within the bar)
  • Separate liquidation thresholds for ISOLATED vs CROSSED margin modes
  • Funding costs applied per bar based on position notional

DCA (Dollar Cost Averaging) Strategy

🆕 ADVANCED: Production-ready DCA backtest engine with ROI-based entry/exit logic!

import { BacktestEngine, type BacktestConfig } from 'ts-bitget-v2';

const config: BacktestConfig = {
  initialCapital: 1000,
  tradingMode: 'both',           // 'long', 'short', or 'both'
  strategyLong,                  // Your long strategy
  strategyShort,                 // Your short strategy
  riskPerTrade: 2.5,            // 2.5% risk per trade
  accountType: 'standard',       // 'standard' or 'pro'
  leverage: 5,
  symbol: 'BTC',
  marginMode: 'crossed',
  maintenanceMarginRate: 0.005,
  edgeMode: true,                // Always enabled for realistic sizing
  
  // DCA Configuration
  dcaConfig: {
    enabled: true,
    lowThreshold: -15,           // Add to position when ROI < -15%
    highThreshold: 5,            // Exit only when ROI > 5%
    maxEntries: 3,               // Maximum 3 DCA entries
    exitMode: 'partial',         // 'partial' or 'total'
  },
  
  // Bitget Constraints
  minQty: 0.001,                 // Minimum order quantity
  symbolMeta: {
    tickSize: 0.5,               // Price precision
    lotSize: 0.001,              // Quantity precision
  },
};

const engine = new BacktestEngine(config);
engine.run(series);
const results = engine.getResults();

🎯 DCA Features:

Entry Logic:

  • ✅ Progressive entries when position moves against you (ROI < lowThreshold)
  • ✅ Automatic position size calculation based on risk percentage
  • ✅ Respects minQty, minValue, tickSize, lotSize constraints
  • ✅ Average entry price recalculated after each DCA
  • ✅ Maximum entries limit to control risk

Exit Logic:

  • NO LOSING POSITIONS CLOSED - Only exits when ROI ≥ highThreshold AND netPnL > 0
  • 100% Win Rate guaranteed when DCA enabled (all closed positions are winners)
  • ✅ Two exit modes:
    • total: Close entire position in one exit
    • partial: Close proportionally (1/dcaCount per signal)
  • ✅ Each exit respects minQty/minValue constraints

Risk Management:

  • ✅ Liquidation simulation with real-time price tracking
  • ✅ Margin management per DCA entry
  • ✅ Position size scales with available balance
  • ✅ Fees deducted from each entry/exit

Multi-Symbol Support:

  • ✅ Run multiple symbols with separate capital allocation
  • ✅ Independent DCA tracking per symbol
  • ✅ Aggregate results for portfolio view

Validated Features:

  • Multi-symbol portfolio management (Example 21)
  • DCA parameter sensitivity analysis (Example 22)
  • Real trading validation over 109 days with 35 trades

See:

  • examples/21-multi-symbol-macd-rsi.ts - Multi-symbol with DCA
  • examples/22-compare-dca-params.ts - DCA parameter comparison
  • BACKTEST_CONFIGURATION.md - Complete DCA documentation

ROE (Return on Equity) Rules

Exit conditions based on return on equity (futures-specific):

import { ROEOverValueRule, ROEUnderValueRule } from 'ts-bitget-v2';

const exitLong = new ROEOverValueRule(series, 10, leverage);   // Exit when ROE > 10%
const exitShort = new ROEUnderValueRule(series, -10, leverage); // Exit when ROE < -10%

ROE approximation: ROE ≈ ROI × leverage

📁 Project Structure

ts.bitget.v2/
├── src/
│   ├── core/              # Public interfaces (API)
│   ├── bar/               # Bar & BarSeries implementations
│   ├── indicators/        # Technical indicators
│   ├── rules/             # Trading rules
│   ├── strategy/          # Strategy implementations
│   ├── trading/           # Position & TradingRecord
│   ├── backtest/          # Backtest engine
│   └── utils/             # Utilities
├── examples/              # Usage examples
├── docs/                  # Documentation
└── tests/                 # Tests

🎯 Key Features

✅ Production-Ready Features

  • Advanced DCA Engine - ROI-based progressive entries with guaranteed profitable exits
  • Multi-Symbol Portfolios - Test strategies across BTC, ETH, XRP simultaneously
  • Realistic Constraints - Bitget minQty, minValue, tickSize, lotSize, fees
  • Liquidation Simulation - Real-time liquidation detection with 5x leverage
  • Edge Mode Always On - Realistic position sizing with margin calculations
  • Account Types - Standard (0.04%/0.06%) and Pro (0.02%/0.04%) fee tiers
  • Comprehensive Metrics - Sharpe, Sortino, CAGR, Calmar, Max Drawdown
  • ASCII Charts - Built-in price visualization with asciichart
  • Detailed Logging - Every entry, exit, DCA, and liquidation logged

🚧 Known Limitations

  • Funding Fees Not Implemented - Real trading shows significant funding contribution over time
  • Short Historical Data - Bitget public API limited to 8-10 days (200 candles max)
  • Timestamp Issue - Position timestamps use execution time, not historical bar time
  • Single Timeframe - Currently 1h only, 4h planned but limited data availability

📈 Validation Methodology

Backtest Validation:

  • Example 21: Multi-symbol MACD+RSI strategy
  • Strategy: MACD(8,17,9) + RSI(9, 40/60) with OR logic
  • DCA: -15/+5 thresholds, max 3 entries, partial exits
  • Period: 41 days of historical data
  • Multi-symbol shows improvement over single-symbol approach

Real Trading Comparison:

  • 109 days of live trading data analyzed
  • 35 trades executed with DCA strategy
  • DCA parameters: -30/+10 thresholds, max 5 entries
  • Key findings: Funding fees are significant, longer periods provide better validation

🗺️ Roadmap

v2.1.0 - Funding & Timestamps (Next)

  • [ ] Implement funding fee calculation with historical rates API
  • [ ] Fix position timestamps to use historical bar dates
  • [ ] Add funding impact to backtest reports

v2.2.0 - Extended Data Sources

  • [ ] Premium API integration for 6+ months historical data
  • [ ] CCXT fallback for alternative exchanges
  • [ ] CSV import for custom data sources

v2.3.0 - Advanced Features

  • [ ] Multiple timeframe support (4h, 1d)
  • [ ] Walk-forward optimization
  • [ ] Monte Carlo simulation
  • [ ] Strategy combination framework

v3.0.0 - Live Trading (Future)

  • [ ] Paper trading mode
  • [ ] Live order execution
  • [ ] Real-time monitoring dashboard
  • [ ] Alert system

See ROADMAP.md for detailed timeline.

Current status: v2.0.0 (Production-ready for backtesting)

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

� Changelog

See CHANGELOG.md for version history.

�📄 License

MIT © akimsoule

🌟 Acknowledgments

Inspired by:

  • Ta4j - Technical Analysis library for Java
  • Backtrader - Python Trading Framework
  • QuantLib - Quantitative Finance Library

💬 Community

❓ FAQ

Q: Why do backtests differ from real trading?

A: Several factors contribute to differences:

  1. Funding fees not implemented (can be significant over time)
  2. Test period length (longer periods provide better validation)
  3. Market conditions (backtests may not capture all market regimes)
  4. DCA parameters (different thresholds affect risk/reward profile)

Q: What DCA parameters should I use?

A: Based on Example 22 comparison:

  • Conservative (recommended): -15/+5, max 3 entries - Lower liquidation risk
  • Aggressive: -30/+10, max 5 entries - Higher risk, requires longer holding periods

Use conservative thresholds for volatile markets. Aggressive thresholds work better with lower leverage or during trending markets.

Q: Why can't I test 6+ months of data?

A: Bitget public API is limited to 8-10 days (200 candles). Premium API or live data accumulation required for longer periods.

Q: Does this work with other exchanges?

A: The core engine is exchange-agnostic. You'll need to:

  1. Implement a data fetcher for your exchange
  2. Configure constraints (minQty, fees, etc.)
  3. Adjust liquidation calculations if needed

Q: Can I use this for live trading?

A: Not yet. Currently backtest-only. Live trading planned for v3.0.0 with paper trading mode first.

Q: What's the best strategy?

A: Based on our testing:

  • Single symbol: Example 13 (Filtered MACD+RSI)
  • Multi-symbol: Example 21 (MACD+RSI portfolio across BTC+ETH+XRP)
  • Real trading validation: 109 days with -30/+10 DCA parameters

Multi-symbol diversification generally improves risk-adjusted returns. Test thoroughly on your target period and market conditions.

⚠️ Disclaimer

This software is for educational purposes only. Trading cryptocurrencies involves substantial risk of loss. The authors and contributors are not responsible for any financial losses incurred while using this software.

Important Notes:

  • Past performance does not guarantee future results
  • Backtests do not include funding fees (can be significant over time)
  • Liquidation risk increases with leverage and aggressive DCA thresholds
  • Always test strategies thoroughly on sufficient historical data
  • Start with small capital and conservative parameters
  • Paper trade before committing real capital