### Exit Bracket Strategy Example Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates how to set up take-profit and stop-loss orders using `strategy.exit()` based on tick distance from the entry price. It calculates moving averages to determine entry conditions. ```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 ``` -------------------------------- ### Example: Using syminfo.ticker and syminfo.prefix Source: https://cn.tradingview.com/pine-script-reference/v6 Illustrates the usage of `syminfo.ticker` and `syminfo.prefix` to build a ticker for `request.security`. This example shows how to combine exchange and ticker information to fetch data for a specific symbol and timeframe. ```pinescript //@version=6 indicator("syminfo.ticker fun", overlay=true) i_sym = input.symbol("NASDAQ:AAPL") pref = syminfo.prefix(i_sym) tick = syminfo.ticker(i_sym) t = ticker.new(pref, tick, session.extended) s = request.security(t, "1D", close) plot(s) ``` -------------------------------- ### Var Keyword Example Source: https://cn.tradingview.com/pine-script-reference/v6 This example shows how to use the 'var' keyword to initialize variables that retain their state across bar updates. 'a' holds the first bar's close, 'b' holds the first green bar's close, and 'c' holds the tenth green bar's close. ```pinescript //@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)  ``` -------------------------------- ### Example: Plotting Quandl Data Source: https://cn.tradingview.com/pine-script-reference/v6 An example demonstrating how to request and plot data using the deprecated request.quandl() function with specific parameters for merging gaps and column index. ```pinescript @version=6 indicator("request.quandl") f = request.quandl("CFTC/SB_FO_ALL", barmerge.gaps_off, 0) plot(f) ``` -------------------------------- ### Display Analyst Recommendations with syminfo.recommendations_date Source: https://cn.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 last recommendation start date and formats it for display. Ensure you are using version 6 of Pine Script. ```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 Indicator Example Source: https://cn.tradingview.com/pine-script-reference/v6 A minimal example of an indicator script that sets a title and short title, and plots the closing price. This demonstrates the basic structure required for an indicator. ```pinescript //@version=6 indicator("My script", shorttitle="Script") plot(close) ``` -------------------------------- ### Basic `for` Loop Example Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates a basic `for` loop to count bars where the closing price is above the current closing price. It initializes a result variable to 0 and iterates from 1 up to the specified length, incrementing the result if the condition is met. ```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)) ``` -------------------------------- ### `for` Loop with a Step Source: https://cn.tradingview.com/pine-script-reference/v6 This example shows a `for` loop that iterates with a specific step value. It sums elements from an array at intervals defined by the step. The loop starts at index 0, goes up to index 9, and increments by 5 in each iteration, effectively processing indices 0 and 5. ```pine //@version=6 indicator("`for` loop with a step") a = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) sum = 0.0 for i = 0 to 9 by 5     // Because the step is set to 5, we are adding only the first (0) and the sixth (5) value from the array `a`.     sum += array.get(a, i) plot(sum) ``` -------------------------------- ### User-Defined Type (UDT) Example Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates defining a 'bar' UDT to hold OHLC and time data, and then using it to draw boxes on a chart based on data from a different timeframe. ```pinescript //@version=6 indicator("Multi Time Period Chart", overlay = true)  timeframeInput = input.timeframe("1D")  type bar      float o = open      float h = high      float l = low      float c = close      int   t = time  drawBox(bar b, right) =>      color boxColor = b.c >= b.o ? color.green : color.red      box.new(b.t, b.h, right, b.l, boxColor, xloc = xloc.bar_time, bgcolor = color.new(boxColor, 90))  updateBox(box boxId, bar b) =>      color boxColor = b.c >= b.o ? color.green : color.red      box.set_border_color(boxId, boxColor)      box.set_bgcolor(boxId, color.new(boxColor, 90))      box.set_top(boxId, b.h)      box.set_bottom(boxId, b.l)      box.set_right(boxId, time)  secBar = request.security(syminfo.tickerid, timeframeInput, bar.new())  if not na(secBar)      // To avoid a runtime error, only process data when an object exists.      if not barstate.islast         if timeframe.change(timeframeInput)            // On historical bars, draw a new box in the past when the HTF closes.            drawBox(secBar, time[1])      else         var box lastBox = na         if na(lastBox) or timeframe.change(timeframeInput)           // On the last bar, only draw a new current box the first time we get there or when HTF changes.           lastBox := drawBox(secBar, time)      else           // On other chart updates, use setters to modify the current box.           updateBox(lastBox, secBar)          ``` -------------------------------- ### Delete all boxes using box.all Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates how to retrieve all existing boxes using `box.all` and then delete them. It's useful for clearing the chart of previously drawn boxes. ```pine //@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)) ``` -------------------------------- ### Place Limit Orders with strategy.entry() Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates placing limit orders using `strategy.entry()`. It cancels existing orders and places new limit orders based on moving average crossovers, visualizing the limit levels with labels and lines. ```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`. ``` -------------------------------- ### Get Trading Day of Week with time_tradingday Source: https://cn.tradingview.com/pine-script-reference/v6 Use `time_tradingday` to get the timestamp of the current bar's trading day at 00:00 UTC. This is useful for handling overnight sessions where the trading day may start on a previous calendar day. The example highlights differences between `dayofweek` and `time_tradingday` for Friday detection. ```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") ``` -------------------------------- ### Delete All Lines with line.all Source: https://cn.tradingview.com/pine-script-reference/v6 This example shows how to get all current lines drawn by the script using `line.all` and then delete them. This is useful for cleaning up the chart dynamically. ```pinescript //@version=6 indicator("line.all") //delete all lines line.new(bar_index - 10, close, bar_index, close) a_allLines = line.all if array.size(a_allLines) > 0     for i = 0 to array.size(a_allLines) - 1         line.delete(array.get(a_allLines, i)) ``` -------------------------------- ### Get Timeframe Multiplier Source: https://cn.tradingview.com/pine-script-reference/v6 Returns the multiplier for the current timeframe. For example, '60' for 60 minutes, '1' for daily, '5' for 5 days, '12' for 12 months. ```pinescript timeframe.multiplier ``` -------------------------------- ### Place Limit and Stop Orders with strategy.order() Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates placing bracket orders (limit and stop) to manage a long position. It calculates profit and loss levels based on the entry price and uses OCA groups to ensure only one order is active. ```pine //@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 ``` -------------------------------- ### Create and Use Label Objects Source: https://cn.tradingview.com/pine-script-reference/v6 Demonstrates the creation of label objects using label.new(). It shows initializing an empty label ID, creating a label with default values, and creating a label with text on the last confirmed bar. ```pine //@version=6 indicator("label") // Empty `label1` label ID. var label label1 = na // `label` type is unnecessary because `label.new()` returns "label" type. var label2 = label.new(na, na, na) if barstate.islastconfirmedhistory label3 = label.new(bar_index, high, text = "label3 text") ``` -------------------------------- ### Get Array Element by Index in Pine Script Source: https://cn.tradingview.com/pine-script-reference/v6 Retrieves the value of an element at a specific index. Supports both positive and negative indexing from the start and end of the array, respectively. ```pinescript //@version=6 indicator("array.get example") a = array.new_float(0) for i = 0 to 9 array.push(a, close[i] - open[i]) plot(array.get(a, 9)) ``` -------------------------------- ### Example: Using syminfo.prefix and syminfo.ticker Source: https://cn.tradingview.com/pine-script-reference/v6 Demonstrates how to use `syminfo.prefix` and `syminfo.ticker` to construct a ticker ID for requesting historical data using `request.security`. This is a common pattern for working with symbols from different exchanges. ```pinescript //@version=6 indicator("syminfo.prefix fun", overlay=true) i_sym = input.symbol("NASDAQ:AAPL") pref = syminfo.prefix(i_sym) tick = syminfo.ticker(i_sym) t = ticker.new(pref, tick, session.extended) s = request.security(t, "1D", close) plot(s) ``` -------------------------------- ### Get Entry Price of Closed Trade Source: https://cn.tradingview.com/pine-script-reference/v6 Retrieves the entry price for a specific closed trade. Use `strategy.closedtrades - 1` to get the most recent closed trade. ```pinescript //@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") ``` ```pinescript // Calculates the average profit percentage for all closed trades. //@version=6 strategy("strategy.closedtrades.entry_price Example 2") // Strategy calls to create single short and long trades if bar_index == last_bar_index - 15     strategy.entry("Long Entry", strategy.long) else if bar_index == last_bar_index - 10     strategy.close("Long Entry")     strategy.entry("Short", strategy.short) else if bar_index == last_bar_index - 5     strategy.close("Short") // Calculate profit for both closed trades. profitPct = 0.0 for tradeNo = 0 to strategy.closedtrades - 1     entryP = strategy.closedtrades.entry_price(tradeNo)     exitP = strategy.closedtrades.exit_price(tradeNo)     profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100 // Calculate average profit percent for both closed trades. avgProfitPct = nz(profitPct / strategy.closedtrades) plot(avgProfitPct) ``` -------------------------------- ### Open Market Orders with strategy.entry() Source: https://cn.tradingview.com/pine-script-reference/v6 Use `strategy.entry()` to place market orders for opening or closing trades. This example demonstrates entering long positions on a crossover and short positions on a crossunder of two moving averages. ```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 close the short trade and enter a long position when `sma14` crosses over `sma28`. if ta.crossover(sma14, sma28)     strategy.entry("My Long Entry ID", strategy.long) // Place a market order to close the long trade and enter a short position when `sma14` crosses under `sma28`. if ta.crossunder(sma14, sma28)     strategy.entry("My Short Entry ID", strategy.short) ``` -------------------------------- ### Place Market Orders with strategy.order() Source: https://cn.tradingview.com/pine-script-reference/v6 Use this snippet to place market orders for entering or exiting positions. It demonstrates how to open a long position on a crossover and close it on a crossunder. ```pine //@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) ``` -------------------------------- ### Create and Use Box Objects Source: https://cn.tradingview.com/pine-script-reference/v6 Demonstrates the creation of box objects using box.new(). It shows initializing an empty box ID, creating a box with default values, and creating a box with specified coordinates and x-axis location. ```pine //@version=6 indicator("box") // Empty `box1` box ID. var box box1 = na // `box` type is unnecessary because `box.new()` returns a "box" type. var box2 = box.new(na, na, na, na) box3 = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time) ``` -------------------------------- ### Get and Append Label Text Source: https://cn.tradingview.com/pine-script-reference/v6 Shows how to retrieve the text from an existing label and append new text to it for a new label. Ensure the label object is valid before attempting to get its text. ```pinescript //@version=6 indicator("label.get_text") my_label = label.new(time, open, text="Open bar text", xloc=xloc.bar_time) a = label.get_text(my_label) label.new(time, close, text = a + " new", xloc=xloc.bar_time) ``` -------------------------------- ### Calculate Buy and Hold Return in Account Currency Source: https://cn.tradingview.com/pine-script-reference/v6 This example calculates the 'Buy and Hold' return percentage using the strategy's account currency. It converts the initial investment value to the account currency and then calculates the percentage change relative to that initial value. This is useful for comparing strategy performance against a simple buy and hold investment in the same currency. ```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)) ``` -------------------------------- ### Fill Array with Value in Pine Script Source: https://cn.tradingview.com/pine-script-reference/v6 Sets array elements to a specified value. Can fill the entire array, from a start index, or within a range defined by start and end indices. ```pinescript //@version=6 indicator("array.fill example") a = array.new_float(10) array.fill(a, close) plot(array.sum(a)) ``` -------------------------------- ### Strategy with Percent of Equity Quantity Type Source: https://cn.tradingview.com/pine-script-reference/v6 This example demonstrates how to use strategy.percent_of_equity for the default_qty_type parameter in a strategy declaration. It shows how trades are entered using a percentage of equity when the 'qty' parameter is not explicitly defined in strategy.entry() or strategy.order(). ```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")  ``` -------------------------------- ### Create an Integer Matrix with Initial Values Source: https://cn.tradingview.com/pine-script-reference/v6 Use `matrix.new()` to create a matrix with a specified number of rows and columns, initializing all elements to a given value. This is useful for setting up matrices with default data. ```pinescript //@version=6 indicator("`matrix.new()` Example 1") // Create a 2x3 (2 rows x 3 columns) "int" matrix with values zero. var m = matrix.new(2, 3, 0) // Display using a label. if barstate.islastconfirmedhistory     label.new(bar_index, high, str.tostring(m)) ``` -------------------------------- ### strategy.entry() Source: https://cn.tradingview.com/pine-script-reference/v6 Creates a new order to open a position or to add to an existing position. If an unfilled order with the same `id` exists, calling this command modifies that order. The type of order generated depends on the `limit` and `stop` parameters. ```APIDOC ## strategy.entry() ### Description Creates a new order to open a position or to add to an existing position. If an unfilled order with the same `id` exists, calling this command modifies that order. The type of order generated depends on the `limit` and `stop` parameters. If the call does not include `limit` or `stop` parameters, it creates a market order to be executed on the next tick. If the call specifies a `limit` value but not a `stop` value, it places a limit order that executes when the market price reaches the `limit` value or better. If the call specifies a `stop` value but not a `limit` value, it places a stop order that executes when the market price reaches the `stop` value or worse. If the call includes both `limit` and `stop` parameters, it creates a stop-limit order that only generates a limit order at the `limit` price after the market price reaches the `stop` value or worse. Orders from this command are affected by the `pyramiding` argument of the `strategy()` declaration statement. Pyramiding specifies the number of concurrent entries allowed for each position. For example, with `pyramiding = 3`, the strategy can have at most three entries, and this command cannot create an order to open additional entries until at least one existing entry is closed. By default, when the strategy executes an order in this command in the opposite direction of the current market position, it reverses the position. Users can change this behavior by specifying allowed directions with the `strategy.risk_allow_entry_in()` function. ### Method ``` strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) ``` ### Parameters * **id** (series string) - Order identifier. If the strategy opens a new position after the order is filled, the order ID will become the value of `strategy.position_entry_name`. Strategy commands can reference order IDs to cancel or modify pending orders and to generate exit orders for specific unfilled trades. The order ID will be displayed in the Strategy Tester and on the chart unless the command specifies a `comment` value. * **direction** (series strategy_direction) - The direction of the trade. Possible values: `strategy.long` for long trades, `strategy.short` for short trades. * **qty** (series int/float) - Optional. The number of contracts/shares/lots/units to be traded when the order is filled. Default is `na`, which means the command uses the `default_qty_type` and `default_qty_value` arguments of the `strategy()` declaration statement to determine the quantity. * **limit** (series int/float) - Optional. The limit price of the order. If specified, the command creates a limit or stop-limit order, depending on whether a `stop` value is also specified. Default is `na`, meaning the generated order is not of the limit or stop-limit type. * **stop** (series int/float) - Optional. The stop price of the order. If specified, the command creates a stop or stop-limit order, depending on whether a `limit` value is also specified. Default is `na`, meaning the generated order is not of the stop or stop-limit type. * **oca_name** (series string) - Optional. The name of the "One Cancels All" (OCA) group for the order. When pending orders with the same `oca_name` and `oca_type` execute, the order affects all unfilled orders within that group. Default is an empty string, indicating the order does not belong to an OCA group. * **oca_type** (input string) - Optional. Specifies the behavior of unfilled orders when another pending order with the same `oca_name` and `oca_type` value executes. Possible values: `strategy.oca.cancel`, `strategy.oca.reduce`, `strategy.oca.none`. Default is `strategy.oca.none`. * **comment** (series string) - Optional. An additional description for filled orders. If the value is not an empty string, the Strategy Tester and the chart will display this text for the order instead of the specified `id`. Default is an empty string. * **alert_message** (series string) - Optional. Custom text for alerts triggered when an order is filled. If the "Message" field of the "Create Alert" dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message will be replaced with this text. Default is an empty string. * **disable_alert** (series bool) - Optional. If `true` when the command creates an order, the strategy will not trigger an alert when that order is filled. This argument accepts a "series" value, meaning users can control which orders trigger alerts upon execution. Default is `false`. ### Request Example ```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 close the short trade and enter a long position when `sma14` crosses over `sma28`. if ta.crossover(sma14, sma28) strategy.entry("My Long Entry ID", strategy.long) // Place a market order to close the long trade and enter a short position when `sma14` crosses under `sma28`. if ta.crossunder(sma14, sma28) strategy.entry("My Short Entry ID", strategy.short) ``` ### Response #### Success Response (200) This function returns `void`. #### Response Example N/A (void return type) ``` -------------------------------- ### ta.min() Source: https://cn.tradingview.com/pine-script-reference/v6 Returns the historical lowest value of the `source` from the start of the chart up to the current bar. ```APIDOC ## ta.min() ### Description Returns the historical lowest value of the `source` from the start of the chart up to the current bar. ### Syntax ``` ta.min(source) → series float ``` ### Parameters * **source** (series int/float) - The source for the calculation. ### Remarks `na` ``` -------------------------------- ### ta.max() Source: https://cn.tradingview.com/pine-script-reference/v6 Returns the historical highest value of the `source` from the start of the chart up to the current bar. ```APIDOC ## ta.max() ### Description Returns the historical highest value of the `source` from the start of the chart up to the current bar. ### Syntax ``` ta.max(source) → series float ``` ### Parameters * **source** (series int/float) - The source for the calculation. ### Remarks `na` ```