OPEN-SOURCE SCRIPT

Grid + Trade Annotations & Liquidations

161
## Introducing the “Grid + Trade Annotations & Liquidations” Pine Script Strategy

Imagine you could overlay a perfectly-spaced price grid on your favorite chart, backtest a simple moving-average crossover, see exactly where trades would have fired off in the past—and even know at what price you’d have been liquidated if you were running at 10× leverage. That’s exactly what this all-in-one TradingView **Pine Script® v6** strategy delivers.

### Why you’ll love it

* **Visual clarity:** A fixed-interval horizontal grid, centered on each bar’s close, helps you instantly spot round-number levels (e.g. every \$0.50).
* **Trade annotations:** Every historical entry/exit is automatically marked with arrows and labels—no more scrolling through Trade History.
* **Liquidation lines:** For each entry, the script computes your theoretical liquidation price, based on your chosen leverage, and draws it as a dashed line.
* **Performance metrics:** Total return, maximum drawdown, Sharpe ratio, and win rate are calculated and displayed on-chart, so you don’t have to wrestle with spreadsheets.

---

## How it’s structured

The code lives in a single **strategy**—add it via **Pine Editor → New Strategy** and click **Add to Chart**. Internally, it’s broken into four main sections:

1. **Grid setup:**

* **Inputs:** `gridStep`, `aboveLines`, `belowLines`, `gridColor`, `gridStyle`, `gridWidth`.
* **Persistent array:** stores `line` objects so they survive bar updates.
* **Draw/update logic:** on each confirmed historical bar, the script either recreates all lines (when you change the count) or simply repositions them around the new close.

2. **Entry/exit logic & annotations:**

* **Example system:** 20-period vs. 50-period simple moving-average crossover.
* **Labels & shapes:**

* Green triangles for long entries/exits, red for short.
* A “Long Liq:” or “Short Liq:” label at the point of entry.

3. **Liquidation calculations:**

* **Formula:**

* Long: `P_liq = P_entry × (1 − 1⁄L)`
* Short: `P_liq = P_entry × (1 + 1⁄L)`
* Let the script draw a dashed red (for longs) or dashed green (for shorts) line at each `P_liq`.

4. **Performance metrics:**

* **Built-ins:**

* `strategy.netprofit_percent` → total return %
* `strategy.max_drawdown_percent` → max drawdown %
* `strategy.wintrades` / `strategy.closedtrades` → win rate %
* **Sharpe ratio:** manually computed from per-bar returns, assuming a user-defined risk-free rate and bars-per-year count.

---

## Using & customizing the strategy

1. **Add to your chart.**

* Copy the full script into Pine Editor, select **Strategy**, and hit **Add to Chart**.
2. **Tune your grid.**

* **`Grid Interval ($)`**: e.g. `0.50` for \$0.50 steps.
* **`Lines Above`/`Below`**: how many lines to show on each side of the current price.
* **`Grid Style`**: choose Solid, Dashed, or Dotted; set line width and opacity via the color picker.
3. **Adjust your trading logic.**

* Out of the box, the script uses SMA(20) vs. SMA(50). Swap in any `ta.*` indicator calls you like.
4. **Set leverage & capital.**

* **`Leverage`**: affects the liquidation price.
* **`Initial Capital`** and **`Order Size`**: the strategy uses 100% of equity per trade by default—you can change that in the `strategy()` call.
5. **Review performance.**

* Metrics show up in the Strategy Tester and on-chart label.
* If you want data in the Data Window, expand the script’s name to see the hidden plots for return, drawdown, Sharpe, and win rate.

---

## Behind the code

Below is a high-level walkthrough of the key snippets:

```pinescript
//version=6
strategy("Grid + Annotations & Liquidations", overlay=true,
initial_capital=100000, default_qty_type=strategy.percent_of_equity,
default_qty_value=100)

// ─ Grid inputs & style mapping ────────────────────────────────────────
gridStep = input.float(0.50, "Grid Interval ($)", minval=0)
aboveLines = input.int(5, "Lines Above", minval=0)
belowLines = input.int(5, "Lines Below", minval=0)
gridColor = input.color(color.new(color.gray, 80), "Grid Color")
gridStyle = input.string("Dashed", "Grid Style", options=["Solid","Dashed","Dotted"])
gridWidth = input.int(1, "Grid Line Width", minval=1, maxval=5)
gridStyleConst = gridStyle == "Solid" ? line.style_solid :
gridStyle == "Dotted"? line.style_dotted :
line.style_dashed
```

* We map a simple string choice into Pine’s `line.style_*` constants.
* `gridStep` drives the spacing in dollars.

```pinescript
// Persist & update lines only when needed
var line[] gridLines = array.new_line()
if barstate.islastconfirmedhistory
total = aboveLines + belowLines + 1
if array.size(gridLines) != total
// delete & recreate

else
// only reposition

```

* Wrapping all drawing in `barstate.islastconfirmedhistory` avoids repaint issues.
* The script deletes and rebuilds lines only when you change `aboveLines`/`belowLines`, otherwise it simply moves them.

```pinescript
// MA crossover logic & liquidation labels
fast = ta.sma(close, 20)
slow = ta.sma(close, 50)
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
liq = close * (1 - 1.0 / leverage)
label.new(bar_index, low, text="Long\nLiq: " + str.tostring(liq))
line.new(…, y1=liq, y2=liq, color=color.red, style=line.style_dashed)
```

* Entries trigger both the `strategy.entry` call and a pair of visual cues: a label and a dashed line at the computed liquidation price.

```pinescript
// Performance metrics: draw from built-ins + manual Sharpe
totalRet = strategy.netprofit_percent
maxDD = strategy.max_drawdown_percent
winRate = strategy.closedtrades > 0 ?
(strategy.wintrades / strategy.closedtrades)*100 : 0

// Manual Sharpe calculation
… accumulate per-bar % returns … compute mean, stddev … apply formula …
```

* TradingView gives us return, drawdown, and trade counts out of the box.
* We calculate Sharpe ourselves so you can adjust the risk-free rate and periods per year.

---

## Wrapping up

This one-file strategy is designed to be both **educational** and **practical**:

* **Learn by reading:** every section is commented so you can see how Pine v6 handles arrays, loops, strategy functions, and labels.
* **Customize for your edge:** swap in your own indicators, change leverage, or hook up alerts.
* **Publish & share:** drop it into your public repo with this story as your README, and fellow traders will know exactly how to use it.

Feel free to fork, file issues, or submit pull requests. Happy charting—and may your grid lines always align!

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.