How to use Leverage and Margin in PineScriptEn route to being absolutely the best and most complete trading platform out there, TradingView has just closed 2 gaps in their PineScript language.
It is now possible to create and backtest a strategy for trading with leverage.
Backtester now produces Margin Calls - so recognizes mid-trade drawdown and if it is too big for the broker to maintain your trade, some part of if will be instantly closed.
New additions were announced in official blogpost , but it lacked code examples, so I have decided to publish this script. Having said that - this is purely educational stuff.
█ LEVERAGE
Let's start with the Leverage. I will discuss this assuming we are always entering trades with some percentage of our equity balance (default_qty_type = strategy.percent_of_equity), not fixed order quantity.
If you want to trade with 1:1 leverage (so no leverage) and enter a trade with all money in your trading account, then first line of your strategy script must include this parameter:
default_qty_value = 100 // which stands for 100%
Now, if you want to trade with 30:1 leverage, you need to multipy the quantity by 30x, so you'd get 30 x 100 = 3000:
default_qty_value = 3000 // which stands for 3000%
And you can play around with this value as you wish, so if you want to enter each trade with 10% equity on 15:1 leverage you'd get default_qty_value = 150.
That's easy. Of course you can modify this quantity value not only in the script, but also afterwards in Script Settings popup, "Properties" tab.
█ MARGIN
Second newly released feature is Margin calculation together with Margin Calls. If the market goes against your trades and your trading account cannot maintain mid-trade drawdown - those trades will be closed in full or partly. Also, if your trading account cannot afford to open more trades (pyramiding those trades), Margin mechanism will prevent them from being entered.
I will not go into details about how Margin calculation works, it was all explainged in above mentioned blogpost and documentation .
All you need to do is to add two parameters to the opening line of your script:
margin_long = 1./30*50, margin_short = 1./30*50
Whereas "30" is a leverage scale as in 30:1, and "50" stands for 50% of Margin required by your broker. Personally the Required Margin number I've met most often is 50%, so I'm using value 50 here, but there are literally 1000+ brokers in this world and this is individual decision by each of them, so you'd better ask yourself.
--------------------
Please note, that if you ever encounter a strategy which triggers Margin Call at least once, then it is probably a very bad strategy. Margin Call is a last resort, last security measure - all the risks should be calculated by the strategy algorithm before it is ever hit. So if you see a Margin Call being triggred, then something is wrong with risk management of the strategy. Therefore - don't use it!
Indikator dan strategi
Normalized Oscillators Spider Chart [LuxAlgo]This indicator displays a spider chart overlaid on the user’s current chart allowing the visualization of information given by various normalized oscillators. It is possible to customize the spider chart by hiding certain oscillators from within the settings which removes their corresponding spokes from the chart.
Users can control the length settings of each oscillator individually or use a global length setting that applies to every oscillator. An additional meter element is displayed and aims to give the overall sentiment returned by the oscillators. This can also be used to gauge whether the market is trending or ranging.
This is a relatively simple application of a spider chart but can prove to be useful to some users.
1. Settings
RSI: Displays the Relative Strength Index spoke on the spider chart, includes the length setting on the right of the toggle.
%K: Displays the Stochastic Oscillator "%K" spoke on the spider chart, includes the length setting on the right of the toggle.
COR: Displays the Correlation Oscillator spoke on the spider chart, includes the length setting on the right of the toggle.
MFI: Displays the Money Flow Index oscillator spoke on the spider chart, includes the length setting on the right of the toggle.
WPR: Displays the Williams Percent Rank oscillator spoke on the spider chart, includes the length setting on the right of the toggle.
%UP: Displays the percentage of upward variations spoke on the spider chart, includes the length setting on the right of the toggle.
CMO: Displays the Chande Momentum Oscillator spoke on the spider chart, includes the length setting on the right of the toggle.
AOS: Displays the Aroon oscillator spoke on the spider chart, includes the length setting on the right of the toggle.
Global Oscillators Length: Determines whether all oscillators should use the same length settings, determined by the setting on the right of the toggle.
1.1 Style Settings
Spider Chart Length: Determines the horizontal width of the spider chart.
Spider Chart Offset: Offset between the most recent bar and the left extremity of the spider chart.
2. Usage
A spider chart can be a very useful visualization tool when it comes to seeing the individual characteristics of various variables at the same time.
Here, the tool can give a general sentiment on the direction of the trend without adding each indicator to your chart. It is also possible to determine when an oscillator is considered overbought or oversold with this indicator.
The dashed line represents the central value for each oscillator.
Disabling any of the oscillators from the settings will return a spider chart using fewer spokes.
The script also displays a meter that can be used to determine the overall sentiment given by all oscillators. This metric is based on the average value between each oscillator. An overall sentiment closer to 50 would indicate a ranging market.
Weighted Harrell-Davis Quantile Estimator with AbsoluteDeviation
QUANTILE ESTIMATORS
Weighted Harrell-Davis Quantile Estimator with Absolute Deviation Fences.
DISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The following indicator was made for NON LUCRATIVE ACTIVITIES and must remain as is, following TradingView's regulations. Use of indicator and their code are published for work and knowledge sharing. All access granted over it, their use, copy or re-use should mention authorship(s) and origin(s).
WARNING NOTICE!
THE INCLUDED FUNCTION MUST BE CONSIDERED FOR TESTING. The models included in the indicator have been taken from open sources on the web and some of them has been modified by the author, problems could occur at diverse data sceneries, compiler version, or any other externality.
Purpose:
Weighted Quantiles or <> are quite difficult to find on must systems, also it's non-weighted approach are rarely used to estimate the location parameter of price distribution WICH IS NOT NORMAL, all this in favour of it's non-robust counterpart, the Arithmetic rolling Mean or <> and it's weighted variants like the WMA, VWAP, etc.
Also, a big drawback from this is that must statistics derived from Normal-Distribution parameter location (the Mean) definitely will not fit for an efficient, nor robust estimation for price distributions, so their moments like the standard deviation, kurtosis, skewness, etc. will not be the better tools to build derived algorithms or technical indicators among price/volume.
In an effort searching better statistical tools for price distributions, I found the excellent work of Andrey Akinshin that took me to port some of their Math research contributions for the compute benchmarking field , and bring it here at the TradingView ecosystem to take a shot at the price distribution crazy fields. For a better detail of what the weighted Harrell-Davis Quantile Estimator can do, who better than drink directly from the source at References:
References:
Weighted Quantile Estimators.
DoubleMAD outlier detector based on the Harrell-Davis quantile estimator.
Unbiased median absolute deviation based on the Harrell-Davis quantile estimator.
Quantile confidence intervals for weighted samples.
Licensing:
This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International Copyright (c) 2021 (CC BY-NC-SA 4.0)
Copyright's & Mentions:
The Gamma Functions & Beta Probability Density Functions C# implementations by the Math.NET Numerics, part of the Math.NET Project.
The Regularized Incomplete (Left) Beta Function C# implementation by the SAMTools, htslib project.
The Weighted Harrell-Davis Quantile estimator ; C# & R implementations by Andrey Akinshin.
External PineScript code, methods, support & consultancy by @PineCoders staff with special mention for:
+ "ma sorter ('sort by array' example)- JD" by @Duyck.
+ Porting, mods, compilation and debugging for this script by @XeL_Arjona for the TradingView's @PineCoders community.
Dominance tagcloud [experimental] This script is mainly about 2 techniques:
- rectangles that don't overlap with the use of random() -> f_overlap(x1_a, y1_a, x2_a, y2_a, x1_b, y1_b, x2_b, y2_b)
- using a "while loop" (inspired by @ricardosantos)
The loop:
for x = 0 to 999999
if ...
do ...
continue
else ...
break
resembles a "while loop"
There are 2 settings :
"Moving Boxes?"
- enabled: the boxes are made and move randomly
- disabled: the boxes are randomly made, without moving
"Label at the side"
- enabled: labels at the side
- disabled: labels at the rectangles, note while rectangles won't overlap, the text can overlap
Cheers!
RedK Slow_Smooth Average (RSS_WMA)RedK Slow Smooth Average (RSS_WMA) is based on simple, multi-WMA passes to generate a moving average that sacrifices low-lag and fast responsiveness for the sake of smoothness.
This smoothness enables an increased trader ability to visualize and track longer-term trends and removes the noise of smaller, relatively insignificant price fluctuations.
Notes:
=========
* RSS_WMA is deliberately built to be a "lazy line" - and it works in a different way to other common moving averages that attempt to achieve less lag and quicker responsiveness - the idea and the use scenario is to act as a "smooth base" when used against a faster moving average like the v_Wave of the Co_Ra Wave
* Note that the settings of this line is "Smoothness' and not "length" - the initial length used for the first WMA pass calculation is 1/3 of that smoothness value selected in the settings
* Increments in the combined smoothness value will be allocated first to 1st WMA pass, then 2nd WMA pass, then 3rd pass consecutively then back to 1st pass.
* because we utilize 3 WMA passes, a settings below 3 will have no effect on the line and it will just track the "source" price.
Suggested Use:
===============
- Use RSS_WMA when you're looking for a smooth moving average that can help you analyze you chart at a broader / macro level, visualize the broader price action patterns and filter out the noise from short-term moves. you can also use this line to help set your position exits since only major and persistent moves will cause this line, as lay as it is, to swing from one direction to the other.
How does RSS_WMA compare?
============================
here's a quick view of how the RSS_WMA compared to other commonly used Moving Averages, including my recently published CoRa_Wave
Code is commented - please feel free to use and customize further - please share a comment if you found this useful in your chart analysis or trading.
Financials on Chart█ OVERVIEW
This indicator displays your choice of up to 9 fundamentals on your chart.
█ FEATURES
You can configure the following attributes of the display:
• Its position on your chart.
• Automatic or custom height and width of rows.
• The size and color of text.
• The default background color (you can override it with a custom color for individual values).
• Conversion of values expressed in USD to one of the major currencies. Financials are normally expressed in quote currency.
Conversion to other currencies is only done when the symbol's quote currency is USD.
• Choose if the currency used for the financials is displayed. Note that some financials are calculated values that are not expressed in currency units.
No currency will be displayed for these values.
• Abbreviate large values.
For each value, you may:
• Pick one of the 222 financials available in Pine, or one of five values calculated from the financials (Market Cap, Earnings Yield, P/B Ratio, P/E Ratio and Price-To-Sales Ratio).
• Choose a period (see the "i" icon near the first value's fields in the script's inputs for a list of exceptions).
• Specify the value's precision.
• Change the legend displayed with the value.
• Adjust the text's size.
• Use a custom background.
█ LIMITATIONS
When changing the indicator's inputs, allow a few seconds for the change to be reflected in the display.
If your chart displays a symbol for which the configured financials cannot be fetched, an error will occur.
Not all periods are available for all fundamentals or for all markets. What financial data is available in Pine? will give you an overview of the available periods for each value. The page also contains the formulas used for the five values we calculate from the financials. This page shows the typical reporting frequency for different countries .
█ FINANCIALS
See What is Financial Data? and Why does Financial Data differ from other sources? for more information on the data used by this indicator.
This lists all the financials. Clicking on one will bring up more information about it:
CALCULATED
Market Capitalization
Earnings Yield
Price Book Ratio
Price Earnings Ratio
Price-To-Sales Ratio
INCOME STATEMENTS
After tax other income/expense
Average basic shares outstanding
Other COGS
Cost of goods
Deprecation and amortization
Diluted net income available to common stockholders
Diluted shares outstanding
Dilution adjustment
Discontinued operations
Basic EPS
Diluted EPS
EBIT
EBITDA
Equity in earnings
Gross profit
Taxes
Interest capitalized
Interest expense on debt
Non-controlling/minority interest
Net income before discontinued operations
Net income
Non-operating income, excl. interest expenses
Interest expense, net of interest capitalized
Non-operating interest income
Operating income
Operating expenses (excl. COGS)
Miscellaneous non-operating expense
Other operating expenses, total
Preferred dividends
Pretax equity in earnings
Pretax income
Research & development
Selling/general/admin expenses, other
Selling/general/admin expenses, total
Non-operating income, total
Total operating expenses
Total revenue
Unusual income/expense
BALANCE SHEET
Accounts payable
Accounts receivable - trade, net
Accrued payroll
Accumulated depreciation, total
Additional paid-in capital/Capital surplus
Tangible book value per share
Book value per share
Capitalized lease obligations
Capital and operating lease obligations
Cash & equivalents
Cash and short term investments
Common equity, total
Common stock par/Carrying value
Current portion of LT debt and capital leases
Deferred income, current
Deferred income, non-current
Deferred tax assets
Deferred tax liabilities
Dividends payable
Goodwill, net
Income tax payable
Net intangible assets
Inventories - finished goods
Inventories - progress payments & other
Inventories - raw materials
Inventories - work in progress
Investments in unconsolidated subsidiaries
Long term debt excl. lease liabilities
Long term debt
Long term investments
Note receivable - long term
Other long term assets, total
Minority interest
Notes payable
Operating lease liabilities
Other common equity
Other current assets, total
Other current liabilities
Other intangibles, net
Other investments
Other liabilities, total
Other receivables
Other short term debt
Paid in capital
Gross property/plant/equipment
Net property/plant/equipment
Preferred stock, carrying value
Prepaid expenses
Provision for risks & charge
Retained earnings
Short term debt excl. current portion of LT debt
Short term debt
Short term investments
Shareholders' equity
Total assets
Total current assets
Total current liabilities
Total debt
Total equity
Total inventory
Total liabilities
Total liabilities & shareholders' equities
Total non-current assets
Total non-current liabilities
Total receivables, net
Treasury stock - common
CASHFLOW
Amortization
Capital expenditures - fixed assets
Capital expenditures
Capital expenditures - other assets
Cash from financing activities
Cash from investing activities
Cash from operating activities
Deferred taxes (cash flow)
Depreciation & amortization (cash flow)
Change in accounts payable
Change in accounts receivable
Change in accrued expenses
Change in inventories
Change in other assets/liabilities
Change in taxes payable
Changes in working capital
Common dividends paid
Depreciation/depletion
Free cash flow
Funds from operations
Issuance/retirement of debt, net
Issuance/retirement of long term debt
Issuance/retirement of other debt
Issuance/retirement of short term debt
Issuance/retirement of stock, net
Net income (cash flow)
Non-cash items
Other financing cash flow items, total
Financing activities - other sources
Financing activities - other uses
Other investing cash flow items, total
Investing activities - other sources
Investing activities - other uses
Preferred dividends paid
Purchase/acquisition of business
Purchase of investments
Repurchase of common & preferred stock
Purchase/sale of business, net
Purchase/sale of investments, net
Reduction of long term debt
Sale of common & preferred stock
Sale of fixed assets & businesses
Sale/maturity of investments
Issuance of long term debt
Total cash dividends paid
STATISTICS
Accruals
Altman Z-score
Asset turnover
Beneish M-score
Buyback yield %
Cash conversion cycle
Cash to debt ratio
COGS to revenue ratio
Current ratio
Days sales outstanding
Days inventory
Days payable
Debt to assets ratio
Debt to EBITDA ratio
Debt to equity ratio
Debt to revenue ratio
Dividend payout ratio %
Dividend yield %
Dividends per share - common stock primary issue
EPS estimates
EPS basic one year growth
EPS diluted one year growth
EBITDA margin %
Effective interest rate on debt %
Enterprise value to EBITDA ratio
Enterprise value
Equity to assets ratio
Enterprise value to EBIT ratio
Enterprise value to revenue ratio
Float shares outstanding
Free cash flow margin %
Fulmer H factor
Goodwill to assets ratio
Graham's number
Gross margin %
Gross profit to assets ratio
Interest coverage
Inventory to revenue ratio
Inventory turnover
KZ index
Long term debt to total assets ratio
Net current asset value per share
Net income per employee
Net margin %
Number of employees
Operating earnings yield %
Operating margin %
PEG ratio
Piotroski F-score
Price earnings ratio forward
Price sales ratio forward
Price to free cash flow ratio
Price to tangible book ratio
Quality ratio
Quick ratio
Research & development to revenue ratio
Return on assets %
Return on equity adjusted to book value %
Return on equity %
Return on invested capital %
Return on tangible assets %
Return on tangible equity %
Revenue one year growth
Revenue per employee
Revenue estimates
Shares buyback ratio %
Sloan ratio %
Springate score
Sustainable growth rate
Tangible common equity ratio
Tobin's Q (approximate)
Total common shares outstanding
Zmijewski score
█ NOTES
This script uses the Pine financial() function to fetch the values it displays.
Look first. Then leap.
Volume per PointHello everyone <3
I present to you guys my new indicator Volume per Point (VP)
As suggested by the title, this script gives you the volume for every point.
Here's a run down on specific features:
SUBCHART COLUMNS:
The columns can be the following four colors:
Green - There was an increase in VP
Red - There was a decrease in VP
Yellow - There was divergence between volume and candle range
Purple - There are signs of exhaustion compared to the previous candlestick
SUBCHART HISTOGRAM:
The histogram can be the following two colors:
Lime - Buying volume
Red - Selling volume
I left you guys the ability to change the multiplier on the volume in settings just incase it's too small or too big compared to the VP. Decimals are allowed!
CANDLESTICK CHART:
The candlesticks can the following two colors:
Yellow - There was a divergence between volume and candle range
Purple - There are signs of exhaustion compared to the previous candlestick
FILTERS
In the settings, you're able to add the following two filters:
RSI Filters - RSI must be below or above the specified value for the divergence or exhaustion to trigger
Percent Filters - The candlestick range or volume must be higher or lower than the specified value depending whether it's divergence or exhaustion.
This is a very helpful tool if you're interesting in reading volume. It also facilitates finding market maker activity depending on the size of the VP. Sudden abnormal spikes in VP usually do signal something and that's up for you to figure out :)
Thank you for your time to read this
~July <3
Cup FinderHello All,
This script finds the Cups and you can use it while analysing the symbols. it creates circle and channel for the potential Cups and checks the number of bars included by the channel, if included bars is equal or greater than the value you set then it shows the cup.
The Options:
"Number for Bars to search" : Maximum length of a Cup
"Channel Width of the Cup" : Tate by the channel width of highest/lowest levels in last 300 bars, by default it's 5%
"Check for Breakout" : if there is Cup then it checks Close or High/Low is used a source for breaokuts, usuful while cheking historical bars
"Contained Bar Rate %" : after channel is created the script checks number of bars included by the channel of the Cup, you can set rate of included bars by this option
"S how Channels of Cups ": if you enable this option then you can see the channels around the Cups and set it as you wish
and there are some other options for labeling/removing old Cups and for coloring
Here you can see how channel looks like:
Cup with different colors:
P.S. This is an experimental work and sorry for no explanation in the script.
in the future if I have time I will try to write a script for Cup&Handle
This script is also an example to calculate and draw circles :)
Enjoy!
Outlier Detector with N-Sigma Confidence IntervalsA detrended series that oscilates around zero is obtained after first differencing a time series (i.e. subtracting the closing price for a candle from the one immediately before, for example). Hypothetically, assuming that every detrended closing price is independent of each other (what might not be true!), these values will follow a normal distribution with mean zero and unknown variance sigma squared (assuming equal variance, what is also probably not true as volatility changes over time for different pairs). After studentizing, they follow a Student's t-distribution, but as the sample size increases (back periods > 30, at least), they follow a standard normal distribution.
This script was developed for personal use and the idea is spotting candles that are at least 99% bigger than average (using N = 3) as they will cross the upper and lower confidence interval limits. N = 2 would roughly provide a 95% confidence interval.
RedK Compound Ratio Moving Average (CoRa_Wave)
Compound Ratio Weighted Average (CoRa_Wave) is a moving average where the weights increase in a "logarithmically linear" way - from the furthest point in the data to the current point - the formula to calculate these weights work in a similar way to how "compound ratio" works - you start with an initial amount, then add a consistent "ratio of the cumulative prior sum" each period until you reach the end amount. The result is, the "step ratio" between the weights is consistent - This is not the case with linear-weights moving average (WMA), or EMA
- for example, if you consider a Weighted Moving Average (WMA) of length 5, the weights will be (from the furthest point towards the most current) 1, 2, 3, 4, 5 -- we can see that the ratio between these weights are inconsistent. in fact, the ratio between the 2 furthest points is 2:1, but the ratio between the most recent points is 5:4 -- the ratio is inconsistent, and in fact, more recent points are not getting the best weights they should/can get to counter-act the lag effect. Using the Compound ratio approach addresses that point.
a key advantage here is that we can significantly reduce the "tail weight" - which is "relatively" large in other MAs and would be main cause for lag - giving more weights to the most recent data points - and in a way that is consistent, reliable and easy to "code"
- the outcome is, a moving average line that suffers very little lag regardless of the length, and that can be relied on to track the price movements and swings closely.
other features:
===============
- An accelerator, or multiplier, has been added to further increase the "aggressiveness" of the moving average line, giving even more weights to the more recent points - the multiplier will have more effect between 1 and 5, then will have a diminishing effect after that - note that a multiplier of 0 (which effectively causes a comp. ratio of 0 to be applied) will produce a Simple Moving Average line :)
- We also added the ability to use an "automatic smoothing" mechanism, that user can over-ride by manually choosing how much smoothing is used. This gives more flexibility to how we can leverage this Moving Average in our charting.
- User can also select the Resolution and Source price for the CoRa_Wave. by default, they will be set to "same as chart" and hlc3
here are the formulas for our Compound Ratio moving average:
Compound Weight ratio r = (A/P)^1/t - 1
Weight at time t A = P(1 + r)^t
= Start_val * (1 + r) ^ index
index in the above formula is 0 for the furthest point out
Here's how CoRa_Wave compares to other common moving averages all set to the same length (20)
Proposed Usage
- CoRa_Wave can be used for any scenarios where we need a moving average that closely tracks the price, trend, swings with high responsiveness and little lag
- MA Cross-over scenarios - against another CoRa_Wave or any other MA
- below is a quick example scenario for how to utilize 2 CoRa_Wave lines of same length (one for open and one for closing price) to track swings and trends
- get as creative as you need :)
Code is commented - please feel free to leverage or customize further as you need.
👉 if you are interested in other moving averages i posted before, please check out the FiMA and the v_Wave ...
Detrended Rhythm Oscillator (DRO)How to detect the current "market beat" or market cycle?
A common way to capture the current dominant cycle length is to detrend the price and look for common rhythms in the detrended series. A common approach is to use a Detrended Price Oscillator (DPO). This is done in order to identify and isolate short-term cycles.
A basic DPO description can be found here:
www.tradingview.com
Improvements to the standard DPO
The main purpose of the standard DPO is to analyze historical data in order to observe cycle's in a market's movement. DPO can give the technical analyst a better sense of a cycle's typical high/low range as well as its duration. However, you need to manually try to "see" tops and bottoms on the detrended price and measure manually the distance from low-low or high-high in order to derive a possible cycle length.
Therefore, I added the following improvements:
1) Using a DPO to detrend the price
2) Indicate the turns of the detrended price with a ZigZag lines to better see the tops/bottoms
3) Detrend the ZigZag to remove price amplitude between turns to even better see the cyclic turns ("rhythm")
4) Measure the distance from last detrended zigzag pivot (high-high / low-low) and plot the distance in bars above/below the turn
Now, you can clearly see the rhythm of the dataset indicated by the Detrended Rhythm Oscillator including the exact length between the turns. This makes the procedure to "spot" turns and "measure" distance more simple for the trader.
How to use this information
The purpose is to check if there is a common rhythm or beat in the underlying dataset. To check that, look for recurring pattern in the numbers. E.g. if you often see the same measured distance, you can conclude that there is a major dominant cycle in this market. Also watch for harmonic relations between the numbers. So in the example above you see the highlighted cluster of detected length of around 40,80 and 120. There three numbers all have a harmonic relation to 40.
Once you have this cyclic information, you can use this number to optimize or tune technical indicators based on the current dominant cycle length. E.g. set the length parameter of a technical indicator to the detected harmonic length with the DRO indicator.
Example Use-Case
You can use this information to set the input for the following free public open-source script:
Disclaimer
This is not meant to be a technical indicator on its own and the derived cyclic length should not be used to forecast the next turn per se. The indicator should give you an indication of the current market beat or dominant beats which can be use to further optimize other oscillator or trading related settings.
Options & settings
The indicator allows to plot different versions. It allows to plot the original DPO, the DRO with ZigZag lines, the DRO with detrended ZigZag lines and length labels on/off. You can turn on or off these version in the indicator settings. So you can tweak it visually to your own needs.
Logging in Pine ScriptI'm building quite a lot of pretty complicated indicators/strategies in Pine Script. Quite often they don't work from the 1 try so I have to debug them heavily.
In Pine Script there are no fancy debuggers so you have to be creative. You can plot values on your screens, check them in the data window, etc.
If you want to display some textual information, you can plot some info as labels on the screen.
It's not the most convenient way, so with the appearance of tables in Pine Script, I decided to implement a custom logger that will allow me to track some useful information about my indicator over time.
Tables work much better for this kind of thing than labels. They're attached to your screen, you can nicely scale them and you can style them much better.
The idea behind it is very simple. I used few arrays to store the message, bar number, timestamp, and type of the message (you can color messages depend on the type for example).
There is a function log_msg that just append new messages to these arrays.
In the end, for the last bar, I create the table and display the last X messages in it.
In parameters, you can show/hide the entire journal, change the number of messages displayed and choose an offset. With offset, you can basically scroll through the history of messages.
Currently, I implemented 3 types of messages, and I color messages according to these types:
Message - gray
Warning - yellow
Error - red
Of course, it's a pretty simple example, you can create a much fancier way of styling your logs.
What do you think about it? Is it useful for you? What do you use to debug code in Pine Script?
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Technical Ratings on Multi-frames / Assets█ OVERVIEW
This indicator is a modified version of TECHNICAL RATING v1.0 available in the public library to provide a quick overview of consolidated technical ratings performed on 12 assets in 3 timeframes.The purpose of the indicator is to provide a quick overview of the current status of the custom 12 (24) assets and to help focus on the appropriate asset.
█ MODIFICATIONS
- Markers, visualizations and alerts have been deleted
- Due to the limitation on maximum number of security (40), the results of 12 assets evaluated in 3 different time frames can be shown at the same time.
- An additional 12 assets can be configured in the settings so that you do not have to choose each ticker one by one to facilitate a quick change, but can switch between the 12 -12 assets with a single click on "Second sets?".
- The position, colors and parameters of the table can be widely customized in the settings.
- The 12 assets can be arranged in rows 3, 4, 6 and 12 with Table Rows options, which can also be used to create a simple mobile view.
- The default gradient color setting has been changed to red/yellow/green traffic lights
ORIGINAL DESCRIPTION ABOUT TECHNICAL RATING v1.0
█ OVERVIEW
This indicator calculates TradingView's well-known "Strong Buy", "Buy", "Neutral", "Sell" or "Strong Sell" states using the aggregate biases of 26 different technical indicators.
█ WARNING
This version is similar, but not identical, to our recently published "Technical Ratings" built-in, which reproduces our "Technicals" ratings displayed as a gauge in the right panel of charts, or in the "Rating" indicator available in the TradingView Screener. This is a fork and refactoring of the code base used in the "Technical Ratings" built-in. Its calculations will not always match those of the built-in, but it provides options not available in the built-in. Up to you to decide which one you prefer to use.
█ FEATURES
Differences with the built-in version
• The built-in version produces values matching the states displayed in the "Technicals" ratings gauge; this one does not always.
• A strategy version is also available as a built-in; this script is an indicator—not a strategy.
• This indicator will show a slightly different vertical scale, as it does not use a fixed scale like the built-in.
• This version allows control over repainting of the signal when you do not use a higher timeframe. Higher timeframe (HTF) information from this version does not repaint.
• You can adjust the weight of the Oscillators and MAs components of the rating here.
• You can configure markers on signal breaches of configurable levels, or on advances declines of the signal.
The indicator's settings allow you to:
• Choose the timeframe you want calculations to be made on.
• When not using a HTF, you can select a repainting or non-repainting signal.
• When using both MAs and Oscillators groups to calculate the rating, you can vary the weight of each group in the calculation. The default is 50/50.
Because the MAs group uses longer periods for some of its components, its value is not as jumpy as the Oscillators value.
Increasing the weight of the MAs group will thus have a calming effect on the signal.
• Alerts can be created on the indicator using the conditions configured to control the display of markers.
Display
The calculated rating is displayed as columns, but you can change the style in the inputs. The color of the signal can be one of three colors: bull, bear, or neutral. You can choose from a few presets, or check one and edit its color. The color is determined from the rating's value. Between 0.1 and -0.1 it is in the neutral color. Above/below 0.1/-0.1 it will appear in the bull/bear color. The intensity of the bull/bear color is determined by cumulative advances/declines in the rating. It is capped to 5, so there are five intensities for each of the bull/bear colors.
The "Strong Buy", "Buy", "Neutral", "Sell" or "Strong Sell" state of the last calculated value is displayed to the right of the last bar for each of the three groups: All, MAs and Oscillators. The first value always reflects your selection in the "Rating uses" field and is the one used to display the signal. A "Strong Buy" or "Strong Sell" state appears when the signal is above/below the 0.5/-0.5 level. A "Buy" or "Sell" state appears when the signal is above/below the 0.1/-0.1 level. The "Neutral" state appears when the signal is between 0.1 and -0.1 inclusively.
Five levels are always displayed: 0.5 and 0.1 in the bull color, zero in the neutral color, and -0.1 and - 0.5 in the bull color.
█ CALCULATIONS
The indicator calculates the aggregate value of two groups of indicators: moving averages and oscillators.
The "MAs" group is comprised of 15 different components:
• Six Simple Moving Averages of periods 10, 20, 30, 50, 100 and 200
• Six Exponential Moving Averages of the same periods
• A Hull Moving Average of period 9
• A Volume-weighed Moving Average of period 20
• Ichimoku
The "Oscillators" group includes 11 components:
• RSI
• Stochastic
• CCI
• ADX
• Awesome Oscillator
• Momentum
• MACD
• Stochastic RSI
• Wiliams %R
• Bull Bear Power
• Ultimate Oscillator
3D Wave-PMThe Wave-PM (Whistler Active Volatility Energy - Price Mass) indicator is an oscillator described in Mark Whistler's book 'Volatility Illuminated'.
The Wave-PM was specifically designed to help read cycles of volatility. When visualizing volatility cycles as a heatmap we can get a clear overview of market volatility phases on multiple timeframes, and more importantly as traders give us insight into 'potential' volatility from to pent up energy signaled by the blue and green plumes which invariably give way to big moves signaled by the orange and red plumes.
This indicator can be quite GPU intensive, so simple and also line based visualization methods are included. Also, its free and open source so go ahead and hack it to your hearts content. Enjoy!
Swing High/Low Anchored SpiralFit the estimate of an Archimedean spiral to the price, with a central point determined by swing high/lows.
Users can determine which historical swing high/low to use as the spiral central point and can choose the number of turns it should make.
You can create cool shapes, cool enough to satisfy your apophenia needs.
If you are having issues just hide and unhide the script, or just lower the length/occurrence setting.
Posting is impossible without the support of my Patreons as well as @LuxAlgo, my scripts are dedicated to them.
Quality ScreenAn attempt to show fundamental stats which describes quality of the stock. Following parameters are depicted:
SOLVENCY
DEBT_TO_EQUITY
Very Good : 0 - 1
Good : 1 - 2
High risk : > 2
DEBT_TO_ASSET
Very Good : < 0.4
Good : 0.4 - 0.6
High Risk : > 0.6
LONG_TERM_DEBT_TO_ASSETS
Very Good : < 0.4
Good : 0.4 - 0.6
High Risk : > 0.6
ALTMAN_Z_SCORE
Very good: > 3
Good : 1.8 - 3
High Risk : < 1.8
SPRINGATE_SCORE
High Risk : < 0.862
LIQUIDITY
CURRENT_RATIO
Very Good : 1.2 - 2
Good : 2+ (Too high and Inefficient)
High Risk : < 1
QUICK_RATIO
Very Good : 1 - 2
Good : 2+ (Too high and Inefficient)
High Risk : < 0.9
SLOAN_RATIO
Very Good: -10% to +10%
Good : -25% to -10% or +10% to +25%
High Risk: < -25% or > +25%
PROFITABILITY
RETURN_ON_ASSETS
Healthy : > 5%
Great : > 20%
RETURN_ON_EQUITY
Healthy : 10%
Great : > 40%
RETURN_ON_INVESTED_CAPITAL
Healthy : > 2%
Great : > 10%
Adapting a built-in [PineCoders]█ OVERVIEW
This Pine script shows how it can be quite simple to personalize a built-in indicator for your needs.
█ OUR SCRIPT
Our objective was to add the current values for volume and its moving average in prominent view, and use brighter colors than the built-in.
We started with the source code from the "Volume" built-in indicator. You can access the source code of many built-ins from the Pine Editor by clicking the "Open" button and choosing "New default built-in script..."
We changed the variable names so they conform to our Coding Conventions . Everybody is of course free to code their scripts the way they want; the conventions provide guidelines for those interested in Pine-specific recommendations. We use our conventions to make our code more readable, which helps readers of open-source publications. As Uncle Bob, a.k.a. Robert Cecil Martin, argues in his "Clean Code" book, code that is easier to read is also useful for its first user: you.
We assigned the colors we use to constants because they are used in multiple places in the script. If we decide to change them, we only need to change the constant definitions for the change to trickle down to the rest of the code.
We used the `inline` and `tooltip` parameters of input() to better organize our inputs and provide extra information under an "i" icon when needed.
We wanted to pack more information in the display of the moving average and volume than just the values, so we color-coded their background:
• When the MA is rising, the background of its table cell is in the bull color, otherwise it's in the bear color. The period used for the MA is also displayed in that cell's legend.
• When the current volume's value is higher/lower than its MA, the background of its cell is of bull/bear color.
We use a Pine table to display our values. We use extra cells to provide a configurable margin to the left, and a small space between the two values.
Because we only use constant colors in this script (i.e., values that are known at compile time), users can change the colors in the "Setting/Style" tab's color widgets. Users of the script can also use the tab to change other attributes of the plots.
Look first. Then leap.
WatermarkLook in the lower-left corner of this chart. If you load the script on your chart, you will see how the watermark animates. You can personalize it in the script's "Settings/Inputs" tab to use it in your chart snapshots.
Do keep in mind that if you use it when publishing ideas, videos or scripts, House Rules prohibit advertising on your chart.
For Pine coders
This script uses our new table feature in Pine to position a watermark on the chart, and the new varip type of variable to animate it.
Look first. Then leap.
Chart OscillatorI present you the chart oscillator where an oscillator (Stoch or RSI) is plotted
on the chart itself (instead of below the chart)
It is inspired on an idea of @Kablamicus
Instead of having the lines between 0 and 100, here the '0-100' are
- lowest(low, len)
- highest(high, len)
An overbought/oversold and a middle line is derived from these lines
and the oscillator goes in between.
It resembles very much the 'normal' oscillator, with a few extra's:
- you can see the movement of the candles against the oscillator
- S/R levels of oscillator, 50 line, overbought/oversold line, 0-100 line
Stoch:
RSI:
Also a table is included with the Stoch/RSI values
Cheers!