#] #] ********************* #] "$d_web"'CompLangs/PineScript/0_PineScript notes.txt' www.BillHowell.ca 14Dec2020 initial see also "$d_mktData"'1_mktData download instructions.txt' 24************************24 24************************24 # Table of Contents, generated by : # $ grep "^#]" "$d_web"'CompLangs/PineScript/0_PineScript notes.txt' | sed 's/^#\]/ /' ********************* "$d_web"'CompLangs/PineScript/0_PineScript notes.txt' +-----+ ToDos +-----+ handy functions, lessons hline(base * 1.05, title='5%', color=green, linestyle=solid, linewidth=1) 02Jun2022 squashing of symbolLines - writing at or beyond left edge of chart squashes t_spikes and legends var keyword - compiler creates and initializes the variable only once (persistent value across iterations) colors - for named PineScript colors see How do I plot lines in the future in pine script? +-----+ Comments +-----+ 19Mar2023 search ‘How do I download PineScript data?’ 25Sep2022 download FX-reated data 21Sep2022 PineScript is NOT suited for multiple real plots, as I cannot assign lines to existing axis 21Sep2022 math.pow does not work -> use pow(...) 21Sep2022 IDIOT! - [oil, commodities] versus exchange rates, even USA 20Sep2022 extend, fix PineScript - intl exchange rates versus 10y rate differentials 19Sep2022 from blog to @quantguy : 17Aug2022 algotrading101.com - great description of PineScript [, dis]-advantages 16Aug2022 fix 'Howell - fix symbols, eg rates div 10.txt', add to 'US interest rates' chart 10Aug2022 clean up 'PuetzUWS IntlStkIdxs multi-fractals (version 2).txt' 25Jul2022 normal [IRX.P 13w T-bill, FVX.P 10y T-bond] rates 25Jul2022 plot a modified symbol : FVX.P / 10 20Jun2022 The price[Normal, Rsd] curves should overlap! 19Jun2022 Posting of PineScript "PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020" 16Jun2022 Publish my PineScript "SP500 - Puetz [time, price] multiFractals [detrend, relStdDev] 1926-2020" 16Jun2022 clean up timeFrac < 0.000 14Jun2022 fix timeFrac 13Jun2022 fix priceFrac 13Jun2022 Federal Reserve - debt held, liabilities, capital 12Jun2022 priceRsdBasIdx, drawPriceFrac 11Jun2022 var keyword - causes problems normally, reverts to initial state! use only for fixed constants, but generally a bad idea except special cases 10Jun2022 try setting overlay = true!? 09Jun2022 symbol definitions, siilarities between [time, price]Fractals 09Jun2022 revamp drawPriceFrac() to handle fracLies [below, above] 1.000, using priceRsdBasIdx 07Jun2022 I'm stupid - try again : priceFractal with newline 04Jun2022 matrix.set isn't working in for loop! must individually set? 04Jun2022 priceMin is corrupted!? 04Jun2022 Publish library("HowellLibrary_time_labels", true) 01Jun2022 squashing of symbolLines (again) 30May2022 ary_n_bars - reoptimize for the 100th time.. 30May2022 line.copy - use to convert priceFractals to same approach as timeFractals? 27May2022 Output section 26May2022 24May2022 PineScript, SP500USD chart - multi-fractal on-chart comments 11May-??May2022 Proj-mini 'Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' 23May2022 TradingView - Publish script "SP500USD (time, price) multi-fractals" 23May2022 status - drawPriceFracs() compiles but doesn't work : 23May2022 @fract - use of [vertical, angled] timeFractals 23May2022 didn't work, no idea why : if barstate.islast and i_zone == 1 22May2022 array.from - creats series from a list of [number, str, etc] 21May2022 fracPice - plot Fibonacci mirror - 21May2022 this makes NO SENSE! Just plot lines!!! 17May2022 drawVerticalLines() 16May2022 KEY!! kodify.net - How to correct TradingView’s ‘end of line without continuation’ error? 13May2022 variable assignment in Pine script 13May2022 search "Pine Script and how to Plot Vertical Lines?" 11May2022 TradingView, jbrothersjr : Revisiting a long term trend line, S&P 500 Index (FX:SPX500) 01Feb2022 Great Pinescript : wugamlo - MACD including 6-period Forecast and Divergences 08Jan2022 edit PineScript in a separate window or tab 21Sep2021 set up multi-symbol charts 19Apr2021 RicardoSantos polynomial script, user input 12Apr2021 array.set 12Apr2021 array.set 11Apr2021 Plotting an exogenous curve in PineScript 21Mar2021 I couldn't publish - House Rules, no links etc 20Mar2021 chart FX-SPX500 features as an 83 year semi-log DETRENDED series (1926-2020) 20Mar2021 Current problems with the script : 20Mar2021 [comment, timeframe, dummy variable]s for "SP500 with 83 year detrended Fibonaccis..." 20Mar2021 Howell Pinescript "SP500 with 83 year detrended Fibonaccis,TNX,CNYU,USOIL,BTCUSD,BEAM pharma" 19Mar2021 Pinescript and arrays - not obvious how to make it work 18Mar2021 Stop - PineScript's own code fails!!!??? 16Mar2021 TradingView standard PineScript for Fibonacci 17Mar2021 search "TradingView PineScript and Mismatched input 'for' expecting 'end of line continuation'." 17Mar2021 search "TradingView PineScript and "cannot call 'array.get' ..." 15Mar2021 PineScript for Turtle Trade of SP500 15Mar2021 to see PineScript built-in functions : 14Dec2020 Awesome statistic commentary!! balipour, Using Moments For Trend and Mean Reversion Trading 24************************24 24************************24 #] +-----+ #] ToDos 19Mar2023 want a "simple" tool to take user forecasts "small-subset" key symbols easy "what-if" scenarios eg Elliot Wave, Puetz, Grossberg, Schumann resonances, merket sentiment etc 19Mar2023 non-TradingView data : [SHCOMP- Yahoo, Fed balance sheet, [govt, business, consumer] debt] 24************************24 #] +-----+ #] handy functions, lessons PineScript built-in functions : go to PineScript editor -> Menu -> ... (more) -> PineScript reference (pop up) -> Built-in functions #] hline(base * 1.05, title='5%', color=green, linestyle=solid, linewidth=1) https://bountify.co/pine-script-for-tradingview-that-draws-horizontal-lines #] 02Jun2022 squashing of symbolLines - writing at or beyond left edge of chart squashes t_spikes and legends example : barFirst_label(n_bars, barsShiftRight, serPrice, priceOffset, txt) => barFirst_label(n_bars, 100, priceMax, -6*txtLineHeight, "Puetz timeFractal [depth, period]s") barsShiftRight == 100 helps avoid a scrunch #] var keyword - compiler creates and initializes the variable only once (persistent value across iterations) The var keyword is a special modifier that instructs the compiler to create and initialize the variable only once. This behavior is very useful in cases where a variable’s value must persist through the iterations of a script across successive bars. For example, suppose we’d like to count the number of green bars on the chart: #] colors - for named PineScript colors see https://www.tradingview.com/pine-script-reference/ -> search "color" -> scroll down menu to color.aqua, continue looking for a color Only ones defined that I can see : color.[black, silver, gray, white, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua, orange] // 19Sep2022 - all of a sudden, math.abs(...) doesn;t work!?!?!, no mention in reference // https://www.tradingview.com/pine-script-reference/v5/#fun_math{dot}abs #] How do I plot lines in the future in pine script? Asked 2 years ago, Modified 10 months ago, Viewed 2k times https://stackoverflow.com/questions/63890304/how-do-i-plot-lines-in-the-future-in-pine-script #] +-----+ 24************************24 #] Comments I give up on Pine Script for programs of even simple complexity. It's not a decent language, it's a waste of time! 18Mar2021 PineScript's own code doesn't work!! - they must be still fixing bugs from an upgrade Jul2020? Help, manual : functions, library : https://www.tradingview.com/pine-script-reference/ Pine Script language : https://www.tradingview.com/pine-script-docs/en/v3/language/ Expressions_declarations_and_statements.html#preventing-na-values-functions-na-and-nz public library : https://www.tradingview.com/pine-script-docs/en/v4/Public_Library.html public library -> from other users +-----+ Debugging tools see "Labels" section of +-----+ https://www.tradingview.com/script/12M8Jqu6-Function-Polynomial-Regression/ Function Polynomial Regression, RicardoSantos, Sep 7, 2020 >> 13Apr2021 - just what I need for array plot approach!!! array.get, array.push +-----+ Some errors I've had The 'resolution' argument is incompatible with functions that have side effects >> label.new -> xloc, yloc not properly specified? The 'end of line without continuation' error : happens when there's an indentation mistake #] +-----+ 24************************24 08******08 #] ??Aug2023 08******08 #] ??Aug2023 08******08 #] ??Aug2023 08******08 #] 17Aug2023 search "PineScript and how do I easily pront out a value?" again, Pinescript is hot!! +-----+ https://stackoverflow.com/questions/63954547/print-a-value-with-label-new-using-pine-script print a value with label.new using pine script Asked 2 years, 11 months ago Modified 2 years, 11 months ago Viewed 10k times Your label is created on the first bar only and then updated on each bar, which is more efficient than continuously creating and deleting the label. So that's ideal, but musn't forget to update the label's text though. Here we also update the label's y position using the highest high in the last 10 bars, plus the true range. We use those values as evaluated on the previous bar so that our label doesn't move up and down during the realtime bar: var label1 = label.new(bar_index, high, "", style=label.style_circle) label.set_xloc(label1, time, xloc.bar_time) label.set_text(label1, text=tostring(diff)) label.set_y(label1, highest(10)[1] + tr[1]) answered Sep 18, 2020 at 12:48 PineCoders-LucF 08******08 #] 17Aug2023 search "PineScript Cannot modify global variable 'seriesMax' in function" +-----+ https://stackoverflow.com/questions/60904563/how-to-change-global-variable-from-function-in-pine-script How to Change global variable from function in pine script? Asked 3 years, 4 months ago Modified 3 months ago Viewed 11k times +--+ Since September 10, 2020 arrays are available in pine. And using that, you can store values created in function in global scope. This works, because writing array elements does not alter the actual array variable's reference. So you just use the global array and modify its content as you would do outside of your function. Arrays have opened many possibilities in pine script. A simple example: // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © wallneradam //@version=4 study("Global variables", overlay=false) // Declare constants to access global variables IDX_STOCH = 0 IDX_RSI = 1 // Initialize an empty array to store variables global = array.new_float(2) // This is the modify the array calculate(period) => v_stoch = stoch(close, high, low, period) v_rsi = rsi(close, period) array.set(global, IDX_STOCH, v_stoch) array.set(global, IDX_RSI, v_rsi) // Call the function any times you want calculate(14) // Plot the results plot(array.get(global, IDX_STOCH), color=color.red) plot(array.get(global, IDX_RSI), color=color.yellow) // Call the function any times you want calculate(14 * 5) // Plot the results plot(array.get(global, IDX_STOCH), color=color.maroon) plot(array.get(global, IDX_RSI), color=color.olive) edited Jan 13 at 13:28 juanmirocks answered Dec 5, 2020 at 10:28 Adam Wallne 08******08 #] 17Aug2023 set base time Puetz factor-of-3 trimeFractal [depth, period]s: +-----+ olde code // tUnix_from_01Jan1970_to_24Oct1929(tUnix_from_01Jan1970) => // math.floor(tUnix_from_01Jan1970 + (1929.5833 - 7.25)*t_year_to_millisecs) int timeLamdaMaxIdx = 0 08******08 #] 16Aug2023 Puetz factor-of-3 trimeFractal [depth, period]s: Puetz factor-of-3 trimeFractal [depth, period]s: 1871-now : (0) 6.336 years; (1) 19.008 years; (3) 57.7.068 years; (4) 503.203 years. 5years : (0) 6.336 years; (1) 19.008 years; (3) 57.7.068 years; (4) 503.203 years. 1year : (0) 6.336 years; (1) 19.008 years; (3) 57.7.068 years; (4) 503.203 years. 6months : (0) 6.336 years; (1) 19.008 years; (3) 57.7.068 years; (4) 503.203 years. $ find "$d_Qndfs" -type f -name "*.ndf" | grep --invert-match "z_Old\|z_Archive" | tr \\n \\0 | xargs -0 -IFILE grep -i --with-filename --line-number 'year_to_days' "FILE" | sed "s|$d_Qndfs||;s|:.*||" | sort -u >"$d_temp"'find-grep-sed temp.txt' 08******08 #] 14Jun2023 search "PineScript and function for starting date" +-----+ https://stackoverflow.com/questions/75948370/how-can-i-add-the-start-date-to-my-table How can I add the Start Date to my Table? Asked 2 months ago Modified 2 months ago Viewed 24 times Use strategy.opentrades and record the time. At the end of your code, just before the Backtester display part : var int MyDate = na if strategy.opentrades == 1 and na(MyDate) MyDate := time You can after modify your MyDate into a string with : str.tostring(dayofmonth(MyDate))+"/"+str.tostring(month(MyDate))+"/"+str.tostring(year(MyDate)) answered Apr 6 at 12:15 G.Lebret i dont know how to give reputation and i think this comment will get deleted again but i really need to say thank you. i was trying around for +10 hours and was not able to find anything helpful around google but this little bit of code from you solved my problem within 30 seconds. thank you so much @g.lebret – Kevin.G Apr 6 at 13:51 @kevin G Glad to help you, just acept the answer. – G.Lebret Apr 6 at 14:02 +-----+ https://stackoverflow.com/questions/75127150/pine-script-starting-an-indicator-plotting-from-a-date-known-after-the-startin Pine script - Starting an indicator plotting from a date known after the starting bar has 'passed' Asked 5 months ago Modified 5 months ago Viewed 54 times Your script is executed on each bar. So, you cannot really go back and plot something with the plot() functions. Your only option is using line but that has its own limitations as you mentioned. Another workaround would be, you do your analysis and identify the start bar index. Then use this as an input and only plot if bar_index > bar_index_start. This of course cannot be automated so someone has to do the analysis first and then input that to the main script. answered Jan 15 at 19:18 vitruvius 14.8k33 gold badges1515 silver badges2525 bronze badges Thanks vitruvius for your support. I need it to be automated, so likely I will use the described 'workaround' (or maybe I'll just describe the event and its impact on the current price in a side table filled when barstate.islast is true). – lp6970 Jan 15 at 19:32 What I find a little bit 'strange' is that an indicator (default one) exists that seems to demonstrate that what I need to do is possible, at least in theory. That indicator is 'VWAP Auto Anchored': the source code is not available, but if you look to the 'Highest-High', 'Lowest-Low', 'Highest-Vol', 'Earnings', 'Dividends', 'Splits' anchors, the result is what I need to do. Thanks anyway. Have a nice long weekend. Cheers from Italy – lp6970 Jan 15 at 19:40 08******08 #] 14Jun2023 create script "SP500 semi-log trend 1926-now" see "$d_web"'CompLangs/PineScript/Howell - SP500 trend 1926-now.txt' relStdDev_plus1 = 1 + 0.0937853 +-----+ olde code # # ********************* # "$d_webRaw"'CompLangs/PineScript/Howell - SP500 semi-log trend 1926-now.txt' # www.BillHowell.ca 14Jun2023 initial # view this file in a text editor, with [constant width font, tab = 3 spaces], no line-wrap 08*****08 #] 14Jun2023 keep it simple! 08******08 #] 19Mar2023 search ‘How do I download PineScript data?’ +-----+ https://quantnomad.com/how-to-grab-data-from-tradingview-charts-and-save-them-as-a-csv-file/ How to Export Data From TradingView Charts and Save It as a CSV File? TradingView / By QuantNomad → Step 1: Add Indicators → Step 2: Launch the Export Chart Data Pop-up Top row above chart -> chart name `V down just to right -> Export chart data -> to "$d_PROJECTS"'economics, markets/market data/unixDate/' → Step 3: Specify Date Format and Export Data From the “Export chart data” pop-up window, select the preferred date format. You’ll be able to select from the following date format options. UNIX timestamp – this option specifies a date and time format of the bars in milliseconds starting the 1st of January 1970 (e.g. “1595311200”). ISO time – this date and time format will show the date and time format in a more human-friendly format (e.g. “2020-07-21T06:00:00Z”). >> Finally! it works with all symbols shown (INCLUDING hidden!, but NOT SP500????) Missing main indicator: SP500? NYET! doesn't show symbol, just 'time,open,high,low,close' exported to : "$d_PROJECTS"'economics, markets/market data/rawCs1 - multi-symbol/' : rawCsv Intl Stock Indices, 1D=1year.txt rawCsv USA mixed market, 1D=1year.txt rawCsv USA rates, inflation, 1M=1872-present.txt rawCsv Intl FX per USD, 1W=5yr.txt rawCsv Intl FX other per USD, 1W=5yr.txt rawCsv Oil&Gas, 1W=5yr.txt rawCsv Pharma, 1W=5yr.txt rawCsv ETH & hi-tech, 1W=5yr.txt To get data, many charts must be added, and some QNial programming needed 08******08 #] 25Sep2022 download FX-reated data see also "$d_mkts"'[interest, exchange] rates/0_exchange rate model notes.txt' 08******08 #] 21Sep2022 PineScript is NOT suited for multiple real plots, as I cannot assign lines to existing axis and all plot lines appear on same axis therefore, split the graphs (actually, do it in QNial) This is a waste of time in PineScript - get the models in QNial, place in PineScript 08******08 #] 21Sep2022 math.pow does not work -> use pow(...) USOIL_detrend = v_USOIL / math.pow(10, -1.6684 + (0.00291 * yrFrac)) line 127: Could not find function or function reference 'math.pow'. >> I just used pow(...) and it worked!!??!!???? NYET : Howell - While the following are for java, maybe a hint for PineScript? +-----+ https://stackoverflow.com/questions/27542765/java-math-pow-is-not-working 1/2 is 0, due to integer division, so Math.pow(16, (1/2) is Math.pow(16, 0), which is 1.0. In order for 1/2 to be evaluated using floating point division, you have to cast either 1 or 2 to double : System.out.println(Math.pow(16, ((double)1/2))); Or use double literal in the first place : System.out.println(Math.pow(16, (1.0/2))); or system.out.println(Math.pow(16, (1/2.0))); answered Dec 18, 2014 at 9:06 Eran +-----+ https://stackoverflow.com/questions/63099365/pow-does-not-work-with-variable-exponent-1-n-nth-root The exponent should be a float, try using pow(M,1./N). answered Jul 26, 2020 at 13:40 alexgrover 08******08 #] 21Sep2022 IDIOT! - [oil, commodities] versus exchange rates, even USA TradingView: M 2012 NQCIER NASDAQ commodity benchmark index ER M 2012 NQCIPEER NASDAQ petroleum benchmark index ER M = monthly data, only shows for time.periods >= 5 years! From DXY chart I removed : [FX_IDC:USDRUB, TVC:GBPUSD] I removed separate lines for 10Y rates, retained only d_(TNX-10Y) added [TVC: USOIL WTI West Texas Intermediate, TVC:CADUSD] effect of detrend(USOIL) and d_(TNX-SYMUSD)? try a*detrend(USOIL) - b*d_(TNX-SYMUSD) detrend(USOIL) from previous regression work : "$d_mkts"'market data/SLregress/220812 SLregress/SLregress USOIL Dec1861-Aug2022 TradingView.png' detrend(USOIL) = USOIL / (10^(-1.6684 + (0.00291 * yFrac)) relStdDevErrTrn = 1.382522, relStdDevTrn = 0.366279 formula?... are coefficients [a, b] functions of netOilImports/GDP? that is a later research project... 08******08 #] 20Sep2022 extend, fix PineScript - intl exchange rates versus 10y rate differentials update - International [interest, exchange] rates 20Sep2022 - This is an update of yesterday's Pine Script. I have simply provided additional constants for the (3M, 6M) time.periods, adding to constants for (1Y, 5Y) time.periods of yesterday. I did try to implement script to automatically provide the (min, max) of del_CN10Y = v_TNX - v_CN10Y (example), but PineScript does not work on full time-period information accurately, so I abandoned that. Below are links to a rapid-throw-together set of charts comparing rates internationally. There are probably millions of other graphs like this created by organisations and educationals institutes, but far more advanced and accurate. Even so, the graphs show the time relationship between rates, and are suggestive of some degree of correlation. No sense pushing this too far, it would be more fun to ferret out more of the network of inter-related factors. One possible current anomaly is the GBPUSD exchange rate? // All manually-provided constants for del[Min, Max]_10Y will become inaccurate with time!! // ONLY time.periods [3M, 6M, 1Y, 5Y] work. // time.periods [1D, 5D, 1M, ALL] do NOT work - I haven't manually provided values from charts. // there are some errors in my manually [read, record] of the 5Y time-periods // additionally, this Pine Script was thrown together in a day, no rigorous testing // exchange rates are shown by darker colors, interest rates lighter similar colors // China - green, Euro - purple, Great Britain - blue, Japan - orange (you can see this in the4 code below!) // stable rates : [JP10Y, CN10Y] // https://www.tradingview.com/x/OXFvIi7I/ // policy-manipulated rates : [TNX, EU10Y, GB10Y] // https://www.tradingview.com/x/V4LOppCz/ Save 2 charts for each "valid" timepeeriod (for which I read [min, max] from chart, manually entered) /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 3M [CN10Y, JP10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 6M [CN10Y, JP10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 1Y [CN10Y, JP10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 5Y [CN10Y, JP10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 3M [EU10Y, GB10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 6M [EU10Y, GB10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 1Y [EU10Y, GB10Y].png /home/bill/SG6/web/economics, markets/[interest, exchange] rates/220920 Howell intl rates, 5Y [EU10Y, GB10Y].png 08******08 #] 19Sep2022 from blog to @quantguy : Below are links to a rapid-throw-together set of charts comparing [interest, exchange] rates internationally. There are probably millions of other graphs like this created by organisations and educationals institutes, but far more advanced and accurate. Even so, the graphs show the time relationship between [exchange, interest] rates, and are suggestive of some degree of correlation. Not sense pushing this too far, it would be more fun to ferret out more of the network of inter-related factors. One possible current anomaly is the GBPUSD exchange rate? The charts were generated using a simple PineScript (should be visible?) // saved graphs - unfortunately, all of the colored labels on the graph were lost!! // exchange rates are shown by darker colors, interest rates lighter similar colors // China - green, Euro - purple, Great Britain - blue, Japan - orange (you can see this in the4 code below!) // stable interest rates : [JP10Y, CN10Y] https://www.tradingview.com/x/OXFvIi7I/ // policy-manipulated interest rates : [TNX, EU10Y, GB10Y] https://www.tradingview.com/x/V4LOppCz/ // maybe the "stable rates" countries do more "exchange rate" manipulation? 220919 Howell TradingView international [interest, exchange] rates - policy-manipulated rates.png 220919 Howell TradingView international [interest, exchange] rates - stable interest rates.png 08******08 #] 17Aug2022 algotrading101.com - great description of PineScript [, dis]-advantages https://algotrading101.com/learn/pine-script-tradingview-guide/ What are the alternatives to using Pine script? TD Ameritrade’s thinkorswim – this platform has a lot of similarities to Pine Script. It utilizes a proprietary language called thinkScript and stores price data in arrays in a similar way to Pine script. Data is built-in and the platform is geared toward creating custom indicators and strategies. Ninjatrader – This platform also uses a proprietary language which is called Ninjascript. The language is not completely proprietary as it is based on C#. Ninjatrader has a bit more flexibility as it allows you to connect to custom data feeds. If you’re already familiar with C#, C, or C++, this might be a viable alternative. 08******08 #] 16Aug2022 fix 'Howell - fix symbols, eg rates div 10.txt', add to 'US interest rates' chart easy - but I messed around to find colors, linewidth no idea of how I lost the earlier version of chart - I did delete several charts, and probably killed it. 08******08 #] 10Aug2022 clean up 'PuetzUWS IntlStkIdxs multi-fractals (version 2).txt' +-----+ olde code // 25May2022 probably WRONG!! - consider semi-log : // 14Jun2022 doesn't work - need a series to et price level? // 04Jun2022 Used for timeSpikes, can't get priceOffset to work, doesn't seem work with label.new... time_label(int timer, float serPrice, float priceOffset, string txt) => label.new(timer, serPrice + priceOffset, txt, xloc = xloc.bar_time, textcolor = color.black, color = na, style=label.style_label_left) // didn't work - dumVar not typed? //time_label(int timer, float serPrice, float priceOffset, string txt) => // dummyVar = priceOffset // label.new(timer, serPrice + priceOffset, txt, xloc = xloc.bar_time, textcolor = color.black, color = na, style=label.style_label_left) // Do not put in an if statement yet - needed by draw_spikes // Note : the y_axis may not be a price, it could be [volume, other], but the "price" term used here // 12Jun2022 this approach did NOT work - it was an attempt to improve efficiency [memory, computation]s //float priceMin = 1.0E6 //float priceMax = 0 // //if close < priceMin // priceMin := close // //if close > priceMax // priceMax := close // priceFractals - are hard-bound to the SP500USD 1926-2020 semi-log trend line and // its standard deviation. (fib = number of relStdDev) // So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics. // The "relative standard deviation" (relStdDev or rsd) of the 83y trend is from the data 1926-2020 // calculated in LibreOffice Calc spreadsheet =STDEV(SP500_detrend_1926_2020), i.e on semi-log detrend basis // see "$d_webRawe"'economics, markets/SP500/multi-fractal/SP500 1872-2020 TradingView, 1928-2020 yahoo // WARNING!!! Redo this yourself!!! I made so many changes of a period of two years, weird things could have happened. // keep coming back like zombies. examples : // fib0236Hi = (1 + 0.236*relStdDev/2) should be relStdDev (should be no "/2") // I don't trust this // 11Jun2022 new approach, trying to get simple floats to work (does not work!) //if priceRsd < priceRsdMin // priceRsdMin := priceRsd // //if priceRsd > priceRsdMax // priceRsdMax := priceRsd // SPX "zero level" priceRsds - [1926.25-2020.???, 1872-1926.25] // too lazy to get 2020 exact endDate of regression fit // rather than feed a jillion parameters to a function, easier to do special func // special funcs also good for [multiple segments, strange conditions, etc] calc_SP500Trend() => relStdDev = 0.4308 if year_fraction <= 1926.25 relStdDev := 0.3314 expnt = 0.0 if year_fraction >= 1926.25 expnt := 0.792392+0.0289587*(year_fraction - 1926.25) else expnt := 0.784617+1.40925E-04 *(year_fraction - 1871.08) SP500base = math.pow(10,expnt) lin0000 = calc_SP500Trend() // lin0000_[start, end] : don't need, its just lin0000 at barstate.islast (horizontal lines) priceRsd = priceNormal_regressParams_to_priceSemilogRsd(close) plot(priceRsd, color=color.aqua, linewidth=2) // 20Jun2022 using lin0000[barIndex] DOESN'T work! // Study Error : This study references too many candles in history (eg 5001) // are hard-bound to the SP500USD 1926-2020 semi-log trend line and // its standard deviation. (fib = number of relStdDev) // So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics. // [lambdaPuetzUWS, rsdPuetzUWS] defined in setup section above // note that the "plot" function cannot be a local : ie in [function, for, if, etc] // for price, key fractal measure is rsdPrice, preferably with 1.0 in set rsdPuetzUWS? // wanted to have options on type of priceFractals : Puetz framework, Fibonacci lowest level? 08******08 #] 25Jul2022 normal [IRX.P 13w T-bill, FVX.P 10y T-bond] rates see "$d_webRaw"'Software programming & code/PineScript for TradingView market charts/Howell - add modified symbols, overlay=true.txt' 08******08 #] 25Jul2022 plot a modified symbol : FVX.P / 10 I used : https://www.tradingcode.net/tradingview/symbol-instrument-input/ Also https://stackoverflow.com/questions/65843133/how-do-separate-panes-work-in-pinescript How do separate panes work in Pinescript? +--+ Unfortunately, at the moment an indicator/strategy can either be on the main pane (with overlay=true as the argument in the study() or strategy()) or on its own new pane (by default or with overlay=false). There is no way to have one plot on a separate pane while also having other plots/labels on the main one if you are only using one script. The only exception to this are the position arrows that the strategy itself creates - they always appear on the main pane, but that is hardcoded. answered Jan 22, 2021 at 11:19 user avatar beeholder +--+ https://forexbee.co/pine-script-tutorial-overlay-and-plot-function/ >> not useful - very incomplete +--+ https://stackoverflow.com/questions/70906476/overlay-is-true-but-my-indicator-on-seperated-chart Could it be that when you added it to your chart overlay was set to false and then you changed it to true without removing the indicator from your chart? What I’m trying to say is, what happens when you remove the indicator from your chart and add again? – vitruvius Jan 29 at 15:03 08******08 #] 20Jun2022 The price[Normal, Rsd] curves should overlap! problem with fracLines > priceRsdMax? +----+ ole code if priceRsdMin < 0.000 iStop := 0 widthr := 0 priceRsdBelow := array.get(rsdPuetzUWS, priceRsdBelowIdx) priceRsdBelowStop := array.get(rsdPuetzUWS, priceRsdBelowStopIdx) //priceLabel := priceRsdMax - 7*txtLineHeight //simple_label(bar_2_3rds, priceLabel, "priceRsdBelowStop = " + str.tostring(priceRsdBelowStop)) //simple_label(bar_1_half, priceLabel, "priceRsdBelow = " + str.tostring(priceRsdBelow)) for iRSD = priceRsdBelowStopIdx to priceRsdBelowIdx widthr := widthr + 1 priceRsdStep := array.get(rsdPuetzUWS, iRSD) priceRsdNow := 0.0 while (priceRsdMin <= priceRsdNow) and (iStop < 300) if priceRsdMax >= priceRsdNow line.new(last_bar_index - n_bars, priceRsdNow, last_bar_index, priceRsdNow, color=color.black, width=widthr) barLast_label(priceRsdNow, " " + str.tostring(priceRsd_to_priceNormal(priceRsdNow), '#')) priceRsdNow := priceRsdNow + priceRsdStep iStop := iStop + 1 // // do levels above priceRsd = 1.000, if they are present if priceRsdMax >= 0.000 iStop := 0 widthr := 0 priceRsdAbove := array.get(rsdPuetzUWS, priceRsdAboveIdx) priceRsdAboveStop := array.get(rsdPuetzUWS, priceRsdAboveStopIdx) //priceLabel := priceRsdMax - 8*txtLineHeight //simple_label(bar_2_3rds, priceLabel, "priceRsdAboveStop = " + str.tostring(priceRsdAboveStop)) //simple_label(bar_1_half, priceLabel, "priceRsdAbove = " + str.tostring(priceRsdAbove)) for iRSD = priceRsdAboveStopIdx to priceRsdAboveIdx widthr := widthr + 1 priceRsdNow := 0.0 priceRsdStep := array.get(rsdPuetzUWS, iRSD) while (priceRsdNow <= priceRsdMax) and (iStop < 300) if priceRsdMin <= priceRsdNow line.new(last_bar_index - n_bars, priceRsdNow, last_bar_index, priceRsdNow, color=color.black, width=widthr) barLast_label(priceRsdNow, " " + str.tostring(priceRsd_to_priceNormal(priceRsdNow), '#')) priceRsdNow := priceRsdNow + priceRsdStep iStop := iStop + 1 08******08 #] 19Jun2022 Posting of PineScript "PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020" This script is simply provided because a few rare people may actually be able to use one or two coding ideas. It is not possible to provide any sort of description or explanations here. Maybe you can find it with a webSearch. As the original was in violation of PineScript rules, I've removed many links, including : - documentation of my code - external sources of code - blog solutions to Pine script programming - math, science references, people Hopefully it will won't be rejected this time, if so, too bad. I only made it through 10% of the conceptual objectives, and I do not believe any of the rest of the concepts are do-able in Pine Script. The current coding is (incomplete, unstable) but does give a faint idea of my "first step" intents. I have stopped all work, as I have to get back to my real projects (nothing to do with markets). 08******08 #] 16Jun2022 Publish my PineScript "SP500 - Puetz [time, price] multiFractals [detrend, relStdDev] 1926-2020" Stephen J. Puetz's "Universal Wave Series" (UWS - see references below) provides one of many generalized approaches to market [time, price] multi-fractals. I have implemented this in TradingView.com's Pine Script language to provide real-time market chart updates on [day, week, [1,3,6] month, [1,5] year, "All"] timescales. INCOMPLETE explanations of the detrended multi-fractal chart, and why you might consider using it, are provided in my webPages, as are descriptions of my PineScript program. However, as external links cannot be used in TradingView, you will have to webSearch for my name and "Howell - PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020", and "Howell - TradingView PineScript of priceTimeFractals" or something like that, to find a starting point for explanations and related webPages. The detrended view of market symbols is intended as a COMPLEMENT to semi-log charts that [investor, trader]s normally use, and NOT as a stand-alone view. Keep in mind that the process of detrending "throws out data", i.e. the trend, and the trend is of primary interest to [investor, trader]s. The detrended view converges to the normal view at timescales less than a month. As such, traders who focus exclusively on these shorter timeframes won't get much practical use form the detrended view. As such, this script complements an earlier script and graph that I posted. Users only have to set up the basic chart and symbols in TradingView based on my chart PuetzUWS [time, price] multiFractal mirrors, SPX 1872-2020. To do so you must be a TradingView subscriber. After that, copy over my PineScript coding, which you can find on my TradingView page - click on "SCRIPTS", and select my script "PuetzUWS [time, price] multifractal of detrended SPX 1871-2020". Further setup details are given on my webPages. It was my intent to provide [Fibonacci, Leibnitz] alternatives as basis for the [time, price] fractals, and to provide detrended series for [NASDAQ, USOIL, GOLD]. But it was enough of a struggle to get the current Pine Script coding to (mostly) work so I leave it as is for the foreseeable future. I hope at least one of these links to chart images (1872-2022) works : https://www.tradingview.com/x/Y2RbXT6v/ https://www.tradingview.com/x/flrPcrND/ 08******08 #] 16Jun2022 clean up timeFrac < 0.000 Freeze the program, with all of its warts! /media/bill/Dell2/Website - raw/economics, markets/SP500/PuetzUWS/ Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 150y 1872-2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 5y Jun2017-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 1y Jun2021-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 6m 16Dec2021-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 3m 16Mar2022-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 1m 16May2022-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 5d 09Jun2022-16Jun2022.png Howell - PuetzUWS SPX [time, price] multiFractal mirrors, 1d 16Jun2022.png Summary What does my TradingView PineScript code do? So, what does the user have to do to [get, adjust] output? What CAN the user change? Initial observations Initial questions PineScript comments PuetzUWS comments Puetz's UWS as a highly-[constrained, specific] Fourier wave series-like analysis? Was 2007-2009 the modern equivalent to the 1929 crash? Are we going there yet? References Inspirations for this webPage $ geany format ToC, multi-line regexpr : search : ^(.*) replace : \t
  • \1 +---+ olde webPage comments

    Model results

    "SP500 & DJIA indexes back to 1872"

    Linear semi-log segments [1872-1926, 1926-2020]

    Fibonnaci levels versus log-levels
    Larger Fibonnaci's at greater timescales

    How do I get negative numbers from a log transformation of the data?


    "Key [results, comments]"


    What's [missing from, wrong with] the current model?

    • The data set :
      • Currently uses historical data of the [SP500,
      • Needs to include the London Stock Exchange (LSE) and Bourse de Paris?
      • Should perhaps be the SP International index back-extended?
      • Pre-stock exchange proxies - agrultural commodities going back to Babylon
    • Update the UWS dataset -
      • currently uses the more complete parameters from Puetz & Borchardt 2011, for both the "normal" and "double" UWS series
      • A 2014 paper changes the base UWS parameters, and applies a Half-wave (HUWS) seeries, rather thanDouble-UWS (DUWS) series
    • Why have I "eyeballed" the linear-log segments, yet I used Particle Swarm Optimization (PSO) for the parameter? I even have routines for linear regression analysis, which are standard and very easy. Laziness is the reason, but I also a fear of getting "artificially precise" at the start of the project when the basic concepts are being explored. I'm not looking for false accuracy at this point. It's much more important to simply get my hands dirty with the data and look for [challenges, questions, anomalies], and to see different approaches by eye.
    • Using a hybrid [linear regression, PSO or other] optimisation approach +-----+ olde code // set iUWS ranges for [below, above] rsd = 1.000 if priceRsdMinIdx < midIdx priceRsdBelowIdx := midIdx - priceRsdBasIdx + 1 // scale smaller (higher idx) than priceRsdBasIdx priceRsdBelowStopIdx := priceRsdBelowIdx + 2 if priceRsdBelowStopIdx > midIdx priceRsdBelowStopIdx := midIdx if priceRsdMaxIdx > midIdx priceRsdAboveIdx := midIdx + priceRsdBasIdx - 2 // extra - 1 because of 0.000 in middle priceRsdAboveStopIdx := priceRsdAboveIdx - 3 // extra - 1 because of 0.000 in middle if priceRsdAboveStopIdx < midIdx priceRsdAboveStopIdx := midIdx if priceRsdBasIdx < 2 priceRsdBelowIdx := midIdx - priceRsdBasIdx - 1 if priceRsdBelowStopIdx > midIdx priceRsdBelowStopIdx := midIdx priceRsdAboveIdx := midIdx + priceRsdBasIdx if priceRsdAboveIdx > lastIdx priceRsdAboveIdx := lastIdx priceRsdAboveStopIdx := priceRsdAboveIdx - 2 if priceRsdAboveStopIdx < midIdx priceRsdAboveStopIdx := midIdx lastRsdIdx = array.size(rsdPuetzUWS) - 1 08******08 #] 14Jun2022 fix timeFrac NUTS! section "Time - timeframe.period" - timeIdx stays at 0, timeframe.period ISN'T "M" +-----+ olde code if t_mod < t_lengthUnix t_spike := timenow - t_mod n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle)) else if t_mod == 0.0 t_spike := timenow n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle)) + 1 else if t_mod > t_lengthUnix flagSpike := false // 14Jun2022 can't get to work : int t_start = 0 if barstate.isfirst t_start := time // //simple_label(last_bar_index - 50, t_start, "t_start = " + str.tostring(t_start)) //simple_label(last_bar_index - math.round(n_bars*2/3), 1.0, "t_start = " + str.tostring(t_start)) //simple_label(last_bar_index - math.round(n_bars /2), 1.0, "t_end = " + str.tostring(t_end )) // example using t_start from "Time - timeframe.period" section - see timeFractal section, drawTimeFrac() //if barstate.islast // time_label(t_start, priceRsdMin, 0.00, "time_label test") // array.set(timeLambdaL, j, timeLamdaMaxIdx - 2 + j) // 08Jun2022 need to convert timeLambda to already including t_year_to_millisecs!! //t_cycle := math.round(array.get(lambdaPuetzUWS, array.get(timeLambdaYearL, iUWS)) * t_year_to_millisecs) // time_label(int timer, float serPrice, float priceOffset, string txt) => //time_label(t_spike, priceRsdMax, 0.0, str.tostring(iUWS)) //priceLabel := priceRsdMax - 8*txtLineHeight //simple_label(bar_2_3rds, priceLabel, "t_spike = " + str.tostring(t_spike)) // //y_offset := -i_spike*txtLineHeight 08******08 #] 13Jun2022 fix priceFrac SP500 1926-2020 semi-log trend = 10^(0.792392+2.89587*10^(-2)*(year - 1926.25)) price revolution* (~7%/y) SP500 1872-1926 semi-log trend = 10^(0.784617+1.40925*10^(-4)*(year - 1871.08)) price equilibrium* (~0.03%/y) *David Fischer 1996 "The Great Wave, Price revolutions and the rhythm of history" SP500 15Apr-06Sep2021: semilog trend = 10^(3.5018 + 0.0940601*(year - 2020.02)) Fibbonacci(0.0) ~upper bound, effective rate ~= ((10 power semiLog_slope) -1) : 24%/year this mis-adjusts somewhat as time progresses from ~06Jan2022 SP500 1926-2020 semi-log trend (thick navy blue, ~7%/y) gray lines above trend : (1 + fib*stdDev/2) * fib0000_base gray lines below trend : (1 - fib*stdDev/2) * fib0000_base where fib = [ 0.382, 0.618, 0.786, 1.000, 1.272 ] stdDev = 0.4308 (for entire 1926-2020 period!) 24%/year 15Apr-06Sep2021 semilog trend +-----+ olde code if priceRsdMin < 0.000 for iRSD = priceRsdBelowStopIdx to priceRsdBelowIdx p_cycle := array.get(rsdPuetzUWS, iRSD) //??? don't want this -> math.abs or something //p_mod := math.floor(((priceRsdMin / p_cycle) % 1) * p_cycle) p_mod := math.floor(priceRsdMin / p_cycle % 1) // find [last, closest] horz in priceRsdMin if p_mod >= priceRsdMin p_spike := priceRsdMin - p_mod n_spikes := math.floor((priceRsdMin - p_mod) / p_cycle) flagSpike := true else if p_mod < priceRsdMin flagSpike := false if flagSpike priceRsdCum := 1.000 for i_spike = 0 to (n_spikes - 1) priceRsdCum := priceRsdCum * p_cycle if priceRsdMin < priceRsdCum and priceRsdCum < priceRsdMax p_frac := priceRsdCum line.new(last_bar_index - n_bars, p_frac, last_bar_index, p_frac, color=color.black, width=iRSD + 1) y_offset := -i_spike*txtLineHeight // barLast_label(float price, string txt) => // barLast_label(p_frac + y_Offset, str.tostring(p_frac, '#.000')) //p_spike := p_spike - p_cycle y_offset := -txtLineHeight txt := "p_cycle = " + str.tostring(p_cycle, '#.000') barFirst_label(0.5, priceRsdMax, y_offset, txt) // // do levels above priceRsd = 1.000, if they are present if priceRsdMax >= 0.000 for iRSD = priceRsdAboveStopIdx to priceRsdAboveIdx p_cycle := array.get(rsdPuetzUWS, iRSD) p_mod := math.floor(((priceRsdMax / p_cycle) % 1) * p_cycle) // find [last, closest] horz in priceRsdMax if p_mod <= priceRsdMax p_spike := priceRsdMax - p_mod n_spikes := math.floor((priceRsdMax - p_mod) / p_cycle) flagSpike := true else if p_mod > priceRsdMax flagSpike := false if flagSpike priceRsdCum := 1.000 for i_spike = 0 to (n_spikes - 1) priceRsdCum := priceRsdCum * p_cycle if priceRsdMin < priceRsdCum and priceRsdCum < priceRsdMax p_frac := priceRsdCum line.new(last_bar_index - n_bars, p_frac, last_bar_index, p_frac, color=color.black, width=iRSD + 1) y_offset := -i_spike*txtLineHeight // barLast_label(float price, string txt) => // barLast_label(p_frac + y_Offset, str.tostring(p_frac, '#.000')) //p_spike := p_spike - p_cycle y_offset := -txtLineHeight txt := "p_cycle = " + str.tostring(p_cycle, '#.000') //barFirst_label(float barFractionFrmRight, float serPrice, float priceOffset, string txt) => barFirst_label(0.5, priceRsd, y_offset, txt) 08******08 #] 13Jun2022 Federal Reserve - debt held, liabilities, capital see "$d_webRawe""economics, markets/SP500/Federal Reserve/0_Fed balance sheet data - notes.txt" FRED: WLFN - Federal Reserve: Liabilities and Capital, Fed notes net of Fed holdings, Wednesday level FRED: FDHBFRBN Federal Debt helby Federal Reserve Banks 08******08 #] 12Jun2022 priceRsdBasIdx, drawPriceFrac +-----+ olde code // set iUWS ranges for [below, above] rsd = 1.000 if priceRsdBas < 0 priceRsdBelowIdx := priceRsdBasIdx priceRsdAboveIdx := (midIdx - priceRsdBasIdx) else priceRsdBelowIdx := (priceRsdBasIdx - midIdx) priceRsdAboveIdx := priceRsdBasIdx // // cannot have indices that "cross over" midIdx (where priceRsd = 1.00, lin0000) if priceRsdBelowIdx > midIdx - 3 priceRsdBelowStopIdx := midIdx else priceRsdBelowStopIdx := priceRsdBelowIdx // if priceRsdAboveIdx < midIdx + 3 priceRsdAboveStopIdx := midIdx else priceRsdAboveStopIdx := priceRsdAboveIdx 13Jun2022 // // cannot have indices that "cross over" midIdx (where priceRsd = 1.00, lin0000) if priceRsdBelowIdx > midIdx - 3 priceRsdBelowStopIdx := midIdx else priceRsdBelowStopIdx := priceRsdBelowIdx // if priceRsdAboveIdx < midIdx + 3 priceRsdAboveStopIdx := midIdx else priceRsdAboveStopIdx := priceRsdAboveIdx 08******08 #] 11Jun2022 var keyword - causes problems normally, reverts to initial state! #] use only for fixed constants, but generally a bad idea except special cases https://www.tradingview.com/pine-script-reference/#op_var var is the keyword used for assigning and one-time initializing of the variable. Normally, a syntax of assignment of variables, which doesn’t include the keyword var, results in the value of the variable being overwritten with every update of the data. Contrary to that, when assigning variables with the keyword var, they can “keep the state” despite the data updating, only changing it when conditions within if-expressions are met. >> I got rid of all "var" uses 08******08 #] 10Jun2022 try setting overlay = true!? >> didn't help https://forexbee.co/pine-script-tutorial-overlay-and-plot-function/ Pine Script Tutorial – Overlay and Plot function Ali Muhammad, June 25, 2021 Overlay is used to plot either on the chart or in a separate window in the pine script. It is Boolean and accepts only true or false. By default, overlay is set to the false value in the pine script. If overlay is set to false, then the indicator will open in a separate window on the chart in tradingview. If overlay is set to true, then the indicator will open in the same window in tradingview. +-----+ https://stackoverflow.com/questions/65224862/plotting-multiple-graphs-some-overlay-some-not Plotting multiple graphs, some overlay, some not This cannot be done in a single script in Pine. One script always pertains to a single window. You can however have your indicator bounded to the left scale, so that it doesn't distort the main chart. To do that, you have to enter the scale parameter on the study() function. Like this: //@version=4 study("Quality of earnings", overlay=true, scale=scale.left) cfo = financial(syminfo.tickerid, "CASH_F_OPERATING_ACTIVITIES", "FY") net = financial(syminfo.tickerid, "NET_INCOME", "FY") qoe = cfo/net plot(qoe, style=plot.style_stepline) answered Dec 9, 2020 at 21:26 Bjorn Mistiaen priceRsdMin -> priceRsdMax inine.new, labels +-----+ olde code // The Fibonacci series is mirrored [above, below] 1.000. More complete version (not used here) : // * = non-primary-Fibonacci but often used (0.5, 0.78, 1.27, 2.0, also 0.65?) // 0.055728, 0.090170, 0.145898, 0.236072, 0.381971, 0.500000*, 0.618047, 0.786164*, 1.000000 // 17.94430, 11.09020, 6.854100, 4.236000, 2.618000, 2.000000*, 1.618000, 1.272000*, 1.000000 //barFirst_label(int n_bars, int barsShiftRight, float serPrice, float priceOffset, string txt) => // label.new(bar_index - n_bars + math.round(barsShiftRight), serPrice + math.round(priceOffset), txt, textcolor = color.black, color = na, style=label.style_label_left) 08******08 #] 09Jun2022 symbol definitions, siilarities between [time, price]Fractals // priceFractal | timeFractal // ---------------|--------------- // flagSpike | flagSpike boolean -whether to output a [line, spike] // lambdaPuetzUWS | lambdaPuetzUWS PuetzUWS (Universal Wave Series), period = cycle lengths (years) // rsdPuetzUWS | timeLambda PuetzUWS converted to relStdDev [time, price] // midIdx | n/a [PuetzUWS, rsdPuetzUWS] index, such that rsdPuetzUWS = 1.000 // p_cycle | t_cycle current cycle length in [drawPriceFrac, drawTimeFrac] // priceRsdMax? | t_now . // priceRsdMax? | timenow . // p_mod | t_mod modulus (leftover) iUWS p_cycles from basLevel to rsdLevel // priceRsdCum | t_spike . // n_spikes | n_spikes number of iUWS [line, spike]s to show on chart // n/a | t_lengthUnix chart's time duration (t_lengthYear) converted to Unix (milliseconds) // n/a | timenow Unix current time UTC (milliseconds since 01Jan1970) // n_bars | t_start starting [bar, time] - sloppy guess // y_offset | y_offset price offset, typically from a [line, spike] on chart, for labels 08******08 #] 09Jun2022 revamp drawPriceFrac() to handle fracLies [below, above] 1.000, using priceRsdBasIdx +-----+ olde code // drawPriceFracLowLevel() - below 1926-202 semi-log trend line (lin0000) // for now only nests 1 level below topLevel // 08Jun2022 need to do [above, below] lin0000 (fractal = 1.000) - currently just above drawPriceFracLowLevel() => var bool flagSpike = true var float p_cycle = 0.0 var int p_mod = 0 var int n_spikes = 0 var float p_spike = 0.0 var float p_frac = 0.0 var float y_offset = 0.0 // skip daily chart, as SP500 [priceRsdMin, n_bars] seem messed up // (maybe not available by minute or whatever) for iUWS = priceRsdMinIdx to priceRsdMaxIdx for iLowLevel = 1 to 2 flagSpike := true p_cycle := array.get(rsdPuetzUWS, midIdx - iLowLevel) p_mod := math.floor(((priceRsdMin / p_cycle) % 1) * p_cycle) // find [last, closest] horz in priceRsdMin if p_mod >= priceRsdMin p_spike := priceRsdMin - p_mod n_spikes := math.floor((priceRsdMin - p_mod) / p_cycle) else if p_mod < priceRsdMin flagSpike := false if flagSpike for i_spike = 0 to (n_spikes - 1) p_frac := lin0000*array.get(priceLamdaTop, i_spike) line.new(last_bar_index - n_bars, p_frac, last_bar_index, p_frac, color=color.black, width=iUWS + 1) y_offset := -i_spike*txtLineHeight/4 // barLast_label(float price, string txt) => // barLast_label(p_frac - y_Offset, str.tostring(p_frac, '#.000')) p_spike := p_spike - p_cycle //if barstate.islast // for iLevel = 1 to 2 // drawPriceFracLowLevel(iLevel) //if barstate.islast and timeframe.period != "1" and timeframe.period != "5" // setPriceLabels() // olde code // line.new(int(n_spike), color=color.black, linewidth=iUWS + 1) // else if p_mod == 0.0 // n_spike := timenow // n_spikes := math.floor((priceRsdMax - p_mod) / p_cycle) + 1 // find the index in rsdPuetzUWS of ary_logRsdPriceSpan_biggest // (which fits into log(rsd of [priceMin, priceMax]))? // skip [1D 5D] charts?, as SP500 [priceRsdMax, n_bars] seem messed up // (maybe not available by minute or whatever) // initial version from a blog - I am getting "type-over" problem, but the lbl doesnt do anything // simple_label(bar_index,price,txt) => // label lbl = na // label.delete(lbl) // lbl:=label.new(bar_index, price, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.large) // there is no first_bar_index -> just use 0 (zero) base // timeBarOffsets are backwards from a specified bar_index // priceOffsets are : + = upward; - = downward // PineScript reference : // 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. //lastbar = last_bar_index // https://kodify.net/tradingview/bar-data/bar-number/ // How to get the bar number in TradingView Pine? (bar_index variable) // >> didn't work // https://kodify.net/tradingview/inputs/string-textbox-input/ // Creating a text box input option in TradingView Pine // stringVariable = input(title, type=string, defval, confirm) // 13May2022 write debug values to chart // 20May2022 I removed options xloc = xloc.bar_index, // n_bars = total number of bars shown in "viewable window", standard timeperiods only! // adapted from : // https://stackoverflow.com/questions/50087999/how-to-know-which-time-period-you-are-on-similar-to-isdaily-isweekly // how to know which time period you are on similar to isdaily, isweekly? // answered May 17 '18 at 6:07, Harold // https://www.tradingcode.net/tradingview/time-frame-period/ // Get a time frame’s period in TradingView with Pine Script // 15May2022 YIKES!!! timeframe.d is completely different than I expected // It's NOT the string-to-click that is seen at chart bottom (depends on series, I guess) // for SP500USD 6M=120 1Y=D 5Y=W All=M // 05Jun2022 copied-over drawTimeFrac() & adapted it, don't use negative numbers! // 29May2022 adapt same approach as timeFractals // initial approach was to use a [long, full] single Fibonacci ratio series // adapt lambdaPuetzUWS = array.from(0.0001072980, 0.0003218942, 0.0009656826, 0.002897047, 0.008691143, 0.02607343, 0.07822029, 0.2346608, 0.7039826, 2.111947, 6.335843, 19.00753, 57.02259, 171.0677, 513.2033) // qnial> a := 0.0001072980 0.0003218942 0.0009656826 0.002897047 0.008691143 0.02607343 0.07822029 0.2346608 0.7039826 2.111947 6.335843 19.00753 57.02259 171.0677 513.2033 // qnial> a / 0.2346608 // 0.000457247 0.00137174 0.00411523 0.0123457 0.037037 0.111111 0.333333 1. 3. 9. 27. 81. 243. 729. 2187. // OK - totally makes sense, confirmation // t_baseUnix - when all UWS for this project assumed to coincide? (perhaps 1929 crash better assumption?) // should use Puetz time for coincidence of all UWS? (or some) - too broad? // t_lengthUnix - t_lengthYear converted to Unix (milliseconds) // iUWS - index for a reduced set of 5 lambdaPuetzUWS that will be marked // iUWS== 2 is max timeLambda that fits into t_lengthYear // actually, many more higher-level should be included! // flagSpike - boolean if any spikes occur over t_lengthYear for an iUWS // note that Puetz choose ?a few hundred miillion years ago? for one of his recent papers // t_mod - modulus (leftover) Unix time (milliseconds) from iUWS cycles starting from t_baseUnix // n_spikes - number of spikes for lamda(iUWS) showing over t_lengthYear // i_spike - index [0,..,4] of spike tbe displayed for lamda(iUWS) // offset - bars offset from timenow (barstate.islast) to placement of spike (towards barstate.isfirst) // timenow - PineScript Unix current time UTC wrt t_baseUnix // Current time in UNIX format. It is the number of milliseconds that have elapsed // since 00:00:00 UTC, 1 January 1970 // timestamp(year, month, day, hour, minute, second) → simple int //// drawPriceFrac(string fracTyp, series float rsdPuetzUWS, float t_year_to_millisecs, float t_lengthUnix, float t_now) => 08******08 #] 07Jun2022 I'm stupid - try again : priceFractal with newline 08Jun2022 +-----+ for easy comparison to priceFracs : var int maxUWSLamdaIdx = 0 ary_t_length_biggest() => max = 0 for j = 0 to 14 if array.get(UWS_lambda, j) < t_lengthYear max := j max var lambda = array.new_float(5, 0.0) init_lambda() => for j = 0 to 4 array.set(lambda, j, array.get(UWS_lambda, maxUWSLamdaIdx - 2 + j)) var phi = array.new_float(5, 0.0) init_phi() => for j = 0 to 4 array.set(phi, j, array.get(UWS_phi, maxUWSLamdaIdx - 2)) if barstate.isfirst maxUWSLamdaIdx := ary_t_length_biggest() init_lambda() init_phi() drawTimeFrac() => var bool flagSpike = true var int t_cycle = 0 var int t_mod = 0 var int t_spike = 0 var int n_spikes = 0 y_offset = 0.0 // skip daily chart, as SP500 [t_lengthUnix, n_bars] seem messed up // (maybe not available by minute or whatever) for iUWS = 0 to 4 flagSpike := true t_cycle := math.round(array.get(lambda, iUWS) * t_year_to_millisecs) t_mod := math.floor(((timenow / t_cycle) % 1) * t_cycle) // find last, closest] spike in t_lengthUnix if t_mod < t_lengthUnix t_spike := timenow - t_mod n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle)) else if t_mod == 0.0 t_spike := timenow n_spikes := math.floor(((t_lengthUnix - t_mod) / t_cycle)) + 1 else if t_mod > t_lengthUnix flagSpike := false if flagSpike for i_spike = 0 to (n_spikes - 1) line.new(t_spike, priceMin, t_spike, priceMax, xloc = xloc.bar_time, color=color.black, width=iUWS + 1) y_offset := -i_spike*txtLineHeight/4 // time_label(int timer, float serPrice, float priceOffset, string txt) => //time_label(t_spike, priceMax, 0.0, str.tostring(iUWS)) time_label(t_spike, priceMax, y_offset, " " + str.tostring(iUWS)) t_spike := t_spike - t_cycle // y_na for plots which aren't used in this script float y_na = na +-----+ olde code // PuetzLevels matrix - limited to 9 relStdDev // matrices don't work well in Pine Script - go back to the cave ages and use variables zone = array.from(0.0, 3.0, 9.0) levl = array.from(0.1667, 0.3333, 0.5000, 0.6667, 0.8334) rsd = array.from(-4.000 -3.8334 -3.) //if barstate.islast // y_offset = 0.0 // rsdTmp = 0.0 // for i = 0 to 24 // y_offset := -(i + 2)*txtLineHeight/2 // rsdTmp := array.get(rsd, i) // barFirst_label(0.75, priceMax, y_offset, str.tostring(rsdTmp, '#.000')) //array.set(rsd, 1, array.get(zone, 1) * (1 + 3*array.get(levl, 4))) //mat_write("Puetz rsdPriceFractal", rsd_Puetz, n_bars, 300, priceMax, txtLineHeight) // boolPuetz - matrix of truth values for [top, lower] PuetzRSD levels boolPuetz = matrix.new(5, 5, false) // priceLamda = array.new_float(5, 0.0) // following not needed - same 4 fracs for fracLevels > 0 //init_priceLamda() => // for j = 0 to 4 // array.set(priceLamda, j, array.get(priceLambda, priceLambdaMaxIdx - 2 + j)) 08******08 #] 04Jun2022 matrix.set isn't working in for loop! must individually set? matrix.set(mat_Puetz, 1, 1, 99.9) matrices are [finicky, poorly defined] useless - drop them // SHIT! I forgot - crappy TradingView : // line 402: Cannot use 'hline' in local scope. // I wasted another day after I quit this shitty programming language!!! 08******08 #] 04Jun2022 priceMin is corrupted!? I removed float declaration : priceMin = smalest(close, n_bars) priceMax = biggest(close, n_bars) time_label(int timer, float serPrice, float priceOffset, string txt) => I lost the timeSpikes!?! >> remove "var " from declarations -> then I put them back in (were there when it worked) put in "var float" : var float txtLineHeight = 0.0 optr change : +.....+ init_t_length(array ary_t_length) => array.set(ary_t_length, 0, 0.00273785) array.set(ary_t_length, 1, 0.0136893) array.set(ary_t_length, 2, 0.0833333) array.set(ary_t_length, 3, 0.25) array.set(ary_t_length, 4, 0.5) array.set(ary_t_length, 5, 1.0) array.set(ary_t_length, 6, 5.0) array.set(ary_t_length, 7, 20.0) if barstate.isfirst init_t_length(ary_t_length) +.....+ To : +.....+ init_t_length() => array.set(ary_t_length, 0, 0.00273785) array.set(ary_t_length, 1, 0.0136893) array.set(ary_t_length, 2, 0.0833333) array.set(ary_t_length, 3, 0.25) array.set(ary_t_length, 4, 0.5) array.set(ary_t_length, 5, 1.0) array.set(ary_t_length, 6, 5.0) array.set(ary_t_length, 7, 20.0) if barstate.isfirst init_t_length() +.....+ >> Nope, didn't help if (array.get(UWS_lambda, j) < t_lengthYear) ary_t_length_biggest() change : +.....+ if (array.get(UWS_lambda, j) < t_lengthYear) +.....+ To : +.....+ if array.get(UWS_lambda, j) < t_lengthYear +.....+ >> didn't help +-----+ olde code // won't work : time_label(t_start, priceMax, -6*txtLineHeight, "Puetz timeFractal [depth, period]s") // won't work : time_label(t_start, priceMax, y_offset, str.tostring(iUWS) + ". " + str.tostring(period, '#.000') + " " + periodLabel) 08******08 #] 04Jun2022 Publish library("HowellLibrary_time_labels", true) https://www.tradingview.com/script/2OnKcFyO-HowellLibrary-time-labels/ >> Big screw-up! Don't use libraries, too messy 08******08 #] 01Jun2022 squashing of symbolLines (again) The timeFracSpikes are sometimes written way above or below the rest of the timespikes Why? Change : +.....+ drawSpikes() +.....+ To : +.....+ if barstate.islast drawSpikes() +.....+ >> OK, helped with >3M, but NOT 1D, 5D Channg: ary_n_bars = array.from( 1000, 1000, 500, 1500, 1000, 240, 240, 230) // 30May2022 >> This definitely helped 02Jun2022 squashing of symbolLines - writing at or beyond left edge of chart shqesh t_spikes and legends +-----+ olde code // Fibonacci lines : lin2618Hi = (1 + relStdDev*fib2618Hi) * lin0000 lin2000Hi = (1 + relStdDev*fib2000Hi) * lin0000 lin1618Hi = (1 + relStdDev*fib1618Hi) * lin0000 lin1272Hi = (1 + relStdDev*fib1272Hi) * lin0000 lin1000Hi = (1 + relStdDev*fib1000Hi) * lin0000 lin0786Hi = (1 + relStdDev*fib0786Hi) * lin0000 lin0618Hi = (1 + relStdDev*fib0618Hi) * lin0000 lin0500Hi = (1 + relStdDev*fib0500Hi) * lin0000 lin0382Hi = (1 + relStdDev*fib0382Hi) * lin0000 lin0236Hi = (1 + relStdDev*fib0236Hi) * lin0000 lin0146Hi = (1 + relStdDev*fib0146Hi) * lin0000 lin0146Lo = (1 - relStdDev*fib0146Lo) * lin0000 lin0236Lo = (1 - relStdDev*fib0236Lo) * lin0000 lin0382Lo = (1 - relStdDev*fib0382Lo) * lin0000 lin0500Lo = (1 - relStdDev*fib0500Lo) * lin0000 lin0618Lo = (1 - relStdDev*fib0618Lo) * lin0000 lin0786Lo = (1 - relStdDev*fib0786Lo) * lin0000 lin1000Lo = (1 - relStdDev*fib1000Lo) * lin0000 lin1272Lo = (1 - relStdDev*fib1272Lo) * lin0000 lin1618Lo = (1 - relStdDev*fib1618Lo) * lin0000 lin2000Lo = (1 - relStdDev*fib2000Lo) * lin0000 lin2618Lo = (1 - relStdDev*fib2618Lo) * lin0000 if barstate.islast // simple_label(last_bar_index-200, close, "rsd_min = " + str.tostring(rsd_min)) // simple_label(last_bar_index-100, close, "rsd_max = " + str.tostring(rsd_max)) // Add Fibonacci mirror-labels barLast_label(bool2618Hi ? lin2618Hi : y_na, "+2.618") barLast_label(bool2000Hi ? lin2000Hi : y_na, "+2.000") barLast_label(bool1618Hi ? lin1618Hi : y_na, "+1.618") barLast_label(bool1272Hi ? lin1272Hi : y_na, "+1.272") barLast_label(bool1000Hi ? lin1000Hi : y_na, "+1.000") barLast_label(bool0786Hi ? lin0786Hi : y_na, "+0.786") barLast_label(bool0618Hi ? lin0618Hi : y_na, "+0.618") barLast_label(bool0500Hi ? lin0500Hi : y_na, "+0.500") barLast_label(bool0382Hi ? lin0382Hi : y_na, "+0.382") barLast_label(bool0236Hi ? lin0236Hi : y_na, "+0.236") barLast_label(bool0146Hi ? lin0146Hi : y_na, "+0.146") barLast_label(bool0000 ? lin0000 : y_na, " 0.000") barLast_label(bool0146Lo ? lin0146Lo : y_na, "-0.146") barLast_label(bool0236Lo ? lin0236Lo : y_na, "-0.236") barLast_label(bool0382Lo ? lin0382Lo : y_na, "-0.382") barLast_label(bool0500Lo ? lin0500Lo : y_na, "-0.500") barLast_label(bool0618Lo ? lin0618Lo : y_na, "-0.618") barLast_label(bool0786Lo ? lin0786Lo : y_na, "-0.786") barLast_label(bool1000Lo ? lin1000Lo : y_na, "-1.000") barLast_label(bool1272Lo ? lin1272Lo : y_na, "-1.272") barLast_label(bool1618Lo ? lin1618Lo : y_na, "-1.618") barLast_label(bool2000Lo ? lin2000Lo : y_na, "-2.000") barLast_label(bool2618Lo ? lin2618Lo : y_na, "-2.618") plot(bool2618Hi ? lin2618Hi : na, color=color.gray, linewidth=1) plot(bool2000Hi ? lin2000Hi : na, color=color.gray, linewidth=1) plot(bool1618Hi ? lin1618Hi : na, color=color.gray, linewidth=1) plot(bool1272Hi ? lin1272Hi : na, color=color.gray, linewidth=1) plot(bool1000Hi ? lin1000Hi : na, color=color.gray, linewidth=1) plot(bool0786Hi ? lin0786Hi : na, color=color.gray, linewidth=1) plot(bool0618Hi ? lin0618Hi : na, color=color.gray, linewidth=1) plot(bool0500Hi ? lin0500Hi : na, color=color.gray, linewidth=1) plot(bool0382Hi ? lin0382Hi : na, color=color.gray, linewidth=1) plot(bool0236Hi ? lin0000 * (1 + relStdDev*fib0236Hi) : na, color=color.gray, linewidth=1) plot(bool0146Hi ? lin0146Hi : na, color=color.gray, linewidth=1) plot(bool0000 ? lin0000 : na, color=color.navy, linewidth=3) plot(bool0146Lo ? lin0146Lo : na, color=color.gray, linewidth=1) plot(bool0236Lo ? lin0236Lo : na, color=color.gray, linewidth=1) plot(bool0382Lo ? lin0382Lo : na, color=color.gray, linewidth=1) plot(bool0500Lo ? lin0500Lo : na, color=color.gray, linewidth=1) plot(bool0618Lo ? lin0618Lo : na, color=color.gray, linewidth=1) plot(bool0786Lo ? lin0786Lo : na, color=color.gray, linewidth=1) plot(bool1000Lo ? lin1000Lo : na, color=color.gray, linewidth=1) plot(bool1272Lo ? lin1272Lo : na, color=color.gray, linewidth=1) plot(bool1618Lo ? lin1618Lo : na, color=color.gray, linewidth=1) plot(bool2000Lo ? lin2000Lo : na, color=color.gray, linewidth=1) plot(bool2618Lo ? lin2618Lo : na, color=color.gray, linewidth=1) // rsd = relative standard deviation series, with respect to 1926-2020 SP500 semilog [trend, relStdDev] // no need to change : ary_rsd = (close / lin0000 - 1) / relStdDev var float rsd_min = 100000. var float rsd_max = -100000. rsd_min := smalest(ary_rsd, n_bars) rsd_max := biggest(ary_rsd, n_bars) if barstate.islast // simple_label(last_bar_index-200, close, "rsd_min = " + str.tostring(rsd_min)) // simple_label(last_bar_index-100, close, "rsd_max = " + str.tostring(rsd_max)) ary_rsd = (close / lin0000 - 1) / relStdDev // 25May2022 probably WRONG!! - consider semi-log // 27May2022 didn't work // var firstBar = last_bar_index // barFirst_label(barOffset, serPrice, priceOffset, txt) => // label.new(firstBar + math.round(barOffset), serPrice + math.round(priceOffset), txt, textcolor = color.black, color = na, style=label.style_label_left) spikeSpaces = "" //time_label(t_spike, priceMax, 0, str.tostring(iUWS)) // test labels // barLast_label(price,txt) => //barLast_label(lin0000, "Puetz timeFractal [depth, period]s") // barFirst_label(barFirstOffset, serPrice, priceOffset, txt) => //barFirst_label(0, lin0000, 0, "Puetz timeFractal [depth, period]s") // simple_label(bar_index,price,txt) //simple_label(bar_index,close,"Puetz timeFractal [depth, period]s") // // 21May2022 WRONG approach!! user may elongate, shorten] timelines, for wich the presets won't work. I should use barstateis.[first, last] to calculate t_length[Bars, Time]. // n_bars = number of dataPoints on time axis // values for timeperiods = "1D" "5D" "1M" "3M" "6M" "1Y" "5Y" "All" (click text below chart) //qnial> (24*60*60) (24*60/5*12*7) (24*60*30) (24*30*3) (60/5*30*6) (30*12) (30*12*5) (30*12*50) //86400 24192. 43200 2160 2160. 360 1800 18000 // https://www.tradingview.com/pine-script-reference/#var_last_bar_index // last_bar_index - Bar index of the last chart bar. Bar indices begin at zero on the first bar. // results aren't consistent even when I repeat the same thing with no code changes! // 25May2022 use last_bar_index! -> doesn't work at lower timescales, I don't know why //n_last_bar_index = last_bar_index //n_bars := last_bar_index //if barstate.islast // simple_label(math.round(last_bar_index-200), close, "n_bars = " + str.tostring(n_bars)) // simple_label(math.round(last_bar_index-100), close, "last_bar_index = " + str.tostring(last_bar_index)) 08******08 #] 30May2022 ary_n_bars - reoptimize for the 100th time.. std timeScales ( 1D 5D 1M 3M 6M 1Y 5Y All) last_bar_index (24924, 21257, 28294, 20055, 22804, 4951, 1000, 230) these vary a bit ary_n_bars = array.from(24900, 21250, 28290, 20000, 22800, 4940, 1000, 230) // doesn't work at all ary_n_bars = array.from( 1440, 1440, 720, 2160, 2160, 240, 1800, 230) // scrunched a chart ary_n_bars = array.from( 720, 500, 500, 1500, 1500, 240, 240, 230) // 27May2022 best yet? still not good ary_n_bars = array.from( 720, 500, 500, 1500, 800, 240, 240, 230) // 30May2022 better ary_n_bars = array.from( 720, 500, 500, 1500, 600, 240, 240, 230) // 30May2022 bad ary_n_bars = array.from( 720, 500, 500, 1500, 1000, 240, 240, 230) // 30May2022 30May2022 6M far better! bad : 1D, 5D, 3M; fair : 1M, 6M; OK : 1Y; good 5Y, All: It just got great results for 6M, but now it is only fair. What else is "scrunching" the lines? ary_n_bars = array.from( 720, 500, 500, 1500, 1200, 240, 240, 230) all of a sudden, 6M is great again!!!???!!! what is going on? ary_n_bars = array.from( 720, 500, 500, 1500, 1100, 240, 240, 230) ary_n_bars = array.from( 720, 500, 500, 1500, 1000, 240, 240, 230) // 30May2022 ary_n_bars = array.from( 240, 1000, 500, 1500, 1000, 240, 240, 230) // 01Jun2022 /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 Intl stock markets, SPX500USD [Puetz time, Fib price]Fractals, 15Ar-06Sep2021 fibChannel, 6 month span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 2003-2022 span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 5 year span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 1 year span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 6 month span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 3 month span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 1 month span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 5 day span.png /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220530 USA multi-markets, SPX500USD [Puetz time, Fib price]Fractals, 1 day span.png 08******08 #] 30May2022 line.copy - use to convert priceFractals to same approach as timeFractals? https://www.tradingview.com/pine-script-reference/#fun_line{dot}copy Clones the line object. line.copy(id) → series line Example //@version=5 indicator('Last 100 bars price range', overlay = true) LOOKBACK = 100 highest = ta.highest(LOOKBACK) lowest = ta.lowest(LOOKBACK) if barstate.islastconfirmedhistory var lineTop = line.new(bar_index[LOOKBACK], highest, bar_index, highest, color = color.green) var lineBottom = line.copy(lineTop) line.set_y1(lineBottom, lowest) line.set_y2(lineBottom, lowest) line.set_color(lineBottom, color.red) $ diff "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/z_Archive/220527 21h25m40s Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' --suppress-common-lines | grep "<" | sed 's/< //' >> OK, 27Mar2022 $ diff "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/z_Archive/220529 20h13m09s Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/z_Archive/220527 21h25m40s Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' --suppress-common-lines | grep "<" | sed 's/< //' >> OK, 29Mar2022 $ diff "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/z_Archive/220529 20h13m09s Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/z_Archive/220527 21h25m40s Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' --suppress-common-lines | grep ">" | sed 's/> //' >> OK, 29Mar2022 +-----+ olde code //+-----+ // priceZone lines - Puetz factor-of-three nested progression // zon = zone levels [above, low] trend, these are the "factor-of-three" fixed upper levels // 30May2022 initial work - do not use zones [9, 27, 81] (crypto might need even more than that! maybe not) zon03Hi = 03.0 zon01Hi = 01.0 zon00 = 00.0 zon01Lo = 01.0 zon03Lo = 03.0 // zone lines : lin03Hi = (1 + relStdDev*zon03Hi) * y_base lin01Hi = (1 + relStdDev*zon01Hi) * y_base lin00 = (1 + relStdDev*zon00 ) * y_base lin01Lo = (1 + relStdDev*zon01Lo) * y_base lin03Lo = (1 + relStdDev*zon03Lo) * y_base // booleans - true if a fib level should be plotted (i.e. some point of it is between [min, max] values) bool03Hi := rsd_min < fib03Hi and fib03Hi < rsd_max bool01Hi := rsd_min < fib01Hi and fib01Hi < rsd_max bool00 := rsd_min < fib00 and fib00 < rsd_max bool01Lo := rsd_min < fib01Lo and fib01Lo < rsd_max bool03Lo := rsd_min < fib03Lo and fib03Lo < rsd_max //+-----+ // priceLevel lines (lowest zone only) // fib = fibonacci levels [above, low] trend fib0786Hi = 0.786 fib0618Hi = 0.618 fib0500Hi = 0.500 fib0382Hi = 0.382 fib0236Hi = 0.236 fib0236Lo = -0.236 fib0382Lo = -0.382 fib0500Lo = -0.500 fib0618Lo = -0.618 fib0786Lo = -0.786 // Fibonacci lines : lin0786Hi = (1 + relStdDev*fib0786Hi) * y_base lin0618Hi = (1 + relStdDev*fib0618Hi) * y_base lin0500Hi = (1 + relStdDev*fib0500Hi) * y_base lin0382Hi = (1 + relStdDev*fib0382Hi) * y_base lin0236Hi = (1 + relStdDev*fib0236Hi) * y_base lin0236Lo = (1 + relStdDev*fib0236Lo) * y_base lin0382Lo = (1 + relStdDev*fib0382Lo) * y_base lin0500Lo = (1 + relStdDev*fib0500Lo) * y_base lin0618Lo = (1 + relStdDev*fib0618Lo) * y_base lin0786Lo = (1 + relStdDev*fib0786Lo) * y_base // booleans - true if a fib level should be plotted (i.e. some point of it is between [min, max] values) bool0786Hi := rsd_min < fib0786Hi and fib0786Hi < rsd_max bool0618Hi := rsd_min < fib0618Hi and fib0618Hi < rsd_max bool0500Hi := rsd_min < fib0500Hi and fib0500Hi < rsd_max bool0382Hi := rsd_min < fib0382Hi and fib0382Hi < rsd_max bool0236Hi := rsd_min < fib0236Hi and fib0236Hi < rsd_max bool0236Lo := rsd_min < fib0236Lo and fib0236Lo < rsd_max bool0382Lo := rsd_min < fib0382Lo and fib0382Lo < rsd_max bool0500Lo := rsd_min < fib0500Lo and fib0500Lo < rsd_max bool0618Lo := rsd_min < fib0618Lo and fib0618Lo < rsd_max bool0786Lo := rsd_min < fib0786Lo and fib0786Lo < rsd_max //+-----+ // plot Fibonacci mirror // note that the "plot" function cannot be a local : ie in [function, for, if, etc] plot(bool81Hi ? lin81Hi : na, color=color.gray, linewidth=1) plot(bool27Hi ? lin27Hi : na, color=color.gray, linewidth=1) plot(bool09Hi ? lin09Hi : na, color=color.gray, linewidth=1) plot(bool03Hi ? lin03Hi : na, color=color.gray, linewidth=1) plot(bool01Hi ? lin01Hi : na, color=color.gray, linewidth=1) plot(bool0786Hi ? lin0786Hi : na, color=color.gray, linewidth=1) plot(bool0618Hi ? lin0618Hi : na, color=color.gray, linewidth=1) plot(bool0500Hi ? lin0500Hi : na, color=color.gray, linewidth=1) plot(bool0382Hi ? lin0382Hi : na, color=color.gray, linewidth=1) plot(bool0236Hi ? lin0236Hi : na, color=color.gray, linewidth=1) plot(bool00 ? lin00 : na, color=color.navy, linewidth=3) plot(bool0236Lo ? lin0236Lo : na, color=color.gray, linewidth=1) plot(bool0382Lo ? lin0382Lo : na, color=color.gray, linewidth=1) plot(bool0500Lo ? lin0500Lo : na, color=color.gray, linewidth=1) plot(bool0618Lo ? lin0618Lo : na, color=color.gray, linewidth=1) plot(bool0786Lo ? lin0786Lo : na, color=color.gray, linewidth=1) plot(bool01Lo ? lin01Lo : na, color=color.gray, linewidth=1) plot(bool03Lo ? lin03Lo : na, color=color.gray, linewidth=1) plot(bool09Lo ? lin09Lo : na, color=color.gray, linewidth=1) plot(bool27Lo ? lin27Lo : na, color=color.gray, linewidth=1) plot(bool81Lo ? lin81Lo : na, color=color.gray, linewidth=1) if barstate.islast // simple_label(last_bar_index-200, close, "rsd_min = " + str.tostring(rsd_min)) // simple_label(last_bar_index-100, close, "rsd_max = " + str.tostring(rsd_max)) // Add Fibonacci mirror-labels barLast_label(bool81Hi ? lin81Hi : na, "+81.0") barLast_label(bool27Hi ? lin27Hi : na, "+27.0") barLast_label(bool09Hi ? lin09Hi : na, "+09.0") barLast_label(bool03Hi ? lin03Hi : na, "+03.0") barLast_label(bool01Hi ? lin01Hi : na, "+01.0") barLast_label(bool0786Hi ? lin0786Hi : na, "+0.786") barLast_label(bool0618Hi ? lin0618Hi : na, "+0.618") barLast_label(bool0500Hi ? lin0500Hi : na, "+0.500") barLast_label(bool0382Hi ? lin0382Hi : na, "+0.382") barLast_label(bool0236Hi ? lin0236Hi : na, "+0.236") barLast_label(bool00 ? lin00 : na, " 0.000") barLast_label(bool0236Lo ? lin0236Lo : na, "-0.236") barLast_label(bool0382Lo ? lin0382Lo : na, "-0.382") barLast_label(bool0500Lo ? lin0500Lo : na, "-0.500") barLast_label(bool0618Lo ? lin0618Lo : na, "-0.618") barLast_label(bool0786Lo ? lin0786Lo : na, "-0.786") barLast_label(bool01Lo ? lin01Lo : na, "-01.0") barLast_label(bool03Lo ? lin03Lo : na, "-03.0") barLast_label(bool09Lo ? lin09Lo : na, "-09.0") barLast_label(bool27Lo ? lin27Lo : na, "-27.0") barLast_label(bool81Lo ? lin81Lo : na, "-81.0") // Determine the highest "active" fibLine, for labelling chart var linHighest = lin81Hi if bool81Hi linHighest := lin81Hi else if bool27Hi linHighest := lin27Hi else if bool09Hi linHighest := lin09Hi else if bool03Hi linHighest := lin03Hi else if bool01Hi linHighest := lin01Hi else if bool0786Hi linHighest := lin0786Hi else if bool0618Hi linHighest := lin0618Hi else if bool0500Hi linHighest := lin0500Hi else if bool0382Hi linHighest := lin0382Hi else if bool0236Hi linHighest := lin0236Hi else if bool00 linHighest := lin00 else if bool0236Lo linHighest := lin0236Lo else if bool0382Lo linHighest := lin0382Lo else if bool0500Lo linHighest := lin0500Lo else if bool0618Lo linHighest := lin0618Lo else if bool0786Lo linHighest := lin0786Lo else if bool01Lo linHighest := lin01Lo else if bool03Lo linHighest := lin03Lo else if bool09Lo linHighest := lin09Lo else if bool27Lo linHighest := lin27Lo else if bool81Lo linHighest := lin81Lo 08******08 #] 27May2022 Output section +-----+ olde code // olde code // //+-----+ // // Add Fibonacci mirror-labels - better setup // // 12May2022 initial // // from @TradeChartist 21Aug2020 "Simple Fibonacci Retracement" // // https://www.tradingview.com/script/mWmIRNVF-Simple-Fibonacci-Retracement/ // // fib0000Label = barLast_label(bool0000 ? fib0000 : na, " 0.000") // // fib0236HiLabel = barLast_label(bool0236Hi ? fib0236Hi : na, "+0.236") // fib0382HiLabel = barLast_label(bool0382Hi ? fib0382Hi : na, "+0.382") // fib0500HiLabel = barLast_label(bool0500Hi ? fib0500Hi : na, "+0.500") // fib0618HiLabel = barLast_label(bool0618Hi ? fib0618Hi : na, "+0.618") // fib0786HiLabel = barLast_label(bool0786Hi ? fib0786Hi : na, "+0.786") // fib1000HiLabel = barLast_label(bool1000Hi ? fib1000Hi : na, "+1.000") // fib1272HiLabel = barLast_label(bool1272Hi ? fib1272Hi : na, "+1.272") // fib1618HiLabel = barLast_label(bool1618Hi ? fib1618Hi : na, "+1.618") // fib2000HiLabel = barLast_label(bool2000Hi ? fib2000Hi : na, "+2.000") // fib2618HiLabel = barLast_label(bool2618Hi ? fib2618Hi : na, "+2.618") // // fib0236LoLabel = barLast_label(bool0236Lo ? fib0236Lo : na, "-0.236") // fib0382LoLabel = barLast_label(bool0382Lo ? fib0382Lo : na, "-0.382") // fib0500LoLabel = barLast_label(bool0500Lo ? fib0500Lo : na, "-0.500") // fib0618LoLabel = barLast_label(bool0618Lo ? fib0618Lo : na, "-0.618") // fib0786LoLabel = barLast_label(bool0786Lo ? fib0786Lo : na, "-0.786") // fib1000LoLabel = barLast_label(bool1000Lo ? fib1000Lo : na, "-1.000") // fib1272LoLabel = barLast_label(bool1272Lo ? fib1272Lo : na, "-1.272") // fib1618LoLabel = barLast_label(bool1618Lo ? fib1618Lo : na, "-1.618") // fib2000LoLabel = barLast_label(bool2000Lo ? fib2000Lo : na, "-2.000") // fib2618LoLabel = barLast_label(bool2618Lo ? fib2618Lo : na, "-2.618") // 23May2022 olde code for debugging // output iUWS-specific vars //if iUWS == 2 // simple_label(math.round(timenow - t_cycle*0.30), priceFrac0 + (priceMax - priceMin)/10,"t_mod") // simple_label(math.round(timenow - t_cycle*0.40), priceFrac0 + (priceMax - priceMin)/10,"t_cycle") // simple_label(math.round(timenow - t_cycle*0.50), priceFrac0 + (priceMax - priceMin)/10,"t_lengthUnix") // simple_label(math.round(timenow - t_cycle*0.60), priceFrac0 + (priceMax - priceMin)/10,"timenow") // simple_label(math.round(timenow - t_cycle*0.30), priceFrac0, str.tostring(t_mod)) // simple_label(math.round(timenow - t_cycle*0.40), priceFrac0, str.tostring(t_cycle)) // simple_label(math.round(timenow - t_cycle*0.50), priceFrac0, str.tostring(t_lengthUnix)) // simple_label(math.round(timenow - t_cycle*0.60), priceFrac0, str.tostring(timenow)) // plot all n_spikes // write debug values for iUWS = 2 (max lambda that fits into t_lengthUnix) // t_spike shown is for last line, close to n_bars // output spike-specific vars //if iUWS == 2 // simple_label(math.round(timenow - t_cycle*0.05), priceFrac0 + (priceMax - priceMin)/10,"t_spike") // simple_label(math.round(timenow - t_cycle*0.15), priceFrac0 + (priceMax - priceMin)/10,"n_spikes") // simple_label(math.round(timenow - t_cycle*0.05), priceFrac0, str.tostring(t_spike)) // simple_label(math.round(timenow - t_cycle*0.15), priceFrac0, str.tostring(n_spikes)) var float year_fractionBeg = 0.0 var float year_fractionEnd = 0.0 if barstate.isfirst year_fractionBeg := year_fraction if barstate.islast year_fractionEnd := year_fraction // reverted to older version in a section below "1926-2020 "Fibonnacci mirror trendlines" // 19May2022 NUTS!!! throw out 5 days of work because I forgot PineScript can't : // handle arrays of series // call plot in a function or if // price equilibrium for 1871-1926, much smaller slope // expnt =10^( 0.784617 + (0.000140925*(yearAD - 1871.08))) // calculate trendline // calc_priceSP500_1926_2020(yearAD) => // expnt = 0.792392+0.0289587*(yearAD - 1926.25) // SP500base = math.pow(10,expnt) // qnial> calc_priceSP500_1926_2020 IS OP yr { 10 power (0.792392 + (0.0289587*(yr - 1926.25))) } // qnial> EACH calc_priceSP500_1926_2020 1926 2020 // 6.09751 3215.66 // >> perfect (n't cheque accuracy) // NUTS!! time in years is argument, NOT price!! // 23May2022 do NOT declare with 'var'!!! : // var float priceBaseBeg = 0.0 // var float priceBaseEnd = 0.0 // // if barstate.isfirst // priceBaseBeg := calc_priceSP500_1926_2020(year_fraction) // // if barstate.islast // priceBaseEnd := calc_priceSP500_1926_2020(year_fraction) // line.new(bar_index, priceBaseBeg, 0, priceBaseEnd, xloc = xloc.bar_index, color=color.black, width=3) // The variance of the 83y trend is from the data only - just use relStdDev 1926-2020 // see "$d_webRawe"'economics, markets/SP500/multi-fractal/SP500 1872-2020 TradingView, 1928-2020 yahoo // relStdDev = 0.4308 // +-----+ // This is my older attempt to plot Fibonacci priceFractals,hich "sort of works" // it lacks a "fractal nesting" like the Petz timeFractals below // the standard TradingView timescales "1" and 5Y" are scruched so they don't span the vertical axis. // I don't know why? //+-----+ // Failed attempt to use line.new, and implement nested price fractals // 23May2022 I revert to the olde code below after spending 2 weeks trying to implement all this by // line.new. I abandoned that because I couldn't achieve an "anchored line.new, // and I ran inttoblems with nested [for, if, for, if,. ..). Too bad, and VERY frustrating. // Leonardo Bonacci, Leonardo of Pisa, or Leonardo Bigollo Pisano ('Leonardo the Traveller from Pisa') // https://en.wikipedia.org/wiki/Fibonacci_number // common fib = [ 0.382, 0.618, 0.786, 1.000, 1.272 ] // 12May2022 initial // from @TradeChartist 21Aug2020 "Simple Fibonacci Retracement" // https://www.tradingview.com/script/mWmIRNVF-Simple-Fibonacci-Retracement/ // find fibonacci index range for current chart // // the ratio-of-3 applies to all fractal types at hiLevel // // note : very rapid price-growth stocks won't fit in this (eg. cryptos over early years) // var int n_ary_fracZone = 9 // ary_fracZone = array.from(1/81.0, 1/27.0, 1/9.0, 1/3.0, 1.0, 3.0, 9.0, 27.0, 81.0) // // // // ary_fracLevels [Fibonacci, Puetz], 21May2022 Liebnitz not started yet // // note that fracLevels [0, .0] are missing - as ary_fracZone puts those in // // note the "somewhat close" levels of [Fibonacci, Puetz] levels // // for implications, see "?my webPage?" // var int n_ary_fracLevel = 5 // // ary_fracfib = array.from(0.236, 0.381, 0.500, 0.618, 0.786) // ary_fracPuetz = array.from(0.250, 0.333, 0.500, 0.667, 0.750) // // // var bool flagFracUsed = false // var ary_fracUsed = array.new_float(n_ary_fracLevel, 0.0) // if fracTyp == "Fibonacci" // ary_fracUsed := array.copy(ary_fracfib) // flagFracUsed := true // else if fracTyp == "Liebnitz" // simple_label( 100, priceBaseEnd, "Liebnitz not yet coded (far more complex - Fractional Order Calculus)") // flagFracUsed := false // else if fracTyp == "Puetz" // ary_fracUsed := array.copy(ary_fracPuetz) // flagFracUsed := true // else // simple_label( 100, priceBase, "Unrecognized fracTyp") // flagFracUsed := false // 21May2022 There are, at present, only two "hierarchical levels" of priceFractals : // Upper zones - factor-of-[2,3] timeFracs (zones) which encompases full priceRatio // [above, below] semi-log price trend // Lower levels - encompase "standard fractal levels" for EACH of the upper levels // could use some criteria for determining whether lower (or even deeper) levels should be use // NOTE : the 1926-2020 semi-log trendline ALWAYS increases with time!! Makes coding simpler... // 22May2022 does not yet recurse to levels < first loLevel // EACH "lower level" always spans only one of the "higher levels", // low levels : lo matches last hiLevel, hi matches current hiLevel // will miss priceFrac lines just [above Hi, below Lo] // 18May2022 can reduce number of priceFrac lines.. maybe later // 19May2022 this coding is very finicky! I mixed up [float, ary]s // [line, label].new EACH "fractal [zone, level] between [priceMin, priceMax]" // above priceBase, high priceFracs //drawPriceFracs() => // var string txt = "" // var float factorZone = 0.0 // var float factorFrac = 0.0 // var float priceFracBeg = 0.0 // var float priceFracEnd = 0.0 // for i_zone = (n_ary_fracZone - 1) to 0 // factorZone := array.get(ary_fracZone, i_zone) // priceFracBeg := priceBaseBeg * factorZone // priceFracEnd := priceBaseEnd * factorZone // if i_zone == 1 // txt := "i_zone = " + str.tostring(i_zone) + "; priceBaseBeg = " + str.tostring(priceBaseBeg) + "; priceFracBeg = " + str.tostring(priceFracBeg) // label.new(0, priceFracEnd, txt, xloc=xloc.bar_index, textcolor = color.black, color = na, style=label.style_label_left, size=size.large) // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // line.new(bar_index, priceBaseBeg, 0, priceBaseEnd, xloc = xloc.bar_index, color=color.black, width=3) // if i_zone == 1 // txt := "(1) relStdDev * " + str.tostring(i_zone) // label.new(bar_index, priceFracEnd, txt, xloc = xloc.bar_index, textcolor = color.black, color = na, style=label.style_label_left, size=size.large) // if priceFracEnd >= priceBaseEnd // for i_level = (n_ary_fracLevel - 1) to 0 // factorFrac := factorZone * (1 + array.get(ary_fracUsed, i_level)*relStdDev) // priceFracEnd := priceBaseEnd * factorFrac // // safer to use priceFracEnd as well - maybe later // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // line.new(bar_index, priceFracEnd, 0, priceFracEnd, color=color.black, width=3) // if i_zone == 1 // txt := "(2) " + str.tostring(array.get(ary_fracUsed, i_level)) // //label.new(bar_index, priceFracEnd, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.normal) // true // else // break // else if priceFracEnd < priceBaseEnd // for i_level = 0 to (n_ary_fracLevel - 1) // factorFrac := factorZone * (1 - array.get(ary_fracUsed, i_level)*relStdDev) // priceFracEnd := priceBaseEnd * factorFrac // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // line.new(bar_index, priceFracEnd, 0, priceFracEnd, color=color.black, width=3) // if i_zone == 1 // txt := "(2) " + str.tostring(array.get(ary_fracUsed, i_level)) // label.new(bar_index, priceFracEnd, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.normal) // else // break // // remove comments for now : // // safer to use priceFracEnd as well - maybe later // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // // differs according to priceFracEnd [below, above] priceBase // if priceFracEnd >= priceBase // // safer to use priceFracEnd as well - maybe later // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // // // // barstate.islast and // if barstate.islast and flagFracUsed // drawPriceFracs() //User must turn OFF : SP500 axis menu -> Labels -> Indicators and financials name labels (no checkmark) //+-----+ //+--+ // Constants and dummy values // In order to reduce memory requirements and calculations (thousands of times for each variable), // I am using "dummy values" initially, which are replaced by actual values when barstate.islast. // This has been strangely difficult to do, as it isn't easy to understand how Pine Script works when you // don't read the manuals. // old version (better) 220518 16h07m4?s // simple_label(t,series,_txt) => // var label lbl = na // label.delete(lbl) // lbl:=label.new(t, series, _txt, xloc = xloc.bar_time, textcolor = color.black, color = na, style=label.style_label_left, size=size.large) // 27May2022 didn't wok // if flagSpike // if iUWS < 2 // initSpike := 1 // else // initSpike := 0 // for i_spike = initSpike to (n_spikes - 1) // line.new(t_spike, priceMin, t_spike, priceMax, xloc = xloc.bar_time, color=color.black, width=iUWS + 1) // // label each spike with its fractal depth# // time_label(t_spike, priceMax, 0, str.tostring(iUWS)) // t_spike := t_spike - t_cycle // spikeSpaces = "" // for i_space = 0 to iUWS // spikeSpaces := spikeSpaces + " " // 24************************24 // track variables // simple_label( 20, priceBase + (priceMax - priceMin)/10,"t_lengthUnix") // simple_label( 40, priceBase + (priceMax - priceMin)/10,"timenow") // simple_label( 20, priceBase, str.tostring(t_lengthUnix)) // simple_label( 40, priceBase, str.tostring(timenow)) // +-----+ // 13May2022 write debug values for key variables to chart // simple_label( 70, priceBase + (priceMax - priceMin)/10, "UWS_periodBase t_lengthYear maxUWSLamdaIdx timeframe.period timeIdx n_bars") // simple_label( 20, priceBase, str.tostring(n_bars)) // simple_label( 40, priceBase, str.tostring(timeIdx)) // simple_label( 60, priceBase, timeframe.period) // simple_label( 80, priceBase, str.tostring(maxUWSLamdaIdx)) // simple_label(100, priceBase, str.tostring(t_lengthYear)) // simple_label(120, priceBase, str.tostring(array.get(UWS_lambda, 2))) // simple_label(140, priceBase, str.tostring(array.get(lambda, 2))) // simple_label(160, priceFrac0, str.tostring(UWS_periodBase)) // simple_label(math.round(timenow - t_cycle*0.30), priceBase + (priceMax - priceMin)/10,"t_mod") // simple_label(math.round(timenow - t_cycle*0.40), priceBase + (priceMax - priceMin)/10,"t_cycle") // simple_label(math.round(timenow - t_cycle*0.50), priceBase + (priceMax - priceMin)/10,"t_lengthUNIX") // simple_label(math.round(timenow - t_cycle*0.60), priceBase + (priceMax - priceMin)/10,"timenow") // simple_label(math.round(timenow - t_cycle*0.30), priceBase, str.tostring(t_mod)) // simple_label(math.round(timenow - t_cycle*0.40), priceBase, str.tostring(t_cycle)) // simple_label(math.round(timenow - t_cycle*0.50), priceBase, str.tostring(t_lengthUNIX)) // simple_label(math.round(timenow - t_cycle*0.60), priceBase, str.tostring(timenow)) 08******08 #] 26May2022 +-----+ olde code : // Add fib labels - this is a crappy, simple text, doesn't help much with models // User must turn OFF : SP500 axis menu -> Labels -> Indicators and financials name labels (no checkmark) // 12May2022 initial // SP500 1926-2020 semi-log trend (navy blue trend) // gray lines above trend : (1 + fib*relStdDev/2) * fib0000 // gray lines below trend : (1 - fib*relStdDev/2) * fib0000 // where fib = [ 0.382, 0.618, 0.786, 1.000, 1.272 ] // relStdDev = 0.4308 +-----+ #] 24May2022 PineScript, SP500USD chart - multi-fractal on-chart comments Chart title : USA multi-markets, with SPX500USD [time, price] multiFractals font : 20point, black, bold /media/bill/Dell2/Website - raw/economics, markets/SP500/multi-fractal/220524 USA multi-markets, with SPX500USD [time, price] multiFractals multi-fractals, Benoit Mandelbrot said : [time, price] multi-fractals : Benoit Mandelbrot said that the true power of fractals only emerges when time is one of the fractal dimensions. missing features : 23May2022 Puetz "Half-UWS" spikes were considered, but I fear would clutter the chart too much. Just imagine that there is a spike between each of the time spikes that do appear (which are UWS only: sequences of [*,/] by a factor of three) 23May2022 My intent was to give multiple fractal options for both time and price, adding [Liebnitz, Elliot, Prechter] to [Fibonacci, Puetz], but I won't get to that for now. PineScript coding [bugs, issues] : the Fibonacci priceFractals are NOT nested!! - this is critical to the nature of fractals PineScript coding is NOT stable!!! - results aren't consistent even when I repeat the same thing with no code changes! - I suspect this might be because I am not properly forcing variables to be constants 23May2022 Standard time-views "1Y" and "5Y" show a "compacted, scrunched" SP500USD that spans only a fraction of the chart. A bug fix will have to wait for a few months. ary_n_bar -> can cause scrunching of outputs!!! - 27May2022 PineScript provides no bug-free means of getting n_bars. - I did it by trial & error for each time period and even then...it isn't so good - I always use the same window size, and expect that n_bars eall change for different windows if the window size matters, it might be possible to put that into a formula time_label(timer, serPrice, priceOffset, txt) => - couldn't get to work could not get line.new to word - nested [for, if] expressions only seem to work for a couple of levels see "WARNINGS! Pine Script coding" in the script itself for many more details Puetz "Universal Wave Series" (UWS) timeFractals : The Puetz "Universal Wave Series" (UWS) timeFractal applies to hugely diverse themes including (physics, astronomy, geology, major extinction events, history, war, psychology, sociology, financial markets). If the "non-optimized time spikes" (vertical lines) appear to relate to market symbol movements at all standard TV timescales (eg 1D 5D 1M 3M 6M 1Y 5Y All), then : - they may be saying something far (broader, deeper) about time series than anything other than Puetz that I know of (eg. far beyond the Mayan system of 20+ calendars) - or is it just another example that human (senses, brain) always infer correlations and and patterns? not used : (Ordovician, Devonian, Permian, Triassic, Cretaceous) Fibonacci priceFractals (= 1926-2020 stdDev semilog) : Fibonacci priceFractals are hard-bound to the SP500USD 1926-2020 semi-log trend line and standard deviation. So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics. Fibonacci priceFractals are hard-bound to the SP500USD 1926-2020 semi-log trend line and standard deviation. (fib = number of stdDev) So they are tied to the SPXUSD over the last 83+ years, but are NOT related to current market specifics. models can enlighten AND blind you : WARNING: While models can help us better understand reality, they also (bias, blind) us to it as well. As science (fashions -> cults -> religions), the religions' (priests, disciples)*(suppress, destroy) the rare rebels who are our only hope for progress. SP500 1926-2020 semi-log trend, standard deviation : SP500 1926-2020 semi-log trend = 10^(0.792392+2.89587*10^(-2)*(year - 1926.25)) price revolution* (~7%/y) SP500 1872-1926 semi-log trend = 10^(0.784617+1.40925*10^(-4)*(year - 1871.08)) price equilibrium* (~0.03%/y) *David Fischer 1996 "The Great Wave, Price revolutions and the rhythm of history" +-----+ #] 11May-??May2022 Proj-mini 'Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' "$d)webRawe"'Software programming & code/PineScript for TradingView market charts/Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' +-----+ #] 23May2022 TradingView - Publish script "SP500USD (time, price) multi-fractals" https://www.tradingview.com/script/qQd2lucH-SP500USD-time-price-multi-fractals/ SP500USD (time, price) multi-fractals (time, price) multi-fractals : Benoit Mandelbrot said that the true power of fractals only emerges when time is one of the fractal dimensions. Stephen Puetz's "Universal Wave Series" (UWS) provides the time fractal, whereas Fibonacci priceFractals are used here. The intent was to give multiple fractal options for both time and price, but I won't get to that any time soon. The 1926-2020 SP500 semi-log (trend, standard deviation) provides the basis of the priceFractals, whereas a FIXED date (Unix 01Jan1977) is taken as the basis of the timefractals (I have not properly shifted, adapted it to fit Puetz's actual series, which is fixed, with allowance for time lags for each factor) . That means that appearances of some kind of "rough "fit" of the (time, price) fractals to the actual SP500 movements, or all standard timescales of the TradingView charts (eg 1D 5D 1M 3M 6M 1Y 5Y All) may or may not be surprising, and may or may not be saying something far beyond any other time series analysis that I've seen (kind of like the s of 20+ Mayan calendars). Keep in mind that this script is just a first, incomplete shot, full of bugs. 23May2022 Standard time-views "1Y" and "5Y" show a "compacted, scrunched" SP500USD that spans only a fraction of the chart. (coding bug) 23May2022 Puetz UWS (0.33, 0.66, 1.0) timeFractals are shown nested, but I'm missing the half-UWS cycles (HUWS) : (0.25, 0.5, 0.75). Each cycle is 3* the cycle below it, 1/3* the one above. While (UWS + HUWS) approaches a Fourier Series in a very crude way, it is still remarkable that such a strong portion of known cycles across many orders of magnitude (seconds to billions of years) fit the stringent 5% criteria to qualify as a UWS member. ********************* Here's my very incomplete implementation of multi-fractals, based on Stephen Puetz's fantastic "Universal Wave Series" (UWS). tradingview.com/chart/qJVK80J7/ I just now reverted to my older Fibonnacci priceFractal coding, which is not time-nested, whereas the Puetz timeFractals are. I've been beaten up too much by PineScript coding over the last few weeks, so I won't go the next steps. Ultimately, what I really wanted was to look at : 1) Leibnitz fractals via his "Fractional Order Calculus" - maybe that would lead to something like your diagonals? 2) Elliot Waves 3) Prechter Socionomics Another question is if Sacha Dobler's books "Solar History", "Solar behaviour", and "Hormonageddon" might provide unifying concepts on the very short term (<<100,000 years). Keep in mind that Puetz's UWS scales to billions of years, and across a big chunk of conceptual themes from (physics, astronomy, geology, 5-7? giant biological extinctions (eg Cambrian, Permian, Silurian, ..., Cretaceous :(ALL, <1 year) ?? find out some other day +-----+ #] 23May2022 status - drawPriceFracs() compiles but doesn't work : Return type of one of the 'if' or 'switch' blocks is not compatible with return type of other block(s) (series string; void) #] 23May2022 @fract - use of [vertical, angled] timeFractals https://www.tradingview.com/chart/BTC1!/6w5z7XIi-Bitcoin-Futures-TIMEFIBS/#tc8564286 Bitcoin Futures TIMEFIBS Bitcoin CME Futures (CME:BTC1!) 29125 110 0.38% fract 3 hours ago TImeFibs are there to decrypt the cycles and warn ahead of market reversals. Nearest TimeFibs: 1.618 at 20 Jul '22 1.786 at 6 Sep '22 Bill_Howell, 2 hours ago Brilliant & Awesome @fract!!! You're using vertical timeLines, rather than the oblique cross-hatches of much of your work. That is the app Bill_Howell, 2 hours ago Rewrite as the text was chopped by the cheer : Brilliant & Awesome @fract!!! You're using vertical timeLines, rather than the oblique cross-hatches of much of your work. That is the approach that I am taking, as it is much more (simple, clear) and amenable to Pine Script programming. However, my very simple script, which should have taken <= 3 days, has consumed 3 weeks (since 04May2022) of (time, frustration) even though I had a skeleton "multi-fractal" program from Sep2020 (almost 2 years ago). PineScript is wickedly different in minor grammatical details, and I'm always forgetting the "series" approach as opposed to "arrays". I abandoned work back in Sep2020 because it was taking too long, the same is about to happen this time around too. fract,16 minutes ago @Bill_Howell, Thank you. I personally prefer angled fib channels because they carry information about average steepness of trend in respect to timing. The vertical TimeFibs and horizontal Fib retracement is perceived easier. I agree with that one. However, Fibonacci Channels approach shows a more accurate market simulation. BTW thanks for TVCoins Bill_Howell, just now @fract, I agree, the angles convey important information. But for the last three days, I can get timeFractals, but not priceFractals with my Pine Script. It's very frustrating, especially as I am trying to do something so simple, and my use of the QNial programming language + Unix (command, utility)s would be vastly more (fast, powerful). But the TradingView tie-in is too important - I am far too lazy to update data, so concepts are forgotten and mistakes repeated without TradingView. #] 23May2022 didn't work, no idea why : if barstate.islast and i_zone == 1 #] 22May2022 array.from - creats series from a list of [number, str, etc] https://wallstreetinvests.com/new-features-in-pine-script-str-format-and-array-from/ admin2, June 7, 2021 8:11 am No Comments &&&&&&&& Howell blog : Thanks - I had trouble finding anything like array.from in the documentation (didn't notice the expression). 08******08 #] 21May2022 fracPice - plot Fibonacci mirror - 21May2022 this makes NO SENSE! Just plot lines!!! 22May2022continue conversion from plot to line,new +-----+ olde code see "$d_weRawe'Software programming & code/PineScript for TradingView market charts/220519 20h55m45s Howell - SP500 with 83 year Fibonacci trend, PineScript - givp arrays.txt' partal examples below // 11May2022 adaptations fib0000_base = calc_yTrend(year_fraction) // Fibonaccis that are used. // This could be reduced by using the factors below and "swap series variables" : // fib00557_plus = (1 + 0.0557*stdDev/2) * fib0000_base ... // plot Fibonacci mirror - 21May2022 this makes NO SENSE! Just plot lines!!! // ... //+-----+ // Add fib labels - this is a crappy, simple text, doesn't help much with models // 12May2022 initial // SP500 1926-2020 semi-log trend (navy blue trend) // gray lines above trend : (1 + fib*stdDev/2) * fib0000_base // gray lines below trend : (1 - fib*stdDev/2) * fib0000_base // where fib = [ 0.382, 0.618, 0.786, 1.000, 1.272 ] // stdDev = 0.4308 // from @TradeChartist 21Aug2020 "Simple Fibonacci Retracement" // https://www.tradingview.com/script/mWmIRNVF-Simple-Fibonacci-Retracement/ Fib_label(y,_txt) => var label lbl = na label.delete(lbl) lbl:=label.new(bar_index, y, _txt, textcolor = color.black, color = na, style=label.style_label_left) fib0000_baseLabel = Fib_label(y_min < fib0000_base and fib0000_base < y_max ? fib0000_base : na, " 0.000") ... // add PriceFractal labels priceFrac_label(y,txt) => var label lbl = na label.delete(lbl) lbl:=label.new(bar_index, y, txt, textcolor = color.black, color = na, style=label.style_label_left) prep_priceFracLine(i_priceFrac, i_fracLo, i_fracHi) => var float fibber = 0.0 var priceFracLine = array.new_float(n_bars, 0.0) for i_priceFrac = i_fracLo to i_fracHi fibber := array.get(ary_fib, i_priceFrac) priceFrac_label(2000, str.string(fibber)) priceFracLine := ratio_to_frac(priceFrac0 * fibber, stdDev) var ary_priceFracLine00 = array.new_float(n_bars, 0.0)- // olde code // and (priceMin < priceFracHi) // var int i_hiLevelMin = 0 // var int i_hiLevelMax = 0 // var int i_loLevelMin = 0 // var int i_loLevelMax = 0 // 22May2022 see what happens without this part... // // // // [line, label].new EACH "fractal [zone, level] between [priceMin, priceMax]" // above priceBaseEnd, high priceFracs // var int i_zone = 0 // var int i_level = 0 // // below priceBaseEnd // for i_zone := 0 to (n_ary_fracZone - 1) // multiplier := array.get(ary_fracZone, i_zone) // priceFracBeg := priceBaseBeg * multiplier // priceFracEnd := priceBaseEnd * multiplier // // safer to use priceFracBeg as well - maybe later // if (priceMin <= priceFracEnd) and (priceFracEnd <= priceMax) // line.new(bar_index[n_bars], priceFracBeg, bar_index[0], priceFracEnd, color=color.black, width=1) // txt := "(1) stdDev multiplier = " + str.tostring(i_zone) + "^(-3)" // label.new(bar_index, priceFracEnd, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.large) // for i_level := (n_ary_fracLevel - 1) to 0 // multiplier := multiplier / (1 + array.get(ary_fracUsed, i_level)*stdDev) // priceFracBeg := priceBaseEnd * multiplier // if priceFracBeg >= priceMin // line.new(bar_index[n_bars], priceFracBeg, bar_index[0], priceFracEnd, color=color.black, width=1) // txt := "(2) -" + str.tostring(array.get(ary_fracUsed, i_level)) // label.new(bar_index, priceFracBeg, txt, textcolor = color.black, color = na, style=label.style_label_left, size=size.normal) // else // break 08******08 #] 17May2022 drawVerticalLines() drawVerticalLines() => for iUWS = 0 to 4 flagSpike = true t_cycle = array.get(lambda, iUWS) t_mod = t_length / t_cycle // find last, closest] spike in t_length if t_mod > t_length flagSpike = false if t_mod == 0.0 t_lastSpike = timenow // last spike during t_length n_spikes = math.round(((t_length - t_mod) / t_cycle)) + 1 else if t_mod < t_length t_lastSpike = timenow - t_mod n_spikes = math.round(((t_length - t_mod) / t_cycle)) if flagSpike // t_lag = t_cycle * cos(array.get(phi, iUWS)) // 16May2022 ignore for now for i_spike = 0 to (n_spikes - 1) offset = ??????? (timenow - t_lastSpike) / t_length * n_bars line.new(bar_index[offset], y_min, bar_index[offset], y_max, color=color.black, width=n) t_lastSpike = t_lastSpike - t_cycle line 490: Syntax error at input 'iUWS'. see "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/0_PineScript errors.txt' https://kodify.net/tradingview/errors/syntax-error-input/ Something wrong with Daily chart - very low resolution now? >> avoid for now, see if other spikes are put on chart var int offset = 0 offset := math.floor((timenow - t_lastSpike) / t_lengthUNIX * n_bars) +-----+ olde code drawVerticalLine(offset,lineThick) => line.new(bar_index[offset], y_min, bar_index[offset], y_max, color=color.black, width=lineThick) var float UWS_periodLoLo = array.get(lambda, 0) / t_length*n_bars var float UWS_periodLoHi = array.get(lambda, 1) / t_length*n_bars var float UWS_periodBase = array.get(lambda, 2) / t_length*n_bars var float UWS_periodHiLo = array.get(lambda, 3) / t_length*n_bars var float UWS_periodHiHi = array.get(lambda, 4) / t_length*n_bars if math.round(bar_index % UWS_periodLoLo) == 0 drawVerticalLine(0, 1) if math.round(bar_index % UWS_periodLoHi) == 0 drawVerticalLine(0, 2) if math.round(bar_index % UWS_periodBase) == 0 drawVerticalLine(0, 3) if math.round(bar_index % UWS_periodHiLo) == 0 drawVerticalLine(0, 4) if math.round(bar_index % UWS_periodHiHi) == 0 drawVerticalLine(0, 5) 08******08 #] 16May2022 KEY!! kodify.net - How to correct TradingView’s ‘end of line without continuation’ error? https://kodify.net/tradingview/errors/end-line-without-continuation/ How to correct TradingView’s ‘end of line without continuation’ error? With a clever use of indentation and whitespace the code of our TradingView indicator and strategy scripts becomes easier to read. But indentation is a precise matter: a single space can make our script error with ‘end of line without continuation’. Let’s see what that error is about. TradingView is quite strict when it comes to whitespace: a single space here or there can make all the difference. When we mess up our script’s indentation, chances are we run into the ‘end of line without continuation’ error. With that error two things can happen. When our script already runs on the chart, we’ll see the general ‘cannot compile script’ error there: These are the indentation rules that TradingView Pine has (TradingView Wiki, 2018a, 2018b, 2018c): When we take one statement and spread it out over multiple lines, we’ll have to indent those extra lines as follows: Additional lines of a multi-line statement are indented with 5 spaces or the equivalent 1 tab plus a space. When we make a multi-line function, each line of code inside that function’s body has to be indented with 4 spaces or 1 tab. Should we make a multi-line statement inside a multi-line function, then we indent each additional line of that statement with at least 9 spaces or 2 tabs plus a space. We indent code of an if/else statement with 4 spaces or 1 tab. Should our if statement contain another if or if/else statement, then we indent that additional if statement with 8 spaces or 2 tabs. We indent code of a loop with 4 spaces or 1 tab. # Tip: quickly see indentation in TradingView’s Pine Editor To see how much whitespace a particular line of code uses, we only need to look for small vertical bars in the Pine Editor: Those little vertical bars appear at each 4 spaces or 1 tab. So when our line is indented with Tab, we don’t see the vertical bar (because the first letter of the line of code appears there). But if our code is indented with say 5 spaces, the vertical bar is visible. In other words, here’s how the vertical bar should appear in our script code: We should see the vertical bar with multi-line statements since these are indented with at least 5 spaces (1 tab + space). We should not see the vertical bar with multi-line functions, if statements, and loops. That’s because these are all indented with one tab (4 spaces). When our multi-line function, if statement, or loop contains another multi-line function, if statement, or loop, then we should see one vertical bar. That’s because we’ll need 2 tabs (8 spaces) of indentation, and the vertical bar appears at the 1 tab (4 spaces) level. +--+ olde code // 12May2022 problem - compresses y_axis at higher timescales // drawVerticalLine(offset) => // line.new(bar_index[offset], y_min, bar_index[offset], y_max, color=color.black, width=1) // 13May2022 for now - just plot the array.get(UWS_lambda, timeIdx + 2) period converted to number of bars // 13May2022 didn't work - compresses output on graph at lower timescales drawVerticalLine(offset,lineThick) => line.new(bar_index[offset], y_min, bar_index[offset], y_max, color=color.black, width=lineThick) var float UWS_periodLoLo = array.get(lambda, 0) / t_length*n_bars var float UWS_periodLoHi = array.get(lambda, 1) / t_length*n_bars var float UWS_periodBase = array.get(lambda, 2) / t_length*n_bars var float UWS_periodHiLo = array.get(lambda, 3) / t_length*n_bars var float UWS_periodHiHi = array.get(lambda, 4) / t_length*n_bars if math.round(bar_index % UWS_periodLoLo) == 0 drawVerticalLine(0, 1) if math.round(bar_index % UWS_periodLoHi) == 0 drawVerticalLine(0, 2) if math.round(bar_index % UWS_periodBase) == 0 drawVerticalLine(0, 3) if math.round(bar_index % UWS_periodHiLo) == 0 drawVerticalLine(0, 4) if math.round(bar_index % UWS_periodHiHi) == 0 drawVerticalLine(0, 5) junk never used : var float t_anchor = 1800.0 t_now = timenow mod_spikes = n_spikes % 1.0 if mod_spikes == 0.0 n_spikes := n_spikes + 1 if i_spike == 1 if mod_spikes == 0.0 offset = 0 08******08 #] 13May2022 variable assignment in Pine script // https://www.tradingview.com/chart/u4klPKBn/ // variable assignment in Pine script // There are four operators to know here. // = is used when you declare a variable. // := is used when you want to assign a new value to an already declared variable. // [] is called history reference operator and used when you want to access historical data of a variable. For example, close[1] returns the close price of one bar ago. // nz(): Replaces NaN values with zeros (or given value) in a series. // To understand this last part, know that your script will be executed on each bar. When you want to have some constant information when you go from one bar to the next, this is how you (used to) do it. Because it will keep updating its value with the previous value, so its value will remain the same. // answered Nov 18, 2021 at 12:10, vitruvius +-----+ #] 13May2022 search "Pine Script and how to Plot Vertical Lines?" // https://quantnomad.com/faq-how-to-plot-vertical-lines-in-pine-script/ // How to Plot Vertical Lines in Pine Script? FAQ, Pine / By admin // if (barstate.islast) line.new(bar_index, close, bar_index, close * 1.01, extend = extend.both, color = color.green, style = line.style_dotted, width = 3) // https://stackoverflow.com/questions/47610638/how-to-draw-a-vertical-line-in-tradingview-pine-script // How to draw a vertical line in TradingView pine script? // If anyone is interested in using the new v4 line.new() function: // LineLengthMult = 10 // LineLength = atr(100) * LineLengthMult // // drawVerticalLine(offset) => // line.new(bar_index[offset], low-LineLength, bar_index[offset], high+LineLength, color=color.new(color.yellow, 50), width=3) // // if bar_index % 21 == 0 // drawVerticalLine(0) // Note: Adjust LineLengthMult as desired. // EDIT: Answer updated with code that auto-scales the vertical lines. // edited Jul 14, 2020 at 1:49 // answered Jul 7, 2020 at 2:13, André // Dany's answer did not display anything on the chart for me, however setting the style to a histogram did the trick. // plot((time == timestamp(2019,01,01,0,0)) ? 10e20 : na, // color = red, linewidth = 10, title = "27", style = histogram) // plot((time == timestamp(2019,01,02,0,0)) ? 10e20 : na, // color = green, linewidth = 10, title = "28", style = histogram) // answered Feb 1, 2019 at 2:16, tergd1 +-----+ olde code // old version // https://www.tradingview.com/pine-script-docs/en/v4/appendix/HOWTOs.html#count-bars-in-a-dataset // Find the highest and lowest values for the entire dataset // 20Mar2021 Howell - adapt this for viewable data // // biggest(series,size) => // max = 0 // for i = 0 to size // if series[i] > max // max := series[i] // max // // smalest(series,size) => // min = 1e5 // for i = 0 to size // if series[i] < min // min := series[i] // min // // ?date, source? // y_min = smalest(close,n_bars) // y_max = biggest(close,n_bars) // 13May2022 https://kodify.net/tradingview/bar-data/highest-high-lowest-low/ // How to get the highest high or lowest low in TradingView Pine? // Doesn't work // // y_min = highest(close,n_bars) // y_max = lowest(close,n_bars) // 13May2022 doesn't work : float int conflict // x = 0 // _txt = "hello" // var lbl = label.new(bar_index, x, _txt, textcolor = color.black, color = na, style=label.style_label_left) // // Fib_label(x,_txt) => // label.set_x(lbl, x) // label.set_text(lbl, _txt) // 13May2022 https://www.tradingcode.net/tradingview/largest-maximum-value/ // Get the largest value from several numbers in Pine Script // back to same problem with PineScript - updates as progresses // ta.[highest, lowest](close,n_bars), math.[max,in](close,n_bars) y_min = math.min(close,n_bars) y_max = math.max(close,n_bars) 08******08 #] 11May2022 TradingView, jbrothersjr : Revisiting a long term trend line, S&P 500 Index (FX:SPX500) see "$d_webRawe"'Software programming & code/PineScript for TradingView market charts/Howell - SP500 with 83 year Fibonacci trend, PineScript.txt' +-----+ SP500 multi-fractal : 1926-2020 semi-log trend; Puetz "Universal Wave Series" temporal nested cycles Benoit Mandelbrot said that "fractals don't reach their true power until used as multifractals, where time itself is a fractal dimension". It just so happens that Stephen Puetz came up with by far the most stunning relationship for common temporal cycles that I have ever seen. It is like expanding the Mayan system of 20+ calendars expanded [far, far] beyond anything that would have ever imagined. Luckily, the UWS is dead simple : cycles are simply are factor of 3 times the previous (lower) value in the series. Normally, I would not have considered this to be a fractal system, but on closer inspection of definitions, perhaps it does qualify? Furthermore - the series is fixed across themes, so one only has to pick some time period, and that defines the rest of the entire series. As one complicaton, a number of standard periodicities do not fit the UWS according to Puetz's tough criteria. Some of these do ft a Double-UWS series (or half, but most recent papers of Puetz focus on the Double-UWS). At the present moment, two cycles of 3 (almost) come to mind from history : 1. Thucydides ~409 BC "Peloponesian Wars" (Athens versus Sparta) - oracles predicted at the outset that the war would last 3*9 = 27 years 2. Ibn Khaldun ~410 AD "The Muqquadimah" - societies tend to decay within three (or four) generations of heroic times This doesn't mean anything, but what if a "generation" in Ibn Khaldun's time was approximately 27 years? 3*9*3 = 3^4 years = 81 years, which doesn't seem to fit much except perhaps some climate (ocean) cycles? In any case, Puetz has ccted a large number of UWS cycles across a very braod range of themes. qnial> (8.691143E-03 2.607343E-02 7.822029E-02 2.346608E-01 7.039826E-01 2.111947E+00 6.335843E+00 1.900753E+01 5.702259E+01 1.710677E+02 5.132033E+02) * 365.25 3.17444 9.52332 28.57 85.7099 257.13 771.389 2314.17 6942.5 20827.5 62482.5 187448. 562343. qnial> (9.656826E-04 2.897047E-03) * 365.25 0.352716 1.05815 qnial> (1.072980E-04 3.218942E-04) * 365.25 0.0391906 0.117572 Full series : qnial> (1.072980E-04 3.218942E-04 9.656826E-04 2.897047E-03 8.691143E-03 2.607343E-02 7.822029E-02 2.346608E-01 7.039826E-01 2.111947E+00 6.335843E+00 1.900753E+01 5.702259E+01 1.710677E+02 5.132033E+02) * 365.25 Hours : qnial> (0.0391906 0.117572 0.352716 1.05815 3.17444 9.52332) * 24 0.940574 2.82173 8.46518 25.3956 76.1866 228.56 +-----+ https://www.tradingview.com/chart/SPX500USD/N6WmJNrr-SP500-versus-1926-2020-semi-log-trend-with-Fibonacci-mirror/ Howell additional comment : I added labels for the 1926-2020 semi-log trend, so that Fibonacci levels can be seen for the lines that appear in the chart. PineScript code for this was taken directly from @TradeChartist 21Aug2020 "Simple Fibonacci Retracement" : https://www.tradingview.com/script/mWmIRNVF-Simple-Fibonacci-Retracement/ +-----+ https://www.tradingview.com/chart/SPX500/yjSVcTsJ-Revisiting-a-long-term-trend-line/ Brilliant @jbrothersjr!! I had dropped my old Pinescript for a 1926-2020 semi-log trend of SP500. I've just revamped it for a simpler perspective, and added it back to one of my charts. I posted it to https://www.tradingview.com/chart/u4klPKBn/ (not sure if even TradingView URLs are legal in blog comments, I've been in trouble before). My stuff is public (I hope), so you might be able to see it there (basically the same result as you). I've hidden a pile of other international stock markets on the chart, so it's easier to see the SP500 trend. Long-term trends - these are my fit periods: SP500 1926-2020 semi-log trend = 10^(0.792392+2.89587*10^(-2)*(year - 1926.25)) price revolution* SP500 1872-1926 semi-log trend = 10^(0.784617+1.40925*10^(-4)*(year - 1871.08)) price equilibrium* *David Fischer 1996 "The Great Wave, Price revolutions and the rhythm of history" More recent trend that I keep on the chart for now, as I suspect that until very recently, much of the market really was hoping for the 24% financial asset inflation that occurred well into the Feb, Treasury] pump period : SP500 Fibbonacci(0.0) ~upper bound 15Apr-06Sep2021 : semilog trend = 10^(3.5018 + 0.0940601*(year - 2020.02)) effective rate ~= ((10 power semiLog_slope) -1) : 24%/year this mis-adjusts somewhat as time progresses from ~06Jan2022 I do NOT yet have a proper "Fibonacci mirror" [above, below] the long-term trend-line. It's been a while since I last programmed in PineScript, and I'm older and dumber now too. 08******08 #] 01Feb2022 Great Pinescript : wugamlo - MACD including 6-period Forecast and Divergences https://www.tradingview.com/chart/SPX500/ONd8kvvU-short-now/?utm_source=notification_email&utm_medium=email&utm_campaign=notification_mention#tc7969552 short now S&P 500 Index (FX:SPX500) 4517.24 17.08 0.38% bonnenul 18 hours ago it's time to short. waiting for 4100 first ,then to see if there is a bounce about two week? big bounce will after sept. in nov. or even the last month ,will be back 4400? i'm sure big bounce will only after sept 18 hours ago Comment: short eu, gbp and gold silver, either silver about 17-18 Bill_Howell : Interesting "MACD close -Flat - Neural - Histogram", color coding of numbers changes as the cursor sweeps past the current date. Not sure how this works. bonnenul, 9 hours ago @Bill_Howell, hoping to help you. Just a script https://www.tradingview.com/script/aYS7faUJ-MACD-including-6-period-Forecast-and-Divergences/ MACD including 6-period Forecast and Divergences wugamlo Feb 2, 2021 Bill_Howell Thanks! I appreciate the Pinescript link : wugamlo - MACD including 6-period Forecast and Divergences It would be interesting to have separate lines for (1, 3, 6) day forecasts starting from the beginning of the time series. That would give an view of (how well the algorithm forecasts, time lags of the predictions, situations that forecasts are (good, bad), etc). I won't be doing any more Pinescript programming - I have to focus on priority projects, and my main Pinescript challenge if I ever get back to it would be to implement exogenous time series. 08******08 #] 08Jan2022 edit PineScript in a separate window or tab https://www.tradingview.com/blog/en/edit-your-pine-code-on-a-separate-page-28522/ TradingView introduces the long-awaited feature — now you can edit the code for Pine indicators in a separate window or tab. Under the chart, next to it or on the adjacent monitor — place the Editor wherever you want! To open the Pine Editor on a separate page, you need to: Click the “More” (three dots) button on the top panel of the editor. Choose one of the options: “Open the Pine Editor in a new window…” or “Open the Pine Editor in a new tab…”. If you edit the code of the indicator added to the chart and click “Save”, the changes will be immediately applied to the indicator. 08******08 #] 21Sep2021 set up multi-symbol charts >> NYET - takes too long to develop code!! +-----+ https://stackoverflow.com/questions/66132277/how-can-i-set-label-location-in-pine-script I'm looking for some help to set a location for my labels. I would like to have them in the top left corner of the chart if possible. Otherwise worst case scenario would be to have have a future offset. I'm lost in where to start with this, any help is much appreciated. Thanks //@version=4 study("Order Flow Share Size Calculator", overlay=true) //------------------------------------------------------------------------------ // Inputs risk = input(100.00, "Risk Amount (USD)", type=input.float) Show_Label_Long = input(true, title="Long Position") Show_Label_Short = input(true, title="Short Position") //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Variables and Calculations Long EntryL = high + 0.01 StopL = low - 0.01 StoplossL = EntryL - StopL SharesL = round(risk/StoplossL) // Long Label LongLabel = "Shares = " + tostring(SharesL) + "\n" + "\nEntry = $" + tostring(round(EntryL * 100)/100) + "\n" + "\nStop = $" +tostring(round(StopL * 100)/100) // Variables and Calacutations Short EntryS = low - 0.01 StopS = high + 0.01 StoplossS = StopS - EntryS SharesS = round(risk/StoplossS) // Short Lables ShortLabel = "Shares = " + tostring(SharesS) +"\n" + "\nEntry = $" + tostring(round(EntryS * 100)/100) + "\n" + "\nStop = $" +tostring(round(StopS *100)/100) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Create Label Long if Show_Label_Long LL = label.new (x=bar_index, y=na, text=LongLabel, xloc=xloc.bar_index, yloc=yloc.belowbar, color=color.green, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_center) label.delete(LL[1]) // Create Label Short if Show_Label_Short SL = label.new (x=bar_index, y=na, text=ShortLabel, xloc=xloc.bar_index, yloc=yloc.abovebar, color=color.red, style=label.style_none, textcolor=color.red, size=size.normal, textalign=text.align_center) label.delete(SL[1]) //------------------------------------------------------------------------------ pine-script Share Improve this question Follow edited Feb 10 at 7:08 asked Feb 10 at 7:02 BD2 +--+ Unfortunately, now labels in pine hasn't absolute position. But you can try something like this to offset your label in future: //@version=4 study("Label in future", overlay=true) count = input(1) // we use minimal time of bars as an offset in future var float minBarTime = 999999999999 var label l = label.new(bar_index, close, "Text", xloc=xloc.bar_time) currentTime = time(timeframe.period) timeOfCurrentBar = change(currentTime, 1) minBarTime := not na(minBarTime) ? min(timeOfCurrentBar, minBarTime) : timeOfCurrentBar // add to current time calculated time of bar label.set_x(l, int(currentTime+(count*minBarTime))) label.set_y(l, hl2) answered Feb 11 at 11:05 Artem Nosov 08******08 #] 19Apr2021 RicardoSantos polynomial script, user input https://www.tradingview.com/pine-script-docs/en/v4/annotations/Script_inputs.html?highlight=input Script inputs The input annotation function makes it possible for script users to modify selected values which the script can then use in its calculation or logic, without the need to modify the script’s code. Specific widgets are supplied in the Settings/Inputs dialog box for each type of input. A description of the value as well as minimum/maximum values and a step increment can also be defined. If the type of the input variable cannot be inferred at compile time, it can be explicitly defined using the type parameter. >> RicardoSantos Change : +.....+ int length = input(10) +.....+ To : +.....+ int length = input(1500) +.....+ >> no output Added n_bars from 83y trend, corrected for excessive lenghts!! : // n_bars = total number of bars shown in "viewable window", standard timeperiods only! // adapted from : // https://stackoverflow.com/questions/50087999/how-to-know-which-time-period-you-are-on-similar-to-isdaily-isweekly // how to know which time period you are on similar to isdaily, isweekly? // answered May 17 '18 at 6:07, Harold n_bars = 250 if timeframe.period == "1D" n_bars = 8*60 // n_bars = 24*60*60 else if timeframe.period == "5D" n_bars = 24*7 // n_bars = 24*60/5*12*7 else if timeframe.period == "1M" n_bars = 8*20 // n_bars = 24*60*30 else if timeframe.period == "3M" n_bars = 7*5*3 // n_bars = 24*30*3 else if timeframe.period == "6M" n_bars = 7*4*6 // n_bars = 60/5*30*6 else if timeframe.period == "1Y" n_bars = 30*12 // n_bars = 30*12 else if timeframe.period == "5Y" n_bars = 7*12*5 // n_bars = 30*12*5 else if timeframe.period == "All" n_bars = 7*12*20 // n_bars = 30*12*50 >> RicardoSantos Change : +.....+ int length = input(10) +.....+ To : +.....+ int length = n_bars +.....+ 08******08 13Apr2021 // 12Apr2021 var float[] debt = array.new_float(n_bars,1.05) var debter = 1.0 for _i = 0 to n_bars -1 array.set(debt,_i,0.9 + _i / n_bars) // 13Apr2021 - adaptation of PineScript code from : // RicardoSantos "Function Polynomial Regression", Sep 7, 2020 // PineScript operators : line.[new,set_xy1], pivot[low,high], // he doesn't use plot? line.set_xy1 does this? // Eventually, I need to use year_fraction, but later? // Call by name, double-nested? f_pr_mid_line_selector(_line) : // line.set_xy1(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i)) // int length = input(10) // var float[] prices = array.new_float(size=length, initial_value=open) // var int[] indices = array.new_int(size=length, initial_value=0) color _pr_mid_col = input(color.blue) color _pr_std_col = input(color.aqua) color _pr_max_col = input(color.purple) f_init_mid()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_mid_col, style=line.style_solid, width=2) var line debt_line = f_init_mid() int pr_fractions = 10 int pr_size = array.size(id=debt) int pr_step = max(pr_size / pr_fractions, 1) for _i = 0 to pr_size - pr_step - 1 by pr_step int _next_step_index = _i + pr_step int _line = _i / pr_step // I changed f_pr_mid_line_selector(_line) to f_init_mid() // changed indices to year_fraction : line.set_xy1(id=f_init_mid(), x=array.get(id=year_fraction, index=_i), y=array.get(id=debt, index=_i)) Save error : line 197:The 'resolution' argument is incompatible wityh functions that have side effects. +-----+ olde code // 12Apr2021 var float[] debt = array.new_float(n_bars,1.05) var debter = 1.0 for _i = 0 to n_bars -1 array.set(debt,_i,0.9 + _i / n_bars) for _i = 0 to n_bars -1 debter := sma(array.get(debt,_i),1) //debter=sma(array.get(debt, 215),1) //debter=sma(array.get(debt),1) plot(debter, title="US Federal debt", color=color.green, linewidth=1, style=6) 08******08 #] 12Apr2021 array.set +-----+ https://www.tradingview.com/script/12M8Jqu6-Function-Polynomial-Regression/ Function Polynomial Regression, RicardoSantos, Sep 7, 2020 >> 13Apr2021 - just what I need for array plot approach!!! array.get, array.push how come this is "floating in the air? : [_predictions, _max_dev, _min_dev, _stdev/_sizeX] >> must be return values or something, as per : [P, Pmax, Pmin, Pstdev] = f_array_polyreg(indices, prices) >> OK, multiple return values. Nice. int length = input(10) var float[] prices = array.new_float(size=length, initial_value=open) var int[] indices = array.new_int(size=length, initial_value=0) if pivothigh(2, 2) e = array.pop(id=prices) i = array.pop(id=indices) array.insert(id=prices, index=0, value=high[2]) array.insert(id=indices, index=0, value=bar_index[2]) pivot high must be inbuilt function, as not defined in code? >> Yes : pivothigh This function returns price of the pivot high point. It returns 'NaN', if there was no pivot high point. RicardoSantos defines lines, and augments for _i = 0 to pr_size - pr_step - 1 by pr_step int _next_step_index = _i + pr_step int _line = _i / pr_step line.set_xy1(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i)) >> he doesn't use plot? 08******08 #] 12Apr2021 array.set array.set(debt,210,1.10) array.set(debt,211,1.11) array.set(debt,212,1.12) array.set(debt,213,1.13) array.set(debt,214,1.14) array.set(debt,215,1.15) array.set(debt,216,1.16) array.set(debt,217,1.17) array.set(debt,218,1.18) array.set(debt,219,1.19) array.set(debt,220,1.20) array.set(debt,221,1.21) array.set(debt,222,1.22) array.set(debt,223,1.23) array.set(debt,224,1.24) array.set(debt,225,1.25) +-----+ // 12Apr2021 float[] debt = array.new_float(n_bars,1.05) var debter = 1.0 for _i = 0 to n_bars -1 //array.set(debt,_i,1.00) b = 0.9 + _i / n_bars array.set(debt,_i,b) debter := sma(array.get(debt,_i),1) //debter=sma(array.get(debt, 215),1) //debter=sma(array.get(debt),1) plot(debter, title="US Federal debt", color=color.green, linewidth=1, style=6) >> nyet - This ONLY plots the last value of debt +-----+ olde code // 11Apr2021 new script - add exogenous datapoints //a = array.new_float(5, close) //array.insert(a, 0, y_to_yTrend*1.2) //plot(array.get(a, 5)) //a = array.new_float(0) // for _i =0 to n_bars //array.push(a, close[i]*0+debt[i]) //plot(array.avg(a)) //works, but const value : //debt = array.new_float(n_bars,y_to_yTrend) //debter = float.avg(debt[2]) //plot(array.get(debt,215), title="US Federal debt", color=color.green, linewidth=1, style=6) //plot(debter, title="US Federal debt", color=color.green, linewidth=1, style=6) // 12Apr2021 History referencing https://www.tradingview.com/pine-script-docs/en/v4/essential/Arrays.html?highlight=array%20avg // plot(array.get(debt,0), title="US Federal debt", color=color.green, linewidth=1, style=6) works only one value? // debter=sma(debt, 2) nyet cannot call // debter=sma(array.get(debt, 0), 20) OK - but onlsingle value for whole series // debter=array.get(debt, 0)[1] nyet, still only one value // debter=array.get(debt, 0) nyet, still only one value // debter=sma(array.get(debt, 0),2) nyet, still only one value 1.05 // debter=sma(array.get(debt, 215),2) nyet, still only one value 1.15 // debter=sma(array.get(debt, 215),1) nyet, still only one value 1.15,but pervert by only 1 sma // plot(debter, title="US Federal debt", color=color.green, linewidth=1, style=6) No output : for _i = 0 to n_bars array.set(debt,_i,1.00) //array.set(debt,_i,0.9 + _i/n_bars) / 12Apr2021 //float[] debt = array.new_float(n_bars,1.05) float[] debt = array.new_float(n_bars,1.05) for _i = 0 to n_bars -1 //array.set(debt,_i,1.00) array.set(debt,_i,0.9 + _i/n_bars) //debter=sma(array.get(debt, 215),1) debter=sma(array.get(debt, 0),1) plot(debter, title="US Federal debt", color=color.green, linewidth=1, style=6) >> constant 0.9 plot +-----+ https://www.tradingview.com/pine-script-docs/en/v4/essential/Arrays.html?highlight=array%20avg History referencing Past instances of array id’s or elements cannot be referenced directly using Pine’s [ ] history-referencing operator. One cannot write: array.get(a[1], 0) to fetch the value of the array’s first element on the previous bar. In Pine, however, each call to a function leaves behind a series trail of function results on previous bars. This series can in turn be used when working with arrays. One can thus write: ma = sma(array.get(a, 0), 20) to calculate the simple moving average of the value returned by the array.get(a, 0) call on the last 20 bars. +-----+ https://stackoverflow.com/questions/62440066/cannot-cast-type-pine-script-error-looking-for-a-workaround Cannot cast type pine-script error? Looking for a workaround Asked 9 months ago Active 9 months ago Viewed 532 times https://www.tradingview.com/pine-script-docs/en/v4/language/Type_system.html >> typecast array_float to series https://stackoverflow.com/questions/62252670/cannot-call-plot-with-arguments-seriesfloat Cannot call 'plot' with arguments (series[float], Asked 10 months ago Active 9 months ago Viewed 1k times >> not helpful https://www.tradingview.com/blog/en/arrays-are-now-available-in-pine-script-20052/ https://www.tradingview.com/support/solutions/43000473337-how-can-i-remove-all-drawings-indicators-from-the-chart/ >> done +----+ https://www.tradingview.com/blog/en/drawing-tool-path-20807/ Our set of drawing tools is constantly growing, and we’re happy to say that we’ve just added yet another new product. Path is a super cool new tool that should make your charting even easier to execute. To find it, open the Geometric Shapes drop-down menu: >> This is it!! https://www.tradingview.com/pine-script-docs/en/v4/essential/Drawings.html Note On TradingView charts, a complete set of Drawing Tools allows users to create and modify drawings using mouse actions. While they may look similar to drawing objects created with Pine code, they are essentially different entities. Drawing objects created using Pine code cannot be modified with mouse actions. +----+ https://www.tradingview.com/chart/REEFUSDT/6TYzOOto-Be-smart-think-and-act-like-a-Reef-Turtle/?&utm_source=Weekly&utm_medium=email&utm_campaign=TradingView+Weekly+102+%28EN%29 Be smart: think and act like a Reef Turtle. Long REEF / TetherUS (BINANCE:REEFUSDT) 0.038163 −0.001431 −3.61% BullSecret Apr 5 https://s3.tradingview.com/j/jFwT0Bkl_mid.webp Surfs up freudianBitSlip https://www.tradingview.com/ideas/chartart/ https://www.tradingview.com/ideas/chartart/page-2/ 08******08 #] 11Apr2021 Plotting an exogenous curve in PineScript Easier & better to start with a copy with my previous PineScript "exogenous data with SP500 83year detrended" OMRXGOVT - Government debt index, what is this? >> nyet - seems toSwedish govbernment tracking of market index debt (call, put, short? +-----+ array.set The function sets the value of the element at the specified index. array.set(id, index, value) → void Example //@version=4 study("array.set example") a = array.new_float(10) for i = 0 to 9 array.set(a, i, close[i]) plot(array.sum(a) / 10) >> Ah hah!, this is what I need! -> may not work with 1000 datapoints? +-----+ array.insert The function changes the contents of an array by adding new elements in place. array.insert(id, index, value) → void Example //@version=4 study("array.insert example") a = array.new_float(5, close) array.insert(a, 0, open) plot(array.get(a, 5)) +-----+ https://www.tradingview.com/script/12M8Jqu6-Function-Polynomial-Regression/ Function Polynomial Regression RicardoSantos Sep 7, 2020 >> can't see function for listing data points, just uses current plot? >> 13Apr2021 - just what I need for array plot approach!!! 08******08 #] 21Mar2021 I couldn't publish - House Rules, no links etc I couldn't publish : PineCoders - You have received a warning for violating our House Rules. You are not banned, you may be if you violate the rules again. More info - https://www.tradingview.com/house-rules/ Violated house rule: violation of script publishing. Content that caused the ban: ► General House Rules All content published on TradingView, including all types of publications and updates, comments, public and private chat messages, scripts, open-source code, script release notes, etc., need to be ree of advertisements, logos, links or references to any website, social media, messaging or email contacts, company names, giveaways, prize contest or any other kind of announcement or solicitation. Exception: Premium subscribers are allowed to include contacts, links and solicitation in their Signature field, which appears under every published idea, script or stream. ► Chart • The chart you are publishing with your script should be easy to understand and your script's output should be readily identifiable. This is the reason why we ask you to publish your script with a clean chart. • Unless your script must be used with another one and your description explains why, do not include other scripts on the chart. • You may use drawings on charts, but they should contribute to understanding what your script does or how to use it. • Do not include chart drawings if their use is not explained. Scripts violating House Rules are hidden and cannot be changed or removed. They have a red background and are no longer visible to the community; only moderators and authors can see them. You may re-publish a new, compliant script and description if you wish. Before doing so, please make sure you understand and abide by our General House Rules linked above, and our Script Publishing Rules: https://www.tradingview.com/house-rules/?solution=43000590599 If you have questions or suggestions, reply to this message. Howell - I assume that was due to a link to an external site from which I adapted code. I will stop publishing on TradingView. It's not worth the hassel as I was just putting up ideas for comment and use by others. PineCoders - Hi, It was the links but the chart also. The vast majority of authors find it pretty straightforward to publish compliant scripts, once they understand the rules. Feel free if you have questions. Regards, // timeframe.isdwm // timeframe.isintraday // timeframe.isminutes // timeframe.isseconds // timeframe.multiplier // timeframe.period 08******08 #] 20Mar2021 chart FX-SPX500 features as an 83 year semi-log DETRENDED series (1926-2020) https://www.tradingview.com/chart/olC6bR38/ This chart FX-SPX500 features as an 83 year semi-log DETRENDED series (1926-2020), plotted as log(Fibonacci) of y/y_Trend. The [min,max] values are calculated on the basis of the "approximate visible bar_index length" in the viewing window, whether [1D,5D,1M,3M,6M,1Y,5Y,All]. Also shown are horizontal lines (grey) of Fibonacci reference levels [0.055728, 0.090170, 0.145898, 0.236072, 0.381971, 0.500000, 0.618047, 0.786164, 1.000000, 1.272000, 1.618000, 2.000000, 2.618000, 4.236000, 6.854100, 11.09020, 17.94430] where these lie between [min,max]. Also shown are a mix of other very different financial markets [TNX 10y T-bill, CNYUSD exchange, BTCUSD, USOIL, BEAM], to compare the behaviours of the various markets. The intent is to : - learn PineScript at a basic level. I don't want to become an expert, but it is handy. - provide the script publicly - it may be handy for other beginners, or others may want to take the approach further. I found it frustrating this week while getting used to PineScript as a beginner, as many simply things have to be approached differently from conventional tools like [gnuplot, bash, QNial, C, gimp, etc]. However, I must say that TradingView PineScript is very well thought out for its purposes, the code is incredibly [simple, compact, powerful], and it really is a wonderful tool! But you knew that already. www.BillHowell.ca +-----+ As noted directly on the chart : Detrended symbol : SP500 only. [TNX 10y T-bill, CNYUSD exchange] might be "detrended-like" variables over some time intervals, comparable on a horizontal graph with log(Fibonacci) levels. Non-detrended symbols : Neither [BTCUSD, USOIL, BEAM] are detrended. Given that [BTCUSD,BEAM] are "new in the last decade or so", and have extreme growth from the start, detrending requires some thinking ... perhaps something like tech S-curves or Business rise&fall curves. +-----+ Label the "Fibonnacci mirror trendlines" for calculated series : Simply done by : right-click on Price Menu of interest -> labels -check : Indicator [label name, last value] label +-----+ #] 20Mar2021 Current problems with the script : - The [min (red), max (green)] levels should be for the "visible bar_index length". As a simplification, I have used a constant 2000 bars only. - I really should make the FX-SPX500 output a line instead of just points, but that's not a priority. - Test this during trading hours - The chart assumes that FX-SPX500 is the primary symbol, but I should make that explicit. The 83 year detrending formula 1926-2020 is specific to FX-SPX500. - I haven't yet posted all of this on my website with explanations, and links to other market-related analysis 08******08 #] 20Mar2021 [comment, timeframe, dummy variable]s for "SP500 with 83 year detrended Fibonaccis..." // References // Robert Prechter // Stephen Puetz, Glenn Borchardt // Sacha Dobler "Solar history", "Solar behaviour" // Steven Yaskell "Maunder minimum", "Grand phases on the Sun" // Anthony Peratt - petroglyphs // Howells - "Butterflies in the clouds, and the Milankoch wandering of greener pastures and glaciers. Towards a quasi-predictive model for the rise and fall of civilisations" // Gobekli Tepe on the Aian plateau - // Mayan calendar // bar_index +-----+ search "PineScript and how do I use timeframe.period?" https://www.tradingview.com/pine-script-reference/#var_period timeframe.isdaily timeframe.isdwm timeframe.isintraday timeframe.isminutes timeframe.ismonthly timeframe.isseconds timeframe.isweekly timeframe.multiplier timeframe.period +-----+ olde code // dummy variables until barstate.islast // y_Trend_min = 0 // y_Trend_max = 0 // y_Trend_minLine = 0 // y_Trend_maxLine = 0 // y_to_yTrend_min = 1 // y_to_yTrend_max = 1 // if barstate.islast 08******08 #] 20Mar2021 Howell Pinescript "SP500 with 83 year detrended Fibonaccis,TNX,CNYU,USOIL,BTCUSD,BEAM pharma" +-----+ search "PineScript and label.new doesn't work" plot(y_to_yTrend_min < 0.055728 and 0.055728 < y_to_yTrend_max ? 0.055728, offset=-9999 : na, title="0.05", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.090170 and 0.090170 < y_to_yTrend_max ? 0.090170, offset=-9999 : na, title="0.09", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.145898 and 0.145898 < y_to_yTrend_max ? 0.145898, offset=-9999 : na, title="0.14", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.236072 and 0.236072 < y_to_yTrend_max ? 0.236072, offset=-9999 : na, title="0.23", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.381971 and 0.381971 < y_to_yTrend_max ? 0.381971, offset=-9999 : na, title="0.38", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.500000 and 0.500000 < y_to_yTrend_max ? 0.500000, offset=-9999 : na, title="0.50", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.618047 and 0.618047 < y_to_yTrend_max ? 0.618047, offset=-9999 : na, title="0.61", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 0.786164 and 0.786164 < y_to_yTrend_max ? 0.786164, offset=-9999 : na, title="0.78", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 1.000000 and 1.000000 < y_to_yTrend_max ? 1.000000, offset=-9999 : na, title="1.00", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 1.272000 and 1.272000 < y_to_yTrend_max ? 1.272000, offset=-9999 : na, title="1.27", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 1.618000 and 1.618000 < y_to_yTrend_max ? 1.618000, offset=-9999 : na, title="1.61", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 2.000000 and 2.000000 < y_to_yTrend_max ? 2.000000, offset=-9999 : na, title="2.00", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 2.618000 and 2.618000 < y_to_yTrend_max ? 2.618000, offset=-9999 : na, title="2.61", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 4.236000 and 4.236000 < y_to_yTrend_max ? 4.236000, offset=-9999 : na, title="4.23", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 6.854100 and 6.854100 < y_to_yTrend_max ? 6.854100, offset=-9999 : na, title="6.85", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 11.09020 and 11.09020 < y_to_yTrend_max ? 11.09020, offset=-9999 : na, title="11.0", color=color.gray, linewidth=1, style=6, trackprice=true) plot(y_to_yTrend_min < 17.94430 and 17.94430 < y_to_yTrend_max ? 17.94430, offset=-9999 : na, title="17.9", color=color.gray, linewidth=1, style=6, trackprice=true) +-----+ olde code a = array.new_float(5, 0) for _i = 0 to 4 array.set(a, _i, _i + 1) if barstate.islast label.new(bar_index, 0, "BEFORE\na: " + tostring(a), size = size.large) array.insert(a, 2, 999) label.new(bar_index, 0, "AFTER\na: " + tostring(a), style = label.style_label_up, size = size.large) var y_to_yTrend = array.new_float(0) int i = 0 for i = 0 to 500 array.push(y_to_yTrend, y_to_yTrend_all[i]) // calculate 83 year detrended data, [upper, lower] "Fibonnacci mirror trendlines" for a time period calc_yTrend(x) => expnt = 0.792392+0.0289587*(x - 1926.25) // for 1871-1926 =10^( 0.784617 + (0.000140925*(x - 1871.08))) SP500base = pow(10,expnt) y_Trend = calc_yTrend(year_fraction) y_to_yTrend = close / y_Trend_all plot(y_to_yTrend, title="SPX83y", color=color.blue, linewidth=1, style=6) y_to_yTrend_min = smalest(y_to_yTrend,500) y_to_yTrend_max = biggest(y_to_yTrend,500) //y_to_yTrend_min_const = y_to_yTrend_min[1] //y_to_yTrend_max_const = y_to_yTrend_max[1] y_to_yTrend_min_line = y_to_yTrend_min_const y_to_yTrend_max_line = y_to_yTrend_max_const plot(y_to_yTrend_min_line, title="y_to_yTrend_min_line", color=color.red, linewidth=1, style=6) plot(y_to_yTrend_max_line, title="y_to_yTrend_max_line", color=color.green, linewidth=1, style=6) //y_to_yTrend_min_const = y_to_yTrend_min[1] //y_to_yTrend_max_const = y_to_yTrend_max[1] //y_to_yTrend_min_line = y_to_yTrend_min_const //y_to_yTrend_max_line = y_to_yTrend_max_const +-----+ search "PineScript and how many bars appears during a timeframe.period?" https://kodify.net/tradingview/bar-data/bar-count/ The bar_index variable can tell us how many bars a particular chart has. With that information we can also see how many bars there were before some time and date. // Make a new label once var label myLabel = label.new(x=bar_index, y=high + tr, textcolor=color.white, color=color.blue) // On the last bar, show the chart's bar count if (barstate.islast) // Set the label content label.set_text(id=myLabel, text="Bars on\nthe chart:\n" + tostring(bar_index + 1)) // Update the label's location label.set_x(id=myLabel, x=bar_index) label.set_y(id=myLabel, y=high + tr) // https://www.tradingview.com/pine-script-docs/en/v4/appendix/HOWTOs.html#count-bars-in-a-dataset // Find the highest and lowest values for the entire dataset // 20Mar2021 Howell - adapt this for viewable data >> labels don't work try : bar_index[1] +-----+ Howell - SP500 with 83 year detrended Fibonaccis,TNX rates,CNYU,USOIL,BTCUSD,BEAM pharma.txt find the end-points of time-scale being viewed, then "mid-y-point or weighted mid-y-point" of y_to_yTrend. adjust [midpoint, spread] of y_to_yTrend indicator scale. The problem is still principally one of [min, max] for viewed time-scale right time-endpoint is obviously "today". left time-endpoint easy to calc from "view timescale" clicked. Where do I find that search "PineScript and timescale being viewed" search "PineScript and how do I check the timeframe?" +-----+ https://stackoverflow.com/questions/50087999/how-to-know-which-time-period-you-are-on-similar-to-isdaily-isweekly how to know which time period you are on similar to isdaily, isweekly? Asked 2 years, 10 months ago Active 2 years, 10 months ago Viewed 1k times Use the "period" built-in variable. Here's a link to the documentation: Pine Script Language Reference https://www.tradingview.com/study-script-reference/#var_period answered May 7 '18 at 2:28 lvinnyl chartResolution = interval if isdaily chartResolution := 24*60*interval if isweekly chartResolution := 24*60*7*interval if ismonthly chartResolution := 24*60*30*interval This portion of code will give you the number of minutes of a single bar (approx. for monthly), no matter the chosen period of the chart, including the personalized ones. Hope it helps answered May 17 '18 at 6:07 Harold +-----+ https://www.tradingview.com/pine-script-reference/#var_period timeframe.multiplier Multiplier of resolution, e.g. '60' - 60, 'D' - 1, '5D' - 5, '12M' - 12 Type integer First, find resolution! timeframe.period Resolution, e.g. '60' - 60 minutes, 'D' - daily, 'W' - weekly, 'M' - monthly, '5D' - 5 days, '12M' - one year, '3M' - one quarter Type string Let me assume history for each? : see Harold above N_BARS_1D = 60*24 N_BARS_5D = 5*24 N_BARS_1M = N_BARS_3M = N_BARS_6M = N_BARS_1Y = N_BARS_5Y = N_BARS_All = timeframe.isdaily search "PineScript and what is the interval?" +-----+ https://kodify.net/tradingview/info/interval/ TradingView's interval variable explained Published November 22, 2017 >> Looks great, explained +--+ >> Below is just what I need!!! adapt it for all timeframe selections //@version=3 study(title="Reference indicator example", overlay=true) // Input option priceData = input(title="Price Data", type=source, defval=close) // Calculate EMA emaLength = not isintraday ? 5 : (interval >= 120) ? 40 : (interval >= 60) ? 20 : 10 emaValue = ema(priceData, emaLength) // Plot values and colour background plot(series=emaValue, color=orange, linewidth=3) bgColour = crossover(close, emaValue) ? green : crossunder(close, emaValue) ? red : na bgcolor(color=bgColour) +--+ Chart interval period resolution returns returns 15 minutes 15 "15" 60 minutes 60 "60" 2 hours 120 "120" 3 hours 180 "180" 1 day 1 "D" 5 days 5 "5D" 1 week 1 "W" 2 weeks 2 "2W" 1 month 1 "M" 3 months 3 "3M" 1 year 1 "12M" In TradingView, all intra-day resolutions are specified with a number of minutes (TradingView Wiki, 2017). And so on a 15-minute chart, interval returns 15. And on a 1-hour chart, interval returns 60 while that variable returns 120 on a 2-hour chart. When our chart has a daily, weekly, or monthly time frame, then interval returns the resolution in number of days, weeks, or months (starting at 1). While the interval variable tells us which resolution interval the current chart uses, it doesn't say anything about the type of time frame (like whether the chart is an intra-day or weekly chart). Luckily, TradingView has other chart information variables that tell us what kind of time frame our script runs on (TradingView, n.d.): Variable Description isdaily Returns true when our indicator or strategy operates on a daily resolution, and false otherwise. isdwm Returns true when the script runs on a daily, weekly, or monthly chart. Returns false when the script runs on an intra-day chart. isintraday Returns true if the current resolution is an intra-day resolution, and false for resolutions higher than that. ismonthly Returns true if the script calculates on a monthly resolution, and false otherwise. isweekly Returns true if the current resolution is a weekly resolution, and false for chart time frames that are higher or lower than that. +--+ https://www.tradingview.com/chart/EURUSD/0co8qlXw-Tips-And-Tricks-In-Pinescript/ Tips And Tricks In Pinescript Education Euro / U.S. Dollar (OANDA:EURUSD) 1.19042 −0.00118 −0.10% alexgrover May 31, 2019 Use Recursion With The Exponential Window Function Recursion is the process of using outputs as inputs for a function. Pine allow you to use outputs as inputs thanks to the nz () function. Lets use an example, imagine the following code with the version 2 of pinescript : a = change( nz (a,close),9) This code compute the difference between a and a 9 bars back, now when the code will make the first calculation you want a numerical value for a because a will be equal to na (non attributed), this is why you need to have an initial value (also called a seed) for a and this is what nz () do , attribute a value to a when a = na. By running the code above you will end up with a periodic results, so how can you use recursion with your indicators ? Here the following code example show you how : alpha = 0.5 a = scale(close, length) b = function(alpha*a+(1-alpha)*nz(b,a)) When you want to use recursion in a function you must first declare alpha, alpha can be any value as long as alpha is greater than 0 and lower than 1, then you must scale your input (here the closing price), this is done because depending on the price scale you could get different results when using recursion, when your rescaling range is low (1,0) your results could be more periodic than in a range like (100,0). +-----+ olde code // https://www.tradingview.com/pine-script-docs/en/v4/appendix/HOWTOs.html#count-bars-in-a-dataset // Find the highest and lowest values for the entire dataset biggest(series) => max = 0.0 max := nz(max[1], series) if series > max max := series max[1] smalest(series) => min = 1e5 min := nz(min[1], series) if series < min min := series min[1] y_to_yTrend_min_const = y_to_yTrend_min[1] y_to_yTrend_max_const = y_to_yTrend_max[1] //+-----+ find the end-points of time-scale being viewed, then "mid-y-point or weighted mid-y-point" of y_to_yTrend. adjust [midpoint, spread] of y_to_yTrend indicator scale. The problem is still principally one of [min, max] for viewed time-scale right time-endpoint is obviously "today". left time-endpoint easy to calc from "view timescale" clicked. Where do I find that 08******08 #] 19Mar2021 Pinescript and arrays - not obvious how to make it work +-----+ 11:06 error msg "Cannot use 'plot' in local scope." >> NUTS!!! Pinescript is so primitive!! +-----+ //prices_n = 0.0 var prices = array.new_float(0) //array.push(prices, close) //if barstate.islast //prices_n = array.size(prices) prices_n = 1000 smallest(arrayInn,array_size) => minAll = 1.0e7 for i = 0 to array_size if array.get(arrayInn,i) < minAll minAll := array.get(arrayInn,i) minAll biggest(arrayInn,array_size) => maxAll = 0.0 for i = 0 to array_size if array.get(arrayInn,i) > maxAll maxAll := array.get(arrayInn,i) maxAll //biggest(series) => // max = 0.0 // max := nz(max[1], series) // if series > max // max := series // max biggest(series) => maxAll = 0.0 if series[1] > maxAll maxAll := series[1] max smallest(series) => min = 10000.0 min := nz(min[1], series) if series < min min := series min +-----+ olde code calc_y_to_yTrend_ratio(x) => x / calc_yTrend(x) y_to_yTrend = calc_y_to_yTrend_ratio(year_fraction) // plot_Fib(fib) => // if (y_to_yTrend_min_const < fib and fib < y_to_yTrend_max_const) // Fib_00_618 = fib * y_Trend // plot(Fib_00_618, title="Fib " + tostring(fib), color=color.gray, linewidth=1, style=6) // plot_Fib(fib) => // if (y_to_yTrend_min_const < fib and fib < y_to_yTrend_max_const) // Fib_00_618 = fib * y_Trend // plot(Fib_00_618, title="Fib " + tostring(fib), color=color.gray, linewidth=1, style=6) // plot(Fib_00_786, title="Fib_00_786", color=color.gray, linewidth=1, style=6) // plot(Fib_01_272, title="Fib_01_272", color=color.gray, linewidth=1, style=6) // plot(Fib_01_618, title="Fib_01_618", color=color.gray, linewidth=1, style=6) //+-----+ // Update the label on the chart's last bar //if (barstate.islast) // label_text = 'total bar_index ' + tostring(bar_index) // var label1 = label.new(bar_index, bar_index, text=label_text, style=label.style_square) // label.set_xloc(label1, bar_index[0], xloc=xloc.bar_index) // label.set_yloc(label1, yloc=yloc.abovebar) // var label1 = label.new(bar_index, high, label_text, style=label.style_square) 08******08 #] 18Mar2021 Stop - PineScript's own code fails!!!??? +----+ // f_print(_text) => // // Create label on the first bar. // //var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // // On next bars, update the label's x and y position, and the text it displays. // label.set_xy(_label, bar_index, highest(10)[1]) // label.set_text(_label, _text) // // f_print("Multiplier = " + tostring(timeframe.multiplier) + "\nPeriod = " + timeframe.period + "\nHigh = " + tostring(high)) // f_print("Hello world!\n\n\n\n") +-----+ olde code x (series) News bar index or bar time of the label position xloc (string) New x-location value https://www.tradingview.com/pine-script-docs/en/v4/appendix/HOWTOs.html#count-bars-in-a-dataset Find the highest and lowest values for the entire dataset //@version=4 study("My Script") biggest(series) => max = 0.0 max := nz(max[1], series) if series > max max := series max smallest(series) => min = 10000.0 min := nz(min[1], series) if series < min min := series min plot(biggest(close), color=color.green) plot(smallest(close), color=color.red) // later - for detrended graph //price_ratio_to_trend = close / y_to_yTrend * 3.800 /10 price_ratio_to_trend = close / y_to_yTrend * 3.800 /10 var float price_high = 0 var float price_low = 0 //for i = 1 to array.size(close) - 1 // array.set(price_array,i, close) //price_array = array.new_float(0) price_array = close //biggest(series) => // max = 0.0 // max := nz(max[1], series) // if series > max // max := series // max +-----+ dump more olde code // https://kodify.net/tradingview/bar-data/highest-high-lowest-low/ highest_fullRange_price_ratio_to_trend = highest(high, bar_index) //title="price_ratio_to_trend", color=color.orange, linewidth=1, style=6) // https://kodify.net/tradingview/bar-data/highest-high-lowest-low/ highest_fullRange_price_ratio_to_trend = highest(high, bar_index) //title="price_ratio_to_trend", color=color.orange, linewidth=1, style=6) // https://www.tradingview.com/blog/en/introducing-pine-script-4-12626/ // label1 = label.new(bar_index, na, 'last price is '+tostring(close), // color=close >= open ? color.green : color.red, // textcolor=color.white, // style=label.style_labeldown, yloc=yloc.abovebar) // // label.delete(l[1]) // https://kodify.net/tradingview/labels/set-price/ // Make a label once (as preparation) var monthLabel = label.new(x=na, y=na, xloc=xloc.bar_time, color=color.black, textcolor=color.white) // Update the label on the chart's last bar label_text = 'total bar_index ' + tostring(bar_index) label1 = label.new(bar_index, high, label_text, style=label.style_square) label.set_xloc(id=label1, time, xloc.bar_time) label.set_yloc(id=label1, yloc=yloc.abovebar) //if (barstate.islast) // labelText = "Month high: " + tostring(monthHigh) + // "\nMonth low: " + tostring(monthLow) + // "\n\nPrv month close:\n" + tostring(monthClose) // // label.set_y(id=monthLabel, y=close) // label.set_x(id=monthLabel, x=time + 3600000 * 18) // // label.set_text(id=monthLabel, text=labelText) //https://stackoverflow.com/questions/63954547/print-a-value-with-label-new-using-pine-script // var label1 = "total bar_index= " + tostring(bar_index) // label.new(bar_index, high, label1, style=label.style_square) // label.set_xloc(label1, time, xloc.bar_time) // label.set_yloc(label1, yloc=yloc.abovebar) //label.new(label1, style=label.style_circle) //var label1 = label.new(bar_index, high, "total bar_index= " + tostring(bar_index), style=label.style_circle) //var label1 = label.new(bar_index, low, text="Hello, world!", style=label.style_circle) //label.set_yloc(label1, highest(bar_index)[1]) //label.set_text(label1, text=tostring(bar_index)) //https://stackoverflow.com/questions/63954547/print-a-value-with-label-new-using-pine-script //label1 = "total bar_index= " + tostring(bar_index) //label.new(label1, style=label.style_circle) //var label1 = label.new(bar_index, high, "total bar_index= " + tostring(bar_index), style=label.style_circle) //var label1 = label.new(bar_index, low, text="Hello, world!", style=label.style_circle) //label.set_xloc(label1, time, xloc.bar_time) //label.set_y(label1, close) //label.set_yloc(label1, highest(bar_index)[1]) //label.set_text(label1, text=tostring(bar_index)) // https://www.tradingview.com/blog/en/introducing-pine-script-4-12626/ // https://www.tradingview.com/blog/en/introducing-pine-script-4-12626/ +-----+ search "PineScript and how do I output text?" +--+ https://kodify.net/tradingview/labels/set-price/ // Make a label once (as preparation) var monthLabel = label.new(x=na, y=na, xloc=xloc.bar_time, color=color.black, textcolor=color.white) // Update the label on the chart's last bar if (barstate.islast) labelText = "Month high: " + tostring(monthHigh) + "\nMonth low: " + tostring(monthLow) + "\n\nPrv month close:\n" + tostring(monthClose) label.set_y(id=monthLabel, y=close) label.set_x(id=monthLabel, x=time + 3600000 * 18) label.set_text(id=monthLabel, text=labelText) +--+ https://www.tradingview.com/blog/en/introducing-pine-script-4-12626/ Label Drawing Object The label.new function allows you to draw labels on the chart including ones that contain arbitrary text. Here is an example of a script that draws a label containing the last bar’s close: //@version=4 study("Last Bar Price", overlay=true) l = label.new(bar_index, na, 'last price is '+tostring(close), color=close >= open ? color.green : color.red, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar) label.delete(l[1]) The 'resolution' argument is incompatible with functions that have side effects +--+ https://stackoverflow.com/questions/63954547/print-a-value-with-label-new-using-pine-script print a value with label.new using pine script Asked 6 months ago Active 6 months ago Viewed 541 times 0 I am doing a simple calculation and trying to print the value on screen in trading view using pine script. When I do the printed value is wrong explained the issue below with example H3 is 11540.49 L3 is 11491.71 diff = (11540.49 - 11491.71) = 48.78 where as i get 115.362 Let me know where I am doing the mistake, below is the code study(title="printlabel",overlay=true) yhigh=security(syminfo.tickerid, "D", high[1], barmerge.gaps_off, barmerge.lookahead_on) ylow=security(syminfo.tickerid, "D", low[1], barmerge.gaps_off, barmerge.lookahead_on) yclose = security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on) yopen = security(syminfo.tickerid, "D", open[1], barmerge.gaps_off, barmerge.lookahead_on) H3 = yclose + (yhigh-ylow) * 1.1/4 L3 = yclose - (yhigh-ylow) * 1.1/4 diff = H3-L3 var label1 = label.new(bar_index,high, text=tostring(diff), style=label.style_circle) //label.set_x(label1, bar_index[10]) label.set_xloc(label1, time, xloc.bar_time) plot(H3,color = color.red) plot(L3,color = color.green) asked Sep 18 '20 at 11:04 siva Your label is created on the first bar only and then updated on each bar, which is more efficient than continuously creating and deleting the label. So that's ideal, but musn't forget to update the label's text though. Here we also update the label's y position using the highest high in the last 10 bars, plus the true range. We use those values as evaluated on the previous bar so that our label doesn't move up and down during the realtime bar: var label1 = label.new(bar_index, high, "", style=label.style_circle) label.set_xloc(label1, time, xloc.bar_time) label.set_text(label1, text=tostring(diff)) label.set_y(label1, highest(10)[1] + tr[1]) Share Follow answered Sep 18 '20 at 12:48 PineCoders-LucF search "PineScript and how do I set a fixed label.set_yloc?" https://stackoverflow.com/questions/57996296/pine-script-is-it-possible-to-set-a-labels-y-location-to-the-top-of-the-chart Not yet. The concept is in the air but no ETA. As Pine has no visibility on the chart and the number of bars it contains, the best compromise I know to achieve your objective is to use something like highest(200)[1]. Share Follow answered Sep 18 '19 at 15:53 PineCoders-LucF +--+ https://backtest-rookies.com/2019/10/06/tradingview-adding-labels-pivot-prices/ Example Code //@version=4 study("Pivot Prices", overlay=true) leftbars = input(10, minval=1, title='Bars to the left') rightbars = input(2, minval=1, title='Bars to the right') phigh = pivothigh(high, leftbars,rightbars) plow = pivotlow(low, leftbars, rightbars) if phigh label1 = label.new(bar_index[rightbars], high[rightbars], text=tostring(high[rightbars]), style=label.style_labeldown, color=color.orange) if plow label2 = label.new(bar_index[rightbars], low[rightbars], text=tostring(low[rightbars]), style=label.style_labelup, color=color.green) Arguments The new label function has several arguments that we can specify. Let’s take a look at the main arguments we have used. x: This is simply the coordinate for where the label should appear along the x-axis. The difference between this and the xlocargument (which we don’t use in this example) is that xexpects you to provide it a series (like bar_index) and xlocexpects a string, which is a single value. To understand more about series variables and indexing, see this article. y: Is similar to above but places the label on the y-axis. In our example, we provide two series variables (highandlow) so we can place our labels at the swing high and swing low points text: Is the text you want to display. It needs to be a string but fortunately, it does not need to be a constant string like the plotshape() in version 3. A constant string is a string that never changes. Price values change each bar and so we could never plot a value from a price series in version 3. By contrast, in version 4, we are able to use the to_string()function and convert our lowandhighprices to a string. Finally, as you might notice, on the x and y arguments, we index our series with our rightbars value. This ensures that the labels point nicely to the swing. However, as mentioned earlier, they will only appear a couple of bars after the swing has happened! +--+ https://backtest-rookies.com/2018/03/23/tradingview-pine-script-indexing/ +-----+ number of time points in current graph https://stackoverflow.com/questions/59722529/is-there-a-function-in-pinescript-for-calculating-the-number-of-bars-displayed bar_index returns the current bar index. That would tell you how many bars the chart has. Is that what you want? – Baris Yakut Jan 13 '20 at 19:40 +-----+ search "PineScript and how do I output text?" https://stackoverflow.com/questions/63954547/print-a-value-with-label-new-using-pine-script Your label is created on the first bar only and then updated on each bar, which is more efficient than continuously creating and deleting the label. So that's ideal, but musn't forget to update the label's text though. Here we also update the label's y position using the highest high in the last 10 bars, plus the true range. We use those values as evaluated on the previous bar so that our label doesn't move up and down during the realtime bar: var label1 = label.new(bar_index, high, "", style=label.style_circle) label.set_xloc(label1, time, xloc.bar_time) label.set_text(label1, text=tostring(diff)) label.set_y(label1, highest(10)[1] + tr[1]) Share Improve this answer Follow answered Sep 18 '20 at 12:48 PineCoders-LucF +-----+ olde code // var float[] FibRise = array.new_float() // var float[] FibDown = array.new_float() // find_series_high(price_array) => // price_high = array.get(price_array, 0) // for i = 1 to array.size(price_array) - 1 // if array.get(price_array, i) > price_high // price_high = array.get(price_array, i) // price_high // find_series_loww(price_array) => // price_low = array.get(price_array, 0) // for i = 1 to array.size(price_array) - 1 // if array.get(price_array, i) > price_low // price_low = array.get(price_array, i) // price_low // find_nextHigh(src, length, isHigh) => // l2 = length * 2 // c = nz(src[length]) // ok = true // for i = 0 to l2 // if isHigh and src[i] > c // ok := false // // if not isHigh and src[i] < c // ok := false // if ok // [bar_index[length], c] // else // [int(na), float(na)] // [iH, pH] = pivots(high, depth / 2, true) // [iL, pL] = pivots(low, depth / 2, false) // y_to_trend_min(t_min,t_max) => // y_minRatio = 1 // for t = t_min to t_max // y_ratio = y_current(t) / y_detrended(t) // y_minRatio = if y_ratio < // y_ratio // y_minFib = if y_minRatio < 17.9443 // 7 // else if y_minRatio < 11.0902 // 1.618 // else if y_minRatio < 6.8541 // 1.618 // else if y_minRatio < 4.236 // 1.618 // else if y_minRatio < 2.618 // 1.618 // else if y_minRatio < 2. // 1.618 // else if y_minRatio < 1.618 // 1.618 // else if y_minRatio < 1.272 // 1.618 // else if y_minRatio < 1. // 1.618 // else if y_minRatio < 0.786164 // 1.618 // else if y_minRatio < ??? // 1.618 // // // y_to_trend_max(t_min,t_max) => // y_maxRatio = 1 // for t = t_min to t_max // y_ratio = y_current(t) / y_detrended(t) // y_maxRatio = if y_ratio > y_maxRatio // y_ratio // y_maxFib = if y_maxRatio > 7 // 7 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // else if y_maxRatio > 1.618 // 1.618 // // // y_Fibonnacci_mirror(price, length) => // sum = price // for i = 1 to length-1 // sum := sum + price[i] // sum / length // plot(my_sma(close,14)) // code in this section adpated from "TradingView auto fib extension" from standard PineScript library // var float[] FibRise = array.new_float() // var float[] FibDown = array.new_float() // // FibRise = 0.055728 0.0901697 0.145898 0.236072 0.381971 0.5 0.618047 0.786164 1. 1.272 1.618 2. 2.618 4.236 6.8541 11.0902 17.9443 // // FibDown = 17.9443 11.0902 6.8541 4.236 2.618 2. 1.618 1.272 1. 0.786164 0.618047 0.5 0.381971 0.236072 0.145898 0.0901697 0.055728 // // // countFibRise = array.size(iFibRise) // // // findNextLow( // // // // // // countFibDown = array.size(iFibDown) // // // // // y_to_yTrend_max = find_series_high(y_to_yTrend) // y_to_yTrend_min = find_series_loww(y_to_yTrend) //+-----+ // y_detrended = y_detrend(year_fraction) // plot(y, title="y_detrended", color=color.orange, linewidth=1, style=6) // Want horizontal SP500 over 1926-2020 - to compare variations from 83 year trend to [interest rates, currencies, inflation, Fed pump, commodities, etc] // save this for down the road // show_0 = input(true, "", inline = "Level0") // value_0 = input(0, "", inline = "Level0") // color_0 = input(#787b86, "", inline = "Level0") // processLevel(show_0, value_0, color_0) // // show_0_236 = input(true, "", inline = "Level0") // value_0_236 = input(0.236, "", inline = "Level0") // color_0_236 = input(#f44336, "", inline = "Level0") // processLevel(show_0_236, value_0_236, color_0_236) // // show_0_382 = input(true, "", inline = "Level1") // value_0_382 = input(0.382, "", inline = "Level1") // color_0_382 = input(#81c784, "", inline = "Level1") // processLevel(show_0_382, value_0_382, color_0_382) // // show_0_5 = input(true, "", inline = "Level1") // value_0_5 = input(0.5, "", inline = "Level1") // color_0_5 = input(#4caf50, "", inline = "Level1") // processLevel(show_0_5, value_0_5, color_0_5) // // show_0_618 = input(true, "", inline = "Level2") // value_0_618 = input(0.618, "", inline = "Level2") // color_0_618 = input(#009688, "", inline = "Level2") // processLevel(show_0_618, value_0_618, color_0_618) // // show_0_65 = input(false, "", inline = "Level2") // value_0_65 = input(0.65, "", inline = "Level2") // color_0_65 = input(#009688, "", inline = "Level2") // processLevel(show_0_65, value_0_65, color_0_65) // // show_0_786 = input(true, "", inline = "Level3") // value_0_786 = input(0.786, "", inline = "Level3") // color_0_786 = input(#64b5f6, "", inline = "Level3") // processLevel(show_0_786, value_0_786, color_0_786) // // show_1 = input(true, "", inline = "Level3") // value_1 = input(1, "", inline = "Level3") // color_1 = input(#787b86, "", inline = "Level3") // processLevel(show_1, value_1, color_1) // // show_1_272 = input(false, "", inline = "Level4") // value_1_272 = input(1.272, "", inline = "Level4") // color_1_272 = input(#81c784, "", inline = "Level4") // processLevel(show_1_272, value_1_272, color_1_272) // // show_1_414 = input(false, "", inline = "Level4") // value_1_414 = input(1.414, "", inline = "Level4") // color_1_414 = input(#f44336, "", inline = "Level4") // processLevel(show_1_414, value_1_414, color_1_414) // // show_1_618 = input(true, "", inline = "Level5") // value_1_618 = input(1.618, "", inline = "Level5") // color_1_618 = input(#2196f3, "", inline = "Level5") // processLevel(show_1_618, value_1_618, color_1_618) // // show_1_65 = input(false, "", inline = "Level5") // value_1_65 = input(1.65, "", inline = "Level5") // color_1_65 = input(#2196f3, "", inline = "Level5") // processLevel(show_1_65, value_1_65, color_1_65) // // show_2_618 = input(true, "", inline = "Level6") // value_2_618 = input(2.618, "", inline = "Level6") // color_2_618 = input(#f44336, "", inline = "Level6") // processLevel(show_2_618, value_2_618, color_2_618) // // show_2_65 = input(false, "", inline = "Level6") // value_2_65 = input(2.65, "", inline = "Level6") // color_2_65 = input(#f44336, "", inline = "Level6") // processLevel(show_2_65, value_2_65, color_2_65) // // show_3_618 = input(true, "", inline = "Level7") // value_3_618 = input(3.618, "", inline = "Level7") // color_3_618 = input(#9c27b0, "", inline = "Level7") // processLevel(show_3_618, value_3_618, color_3_618) // // show_3_65 = input(false, "", inline = "Level7") // value_3_65 = input(3.65, "", inline = "Level7") // color_3_65 = input(#9c27b0, "", inline = "Level7") // processLevel(show_3_65, value_3_65, color_3_65) // // show_4_236 = input(true, "", inline = "Level8") // value_4_236 = input(4.236, "", inline = "Level8") // color_4_236 = input(#e91e63, "", inline = "Level8") // processLevel(show_4_236, value_4_236, color_4_236) // // show_4_618 = input(false, "", inline = "Level8") // value_4_618 = input(4.618, "", inline = "Level8") // color_4_618 = input(#81c784, "", inline = "Level8") // processLevel(show_4_618, value_4_618, color_4_618) // // show_neg_0_236 = input(false, "", inline = "Level9") // value_neg_0_236 = input(-0.236, "", inline = "Level9") // color_neg_0_236 = input(#f44336, "", inline = "Level9") // processLevel(show_neg_0_236, value_neg_0_236, color_neg_0_236) // // show_neg_0_382 = input(false, "", inline = "Level9") // value_neg_0_382 = input(-0.382, "", inline = "Level9") // color_neg_0_382 = input(#81c784, "", inline = "Level9") // processLevel(show_neg_0_382, value_neg_0_382, color_neg_0_382) // // show_neg_0_618 = input(false, "", inline = "Level10") // value_neg_0_618 = input(-0.618, "", inline = "Level10") // color_neg_0_618 = input(#009688, "", inline = "Level10") // processLevel(show_neg_0_618, value_neg_0_618, color_neg_0_618) // // show_neg_0_65 = input(false, "", inline = "Level10") // value_neg_0_65 = input(-0.65, "", inline = "Level10") // color_neg_0_65 = input(#009688, "", inline = "Level10") // processLevel(show_neg_0_65, value_neg_0_65, color_neg_0_65) 08******08 #] 16Mar2021 TradingView standard PineScript for Fibonacci bar_index - is the array index for chart's [x,y] values? https://www.tradingview.com/script/Rhj1nNLH-Max-Drawdown-Calculating-Functions-Optimized/ >> this might help me >> many scripters seem to be struggling +-----+ #] 17Mar2021 search "TradingView PineScript and Mismatched input 'for' expecting 'end of line continuation'." https://stackoverflow.com/questions/51724359/i-got-tradingviews-end-of-line-without-continuation-error-with-pine-script The 'end of line without continuation' error happens when there's an indentation mistake in the TradingView Pine code. Looking at your code (and assuming copying it into StackOverflow went right), there is indeed an indentation problem: val(s) => if s != s[1] a = s-s[1] if s = s[1] a a There are two indentation problems in this code: The first 4 lines of the function are indented with 5 spaces (or 1 Tab plus a space). But code lines of a function need to be indented with 4 spaces (or 1 Tab) in TradingView Pine. The two lines that follow after the if statements are not indented. But they do need to be: with 4 spaces (or 1 Tab) or a multiple thereof. When we fix those two points the code becomes: val(s) => if s != s[1] a = s-s[1] if s == s[1] a a (Note that I also replaced the = assignment operator with the == operator for equality here.) +-----+ Fibonacci numbers https://school.stockcharts.com/doku.php?id=chart_analysis:fibonacci_retracemen https://medium.com/@mehmetatakartal/fibonacci-ratios-and-methods-in-technical-analysis-db3cc2f1182e Personally, I do not use Fibonacci retracement in cryptocurrency market. I only use the Fibonacci Ratios in moving averages. They work perfect because when the market is volatile, we need dynamic support/resistance levels not just static lines. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765 0.055728 0.0901697 0.145898 0.236072 0.381971 0.5 0.618047 0.786164 1.0 1.272 1.618 2.0 2.618 4.236 6.8541 11.0902 17.9443 4.23729 2.6178 2. 1.61812 1.27226 1. 0.786164 0.618047 0.381971 0.276396 0.236072 0.216544 very aproximate extimates > 1.618, removed false literature 0.216544 0.276396, 6765/987 = 4.23607, 3.618 stick with solid ratios qnial> 6765/377 17.9443 qnial> 6765/610 11.0902 qnial> 6765/987 6.8541 qnial> 6765/1597 4.23607 qnial> 6765/2584 2.61803 qnial> a := 0.055728 0.0901697 0.145898 0.236072 0.381971 0.5 0.618047 0.786164 1.0 1.272 1.618 2.0 2.618 4.236 6.8541 11.0902 17.9443 qnial> b := reverse recip a 0.055728 0.0901697 0.145898 0.236072 0.381971 0.5 0.618047 0.786164 1. 1.272 1.618 2. 2.618 4.236 6.8541 11.0902 17.9443 qnial> c := (a - b)/a -4.96e-08 6.94e-09 -5.182e-07 9.91999e-07 7.8e-08 0. 4.6e-08 6.08e-07 0. 6.08e-07 4.6e-08 0. 7.8e-08 9.91999e-07 -5.182e-07 6.94e-09 -4.96e-08 >> OK! qnial> reverse a 17.9443 11.0902 6.8541 4.236 2.618 2. 1.618 1.272 1. 0.786164 0.618047 0.5 0.381971 0.236072 0.145898 0.0901697 0.055728 +-----+ #] 17Mar2021 search "TradingView PineScript and "cannot call 'array.get' ..." "TradingView PineScript and "cannot call 'array.get' with arguments (series[float], literal integer); available overloads: array.get(array[], series[integer]) => ;" 08******08 #] 15Mar2021 PineScript for Turtle Trade of SP500 https://www.tradingview.com/chart/kfkUtvGu/ https://tr.tradingview.com/script/pB5nv16J/?utm_source=notification_email&utm_medium=email&utm_campaign=notification_pubscript_update Kıvanç Özbilgiç 29Oct2020, Sürüm Notları update 13Mar2021 Kıvanç : Turtle Trade uses the basic logic of well known DONCHIAN CHANNELS which were developed by Richard Donchian. SP500 log detrended 1926-2020 = 10^(0.792392+0.0289587*(year_fraction - 1926.25)) http://www.billhowell.ca/economics,%20markets/SP500/multi-fractal/1872-2020%20SP500%20index,%20ratio%20of%20opening%20price%20to%20semi-log%20detrended%20price.html Here's my first shot at learning PineScript. I have adapted Kıvanç Özbilgiç's Turtle Trade PineScript : https://tr.tradingview.com/script/pB5nv16J/?utm_source=notification_email&utm_medium=email&utm_campaign=notification_pubscript_update I've also added an 83-year semi-log detrended SP500 index, which is explained at : http://www.billhowell.ca/economics,%20markets/SP500/multi-fractal/1872-2020%20SP500%20index,%20ratio%20of%20opening%20price%20to%20semi-log%20detrended%20price.html >> Oops, should have published the PineScript, not the graph. +--+ @onurkarabag, Although this was a quick training lesson applied to SP500, the script is actually more generic. I'm just getting started at this, but my approach would be : - start up a chart, for example https://www.tradingview.com/symbols/BTCUSD/?exchange=BITSTAMP - click "Full-feature chart" - click "Pine Editor"" in the menu at the bottom of the page - copy-paste the script above to the editor and Save - switch from the editor to the "Full-feature chart" to see if it works But I'm sure that there are short-cuts and easier ways to do it, such as just linking to the public version of this script somehow. Note that most of the script, and the hard parts, are from Kıvanç Özbilgiç & Sürüm Notları. I just made some very simple changes and additions. I wouldn't spend too much time on that, as I hope to find time to clean it up and upgrade it with a Fibonnacci mirror. That has to wait until I take a break from other priorities, so a or a month from now or something that. 08******08 #] 15Mar2021 to see PineScript built-in functions : go to PineScript editor -> Menu -> ... (more) -> PineScript reference (pop up) -> Built-in functions https://www.tradingview.com/pine-script-docs/en/v4/language/Expressions_declarations_and_statements.html [if, for, etc] statements +-----+ time The time function returns the UNIX time of the current bar for the specified resolution and session or NaN if the time point is out of session. time(resolution, session) → series[integer] time(resolution) → series[integer] Example //@version=4 study("Time", overlay=true) // Try this on chart AAPL,1 timeinrange(res, sess) => not na(time(res, sess)) ? 1 : 0 plot(timeinrange("1", "1300-1400"), color=color.red) // This plots 1.0 at every start of 10 minute bar on a 1 minute chart: newbar(res) => change(time(res)) == 0 ? 0 : 1 plot(newbar("10")) While setting up a session you can specify not just the hours and minutes but also the days of the week that will be included in that session. If the days aren't specified, the session is considered to have been set from Monday to Friday (Saturday and Sunday are excluded as the weekend days), i.e. "1100-2000" is the same as "1100-1200:23456". For example, on a symbol that is traded seven days a week with the 24-hour trading session the following script will not color Saturdays and Sundays: Example //@version=4 study("Time", overlay=true) t1 = time(timeframe.period, "0000-0000") bgcolor(t1 ? color.blue : na) You can change that by specifying the days: Example //@version=4 study("Time - days", overlay=true) t1 = time(timeframe.period, "0000-0000:1234567") bgcolor(t1 ? color.green : na) Returns UNIX time. Arguments resolution (string) Resolution. An empty string is interpreted as the current resolution of the chart. session (string) Session specification. Optional argument, session of the symbol is used by default. An empty string is interpreted as the session of the symbol. Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. +-----+ year year(time) → series[integer] year(time, timezone) → series[integer] Returns Year (in exchange timezone) for provided UNIX time. Arguments time (series) UNIX time in milliseconds. timezone (string) An optional parameter. Timezone. Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp. +-----+ pow - Mathematical power function. pow(base, exponent) → float pow(base, exponent) → input float pow(base, exponent) → const float pow(base, exponent) → series[float] Example pow(close, 2) 08********08 #] 14Dec2020 Awesome statistic commentary!! balipour, Using Moments For Trend and Mean Reversion Trading https://www.tradingview.com/script/LiQbTD6e-Moments-Mean-Variance-Skewness-Kurtosis-pig/?&utm_source=Weekly&utm_medium=email&utm_campaign=TradingView+Weekly+86+%28EN%29 Moments (Mean,Variance,Skewness,Kurtosis) [pig] balipour, Dec 9 Using Moments For Trend and Mean Reversion Trading: Use the autocorrelation testing indicators to confirm trend or mean reversion. Then use log return, mean, and stdev bands to act accordingly. Trend trading using mean and variance. When variance/stdev is high, take a trade based on the mean's direction. Trend trading using skewness and kurtosis . When kurtosis is significantly positive, it indicates a large risk. But for trend trading strategies, they profit from extreme moves. Take a trade based on the direction of skewness if the kurtosis and skewness are both significant. Profit from extreme values in the direction of skewness. Mean reversion strategies using kurtosis . When kurtosis is low, the risk of trading mean reversion is lower. Mean reversion strategies using skewness. A positive skewness doesn't always mean bullish and a negative skewness doesn't always mean bearish . It only shows the shape of the distribution in the past. Skewness may sometimes even have a negative correlation with price. There are studies that show buying commodities with the most negative skewness and shorting commodities with the largest positive skewness can be profitable. And it could be applied not only in commodities . This is probably due to people's preference for longing positively-skewed securities. They tend to speculate a large profit from low probabilities. They will be overpricing the large positively-skewed securities and when the market underperforms, their expectation is that it will drop. >> See Pinescript code : /media/bill/PROJECTS/Investments/PineScript/balipour, pig - moments [mean, variance, skewness, kurtosis].pineScript Andye81 Dec 10 Another amazing indicator to add to the arsenal of world class indicators from bapigindicators.com. These two gentlemen, are maths geniuses and are making tools for the benefit of man ( and lady) kind. Amazing explanation and write up. Keep up the amazing work. # enddoc # enddoc