← Rajandran R's posts

OpenScript: An Open Source Custom Scripting Engine to Build Your Own Indicators and Strategies

View Original ↗

Have you ever wondered why the indicator you spent weeks perfecting only works on one website?

Every trader who writes their own indicators runs into the same wall. You write a script in one platform’s language. It lives on that platform’s servers, draws only on that platform’s charts, and trades only with the brokers that platform chooses to support. Change the platform, and your work stays behind. Want to trade the same idea through your own broker? Rewrite it. Want to run it on your own server? Rewrite it again. Over the years, traders end up locked in, not because the platform is the best, but because leaving means starting from zero.

Now imagine the opposite. A scripting language that is open source, that you can run anywhere, and that anyone, a trader, a developer, a broker, a startup, can use to build their own charting engine with custom scripts. Your indicators and strategies belong to you, not to a website.

That is OpenScript. And it is not a prototype. It already powers the chart based trading section of OpenAlgo today.

OpenScript inside OpenAlgo’s chart based trading section: a custom HalfTrend written on the right, drawn on an AXISBANK 15 minute chart on the left.

What is OpenScript?

OpenScript is an open source custom scripting engine for trading. If you have used Pine Script on TradingView or AFL on Amibroker, the idea will feel familiar: you describe a calculation bar by bar, and the engine draws it, tests it or trades it for you.

There are two kinds of script:

  • A study is an indicator. It draws lines, bands and labels on your chart. It never places an order.
  • A strategy also decides when to buy and when to exit. You can backtest it, run it in sandbox mode, and trade it live.

The difference between the two starts with one word at the top of the script: study(...) or strategy(...).

Build your own indicators: HalfTrend as an example

HalfTrend is a popular trend indicator. It holds a flat level through noise and only turns when the other side of the recent range gives way. Blue while the trend is up, red while it is down, with a shaded channel and a Buy or Sell label on every flip.

Here is the complete HalfTrend indicator in OpenScript. Copy it, paste it into the Scripts panel on OpenAlgo’s Trading page (or the playground on openalgo.in/script), press Save, and it is on your chart:

// HalfTrend: a trend level that holds flat through noise and turns only when
// the other side of the range gives way. Blue while the trend is up, red while
// it is down, with a shaded channel and a label on every flip.
version 1

study("HalfTrend", overlay = true, precision = 2)

amplitude = input(2, "Amplitude", min = 1, max = 100)
channelDev = input(2, "Channel deviation", min = 0, max = 20)
atrLen = input(100, "ATR length", min = 1, max = 500)

half = atr(atrLen) / 2
dev = channelDev * half
rollHigh = highest(high, amplitude)
rollLow = lowest(low, amplitude)
meanHigh = sma(high, amplitude)
meanLow = sma(low, amplitude)
prevHigh = bar.isFirst ? high : high[1]
prevLow = bar.isFirst ? low : low[1]

// trend is 0 while up and 1 while down; armed is the flip being watched for.
var trend = 0
var armed = 0
var maxLow = low
var minHigh = high
var upLevel = low
var downLevel = high

wasTrend = bar.isFirst ? -1 : trend

if armed == 1
maxLow = max(orElse(rollLow, maxLow), maxLow)
if not isNone(meanHigh) and meanHigh < maxLow and close < prevLow
trend = 1
armed = 0
minHigh = orElse(rollHigh, high)
else
minHigh = min(orElse(rollHigh, minHigh), minHigh)
if not isNone(meanLow) and meanLow > minHigh and close > prevHigh
trend = 0
armed = 1
maxLow = orElse(rollLow, low)

flipUp = trend == 0 and wasTrend == 1
flipDown = trend == 1 and wasTrend == 0

// On a flip the new level starts where the other side ended, so it steps.
if trend == 0
upLevel = flipUp ? downLevel : wasTrend == -1 ? maxLow : max(maxLow, upLevel)
else
downLevel = flipDown ? upLevel : wasTrend == -1 ? minHigh : min(minHigh, downLevel)

ht = trend == 0 ? upLevel : downLevel

