
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
ts-bitget-v2
Advanced tools
Modern TypeScript library for cryptocurrency trading - Modular architecture inspired by Ta4j
Modern TypeScript library for cryptocurrency futures backtesting with advanced DCA, liquidation simulation, and realistic Bitget constraints
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.
npm install ts-bitget-v2
Requirements:
┌─────────────────────────────────────────────────────────────┐
│ 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) │
└─────────────────────────────────────────────────────────────┘
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`);
See examples/21-multi-symbol-macd-rsi.ts for a complete multi-symbol DCA strategy featuring:
npm run example:21
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,
});
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);
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);
Combines entry and exit rules.
const strategy = new BaseStrategy(
'My Strategy',
entryRule,
exitRule,
{ stopLoss: 0.02, takeProfit: 0.05 } // optional
);
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()}`);
Multi-Symbol Benefits:
DCA Parameter Impact:
Real Trading Validation:
Core Documentation:
Example Analysis:
# 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)
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:
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.
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:
high/low to catch liquidations within the bar)🆕 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:
Exit Logic:
ROI ≥ highThreshold AND netPnL > 0total: Close entire position in one exitpartial: Close proportionally (1/dcaCount per signal)Risk Management:
Multi-Symbol Support:
Validated Features:
See:
examples/21-multi-symbol-macd-rsi.ts - Multi-symbol with DCAexamples/22-compare-dca-params.ts - DCA parameter comparisonBACKTEST_CONFIGURATION.md - Complete DCA documentationExit 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
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
Backtest Validation:
Real Trading Comparison:
v2.1.0 - Funding & Timestamps (Next)
v2.2.0 - Extended Data Sources
v2.3.0 - Advanced Features
v3.0.0 - Live Trading (Future)
See ROADMAP.md for detailed timeline.
Current status: v2.0.0 (Production-ready for backtesting)
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
See CHANGELOG.md for version history.
MIT © akimsoule
Inspired by:
Q: Why do backtests differ from real trading?
A: Several factors contribute to differences:
Q: What DCA parameters should I use?
A: Based on Example 22 comparison:
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:
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:
Multi-symbol diversification generally improves risk-adjusted returns. Test thoroughly on your target period and market conditions.
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:
FAQs
Modern TypeScript library for cryptocurrency trading - Modular architecture inspired by Ta4j
We found that ts-bitget-v2 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.