Ensemble Alerts█ OVERVIEW
This indicator creates highly customizable alert conditions and messages by combining several technical conditions into groups , which users can specify directly from the "Settings/Inputs" tab. It offers a flexible framework for building and testing complex alert conditions without requiring code modifications for each adjustment.
█ CONCEPTS
Ensemble analysis
Ensemble analysis is a form of data analysis that combines several "weaker" models to produce a potentially more robust model. In a trading context, one of the most prevalent forms of ensemble analysis is the aggregation (grouping) of several indicators to derive market insights and reinforce trading decisions. With this analysis, traders typically inspect multiple indicators, signaling trade actions when specific conditions or groups of conditions align.
Simplifying ensemble creation
Combining indicators into one or more ensembles can be challenging, especially for users without programming knowledge. It usually involves writing custom scripts to aggregate the indicators and trigger trading alerts based on the confluence of specific conditions. Making such scripts customizable via inputs poses an additional challenge, as it often involves complicated input menus and conditional logic.
This indicator addresses these challenges by providing a simple, flexible input menu where users can easily define alert criteria by listing groups of conditions from various technical indicators in simple text boxes . With this script, you can create complex alert conditions intuitively from the "Settings/Inputs" tab without ever writing or modifying a single line of code. This framework makes advanced alert setups more accessible to non-coders. Additionally, it can help Pine programmers save time and effort when testing various condition combinations.
█ FEATURES
Configurable alert direction
The "Direction" dropdown at the top of the "Settings/Inputs" tab specifies the allowed direction for the alert conditions. There are four possible options:
• Up only : The indicator only evaluates upward conditions.
• Down only : The indicator only evaluates downward conditions.
• Up and down (default): The indicator evaluates upward and downward conditions, creating alert triggers for both.
• Alternating : The indicator prevents alert triggers for consecutive conditions in the same direction. An upward condition must be the first occurrence after a downward condition to trigger an alert, and vice versa for downward conditions.
Flexible condition groups
This script features six text inputs where users can define distinct condition groups (ensembles) for their alerts. An alert trigger occurs if all the conditions in at least one group occur.
Each input accepts a comma-separated list of numbers with optional spaces (e.g., "1, 4, 8"). Each listed number, from 1 to 35, corresponds to a specific individual condition. Below are the conditions that the numbers represent:
1 — RSI above/below threshold
2 — RSI below/above threshold
3 — Stoch above/below threshold
4 — Stoch below/above threshold
5 — Stoch K over/under D
6 — Stoch K under/over D
7 — AO above/below threshold
8 — AO below/above threshold
9 — AO rising/falling
10 — AO falling/rising
11 — Supertrend up/down
12 — Supertrend down/up
13 — Close above/below MA
14 — Close below/above MA
15 — Close above/below open
16 — Close below/above open
17 — Close increase/decrease
18 — Close decrease/increase
19 — Close near Donchian top/bottom (Close > (Mid + HH) / 2)
20 — Close near Donchian bottom/top (Close < (Mid + LL) / 2)
21 — New Donchian high/low
22 — New Donchian low/high
23 — Rising volume
24 — Falling volume
25 — Volume above average (Volume > SMA(Volume, 20))
26 — Volume below average (Volume < SMA(Volume, 20))
27 — High body to range ratio (Abs(Close - Open) / (High - Low) > 0.5)
28 — Low body to range ratio (Abs(Close - Open) / (High - Low) < 0.5)
29 — High relative volatility (ATR(7) > ATR(40))
30 — Low relative volatility (ATR(7) < ATR(40))
31 — External condition 1
32 — External condition 2
33 — External condition 3
34 — External condition 4
35 — External condition 5
These constituent conditions fall into three distinct categories:
• Directional pairs : The numbers 1-22 correspond to pairs of opposing upward and downward conditions. For example, if one of the inputs includes "1" in the comma-separated list, that group uses the "RSI above/below threshold" condition pair. In this case, the RSI must be above a high threshold for the group to trigger an upward alert, and the RSI must be below a defined low threshold to trigger a downward alert.
• Non-directional filters : The numbers 23-30 correspond to conditions that do not represent directional information. These conditions act as filters for both upward and downward alerts. Traders often use non-directional conditions to refine trending or mean reversion signals. For instance, if one of the input lists includes "30", that group uses the "Low relative volatility" condition. The group can trigger an upward or downward alert only if the 7-period Average True Range (ATR) is below the 40-period ATR.
• External conditions : The numbers 31-35 correspond to external conditions based on the plots from other indicators on the chart. To set these conditions, use the source inputs in the "External conditions" section near the bottom of the "Settings/Inputs" tab. The external value can represent an upward, downward, or non-directional condition based on the following logic:
▫ Any value above 0 represents an upward condition.
▫ Any value below 0 represents a downward condition.
▫ If the checkbox next to the source input is selected, the condition becomes non-directional . Any group that uses the condition can trigger upward or downward alerts only if the source value is not 0.
To learn more about using plotted values from other indicators, see this article in our Help Center and the Source input section of our Pine Script™ User Manual.
Group markers
Each comma-separated list represents a distinct group , where all the listed conditions must occur to trigger an alert. This script assigns preset markers (names) to each condition group to make the active ensembles easily identifiable in the generated alert messages and labels. The markers assigned to each group use the format "M", where "M" is short for "Marker" and "x" is the group number. The titles of the inputs at the top of the "Settings/Inputs" tab show these markers for convenience.
For upward conditions, the labels and alert messages show group markers with upward triangles (e.g., "M1▲"). For downward conditions, they show markers with downward triangles (e.g., "M1▼").
NOTE: By default, this script populates the "M1" field with a pre-configured list for a mean reversion group ("2,18,24,28"). The other fields are empty. If any "M*" input does not contain a value, the indicator ignores it in the alert calculations.
Custom alert messages
By default, the indicator's alert message text contains the activated markers and their direction as a comma-separated list. Users can override this message for upward or downward alerts with the two text fields at the bottom of the "Settings/Inputs" tab. When the fields are not empty , the alerts use that text instead of the default marker list.
NOTE: This script generates alert triggers, not the alerts themselves. To set up an alert based on this script's conditions, open the "Create Alert" dialog box, then select the "Ensemble Alerts" and "Any alert() function call" options in the "Condition" tabs. See the Alerts FAQ in our Pine Script™ User Manual for more information.
Condition visualization
This script offers organized visualizations of its conditions, allowing users to inspect the behaviors of each condition alongside the specified groups. The key visual features include:
1) Conditional plots
• The indicator plots the history of each individual condition, excluding the external conditions, as circles at different levels. Opposite conditions appear at positive and negative levels with the same absolute value. The plots for each condition show values only on the bars where they occur.
• Each condition's plot is color-coded based on its type. Aqua and orange plots represent opposing directional conditions, and purple plots represent non-directional conditions. The titles of the plots also contain the condition numbers to which they apply.
• The plots in the separate pane can be turned on or off with the "Show plots in pane" checkbox near the top of the "Settings/Inputs" tab. This input only toggles the color-coded circles, which reduces the graphical load. If you deactivate these visuals, you can still inspect each condition from the script's status line and the Data Window.
• As a bonus, the indicator includes "Up alert" and "Down alert" plots in the Data Window, representing the combined upward and downward ensemble alert conditions. These plots are also usable in additional indicator-on-indicator calculations.
2) Dynamic labels
• The indicator draws a label on the main chart pane displaying the activated group markers (e.g., "M1▲") each time an alert condition occurs.
• The labels for upward alerts appear below chart bars. The labels for downward alerts appear above the bars.
NOTE: This indicator can display up to 500 labels because that is the maximum allowed for a single Pine script.
3) Background highlighting
• The indicator can highlight the main chart's background on bars where upward or downward condition groups activate. Use the "Highlight background" inputs in the "Settings/Inputs" tab to enable these highlights and customize their colors.
• Unlike the dynamic labels, these background highlights are available for all chart bars, irrespective of the number of condition occurrences.
█ NOTES
• This script uses Pine Script™ v6, the latest version of TradingView's programming language. See the Release notes and Migration guide to learn what's new in v6 and how to convert your scripts to this version.
• This script imports our new Alerts library, which features functions that provide high-level simplicity for working with complex compound conditions and alerts. We used the library's `compoundAlertMessage()` function in this indicator. It evaluates items from "bool" arrays in groups specified by an array of strings containing comma-separated index lists , returning a tuple of "string" values containing the marker of each activated group.
• The script imports the latest version of the ta library to calculate several technical indicators not included in the built-in `ta.*` namespace, including Double Exponential Moving Average (DEMA), Triple Exponential Moving Average (TEMA), Fractal Adaptive Moving Average (FRAMA), Tilson T3, Awesome Oscillator (AO), Full Stochastic (%K and %D), SuperTrend, and Donchian Channels.
• The script uses the `force_overlay` parameter in the label.new() and bgcolor() calls to display the drawings and background colors in the main chart pane.
• The plots and hlines use the available `display.*` constants to determine whether the visuals appear in the separate pane.
Look first. Then leap.
Conditions
Alerts█ OVERVIEW
This library is a Pine Script™ programmers tool that provides functions to simplify the creation of compound conditions and alert messages. With these functions, scripts can use comma-separated "string" lists to specify condition groups from arbitrarily large "bool" arrays , offering a convenient way to provide highly flexible alert creation to script users without requiring numerous inputs in the "Settings/Inputs" menu.
█ CONCEPTS
Compound conditions
Compound conditions are essentially groups of two or more conditions, where each required condition must occur to produce a `true` result. Traders often combine conditions, including signals from various indicators, to drive and reinforce trade decisions. Similarly, programmers use compound conditions in logical operations to create scripts that respond dynamically to groups of events.
Condition conundrum
Providing flexible condition combinations to script users for signals and alerts often poses a significant challenge: input complexity . Conventionally, such flexibility comes at the cost of an extensive list of separate inputs for toggling individual conditions and customizing their properties, often resulting in complicated input menus that are difficult for users to navigate effectively. Furthermore, managing all those inputs usually entails tediously handling many extra variables and logical expressions, making such projects more complex for programmers.
Condensing complexity
This library introduces a technique using parsed strings to reference groups of elements from "bool" arrays , helping to simplify and streamline the construction of compound conditions and alert messages. With this approach, programmers can provide one or more "string" inputs in their scripts where users can list numbers corresponding to the conditions they want to combine.
For example, suppose you have a script that creates alert triggers based on a combination of up to 20 individual conditions, and you want to make inputs for users to choose which conditions to combine. Instead of creating 20 separate checkboxes in the "Settings/Inputs" tab and manually adding associated logic for each one, you can store the conditional values in arrays, make one or more "string" inputs that accept values listing the array item locations (e.g., "1,4,8,11"), and then pass the inputs to these functions to determine the compound conditions formed by the specified groups.
This approach condenses the input space, improving navigability and utility. Additionally, it helps provide high-level simplicity to complex conditional code, making it easier to maintain and expand over time.
█ CALCULATIONS AND USE
This library contains three functions for evaluating compound conditions: `getCompoundConditon()`, `getCompoundConditionsArray()`, and `compoundAlertMessage()`. Each function has two overloads that evaluate compound conditions based on groups of items from one or two "bool" arrays . The sections below explain the functions' calculations and how to use them.
Referencing conditions using "string" index lists
Each function processes "string" values containing comma-separated lists of numerals representing the indices of the "bool" array items to use in its calculations (e.g., "4, 8, 12"). The functions split each supplied "string" list by its commas, then iterate over those specified indices in the "bool" arrays to determine each group's combined `true` or `false` state.
For convenience, the numbers in the "string" lists can represent zero-based indices (where the first item is at index 0) or one-based indices (where the first item is at index 1), depending on the function's `zeroIndex` parameter. For example, an index list of "0, 2, 4" with a `zeroIndex` value of `true` specifies that the condition group uses the first , third , and fifth "bool" values in the array, ignoring all others. If the `zeroIndex` value is `false`, the list "1, 3, 5" also refers to those same elements.
Zero-based indexing is convenient for programmers because Pine arrays always use this index format. However, one-based indexing is often more convenient and familiar for script users, especially non-programmers.
Evaluating one or many condition groups
The `getCompoundCondition()` function evaluates singular condition groups determined by its `indexList` parameter, returning `true` values whenever the specified array elements are `true`. This function is helpful when a script has to evaluate specific groups of conditions and does not require many combinations.
In contrast, the `getCompoundConditionsArray()` function can evaluate numerous condition groups, one for each "string" included in its `indexLists` argument. It returns arrays containing `true` or `false` states for each listed group. This function is helpful when a script requires multiple condition combinations in additional calculations or logic.
The `compoundAlertMessage()` function is similar to the `getCompoundConditionsArray()` function. It also evaluates a separate compound condition group for each "string" in its `indexLists` array, but it returns "string" values containing the marker (name) of each group with a `true` result. You can use these returned values as the `message` argument in alert() calls, display them in labels and other drawing objects, or even use them in additional calculations and logic.
Directional condition pairs
The first overload of each function operates on a single `conditions` array, returning values representing one or more compound conditions from groups in that array. These functions are ideal for general-purpose condition groups that may or may not represent direction information.
The second overloads accept two arrays representing upward and downward conditions separately: `upConditions` and `downConditions`. These overloads evaluate opposing directional conditions in pairs (e.g., RSI is above/below a level) and return upward and downward condition information separately in a tuple .
When using the directional overloads, ensure the `upConditions` and `downConditions` arrays are the same size, with the intended condition pairs at the same indices . For instance, if you have a specific upward RSI condition's value at the first index in the `upConditions` array, include the opposing downward RSI condition's value at that same index in the `downConditions` array. If a condition can apply to both directions (e.g., rising volume), include its value at the same index in both arrays.
Group markers
To simplify the generation of informative alert messages, the `compoundAlertMessage()` function assigns "string" markers to each condition group, where "marker" refers to the group's name. The `groupMarkers` parameter allows you to assign custom markers to each listed group. If not specified, the function generates default group markers in the format "M", where "M" is short for "Marker" and "" represents the group number starting from 1. For example, the default marker for the first group specified in the `indexLists` array is "M1".
The function's returned "string" values contain a comma-separated list with markers for each activated condition group (e.g., "M1, M4"). The function's second overload, which processes directional pairs of conditions, also appends extra characters to the markers to signify the direction. The default for upward groups is "▲" (e.g., "M1▲") and the default for downward ones is "▼" (e.g., "M1▼"). You can customize these appended characters with the `upChar` and `downChar` parameters.
Designing customizable alerts
We recommend following these primary steps when using this library to design flexible alerts for script users:
1. Create text inputs for users to specify comma-separated lists of conditions with the input.string() or input.text_area() functions, and then collect all the input values in a "string" array . Note that each separate "string" in the array will represent a distinct condition group.
2. Create arrays of "bool" values representing the possible conditions to choose from. If your script will process pairs of upward and downward conditions, ensure the related elements in the arrays align at the same indices.
3. Call `compoundAlertMessage()` using the arrays from steps 1 and 2 as arguments to get the alert message text. If your script will use the text for alerts only, not historical display or calculation purposes, the call is necessary only on realtime bars .
4. Pass the calculated "string" values as the `message` argument in alert() calls. We recommend calling the function only when the "string" is not empty (i.e., `messageText != ""`). To avoid repainting alerts on open bars, use barstate.isconfirmed in the condition to allow alert triggers only on each bar's close .
5. Test the alerts. Open the "Create Alert" dialog box and select "Any alert() function call" in the "Condition" field. It is also helpful to inspect the strings with Pine Logs .
NOTE: Because the techniques in this library use lists of numbers to specify conditions, we recommend including a tooltip for the "string" inputs that lists the available numbers and the conditions they represent. This tooltip provides a legend for script users, making it simple to understand and utilize. To create the tooltip, declare a "const string" listing the options and pass it to the `input.*()` call's `tooltip` parameter. See the library's example code for a simple demonstration.
█ EXAMPLE CODE
This library's example code demonstrates one possible way to offer a selection of compound conditions with "string" inputs and these functions. It uses three input.string() calls, each accepting a comma-separated list representing a distinct condition group. The title of each input represents the default group marker that appears in the label and alert text. The code collects these three input values in a `conditionGroups` array for use with the `compoundAlertMessage()` function.
In this code, we created two "bool" arrays to store six arbitrary condition pairs for demonstration:
1. Bar up/down: The bar's close price must be above the open price for upward conditions, and vice versa for downward conditions.
2. Fast EMA above/below slow EMA : The 9-period Exponential Moving Average of close prices must be above the 21-period EMA for upward conditions, and vice versa for downward conditions.
3. Volume above average : The bar's volume must exceed its 20-bar average to activate an upward or downward condition.
4. Volume rising : The volume must exceed that of the previous bar to activate an upward or downward condition.
5. RSI trending up/down : The 14-period Relative Strength Index of close prices must be between 50 and 70 for upward conditions, and between 30 and 50 for downward conditions.
6. High volatility : The 7-period Average True Range (ATR) must be above the 40-period ATR to activate an upward or downward condition.
We included a `tooltip` argument for the third input.string() call that displays the condition numbers and titles, where 1 is the first condition number.
The `bullConditions` array contains the `true` or `false` states of all individual upward conditions, and the `bearConditions` array contains all downward condition states. For the conditions that filter either direction because they are non-directional, such as "High volatility", both arrays contain the condition's `true` or `false` value at the same index. If you use these conditions alone, they activate upward and downward alert conditions simultaneously.
The example code calls `compoundAlertMessage()` using the `bullConditions`, `bearConditions`, and `conditionGroups` arrays to create a tuple of strings containing the directional markers for each activated group. On confirmed bars, it displays non-empty strings in labels and uses them in alert() calls. For the text shown in the labels, we used str.replace_all() to replace commas with newline characters, aligning the markers vertically in the display.
Look first. Then leap.
█ FUNCTIONS
This library exports the following functions:
getCompoundCondition(conditions, indexList, minRequired, zeroIndex)
(Overload 1 of 2) Determines a compound condition based on selected elements from a `conditions` array.
Parameters:
conditions (array) : (array) An array containing the possible "bool" values to use in the compound condition.
indexList (string) : (series string) A "string" containing a comma-separated list of whole numbers representing the group of `conditions` elements to use in the compound condition. For example, if the value is `"0, 2, 4"`, and `minRequired` is `na`, the function returns `true` only if the `conditions` elements at index 0, 2, and 4 are all `true`. If the value is an empty "string", the function returns `false`.
minRequired (int) : (series int) Optional. Determines the minimum number of selected conditions required to activate the compound condition. For example, if the value is 2, the function returns `true` if at least two of the specified `conditions` elements are `true`. If the value is `na`, the function returns `true` only if all specified elements are `true`. The default is `na`.
zeroIndex (bool) : (series bool) Optional. Specifies whether the `indexList` represents zero-based array indices. If `true`, a value of "0" in the list represents the first array index. If `false`, a `value` of "1" represents the first index. The default is `true`.
Returns: (bool) `true` if `conditions` elements in the group specified by the `indexList` are `true`, `false` otherwise.
getCompoundCondition(upConditions, downConditions, indexList, minRequired, allowUp, allowDown, zeroIndex)
(Overload 2 of 2) Determines upward and downward compound conditions based on selected elements from `upConditions` and `downConditions` arrays.
Parameters:
upConditions (array) : (array) An array containing the possible "bool" values to use in the upward compound condition.
downConditions (array) : (array) An array containing the possible "bool" values to use in the downward compound condition.
indexList (string) : (series string) A "string" containing a comma-separated list of whole numbers representing the `upConditions` and `downConditions` elements to use in the compound conditions. For example, if the value is `"0, 2, 4"` and `minRequired` is `na`, the function returns `true` for the first value only if the `upConditions` elements at index 0, 2, and 4 are all `true`. If the value is an empty "string", the function returns ` `.
minRequired (int) : (series int) Optional. Determines the minimum number of selected conditions required to activate either compound condition. For example, if the value is 2, the function returns `true` for its first value if at least two of the specified `upConditions` elements are `true`. If the value is `na`, the function returns `true` only if all specified elements are `true`. The default is `na`.
allowUp (bool) : (series bool) Optional. Controls whether the function considers upward compound conditions. If `false`, the function ignores the `upConditions` array, and the first item in the returned tuple is `false`. The default is `true`.
allowDown (bool) : (series bool) Optional. Controls whether the function considers downward compound conditions. If `false`, the function ignores the `downConditions` array, and the second item in the returned tuple is `false`. The default is `true`.
zeroIndex (bool) : (series bool) Optional. Specifies whether the `indexList` represents zero-based array indices. If `true`, a value of "0" in the list represents the first array index. If `false`, a value of "1" represents the first index. The default is `true`.
Returns: ( ) A tuple containing two "bool" values representing the upward and downward compound condition states, respectively.
getCompoundConditionsArray(conditions, indexLists, zeroIndex)
(Overload 1 of 2) Creates an array of "bool" values representing compound conditions formed by selected elements from a `conditions` array.
Parameters:
conditions (array) : (array) An array containing the possible "bool" values to use in each compound condition.
indexLists (array) : (array) An array of strings containing comma-separated lists of whole numbers representing the `conditions` elements to use in each compound condition. For example, if an item is `"0, 2, 4"`, the corresponding item in the returned array is `true` only if the `conditions` elements at index 0, 2, and 4 are all `true`. If an item is an empty "string", the item in the returned array is `false`.
zeroIndex (bool) : (series bool) Optional. Specifies whether the "string" lists in the `indexLists` represent zero-based array indices. If `true`, a value of "0" in a list represents the first array index. If `false`, a value of "1" represents the first index. The default is `true`.
Returns: (array) An array of "bool" values representing compound condition states for each condition group. An item in the array is `true` only if all the `conditions` elements specified by the corresponding `indexLists` item are `true`. Otherwise, the item is `false`.
getCompoundConditionsArray(upConditions, downConditions, indexLists, allowUp, allowDown, zeroIndex)
(Overload 2 of 2) Creates two arrays of "bool" values representing compound upward and
downward conditions formed by selected elements from `upConditions` and `downConditions` arrays.
Parameters:
upConditions (array) : (array) An array containing the possible "bool" values to use in each upward compound condition.
downConditions (array) : (array) An array containing the possible "bool" values to use in each downward compound condition.
indexLists (array) : (array) An array of strings containing comma-separated lists of whole numbers representing the `upConditions` and `downConditions` elements to use in each compound condition. For example, if an item is `"0, 2, 4"`, the corresponding item in the first returned array is `true` only if the `upConditions` elements at index 0, 2, and 4 are all `true`. If an item is an empty "string", the items in both returned arrays are `false`.
allowUp (bool) : (series bool) Optional. Controls whether the function considers upward compound conditions. If `false`, the function ignores the `upConditions` array, and all elements in the first returned array are `false`. The default is `true`.
allowDown (bool) : (series bool) Optional. Controls whether the function considers downward compound conditions. If `false`, the function ignores the `downConditions` array, and all elements in the second returned array are `false`. The default is `true`.
zeroIndex (bool) : (series bool) Optional. Specifies whether the "string" lists in the `indexLists` represent zero-based array indices. If `true`, a value of "0" in a list represents the first array index. If `false`, a value of "1" represents the first index. The default is `true`.
Returns: ( ) A tuple containing two "bool" arrays:
- The first array contains values representing upward compound condition states determined using the `upConditions`.
- The second array contains values representing downward compound condition states determined using the `downConditions`.
compoundAlertMessage(conditions, indexLists, zeroIndex, groupMarkers)
(Overload 1 of 2) Creates a "string" message containing a comma-separated list of markers representing active compound conditions formed by specified element groups from a `conditions` array.
Parameters:
conditions (array) : (array) An array containing the possible "bool" values to use in each compound condition.
indexLists (array) : (array) An array of strings containing comma-separated lists of whole numbers representing the `conditions` elements to use in each compound condition. For example, if an item is `"0, 2, 4"`, the corresponding marker for that item appears in the returned "string" only if the `conditions` elements at index 0, 2, and 4 are all `true`.
zeroIndex (bool) : (series bool) Optional. Specifies whether the "string" lists in the `indexLists` represent zero-based array indices. If `true`, a value of "0" in a list represents the first array index. If `false`, a value of "1" represents the first index. The default is `true`.
groupMarkers (array) : (array) Optional. If specified, sets the marker (name) for each condition group specified in the `indexLists` array. If `na`, the function uses the format `"M"` for each group, where "M" is short for "Marker" and `` represents the one-based index for the group (e.g., the marker for the first listed group is "M1"). The default is `na`.
Returns: (string) A "string" containing a list of markers corresponding to each active compound condition.
compoundAlertMessage(upConditions, downConditions, indexLists, allowUp, allowDown, zeroIndex, groupMarkers, upChar, downChar)
(Overload 2 of 2) Creates two "string" messages containing comma-separated lists of markers representing active upward and downward compound conditions formed by specified element groups from `upConditions` and `downConditions` arrays.
Parameters:
upConditions (array) An array containing the possible "bool" values to use in each upward compound condition.
downConditions (array) An array containing the possible "bool" values to use in each downward compound condition.
indexLists (array) An array of strings containing comma-separated lists of whole numbers representing the `upConditions` and `downConditions` element groups to use in each compound condition. For example, if an item is `"0, 2, 4"`, the corresponding group marker for that item appears in the first returned "string" only if the `upConditions` elements at index 0, 2, and 4 are all `true`.
allowUp (bool) Optional. Controls whether the function considers upward compound conditions. If `false`, the function ignores the `upConditions` array and returns an empty "string" for the first tuple element. The default is `true`.
allowDown (bool) Optional. Controls whether the function considers downward compound conditions. If `false`, the function ignores the `downConditions` array and returns an empty "string" for the second tuple element. The default is `true`.
zeroIndex (bool) Optional. Specifies whether the "string" lists in the `indexLists` represent zero-based array indices. If `true`, a value of "0" in a list represents the first array index. If `false`, a value of "1" represents the first index. The default is `true`.
groupMarkers (array) Optional. If specified, sets the name (marker) of each condition group specified in the `indexLists` array. If `na`, the function uses the format `"M"` for each group, where "M" is short for "Marker" and `` represents the one-based index for the group (e.g., the marker for the first listed group is "M1"). The default is `na`.
upChar (string) Optional. A "string" appended to all group markers for upward conditions to signify direction. The default is "▲".
downChar (string) Optional. A "string" appended to all group markers for downward conditions to signify direction. The default is "▼".
Returns: ( ): A tuple of "string" values containing lists of markers corresponding to active upward and downward compound conditions, respectively.
Multi conditions matricesLibrary "multi_conditions_matrices"
: facilitate including multiple AND / OR conditions to a script such as two entry / exit inputs groups.
method addConditions(conditions, conditionPair)
Helper to append conditions to a matrix condition array
Namespace types: matrix
Parameters:
conditions (matrix)
conditionPair (array) : array A condition pair , an input can be passed directly to enable
method check(conditions, operatorAnd)
check several condition within given operator
Namespace types: matrix
Parameters:
conditions (matrix)
operatorAnd (bool) : bool true if the operator between condition is AND (default OR)
Returns: bool Evaluates conditions
isWeekend()
isNightSignal(nightHour, morningHour, timezone)
Parameters:
nightHour (int)
morningHour (int)
timezone (string)
Threshold counterOVERVIEW
The "Threshold Counter" is a tool for quantifying occurrences of closing prices of an asset that align with specified criteria and is a flexible and visual approach to studying price action.
A user-definable target threshold can be set and a comparator (<, =, >, and so on) can be selected. The indicator counts values on the main chart meeting these conditions, over a user-defined `lookback` period.
KEY FEATURES
User definable threshold: target value with optional upper bound can be specified
Versatile Comparisons: Choose from "=", ">=", ">", "<=", "<", "between", and "between (inclusive)" for diverse analysis.
Historical Analysis: Assess occurrences over a customisable period.
Visual Representation: Displays instances graphically on the chart with customisable colours.
Summary: Provides a summary label for a quick understanding of the analysed data.
USE-CASES
Pattern Recognition: Identify patterns or trends based on user-defined price criteria.
Threshold Analysis: Quantify occurrences of prices crossing or staying within a specified range.
Strategy Testing: Evaluate historical performance of strategies relying on specific price conditions.
Behavioural Insights: Gain insights into price behaviour by counting occurrences of interest.
The "Threshold Counter" indicator offers a flexible and visual approach to studying price action, which may aid in making decisions based on historical data.
IMPORTANT CONSIDERATIONS
Period selection: The effectiveness of the analysis may be influenced by the choice of the lookback period. Consider an appropriate duration based on the strategy or pattern being analysed.
Comparator Selection: Comparison operator selection will obviously affect the results. There are two range operators of `between` and `between (inclusive)`. The latter will add closing prices that exactly meet the threshold and upper bound. The former does not.
Visualisation: Interpretation of the visual representation is colour-coded.
Red is threshold condition is not met.
Green is threshold condition is met.
Aqua is outside of the lookback period.
User Discretion: This script relies on historical data and should be used with caution. Past performance is not indicative of future results.
Supplementary Analysis: Trading decisions should not rely solely on this script. Users should exercise judgment and consider market conditions.
Signal ComposerThis Signal Composer script can compose existing signals from other "Signal Indicators" into one and can forward it to the "Template Trailing Strategy".
It allows the user to combine the logic of two signals and define the conditions that will trigger the start, end, cancel start, and cancel end deals of the produced signal. A signal will be composed from those user-defined conditions.
For example, one signal indicator may have the main logic and the other the filter logic. If you want to combine more signals you may add two Signal Composer scripts and pipe the output of the first composer to the second one.
This is the "main building block" of creating a bit more complex strategies without writing any code.
The "indicator on indicator" feature is needed so you can forward the resulting signal to the "Template Trailing Strategy" so that you can set take profits, stop losses, custom alerts, and all other nifty features this framework provides.
Thus, you should be a Plus or Premium user to get its full potential. It is very convenient for those who want to create a strategy without coding their own signal indicator and for those who want to fast-prototype various ideas based on simple but composable conditions.
It can nicely be combined with the "Signal Adapter" which combines simple (non-signal) indicators and produces a signal. This is a recipe to build fast and backtest more complex strategy logic.
This approach has a fail-fast mentality! Keep, in mind that you can code a single signal indicator with your composed logic later on only if the idea turns out to be "good enough".
Signal AdapterThis Signal Adapter script can compose a signal based on inputs from other simple (non-signal) indicators and can forwards it to the "Template Trailing Strategy".
It allows the user to combine up to eight external inputs and define the conditions that will trigger the start, end, cancel start and cancel end deals.
A signal will be composed from those user-defined conditions. The "indicator on indicator" feature is needed so you can forward the resulted signal to the "Template Trailing Strategy".
Thus you should be Plus or Premium user to get it's full potential. It is very convenient for those who want to create a strategy without coding their own signal indicator and for those
who want to fast prototype various ideas based on simple conditions.
How To Limit Repeating SignalsAn example of how to limit the input number of allowed signals using a function containing a condition counter with a reset.
conditionLibrary "condition"
True/False Condition tools and toggles for booleans and utility.
suggested use is checking if a calculation is required, or can be skipped
speeding up script calculations in realtime and historical scenarios.
isonlywihtout(_first_cond, _second_cond)
output is true only if first true and second false
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isonlywih(_first_cond, _second_cond)
output is true only for the first condition if the second condition is also true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isactive(_cond)
output is true active only while actively true
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotactive(_cond)
output is true only while condition is not active
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isontoggle(_cond)
output is true and holds on True activation , na input has no effect, only a false will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isofftoggle(_cond)
output is true and holds on False activation, na input has no effect, only a true will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotboth(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isneither(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isbothtoggled(_first_cond, _second_cond)
output is true and held when both trigger true, and only disengages if both are false at once
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
Indicators Combination Framework v3 IND [DTU]Hello All,
This script is a framework to analyze and see the results by combine selected indicators for (long, short, longexit, shortexit) conditions.
I was designed this for beginners and users to facilitate to see effects of the technical indicators combinations on the chart WITH NO CODE
You can improve your strategies according the results of this system by connecting the framework to a strategy framework/template such as Pinecoder, Benson, daveatt or custom.
This is enhanced version of my previous indicator "Indicators & Conditions Test Framework "
Currently there are 93 indicators (23 newly added) connected over library. You can also import an External Indicator or add Custom indicator (In the source)
It is possible to change it from Indicator to strategy (simple one) by just remarking strategy parts in the source code and see real time profit of your combinations
Feel free to change or use it in your source
Special thanks goes to Pine wizards: Trading view (built-in Indicators), @Rodrigo, @midtownsk8rguy, @Lazybear, @Daveatt and others for their open source codes and contributions
SIMPLE USAGE
1. SETTING: Show Alerts= True (To see your entries and Exists)
2. Define your Indicators (ex: INDICATOR1: ema(close,14), INDICATOR2: ema(close,21), INDICATOR3: ema(close,200)
3. Define Your Combinations for long & Short Conditions
a. For Long: (INDICATOR1 crossover INDICATOR2) AND (INDICATOR3 < close)
b. For Short: (INDICATOR1 crossunder INDICATOR2) AND (INDICATOR3 > close)
4. Select Strategy/template (Import strategy to chart) that you export your signals from the list
5. Analyze the best profit by changing Indicators values
SOME INDICATORS DETAILS
Each Indicator includes:
- Factorization : Converting the selected indicator to Double, triple Quadruple such as EMA to DEMA, TEMA QEMA
- Log : Simple or log10 can be used for calculation on function entries
- Plot Type : You can overlay the indicator on the chart (such ema) or you can use stochastic/Percentrank approach to display in the variable hlines range
- Extended Parametes : You can use default parameters or you can use extended (P1,P2) parameters regarding to indicator type and your choice
- Color : You can define indicator color and line properties
- Smooth : you can enable swma smooth
- indicators : you can select one of the 93 function like ema(),rsi().. to define your indicator
- Source : you can select from already defined indicators (IND1-4), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...)
CONDITION DETAILS
- There are are 4 type of conditions, long entry, short entry, long exit, short exit.
- Each condition are built up from 4 combinations that joined with "AND" & "OR" operators
- You can see the results by enabling show alerts check box
- If you only wants to enter long entry and long exit, just fill these conditions
- If "close on opposite" checkbox selected on settings, long entry will be closed on short entry and vice versa
COMBINATIONS DETAILS
- There are 4 combinations that joined with "AND" & "OR" operators for each condition
- combinations are built up from compare 1st entry with 2nd one by using operator
- 1st and 2nd entries includes already defined indicators (IND1-5), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...)
- Operators are comparison values such as >,<, crossover,...
- 2nd entry include "VALUE" parameter that will use to compare 1st indicator with value area
- If 2nd indicator selected different than "VALUE", value are will mean previous value of the selection. (ex: value area= 2, 2nd entry=close, means close )
- Selecting "NONE" for the 1st entry will disable calculation of current and following combinations
JOINS DETAILS
- Each combination will join wiht the following one with the JOIN (AND, OR) operator (if the following one is not equal "NONE")
CUSTOM INDICATOR
- Custom Indicator defines harcoded in the source code.
- You can call it with "CUST" in the Indicator definition source or combination entries source
- You can change or implement your custom indicator by updating the source code
EXTERNAL INDICATOR
- You can import an external indicator by selecting it from the ext source.
- External Indicator should be already imported to the chart and it have an plot function to output its signal
EXPORTING SIGNAL
- You can export your result to an already defined strategy template such as Pine coders, Benson, Daveatt Strategy templates
- Or you can define your custom export for other future strategy templates
ALERTS
- By enabling show alerts checkbox, you can see long entry exits on the bottom, and short entry exits aon the top of the chart
ADDITIONAL INFO
- You can see all off the inputs descriptions in the tooltips. (You can also see the previous version for details)
- Availability to set start, end dates
- Minimize repainting by using security function options (Secure, Semi Secure, Repaint)
- Availability of use timeframes
-
Version 3 INDICATORS LIST (More to be added):
▼▼▼ OVERLAY INDICATORS ▼▼▼
alma(src,len,offset=0.85,sigma=6).-------Arnaud Legoux Moving Average
ama(src,len,fast=14,slow=100).-----------Adjusted Moving Average
accdist().-------------------------------Accumulation/distribution index.
cma(src,len).----------------------------Corrective Moving average
dema(src,len).---------------------------Double EMA (Same as EMA with 2 factor)
ema(src,len).----------------------------Exponential Moving Average
gmma(src,len).---------------------------Geometric Mean Moving Average
highest(src,len).------------------------Highest value for a given number of bars back.
hl2ma(src,len).--------------------------higest lowest moving average
hma(src,len).----------------------------Hull Moving Average.
lagAdapt(src,len,perclen=5,fperc=50).----Ehlers Adaptive Laguerre filter
lagAdaptV(src,len,perclen=5,fperc=50).---Ehlers Adaptive Laguerre filter variation
laguerre(src,len).-----------------------Ehlers Laguerre filter
lesrcp(src,len).-------------------------lowest exponential esrcpanding moving line
lexp(src,len).---------------------------lowest exponential expanding moving line
linreg(src,len,loffset=1).---------------Linear regression
lowest(src,len).-------------------------Lovest value for a given number of bars back.
mcginley(src, len.-----------------------McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
percntl(src,len).------------------------percentile nearest rank. Calculates percentile using method of Nearest Rank.
percntli(src,len).-----------------------percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
previous(src,len).-----------------------Previous n (len) value of the source
pivothigh(src,BarsLeft=len,BarsRight=2).-Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
pivotlow(src,BarsLeft=len,BarsRight=2).--Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
rema(src,len).---------------------------Range EMA (REMA)
rma(src,len).----------------------------Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sar(start=len, inc=0.02, max=0.02).------Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)
sma(src,len).----------------------------Smoothed Moving Average
smma(src,len).---------------------------Smoothed Moving Average
super2(src,len).-------------------------Ehlers super smoother, 2 pole
super3(src,len).-------------------------Ehlers super smoother, 3 pole
supertrend(src,len,period=3).------------Supertrend indicator
swma(src,len).---------------------------Sine-Weighted Moving Average
tema(src,len).---------------------------Triple EMA (Same as EMA with 3 factor)
tma(src,len).----------------------------Triangular Moving Average
vida(src,len).---------------------------Variable Index Dynamic Average
vwma(src,len).---------------------------Volume Weigted Moving Average
volstop(src,len,atrfactor=2).------------Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
wma(src,len).----------------------------Weigted Moving Average
vwap(src_).------------------------------Volume Weighted Average Price (VWAP) is used to measure the average price weighted by volume
▼▼▼ NON OVERLAY INDICATORS ▼▼
adx(dilen=len, adxlen=14, adxtype=0).----adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
angle(src,len).--------------------------angle of the series (Use its Input as another indicator output)
aroon(len,dir=0).------------------------aroon indicator. Aroons major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
atr(src,len).----------------------------average true range. RMA of true range.
awesome(fast=len=5,slow=34,type=0).------Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
bbr(src,len,mult=1).---------------------bollinger %%
bbw(src,len,mult=2).---------------------Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci(src,len).----------------------------commodity channel index
cctbbo(src,len).-------------------------CCT Bollinger Band Oscilator
change(src,len).-------------------------A.K.A. Momentum. Difference between current value and previous, source - source . is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security
cmf(len=20).-----------------------------Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
cmo(src,len).----------------------------Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog(src,len).----------------------------The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
copcurve(src,len).-----------------------Coppock Curve. was originally developed by Edwin Sedge Coppock (Barrons Magazine, October 1962).
correl(src,len).-------------------------Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count(src,len).--------------------------green avg - red avg
cti(src,len).----------------------------Ehler s Correlation Trend Indicator by
dev(src,len).----------------------------ta.dev() Measure of difference between the series and its ta.sma
dpo(len).--------------------------------Detrended Price OScilator is used to remove trend from price.
efi(len).--------------------------------Elders Force Index (EFI) measures the power behind a price movement using price and volume.
eom(len=14,div=10000).-------------------Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
falling(src,len).------------------------ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
fisher(len).-----------------------------Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
histvol(len).----------------------------Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
kcr(src,len,mult=2).---------------------Keltner Channels Range
kcw(src,len,mult=2).---------------------ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
klinger(type=len).-----------------------Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
macd(src,len).---------------------------MACD (Moving Average Convergence/Divergence)
mfi(src,len).----------------------------Money Flow Index s a tool used for measuring buying and selling pressure
msi(len=10).-----------------------------Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
nvi().-----------------------------------Negative Volume Index
obv().-----------------------------------On Balance Volume
pvi().-----------------------------------Positive Volume Index
pvt().-----------------------------------Price Volume Trend
ranges(src,upper=len, lower=-5).---------ranges of the source. src=src, upper=len, v1:lower=upper . returns: -1 source=upper otherwise 0
rising(src,len).-------------------------ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc(src,len).----------------------------Rate of Change
rsi(src,len).----------------------------Relative strength Index
rvi(src,len).----------------------------The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
smi_osc(src,len,fast=5, slow=34).--------smi Oscillator
smi_sig(src,len,fast=5, slow=34).--------smi Signal
stc(src,len,fast=23,slow=50).------------Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from
stdev(src,len).--------------------------Standart deviation
trix(src,len) .--------------------------the rate of change of a triple exponentially smoothed moving average.
tsi(src,len).----------------------------The True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend.
ultimateOsc(len.-------------------------Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
variance(src,len).-----------------------ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
willprc(src,len).------------------------Williams %R
wad().-----------------------------------Williams Accumulation/Distribution.
wvad().----------------------------------Williams Variable Accumulation/Distribution.
HISTORY
v3.01
ADD: 23 new indicators added to indicators list from the library. Current Total number of Indicators are 93. (to be continued to adding)
ADD: 2 more Parameters (P1,P2) for indicator calculation added. Par:(Use Defaults) uses only indicator(Source, Length) with library's default parameters. Par:(Use Extra Parameters P1,P2) use indicator(Source,Length,p1,p2) with additional parameters if indicator needs.
ADD: log calculation (simple, log10) option added on indicator function entries
ADD: New Output Signals added for compatibility on exporting condition signals to different Strategy templates.
ADD: Alerts Added according to conditions results
UPD: Indicator source inputs now display with indicators descriptions
UPD: Most off the source code rearranged and some functions moved to the new library. Now system work like a little bit frontend/backend
UPD: Performance improvement made on factorization and other source code
UPD: Input GUI rearranged
UPD: Tooltips corrected
REM: Extended indicators removed
UPD: IND1-IND4 added to indicator data source. Now it is possible to create new indicators with the previously defined indicators value. ex: IND1=ema(close,14) and IND2=rsi(IND1,20) means IND2=rsi(ema(close,14),20)
UPD: Custom Indicator (CUST) added to indicator data source and Combination Indicator source.
UPD: Volume added to indicator data source and Combination Indicator source.
REM: Custom indicators removed and only one custom indicator left
REM: Plot Type "Org. Range (-1,1)" removed
UPD: angle, rising, falling type operators moved to indicator library
Indicators & Conditions Test Framework [DTU]Hello All,
This script is a framework to build strategies by combining indicators and conditions (long, short, exits). You are able to analyze your strategies in realtime by changing the input parameters related to indicators, conditions and their combinations.
OVERVIEW
With this Study/Strategy framework, you will be able to create strategy conditions, display them on the chart, and test them using existing indicators as well as external and custom indicators that you can add.
The main purpose of the Framework is to choose your indicators to be used in the conditions and test your strategy by producing your "Long, short, Exit long, Exit short" combinations.
Although may be, it can be a bit difficult and complicated at first start, but you can understand the logic on its use in a very short time.
Notes:
I removed external links off descriptive images and video to be comply with Trading view violation House Rules
Since I am new in the community and still trying to understand the pine script language I can make errors and violations on my script. Please Inform me on any issue that I made..
HOW TO
STEP 1: SETTINGS ______________________________________________________________________________________________________
SOURCE, TIMEFRAME, SECURITY
Select the Source, timeframe and Secure type that your indicators will use.
Here, the Secure entry consists of 3 parts and the f_security function is used to determine it.
a)Secure
This option is defined as reducing repaint in tradingview calculations as much as possible. The following function is used.
request.security(_symbol, _res, _src , lookahead=barmerge.lookahead_on)
b)Semi Secure
While this option can reduce repaint in tradingview calculations as much as possible, it is less secure. The following function is used.
request.security(_symbol, _res, _src )
c)Repaint
This option turns on the repaint feature. The following function is used.
request.security(_symbol, _res, _src ) : na
Ind Source:
You can the source that indicators will use their own calculations
Ext Source:
You can import external Indicator sources from here . It appears on condition/combination area as "EXT".
To export the External indicator plot it with a title. It will be visible in source dropdown input
PERIOD , ALERTS...
Period:
Determine your strategy testing period by selecting start and end date/time
(!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars.
The extra bar option may cause problems such as not appearing in the calculations or errors).
Plot Alerts:
Plot condition result as alerts arrows on the chart's bottom for "LONG" and the top for "SHORT" entries, exits
Close on opposite:
When selected, a long entry gets closed when a short entry opens and vice versa
Show Profit:
It appears if script is in strategy mode (not in study) this can display current or open profit for better reanalyzing your strategy entry exit points. (Currently under development)
PLOT TYPE OPERATIONS
This option has 4 entries
a) Mult
Sets the multiplier for the selected Plot Type (stochastic, Percentrank, Org Range (-1,1) ) except for "Original" in the range (-1,1).
EXAMPLE: When 1000 is selected, the indicator in the range of (-1,1) will appear in the range of (-1000, 1000) on the screen.
b) Shift
It determines the shift that will appear on the screen for the selected Plot Type (stochastic, Percentrank,Org Range (-1,1) ) in the range (-1,1) other than "Original".
EXAMPLE: When Shift:35000 and mult:1000 are selected, the indicator will appear in the range (34000, 36000) on the screen.
c) Smooth
This option (only for Stochastic & PercentRank) allows to smooth the indicator to be displayed.
Here, tradinview ta.swma function is used.
b) hline
Adjusts the horizontal lines to appear on the screen according to the mult factor for the range (-1,1)
The lines represent the values (-1, -05, 0, 05, 1)
STEP 2: INDICATORS ______________________________________________________________________________________________________
You need to choose indicators that you can use in strategy conditions.
Here, the indicators come from the dturkuler/lib_Indicators_DT open script library defined in the code
In addition, you can add the indicators that you will create in the area defined in the code to this list..
You can also import external indicators and test them with other variables on the system..
You can choose a maximum of 5 indicators that you can use in total. (can be increased in new versions)
Indicators are categorized in 3 main sections
Indicator Selection:
You can select your indicators from this area
a)Moving Averages
These are indicators such as EMA, SMA that you can show on the stock. They come from the library.
These indicators are fed from Settings/source. Only the length value can be used as a parameter.
In addition, line colors can be changed..
As of now, there are 28 indicators in the library in total and 5 indicators are left as future use for this field for now.
b)Other Indicators
These are different indicators from the stock value such as RSI, COG. They come from the library. These indicators are fed from Settings/source.
Only the length value can be used as a parameter. In addition, line colors can be changed.
As of now, there are 24 indicators in the library in total and 5 indicators are left as a future use for this field for now.
c)Custom Indicators
These indicators are the ones you can create by programming yourself in the source code..
The area at the bottom of the settings screen is reserved for the parameters of this type of indicators.
Indicator Length:
You can update your selected indicator length value from here. (Not: it doesn't work for custom indicators since they have their parameter on cust. Ind. input screen )
Indicator Plot Type:
Next to the indicators, there is an input selection field about how they will be displayed on the screen.
a)Original
The indicator is displayed on the screen with its current values. It is an ideal solution for displaying moving average indicators such as (EMA, SMA) over current stock.
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
For this reason, other options may be more suitable for these.
b)Stochastic
The indicator is displayed on the screen with stochastic calculation in the range of -1.1.
It uses the stochastic(50) calculation method to spread indicators such as (RSI, COB) over the range (-1,1).
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
c)PercentRank
The indicator is displayed on the screen with stochastic calculation in the range of -1.1. .
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen
((!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
d)Org Range (-1,1)
If your indicator is in the range of -1.1, your indicator will be displayed on the screen with its original calculation in the range of -1.1.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your fitness calculations. Instead, get the values from Data Window)
STEP 2 NOTES:
STEP 3: CONDITIONS ______________________________________________________________________________________________________
After choosing the indicators you will use in the conditions, you move on to the "CONDITIONS" section.
There are 4 conditions type here.
• LONG ENTRY CONDITION
• SHORT ENTRY CONDITION
• LONG CLOSE CONDITION
• SHORT CLOSE CONDITION
The use of each condition is the same.
There are 3 combinations you can use in each condition. (can be increased in new versions)
a)COMBINATIONS
There are 3 combinations you can use in each condition. (can be increased in new versions)
Each combination are build from 4 parts
1)1st Indicator
If set to "NONE" this combination will not be used on calculations. You can select
IND1-5: from indicators (See above),
EXT: value from externally imported indicator
Stock built-in values: close, open...
2)Operator
Selected Operator compares 1st Indicator with the 2nd one. You can select different operators such as
crossover, crossunder, cross,>,<,=....
3)2nd Indicator
This indicator will be compared with the 1st one via selected Operator. You can select
IND1-5: from indicators (See above),
VALUE: a float value defined in the combinations value parameter
EXT: value from externally imported indicator
Stock builtin values: close,open...
4)Value
When the 2nd indicator field is "VALUE", value area compares the entered value.
ex: 1st indicator="open", op=">", 2nd indicator="VALUE", value=3000.12 means is(close>3000.12)
In other conditions, it compares the previous values of the indicator.
ex: 1st indicator="open", op=">" 2nd indicator is "close" and value is 2 means is(open>close )
EXAMPLES:
indicator 1= "IND1", Operator=">", indicator 2= "IND2" => is(IND1>IND2)
indicator 1= "IND1", Operator=">", indicator 2= "VALUE", "0.1" => is(IND1>0.9)
indicator 1= "IND2", Operator="crossover", indicator 2= "IND1" => is(IND2 crossover IND1) : like a=ta.crossover(IND2, IND1)
indicator 1= "IND1", Operator="<", indicator 2= "close" => is(IND1>close)
indicator 1= "IND1", Operator="<", indicator 2= "EXT" => is(IND1>EXT) , EXT mean external imported indicator that define on settings section
indicator 1= "IND1", Operator="<", indicator 2= "IND1", Value="1" => is (IND1>IND1 )
b)JOIN COMBINATIONS
Each combination in Condition is compared with the next one via JOIN operator
The join operator can be selected as AND or OR.
Examples:
1st combination= is(IND1>0.9) true
2nd combination= is(IND2 crossover IND1) false
1st combination "AND" 2ndcombination" => false (is(IND1>0.9) AND is(IND2 crossover IND1))
1st combination "OR" 2nd combination" => true (is(IND1>0.9) OR is(IND2 crossover IND1))
STEP 3 NOTES:
When the 2nd indicator field is "VALUE", value area compares the entered value. In other conditions, it compares the previous values of the indicator.
In cases where "VALUE" is not selected, integer values must be entered in this field. (float should not be entered. ie 1, 2 should be entered)
!!!If the 1st indicator is "NONE" in the combination, that combination is cancelled.
Each combination returns true/false, allowing the selected value to be compared with another value
Example: EMA(21)>EMA(50) returns true under all conditions or (EMA(21) crossover EMA(50)) returns true when passed.
You can use , Value of 5 indicators (IND1-IND5) or (VALUE) that you have defined in combinations or import indicator (EXT) or stock values (close, open, high...) in your calculations.
combination Compares the 1st indicator with 2nd indicator via the operator.
STEP 4: CUSTOM INDICATORS ______________________________________________________________________________________________________
There is an area in the code for designing Custom Indicators.
Here you can design your own indicators and use them in the framework.
You can also create unlimited parameters for your indicators in the SETTINGS custom indicator field.
For now, only 3 Custom indicators have been defined.
Examples are entered in the code for custom indicators.
STEP 4 NOTES:
Including / updating custom to the code is explained in the source code
• LIMITATIONS:
!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars. More bar options may cause problems such as not appearing in the calculations or errors.
• RAMBLINGS:
• NOTES [ /i]
This Script can be used as an indicator if the last strategy parts in the code are commented out and converted to the initial strategy study.
It was originally prepared for my use with my own strategy framework and has export functions accordingly.
When integrated to my own strategy framework it brings many more features over strategy definition of trades.
• TODO [ /i]
TODO: Add tooltips to the settings screen
TODO: Add double triple, Quatr factor for all indicators (convert any indicator to factor2-4 facotr. ex: EMA to DEMA, TEMA, QEMA...)
TODO: Add factorized Fibo avg range indicator (good for trend definition and entry exit points)
TODO: Add bands to the indicator and conditions
TODO: Add debug window for exporting indicator's parameters
TODO: Add isRising(value) isFalling(value), is...(value) .... to combinations (they can be used as custom indicator also
TODO: Reassess condition entry screen for user friendly GUI
TODO: Increase # conditions from 3 to 4
TODO: Reassess strategy entries, exit and close (should be improved)
TODO: Add Alerts, Condiional alerts for indicator (study) part
TODO: Create export function v3 for Pinecoders Indicator framework
• THANKS:
For Pine script format docs RicardoSantos .
For Pine script coding standards Pinecoders .
For moving average script used on library s RodrigoKazuma .
Special Long Short ConditionsIt generates buy and sell signals using a special algorithm when various moving averages approach and diverge from the price. It aims to stay in the trend as long as possible. Please control the risks of your investments well. It is not investment advice.
It calculates using fast, slow period and distance and near distance units. You can adapt it by changing the parameters, but too much optimization is not recommended.
Cesitli hareketli ortalamalarin fiyata yakinlasmasi ve uzaklasmasi durumunda ozel bir algoritma kullanarak al ve sat sinyalleri uretir. Trendde mumkun olabildigince kalabilmeyi amaclar. Lutfen yatirimlarizda risklerini iyi kontrol edin. Yatirim tavsiyesi degildir.
Hizli,yavas periyot ve uzak, yakin uzaklik birimlerini kullanarak hesaplama yapar. Parametreleri degistirerek kendinize uyarlayabilirsiniz fakat cok fazla optimizasyon tavsiye edilemez.
RSI ExtendedThis script is intended to print signals on the main price chart and send alerts when the RSI is overbought or oversold.
You can customize the source of the signal (open, close, etc), as well as oversold/overbought levels, and RSI length.
Long Wick TrialI've created this as a confirmation indicator to help know when market conditions are favorable to enter a trade. It measures volume, volatility, and ATR. It is not intended to tell you when to enter/exit the market, but use it with another indicator such as the mirror macd to filter out many losses and avoid entering the market during low volume or excessive volatility that may trip your stop loss.
Green = Favorable Market conditions
Yellow = Enter with caution, the market is moving sideways but is slightly trending
Orange = Enter with caution, the market is trending but extremely volatile and may trip stop loss early
Black = Shouldn't enter market here, market is moving sideways and volume is also low.
Average True Range ShiftThis indicator builds on the idea of the Average True Range (ATR) as a way of measuring volatility. It uses two different ATRs to show a shift in market volatility.
It is mainly composed of two moving averages of ATR. One fast moving, which looks back at the previous 5 periods. One slow moving, which looks back at the previous 21 periods. Both ATRs have been normalized (show percentage instead of an absolute amount). The third component of this indicator is the histogram that is created by subtracting the slow moving average, from the fast moving average.
By having two ATRs of different lengths, traders can see how short term volatility compares to long term volatility, and how it is shifting over time. When the fast-moving crosses above the slow-moving, it will show a positive value on the histogram, meaning that short term volatility is increasing and higher than normal. When it crosses below, it will show a negative value on the histogram, meaning that short term volatility is decreasing, and lower than normal.
There are a variety of ways to utilize this indicator, and it will work in most markets. I find it is best to analyze macro market conditions on daily charts and above, rather than micro intraday moves.
12Hours-optimized Crypto Alert ReloadedSame as 4H, but this time 12H.
In my opinion this one is way more accurate, let me know yours.
UPDATES:
I added Short Sell signals, both Red and Blue means "Short Sell", but they use different formulas. The blue one seems pretty solid, meanwhile the red one get more oportunities but might give an earlier entrance aswell.
Remember no software is 100% accurate, but this one seems at least >90% accurate so I guess that with a decent risk management and order placing you will make great profit.
The script gave1 bad short signal in whole 2018, and 4 bad buy signals, pretty decent on a market as cryptos, and at a correction phase.
Again, let me know your opinion, feedback, and critics.
Stay aware since I will update it for sure, I'm already working on it.
Soon:
*Filtering signal by candlestick patterns
*Pivot levels for resistance and support forecast beforehand.
*and more cool features ;)
Thanks again!