### New Bar Detection Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/time.md Example showing how to use the time() function to detect the start of a new bar for a given timeframe. ```APIDOC //@version=6 indicator("New Bar Detection", overlay=true) // Function to detect the start of a new bar for a given resolution newbar(res) => ta.change(time(res)) == 0 ? 0 : 1 // Plot 1.0 at the start of every 10-minute bar on a 1-minute chart plot(newbar("10")) ``` -------------------------------- ### Example of strategy.opentrades.entry_bar_index() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.opentrades.entry_bar_index.md This example demonstrates how to use `strategy.opentrades.entry_bar_index()` to calculate the number of bars since the last entry and close a position after 10 bars. ```javascript //Wait10barsandthenclosetheposition. //@version=6 strategy("`strategy.opentrades.entry_bar_index`Example") barsSinceLastEntry() => strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na //Enteralongpositioniftherearenoopenpositions. ifstrategy.opentrades==0 strategy.entry("Long",strategy.long) //Closethelongpositionafter10bars. ifbarsSinceLastEntry()>=10 strategy.close("Long") ``` -------------------------------- ### strategy.entry() - Market Order Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.entry.md This example demonstrates how to use strategy.entry() to place market orders for long and short positions based on moving average crossovers. ```APIDOC ## strategy.entry() ### Description Places a market order to enter a long or short position. ### Parameters - **id** (string) - Required. A unique identifier for the order. - **direction** (strategy.direction) - Required. The direction of the order (strategy.long or strategy.short). - **comment** (series string) - Optional. Additional notes on the filled order. If not an empty string, this text is shown for the order instead of the specified `id`. - **alert_message** (series string) - Optional. Custom text for the alert that fires when an order fills. If the "Message" field of the "Create Alert" dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message replaces the placeholder with this text. - **disable_alert** (series bool) - Optional. If true when the command creates an order, the strategy does not trigger an alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger alerts when they execute. ### Request Example ```pinescript //@version=6 strategy("Market Order strategy", overlay = true) float sma14 = ta.sma(close, 14) float sma28 = ta.sma(close, 28) if ta.crossover(sma14, sma28) strategy.entry("My Long Entry ID", strategy.long) if ta.crossunder(sma14, sma28) strategy.entry("My Short Entry ID", strategy.short) ``` ``` -------------------------------- ### Session Specification Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/time.md Example demonstrating how to use the time() function with a specific session and timezone to highlight trading hours. ```APIDOC //@version=6 indicator("Time Example", overlay=true) // This example highlights bars within a specific session (10:00-11:00 and 14:00-15:00 on weekdays) t1 = time(timeframe.period, "1000-1100,1400-1500:23456") // Plot a background color when the time is within the specified session bgcolor(not na(t1) ? color.new(color.blue, 90) : na) ``` -------------------------------- ### strategy.entry() - Limit Order Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.entry.md This example shows how to use strategy.entry() to place limit orders, including setting a specific limit price and visualizing the limit level on the chart. ```APIDOC ## strategy.entry() ### Description Places a limit order to enter a long or short position at a specified price level. ### Parameters - **id** (string) - Required. A unique identifier for the order. - **direction** (strategy.direction) - Required. The direction of the order (strategy.long or strategy.short). - **limit** (float) - Optional. The price level at which to fill the limit order. - **comment** (series string) - Optional. Additional notes on the filled order. If not an empty string, this text is shown for the order instead of the specified `id`. - **alert_message** (series string) - Optional. Custom text for the alert that fires when an order fills. If the "Message" field of the "Create Alert" dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message replaces the placeholder with this text. - **disable_alert** (series bool) - Optional. If true when the command creates an order, the strategy does not trigger an alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger alerts when they execute. ### Request Example ```pinescript //@version=6 strategy("Limit order strategy", overlay=true, margin_long=100, margin_short=100) float limitOffsetInput = input.int(100, "Limit offset, in ticks", 1) * syminfo.mintick float sma14 = ta.sma(close, 14) float sma28 = ta.sma(close, 28) if ta.crossover(sma14, sma28) strategy.cancel("My Short Entry ID") float limitLevel = close - limitOffsetInput strategy.entry("My Long Entry ID", strategy.long, limit = limitLevel) if ta.crossunder(sma14, sma28) strategy.cancel("My Long Entry ID") float limitLevel = close + limitOffsetInput strategy.entry("My Short Entry ID", strategy.short, limit = limitLevel) ``` ``` -------------------------------- ### Install lightweight-charts-indicators Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/README.md Install the necessary packages for lightweight-charts-indicators, oakscriptjs, and lightweight-charts using npm. ```bash npm install lightweight-charts-indicators oakscriptjs lightweight-charts ``` -------------------------------- ### Cancel All Orders Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.cancel_all.md This example demonstrates how to use strategy.cancel_all() to cancel all pending limit orders. It enters two long positions with limit orders and then cancels them if a specific condition is met. ```pine //@version=6 strategy(title = "Cancel all orders demo") conditionForBuy1 = open > high[1] if conditionForBuy1 strategy.entry("Long entry 1", strategy.long, 1, limit = low) // Enter long using a limit order if `conditionForBuy1` is `true`. conditionForBuy2 = conditionForBuy1 and open[1] > high[2] float lowest2 = ta.lowest(low, 2) if conditionForBuy2 strategy.entry("Long entry 2", strategy.long, 1, limit = lowest2) // Enter long using a limit order if `conditionForBuy2` is `true`. conditionForStopTrading = open < lowest2 if conditionForStopTrading strategy.cancel_all() // Cancel both limit orders if `conditionForStopTrading` is `true`. ``` -------------------------------- ### Basic `for` loop Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/keywords/for.md This example demonstrates a basic `for` loop to count bars where the close price is above the current close price. It iterates from 1 up to a specified length. ```pine //@version=6 indicator("Basic `for` loop") //@function Calculates the number of bars in the last `length` bars that have their `close` above the current `close`.  //@param length The number of bars used in the calculation.  greaterCloseCount(length) =>     int result = 0     for i = 1 to length        if close[i] > close           result += 1     result plot(greaterCloseCount(14)) ``` -------------------------------- ### array.slice() Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/array.slice.md This example demonstrates how to create an array, populate it, and then extract a slice. Note that modifications to the slice will also alter the original array. ```javascript //@version=6 indicator("array.slice example") a = array.new_float(0) for i = 0 to 9     array.push(a, close[i]) // take elements from 0 to 4 // * note that changes in slice also modify original array slice = array.slice(a, 0, 5) plot(array.sum(a) / 10) plot(array.sum(slice) / 5) ``` -------------------------------- ### strategy.exit() Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.exit.md This example demonstrates how to use strategy.exit() to place a trailing stop order. It defines an exit order with a specific ID, links it to an entry ID, and sets trailing stop parameters. ```APIDOC ## strategy.exit() ### Description Places exit orders for trades. A single call can generate exit orders for several entries in an open position. ### Method `strategy.exit(id, from_entry, qty, profit, loss, limit, stop, trail_points, trail_offset, trail_price, oca_name, comment, alert_message, when)` ### Parameters - **id** (string) - Optional. ID of the exit order. - **from_entry** (string) - Optional. ID of the entry to exit from. If not specified, exits all open trades. - **qty** (float) - Optional. Quantity of the position to exit. - **profit** (float) - Optional. Target profit in ticks. - **loss** (float) - Optional. Stop-loss in ticks. - **limit** (float) - Optional. Limit price. - **stop** (float) - Optional. Stop price. - **trail_points** (float) - Optional. Trailing stop in ticks. - **trail_offset** (float) - Optional. Trailing stop offset in ticks. - **trail_price** (float) - Optional. Trailing stop activation price. - **oca_name** (string) - Optional. OCA group name. - **comment** (string) - Optional. Comment for the order. - **alert_message** (string) - Optional. Alert message. - **when** (bool) - Optional. Condition to execute the exit order. ### Request Example ```pinescript strategy.exit("My Long Exit ID", "My Long Entry ID", trail_price = activationPrice, trail_offset = trailDistanceInput, oca_name = "Exit") ``` ### Remarks - If `from_entry` is not specified, exit orders are created for all open trades until the position closes. - When `close_entries_rule` is "FIFO" (default), orders exit from the position starting with the first open trade, even if `from_entry` specifies different open trades. - If both stop-loss and trailing stop arguments are included, only the order that fills first is placed. ``` -------------------------------- ### Get X1 Coordinate of a Line Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/line.get_x1.md This example demonstrates how to create a line and then retrieve the x-coordinate of its starting point using line.get_x1(). The retrieved value is then used in a plot calculation. ```javascript //@version=6 indicator("line.get_x1") my_line = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time) a = line.get_x1(my_line) plot(time - line.get_x1(my_line)) //draws zero plot ``` -------------------------------- ### Example Usage of matrix.kron() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.kron.md Demonstrates how to create matrices, calculate their Kronecker product using `matrix.kron()`, and display the results in a table. ```APIDOC ``` //@version=6 indicator("`matrix.kron()` Example") // Display using a table. if barstate.islastconfirmedhistory     // Create two matrices with default values `1` and `2`.     var m1 = matrix.new(2, 2, 1)     var m2 = matrix.new(2, 2, 2)     // Calculate the Kronecker product of the matrices.     var m3 = matrix.kron(m1, m2)     // Display matrix elements.     var t = table.new(position.top_right, 5, 2, color.green)     table.cell(t, 0, 0, "Matrix 1:")     table.cell(t, 0, 1, str.tostring(m1))     table.cell(t, 1, 1, "⊗")     table.cell(t, 2, 0, "Matrix 2:")     table.cell(t, 2, 1, str.tostring(m2))     table.cell(t, 3, 1, "=")     table.cell(t, 4, 0, "Kronecker product:")     table.cell(t, 4, 1, str.tostring(m3)) ``` ``` -------------------------------- ### Get Open Trade Entry Comment Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.opentrades.entry_comment.md This example demonstrates how to retrieve and display the comment of the last open trade's entry. It uses `strategy.opentrades.entry_comment()` to get the comment and `strategy.opentrades - 1` to reference the most recent trade. ```pine //@version=6 strategy("`strategy.opentrades.entry_comment()` Example", overlay = true) stopPrice = open * 1.01 longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (longCondition)     strategy.entry("Long", strategy.long, stop = stopPrice, comment = str.tostring(stopPrice, "#.####")) var testTable = table.new(position.top_right, 1, 3, color.orange, border_width = 1) if barstate.islastconfirmedhistory or barstate.isrealtime     table.cell(testTable, 0, 0, 'Last entry stats')     table.cell(testTable, 0, 1, "Order stop price value: " + strategy.opentrades.entry_comment(strategy.opentrades - 1))     table.cell(testTable, 0, 2, "Actual Entry Price: " + str.tostring(strategy.opentrades.entry_price(strategy.opentrades - 1))) ``` -------------------------------- ### Place Market Orders with strategy.order() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.order.md This example demonstrates placing market orders for entering and exiting long positions based on moving average crossovers. It shows how to specify order IDs and trade directions. ```javascript //@version=6 strategy("Market order strategy", overlay = true) // Calculate a 14-bar and 28-bar moving average of `close` prices. float sma14 = ta.sma(close, 14) float sma28 = ta.sma(close, 28) // Place a market order to enter a long position when `sma14` crosses over `sma28`. if ta.crossover(sma14, sma28) and strategy.position_size == 0     strategy.order("My Long Entry ID", strategy.long) // Place a market order to sell the same quantity as the long trade when `sma14` crosses under `sma28`, effectively closing the long position. if ta.crossunder(sma14, sma28) and strategy.position_size > 0     strategy.order("My Long Exit ID", strategy.short) ``` -------------------------------- ### Drawing Primitive: Line Source: https://context7.com/deepentropy/lightweight-charts-indicators/llms.txt Example of `LineDrawingData` for PineScript's `line.new()`. Define start and end points, color, width, style, and extension. ```typescript // Horizontal line segment (line.new in PineScript) const line: LineDrawingData = { time1: 1609459200, price1: 29600, time2: 1609632000, price2: 29600, color: '#2157f3', width: 1, style: 'dashed', // 'solid' | 'dashed' | 'dotted' extend: 'left', // 'none' | 'left' | 'right' | 'both' }; ``` -------------------------------- ### Example Usage Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/input.bool.md Demonstrates how to use the input.bool() function to create a boolean input that controls whether to plot the open price. ```APIDOC ## Example ```pinescript //@version=6 indicator("input.bool", overlay=true) i_switch = input.bool(true, "On/Off") plot(i_switch ? open : na) ``` ``` -------------------------------- ### Extracting a Matrix Row into an Array Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.row.md Use this function to get all values from a specific row of a matrix and store them in an array. Row indexing starts at 0. ```pine //@version=6 indicator("`matrix.row()` Example", "", true) // Create a 2x3 "float" matrix from `hlc3` values. m = matrix.new(2, 3, hlc3) // Return an array with the values of the first row of the matrix. a = matrix.row(m, 0) // Plot the first value from the array `a`. plot(array.get(a, 0)) ``` -------------------------------- ### Example Usage Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.eigenvectors.md Demonstrates how to create a matrix and compute its eigenvectors using `matrix.eigenvectors()`. ```APIDOC ``` //@version=6 indicator("`matrix.eigenvectors()` Example") // For efficiency, execute this code only once. if barstate.islastconfirmedhistory // Create a 2x2 matrix var m1 = matrix.new(2, 2, 1) // Fill the matrix with values. matrix.set(m1, 0, 0, 2) matrix.set(m1, 0, 1, 4) matrix.set(m1, 1, 0, 6) matrix.set(m1, 1, 1, 8) // Get the eigenvectors of the matrix. m2 = matrix.eigenvectors(m1) // Display matrix elements. var t = table.new(position.top_right, 2, 2, color.green) table.cell(t, 0, 0, "Matrix Elements:") table.cell(t, 0, 1, str.tostring(m1)) table.cell(t, 1, 0, "Matrix Eigenvectors:") table.cell(t, 1, 1, str.tostring(m2)) ``` ``` -------------------------------- ### Sorting Array Indices Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/array.sort_indices.md This example demonstrates how to get the indices that would sort an array in ascending order and then use those indices to find the smallest value. ```javascript //@version=6 indicator("array.sort_indices") a = array.from(5, 2, 0, 9, 1) sortedIndices = array.sort_indices(a) // [1, 2, 4, 0, 3] indexOfSmallestValue = array.get(sortedIndices, 0) // 1 smallestValue = array.get(a, indexOfSmallestValue) // -2 plot(smallestValue) ``` -------------------------------- ### Get Element from Matrix Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.get.md Use matrix.get() to retrieve a specific element from a matrix. Ensure the matrix is created and indices are within bounds. Indexing starts at zero. ```javascript //@version=6 indicator("`matrix.get()` Example", "", true) // Create a 2x3 "float" matrix from the `hl2` values. m = matrix.new(2, 3, hl2) // Return the value of the element at index [0, 0] of matrix `m`. x = matrix.get(m, 0, 0) plot(x) ``` -------------------------------- ### Example: Bracket Exit Strategy Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.exit.md Demonstrates how to use strategy.exit() to set both take-profit and stop-loss levels for a long entry order. ```APIDOC ## Example: Bracket Exit Strategy ### Description This example shows a strategy that enters a long position based on moving average crossovers and then uses `strategy.exit()` to define a take-profit and stop-loss based on user-defined tick distances. ### Code ```pinescript //@version=6 strategy("Exit Bracket strategy", overlay = true) // Inputs that define the profit and loss amount of each trade as a tick distance from the entry price. int profitDistanceInput = input.int(100, "Profit distance, in ticks", 1) int lossDistanceInput = input.int(100, "Loss distance, in ticks", 1) // Variables to track the take-profit and stop-loss price. var float takeProfit = na var float stopLoss = na // Calculate a 14-bar and 28-bar moving average of `close` prices. float sma14 = ta.sma(close, 14) float sma28 = ta.sma(close, 28) if ta.crossover(sma14, sma28) and strategy.opentrades == 0 // Place a market order to enter a long position. strategy.entry("My Long Entry ID", strategy.long) // Place a take-profit and stop-loss order when the entry order fills. strategy.exit("My Long Exit ID", "My Long Entry ID", profit = profitDistanceInput, loss = lossDistanceInput) if ta.change(strategy.opentrades) == 1 //@variable The long entry price. float entryPrice = strategy.opentrades.entry_price(0) // Update the `takeProfit` and `stopLoss` values. takeProfit := entryPrice + profitDistanceInput * syminfo.mintick stopLoss := entryPrice - lossDistanceInput * syminfo.mintick if ta.change(strategy.closedtrades) == 1 // Reset the `takeProfit` and `stopLoss`. takeProfit := na stopLoss := na // Plot the `takeProfit` and `stopLoss`. plot(takeProfit, "Take-profit level", color.green, 2, plot.style_linebr) plot(stopLoss, "Stop-loss level", color.red, 2, plot.style_linebr) ``` ``` -------------------------------- ### Get Map Size with map.size() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/map.size.md Use map.size() to retrieve the number of elements in a map. This example initializes a map, populates it with key-value pairs, and then plots its size. ```javascript //@version=6 indicator("map.size example") a = map.new() size = 10 for i = 0 to size a.put(i, size-i) plot(map.size(a)) ``` -------------------------------- ### Get Green Component of a Color Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/color.g.md Use color.g() to retrieve the green component (0-255) of a specified color. This example plots the green value of the predefined color.green. ```javascript //@version=6 indicator("color.g", overlay=true) plot(color.g(color.green)) ``` -------------------------------- ### Place Limit and Stop Orders with strategy.order() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.order.md This example shows how to place limit and stop orders to manage a long position. It calculates profit and loss levels based on the entry price and uses OCA (One-Cancels-All) groups to ensure only one of the exit orders is executed. ```javascript //@version=6 strategy("Limit and stop exit strategy", overlay = true) //@variable The distance from the long entry price for each short limit order. float shortOffsetInput = input.int(200, "Sell limit/stop offset, in ticks", 1) * syminfo.mintick //@function Draws a label and line at the specified `price` to visualize a limit order's level. drawLimit(float price, bool isLong, bool isStop = false) =>     color col = isLong ? color.blue : color.red     label.new(          bar_index, price, (isLong ? "Long " : "Short ") + (isStop ? "stop" : "limit") + " order created",          style = label.style_label_right, color = col, textcolor = color.white      )     line.new(bar_index, price, bar_index + 1, price, extend = extend.right, style = line.style_dashed, color = col) //@function Stops the `l` line from extending further. method stopExtend(line l) =>     l.set_x2(bar_index)     l.set_extend(extend.none) // Initialize two `line` variables to reference limit and stop line IDs. var line profitLimit = na var line lossStop    = na // Calculate a 14-bar and 28-bar moving average of `close` prices. float sma14 = ta.sma(close, 14) float sma28 = ta.sma(close, 28) if ta.crossover(sma14, sma28) and strategy.position_size == 0     // Place a market order to enter a long position.     strategy.order("My Long Entry ID", strategy.long) if strategy.position_size > 0 and strategy.position_size[1] == 0     //@variable The entry price of the long trade.     float entryPrice = strategy.opentrades.entry_price(0)     // Calculate short limit and stop levels above and below the `entryPrice`.     float profitLevel = entryPrice + shortOffsetInput     float lossLevel   = entryPrice - shortOffsetInput     // Place short limit and stop orders at the `profitLevel` and `lossLevel`.     strategy.order("Profit", strategy.short, limit = profitLevel, oca_name = "Bracket", oca_type = strategy.oca.cancel)     strategy.order("Loss", strategy.short, stop = lossLevel, oca_name = "Bracket", oca_type = strategy.oca.cancel)     // Make new drawings for the `profitLimit` and `lossStop` lines.     profitLimit := drawLimit(profitLevel, isLong = false)     lossStop    := drawLimit(lossLevel, isLong = false, isStop = true) if ta.change(strategy.closedtrades) > 0     // Stop extending the `profitLimit` and `lossStop` lines.     profitLimit.stopExtend()     lossStop.stopExtend() ``` -------------------------------- ### Get Closing Time of a Bar with Specific Session Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/time_close.md This example demonstrates how to get the UNIX time of the close for a bar on a specific timeframe and session. It highlights the use of `timeframe.period` for the chart's current resolution and a custom session string. The `bgcolor` function is used to visualize when a valid timestamp is returned. ```javascript //@version=6 indicator("Time", overlay=true) t1 = time_close(timeframe.period, "1200-1300", "America/New_York") bgcolor(not na(t1) ? color.new(color.blue, 90) : na) ``` -------------------------------- ### Using strategy.percent_of_equity for Trade Entries Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/constants/strategy.percent_of_equity.md This example demonstrates how to use `strategy.percent_of_equity` as the `default_qty_type`. When `qty` is not specified in `strategy.entry`, trades will use 100% of the available equity. It also shows how explicitly setting `qty` overrides this behavior. ```pine //@version=6 strategy("strategy.percent_of_equity", overlay  false,  default_qty_value  100,  default_qty_type  strategy.percent_of_equity,  initial_capital  1000000) // As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_value` parameters are used to enter trades, namely 100% of available equity. if  bar_index  0  strategy.entry("EN",  strategy.long) if  bar_index  2  strategy.close("EN") plot(strategy.equity)  // The ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry market price = (10 * close). if  bar_index  4  strategy.entry("EN",  strategy.long,  qty  10) if  bar_index  6  strategy.close("EN") ``` -------------------------------- ### Example: Trailing Stop with Activation Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.exit.md This example demonstrates how to set up a trailing stop order that activates after a certain price level is reached. It includes logic for visualizing the activation line and the trailing stop price. ```pinescript //@function Stops the `l` line from extending further. method stopExtend(line l) =>     l.set_x2(bar_index)     l.set_extend(extend.none) // The activation line, active trailing stop price, and active trailing stop flag. var line activationLine     = na var float trailingStopPrice = na var bool isActive           = false if bar_index % 100 == 0 and strategy.opentrades == 0     trailingStopPrice := na     isActive          := false     // Place a market order to enter a long position.     strategy.entry("My Long Entry ID", strategy.long)     //@variable The activation level's price.     float activationPrice = close + activationDistanceInput     // Create a trailing stop order that activates the defined number of ticks above the entry price.     strategy.exit(          "My Long Exit ID", "My Long Entry ID", trail_price = activationPrice, trail_offset = trailDistanceInput,          oca_name = "Exit"      )     // Create new drawings at the `activationPrice`.     activationLine := drawActivation(activationPrice) // Logic for trailing stop visualization. if strategy.opentrades == 1     // Stop extending the `activationLine` when the stop activates.     if not isActive and high > activationLine.get_price(bar_index)         isActive := true         activationLine.stopExtend()     // Update the `trailingStopPrice` while the trailing stop is active.     if isActive         float offsetPrice = high - trailDistanceInput * syminfo.mintick         trailingStopPrice := math.max(nz(trailingStopPrice, offsetPrice), offsetPrice) // Close the trade with a market order if the trailing stop does not activate before the next 300th bar. if not isActive and bar_index % 300 == 0     strategy.close_all("Market close") // Reset the `trailingStopPrice` and `isActive` flags when the trade closes, and stop extending the `activationLine`. if ta.change(strategy.closedtrades) > 0     if not isActive         activationLine.stopExtend()     trailingStopPrice := na     isActive          := false // Plot the `trailingStopPrice`. plot(trailingStopPrice, "Trailing stop", color.red, 3, plot.style_linebr) ``` -------------------------------- ### Retrieve and Delete All Boxes Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/variables/box.all.md This example demonstrates how to get all existing boxes using box.all and then iterate through them to delete each one. Ensure that the array is not empty before attempting to access its elements. ```javascript //@version=6 indicator("box.all") //delete all boxes box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed) a_allBoxes = box.all if array.size(a_allBoxes) > 0     for i = 0 to array.size(a_allBoxes) - 1         box.delete(array.get(a_allBoxes, i)) ``` -------------------------------- ### Get Array Element by Index Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/array.get.md Use array.get() to retrieve an element from an array using its index. Positive indices count from the start, while negative indices count from the end. ```pine //@version=6 indicator("array.get\u00a0example") a\u00a0=\u00a0array.new_float(0) for\u00a0i\u00a0=\u00a00\u00a0to\u00a09 \u00a0\u00a0\u00a0\u00a0array.push(a, \u00a0close[i]\u00a0-\u00a0open[i]) plot(array.get(a, \u00a09)) ``` -------------------------------- ### Basic indicator() call Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/indicator.md Every indicator script must include a call to the indicator() function. This example shows a basic setup with a script title and short title. ```pine //@version=6 indicator("My script", shorttitle="Script") plot(close) ``` -------------------------------- ### Implement Trailing Stops with strategy.exit() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.exit.md This example demonstrates how to set up a trailing stop loss using `strategy.exit()`. It defines an activation distance and a trail distance, allowing the stop loss to follow the price as it moves favorably. ```pinescript //@version=6 strategy("Trailing stop strategy", overlay = true) //@variable The distance required to activate the trailing stop. float activationDistanceInput = input.int(100, "Trail activation distance, in ticks") * syminfo.mintick //@variable The number of ticks the trailing stop follows behind the price as it reaches new peaks. int trailDistanceInput = input.int(100, "Trail distance, in ticks") //@function Draws a label and line at the specified `price` to visualize a trailing stop order's activation level. drawActivation(float price) =>     label.new(          bar_index, price, "Activation level", style = label.style_label_right,          color = color.gray, textcolor = color.white      )     line.new(          bar_index, price, bar_index + 1, price, extend = extend.right, style = line.style_dashed, color = color.gray      ) ``` -------------------------------- ### Get Latest Open Trade Entry Price Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.opentrades.entry_price.md This example demonstrates how to retrieve the entry price of the most recent open trade. It's used here to set a target exit price. ```pine //@version=6 strategy("strategy.opentrades.entry_price Example 1", overlay = true) // Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars. if ta.crossover(close, ta.sma(close, 14))     strategy.entry("Long", strategy.long) // Return the entry price for the latest closed trade. currEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1) currExitPrice = currEntryPrice * 1.05 if high >= currExitPrice     strategy.close("Long") plot(currEntryPrice, "Long entry price", style = plot.style_linebr) plot(currExitPrice, "Long exit price", color.green, style = plot.style_linebr) ``` -------------------------------- ### Build Lightweight Charts Indicators Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/README.md Run the build command using npm to compile the project. ```bash npm run build ``` -------------------------------- ### Detect new bar on a specific timeframe Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/time.md This snippet shows how to detect the start of a new bar on a specified timeframe. It uses the time() function to get the timestamp of the bar and checks for changes. ```javascript // This plots 1.0 at every start of 10 minute bar on a 1 minute chart: newbar(res) => ta.change(time(res)) == 0 ? 0 : 1 plot(newbar("10")) ``` -------------------------------- ### Var Keyword Initialization Example Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/keywords/var.md This example demonstrates how 'var' variables retain their initial values across bar updates. 'a' stores the initial close price, 'b' stores the close price of the first 'green' bar, and 'c' stores the close price of the tenth 'green' bar. ```pine //@version=6 indicator("Var keyword example") var a = close var b = 0.0 var c = 0.0 var green_bars_count = 0 if close > open     var x = close     b := x     green_bars_count := green_bars_count + 1     if green_bars_count >= 10         var y = close         c := y plot(a) plot(b) plot(c) ``` -------------------------------- ### Get Closed Trade Entry Comment Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/strategy.closedtrades.entry_comment.md This example demonstrates how to retrieve and display the comment of the last closed trade using `strategy.closedtrades.entry_comment()`. It also shows how to display the actual entry price for comparison. ```pine //@version=6 strategy("`strategy.closedtrades.entry_comment()` Example", overlay = true) stopPrice = open * 1.01 longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (longCondition)     strategy.entry("Long", strategy.long, stop = stopPrice, comment = str.tostring(stopPrice, "#.####"))     strategy.exit("EXIT", trail_points = 1000, trail_offset = 0) var testTable = table.new(position.top_right, 1, 3, color.orange, border_width = 1) if barstate.islastconfirmedhistory or barstate.isrealtime     table.cell(testTable, 0, 0, 'Last closed trade:')     table.cell(testTable, 0, 1, "Order stop price value: " + strategy.closedtrades.entry_comment(strategy.closedtrades - 1))     table.cell(testTable, 0, 2, "Actual Entry Price: " + str.tostring(strategy.closedtrades.entry_price(strategy.closedtrades - 1))) ``` -------------------------------- ### Get Array Size with array.size() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/array.size.md Use array.size() to retrieve the number of elements in an array. This example demonstrates creating an array, pushing elements, slicing it, and then plotting the sizes of both the original and sliced arrays. ```javascript //@version=6 indicator("array.size example") a = array.new_float(0) for i = 0 to 9 array.push(a, close[i]) // note that changes in slice also modify original array slice = array.slice(a, 0, 5) array.push(slice, open) // size was changed in slice and in original array plot(array.size(a)) plot(array.size(slice)) ``` -------------------------------- ### Calculate Matrix Mode Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.mode.md This example demonstrates how to create a matrix, fill it with integer values, and then calculate its mode using `matrix.mode()`. The result is plotted as an indicator. ```javascript //@version=6 indicator("`matrix.mode()` Example") // Create a 2x2 matrix. var m = matrix.new(2, 2, na) // Fill the matrix with values. matrix.set(m, 0, 0, 0) matrix.set(m, 0, 1, 0) matrix.set(m, 1, 0, 1) matrix.set(m, 1, 1, 1) // Get the mode of the matrix. var x = matrix.mode(m) plot(x, 'Mode of the matrix') ``` -------------------------------- ### Get Matrix Row Count with matrix.rows() Source: https://github.com/deepentropy/lightweight-charts-indicators/blob/main/docs/official/language-reference/functions/matrix.rows.md Use this snippet to create a matrix and then retrieve the number of rows it contains. The example displays the row count using a label on the last confirmed history bar. ```javascript //@version=6 indicator("`matrix.rows()` Example") // Create a 2x6 matrix with values `0`. var m = matrix.new(2, 6, 0) // Get the quantity of rows in the matrix. var x = matrix.rows(m) // Display using a label. if barstate.islastconfirmedhistory     label.new(bar_index, high, "Rows: " + str.tostring(x) + "\n" + str.tostring(m)) ```