Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@tradecanvas/analytics

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tradecanvas/analytics

Backtesting, portfolio tracking, and risk analytics for TradeCanvas — bar-by-bar Backtester with virtual fills, commission/slippage models, and risk metrics (Sharpe, Sortino, Calmar, max drawdown).

latest
Source
npmnpm
Version
0.9.0
Version published
Weekly downloads
185
-24.8%
Maintainers
1
Weekly downloads
 
Created
Source

@tradecanvas/analytics

Backtesting, portfolio tracking, and risk analytics for TradeCanvas.

Preview release. API is stable but the engine has only been validated against synthetic test fixtures. Treat results as indicative until you've cross-checked them against your own reference implementation.

Install

npm install @tradecanvas/analytics @tradecanvas/commons

Backtester

Bar-by-bar engine. Strategy fn runs at close of each bar; orders fill on the next bar (market → next-bar open, limit/stop → when the next bar trades through the trigger price).

import { Backtester, FixedCommission, PercentSlippage } from '@tradecanvas/analytics'

const bt = new Backtester({
  initialCash: 10_000,
  commission: new FixedCommission(2),
  slippage: new PercentSlippage(0.0005),
  allowShort: true,
})

const result = bt.run(historicalBars, (ctx) => {
  if (!ctx.position) {
    ctx.placeOrder({ side: 'long', type: 'market', quantity: 1 })
  } else if (ctx.bar.close > ctx.position.averagePrice * 1.02) {
    ctx.close()
  }
})

console.log(result.metrics.sharpe, result.metrics.maxDrawdownPct)

StrategyContext

Field / methodDescription
barCurrent bar
indexIndex of bar in the input series
historyBars up to and including bar
positionCurrent position or null
cashAvailable cash
equityCash + mark-to-market position value
placeOrder(order)Queue order for next bar
close(tag?)Market-close current position
cancel(orderId)Cancel a pending order

Commission & slippage models

  • FixedCommission(perTrade)
  • PercentCommission(rate) — fraction of notional, e.g. 0.001 = 10 bps
  • PerShareCommission(perShare, minimum?)
  • PercentSlippage(rate) — adverse fraction of price
  • RangeBasedSlippage(factor) — proportional to bar range

Portfolio

Tracks cash, one net position, realized P&L, and the equity curve.

import { Portfolio } from '@tradecanvas/analytics'

const portfolio = new Portfolio({ initialCash: 10_000 })
portfolio.applyFill({ ... })
portfolio.mark(time, price)

portfolio.getPosition()        // → { side, quantity, averagePrice, ... } | null
portfolio.getTrades()          // → closed trades
portfolio.getEquityCurve()     // → equity points
portfolio.equity(price)        // mark-to-market

Currently single-position. Multi-symbol portfolios are on the roadmap.

Risk metrics

import { computeRiskMetrics } from '@tradecanvas/analytics'

const m = computeRiskMetrics(initialCash, equityCurve, trades, {
  periodsPerYear: 252,    // optional; auto-detected from timestamps
  riskFreeRate: 0.03,
})

m.totalReturnPct
m.cagr
m.sharpe
m.sortino
m.calmar
m.maxDrawdownPct
m.winRate
m.profitFactor
m.expectancy

Strategy library

Reference strategies live under @tradecanvas/analytics — drop in, tune parameters, run. All four implement the same StrategyFn shape and respect the backtester's allowShort flag.

import {
  Backtester,
  smaCrossStrategy,
  rsiReversionStrategy,
  donchianBreakoutStrategy,
  bollingerReversionStrategy,
} from '@tradecanvas/analytics';

const bt = new Backtester({ initialCash: 10_000 });

const result = bt.run(bars, smaCrossStrategy({
  fastPeriod: 10,
  slowPeriod: 30,
  size: 1,
}));
StrategyStyleTuning
smaCrossStrategyTrend-followingfastPeriod, slowPeriod, size
rsiReversionStrategyMean-reversion (long-only)period, oversold, overbought, size
donchianBreakoutStrategyTrend breakout (Turtle-style)entryPeriod, exitPeriod, size
bollingerReversionStrategyMean-reversion to SMAperiod, stdDev, size

Each is a one-line function call returning a StrategyFn — easy to wrap, combine, or compare side-by-side in a backtest harness.

Edge cases (current behavior)

  • Gaps past a limit price: if the bar opens already through the limit, the order fills at the better of open and the limit price.
  • Stop orders inside a gap: fill at the worse of open and the stop price.
  • Bar that touches both stop and limit on the same bar: order resolves to the more pessimistic price for the current side (no intra-bar tick simulation).

These choices are conservative. A future release will offer a configurable intra-bar fill model.

License

MIT

Keywords

trading

FAQs

Package last updated on 02 Jun 2026

Did you know?

Socket

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.

Install

Related posts