PINE LIBRARY
Cập nhật

ema_stoploss

33
Library "ema_stoploss"

What it does
A small library that builds stop-loss levels from dynamically computed EMAs. It finds EMAs strictly on the desired side of price (long: below; short: above), sorts them by distance to price, and returns the n-th nearest as your stop.

How it works

sortEMAsByDistanceStrictDyn(signal, lensArr, src, ascending)

Computes each EMA internally with the alpha formula (alpha = 2/(len+1)), so you can pass a dynamic array of lengths.

Strict side filter:

signal = 1 → only EMAs < src (below)

signal = -1 → only EMAs > src (above)

Sorts candidates by distance to src (default: nearest → farthest) and returns two arrays: EMA values and their lengths.

get_stop_loss(index) (exported)

Builds a default length array: 21, 50, 100, 200, 250, 500, 750, 1000.

Long side uses low to find the index-th nearest lower EMA.
Short side uses high to find the index-th nearest upper EMA.

Returns [sl_buy, sl_sell].

Plots

Stop-Loss Long (green): the selected lower EMA (based on low).

Stop-Loss Short (red): the selected upper EMA (based on high).

Input

Index (default 2): 0-based.
0 = nearest, 1 = second nearest, 2 = third, etc.
If there aren’t enough EMAs on the required side, the function returns na (no plot).

Why internal EMA calc?
ta.ema() doesn’t accept a series length; by updating each EMA with its alpha step every bar, the library supports arbitrary dynamic length arrays and stays bar-consistent.

Customize

Edit the list in get_stop_loss() to use your own EMA lengths.

Change ascending in sortEMAsByDistanceStrictDyn if you prefer farthest → nearest.

Use a different src if needed (e.g., close, hlc3, etc.).
The example intentionally uses low for long stops and high for short stops.

Notes

Strict side filtering: EMAs on the wrong side are ignored (no fallback).

If no EMA qualifies on a side, you’ll get na for that side.

Complexity is O(n²) for sorting, which is negligible for small EMA lists.
Phát hành các Ghi chú
v2

fix na

Thông báo miễn trừ trách nhiệm

Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.