JavaScript mirror of the PineScript API - with 100% PineScript-like Syntax
OakScriptJS is a TypeScript/JavaScript library that mirrors PineScript's API, enabling you to write indicators that look exactly like PineScript. Perfect for building trading engines, backtesting systems, or transpiling PineScript with OakScriptEngine.
- Computational Core: Pure calculation functions
- PineScript DSL: Declarative indicator syntax
- Native Operators: 100% PineScript-like with
close - open
This library includes:
- ✅ Technical Analysis (
ta.*) - All indicators and calculations - ✅ Mathematics (
math.*) - All mathematical operations - ✅ Arrays (
array.*) - Array manipulation and operations - ✅ Matrices (
matrix.*) - Matrix operations - ✅ Strings (
str.*) - String manipulation - ✅ Time (
time.*) - Time calculations and conversions - ✅ Color (
color.*) - Color data structures and manipulation - ✅ Drawing Objects (
line.*,box.*,label.*,linefill.*) - Computational features only
This library does NOT include:
- ❌ Rendering functions (
plot.*,table.*) - ❌ UI/Input functions (
input.*) - ❌ Strategy execution (
strategy.*) - ❌ Data fetching (
request.*) - ❌ Alert systems (
alert.*,alertcondition.*)
While drawing objects (line, box, label, linefill) are primarily visual in TradingView, they have genuine computational value:
line.get_price()- Calculate trend line prices using linear interpolation for breakout detectionboxgetters - Detect gap fills, range breakouts, and pattern recognitionlabel&linefill- Primarily annotations, but useful for algorithmic context
These objects are implemented without rendering - focusing purely on their computational aspects.
The excluded namespaces require external infrastructure (rendering engines, UI frameworks, data feeds, backtesting systems) that are specific to TradingView's platform. OakScriptJS focuses on what can be accurately replicated in pure JavaScript: calculations and data transformations.
- 100% PineScript Syntax: Native operators with Babel plugin - write
(close - open) / (high - low) - Exact API Match: Function signatures match PineScript exactly
- Type Safety: Full TypeScript support with type definitions
- PineScript DSL: Declarative indicator syntax with
indicator(),plot(),compile() - Performance Optimized: Efficient implementations for technical analysis
- Zero Dependencies: Lightweight with no external runtime dependencies
- Well Tested: Extensive test coverage ensuring accuracy
- Exact same signature as PineScript API - Maintains 100% compatibility
- Accuracy - Produces results matching PineScript calculations
- Performance - Optimized for speed and efficiency
# npm
npx jsr add @deepentropy/oakscriptjs
# pnpm (10.9+)
pnpm add jsr:@deepentropy/oakscriptjs
# yarn (4.9+)
yarn add jsr:@deepentropy/oakscriptjs
# Deno
deno add jsr:@deepentropy/oakscriptjs
# Bun
bunx jsr add @deepentropy/oakscriptjsnpm install @deepentropy/oakscriptjsimport { ta } from '@deepentropy/oakscriptjs';
const closes = [100, 102, 101, 103, 105];
const sma = ta.sma(closes, 3);
const rsi = ta.rsi(closes, 14);import { indicator, plot, close, ta, color, compile } from '@deepentropy/oakscriptjs';
indicator("My RSI");
const rsi = ta.rsi(close, 14);
plot(rsi, {color: color.purple});
export default compile();import { indicator, plot, close, open, high, low, compile } from '@deepentropy/oakscriptjs';
indicator("Balance of Power");
const bop = (close - open) / (high - low); // Native operators!
plot(bop);
export default compile();📚 See Complete Examples in the Guide →
- 🎯 OakScriptEngine Integration - Transpile PineScript to JavaScript
- 📊 Custom Trading Engines - Build backtesting or execution systems
- 📈 Analysis Tools - Create technical analysis applications
- 🤖 Algorithm Development - Develop trading algorithms
- 📚 Educational Projects - Learn technical indicators
OakScriptJS is designed to make PineScript transpilation straightforward:
// PineScript
indicator("My Indicator")
bop = (close - open) / (high - low)
plot(bop)
// Transpiles to (with Babel plugin)
import { indicator, plot, close, open, high, low, compile } from '@deepentropy/oakscriptjs';
indicator("My Indicator");
const bop = (close - open) / (high - low);
plot(bop);
export default compile();100% PineScript syntax with Babel plugin!
📚 Complete Transpilation Guide →
- ✅ Streamlined Documentation: Single approach using native operators with Babel
- ✅ Cleaner Examples: All examples updated to use DSL with native operators
- ✅ Better Organization: Removed outdated examples, kept only PineScript DSL patterns
- ✅ Internal Refactoring: IndicatorController is now internal implementation detail
Complete implementation of PineScript's technical analysis functions:
- Moving Averages:
sma(),ema(),wma(),vwma(),swma(), etc. - Oscillators:
rsi(),stoch(),cci(),macd(),mfi(), etc. - Volatility:
bb(),atr(),stdev(),variance(), etc. - Momentum:
mom(),roc(),percentrank(), etc. - Regression:
linreg(),correlation(), etc. - Crossovers:
crossover(),crossunder(),cross() - Other:
change(),tr(),supertrend(), and many more
Mathematical functions and operations:
- Basic:
abs(),ceil(),floor(),round() - Min/Max:
min(),max(),avg() - Powers:
sqrt(),pow(),exp(),log(),log10() - Trigonometry:
sin(),cos(),tan(),asin(),acos(),atan(),atan2() - Utilities:
sum(),sign(),random(),todegrees(),toradians()
Array manipulation functions:
- Creation:
new_array(),from() - Access:
get(),set(),size() - Modification:
push(),pop(),shift(),unshift(),insert(),remove() - Analysis:
sum(),avg(),min(),max(),median(),stdev(),variance() - Operations:
sort(),reverse(),slice(),concat(),includes(),indexof()
Matrix operations for advanced calculations:
- Creation:
new(),copy() - Operations:
mult(),add(),transpose() - Access:
get(),set(),row(),col()
String manipulation functions:
- Conversion:
tostring(),tonumber() - Manipulation:
substring(),split(),concat(),replace() - Case:
upper(),lower() - Search:
contains(),pos(),startswith(),endswith() - Formatting:
format(),trim()
Time calculations and conversions:
- Conversions: Convert between timestamps and time components
- Calculations: Work with timeframes and time-based logic
Color creation and manipulation:
- Creation:
rgb(),from_hex(),new_color() - Components:
r(),g(),b(),t() - Predefined Colors:
red,green,blue,yellow, etc.
NEW: Drawing objects with computational features (no rendering):
- Creation:
new()- Create trend lines with coordinates - Computation:
get_price()- Linear interpolation for breakout detection - Getters:
get_x1(),get_y1(),get_x2(),get_y2() - Setters:
set_x1(),set_y1(),set_xy1(),set_color(),set_style(), etc. - Operations:
copy(),delete()
- Creation:
new()- Create rectangles for ranges - Computation:
get_top(),get_bottom(),get_left(),get_right()- Gap detection & range analysis - Setters:
set_top(),set_bottom(),set_bgcolor(),set_border_color(), etc. - Operations:
copy(),delete()
- Creation:
new()- Create labels at coordinates - Getters:
get_x(),get_y(),get_text() - Setters:
set_xy(),set_text(),set_color(),set_style(), etc. - Operations:
copy(),delete()
- Creation:
new()- Fill between two lines - Getters:
get_line1(),get_line2() - Setters:
set_color() - Operations:
delete()
Simple Moving Average
ta.sma(source: series_float, length: simple_int): series_floatParameters:
source- Source series (e.g., close prices)length- Number of bars to average
Returns: Series of SMA values
Exponential Moving Average
ta.ema(source: series_float, length: simple_int): series_floatRelative Strength Index
ta.rsi(source: series_float, length: simple_int): series_floatMoving Average Convergence Divergence
ta.macd(
source: series_float,
fastLength: simple_int,
slowLength: simple_int,
signalLength: simple_int
): [series_float, series_float, series_float]Returns: [macdLine, signalLine, histogram]
Bollinger Bands
ta.bb(
source: series_float,
length: simple_int,
mult: simple_float
): [series_float, series_float, series_float]Returns: [basis, upper, lower]
See the /examples/indicators directory for complete examples:
balance-of-power.ts- Balance of Power indicator with native operatorsrsi.ts- RSI with native operators and horizontal linesmacd.ts- MACD with native operators and histogram
OakScriptJS uses TypeScript types that mirror PineScript's type system:
type int = number;
type float = number;
type bool = boolean;
type series<T> = T[];
type series_float = series<float>;
type series_bool = series<bool>;npm installnpm run buildnpm test
npm run test:watch
npm run test:coveragenpm run lint
npm run lint:fixnpm run format
npm run format:checkoakscriptjs/
├── src/
│ ├── ta/ # Technical analysis functions
│ ├── math/ # Mathematical functions
│ ├── array/ # Array operations
│ ├── str/ # String operations
│ ├── color/ # Color functions
│ ├── types/ # Type definitions
│ ├── utils/ # Internal utilities
│ └── index.ts # Main entry point
├── tests/ # Test files
├── examples/ # Usage examples
└── dist/ # Built output
Included Namespaces:
- Complete
matrixnamespace implementation - Complete
timenamespace implementation -
tanamespace - Core indicators implemented -
mathnamespace - Complete -
arraynamespace - Complete -
strnamespace - Complete -
colornamespace - Complete -
line,box,label,linefill- Drawing objects (computational features only)
Improvements:
- Performance benchmarks
- Comprehensive documentation site
- Additional technical indicators
- More test coverage
Explicitly Excluded (require external infrastructure):
- ❌
plot,table- Rendering functions - ❌
input- UI controls - ❌
strategy- Strategy execution engine - ❌
request- Data fetching - ❌
alert,alertcondition- Alert system
Contributions are welcome! Please ensure:
- Maintain exact PineScript API signatures
- Add tests for new functionality
- Follow the existing code style
- Update documentation
MIT
- 📚 Complete Guide - User guide + OakScriptEngine transpilation guide
- 🔌 Babel Plugin Guide - Native operators setup
- 📊 Examples - Working indicator examples
- 🎯 API Reference - Complete API documentation
This library is inspired by TradingView's PineScript language. It is not affiliated with or endorsed by TradingView.