### Calculate Buy and Hold Return in Account Currency Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates calculating a buy and hold return percentage using `strategy.convert_to_account` to ensure calculations are based on the strategy's account currency, starting from a user-defined date. ```pinescript // Calculates the "Buy and hold return" using your account's currency. //@version=6 strategy("`strategy.convert_to_account` Example 2", currency = currency.EUR) dateInput = input.time(timestamp("20 Jul 2021 00:00 +0300"), "From Date", confirm = true) buyAndHoldReturnPct(fromDate) =>     if time >= fromDate         money = close * syminfo.pointvalue         var initialBal = strategy.convert_to_account(money)         (strategy.convert_to_account(money) - initialBal) / initialBal * 100 plot(buyAndHoldReturnPct(dateInput)) ``` -------------------------------- ### Pine Script input() function example Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates various uses of the input() function to configure a script's behavior, including boolean switches, length and source selection, price level input, color selection, and text messages. Ensure inputs are assigned to variables for use within the script. ```pine //@version=6 indicator("input", overlay=true) i_switch = input(true, "On/Off") plot(i_switch ? open : na) i_len = input(7, "Length") i_src = input(close, "Source") plot(ta.sma(i_src, i_len)) i_border = input(142.50, "Price Border") hline(i_border) bgcolor(close > i_border ? color.green : color.red) i_col = input(color.red, "Plot Color") plot(close, color=i_col) i_text = input("Hello!", "Message") l = label.new(bar_index, high, text=i_text) label.delete(l[1]) ``` -------------------------------- ### strategy.entry() - Market Order Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates how to use strategy.entry() to place market orders for long and short positions based on moving average crossovers. ```APIDOC ## strategy.entry() - Market Order ### Description Places a market order to enter a trade. This function can be used to open new positions or to close existing ones by entering in the opposite direction. ### Method strategy.entry(id, direction, qty, when, comment, alert_message, stop, limit, oca_name, oca_type, when_open, when_close) ### Parameters - **id** (string) - Unique identifier for the entry order. - **direction** (strategy.long | strategy.short) - The direction of the trade to enter. - **qty** (float, optional) - The quantity of the base asset to trade. Defaults to strategy.equity. - **when** (bool, optional) - Condition to execute the entry. Defaults to true. - **comment** (string, optional) - A comment for the order. - **alert_message** (string, optional) - Message for alerts. - **stop** (float, optional) - Stop loss price. - **limit** (float, optional) - Limit price. - **oca_name** (string, optional) - OCA group name. - **oca_type** (const, optional) - OCA group type. - **when_open** (bool, optional) - Condition to open a position. - **when_close** (bool, optional) - Condition to close a position. ### 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) ``` ### Response This function does not return a value directly but modifies the strategy's state by placing orders. ``` -------------------------------- ### strategy.entry() - Limit Order Example Source: https://www.tradingview.com/pine-script-reference/v6 Illustrates using strategy.entry() with a limit price to place limit orders, including canceling existing orders. ```APIDOC ## strategy.entry() - Limit Order ### Description Places a limit order to enter a trade at a specific price. This example also shows how to cancel existing orders before placing a new limit order. ### Method strategy.entry(id, direction, qty, when, comment, alert_message, stop, limit, oca_name, oca_type, when_open, when_close) ### Parameters - **id** (string) - Unique identifier for the entry order. - **direction** (strategy.long | strategy.short) - The direction of the trade to enter. - **qty** (float, optional) - The quantity of the base asset to trade. Defaults to strategy.equity. - **when** (bool, optional) - Condition to execute the entry. Defaults to true. - **comment** (string, optional) - A comment for the order. - **alert_message** (string, optional) - Message for alerts. - **stop** (float, optional) - Stop loss price. - **limit** (float, optional) - Limit price. If specified, the order will be a limit order. - **oca_name** (string, optional) - OCA group name. - **oca_type** (const, optional) - OCA group type. - **when_open** (bool, optional) - Condition to open a position. - **when_close** (bool, optional) - Condition to close a position. ### 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 var line longLimit = na var line shortLimit = na 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) ``` ### Response This function does not return a value directly but modifies the strategy's state by placing orders. ``` -------------------------------- ### Addition Assignment Operator (+=) Example Source: https://www.tradingview.com/pine-script-reference/v6 Provides an example of the addition assignment operator, which adds a value to a variable and updates the variable with the sum. ```pine //@version=6 indicator("+=") // Equals to expr1 = expr1 + expr2. a = 2 b = 3 a += b // Result: a = 5. plot(a) ``` -------------------------------- ### Color from Gradient Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates using `color.from_gradient` to create two different color series based on `close` price and RSI values, applying them to plots. ```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) ``` -------------------------------- ### Modulo Assignment Operator (%=) Example Source: https://www.tradingview.com/pine-script-reference/v6 Illustrates the modulo assignment operator, which calculates the remainder of a division and assigns it back to the original variable. ```pine //@version=6 indicator("%=") // Equals to expr1 = expr1 % expr2. a = 3 b = 3 a %= b // Result: a = 0. plot(a) ``` -------------------------------- ### Division Assignment Operator (/=) Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates the division assignment operator, a concise way to divide a variable by a value and update the variable with the result. ```pine //@version=6 indicator("/=") // Equals to expr1 = expr1 / expr2. float a = 3.0 b = 3 a /= b // Result: a = 1. plot(a) ``` -------------------------------- ### Plot Blue Component of Color.blue Source: https://www.tradingview.com/pine-script-reference/v6 Example demonstrating how to plot the blue component of the predefined `color.blue` constant. ```pinescript //@version=6 indicator("color.b",overlay=true) plot(color.b(color.blue)) ``` -------------------------------- ### Implement Trailing Stop Loss with strategy.exit() Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates setting up a trailing stop loss using strategy.exit(). It includes logic for drawing an activation line and updating the trailing stop price as the trade moves favorably. The trade is closed with a market order if the trailing stop does not activate within a specified number of bars. ```pine 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) ``` -------------------------------- ### Get Closed Trade Entry Price (Example 1) - Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Use `strategy.closedtrades.entry_price()` to get the price at which a closed trade was entered. This example plots the entry price of the latest long trade. Ensure the `trade_num` is valid. ```javascript //@version=6 strategy("strategy.closedtrades.entry_price Example 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") // Return the entry price for the latest entry. entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1) plot(entryPrice, "Long entry price") ``` -------------------------------- ### Get Trading Day Timestamp with time_tradingday Source: https://www.tradingview.com/pine-script-reference/v6 Use `time_tradingday` to get the 00:00 UTC UNIX timestamp of the current trading day. This is particularly useful for handling overnight sessions where a trading day might start on the previous calendar day. It differs from `time` by always returning the start of the trading day in UTC. ```pinescript //@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") ``` -------------------------------- ### 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 for the first bar. ```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 ``` -------------------------------- ### Place Limit Orders with strategy.entry() Source: https://www.tradingview.com/pine-script-reference/v6 Use strategy.entry() with the 'limit' parameter to place limit orders. This example shows how to set limit orders at a specified offset from the current close price and includes visual indicators for the limit levels. ```pinescript @version=6  strategy("Limit order strategy", overlay=true, margin_long=100, margin_short=100)  //@variable The distance from the `close` price for each limit order.  float limitOffsetInput = input.int(100, "Limit 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) =>      color col = isLong ? color.blue : color.red      label.new(         bar_index, price, (isLong ? "Long" : "Short" ) + " 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 line IDs.  var line longLimit  = na  var line shortLimit = 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)      // Cancel any unfilled sell orders with the specified ID.      strategy.cancel("My Short Entry ID")      //@variable The limit price level. Its value is `limitOffsetInput` ticks below the current `close`.      float limitLevel = close - limitOffsetInput      // Place a long limit order to close the short trade and enter a long position at the `limitLevel`.      strategy.entry("My Long Entry ID", strategy.long, limit = limitLevel)      // Make new drawings for the long limit and stop extending the `shortLimit` line.      longLimit := drawLimit(limitLevel, isLong = true)      shortLimit.stopExtend()  if ta.crossunder(sma14, sma28)      // Cancel any unfilled buy orders with the specified ID.      strategy.cancel("My Long Entry ID")      //@variable The limit price level. Its value is `limitOffsetInput` ticks above the current `close`.      float limitLevel = close + limitOffsetInput      // Place a short limit order to close the long trade and enter a short position at the `limitLevel`.      strategy.entry("My Short Entry ID", strategy.short, limit = limitLevel)      // Make new drawings for the short limit and stop extending the `shortLimit` line.      shortLimit := drawLimit(limitLevel, isLong = false)      longLimit.stopExtend()  ``` -------------------------------- ### Get Matrix Element by Index Source: https://www.tradingview.com/pine-script-reference/v6 Retrieves the value of a matrix element at a specific row and column index. Matrix 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 points using time and price inputs and then constructs the polyline. Labels are added to mark each point. ```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) ``` -------------------------------- ### Calculate Parabolic SAR in Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Implement the Parabolic SAR indicator using ta.sar() with specified start, increment, and maximum values. This example plots the SAR using cross style. ```pine //@version=6 indicator("ta.sar") plot(ta.sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3) // The same on Pine Script® pine_sar(start, inc, max) =>     var float result = na     var float maxMin = na     var float acceleration = na     var bool isBelow = false     bool isFirstTrendBar = false     if bar_index == 1         if close > close[1]             isBelow := true             maxMin := high             result := low[1]         else             isBelow := false             maxMin := low             result := high[1]         isFirstTrendBar := true         acceleration := start     result := result + acceleration * (maxMin - result)     if isBelow         if result > low             isFirstTrendBar := true             isBelow := false             result := math.max(high, maxMin)             maxMin := low             acceleration := start     else         if result < high             isFirstTrendBar := true             isBelow := true             result := math.min(low, maxMin)             maxMin := high             acceleration := start                  if not isFirstTrendBar         if isBelow             if high > maxMin                 maxMin := high                 acceleration := math.min(acceleration + inc, max)         else             if low < maxMin                 maxMin := low                 acceleration := math.min(acceleration + inc, max)     if isBelow         result := math.min(result, low[1])         if bar_index > 1             result := math.min(result, low[2])              else         result := math.max(result, high[1])         if bar_index > 1             result := math.max(result, high[2])     result plot(pine_sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3) ``` -------------------------------- ### Delete all boxes on chart Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to retrieve all existing boxes on the chart and delete them. It uses `box.all` to get an array of boxes and then iterates through it to delete each one. Note that `box.all` returns a read-only array. ```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)) ``` -------------------------------- ### Display Analyst Recommendations in a Table Source: https://www.tradingview.com/pine-script-reference/v6 This example demonstrates how to create and populate a table with analyst recommendation data, including 'Strong Buy' ratings. It requires the 'syminfo' namespace functions and should be used on the last confirmed history bar. ```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)  ``` -------------------------------- ### Get Symbol Prefix - Pine Script Source: https://www.tradingview.com/pine-script-reference/v6 Retrieves the exchange prefix of the current chart's symbol. For example, if the symbol is 'BATS:MSFT', this will return 'BATS'. This is useful for differentiating symbols across different exchanges. ```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) ``` -------------------------------- ### 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 only if no position is currently open. ```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 First Order", strategy.long) ``` -------------------------------- ### Get Commission for a Closed Trade 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 index, starting from zero for the oldest trade. Ensure commission is configured in the strategy settings. ```pine //@version=6 strategy("`strategy.closedtrades.commission`Example",commission_type=strategy.commission.percent,commission_value=0.1) //Strategycallstoenterlongtradesevery15barsandexitlongtradesevery20bars. ifbar_index%15==0 strategy.entry("Long",strategy.long) ifbar_index%20==0 strategy.close("Long") //Plottotalfeesforthelatestclosedtrade. plot(strategy.closedtrades.commission(strategy.closedtrades-1)) ``` -------------------------------- ### Create a Limit Order with strategy.entry() Source: https://www.tradingview.com/pine-script-reference/v6 Specify the `limit` parameter to create a limit order. This order will execute at the specified limit price or better after the market price reaches it. ```pinescript //@version=6 strategy("My Strategy", overlay=true) // Buy limit order at 100.0 strategy.entry("Buy Limit", strategy.long, qty=10, limit=100.0) // Sell limit order at 150.0 strategy.entry("Sell Limit", strategy.short, qty=10, limit=150.0) ``` -------------------------------- ### Get Entry Bar Index of a Closed Trade Source: https://www.tradingview.com/pine-script-reference/v6 Retrieve the bar index where a closed trade entered using `strategy.closedtrades.entry_bar_index(trade_num)`. The `trade_num` argument specifies the trade index, starting from zero. This is useful for calculating trade duration or analyzing entry timing. ```pine //@version=6 strategy("strategy.closedtrades.entry_bar_indexExample") //Enterlongtradesonthreerisingbars;exitontwofallingbars. ifta.rising(close,3) strategy.entry("Long",strategy.long) ifta.falling(close,2) strategy.close("Long") //Functionthatcalculatestheaverageamountofbarsinatrade. avgBarsPerTrade()=> sumBarsPerTrade=0 fortradeNo=0tostrategy.closedtrades-1 //Loopthroughallclosedtrades,startingwiththeoldest. sumBarsPerTrade+=strategy.closedtrades.exit_bar_index(tradeNo)-strategy.closedtrades.entry_bar_index(tradeNo)+1 result=nz(sumBarsPerTrade/strategy.closedtrades) plot(avgBarsPerTrade()) ``` -------------------------------- ### varip Variable Initialization Example Source: https://www.tradingview.com/pine-script-reference/v6 Demonstrates basic varip usage for an integer variable that increments on each bar. Note that 'varip' variables behave like 'var' on historical bars but differ on real-time bars. ```pinescript //@version=6 indicator("varip") varip int v = -1 v := v + 1 plot(v) ``` -------------------------------- ### Use Enum as Map Keys Source: https://www.tradingview.com/pine-script-reference/v6 Enums can be used as keys in maps to restrict the allowed values. This example defines an enum 'symbols' for ticker IDs and uses it as the key type for a map storing float values. It demonstrates putting and getting data from the map using enum fields. ```pinescript //@version=6 indicator("Mapwithenumkeys") //@enumContainsfieldswithtitlesrepresentingtickerIDs. //@fieldaaplHasanAppletickerIDasitstitle. //@fieldtslaHasaTeslatickerIDasitstitle. //@fieldamznHasanAmazontickerIDasitstitle. enumsymbols aapl="NASDAQ:AAPL" tsla="NASDAQ:TSLA" amzn="NASDAQ:AMZN" //@variableAmapthatacceptsfieldsfromthe`symbols`enumaskeysand"float"values. mapdata=map.new() //Putkey-valuepairsintothe`data`map. data.put(symbols.aapl,request.security(str.tostring(symbols.aapl),timeframe.period,close)) data.put(symbols.tsla,request.security(str.tostring(symbols.tsla),timeframe.period,close)) data.put(symbols.amzn,request.security(str.tostring(symbols.amzn),timeframe.period,close)) //Plotthevaluefromthe`data`mapaccessedbythe`symbols.aapl`key. plot(data.get(symbols.aapl)) ``` -------------------------------- ### Create a Market Order with strategy.entry() Source: https://www.tradingview.com/pine-script-reference/v6 Use strategy.entry() without limit or stop parameters to create a market order that executes on the next tick. This is the default behavior for opening or adding to a position. ```pinescript //@version=6 strategy("My Strategy", overlay=true) if strategy.position_size == 0 strategy.entry("Buy", strategy.long, qty=10) strategy.entry("Sell", strategy.short, qty=10) ``` -------------------------------- ### Implement Bracket Orders with strategy.exit() Source: https://www.tradingview.com/pine-script-reference/v6 Use this snippet to set up take-profit and stop-loss orders simultaneously with an entry order. Define profit and loss distances in ticks from the entry price. ```pinescript //@version=6 strategy("Exitubracketustrategy",uoverlayu=utrue)u //uInputsuthatudefineutheuprofituandulossuamountuofueachutradeuasuautickudistanceufromutheuentryuprice.u intuprofitDistanceInputu=uinput.int(100,u"Profitudistance,uinuticks",u1)u intulossDistanceInputuu=uinput.int(100,u"Lossudistance,uinuticks",u1)u //uVariablesutoutrackutheutake-profituandustop-lossuprice.u varufloatutakeProfitu=unau varufloatustopLossuu=unau //uCalculateuau14-baruandu28-barumovinguaverageuofu`close`uprices.u floatusma14u=uta.sma(close,u14)u floatusma28u=uta.sma(close,u28)u ifuta.crossover(sma14,usma28)uandustrategy.opentradesu==u0u ut//uPlaceuaumarketuorderutouenteruaulonguposition.u utstrategy.entry("MyuLonguEntryuID",ustrategy.long)u ut//uPlaceuautake-profituandustop-lossuorderuwhenutheuentryuorderufills.u utstrategy.exit("MyuLonguExituID",u"MyuLonguEntryuID",uprofitu=uprofitDistanceInput,ulossu=ulossDistanceInput)u ifuta.change(strategy.opentrades)u==u1u ut//@variableuTheulonguentryuprice.u utfloatuentryPriceu=ustrategy.opentrades.entry_price(0)u ut//uUpdateutheu`takeProfit`uandu`stopLoss`uvalues.u uttakeProfitu:=uentryPriceu+uprofitDistanceInputu*usyminfo.minticku utstopLossuu:=uentryPriceu-ulossDistanceInputu*usyminfo.minticku ifuta.change(strategy.closedtrades)u==u1u ut//uResetutheu`takeProfit`uandu`stopLoss`.u uttakeProfitu:=unau utstopLossuu:=unau //uPlotutheu`takeProfit`uandu`stopLoss`.u plot(takeProfit,u"Take-profitulevel",ucolor.green,u2,uplot.style_linebr)u plot(stopLoss,u"Stop-lossulevel",ucolor.red,u2,uplot.style_linebr)u ```