upLine = plot(trend == 0 ? ht : none, "Up trend", #2962ff, width = 2)
downLine = plot(trend == 1 ? ht : none, "Down trend", #ef5350, width = 2)
upEdge = plot(trend == 0 ? ht - dev : none, "Channel low", fade(#2962ff, 55), width = 1)
downEdge = plot(trend == 1 ? ht + dev : none, "Channel high", fade(#ef5350, 55), width = 1)
fill(upLine, upEdge, fade(#2962ff, 82))
fill(downLine, downEdge, fade(#ef5350, 82))

if flipUp
signal("Buy", #2962ff, at = "below", shape = "label")

if flipDown
signal("Sell", #ef5350, at = "above", shape = "label")

Even without knowing the language, most of it reads like plain English: take the inputs, calculate the ATR and the recent highs and lows, decide whether the trend has flipped, then draw the lines, the shaded channel and the Buy and Sell labels.

It tells you exactly what is wrong

When a community member first shared this script, it did not compile. That turned out to be useful.

A script with mistakes never runs. Each problem has a code, the exact line, and a plain explanation of the fix.

The first line started with a single slash (/ HalfTrend) instead of the two slashes that mark a comment (// HalfTrend). A tiny typo, but OpenScript caught it before anything reached the chart and reported exactly where it was:

  • OS1022: an expression was expected after /
  • OS2001: HalfTrend is not defined
  • OS1021: the version line must come first

All three come from that one missing slash. Add it, press Save, and the status bar changes to “Ready”. This is the most important habit OpenScript builds: a script with a mistake never runs. It does not quietly draw the wrong line or place a wrong order. It stops and tells you why.

Does the custom version match the real thing?

OpenAlgo’s chart already ships a built-in HalfTrend. So we applied both, the built-in one and the custom OpenScript one, on the same AXISBANK chart. The lines lie exactly on top of each other, the Buy and Sell labels appear on the same bars, and the values in the legend match. The custom script is a faithful copy of the indicator.

The built-in HalfTrend and the custom OpenScript HalfTrend on the same chart. They overlap exactly, which is how you know the script is right.

This is a good habit for any trader bringing an indicator from another platform: rebuild it, then check it against a version you trust before you rely on it.

Help while you write

You do not need to memorise anything. The OpenScript editor on openalgo.in/script checks your script as you type, and hovering over any function shows what it does and what it expects.

The OpenScript editor on openalgo.in/script. Hover over any function to see what it does. The full HalfTrend, 66 lines, checked with no problems in 9.5 ms.

Your first strategy: a simple EMA crossover

An indicator shows you what the market is doing. A strategy acts on it. The classic starting point is the moving average crossover: buy when a fast EMA crosses above a slow EMA, and exit when it crosses back below. Here is the complete long only version:

// EMA Crossover: go long when the fast EMA crosses above the slow EMA,
// and exit the long when it crosses back below. Long only, never short.
version 1

strategy("EMA Crossover, long only", overlay = true, precision = 2,
capital = 100000, qty = input(10, "Quantity", min = 1), qtyType = "units",
product = "intraday", fillOn = "nextOpen")

fastLen = input(9, "Fast EMA", min = 1, max = 200)
slowLen = input(21, "Slow EMA", min = 1, max = 500)

fast = ema(close, fastLen)
slow = ema(close, slowLen)

plot(fast, "Fast EMA", #2962ff, width = 2)
plot(slow, "Slow EMA", #ff9800, width = 2)

// Long entry: fast EMA crosses above slow EMA while we have no position.
if crossUp(fast, slow) and pos.isFlat
buy()

// Long exit: fast EMA crosses below slow EMA while we are long.
if crossDown(fast, slow) and pos.isLong
close()

Read it like a sentence:

  • The first line says this is a strategy, not a study, and sets how to trade it the way a trader thinks: starting capital, quantity, product type (intraday), and fill at the next bar's open.
  • The inputs are the 9 and 21 period EMAs. Change them from the settings without touching the code.
  • The two plots draw both EMAs on your chart, so you can see every crossover.
  • Long entry: if the fast EMA crosses above the slow EMA and you have no position, buy().
  • Long exit: if the fast EMA crosses below the slow EMA and you are long, close().

The checks pos.isFlat and pos.isLong make sure it never buys twice or sells what it does not hold. That is the whole strategy: about twenty lines, most of them comments and settings.

Backtesting in your browser

Press the play button next to a strategy and OpenAlgo runs it over the bars on your chart and opens a full report: net profit, win rate, drawdown, every trade with its entry and exit, and every fill marked on the chart. It runs entirely in your browser, on thousands of bars in a fraction of a second, and nothing is sent to your broker. You can try different EMA lengths, a different timeframe or a different exit, and test again in seconds, with no money at risk.

Execution: sandbox first, then live

When a strategy is ready, you deploy it from the Strategies panel. A deployed strategy no longer runs in your browser. It runs on your OpenAlgo server, bar by bar, and places its orders through the same order path as every other OpenAlgo order.

The Strategies panel, where a saved strategy is deployed to run on your OpenAlgo server, in sandbox mode or live.
  • In analyzer mode (sandbox mode), those orders go to OpenAlgo’s sandbox with virtual funds. You can watch your strategy trade live market data without risking a rupee.
  • In live mode, the same orders go to your broker.

The strategy does not change between the two. You flip the mode, not the code. The thing you tested is the thing you trade.

How it works, in plain language

You do not need to know any of this to use OpenScript, but it explains why you can trust it.

What happens when you press Save: your script is read, checked for mistakes, and sealed into one recipe that the chart, the backtest and the live strategy all share.

When you press Save, OpenScript does three things in your browser, in about 10 milliseconds:

  1. It reads your script, word by word.
  2. It checks it for mistakes: a typo, a name that does not exist, a setting that is out of range. If it finds any, it stops and shows you the line and the fix.
  3. It seals it into a recipe. The result is not a program that can do anything it likes. It is a fixed list of calculations, stored as data, with a fingerprint of your original script. It cannot open files, reach the internet, or run anything that is not an OpenScript calculation.

That sealed recipe is then run by two engines that follow the same rules: one in the browser (for the chart and the backtest) and one on the server (for the live strategy). Because both engines run the same recipe, what you see on the chart, what you backtest, and what you trade are the same calculation. They cannot quietly drift apart.

A few details that matter to traders:

  • No fake values at the start. A 21 period EMA has no value until enough bars exist. OpenScript leaves it empty rather than pretending it is zero, so early signals are not invented.
  • Clear, numbered errors. Every problem has a code (like OS2001) and a suggested fix, so you can search for it or ask for help.
  • A large library. Moving averages, ATR, RSI, highest and lowest, crossovers and hundreds more are built in, with the list growing each release.

Build your own charting engine

This is where OpenScript is different from every closed trading language. It is not a feature locked inside one product. It is an engine you can take and build on.

  • The engines are published packages. JavaScript on npm (openalgo-script) for charts and browsers, and Python on PyPI (openscript) for servers, research notebooks and automation.
  • The language has a published specification, so the rules are written down, not hidden inside one product.
  • A conformance test suite checks that every engine produces the same numbers on the same tests. That is how OpenAlgo’s browser engine and server engine stay in agreement, and how anyone else can build a compatible one.

OpenAlgo’s own chart based trading section is the proof: the charts, the custom indicators, the in-browser backtest and the deployed strategies you saw above are all built on these same public engines. A trader or developer can use the same pieces to add custom scripting to their own charting app, dashboard or trading tool.

Built for commercial use: businesses, brokers and web portals

OpenScript is released under the Apache 2.0 licence, which is designed to allow commercial use. That opens the door well beyond individual traders:

  • Brokers can offer custom indicators and strategies on their own trading terminals and charts, without licensing a closed scripting language from someone else.
  • Web portals and fintech startups can add a scripting layer to their charting, screening or strategy products, and let their users write their own logic.
  • Businesses and trading desks can standardise on one language for research, backtesting and execution, and keep full control of where their scripts run.

And because every compatible engine follows the same specification, a script written on one platform can run on another. For traders, that means no more lock-in. For businesses, it means building on a shared standard instead of reinventing one.

Getting started

  1. Try it without installing anything. Open openalgo.in/script and paste the HalfTrend script above into the playground.
  2. Use it in OpenAlgo. Update OpenAlgo, open the Trading page, and open the Scripts panel. Paste a script, press Save, and press play to put it on your chart.
  3. Try the EMA crossover strategy. Paste it in, press play, and read the backtest report. Change the EMA lengths and test again.
  4. Trade it in sandbox mode first. Deploy from the Strategies panel with analyzer mode on, and go live once you are comfortable with how it behaves.
  5. Building a product? Start with the specification and the npm and PyPI engines.

Learn more: