### Basic `for` Loop Example Source: https://www.tradingview.com/pine-script-reference/v6 Calculates the number of bars where the close price was above the current close price within a specified length. Requires no special setup. ```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)) ``` -------------------------------- ### Partial Close Strategy Example Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to use strategy.close() to exit 50% of a long position when a crossover condition is met. It requires calculating moving averages and placing an initial entry order. ```pine //@version=6 strategy("Partialclosestrategy") //Calculatea14-barand28-barmovingaverageof`close`prices. floatsma14=ta.sma(close,14) floatsma28=ta.sma(close,28) //Placeamarketordertoenteralongpositionwhen`sma14`crossesover`sma28`. ifta.crossover(sma14,sma28) strategy.entry("MyLongEntryID",strategy.long) //Placeamarketordertoclosethelongtradewhen`sma14`crossesunder`sma28`. ifta.crossunder(sma14,sma28) strategy.close("MyLongEntryID","50% marketclose",qty_percent=50) //Plotthepositionsize. plot(strategy.position_size) ``` -------------------------------- ### Example: Set Table Cell Text in Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates creating a table and then setting the text for a specific cell using table.cell_set_text. It also shows initial cell creation with table.cell. ```pinescript //@version=6 indicator("TABLE example") var tLog = table.new(position = position.top_left, rows = 1, columns = 2, bgcolor = color.yellow, border_width=1) table.cell(tLog, row = 0, column = 0, text = "sometext", text_color = color.blue) table.cell_set_text(tLog, row = 0, column = 0, text = "sometext") ``` -------------------------------- ### strategy.entry() Function Syntax and Example - Pine Script Source: https://www.tradingview.com/pine-script-reference/index Demonstrates the syntax and provides an example usage of the strategy.entry() function in Pine Script. This function is crucial for initiating trades and managing order types within a trading strategy. ```pine // strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void //@version=6 // Example usage (this is a placeholder, actual implementation would involve strategy logic) // strategy.entry("Buy", strategy.long, qty=10, limit=100, stop=90) // strategy.entry("Sell", strategy.short, qty=5, limit=110, stop=120) ``` -------------------------------- ### Delete All Boxes Example Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to retrieve all existing boxes drawn by the script using `box.all` and then delete them. It's useful for clearing the chart of previously drawn boxes. ```pinescript //@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)) ``` -------------------------------- ### input.time() Function Reference Source: https://www.tradingview.com/pine-script-reference/v6 This section details the input.time() function, its parameters, and provides an example of its usage in Pine Script. ```APIDOC ## input.time() ### Description Adds two inputs to the script's "Settings/Inputs" tab on the same line: one for the date and one for the time. The function returns a date/time value in UNIX format. ### Method N/A (This is a function call within a script, not an HTTP method) ### Endpoint N/A ### Parameters #### Arguments - **defval** (const int) - Default value for the input. Can be a timestamp() function with a const string date argument. - **title** (const string) - Title of the input. Defaults to the variable name if not specified or empty. - **tooltip** (const string) - Text displayed when hovering over the tooltip icon. - **inline** (const string) - Combines inputs on the same line. The string identifies inputs belonging to the same line. - **group** (const string) - Creates a header above inputs. The string is used as the header's text. - **confirm** (const bool) - Optional. If true, prompts the user to set the initial value by clicking on the chart. Defaults to false. - **display** (const plot_display) - Controls where the input's information is displayed (e.g., `display.none`, `display.data_window`, `display.status_line`, `display.all`). Optional. Defaults to `display.none`. - **active** (input bool) - Optional. Specifies if users can change the input's value in settings. If false, the input is grayed out. Defaults to true. ### Request Example ```pinescript //@version=6 indicator("input.time", overlay=true) i_date = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date") l = label.new(i_date, high, "Date", xloc=xloc.bar_time) label.delete(l[1]) ``` ### Response #### Success Response (200) Value of input variable (int - UNIX timestamp format). #### Response Example N/A (This is a function return value, not an HTTP response) ### Remarks - Users can change the input's value in the "Settings/Inputs" tab, by moving the marker on the chart, or by selecting "Reset points" and clicking on the chart. - If `input.time()` and `input.price()` share the same `inline` and `group` arguments, they create a single interactive marker on the chart for simultaneous adjustment. ``` -------------------------------- ### Clone Box Object - Pine Script Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to clone an existing box object using box.copy(). The example creates a new box, then copies it and modifies the properties of the copied box. This is useful for creating multiple similar boxes without redefining all properties. ```pine //@version=6 indicator('Last 50 bars price ranges', overlay = true) LOOKBACK = 50 highest = ta.highest(LOOKBACK) lowest = ta.lowest(LOOKBACK) if barstate.islastconfirmedhistory var BoxLast = box.new(bar_index[LOOKBACK], highest, bar_index, lowest, bgcolor = color.new(color.green, 80)) var BoxPrev = box.copy(BoxLast) box.set_lefttop(BoxPrev, bar_index[LOOKBACK * 2], highest[50]) box.set_rightbottom(BoxPrev, bar_index[LOOKBACK], lowest[50]) box.set_bgcolor(BoxPrev, color.new(color.red, 80)) ``` -------------------------------- ### Plot Blue Component of Color.blue Source: https://www.tradingview.com/pine-script-reference/v6 An example demonstrating how to plot the blue component of the predefined 'color.blue'. ```pinescript //@version=6 indicator("color.b", overlay=true) plot(color.b(color.blue)) ``` -------------------------------- ### Pine Script Strategy Example Source: https://www.tradingview.com/pine-script-reference/v6 A basic example of a TradingView Pine Script strategy demonstrating entry and exit orders. It includes the mandatory strategy() call and conditional order placement. This script requires Pine Script version 6. ```pine //@version=6 strategy("My strategy", overlay = true)  // Enter long by market if current open is greater than previous high.  if open > high[1]    strategy.entry("Long", strategy.long, 1)  // Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".  strategy.exit("Exit", "Long", profit = 10, loss = 5)  ``` -------------------------------- ### Display Analyst Recommendations with syminfo.recommendations_date Source: https://www.tradingview.com/pine-script-reference/v6 This script displays analyst recommendation data, including the start date, in a table. It uses syminfo.recommendations_date to get the starting date of the last recommendations. ```pinescript //@version=6 indicator("syminfo recommendations", overlay = true) //@variable A table containing information about analyst recommendations. var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000) if barstate.islastconfirmedhistory //@variable The time value one year from the date of the last analyst recommendations. int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000 // Add header cells. table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_size = size.large) table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_size = size.large) table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size = size.large) table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_size = size.large) table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size = size.large) table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_size = size.large) table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size = size.large) table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_size = size.large) // Recommendation strings string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd") string endDate = str.format_time(YTD, "yyyy-MM-dd") string buyRatings = str.tostring(syminfo.recommendations_buy) string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong) string sellRatings = str.tostring(syminfo.recommendations_sell) string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong) string holdRatings = str.tostring(syminfo.recommendations_hold) string totalRatings = str.tostring(syminfo.recommendations_total) // Add value cells table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_size = size.large) table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size = size.large) table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_size = size.large) table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, text_size = size.large) table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text_size = size.large) ``` -------------------------------- ### Basic Strategy Entry Example Source: https://www.tradingview.com/pine-script-reference/v6 Illustrates a basic usage of strategy.entry() to open a long position. Ensure the strategy declaration includes appropriate default quantity settings if 'qty' is not specified. ```pinescript //@version=6 strategy("My Strategy", overlay=true) if (strategy.position_size == 0) strategy.entry("Buy", strategy.long) ``` -------------------------------- ### last_bar_index Source: https://www.tradingview.com/pine-script-reference/v6 Gets the index of the last bar on the chart. Bar indices start at 0. ```APIDOC ## last_bar_index ### Description Bar index of the last chart bar. Bar indices begin at zero on the first bar. ### Type series int ### Example ``` //@version=6 strategy("Mark Last X Bars For Backtesting", overlay = true, calc_on_every_tick = true) lastBarsFilterInput = input.int(100, "Bars Count:") // Here, we store the 'last_bar_index' value that is known from the beginning of the script's calculation. // The 'last_bar_index' will change when new real-time bars appear, so we declare 'lastbar' with the 'var' keyword. var lastbar = last_bar_index // Check if the current bar_index is 'lastBarsFilterInput' removed from the last bar on the chart, or the chart is traded in real-time. allowedToTrade = (lastbar - bar_index <= lastBarsFilterInput) or barstate.isrealtime bgcolor(allowedToTrade ? color.new(color.green, 80) : na) ``` ### Returns Last historical bar index for closed markets, or the real-time bar index for open markets. ### Remarks Please note that using this variable can cause indicator repainting. ### See also bar_index last_bar_time barstate.ishistory barstate.isrealtime ``` -------------------------------- ### Strategy Entry and Exit Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates basic strategy entry and exit logic. Ensure the strategy() call is present in your script. ```pine //@version=6 strategy("My strategy", overlay = true)  // Enter long by market if current open is greater than previous high.  if open > high[1]    strategy.entry("Long", strategy.long, 1)  // Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".  strategy.exit("Exit", "Long", profit = 10, loss = 5)  ``` -------------------------------- ### Trailing Stop Strategy Implementation Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates setting up a trailing stop order. It includes logic for activation distance, trail distance, and visualizing the activation level. The `strategy.exit` function is used to define the trailing stop parameters. ```pine //@version=6 strategy("Trailingustopustrategy",uoverlayu=utrue) //@variableuTheudistanceurequiredutouactivateutheutrailingustop. floatuactivationDistanceInputu=uinput.int(100,u"Trailuactivationudistance,uinuticks")u*usyminfo.mintick //@variableuTheunumberuofuticksutheutrailingustopufollowsubehindutheupriceuasuitureachesunewupeaks. intutrailDistanceInputu=uinput.int(100,u"Trailudistance,uinuticks") //@functionuDrawsuaulabeluandulineuatutheuspecifiedu`price`utouvisualizeuautrailingustopuorder'suactivationulevel. drawActivation(floatuprice)u=> uulabel.new( uuuubar_index,uprice,u"Activationulevel",ustyleu=ulabel.style_label_right, uuuucoloru=ucolor.gray,utextcoloru=ucolor.white uu) uuline.new( uuuubar_index,uprice,ubar_indexu+u1,uprice,uextendu=uextend.right,ustyleu=uline.style_dashed,ucoloru=ucolor.gray uu) //@functionuStopsutheu`l`ulineufromuextendingufurther. methodustopExtend(lineul)u=> uul.set_x2(bar_index) uul.set_extend(extend.none) //uTheuactivationuline,uactiveutrailingustopuprice,uanduactiveutrailingustopuflag. varulineuactivationLineuu=una varufloatutrailingStopPriceu=una varubooluisActiveuu=ufalse ifubar_indexu%u100u==u0uandustrategy.opentradesu==u0 uutrailingStopPriceu:=una uuisActiveuu:=ufalse uu//uPlaceuaumarketuorderutouenteruaulonguposition. uustrategy.entry("MyuLonguEntryuID",ustrategy.long) uu//@variableuTheuactivationulevel'suprice. uufloatuactivationPriceu=ucloseu+uactivationDistanceInput uu//uCreateuautrailingustopuorderuthatuactivatesutheudefinedunumberuofuticksuaboveutheuentryuprice. uustrategy.exit( ``` -------------------------------- ### Get Closing Timestamp with Session Filter Source: https://www.tradingview.com/pine-script-reference/v6 Use `time_close` to get the closing UNIX timestamp for a specified timeframe and session. It returns `na` if the time is outside the session. This example highlights bars within a specific 2-hour session. ```pinescript //@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) ``` -------------------------------- ### Plot Colors from Gradient Examples Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates using 'color.from_gradient' with 'close' prices and RSI values, mapping them to different color gradients. ```pinescript //@version=6 indicator("color.from_gradient", overlay=true) color1 = color.from_gradient(close, low, high, color.yellow, color.lime) color2 = color.from_gradient(ta.rsi(close, 7), 0, 100, color.rgb(255, 0, 0), color.rgb(0, 255, 0, 50)) plot(close, color=color1) plot(ta.rsi(close,7), color=color2) ``` -------------------------------- ### Get Closed Trade Exit Price in Pine Script (Example 1) Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to retrieve the exit price of the latest closed trade using strategy.closedtrades.exit_price(). It plots the exit price for trades initiated every 5 bars. ```pinescript //@version=6 strategy("strategy.closedtrades.exit_price Example 1") // We are creating a long trade every 5 bars if bar_index % 5 == 0     strategy.entry("Long", strategy.long) strategy.close("Long") // Return the exit price from the latest closed trade. exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1) plot(exitPrice, "Long exit price") ``` -------------------------------- ### Get Matrix Element - Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Retrieves the element at a specific row and column index from a matrix. Remember that indexing starts at zero. ```pinescript //@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) ``` -------------------------------- ### Create and Display a Polyline Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to create a polyline using user inputs for curvature, closure, and fill color. It defines multiple time and price points, collects them into an array of chart.point objects, and then calls polyline.new() to draw the polyline on the chart. ```pinescript //@version=6 indicator("Polylines example", overlay = true) //@variable If `true`, connects all points in the polyline with curved line segments. bool curvedInput = input.bool(false, "Curve Polyline") //@variable If `true`, connects the first point in the polyline to the last point. bool closedInput = input.bool(true, "Close Polyline") //@variable The color of the space filled by the polyline. color fillcolor = input.color(color.new(color.blue, 90), "Fill Color") // Time and price inputs for the polyline's points. p1x = input.time(0,  "p1", confirm = true, inline = "p1") p1y = input.price(0, "  ", confirm = true, inline = "p1") p2x = input.time(0,  "p2", confirm = true, inline = "p2") p2y = input.price(0, "  ", confirm = true, inline = "p2") p3x = input.time(0,  "p3", confirm = true, inline = "p3") p3y = input.price(0, "  ", confirm = true, inline = "p3") p4x = input.time(0,  "p4", confirm = true, inline = "p4") p4y = input.price(0, "  ", confirm = true, inline = "p4") p5x = input.time(0,  "p5", confirm = true, inline = "p5") p5y = input.price(0, "  ", confirm = true, inline = "p5") if barstate.islastconfirmedhistory     //@variable An array of `chart.point` objects for the new polyline.     var points = array.new()     // Push new `chart.point` instances into the `points` array.     points.push(chart.point.from_time(p1x, p1y))     points.push(chart.point.from_time(p2x, p2y))     points.push(chart.point.from_time(p3x, p3y))     points.push(chart.point.from_time(p4x, p4y))     points.push(chart.point.from_time(p5x, p5y))     // Add labels for each `chart.point` in `points`.     l1p1 = label.new(points.get(0), text = "p1", xloc = xloc.bar_time, color = na)     l1p2 = label.new(points.get(1), text = "p2", xloc = xloc.bar_time, color = na)     l2p1 = label.new(points.get(2), text = "p3", xloc = xloc.bar_time, color = na)     l2p2 = label.new(points.get(3), text = "p4", xloc = xloc.bar_time, color = na)     // Create a new polyline that connects each `chart.point` in the `points` array, starting from the first.     polyline.new(points, curved = curvedInput, closed = closedInput, fill_color = fillcolor, xloc = xloc.bar_time) ``` -------------------------------- ### Detect New Day Start Source: https://www.tradingview.com/pine-script-reference/v6 The `timeframe.change` function detects when a new timeframe begins. This example highlights the first bar of each new day by checking for changes in the '1D' timeframe. ```pinescript //@version=6 // Run this script on an intraday chart. indicator("New day started", overlay = true) // Highlights the first bar of the new day. isNewDay = timeframe.change("1D") bgcolor(isNewDay ? color.new(color.green, 80) : na) ``` -------------------------------- ### Requesting Lower Timeframe Close Prices Source: https://www.tradingview.com/pine-script-reference/v6 Fetches 'close' prices from a lower timeframe (e.g., 60 minutes) for each bar on the current chart. This example demonstrates how to use `request.security_lower_tf` to get an array of close prices and display them. ```pine //@version=6 indicator("`request.security_lower_tf()` Example", overlay = true) // If the current chart timeframe is set to 120 minutes, then the `arrayClose` array will contain two 'close' values from the 60 minute timeframe for each bar. arrClose = request.security_lower_tf(syminfo.tickerid, "60", close) if bar_index == last_bar_index - 1     label.new(bar_index, high, str.tostring(arrClose)) ``` -------------------------------- ### Create Market Order with strategy.order() Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates placing a market order to enter a long position when the 14-bar Simple Moving Average crosses over the 28-bar Simple Moving Average, and no position is currently open. This function creates a market order that executes on the next tick. ```pinescript //@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 Buy Order", strategy.long) ``` -------------------------------- ### Get First Point Coordinates of a Line in Pine Script Source: https://www.tradingview.com/pine-script-reference/index Shows how to retrieve the y-coordinate (price) of the first point of a line using `line.get_y1()`. This function is useful for accessing the starting price level of a drawn line. ```pine-script //@version=6 indicator("Get First Point Y Coordinate") var line myLine = line.new(bar_index, open, bar_index + 10, close, extend=extend.none) // Get the y-coordinate of the first point (price) y1_coord = line.get_y1(myLine) plot(y1_coord, title="Y1 Coordinate") ``` -------------------------------- ### Advanced str.format() Examples with Number Formatting Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates advanced string formatting using str.format() with various number format specifiers like decimals, integer, currency, and percentage. Each label.new() call shows a different formatting outcome. ```pinescript //@version=6 indicator("Extensive `str.format()` demo", overlay=true) // The format specifier inside the curly braces accepts certain modifiers: // - Specify the number of decimals to display: s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3 label.new(bar_index, close, text=s1) // - Round a float value to an integer: s2 = str.format("{0,number,integer}", 1.34) // returns: 1 label.new(bar_index - 1, close, text=s2) // - Display a number in currency: s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34 label.new(bar_index - 2, close, text=s3) // - Display a number as a percentage: s4 = str.format("{0,number,percent}", 0.5) // returns: 50% label.new(bar_index - 3, close, text=s4) // EXAMPLES WITH SEVERAL ARGUMENTS // returns: Number 1 is not equal to 4 s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4) label.new(bar_index - 4, close, text=s5) // returns: 1.34 != 1.3 s6 = str.format("{0} != {0, number, #.#}", 1.34) label.new(bar_index - 5, close, text=s6) // returns: 1 is equal to 1, but 2 is equal to 2 s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52) label.new(bar_index - 6, close, text=s7) // returns: The cash turnover amounted to $1,340,000.00 s8 = str.format("The cash turnover amounted to {0, number, currency}", 1340000) label.new(bar_index - 7, close, text=s8) // returns: Expected return is 10% - 20% s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2) label.new(bar_index - 8, close, text=s9) ``` -------------------------------- ### Manage tables using table.all Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to retrieve all current tables and delete them. The 'table.all' array is read-only, with index zero being the oldest object. ```pine //@version=6 indicator("table.all") //delete all tables table.new(position=position.top_right, columns=2, rows=1, bgcolor=color.yellow, border_width=1) a_allTables=table.all ifarray.size(a_allTables)>0 fori=0toarray.size(a_allTables)-1 table.delete(array.get(a_allTables,i)) ``` -------------------------------- ### Get Symbol Prefix in Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Retrieves the prefix of the current symbol's name. This is useful for identifying the exchange or data provider associated with a symbol. The example demonstrates how to display the prefix using a label. ```pine //@version=6 indicator("syminfo.prefix") // If current chart symbol is 'BATS:MSFT' then syminfo.prefix is 'BATS'. if barstate.islastconfirmedhistory label.new(bar_index, high, text=syminfo.prefix) ``` -------------------------------- ### Get Last Bar Index (Pine Script) Source: https://www.tradingview.com/pine-script-reference/v6 Returns the bar index of the last bar on the chart. Bar indices start at zero. This value can be used for calculations related to the end of the chart data or for real-time updates. ```pine-script //@version=6 strategy("Last Bar Index Example", overlay=true) // Get the last bar indexlastBar = last_bar_index // Plot a vertical line at the last bar hline(lastBar, "Last Bar", color=color.red) // Example: Highlight the last N bars inputBars = input.int(50, title="Highlight Last Bars") // Check if the current bar is within the last 'inputBars' from the 'lastBar' shouldHighlight = (lastBar - bar_index <= inputBars) or barstate.isrealtime bgcolor(shouldHighlight ? color.new(color.yellow, 80) : na) ``` -------------------------------- ### Pine Script input.price() Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to use input.price() to create two price inputs with different configurations. The first uses named arguments for title and default value, while the second uses positional arguments. Both are plotted on the chart. ```pine //@version=6 indicator("input.price", overlay=true) price1 = input.price(title="Date", defval=42) plot(price1) price2 = input.price(54, title="Date") plot(price2) ``` -------------------------------- ### str.format() - Basic Usage Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates the basic usage of the str.format() function to create a formatted string using placeholders for bar_index and close values. ```APIDOC ## str.format() ### Description Creates a formatted string using a specified formatting string (`formatString`) and one or more additional arguments (`arg0`, `arg1`, etc.). The formatting string defines the structure of the returned string, where all placeholders in curly brackets (`{}`) refer to the additional arguments. Each placeholder requires a number representing an argument's position, starting from 0. The function replaces each placeholder with a string representation of the corresponding argument. ### Method `str.format(formatString, arg0, arg1, ...)` ### Parameters #### Arguments - `formatString` (simple string) - The format string. - `arg0, arg1, ...` (simple int/float/bool/string) - Values to format. ### Request Example ```pinescript //@version=6 indicator("Simple `str.format()` demo") string labelText = str.format("Current bar index: {0}\nCurrent bar close: {1}", bar_index, close) label.new(bar_index, high, labelText) ``` ### Response Returns the formatted string. ``` -------------------------------- ### Clear Cells in Pine Script Table Source: https://www.tradingview.com/pine-script-reference/v6 Removes a rectangular area of cells from a table, defined by start and end column/row indices. If end column/row are omitted, it clears a single cell. The example shows clearing a 4x4 area from a larger table. ```pine-script //@version=6 indicator("A donut", overlay=true) if barstate.islast     colNum = 8, rowNum = 8     padding = "◯"     donutTable = table.new(position.middle_right, colNum, rowNum)     for c = 0 to colNum - 1         for r = 0 to rowNum - 1             table.cell(donutTable, c, r, text=padding, bgcolor=#face6e, text_color=color.new(color.black, 100))     table.clear(donutTable, 2, 2, 5, 5) ``` -------------------------------- ### Get Closed Trade Commission with strategy.closedtrades.commission() Source: https://www.tradingview.com/pine-script-reference/v6 Retrieve the total commission paid for a specific closed trade using strategy.closedtrades.commission(trade_num). The trade_num argument specifies the trade's index, starting from zero for the oldest trade. This function returns the commission in the strategy's account currency. ```pinescript //@version=6 strategy("`strategy.closedtrades.commission` Example", commission_type = strategy.commission.percent, commission_value = 0.1) // Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars. if bar_index % 15 == 0     strategy.entry("Long", strategy.long) if bar_index % 20 == 0     strategy.close("Long") // Plot total fees for the latest closed trade. plot(strategy.closedtrades.commission(strategy.closedtrades - 1)) ``` -------------------------------- ### Strategy Margin Call Management Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to use strategy.margin_liquidation_price to prevent margin calls by closing positions when a certain percentage away from liquidation. Requires margin parameters in the strategy() declaration. ```pinescript //@version=6 strategy("Margin call management", overlay = true, margin_long = 25, margin_short = 25, default_qty_type = strategy.percent_of_equity, default_qty_value = 395) float maFast = ta.sma(close, 14) float maSlow = ta.sma(close, 28) if ta.crossover(maFast, maSlow)     strategy.entry("Long", strategy.long) if ta.crossunder(maFast, maSlow)     strategy.entry("Short", strategy.short) changePercent(v1, v2) =>     float result = (v1 - v2) * 100 / math.abs(v2) // exit when we're 10% away from a margin call, to prevent it. if math.abs(changePercent(close, strategy.margin_liquidation_price)) <= 10     strategy.close("Long")     strategy.close("Short") ``` -------------------------------- ### Get Derivative Root with syminfo.root (Pine Script) Source: https://www.tradingview.com/pine-script-reference/v6 This Pine Script snippet shows how to retrieve the root symbol for derivatives like futures contracts using syminfo.root. For non-derivative symbols, it returns the same value as syminfo.ticker. The example displays the root symbol as a label on the chart. ```pine //@version=6 indicator("syminfo.root") // If the current chart symbol is continuous futures ('ES1!'), it would display 'ES'. if barstate.islastconfirmedhistory     label.new(bar_index, high, syminfo.root) ``` -------------------------------- ### Example: Setting a Table Cell Tooltip in Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to create a table and set a tooltip for a specific cell using the table.cell_set_tooltip function. Ensure the table and cell are initialized before setting the tooltip. ```pinescript //@version=6 indicator("TABLE example") var tLog = table.new(position = position.top_left, rows = 1, columns = 2, bgcolor = color.yellow, border_width=1) table.cell(tLog, row = 0, column = 0, text = "sometext", text_color = color.blue) table.cell_set_tooltip(tLog, row = 0, column = 0, tooltip = "sometext") ``` -------------------------------- ### Get Trading Day Timestamp with time_tradingday (Pine Script) Source: https://www.tradingview.com/pine-script-reference/v6 The `time_tradingday` variable returns the timestamp for 00:00 UTC of the current trading day. It is useful for handling overnight sessions and different timeframes. The example demonstrates its use in identifying Fridays and comparing it with the regular day of the week. ```pine-script //@version=6 indicator("Friday session") //@variable The day of week, based on the current `time_tradingday` value.  //          Uses "UTC+0" to return the daily session's timestamp at 00:00 UTC.  int tradingDayOfWeek = dayofweek(time_tradingday, "UTC+0") //@variable Returns `true` if the `dayofweek` represents Friday, in exchange time.  //          It might never return `true` on overnight symbols, depending on the timeframe, since the Friday session //          starts on Thursday. bool isFriday = dayofweek == dayofweek.friday //@variable Returns `true` if the `tradingDayOfWeek` is Friday.  //          Differs from `isFriday` on symbols with overnight sessions and for timeframes > "1D" on others.  bool isFridaySession = tradingDayOfWeek == dayofweek.friday // Create a horizontal line at the `dayofweek.friday` value. hline(dayofweek.friday, "Friday value", color.gray, hline.style_dashed, 2) // Plot the `dayofweek` and `tradingDayOfWeek` for comparison. plot(dayofweek, "Day of week", color.blue, 2) plot(tradingDayOfWeek, "Trading day", color.teal, 3) // Highlight the background when `isFriday` and `isFridaySession` occur. bgcolor(isFriday ? color.new(color.blue, 90) : na, title = "isFriday highlight") bgcolor(isFridaySession ? color.new(color.teal, 80) : na, title = "isFridaySession highlight") ```