# Deskr Script

> Write your own indicators and alerts for the Deskr terminal in plain JavaScript, with perp data (OI, funding, taker flow) and Deskr's live levels.

Deskr Script lets you build your own indicators on the terminal at [/app/terminal](https://deskr.trade/app/terminal): plot lines and histograms, mark signals, draw levels, test a strategy and get alerts. It's plain JavaScript run once over all bars, with the same maths as the built-in indicators.

## Your first indicator

1. Open the terminal and click **{ }** (*Deskr Script editor*) in the top bar, or press **/** and pick **New indicator from template**.
2. Choose a template (*Price overlay*, *Oscillator in a pane*, *Perp positioning*, *Signals + strategy*, *Levels from live data* or *Blank*).
3. Edit it. The editor highlights syntax, suggests the API as you type (Ctrl+Space; type `ta.` for the library) and shows docs when you hover a name. Syntax errors are underlined as you type; a run-time error is shown on its line.
4. **Run** (Ctrl+Enter). The output appears on the chart.
5. Name it and click **Add to chart**. It's saved to **My indicators** (on your account when signed in, in this browser otherwise) and drawn on every chart like a built-in.

```js
// Oscillator in its own pane, with guides and an alert
const len = input("Length", 14, { min: 2, max: 100 });
const r = ta.rsi(close, len);
plot(r, { title: "RSI " + len, pane: "osc", color: "#b48cff" });
hline(30, { pane: "osc" }); hline(70, { pane: "osc" });
alertcondition(ta.crossover(r, 30), "Back above 30");
```

## My indicators

- Press **/** — your indicators are listed under *My indicators* below the built-ins, searchable by name.
- Click one to open its **inputs dialog** (every `input()` it declares), then **Add to chart** or **Apply**. Inputs are kept per indicator.
- In the chart legend, a *Script* chip shows each one; click it for inputs, × to remove. **Edit source** opens it in the editor.
- Up to 6 of your indicators can be on the charts at once; each runs on each chart's own coin and timeframe.

## Alerts from a script

Add `alertcondition(cond, "title")` — `cond` is a series of booleans (true on the bars where it fires) or one boolean for the last bar. After **Run**, the *Alert conditions* list in the Output tab shows each one; click **Alert me · once** or **every time**. Deskr checks it on every closed bar of that coin and timeframe and notifies you in the app (bell + Rules & alerts). Free: 2 script alerts, Pro: 20.

The live snapshot (`zones`, `levels`, `walls`, `liqs`, `options`) is `null` when alerts are evaluated, as in the Strategy Tester — there is no history of it, so alerts can't depend on it.

## Sharing

Click **Share** to create a read-only link (`deskr.trade/script/…`) with the source. Anyone with the link can read it and open it in their terminal to keep a copy. Sharing is opt-in per script; your name is shown only if you tick *Show my name*. A public library with ranking comes later.

## Safety and limits

- In your browser, scripts run in a sandboxed iframe with no network and no access to the page, in a fresh worker per run, stopped after 3 s.
- Script alerts run on Deskr's server in a separate worker process — never in the web app or the data engine — with Node's permission model on (no file writes, no child processes), an empty environment, a fresh JavaScript context per run with no host objects, a 1 s run limit, a 64 MB heap and a hard kill after 3 s.
- Scripts are capped at 20,000 characters; up to 20 plots, 20 guides, 200 levels, 500 markers and 10 alert conditions per run.

## Reference

<!-- api:start -->
### Series

| Name | What it is |
|---|---|
| `time` | Bar open times, unix seconds, oldest first. |
| `open` | Open prices. |
| `high` | High prices. |
| `low` | Low prices. |
| `close` | Close prices. |
| `volume` | Volume in coins (Binance USDT-M perp). |
| `buyVol` | Taker buy volume in coins (NaN where unknown). volume − buyVol is taker sell volume. |

### Perp

| Name | What it is |
|---|---|
| `oi` | Open interest in USD aligned to bars (NaN where no reading). null when the coin has no OI history. |
| `funding` | Realised funding as an annualised fraction (0.10 = 10% APR), aligned to bars. null when unavailable. |

### Values

| Name | What it is |
|---|---|
| `n` | Number of bars. |
| `sym` | Coin symbol, e.g. "BTC". |
| `tf` | Timeframe, e.g. "1h". |
| `barSec` | Seconds per bar. |

### Live snapshot

| Name | What it is |
|---|---|
| `zones` | Today's Deskr zones [{lo, hi, kind: "p50"\|"p80"}]. Live snapshot: null in the Strategy Tester and in alerts. |
| `levels` | All key levels on the chart [{p, label, src, usd?}]. Live snapshot. |
| `walls` | Order-book walls [{p, label, usd}]. Live snapshot. |
| `liqs` | Liquidation levels (est) [{p, label, usd}]. Live snapshot. |
| `options` | Options levels (max pain, big OI strikes) [{p, label}]. Live snapshot. |

### Inputs

| Name | What it is |
|---|---|
| `input(name, default, {min, max, step})` | Declares a number input shown in the inputs dialog; returns its current value. |

### Outputs

| Name | What it is |
|---|---|
| `plot(series, {title, color, pane, style, width})` | Draws a series. pane: "price" (default) or any name for a lower pane. style: line \| hist \| dots. |
| `hline(value, {title, color, pane})` | Horizontal guide line in a pane (or a price level). |
| `level(price, label, {color})` | Labelled price level; joins the Levels panel and the magnet. |
| `marker(i, "up"\|"down", text, {color})` | Arrow on bar i with a short text. |

### Alerts

| Name | What it is |
|---|---|
| `alertcondition(cond, title)` | Makes the indicator alertable: cond is a series of booleans (or one boolean for the last bar). An alert fires when it is true on the last closed bar. |

### Strategy

| Name | What it is |
|---|---|
| `strategy` | Orders for the Strategy Tester: strategy.long(i, opts), strategy.short(i, opts), strategy.close(i). |

### ta

| Name | What it is |
|---|---|
| `ta` | Technical analysis library; same maths as the chart's built-in indicators. |

### Patterns

| Name | What it is |
|---|---|
| `patterns` | Confirmed possible patterns: patterns.find({ kind, cat, dir, minQ }), patterns.at(i), patterns.all. cat is chart \| harmonic \| candle \| smc \| perp; kind is one id or a list. Each result has .at (the bar whose close confirmed it), .dir, .q, .target, .stop, .name. Outcome fields are omitted so a script cannot peek. |

### Helpers

| Name | What it is |
|---|---|
| `na(x)` | True when x is not a finite number. |
| `nz(x, d = 0)` | x, or d when x is NaN. |
| `last(series)` | Last value of a series. |

### strategy.*

| Name | What it is |
|---|---|
| `strategy.long(i, {stop, target, sl, tp, size})` | Go long at the next bar's open. sl/tp in %, stop/target as prices, size 0.01–1 of equity. |
| `strategy.short(i, {stop, target, sl, tp, size})` | Go short at the next bar's open. |
| `strategy.close(i)` | Close the open position at the next bar's open. |

### ta.*

| Function | Returns |
|---|---|
| `ta.sma(x, len)` | Simple moving average. |
| `ta.ema(x, len)` | Exponential moving average (SMA-seeded). |
| `ta.rma(x, len)` | Wilder's moving average. |
| `ta.wma(x, len)` | Weighted moving average. |
| `ta.hma(x, len)` | Hull moving average. |
| `ta.vwma(x, v, len)` | Volume-weighted moving average. |
| `ta.stdev(x, len)` | Rolling standard deviation. |
| `ta.highest(x, len)` | Rolling maximum. |
| `ta.lowest(x, len)` | Rolling minimum. |
| `ta.change(x, len = 1)` | x − x[len bars ago]. |
| `ta.roc(x, len)` | Rate of change, %. |
| `ta.mom(x, len)` | Momentum (same as change). |
| `ta.crossover(a, b, i?)` | a crosses above b on bar i (or a boolean series when i is omitted). a/b can be numbers. |
| `ta.crossunder(a, b, i?)` | a crosses below b. |
| `ta.cross(a, b, i?)` | Either direction. |
| `ta.rsi(x, len = 14)` | Relative strength index. |
| `ta.macd(x, fast, slow, sig)` | {line, signal, hist}. |
| `ta.atr(h, l, c, len = 14)` | Average true range. |
| `ta.tr(h, l, c)` | True range. |
| `ta.stoch(h, l, c, len, k, d)` | Stochastic {k, d}. |
| `ta.stochrsi(x, len, stLen, k, d)` | Stochastic RSI {k, d}. |
| `ta.bb(x, len = 20, mult = 2)` | Bollinger {mid, upper, lower}. |
| `ta.cci(h, l, c, len)` | Commodity channel index. |
| `ta.willr(h, l, c, len)` | Williams %R (−100…0). |
| `ta.mfi(h, l, c, v, len)` | Money flow index. |
| `ta.adx(h, l, c, len)` | {adx, plus, minus} directional movement. |
| `ta.supertrend(h, l, c, len, mult)` | {line, dir}: dir 1 up, −1 down. |
| `ta.ichimoku(h, l, conv, base, span)` | {conv, base, a, b, shift}; plot a/b shifted forward by shift bars. |
| `ta.donchian(h, l, len)` | {upper, lower, mid}. |
| `ta.keltner(h, l, c, len, mult, atrLen)` | {mid, upper, lower}. |
| `ta.zscore(x, len)` | (x − mean) / stdev. |
| `ta.percentrank(x, len)` | Share of the last len values ≤ x, %. |
| `ta.pivots(h, l, left, right)` | {hi, lo}: confirmed pivot values on the confirming bar (no lookahead). |
| `ta.cvd(volume, buyVol)` | Cumulative taker delta. |
| `ta.obv(c, v)` | On-balance volume. |
| `ta.vwap(h, l, c, v, time, resetSec = 86400)` | Session VWAP reset every resetSec. |
| `ta.avwap(h, l, c, v, from)` | Anchored VWAP from bar index from. |

### Templates

- **Price overlay** — A line on the price chart with one input.
- **Oscillator in a pane** — A value in its own pane with guide lines and an alert.
- **Perp positioning** — Open interest change and funding: the perp data most charts don't have.
- **Signals + strategy** — Arrows on a condition, an alert, and orders for the Strategy Tester.
- **Levels from live data** — Uses the live Deskr snapshot: biggest book wall and liquidation level.
- **Blank** — An empty script with the API in comments.
<!-- api:end -->

## Strategy Tester

`strategy.long(i, {sl, tp})`, `strategy.short(i, …)` and `strategy.close(i)` place orders that the **Test strategy** tab simulates honestly: signals are found by re-running the script on every bar as it closed, fills are at the next bar's open, with taker fees, funding, stops before targets and liquidation. A repaint check reports signals that change once later bars arrive.
