dmarcLevelParserLibrary "dmarcLevelParser"
Provides a parsing library that indicator authors can use in order to parse dmarcLevels.
parseLevels(s)
โโParses the string content and returns the `dmarcLevels` found within.
โโParameters:
โโโโ s (string) : The string to parse.
โโReturns: The parsed dmarc levels.
zoneRange
โโFields:
โโโโ high (series float)
โโโโ low (series float)
wtdLevels
โโFields:
โโโโ lvnLines (array)
โโโโ lvnZones (array)
โโโโ supplyLines (array)
โโโโ supplyZones (array)
โโโโ vses (array)
โโโโ vahs (array)
โโโโ vals (array)
โโโโ pocs (array)
โโโโ miscZones (array)
โโโโ miscLines (array)
โโโโ fbos (array)
โโโโ fbds (array)
โโโโ majorLevels (array)
โโโโ mansupLines (array)
โโโโ mansupmajLines (array)
โโโโ mansupZones (array)
โโโโ mansupmajZones (array)
โโโโ manresLines (array)
โโโโ manresmajLines (array)
โโโโ manresZones (array)
โโโโ manresmajZones (array)
Indikator dan strategi
capital_managementLibrary "capital_management"
TODO: add library description here
Volume_calculation(precent_risk, order_entry_price, stop_loss_price)
โโTODO: Volume calculation function by placing orders with fiven % risk
โโParameters:
โโโโ precent_risk (float)
โโโโ order_entry_price (float)
โโโโ stop_loss_price (float)
โโReturns: stop_loss_price: Price that place stop loss order
PaddingThe Padding library is a comprehensive and flexible toolkit designed to extend time series data within TradingView, making it an indispensable resource for advanced signal processing tasks such as FFT, filtering, convolution, and wavelet analysis. At its core, the library addresses the common challenge of edge effects by "padding" your dataโthat is, by appending additional data points beyond the natural boundaries of your original dataset. This extension not only mitigates the distortions that can occur at the endpoints but also helps to maintain the integrity of various transformations and calculations performed on the series. The library accomplishes this while preserving the ordering of your data, ensuring that the most recent point always resides at index 0.
Central to the functionality of this library are two key enumerations: Direction and PaddingType. The Direction enum determines where the padding will be applied. You can choose to extend the data in the forward direction (ahead of the current values), in the backward direction (behind the current values), or in both directions simultaneously. The PaddingType enum defines the specific method used for extending the data. The library supports several methodsโincluding symmetric, reflect, periodic, antisymmetric, antireflect, smooth, constant, and zero paddingโeach of which has been implemented to suit different analytical scenarios. For instance, symmetric padding mirrors the original data across its boundaries, while reflect padding continues the trend by reflecting around endpoint values. Periodic padding repeats the data, and antisymmetric padding mirrors the data with alternating signs to counterbalance it. The antireflect and smooth methods take into account the derivatives of your data, thereby extending the series in a way that preserves or smoothly continues these derivative values. Constant and zero padding simply extend the series using fixed endpoint values or zeros. Together, these enums allow you to fine-tune how your data is extended, ensuring that the padding method aligns with the specific requirements of your analysis.
The library is designed to work with both single variable inputs and array inputs. When using array-based methodsโparticularly with the antireflect and smooth padding typesโplease note that the implementation intentionally discards the last data point as a result of the delta computation process. This behavior is an important consideration when integrating the library into your TradingView studies, as it affects the overall data length of the padded series. Despite this, the libraryโs structure and documentation make it straightforward to incorporate into your existing scripts. You simply provide your data source, define the length of your data window, and select the desired padding type and direction, along with any optional parameters to control the extent of the padding (using both_period, forward_period, or backward_period).
In practical application, the Padding library enables you to extend historical data beyond its original range in a controlled and predictable manner. This is particularly useful when preparing datasets for further signal processing, as it helps to reduce artifacts that can otherwise compromise the results of your analytical routines. Whether you are an experienced Pine Script developer or a trader exploring advanced data analysis techniques, this library offers a robust solution that enhances the reliability and accuracy of your studies by ensuring your algorithms operate on a more complete and well-prepared dataset.
Library "Padding"
A comprehensive library for padding time series data with various methods. Supports both single variable and array inputs, with flexible padding directions and periods. Designed for signal processing applications including FFT, filtering, convolution, and wavelets. All methods maintain data ordering with most recent point at index 0.
symmetric(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies symmetric padding by mirroring the input data across boundaries
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with symmetric padding applied
method symmetric(source, direction, both_period, forward_period, backward_period)
โโApplies symmetric padding to an array by mirroring the data across boundaries
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with symmetric padding applied
reflect(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies reflect padding by continuing trends through reflection around endpoint values
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with reflect padding applied
method reflect(source, direction, both_period, forward_period, backward_period)
โโApplies reflect padding to an array by continuing trends through reflection around endpoint values
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with reflect padding applied
periodic(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies periodic padding by repeating the input data
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with periodic padding applied
method periodic(source, direction, both_period, forward_period, backward_period)
โโApplies periodic padding to an array by repeating the data
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with periodic padding applied
antisymmetric(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies antisymmetric padding by mirroring data and alternating signs
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with antisymmetric padding applied
method antisymmetric(source, direction, both_period, forward_period, backward_period)
โโApplies antisymmetric padding to an array by mirroring data and alternating signs
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with antisymmetric padding applied
antireflect(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies antireflect padding by reflecting around endpoints while preserving derivatives
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with antireflect padding applied
method antireflect(source, direction, both_period, forward_period, backward_period)
โโApplies antireflect padding to an array by reflecting around endpoints while preserving derivatives
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with antireflect padding applied. Note: Last data point is lost when using array input
smooth(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies smooth padding by extending with constant derivatives from endpoints
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with smooth padding applied
method smooth(source, direction, both_period, forward_period, backward_period)
โโApplies smooth padding to an array by extending with constant derivatives from endpoints
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with smooth padding applied. Note: Last data point is lost when using array input
constant(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies constant padding by extending endpoint values
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with constant padding applied
method constant(source, direction, both_period, forward_period, backward_period)
โโApplies constant padding to an array by extending endpoint values
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with constant padding applied
zero(source, series_length, direction, both_period, forward_period, backward_period)
โโApplies zero padding by extending with zeros
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with zero padding applied
method zero(source, direction, both_period, forward_period, backward_period)
โโApplies zero padding to an array by extending with zeros
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with zero padding applied
pad_data(source, series_length, padding_type, direction, both_period, forward_period, backward_period)
โโGeneric padding function that applies specified padding type to input data
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ padding_type (series PaddingType) : Type of padding to apply (see PaddingType enum)
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with specified padding applied
method pad_data(source, padding_type, direction, both_period, forward_period, backward_period)
โโGeneric padding function that applies specified padding type to array input
โโNamespace types: array
โโParameters:
โโโโ source (array) : Array of values to pad
โโโโ padding_type (series PaddingType) : Type of padding to apply (see PaddingType enum)
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to array length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to array length if not specified
โโReturns: Array ordered with most recent point at index 0, containing original data with specified padding applied. Note: Last data point is lost when using antireflect or smooth padding types
make_padded_data(source, series_length, padding_type, direction, both_period, forward_period, backward_period)
โโCreates a window-based padded data series that updates with each new value. WARNING: Function must be called on every bar for consistency. Do not use in scopes where it may not execute on every bar.
โโParameters:
โโโโ source (float) : Input value to pad from
โโโโ series_length (int) : Length of the data window
โโโโ padding_type (series PaddingType) : Type of padding to apply (see PaddingType enum)
โโโโ direction (series Direction) : Direction to apply padding
โโโโ both_period (int) : Optional - periods to pad in both directions. Overrides forward_period and backward_period if specified
โโโโ forward_period (int) : Optional - periods to pad forward. Defaults to series_length if not specified
โโโโ backward_period (int) : Optional - periods to pad backward. Defaults to series_length if not specified
โโReturns: Array ordered with most recent point at index 0, containing windowed data with specified padding applied
UtilityLibraryLibrary "UtilityLibrary"
A collection of custom utility functions used in my scripts.
milliseconds_per_bar()
โโGets the number of milliseconds per bar.
โโReturns: (int) The number of milliseconds per bar.
realtime()
โโChecks if the current bar is the actual realtime bar.
โโReturns: (bool) `true` when the current bar is the actual realtime bar, `false` otherwise.
replay()
โโChecks if the current bar is the last replay bar.
โโReturns: (bool) `true` when the current bar is the last replay bar, `false` otherwise.
bar_elapsed()
โโChecks how much of the current bar has elapsed.
โโReturns: (float) Between 0 and 1.
even(number)
โโChecks if a number is even.
โโParameters:
โโโโ number (float) : (float) The number to evaluate.
โโReturns: (bool) `true` when the number is even, `false` when the number is odd.
sign(number)
โโGets the sign of a float.
โโParameters:
โโโโ number (float) : (float) The number to evaluate.
โโReturns: (int) 1 or -1, unlike math.sign() which returns 0 if the number is 0.
atan2(y, x)
โโDerives an angle in radians from the XY coordinate.
โโParameters:
โโโโ y (float) : (float) Y coordinate.
โโโโ x (float) : (float) X coordinate.
โโReturns: (float) Between -ฯ and ฯ.
clamp(number, min, max)
โโEnsures a value is between the `min` and `max` thresholds.
โโParameters:
โโโโ number (float) : (float) The number to clamp.
โโโโ min (float) : (float) The minimum threshold (0 by default).
โโโโ max (float) : (float) The maximum threshold (1 by default).
โโReturns: (float) Between `min` and `max`.
remove_gamma(value)
โโRemoves gamma from normalized sRGB channel values.
โโParameters:
โโโโ value (float) : (float) The normalized channel value .
โโReturns: (float) Channel value with gamma removed.
add_gama(value)
โโAdds gamma into normalized linear RGB channel values.
โโParameters:
โโโโ value (float) : (float) The normalized channel value .
โโReturns: (float) Channel value with gamma added.
rgb_to_xyz(Color)
โโExtracts XYZ-D65 channels from sRGB colors.
โโParameters:
โโโโ Color (color) : (color) The sRGB color to process.
โโReturns: (float tuple)
xyz_to_rgb(x, y, z)
โโConverts XYZ-D65 channels to sRGB channels.
โโParameters:
โโโโ x (float) : (float) The X channel value.
โโโโ y (float) : (float) The Y channel value.
โโโโ z (float) : (float) The Z channel value.
โโReturns: (int tuple)
rgb_to_oklab(Color)
โโExtracts OKLAB-D65 channels from sRGB colors.
โโParameters:
โโโโ Color (color) : (color) The sRGB color to process.
โโReturns: (float tuple)
oklab_to_rgb(l, a, b)
โโConverts OKLAB-D65 channels to sRGB channels.
โโParameters:
โโโโ l (float) : (float) The L channel value.
โโโโ a (float) : (float) The A channel value.
โโโโ b (float) : (float) The B channel value.
โโReturns: (int tuple)
rgb_to_oklch(Color)
โโExtracts OKLCH channels from sRGB colors.
โโParameters:
โโโโ Color (color) : (color) The sRGB color to process.
โโReturns: (float tuple)
oklch_to_rgb(l, c, h)
โโConverts OKLCH channels to sRGB channels.
โโParameters:
โโโโ l (float) : (float) The L channel value.
โโโโ c (float) : (float) The C channel value.
โโโโ h (float) : (float) The H channel value.
โโReturns: (float tuple)
hues(l1, h1, l2, h2, dist)
โโEnsures the hue angles are set correctly for linearly interpolating OKLCH.
โโParameters:
โโโโ l1 (float) : (float) The first L channel value.
โโโโ h1 (float) : (float) The first H channel value.
โโโโ l2 (float) : (float) The second L channel value.
โโโโ h2 (float) : (float) The second H channel value.
โโโโ dist (string) : (string) The preferred angular distance to use. Options: `min` or `max` (`min` by default).
โโReturns: (float tuple)
lerp(a, b, t)
โโLinearly interpolates between two values.
โโParameters:
โโโโ a (float) : (float) The starting point (first value).
โโโโ b (float) : (float) The ending point (second value).
โโโโ t (float) : (float) The interpolation factor .
โโReturns: (float) Between `a` and `b`.
smoothstep(t, precise)
โโA non-linear (smooth) interpolation between 0 and 1.
โโParameters:
โโโโ t (float) : (float) The interpolation factor .
โโโโ precise (bool) : (bool) Sets if the calc should be precise or efficient (`true` by default).
โโReturns: (float) Between 0 and 1.
ease(t, n, v, x1, y1, x2, y2)
โโA customizable non-linear interpolation between 0 and 1.
โโParameters:
โโโโ t (float) : (float) The interpolation factor .
โโโโ n (float) : (float) The degree of ease (1 by default).
โโโโ v (string) : (string) The easing variant type: `in-out`, `in`, or `out` (`in-out` by default).
โโโโ x1 (float) : (float) Optional X coordinate of starting point (0 by default).
โโโโ y1 (float) : (float) Optional Y coordinate of starting point (0 by default).
โโโโ x2 (float) : (float) Optional X coordinate of ending point (1 by default).
โโโโ y2 (float) : (float) Optional Y coordinate of ending point (1 by default).
โโReturns: (float) Between 0 and 1.
mix(color1, color2, blend, space, dist)
โโLinearly interpolates between two colors.
โโParameters:
โโโโ color1 (color) : (color) The first color.
โโโโ color2 (color) : (color) The second color.
โโโโ blend (float) : (float) The interpolation factor .
โโโโ space (string) : (string) The color space to use for interpolating. Options: `rgb`, `oklab`, and `oklch` (`rgb` by default).
โโโโ dist (string) : (string) The anglular distance to use for the hue change when the color space is set to `oklch`. Options: `min` and `max` (`min` by default).
โโReturns: (color) Blend of `color1` and `color2`.
VolumeProfileLibrary "VolumeProfile"
Analyzes volume and price and calculates a volume profile, in particular the Point Of Control and Value Area values.
new(rowSizeInTicks, valueAreaCoverage, startTime)
โโConstructor method that creates a new Volume Profile
โโParameters:
โโโโ rowSizeInTicks (float) : Internal row size (aka resolution) of the volume profile. Useful for most futures contracts would be '1 / syminfo.mintick'. Default '4'.
โโโโ valueAreaCoverage (int) : Percentage of total volume that is considered the Value Area. Default '70'
โโโโ startTime (int) : Start time (unix timestamp in milliseconds) of the Volume Profile. Default 'time'.
โโReturns: VolumeProfile object
method calculatePOC(vp)
โโCalculates current Point Of Control of the VP
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโReturns: void
method calculateVA(vp)
โโCalculates current Value Area High and Low of the VP
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโReturns: void
method update(vp, h, l, v, t)
โโProcesses new chart data and sorts volume into rows. Then calls calculatePOC() and calculateVA() to update the VP. Parameters are usually the output of request.security_lower_tf.
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโโโ h (array) : Array of highs
โโโโ l (array) : Array of lows
โโโโ v (array) : Array of volumes
โโโโ t (array) : Array of candle times
โโReturns: void
method setSessionHigh(vp, h)
โโSets the high of the session the VP is tracking
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโโโ h (float)
โโReturns: void
method setSessionLow(vp, l)
โโSets the low of the session the VP is tracking
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโโโ l (float)
โโReturns: void
method getPOC(vp)
โโGets the current Point Of Control
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโReturns: Point Of Control (float)
method getVAH(vp)
โโGets the current Value Area High
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโReturns: Value Area High (float)
method getVAL(vp)
โโGets the current Value Area Low
โโNamespace types: VolumeProfile
โโParameters:
โโโโ vp (VolumeProfile)
โโReturns: Value Area Low (float)
VolumeProfile
โโFields:
โโโโ rowSizeInTicks (series float)
โโโโ valueAreaCoverage (series int)
โโโโ startTime (series int)
โโโโ valueAreaHigh (series float)
โโโโ pointOfControl (series float)
โโโโ valueAreaLow (series float)
โโโโ sessionHigh (series float)
โโโโ sessionLow (series float)
โโโโ volumeByRow (map)
โโโโ totalVolume (series float)
โโโโ pocRow (series float)
โโโโ pocVol (series float)
wavesโโ OVERVIEW
This library intended for use in Bar Replay provides functions to generate various wave forms (sine, cosine, triangle, square) based on time and customizable parameters. Useful for testing and in creating oscillators, indicators, or visual effects.
โโ FUNCTIONS
โโข getSineWave()
โโข getCosineWave()
โโข getTriangleWave()
โโข getSquareWave()
โโ USAGE EXAMPLE
//@version=6
indicator("Wave Example")
import kaigouthro/waves/1
plot(waves.getSineWave(cyclesPerMinute=15))
โโ NOTES
* barsPerSecond defaults to 10. Adjust this if not using 10x in Bar Replay.
* Phase shift is in degrees.
---
Library "waves"
getSineWave(cyclesPerMinute, bar, barsPerSecond, amplitude, verticalShift, phaseShift)
โโ`getSineWave`
> Calculates a sine wave based on bar index, cycles per minute (BPM), and wave parameters.
โโParameters:
โโโโ cyclesPerMinute (float) : (float) The desired number of cycles per minute (BPM). Default is 30.0.
โโโโ bar (int) : (int) The current bar index. Default is bar_index.
โโโโ barsPerSecond (float) : (float) The number of bars per second. Default is 10.0 for Bar Replay
โโโโ amplitude (float) : (float) The amplitude of the sine wave. Default is 1.0.
โโโโ verticalShift (float) : (float) The vertical shift of the sine wave. Default is 0.0.
โโโโ phaseShift (float) : (float) The phase shift of the sine wave in radians. Default is 0.0.
โโReturns: (float) The calculated sine wave value.
getCosineWave(cyclesPerMinute, bar, barsPerSecond, amplitude, verticalShift, phaseShift)
โโ`getCosineWave`
> Calculates a cosine wave based on bar index, cycles per minute (BPM), and wave parameters.
โโParameters:
โโโโ cyclesPerMinute (float) : (float) The desired number of cycles per minute (BPM). Default is 30.0.
โโโโ bar (int) : (int) The current bar index. Default is bar_index.
โโโโ barsPerSecond (float) : (float) The number of bars per second. Default is 10.0 for Bar Replay
โโโโ amplitude (float) : (float) The amplitude of the cosine wave. Default is 1.0.
โโโโ verticalShift (float) : (float) The vertical shift of the cosine wave. Default is 0.0.
โโโโ phaseShift (float) : (float) The phase shift of the cosine wave in radians. Default is 0.0.
โโReturns: (float) The calculated cosine wave value.
getTriangleWave(cyclesPerMinute, bar, barsPerSecond, amplitude, verticalShift, phaseShift)
โโ`getTriangleWave`
> Calculates a triangle wave based on bar index, cycles per minute (BPM), and wave parameters.
โโParameters:
โโโโ cyclesPerMinute (float) : (float) The desired number of cycles per minute (BPM). Default is 30.0.
โโโโ bar (int) : (int) The current bar index. Default is bar_index.
โโโโ barsPerSecond (float) : (float) The number of bars per second. Default is 10.0 for Bar Replay
โโโโ amplitude (float) : (float) The amplitude of the triangle wave. Default is 1.0.
โโโโ verticalShift (float) : (float) The vertical shift of the triangle wave. Default is 0.0.
โโโโ phaseShift (float) : (float) The phase shift of the triangle wave in radians. Default is 0.0.
โโReturns: (float) The calculated triangle wave value.
getSquareWave(cyclesPerMinute, bar, barsPerSecond, amplitude, verticalShift, dutyCycle, phaseShift)
โโ`getSquareWave`
> Calculates a square wave based on bar index, cycles per minute (BPM), and wave parameters.
โโParameters:
โโโโ cyclesPerMinute (float) : (float) The desired number of cycles per minute (BPM). Default is 30.0.
โโโโ bar (int) : (int) The current bar index. Default is bar_index.
โโโโ barsPerSecond (float) : (float) The number of bars per second. Default is 10.0 for Bar Replay
โโโโ amplitude (float) : (float) The amplitude of the square wave. Default is 1.0.
โโโโ verticalShift (float) : (float) The vertical shift of the square wave. Default is 0.0.
โโโโ dutyCycle (float) : (float) The duty cycle of the square wave (0.0 to 1.0). Default is 0.5 (50% duty cycle).
โโโโ phaseShift (float) : (float) The phase shift of the square wave in radians. Default is 0.0.
โโReturns: (float) The calculated square wave value.
KalmanfilterLibrary "Kalmanfilter"
A sophisticated Kalman Filter implementation for financial time series analysis
@author Rocky-Studio
@version 1.0
initialize(initial_value, process_noise, measurement_noise)
โโInitializes Kalman Filter parameters
โโParameters:
โโโโ initial_value (float) : (float) The initial state estimate
โโโโ process_noise (float) : (float) The process noise coefficient (Q)
โโโโ measurement_noise (float) : (float) The measurement noise coefficient (R)
โโReturns: A tuple containing
update(prev_state, prev_covariance, measurement, process_noise, measurement_noise)
โโUpdate Kalman Filter state
โโParameters:
โโโโ prev_state (float)
โโโโ prev_covariance (float)
โโโโ measurement (float)
โโโโ process_noise (float)
โโโโ measurement_noise (float)
calculate_measurement_noise(price_series, length)
โโAdaptive measurement noise calculation
โโParameters:
โโโโ price_series (array)
โโโโ length (int)
calculate_measurement_noise_simple(price_series)
โโParameters:
โโโโ price_series (array)
update_trading(prev_state, prev_velocity, prev_covariance, measurement, volatility_window)
โโEnhanced trading update with velocity
โโParameters:
โโโโ prev_state (float)
โโโโ prev_velocity (float)
โโโโ prev_covariance (float)
โโโโ measurement (float)
โโโโ volatility_window (int)
model4_update(prev_mean, prev_speed, prev_covariance, price, process_noise, measurement_noise)
โโKalman Filter Model 4 implementation (Benhamou 2018)
โโParameters:
โโโโ prev_mean (float)
โโโโ prev_speed (float)
โโโโ prev_covariance (array)
โโโโ price (float)
โโโโ process_noise (array)
โโโโ measurement_noise (float)
model4_initialize(initial_price)
โโInitialize Model 4 parameters
โโParameters:
โโโโ initial_price (float)
model4_default_process_noise()
โโCreate default process noise matrix for Model 4
model4_calculate_measurement_noise(price_series, length)
โโAdaptive measurement noise calculation for Model 4
โโParameters:
โโโโ price_series (array)
โโโโ length (int)
BybitPerpsArrayLibrary "BybitPerpsArray"
f_getSymbolsForGroup(groupName)
โโParameters:
โโโโ groupName (string)
Contains all of the BYBIT Perp charts- use function to call them in groups
pslibs_revisedLibrary "pslibs_revised"
f_calculate_divergence_on_close(close, mom, rsi, start_lookback, max_lookback, rsiThresholdBuy, rsiThresholdSell, minAngleDiff, run_flag)
โโParameters:
โโโโ close (float)
โโโโ mom (float)
โโโโ rsi (float)
โโโโ start_lookback (int)
โโโโ max_lookback (int)
โโโโ rsiThresholdBuy (float)
โโโโ rsiThresholdSell (float)
โโโโ minAngleDiff (float)
โโโโ run_flag (bool)
f_calculate_divergence_on_low(low, mom, rsi, start_lookback, max_lookback, rsiThresholdBuy, rsiThresholdSell, minAngleDiff, run_flag)
โโParameters:
โโโโ low (float)
โโโโ mom (float)
โโโโ rsi (float)
โโโโ start_lookback (int)
โโโโ max_lookback (int)
โโโโ rsiThresholdBuy (float)
โโโโ rsiThresholdSell (float)
โโโโ minAngleDiff (float)
โโโโ run_flag (bool)
f_calculate_reversal(close, low, high, macdFastPeriod, macdSlowPeriod, macdSignalPeriod, stochPeriod, prcKPeriod, stochOS, stochOB, run_flag)
โโParameters:
โโโโ close (float)
โโโโ low (float)
โโโโ high (float)
โโโโ macdFastPeriod (simple int)
โโโโ macdSlowPeriod (simple int)
โโโโ macdSignalPeriod (simple int)
โโโโ stochPeriod (int)
โโโโ prcKPeriod (int)
โโโโ stochOS (int)
โโโโ stochOB (int)
โโโโ run_flag (bool)
is_within_first_30_minutes()
is_last_60_minutes()
is_last_30_minutes()
func_yestday_was_postive_trend()
Geo. Geo.
This library provides a comprehensive set of geometric functions based on 2 simple types for point and line manipulation, point array calculations, some vector operations (Borrowed from @ricardosantos ), angle calculations, and basic polygon analysis. It offers tools for creating, transforming, and analyzing geometric shapes and their relationships.
View the source code for detailed documentation on each function and type.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโ OVERVIEW
This library enhances TradingView's Pine Script with robust geometric capabilities. It introduces the Point and Line types, along with a suite of functions for various geometric operations. These functionalities empower you to perform advanced calculations, manipulations, and analyses involving points, lines, vectors, angles, and polygons directly within your Pine scripts. The example is at the bottom of the script. ( Commented out )
โโ CONCEPTS
This library revolves around two fundamental types:
โโข Point: Represents a point in 2D space with x and y coordinates, along with optional 'a' (angle) and 'v' (value) fields for versatile use. Crucially, for plotting, utilize the `.to_chart_point()` method to convert Points into plottable chart.point objects.
โโข Line: Defined by a starting Point and a slope , enabling calculations like getting y for a given x, or finding intersection points.
โโ FEATURES
โโข Point Manipulation: Perform operations like addition, subtraction, scaling, rotation, normalization, calculating distances, dot products, cross products, midpoints, and more with Point objects.
โโข Line Operations: Create lines, determine their slope, calculate y from x (and vice versa), and find the intersection points of two lines.
โโข Vector Operations: Perform vector addition, subtraction, multiplication, division, negation, perpendicular vector calculation, floor, fractional part, sine, absolute value, modulus, sign, round, scaling, rescaling, rotation, and ceiling operations.
โโข Angle Calculations: Compute angles between points in degrees or radians, including signed, unsigned, and 360-degree angles.
โโข Polygon Analysis: Calculate the area, perimeter, and centroid of polygons. Check if a point is inside a given polygon and determine the convex hull perimeter.
โโข Chart Plotting: Conveniently convert Point objects to chart.point objects for plotting lines and points on the chart. The library also includes functions for plotting lines between individual and series of points.
โโข Utility Functions: Includes helper functions such as square root, square, cosine, sine, tangent, arc cosine, arc sine, arc tangent, atan2, absolute distance, golden ratio tolerance check, fractional part, and safe index/check for chart plotting boundaries.
โโ HOW TO USE
1 โ Include the library in your script using:
import kaigouthro/geo/1
2 โ Create Point and Line objects:
p1 = geo.Point(bar_index, close)
p2 = geo.Point(bar_index , open)
myLine = geo.Line(p1, geo.slope(p1, p2))
// maybe use that line to detect a crossing for an alert ... hmmm
3 โ Utilize the provided functions:
distance = geo.distance(p1, p2)
intersection = geo.intersection(line1, line2)
4 โ For plotting labels, lines, convert Point to chart.point :
label.new(p1.to_chart_point(), " Hi ")
line.new(p1.to_chart_point(),p2.to_chart_point())
โโ NOTES
This description provides a concise overview. Consult the library's source code for in-depth documentation, including detailed descriptions, parameter types, and return values for each function and method. The source code is structured with comprehensive comments using the `//@` format for seamless integration with TradingView's auto-documentation features.
โโ Possibilities..
Library "geo"
This library provides a comprehensive set of geometric functions and types, including point and line manipulation, vector operations, angle calculations, and polygon analysis. It offers tools for creating, transforming, and analyzing geometric shapes and their relationships.
sqrt(value)
โโSquare root function
โโParameters:
โโโโ value (float) : (float) - The number to take the square root of
โโReturns: (float) - The square root of the input value
sqr(x)
โโSquare function
โโParameters:
โโโโ x (float) : (float) - The number to square
โโReturns: (float) - The square of the input value
cos(v)
โโCosine function
โโParameters:
โโโโ v (float) : (series float) - The value to find the cosine of
โโReturns: (series float) - The cosine of the input value
sin(v)
โโSine function
โโParameters:
โโโโ v (float) : (series float) - The value to find the sine of
โโReturns: (series float) - The sine of the input value
tan(v)
โโTangent function
โโParameters:
โโโโ v (float) : (series float) - The value to find the tangent of
โโReturns: (series float) - The tangent of the input value
acos(v)
โโArc cosine function
โโParameters:
โโโโ v (float) : (series float) - The value to find the arc cosine of
โโReturns: (series float) - The arc cosine of the input value
asin(v)
โโArc sine function
โโParameters:
โโโโ v (float) : (series float) - The value to find the arc sine of
โโReturns: (series float) - The arc sine of the input value
atan(v)
โโArc tangent function
โโParameters:
โโโโ v (float) : (series float) - The value to find the arc tangent of
โโReturns: (series float) - The arc tangent of the input value
atan2(dy, dx)
โโatan2 function
โโParameters:
โโโโ dy (float) : (float) - The y-coordinate
โโโโ dx (float) : (float) - The x-coordinate
โโReturns: (float) - The angle in radians
gap(_value1, __value2)
โโAbsolute distance between any two float values
โโParameters:
โโโโ _value1 (float) : First value
โโโโ __value2 (float)
โโReturns: Absolute Positive Distance
phi_tol(a, b, tolerance)
โโCheck if the ratio is within the tolerance of the golden ratio
โโParameters:
โโโโ a (float) : (float) The first number
โโโโ b (float) : (float) The second number
โโโโ tolerance (float) : (float) The tolerance percennt as 1 = 1 percent
โโReturns: (bool) True if the ratio is within the tolerance, false otherwise
frac(x)
โโfrad Fractional
โโParameters:
โโโโ x (float) : (float) - The number to convert to fractional
โโReturns: (float) - The number converted to fractional
safeindex(x, limit)
โโlimiting int to hold the value within the chart range
โโParameters:
โโโโ x (float) : (float) - The number to limit
โโโโ limit (int)
โโReturns: (int) - The number limited to the chart range
safecheck(x, limit)
โโlimiting int check if within the chartplottable range
โโParameters:
โโโโ x (float) : (float) - The number to limit
โโโโ limit (int)
โโReturns: (int) - The number limited to the chart range
interpolate(a, b, t)
โโinterpolate between two values
โโParameters:
โโโโ a (float) : (float) - The first value
โโโโ b (float) : (float) - The second value
โโโโ t (float) : (float) - The interpolation factor (0 to 1)
โโReturns: (float) - The interpolated value
gcd(_numerator, _denominator)
โโGreatest common divisor of two integers
โโParameters:
โโโโ _numerator (int)
โโโโ _denominator (int)
โโReturns: (int) The greatest common divisor
method set_x(self, value)
โโSet the x value of the point, and pass point for chaining
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point to modify
โโโโ value (float) : (float) The new x-coordinate
method set_y(self, value)
โโSet the y value of the point, and pass point for chaining
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point to modify
โโโโ value (float) : (float) The new y-coordinate
method get_x(self)
โโGet the x value of the point
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point to get the x-coordinate from
โโReturns: (float) The x-coordinate
method get_y(self)
โโGet the y value of the point
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point to get the y-coordinate from
โโReturns: (float) The y-coordinate
method vmin(self)
โโLowest element of the point
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point
โโReturns: (float) The lowest value between x and y
method vmax(self)
โโHighest element of the point
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The point
โโReturns: (float) The highest value between x and y
method add(p1, p2)
โโAddition
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (Point) - the add of the two points
method sub(p1, p2)
โโSubtraction
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (Point) - the sub of the two points
method mul(p, scalar)
โโMultiplication by scalar
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point
โโโโ scalar (float) : (float) - The scalar to multiply by
โโReturns: (Point) - the multiplied point of the point and the scalar
method div(p, scalar)
โโDivision by scalar
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point
โโโโ scalar (float) : (float) - The scalar to divide by
โโReturns: (Point) - the divided point of the point and the scalar
method rotate(p, angle)
โโRotate a point around the origin by an angle (in degrees)
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to rotate
โโโโ angle (float) : (float) - The angle to rotate by in degrees
โโReturns: (Point) - the rotated point
method length(p)
โโLength of the vector from origin to the point
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point
โโReturns: (float) - the length of the point
method length_squared(p)
โโLength squared of the vector
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) The point
โโReturns: (float) The squared length of the point
method normalize(p)
โโNormalize the point to a unit vector
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to normalize
โโReturns: (Point) - the normalized point
method dot(p1, p2)
โโDot product
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (float) - the dot of the two points
method cross(p1, p2)
โโCross product result (in 2D, this is a scalar)
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (float) - the cross of the two points
method distance(p1, p2)
โโDistance between two points
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (float) - the distance of the two points
method Point(x, y, a, v)
โโPoint Create Convenience
โโNamespace types: series float, simple float, input float, const float
โโParameters:
โโโโ x (float)
โโโโ y (float)
โโโโ a (float)
โโโโ v (float)
โโReturns: (Point) new point
method angle(p1, p2)
โโAngle between two points in degrees
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (float) - the angle of the first point and the second point
method angle_between(p, pivot, other)
โโAngle between two points in degrees from a pivot point
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to calculate the angle from
โโโโ pivot (Point) : (Point) - The pivot point
โโโโ other (Point) : (Point) - The other point
โโReturns: (float) - the angle between the two points
method translate(p, from_origin, to_origin)
โโTranslate a point from one origin to another
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to translate
โโโโ from_origin (Point) : (Point) - The origin to translate from
โโโโ to_origin (Point) : (Point) - The origin to translate to
โโReturns: (Point) - the translated point
method midpoint(p1, p2)
โโMidpoint of two points
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (Point) - The midpoint of the two points
method rotate_around(p, angle, pivot)
โโRotate a point around a pivot point by an angle (in degrees)
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to rotate
โโโโ angle (float) : (float) - The angle to rotate by in degrees
โโโโ pivot (Point) : (Point) - The pivot point to rotate around
โโReturns: (Point) - the rotated point
method multiply(_a, _b)
โโMultiply vector _a with _b
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (Point) The result of the multiplication
method divide(_a, _b)
โโDivide vector _a by _b
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (Point) The result of the division
method negate(_a)
โโNegative of vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to negate
โโReturns: (Point) The negated point
method perp(_a)
โโPerpendicular Vector of _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The perpendicular point
method vfloor(_a)
โโCompute the floor of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The floor of the point
method fractional(_a)
โโCompute the fractional part of the elements from vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The fractional part of the point
method vsin(_a)
โโCompute the sine of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The sine of the point
lcm(a, b)
โโLeast common multiple of two integers
โโParameters:
โโโโ a (int) : (int) The first integer
โโโโ b (int) : (int) The second integer
โโReturns: (int) The least common multiple
method vabs(_a)
โโCompute the absolute of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The absolute of the point
method vmod(_a, _b)
โโCompute the mod of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโโโ _b (float) : (float) The mod
โโReturns: (Point) The mod of the point
method vsign(_a)
โโCompute the sign of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The sign of the point
method vround(_a)
โโCompute the round of argument vector _a
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (Point) The round of the point
method normalize_y(p, height)
โโnormalizes the y value of a point to an input height
โโNamespace types: Point
โโParameters:
โโโโ p (Point) : (Point) - The point to normalize
โโโโ height (float) : (float) - The height to normalize to
โโReturns: (Point) - the normalized point
centroid(points)
โโCalculate the centroid of multiple points
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (Point) The centroid point
random_point(_height, _width, _origin, _centered)
โโRandom Point in a given height and width
โโParameters:
โโโโ _height (float) : (float) The height of the area to generate the point in
โโโโ _width (float) : (float) The width of the area to generate the point in
โโโโ _origin (Point) : (Point) The origin of the area to generate the point in (default: na, will create a Point(0, 0))
โโโโ _centered (bool) : (bool) Center the origin point in the area, otherwise, positive h/w (default: false)
โโReturns: (Point) The random point in the given area
random_point_array(_origin, _height, _width, _centered, _count)
โโRandom Point Array in a given height and width
โโParameters:
โโโโ _origin (Point) : (Point) The origin of the area to generate the array (default: na, will create a Point(0, 0))
โโโโ _height (float) : (float) The height of the area to generate the array
โโโโ _width (float) : (float) The width of the area to generate the array
โโโโ _centered (bool) : (bool) Center the origin point in the area, otherwise, positive h/w (default: false)
โโโโ _count (int) : (int) The number of points to generate (default: 50)
โโReturns: (array) The random point array in the given area
method sort_points(points, by_x)
โโSorts an array of points by x or y coordinate
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points to sort
โโโโ by_x (bool) : (bool) Whether to sort by x-coordinate (true) or y-coordinate (false)
โโReturns: (array) The sorted array of points
method equals(_a, _b)
โโCompares two points for equality
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (bool) True if the points are equal, false otherwise
method max(origin, _a, _b)
โโMaximum of two points from origin, using dot product
โโNamespace types: Point
โโParameters:
โโโโ origin (Point)
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (Point) The maximum point
method min(origin, _a, _b)
โโMinimum of two points from origin, using dot product
โโNamespace types: Point
โโParameters:
โโโโ origin (Point)
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (Point) The minimum point
method avg_x(points)
โโAverage x of point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The average x-coordinate
method avg_y(points)
โโAverage y of point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The average y-coordinate
method range_x(points)
โโRange of x values in point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The range of x-coordinates
method range_y(points)
โโRange of y values in point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The range of y-coordinates
method max_x(points)
โโmax of x values in point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The max of x-coordinates
method min_y(points)
โโmin of x values in point array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (float) The min of x-coordinates
method scale(_a, _scalar)
โโScale a point by a scalar
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to scale
โโโโ _scalar (float) : (float) The scalar value
โโReturns: (Point) The scaled point
method rescale(_a, _length)
โโRescale a point to a new magnitude
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to rescale
โโโโ _length (float) : (float) The new magnitude
โโReturns: (Point) The rescaled point
method rotate_rad(_a, _radians)
โโRotate a point by an angle in radians
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to rotate
โโโโ _radians (float) : (float) The angle in radians
โโReturns: (Point) The rotated point
method rotate_degree(_a, _degree)
โโRotate a point by an angle in degrees
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to rotate
โโโโ _degree (float) : (float) The angle in degrees
โโReturns: (Point) The rotated point
method vceil(_a, _digits)
โโCeil a point to a certain number of digits
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to ceil
โโโโ _digits (int) : (int) The number of digits to ceil to
โโReturns: (Point) The ceiled point
method vpow(_a, _exponent)
โโRaise both point elements to a power
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโโโ _exponent (float) : (float) The exponent
โโReturns: (Point) The point with elements raised to the power
method perpendicular_distance(_a, _b, _c)
โโDistance from point _a to line between _b and _c
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโโโ _b (Point) : (Point) The start point of the line
โโโโ _c (Point) : (Point) The end point of the line
โโReturns: (float) The perpendicular distance
method project(_a, _axis)
โโProject a point onto another
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to project
โโโโ _axis (Point) : (Point) The point to project onto
โโReturns: (Point) The projected point
method projectN(_a, _axis)
โโProject a point onto a point of unit length
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to project
โโโโ _axis (Point) : (Point) The unit length point to project onto
โโReturns: (Point) The projected point
method reflect(_a, _axis)
โโReflect a point on another
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to reflect
โโโโ _axis (Point) : (Point) The point to reflect on
โโReturns: (Point) The reflected point
method reflectN(_a, _axis)
โโReflect a point to an arbitrary axis
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to reflect
โโโโ _axis (Point) : (Point) The axis to reflect to
โโReturns: (Point) The reflected point
method angle_rad(_a)
โโAngle in radians of a point
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point
โโReturns: (float) The angle in radians
method angle_unsigned(_a, _b)
โโUnsigned degree angle between 0 and +180 by given two points
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (float) The unsigned angle in degrees
method angle_signed(_a, _b)
โโSigned degree angle between -180 and +180 by given two points
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (float) The signed angle in degrees
method angle_360(_a, _b)
โโDegree angle between 0 and 360 by given two points
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The first point
โโโโ _b (Point) : (Point) The second point
โโReturns: (float) The angle in degrees (0-360)
method clamp(_a, _vmin, _vmax)
โโRestricts a point between a min and max value
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The point to restrict
โโโโ _vmin (Point) : (Point) The minimum point
โโโโ _vmax (Point) : (Point) The maximum point
โโReturns: (Point) The restricted point
method lerp(_a, _b, _rate_of_move)
โโLinearly interpolates between points a and b by _rate_of_move
โโNamespace types: Point
โโParameters:
โโโโ _a (Point) : (Point) The starting point
โโโโ _b (Point) : (Point) The ending point
โโโโ _rate_of_move (float) : (float) The rate of movement (0-1)
โโReturns: (Point) The interpolated point
method slope(p1, p2)
โโSlope of a line between two points
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโReturns: (float) - The slope of the line
method gety(self, x)
โโGet y-coordinate of a point on the line given its x-coordinate
โโNamespace types: Line
โโParameters:
โโโโ self (Line) : (Line) - The line
โโโโ x (float) : (float) - The x-coordinate
โโReturns: (float) - The y-coordinate
method getx(self, y)
โโGet x-coordinate of a point on the line given its y-coordinate
โโNamespace types: Line
โโParameters:
โโโโ self (Line) : (Line) - The line
โโโโ y (float) : (float) - The y-coordinate
โโReturns: (float) - The x-coordinate
method intersection(self, other)
โโIntersection point of two lines
โโNamespace types: Line
โโParameters:
โโโโ self (Line) : (Line) - The first line
โโโโ other (Line) : (Line) - The second line
โโReturns: (Point) - The intersection point
method calculate_arc_point(self, b, p3)
โโCalculate a point on the arc defined by three points
โโNamespace types: Point
โโParameters:
โโโโ self (Point) : (Point) The starting point of the arc
โโโโ b (Point) : (Point) The middle point of the arc
โโโโ p3 (Point) : (Point) The end point of the arc
โโReturns: (Point) A point on the arc
approximate_center(point1, point2, point3)
โโApproximate the center of a spiral using three points
โโParameters:
โโโโ point1 (Point) : (Point) The first point
โโโโ point2 (Point) : (Point) The second point
โโโโ point3 (Point) : (Point) The third point
โโReturns: (Point) The approximate center point
createEdge(center, radius, angle)
โโGet coordinate from center by radius and angle
โโParameters:
โโโโ center (Point) : (Point) - The center point
โโโโ radius (float) : (float) - The radius of the circle
โโโโ angle (float) : (float) - The angle in degrees
โโReturns: (Point) - The coordinate on the circle
getGrowthFactor(p1, p2, p3)
โโGet growth factor of spiral point
โโParameters:
โโโโ p1 (Point) : (Point) - The first point
โโโโ p2 (Point) : (Point) - The second point
โโโโ p3 (Point) : (Point) - The third point
โโReturns: (float) - The growth factor
method to_chart_point(point)
โโConvert Point to chart.point using chart.point.from_index(safeindex(point.x), point.y)
โโNamespace types: Point
โโParameters:
โโโโ point (Point) : (Point) - The point to convert
โโReturns: (chart.point) - The chart.point representation of the input point
method plotline(p1, p2, col, width)
โโDraw a line from p1 to p2
โโNamespace types: Point
โโParameters:
โโโโ p1 (Point) : (Point) First point
โโโโ p2 (Point) : (Point) Second point
โโโโ col (color)
โโโโ width (int)
โโReturns: (line) Line object
method drawlines(points, col, ignore_boundary)
โโDraw lines between points in an array
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโโโ col (color) : (color) The color of the lines
โโโโ ignore_boundary (bool) : (bool) The color of the lines
method to_chart_points(points)
โโDraw an array of points as chart points on the chart with line.new(chartpoint1, chartpoint2, color=linecolor)
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) - The points to draw
โโReturns: (array) The array of chart points
polygon_area(points)
โโCalculate the area of a polygon defined by an array of points
โโParameters:
โโโโ points (array) : (array) The array of points representing the polygon vertices
โโReturns: (float) The area of the polygon
polygon_perimeter(points)
โโCalculate the perimeter of a polygon
โโParameters:
โโโโ points (array) : (array) Array of points defining the polygon
โโReturns: (float) Perimeter of the polygon
is_point_in_polygon(point, _polygon)
โโCheck if a point is inside a polygon
โโParameters:
โโโโ point (Point) : (Point) The point to check
โโโโ _polygon (array)
โโReturns: (bool) True if the point is inside the polygon, false otherwise
method perimeter(points)
โโCalculates the convex hull perimeter of a set of points
โโNamespace types: array
โโParameters:
โโโโ points (array) : (array) The array of points
โโReturns: (array) The array of points forming the convex hull perimeter
Point
โโA Point, can be used for vector, floating calcs, etc. Use the cp method for plots
โโFields:
โโโโ x (series float) : (float) The x-coordinate
โโโโ y (series float) : (float) The y-coordinate
โโโโ a (series float) : (float) An Angle storage spot
โโโโ v (series float) : (float) A Value
Line
โโLine
โโFields:
โโโโ point (Point) : (Point) The starting point of the line
โโโโ slope (series float) : (float) The slope of the line
GOMTRY.
lib_statemachine_modifiedLibrary "lib_statemachine_modified"
Modified to fix bugs and create getState and priorState methods.
method step(this, before, after, condition)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
โโโโ before (int) : (int): Current state before transition
โโโโ after (int) : (int): State to transition to
โโโโ condition (bool) : (bool): Condition to trigger the transition
โโReturns: (bool): True if the state changed, else False
method step(this, after, condition)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
โโโโ after (int) : (int): State to transition to
โโโโ condition (bool) : (bool): Condition to trigger the transition
โโReturns: (bool): True if the state changed, else False
method currentState(this)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
method previousState(this)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
method changed(this, within_bars)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
โโโโ within_bars (int) : (int): Number of bars to look back for a state change
โโReturns: (bool): True if a state change occurred within the timeframe, else False
method reset(this, condition, min_occurrences)
โโNamespace types: StateMachine
โโParameters:
โโโโ this (StateMachine)
โโโโ condition (bool) : (bool): Condition to trigger the reset
โโโโ min_occurrences (int) : (int): Minimum number of times the condition must be true to reset
โโReturns: (bool): True if the state was reset, else False
StateMachine
โโFields:
โโโโ state (series int)
โโโโ neutral (series int)
โโโโ enabled (series bool)
โโโโ reset_counter (series int)
โโโโ prior_state (series int)
โโโโ last_change_bar (series int)
KwakPineHelperLibrary "KwakPineHelper"
TODO: add library description here
fun(x)
โโTODO: add function description here
โโParameters:
โโโโ x (float) : TODO: add parameter x description here
โโReturns: TODO: add what function returns
all_opentrades_size()
โโget all opentrades size
โโReturns: (float) size
recent_opentrade_profit()
โโget recent opentrade profit
โโReturns: (float) profit
all_opentrades_profit()
โโget all opentrades profit
โโReturns: (float) profit
recent_closedtrade_profit()
โโget recent closedtrade profit
โโReturns: (float) profit
recent_opentrade_max_runup()
โโget recent opentrade max runup
โโReturns: (float) runup
recent_closedtrade_max_runup()
โโget recent closedtrade max runup
โโReturns: (float) runup
recent_opentrade_max_drawdown()
โโget recent opentrade maxdrawdown
โโReturns: (float) mdd
recent_closedtrade_max_drawdown()
โโget recent closedtrade maxdrawdown
โโReturns: (float) mdd
max_open_trades_drawdown()
โโget max open trades drawdown
โโReturns: (float) mdd
recent_opentrade_commission()
โโget recent opentrade commission
โโReturns: (float) commission
recent_closedtrade_commission()
โโget recent closedtrade commission
โโReturns: (float) commission
qty_by_percent_of_equity(percent)
โโget qty by percent of equtiy
โโParameters:
โโโโ percent (float) : (series float) percent that you want to set
โโReturns: (float) quantity
qty_by_percent_of_position_size(percent)
โโget size by percent of position size
โโParameters:
โโโโ percent (float) : (series float) percent that you want to set
โโReturns: (float) size
is_day_change()
โโget bool change of day
โโReturns: (bool) day is change or not
is_in_trade(numberOfBars)
โโget bool using number of bars
โโParameters:
โโโโ numberOfBars (int)
โโReturns: (bool) allowedToTrade
api_msg_system(chat_id, message)
โโParameters:
โโโโ chat_id (string)
โโโโ message (string)
is_first_day()
โโCheck if today is the first day
โโReturns: (bool) true if today is the first day, false otherwise
is_last_day()
โโCheck if today is the last day
โโReturns: (bool) true if today is the last day, false otherwise
is_entry()
โโCheck if trade is open
โโReturns: (bool) true if trade is open, false otherwise
is_close()
โโCheck if trade is closed
โโReturns: (bool) true if trade is closed, false otherwise
is_win()
โโCheck if trade is win
โโReturns: (bool) true if trade is win, false otherwise
is_loss()
โโCheck if trade is loss
โโReturns: (bool) true if trade is loss, false otherwise
permutationโโ OVERVIEW
This library provides functions for generating permutations of string or float arrays, using an iterative approach where pine has no recursion. It supports allowing/limiting duplicate elements and handles large result sets by segmenting them into manageable chunks within custom Data types. The most combinations will vary, but the highest is around 250,000 unique combinations. depending on input array values and output length. it will return nothing if the input count is too low.
โโ CONCEPTS
This library addresses two key challenges in Pine Script:
โโขย Recursion Depth Limits: Pine has limitations on recursion depth. This library uses an iterative, stack-based algorithm to generate permutations, avoiding recursive function calls that could exceed these limits.
โโขย Array Size Limits: Pine arrays have size restrictions. This library manages large permutation sets by dividing them into smaller segments stored within a custom Data or DataFloat type, using maps for efficient access.
โโ HOW TO USE
1 โ Include the Library: Add this library to your script using:
import kaigouthro/permutation/1 as permute
2 โ Call the generatePermutations Function:
stringPermutations = permute.generatePermutations(array.from("a", "b", "c"), 2, 1)
floatPermutations = permute.generatePermutations(array.from(1.0, 2.0, 3.0), 2, 1)
โโข set : The input array of strings or floats.
โโข size : The desired length of each permutation.
โโข maxDuplicates (optional): The maximum allowed repetitions of an element within a single permutation. Defaults to 1.
3 โ Access the Results: The function returns a Data (for strings) or DataFloat (for floats) object. These objects contain:
โโขย data : An array indicating which segments are present (useful for iterating).
โโขย segments : A map where keys represent segment indices and values are the actual permutation data within that segment.
Example: Accessing Permutations
for in stringPermutations.segments
for in currentSegment.segments
// Access individual permutations within the segment.
permutation = segmennt.data
for item in permutation
// Use the permutation elements...
โโ TYPES
โโขย PermutationState / PermutationStateFloat : Internal types used by the iterative algorithm to track the state of permutation generation.
โโขย Data / DataFloat : Custom types to store and manage the generated permutations in segments.
โโ NOTES
* The library prioritizes handling potentially large permutation sets. 250,000 i about the highest achievable.
* The segmentation logic ensures that results are accessible even when the total number of permutations exceeds Pine's array size limits.
----
Library "permutation"
This library provides functions for generating permutations of user input arrays containing either strings or floats. It uses an iterative, stack-based approach to handle potentially large sets and avoid recursion limitation. The library supports limiting the number of duplicate elements allowed in each permutation. Results are stored in a custom Data or DataFloat type that uses maps to segment large permutation sets into manageable chunks, addressing Pine Script's array size limitations.
generatePermutations(set, size, maxDuplicates)
โโ> Generates permutations of a given size from a set of strings or floats.
โโParameters:
โโโโ set (array) : (array or array) The set of strings or floats to generate permutations from.
โโโโ size (int) : (int) The size of the permutations to generate.
โโโโ maxDuplicates (int) : (int) The maximum number of times an element can be repeated in a permutation.
โโReturns: (Data or DataFloat) A Data object for strings or a DataFloat object for floats, containing the generated permutations.
stringPermutations = generatePermutations(array.from("a", "b", "c"), 2, 1)
floatPermutations = generatePermutations(array.from(1.0, 2.0, 3.0), 2, 1)
generatePermutations(set, size, maxDuplicates)
โโParameters:
โโโโ set (array)
โโโโ size (int)
โโโโ maxDuplicates (int)
PermutationState
โโPermutationState
โโFields:
โโโโ data (array) : (array) The current permutation being built.
โโโโ index (series int) : (int) The current index being considered in the set.
โโโโ depth (series int) : (int) The current depth of the permutation (number of elements).
โโโโ counts (map) : (map) Map to track the count of each element in the current permutation (for duplicates).
PermutationStateFloat
โโPermutationStateFloat
โโFields:
โโโโ data (array) : (array) The current permutation being built.
โโโโ index (series int) : (int) The current index being considered in the set.
โโโโ depth (series int) : (int) The current depth of the permutation (number of elements).
โโโโ counts (map) : (map) Map to track the count of each element in the current permutation (for duplicates).
Data
โโData
โโFields:
โโโโ data (array) : (array) Array to indicate which segments are present.
โโโโ segments (map) : (map) Map to store permutation segments. Each segment contains a subset of the generated permutations.
DataFloat
โโDataFloat
โโFields:
โโโโ data (array) : (array) Array to indicate which segments are present.
โโโโ segments (map) : (map) Map to store permutation segments. Each segment contains a subset of the generated permutations.
random_valuesโโ OVERVIEW
This library provides helper functions for generating random values of various types, including numbers, letters, words, booleans, and arrays. It simplifies the creation of random data within Pine Scriptโข for testing, simulations, or other applications.
โโ HOW TO USE
Import the library into your script:
import kaigouthro/random_values/1 as rv
Then, use the functions provided:
// Get a random integer between 5 and 15
int randInt = rv.intVal(5, 15)
// Generate a random word with 8 characters
string randWord = rv.word(8)
// Create a boolean array with 5 elements
array randBoolArray = rv.boolArray(5)
// And other options! See below for details.
โโ FEATURES
โโข num(float min, float max) : Returns a random float between *min* and *max*. (Internal helper function, not exported).
โโข letter() : Returns a random lowercase letter (a-z).
โโข word(int size = 0) : Returns a random word. *size* specifies the length (default: random length between 3 and 10).
โโข words(int size = 20) : Returns a string of random words separated by spaces, where *size* specifies the number of words.
โโข boolVal() : Returns a random boolean (true or false).
โโข floatVal(float min = 0, float max = 100, int precision = 2) : Returns a random float with specified *min*, *max*, and *precision*.
โโข intVal(int min = 1, int max = 100) : Returns a random integer between *min* and *max*.
โโข stringArray(int size = 0) : Returns an array of random words. *size* specifies the array length (default: random between 3 and 10).
โโข floatArray(int size = 0, float min = 0, float max = 100, int precision = 2) : Returns an array of random floats with specified parameters. *size* determines the array length.
โโข intArray(int size = 0, int min = 1, int max = 100) : Returns an array of random integers with specified parameters. *size* determines the array length.
โโข boolArray(int size = 0) : Returns an array of random booleans. *size* specifies the array length (default: random between 3 and 10).
โโ NOTES
* This library uses the `kaigouthro/into/2` library for type conversions. Make sure it's available.
* Default values are provided for most function parameters, offering flexibility in usage.
โโ LICENSE
This Pine Scriptโข code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
```
**Changes and Rationale:**
* **OVERVIEW:** Clearly states the library's purpose.
* **HOW TO USE:** Provides essential import and usage instructions with Pine Scriptโข examples.
* **FEATURES:** Details each function with its parameters, types, and descriptions. Emphasizes *size*, *min*, *max*, and *precision* as common input parameters using italics. Uses custom bulleted lists.
* **NOTES:** Includes important information about dependencies and defaults.
* **LICENSE:** Directly links to the license URL using the proper ` ` tag.
* **Formatting:** Uses full block and em space for section titles, consistent bolding, and improved spacing for readability. Removes unnecessary blank lines.
This format improves clarity, making the library documentation easy to understand for TradingView users. Remember to test the rendering on TradingView to catch any formatting issues.
Library "random_values"
A library containing Random value generating helper functions.
letter()
โโRandom letter generator.
โโReturns: (string) A random lowercase letter.
word(size)
โโRandom word generator.
โโParameters:
โโโโ size (int) : (int) The desired length of the word. If 0 or not provided, a random length between 3 and 10 is used.
โโReturns: (string) A random word.
words(size)
โโRandom words generator.
โโParameters:
โโโโ size (int) : (int) The number of words to generate. If 0 or not provided, a random number between 3 and 10 is used.
โโReturns: (string) A string of random words separated by spaces.
boolVal()
โโRandom boolean generator.
โโReturns: (bool) A random boolean value (true or false).
floatVal(min, max, precision)
โโRandom float number generator.
โโParameters:
โโโโ min (float) : (float) The minimum float value. Defaults to 0.
โโโโ max (float) : (float) The maximum float value. Defaults to 100.
โโโโ precision (int) : (int) The number of decimal places. Defaults to 2.
โโReturns: (float) A random float number.
intVal(min, max)
โโRandom integer number generator.
โโParameters:
โโโโ min (int) : (int) The minimum integer value. Defaults to 1.
โโโโ max (int) : (int) The maximum integer value. Defaults to 100.
โโReturns: (int) A random integer number.
stringArray(size)
โโRandom string array generator.
โโParameters:
โโโโ size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
โโReturns: (array) An array of random words.
floatArray(size, min, max, precision)
โโRandom float array generator.
โโParameters:
โโโโ size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
โโโโ min (float) : (float) The minimum float value. Defaults to 0.
โโโโ max (float) : (float) The maximum float value. Defaults to 100.
โโโโ precision (int) : (int) The number of decimal places. Defaults to 2.
โโReturns: (array) An array of random float numbers.
intArray(size, min, max)
โโRandom integer array generator.
โโParameters:
โโโโ size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
โโโโ min (int) : (int) The minimum integer value. Defaults to 1.
โโโโ max (int) : (int) The maximum integer value. Defaults to 100.
โโReturns: (array) An array of random integer numbers.
boolArray(size)
โโRandom boolean array generator.
โโParameters:
โโโโ size (int) : (int) The desired size of the array. If 0 or not provided, a random size between 3 and 10 is used.
โโReturns: (array) An array of random boolean values.
metaconnectorLibrary "metaconnector"
metaconnector
buy_market_order(License_ID, symbol, lot)
โโPlaces a buy market order
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to buy
โโReturns: String syntax for the buy market order
sell_market_order(License_ID, symbol, lot)
โโPlaces a sell market order
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to sell
โโReturns: String syntax for the sell market order
buy_limit_order(License_ID, symbol, lot, price)
โโPlaces a buy limit order
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to buy
โโโโ price (float) : Limit price for the order
โโReturns: String syntax for the buy limit order
sell_limit_order(License_ID, symbol, lot, price)
โโPlaces a sell limit order
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to sell
โโโโ price (float) : Limit price for the order
โโReturns: String syntax for the sell limit order
stoploss_for_buy_order(License_ID, symbol, lot, stoploss_price)
โโPlaces a stop-loss order for a buy position
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to buy
โโโโ stoploss_price (float)
โโReturns: String syntax for the buy stop-loss order
stoploss_for_sell_order(License_ID, symbol, lot, stoploss_price)
โโPlaces a stop-loss order for a sell position
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to sell
โโโโ stoploss_price (float)
โโReturns: String syntax for the sell stop-loss order
takeprofit_for_buy_order(License_ID, symbol, lot, target_price)
โโPlaces a take-profit order for a buy position
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to buy
โโโโ target_price (float)
โโReturns: String syntax for the buy take-profit order
takeprofit_for_sell_order(License_ID, symbol, lot, target_price)
โโPlaces a take-profit order for a sell position
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to sell
โโโโ target_price (float)
โโReturns: String syntax for the sell take-profit order
buy_stop_order(License_ID, symbol, lot, price)
โโPlaces a buy stop order above the current market price
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to buy
โโโโ price (float) : Stop order price
โโReturns: String syntax for the buy stop order
sell_stop_order(License_ID, symbol, lot, price)
โโPlaces a sell stop order below the current market price
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to sell
โโโโ price (float) : Stop order price
โโReturns: String syntax for the sell stop order
close_all_positions(License_ID, symbol)
โโCloses all positions for a specific symbol
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโReturns: String syntax for closing all positions
close_buy_positions(License_ID, symbol)
โโCloses all buy positions for a specific symbol
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโReturns: String syntax for closing all buy positions
close_sell_positions(License_ID, symbol)
โโCloses all sell positions for a specific symbol
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโReturns: String syntax for closing all sell positions
close_partial_buy_position(License_ID, symbol, lot)
โโCloses a partial buy position for a specific symbol
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to close
โโReturns: String syntax for closing a partial buy position
close_partial_sell_position(License_ID, symbol, lot)
โโCloses a partial sell position for a specific symbol
โโParameters:
โโโโ License_ID (string) : Unique license ID of the user
โโโโ symbol (string) : Trading symbol
โโโโ lot (int) : Number of lots to close
โโReturns: String syntax for closing a partial sell position
Requestโ โ OVERVIEW
This library is a tool for Pine Scriptโข programmers that consolidates access to a wide range of lesser-known data feeds available on TradingView, including metrics from the FRED database, FINRA short sale volume, open interest, and COT data. The functions in this library simplify requests for these data feeds, making them easier to retrieve and use in custom scripts.
โ โ CONCEPTS
Federal Reserve Economic Data (FRED)
FRED (Federal Reserve Economic Data) is a comprehensive online database curated by the Federal Reserve Bank of St. Louis. It provides free access to extensive economic and financial data from U.S. and international sources. FRED includes numerous economic indicators such as GDP, inflation, employment, and interest rates. Additionally, it provides financial market data, regional statistics, and international metrics such as exchange rates and trade balances.
Sourced from reputable organizations, including U.S. government agencies, international institutions, and other public and private entities, FRED enables users to analyze over 825,000 time series, download their data in various formats, and integrate their information into analytical tools and programming workflows.
On TradingView, FRED data is available from ticker identifiers with the "FRED:" prefix. Users can search for FRED symbols in the "Symbol Search" window, and Pine scripts can retrieve data for these symbols via `request.*()` function calls.
FINRA Short Sale Volume
FINRA (the Financial Industry Regulatory Authority) is a non-governmental organization that supervises and regulates U.S. broker-dealers and securities professionals. Its primary aim is to protect investors and ensure integrity and transparency in financial markets.
FINRA's Short Sale Volume data provides detailed information about daily short-selling activity across U.S. equity markets. This data tracks the volume of short sales reported to FINRA's trade reporting facilities (TRFs), including shares sold on FINRA-regulated Alternative Trading Systems (ATSs) and over-the-counter (OTC) markets, offering transparent access to short-selling information not typically available from exchanges. This data helps market participants, researchers, and regulators monitor trends in short-selling and gain insights into bearish sentiment, hedging strategies, and potential market manipulation. Investors often use this data alongside other metrics to assess stock performance, liquidity, and overall trading activity.
It is important to note that FINRA's Short Sale Volume data does not consolidate short sale information from public exchanges and excludes trading activity that is not publicly disseminated.
TradingView provides ticker identifiers for requesting Short Sale Volume data with the format "FINRA:_SHORT_VOLUME", where "" is a supported U.S. equities symbol (e.g., "AAPL").
Open Interest (OI)
Open interest is a cornerstone indicator of market activity and sentiment in derivatives markets such as options or futures. In contrast to volume, which measures the number of contracts opened or closed within a period, OI measures the number of outstanding contracts that are not yet settled. This distinction makes OI a more robust indicator of how money flows through derivatives, offering meaningful insights into liquidity, market interest, and trends. Many traders and investors analyze OI alongside volume and price action to gain an enhanced perspective on market dynamics and reinforce trading decisions.
TradingView offers many ticker identifiers for requesting OI data with the format "_OI", where "" represents a derivative instrument's ticker ID (e.g., "COMEX:GC1!").
Commitment of Traders (COT)
Commitment of Traders data provides an informative weekly breakdown of the aggregate positions held by various market participants, including commercial hedgers, non-commercial speculators, and small traders, in the U.S. derivative markets. Tallied and managed by the Commodity Futures Trading Commission (CFTC) , these reports provide traders and analysts with detailed insight into an asset's open interest and help them assess the actions of various market players. COT data is valuable for gaining a deeper understanding of market dynamics, sentiment, trends, and liquidity, which helps traders develop informed trading strategies.
TradingView has numerous ticker identifiers that provide access to time series containing data for various COT metrics. To learn about COT ticker IDs and how they work, see our LibraryCOT publication.
โ โ USING THE LIBRARY
Common function characteristics
โโข This library's functions construct ticker IDs with valid formats based on their specified parameters, then use them as the `symbol` argument in request.security() to retrieve data from the specified context.
โโข Most of these functions automatically select the timeframe of a data request because the data feeds are not available for all timeframes.
โโข All the functions have two overloads. The first overload of each function uses values with the "simple" qualifier to define the requested context, meaning the context does not change after the first script execution. The second accepts "series" values, meaning it can request data from different contexts across executions.
โโข The `gaps` parameter in most of these functions specifies whether the returned data is `na` when a new value is unavailable for request. By default, its value is `false`, meaning the call returns the last retrieved data when no new data is available.
โโข The `repaint` parameter in applicable functions determines whether the request can fetch the latest unconfirmed values from a higher timeframe on realtime bars, which might repaint after the script restarts. If `false`, the function only returns confirmed higher-timeframe values to avoid repainting. The default value is `true`.
`fred()`
The `fred()` function retrieves the most recent value of a specified series from the Federal Reserve Economic Data (FRED) database. With this function, programmers can easily fetch macroeconomic indicators, such as GDP and unemployment rates, and use them directly in their scripts.
How it works
The function's `fredCode` parameter accepts a "string" representing the unique identifier of a specific FRED series. Examples include "GDP" for the "Gross Domestic Product" series and "UNRATE" for the "Unemployment Rate" series. Over 825,000 codes are available. To access codes for available series, search the FRED website .
The function adds the "FRED:" prefix to the specified `fredCode` to construct a valid FRED ticker ID (e.g., "FRED:GDP"), which it uses in request.security() to retrieve the series data.
Example Usage
This line of code requests the latest value from the Gross Domestic Product series and assigns the returned value to a `gdpValue` variable:
float gdpValue = fred("GDP")
`finraShortSaleVolume()`
The `finraShortSaleVolume()` function retrieves EOD data from a FINRA Short Sale Volume series. Programmers can call this function to retrieve short-selling information for equities listed on supported exchanges, namely NASDAQ, NYSE, and NYSE ARCA.
How it works
The `symbol` parameter determines which symbol's short sale volume information is retrieved by the function. If the value is na , the function requests short sale volume data for the chart's symbol. The argument can be the name of the symbol from a supported exchange (e.g., "AAPL") or a ticker ID with an exchange prefix ("NASDAQ:AAPL"). If the `symbol` contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", or "BATS".
The function constructs a ticker ID in the format "FINRA:ticker_SHORT_VOLUME", where "ticker" is the symbol name without the exchange prefix (e.g., "AAPL"). It then uses the ticker ID in request.security() to retrieve the available data.
Example Usage
This line of code retrieves short sale volume for the chart's symbol and assigns the result to a `shortVolume` variable:
float shortVolume = finraShortSaleVolume(syminfo.tickerid)
This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:
float shortVolume = finraShortSaleVolume("NASDAQ:AAPL")
`openInterestFutures()` and `openInterestCrypto()`
The `openInterestFutures()` function retrieves EOD open interest (OI) data for futures contracts. The `openInterestCrypto()` function provides more granular OI data for cryptocurrency contracts.
How they work
The `openInterestFutures()` function retrieves EOD closing OI information. Its design is focused primarily on retrieving OI data for futures, as only EOD OI data is available for these instruments. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe.
The `openInterestCrypto()` function retrieves opening, high, low, and closing OI data for a cryptocurrency contract on a specified timeframe. Unlike `openInterest()`, this function can also retrieve granular data from intraday timeframes.
Both functions contain a `symbol` parameter that determines the symbol for which the calls request OI data. The functions construct a valid OI ticker ID from the chosen symbol by appending "_OI" to the end (e.g., "CME:ES1!_OI").
The `openInterestFutures()` function requests and returns a two-element tuple containing the futures instrument's EOD closing OI and a "bool" condition indicating whether OI is rising.
The `openInterestCrypto()` function requests and returns a five-element tuple containing the cryptocurrency contract's opening, high, low, and closing OI, and a "bool" condition indicating whether OI is rising.
Example usage
This code line calls `openInterest()` to retrieve EOD OI and the OI rising condition for a futures symbol on the chart, assigning the values to two variables in a tuple:
= openInterestFutures(syminfo.tickerid)
This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:
= openInterestFutures("CME:ES1!")
This example uses `openInterestCrypto()` to retrieve OHLC OI data and the OI rising condition for a cryptocurrency contract on the chart, sampled at the chart's timeframe. It assigns the returned values to five variables in a tuple:
= openInterestCrypto(syminfo.tickerid, timeframe.period)
This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:
= openInterestCrypto("BINANCE:BTCUSDT.P", "1D")
`commitmentOfTraders()`
The `commitmentOfTraders()` function retrieves data from the Commitment of Traders (COT) reports published by the Commodity Futures Trading Commission (CFTC). This function significantly simplifies the COT request process, making it easier for programmers to access and utilize the available data.
How It Works
This function's parameters determine different parts of a valid ticker ID for retrieving COT data, offering a streamlined alternative to constructing complex COT ticker IDs manually. The `metricName`, `metricDirection`, and `includeOptions` parameters are required. They specify the name of the reported metric, the direction, and whether it includes information from options contracts.
The function also includes several optional parameters. The `CFTCCode` parameter allows programmers to request data for a specific report code. If unspecified, the function requests data based on the chart symbol's root prefix, base currency, or quoted currency, depending on the `mode` argument. The call can specify the report type ("Legacy", "Disaggregated", or "Financial") and metric type ("All", "Old", or "Other") with the `typeCOT` and `metricType` parameters.
Explore the CFTC website to find valid report codes for specific assets. To find detailed information about the metrics included in the reports and their meanings, see the CFTC's Explanatory Notes .
View the function's documentation below for detailed explanations of its parameters. For in-depth information about COT ticker IDs and more advanced functionality, refer to our previously published COT library .
Available metrics
Different COT report types provide different metrics . The tables below list all available metrics for each type and their applicable directions:
+------------------------------+------------------------+
| Legacy (โCOT) Metric Names | Directions |
+------------------------------+------------------------+
| Open Interest | No direction |
| Noncommercial Positions | Long, Short, Spreading |
| Commercial Positions | Long, Short |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No direction |
| Traders Noncommercial | Long, Short, Spreading |
| Traders Commercial | Long, Short |
| Traders Total Reportable | Long, Short |
| Concentration Gross โLT 4 TDR | Long, Short |
| Concentration Gross โLT 8 TDR | Long, Short |
| Concentration Net โLT 4 TDR | Long, Short |
| Concentration Net โLT 8 TDR | Long, Short |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names | Directions |
+-----------------------------------+------------------------+
| Open Interest | No Direction |
| Producer Merchant Positions | Long, Short |
| Swap Positions | Long, Short, Spreading |
| Managed Money Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Producer Merchant | Long, Short |
| Traders Swap | Long, Short, Spreading |
| Traders Managed Money | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names | Directions |
+-------------------------------+------------------------+
| Open Interest | No Direction |
| Dealer Positions | Long, Short, Spreading |
| Asset Manager Positions | Long, Short, Spreading |
| Leveraged Funds Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Dealer | Long, Short, Spreading |
| Traders Asset Manager | Long, Short, Spreading |
| Traders Leveraged Funds | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-------------------------------+------------------------+
Example usage
This code line retrieves "Noncommercial Positions (Long)" data, without options information, from the "Legacy" report for the chart symbol's root, base currency, or quote currency:
float nonCommercialLong = commitmentOfTraders("Noncommercial Positions", "Long", false)
This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:
float disaggregatedData = commitmentOfTraders("Managed Money Positions", "Short", true, "", "Disaggregated")
โ โ NOTES
โโข This library uses dynamic requests , allowing dynamic ("series") arguments for the parameters defining the context (ticker ID, timeframe, etc.) of a `request.*()` function call. With this feature, a single `request.*()` call instance can flexibly retrieve data from different feeds across historical executions. Additionally, scripts can use such calls in the local scopes of loops, conditional structures, and even exported library functions, as demonstrated in this script. All scripts coded in Pine Scriptโข v6 have dynamic requests enabled by default. To learn more about the behaviors and limitations of this feature, see the Dynamic requests section of the Pine Scriptโข User Manual.
โโข The library's example code offers a simple demonstration of the exported functions. The script retrieves available data using the function specified by the "Series type" input. The code requests a FRED series or COT (Legacy), FINRA Short Sale Volume, or Open Interest series for the chart's symbol with specific parameters, then plots the retrieved data as a step-line with diamond markers.
Look first. Then leap.
โ โ EXPORTED FUNCTIONS
This library exports the following functions:
fred(fredCode, gaps)
โโRequests a value from a specified Federal Reserve Economic Data (FRED) series. FRED is a comprehensive source that hosts numerous U.S. economic datasets. To explore available FRED datasets and codes, search for specific categories or keywords at fred.stlouisfed.org Calls to this function count toward a script's `request.*()` call limit.
โโParameters:
โโโโ fredCode (series string) : The unique identifier of the FRED series. The function uses the value to create a valid ticker ID for retrieving FRED data in the format `"FRED:fredCode"`. For example, `"GDP"` refers to the "Gross Domestic Product" series ("FRED:GDP"), and `"GFDEBTN"` refers to the "Federal Debt: Total Public Debt" series ("FRED:GFDEBTN").
โโโโ gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
โโReturns: (float) The value from the requested FRED series.
finraShortSaleVolume(symbol, gaps, repaint)
โโRequests FINRA daily short sale volume data for a specified symbol from one of the following exchanges: NASDAQ, NYSE, NYSE ARCA. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
โโParameters:
โโโโ symbol (series string) : The symbol for which to request short sale volume data. If the specified value contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", "BATS".
โโโโ gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
โโโโ repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
โโReturns: (float) The short sale volume for the specified symbol or the chart's symbol.
openInterestFutures(symbol, gaps, repaint)
โโRequests EOD open interest (OI) and OI rising information for a valid futures symbol. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
โโParameters:
โโโโ symbol (series string) : The symbol for which to request open interest data.
โโโโ gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
โโโโ repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
โโReturns: ( ) A tuple containing the following values:
โโโโ- The closing OI value for the symbol.
โโโโ- `true` if the closing OI is above the previous period's value, `false` otherwise.
openInterestCrypto(symbol, timeframe, gaps, repaint)
โโRequests opening, high, low, and closing open interest (OI) data and OI rising information for a valid cryptocurrency contract on a specified timeframe. Calls to this function count toward a script's `request.*()` call limit.
โโParameters:
โโโโ symbol (series string) : The symbol for which to request open interest data.
โโโโ timeframe (series string) : The timeframe of the data request. If the timeframe is lower than the chart's timeframe, it causes a runtime error.
โโโโ gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
โโโโ repaint (simple bool) : Optional. If `true` and the `timeframe` represents a higher timeframe, the function returns unconfirmed values from the timeframe on realtime bars, which repaint when the script restarts its executions. If `false`, it returns only confirmed higher-timeframe values to avoid repainting. The default is `true`.
โโReturns: ( ) A tuple containing the following values:
โโโโ- The opening, high, low, and closing OI values for the symbol, respectively.
โโโโ- `true` if the closing OI is above the previous period's value, `false` otherwise.
commitmentOfTraders(metricName, metricDirection, includeOptions, CFTCCode, typeCOT, mode, metricType)
โโRequests Commitment of Traders (COT) data with specified parameters. This function provides a simplified way to access CFTC COT data available on TradingView. Calls to this function count toward a script's `request.*()` call limit. For more advanced tools and detailed information about COT data, see TradingView's LibraryCOT library.
โโParameters:
โโโโ metricName (series string) : One of the valid metric names listed in the library's documentation and source code.
โโโโ metricDirection (series string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Consult the library's documentation or code to see which direction values apply to the specified metric.
โโโโ includeOptions (series bool) : If `true`, the COT symbol includes options information. Otherwise, it does not.
โโโโ CFTCCode (series string) : Optional. The CFTC code for the asset. For example, wheat futures (root "ZW") have the code "001602". If one is not specified, the function will attempt to get a valid code for the chart symbol's root, base currency, or main currency.
โโโโ typeCOT (series string) : Optional. The type of report to request. Possible values are: "Legacy", "Disaggregated", "Financial". The default is "Legacy".
โโโโ mode (series string) : Optional. Specifies the information the function extracts from a symbol. Possible modes are:
โโ- "Root": The function extracts the futures symbol's root prefix information (e.g., "ES" for "ESH2020").
โโ- "Base currency": The function extracts the first currency from a currency pair (e.g., "EUR" for "EURUSD").
โโ- "Currency": The function extracts the currency of the symbol's quoted values (e.g., "JPY" for "TSE:9984" or "USDJPY").
โโ- "Auto": The function tries the first three modes (Root -> Base currency -> Currency) until it finds a match.
โโThe default is "Auto". If the specified mode is not available for the symbol, it causes a runtime error.
โโโโ metricType (series string) : Optional. The metric type. Possible values are: "All", "Old", "Other". The default is "All".
โโReturns: (float) The specified Commitment of Traders data series. If no data is available, it causes a runtime error.
PremiumDiscountLibraryLibrary "PremiumDiscountLibrary"
isInZone(currentTime, price, trend, tz)
โโVรฉrifie si le prix est en zone premium ou discount
โโParameters:
โโโโ currentTime (int) : L'heure actuelle (timestamp)
โโโโ price (float) : Le prix actuel
โโโโ trend (string) : La tendance ("bullish" ou "bearish")
โโโโ tz (string) : Le fuseau horaire pour calculer les sessions (par dรฉfaut : "GMT+1")
โโReturns: true si le prix est dans la zone correcte, sinon false
KillzoneLibraryLibrary "KillzoneLibrary"
isKillzone(currentTime, tz)
โโVรฉrifie si l'heure actuelle est dans une Killzone
โโParameters:
โโโโ currentTime (int) : L'heure actuelle (entier reprรฉsentant le timestamp)
โโโโ tz (string) : Le fuseau horaire (par dรฉfaut : "GMT+1")
โโReturns: true si dans une Killzone, sinon false
LibraryDivergenceV6LibraryDivergenceV6
Enhance your trading strategies with LibraryDivergenceV6, a comprehensive Pine Script library designed to simplify and optimize the detection of bullish and bearish divergences across multiple technical indicators. Whether you're developing your own indicators or seeking to incorporate robust divergence analysis into your trading systems, this library provides the essential tools and functions to accurately identify potential market reversals and continuations.
Overview
LibraryDivergenceV6 offers a suite of functions that detect divergences between price movements and key technical indicators such as the Relative Strength Index (RSI) and On-Balance Volume (OBV). By automating the complex calculations involved in divergence detection, this library enables traders and developers to implement reliable and customizable divergence strategies with ease.
Key Features
Comprehensive Divergence Detection
Bullish Divergence: Identifies instances where the indicator forms higher lows while the price forms lower lows, signaling potential upward reversals.
Bearish Divergence: Detects situations where the indicator creates lower highs while the price forms higher highs, indicating possible downward reversals.
Overbought and Oversold Conditions: Differentiates between standard and strong divergences by considering overbought and oversold levels, enhancing signal reliability.
Multi-Indicator Support
RSI (Relative Strength Index): Analyze momentum-based divergences to spot potential trend reversals.
OBV (On-Balance Volume): Incorporate volume flow into divergence analysis for a more comprehensive market perspective.
Customizable Parameters
Pivot Points Configuration: Adjust the number of bars to the left and right for pivot detection, allowing fine-tuning based on different timeframes and trading styles.
Range Settings: Define minimum and maximum bar ranges to control the sensitivity of divergence detection, reducing false signals.
Noise Cancellation: Enable or disable noise filtering to focus on significant divergences and minimize minor fluctuations.
Flexible Usage
Exported Functions: Easily integrate divergence detection into your custom indicators or trading strategies with exported functions such as DivergenceBull, DivergenceBear, DivergenceBullOversold, and DivergenceBearOverbought.
Occurrence Handling: Specify which occurrence of a divergence to consider (e.g., most recent, previous) for precise analysis.
Optimized Performance
Efficient Calculations: Designed to handle multiple occurrences and pivot points without compromising script performance.
Line Management: Automatically creates and deletes trend lines based on divergence conditions, ensuring a clean and uncluttered chart display.
MyRenkoLibraryLibrary "MyRenkoLibrary"
calcRenko(real_break_size)
โโParameters:
โโโโ real_break_size (float)
PseudoPlotLibrary "PseudoPlot"
PseudoPlot: behave like plot and fill using polyline
This library enables line plotting by polyline like plot() and fill().
The core of polyline() is array of chart.point array, polyline() is called in its method.
Moreover, plotarea() makes a box in main chart, plotting data within the box is enabled.
It works so slowy to manage array of chart.point, so limit the target to visible area of the chart.
Due to polyline specifications, na and expression can not be used for colors.
1. pseudoplot
pseudoplot() behaves like plot().
//use plot()
plot(close)
//use pseudoplot()
pseudoplot(close)
Pseudoplot has label. Label is enabled when title argument is set.
In the example bellow, "close value" label is shown with line.
The label is shown at right of the line when recent bar is visible.
It is shown at 15% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
//use plot()
plot(close,"close value")
//use pseudoplot
pseudoplot(close, "close value")
Arguments are designed in an order as similar as possible to plot.
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display, format, precision, force_overlay) โ plot
pseudoplot(series, title, ,linecolor ,linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) โ pseudo_plot
2. pseudofill
pseudofill() behaves like fill().
The label is shown(text only) at right of the line when recent bar is visible.
It is shown at 10% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
//use plot() and fill()
p1=plot(open)
p2=plot(close)
fill(p1,p2)
//use pseudofill()
pseudofill(open,close)
Arguments are designed in an order as similar as possible to fill.
fill(hline1, hline2, color, title, editable, fillgaps, display) โ void
pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) โ pseudo_plot
3. plotarea and its methods
plotarea() makes a box in main chart. You can set the box position to top or bottom, and
the box height in percentage of the range of visible high and low prices.
x-coordinate of the box is from chart.left_visible_bar_time to chart.right_visible_bar_time,
y-coordinate is highest and lowest price of visible bars.
pseudoplot() and pseudofill() work as method of plotarea(box).
Usage is almost same as the function version, just set min and max value, y-coodinate is remapped automatically.
hline() is also available. The y-coordinate of hline is specified as a percentage from the bottom.
plotarea() and its associated methods are overlay=true as default.
Depending on the drawing order of the objects, plot may become invisible, so the bgcolor of plotarea should be na or tranceparent.
//1. make a plotarea
// bgcolor should be na or transparent color.
area=plotarea("bottom",30,"plotarea",bgcolor=na)
//2. plot in a plotarea
//(min=0, max=100 is omitted as it is the default.)
area.pseudoplot(ta.rsi(close,14))
//3. draw hlines
area.hline(30,linestyle="dotted",linewidth=2)
area.hline(70,linestyle="dotted",linewidth=2)
4. Data structure and sub methods
Array management is most imporant part of using polyline.
I don't know the proper way to handle array, so it is managed by array and array as intermediate data.
(type xy_arrays to manage bar_time and price as independent arrays.)
method cparray() pack arrays to array, when array includes both chart.left_visible_bar_time and chart.right_visible_bar.time.
Calling polyline is implemented as methods of array of chart.point.
Method creates polyline object if array is not empty.
method polyline(linecolor, linewidth, linestyle, overlay) โ series polyline
method polyline_fill(fillcolor, linecolor, linewidth, linestyle, overlay) โ series polyline
Also calling label is implemented as methods of array of chart.point.
Method creates label ofject if array is not empty.
Label is located at right edge of the chart when recent bar is visible, located at left side when recent bar is invisible.
label(title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) โ series label
label_for_fill(title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) โ series label
visible_xyInit(series)
โโmake arrays of visible x(bar_time) and y(price/value).
โโParameters:
โโโโ series (float) : (float) series variable
โโReturns: (xy_arrays)
method remap(this, bottom, top, min, max)
โโNamespace types: xy_arrays
โโParameters:
โโโโ this (xy_arrays)
โโโโ bottom (float) : (float) bottom price to ajust.
โโโโ top (float) : (float) top price to ajust.
โโโโ min (float) : (float) min of src value.
โโโโ max (float) : (float) max of src value.
โโReturns: (xy_arrays)
method polyline(this, linecolor, linewidth, linestyle, overlay)
โโNamespace types: array
โโParameters:
โโโโ this (array)
โโโโ linecolor (color) : (color) color of polyline.
โโโโ linewidth (int) : (int) width of polyline.
โโโโ linestyle (string) : (string) linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
โโโโ overlay (bool) : (bool) force_overlay of polyline. default is false.
โโReturns: (polyline)
method polyline_fill(this, fillcolor, linecolor, linewidth, linestyle, overlay)
โโNamespace types: array
โโParameters:
โโโโ this (array)
โโโโ fillcolor (color)
โโโโ linecolor (color) : (color) color of polyline.
โโโโ linewidth (int) : (int) width of polyline.
โโโโ linestyle (string) : (string) linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
โโโโ overlay (bool) : (bool) force_overlay of polyline. default is false.
โโReturns: (polyline)
method label(this, title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay)
โโNamespace types: array
โโParameters:
โโโโ this (array)
โโโโ title (string) : (string) label text.
โโโโ labelbg (color) : (color) color of label bg.
โโโโ labeltext (color) : (color) color of label text.
โโโโ labelsize (int) : (int) size of label.
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ shorttitle (string) : (string) another label text for recent bar is not visible.
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
โโโโ overlay (bool) : (bool) force_overlay of label. default is false.
โโReturns: (label)
method label_for_fill(this, title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay)
โโNamespace types: array
โโParameters:
โโโโ this (array)
โโโโ title (string) : (string) label text.
โโโโ labeltext (color) : (color) color of label text.
โโโโ labelsize (int) : (int) size of label.
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ shorttitle (string) : (string) another label text for recent bar is not visible.
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 10%.
โโโโ overlay (bool) : (bool) force_overlay of label. default is false.
โโReturns: (label)
pseudoplot(series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay)
โโpolyline like plot with label
โโParameters:
โโโโ series (float) : (float) series variable to plot.
โโโโ title (string) : (string) title if need label. default value is ""(disable label).
โโโโ linecolor (color) : (color) color of line.
โโโโ linewidth (int) : (int) width of line.
โโโโ linestyle (string) : (string) style of plotting line. default is "solid", others "dashed", "dotted".
โโโโ labelbg (color) : (color) color of label bg.
โโโโ labeltext (color) : (color) color of label text.
โโโโ labelsize (int) : (int) size of label text.
โโโโ shorttitle (string) : (string) another label text for recent bar is not visible.
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (pseudo_plot)
method pseudoplot(this, series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay)
โโNamespace types: series box
โโParameters:
โโโโ this (box)
โโโโ series (float) : (float) series variable to plot.
โโโโ title (string) : (string) title if need label. default value is ""(disable label).
โโโโ linecolor (color) : (color) color of line.
โโโโ linewidth (int) : (int) width of line.
โโโโ linestyle (string) : (string) style of plotting line. default is "solid", others "dashed", "dotted".
โโโโ labelbg (color) : (color) color of label bg.
โโโโ labeltext (color) : (color) color of label text.
โโโโ labelsize (int) : (int) size of label text.
โโโโ shorttitle (string) : (string) another label text for recent bar is not visible.
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
โโโโ min (float)
โโโโ max (float)
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (pseudo_plot)
pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay)
โโfill by polyline
โโParameters:
โโโโ series1 (float) : (float) series variable to plot.
โโโโ series2 (float) : (float) series variable to plot.
โโโโ fillcolor (color) : (color) color of fill.
โโโโ title (string)
โโโโ linecolor (color) : (color) color of line.
โโโโ linewidth (int) : (int) width of line.
โโโโ linestyle (string) : (string) style of plotting line. default is "solid", others "dashed", "dotted".
โโโโ labeltext (color)
โโโโ labelsize (int)
โโโโ shorttitle (string)
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (pseudoplot)
method pseudofill(this, series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay)
โโNamespace types: series box
โโParameters:
โโโโ this (box)
โโโโ series1 (float) : (float) series variable to plot.
โโโโ series2 (float) : (float) series variable to plot.
โโโโ fillcolor (color) : (color) color of fill.
โโโโ title (string)
โโโโ linecolor (color) : (color) color of line.
โโโโ linewidth (int) : (int) width of line.
โโโโ linestyle (string) : (string) style of plotting line. default is "solid", others "dashed", "dotted".
โโโโ labeltext (color)
โโโโ labelsize (int)
โโโโ shorttitle (string)
โโโโ format (string) : (string) textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
โโโโ xpos_from_left (int) : (int) another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
โโโโ min (float)
โโโโ max (float)
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (pseudo_plot)
plotarea(pos, height, title, bordercolor, borderwidth, bgcolor, textsize, textcolor, format, overlay)
โโsubplot area in main chart
โโParameters:
โโโโ pos (string) : (string) position of subplot area, bottom or top.
โโโโ height (int) : (float) percentage of visible chart heght.
โโโโ title (string) : (string) text of area box.
โโโโ bordercolor (color) : (color) color of border.
โโโโ borderwidth (int) : (int) width of border.
โโโโ bgcolor (color) : (string) color of area bg.
โโโโ textsize (int)
โโโโ textcolor (color)
โโโโ format (string)
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (box)
method hline(this, ypos_from_bottom, linecolor, linestyle, linewidth, overlay)
โโNamespace types: series box
โโParameters:
โโโโ this (box)
โโโโ ypos_from_bottom (float) : (float) percentage of box height from the bottom of box.(bottom is 0%, top is 100%).
โโโโ linecolor (color) : (color) color of line.
โโโโ linestyle (string) : (string) style of line.
โโโโ linewidth (int) : (int) width of line.
โโโโ overlay (bool) : (bool) force_overlay of polyline and label.
โโReturns: (line)
pseudo_plot
โโpolyline and label.
โโFields:
โโโโ p (series polyline)
โโโโ l (series label)
xy_arrays
โโx(bartime) and y(price or value) arrays.
โโFields:
โโโโ t (array)
โโโโ p (array)
Milvetti_Pineconnector_LibraryLibrary "Milvetti_Pineconnector_Library"
This library has methods that provide practical signal transmission for Pineconnector.Developed By Milvetti
buy(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a buy order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
sell(licenseId, symbol, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a buy order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
buyLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a buy limit order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
buyStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a buy stop order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
sellLimit(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a sell limit order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
sellStop(licenseId, symbol, pending, risk, sl, tp, beTrigger, beOffset, trailTrig, trailDist, trailStep, atrTimeframe, atrTrigger, atrPeriod, atrMultiplier, atrShift, spread, accFilter, secret, comment)
โโCreate a sell stop order message
โโParameters:
โโโโ licenseId (string) : License Id. This is a unique identifier found in the Pineconnector Licensing Dashboard.
โโโโ symbol (string) : Symbol. Default is syminfo.ticker
โโโโ pending (float) : Computing pending order entry price. EA Options: Pips, Specified Price, Percentage
โโโโ risk (float) : Risk. Function depends on the โVolume Typeโ selected in the EA
โโโโ sl (float) : StopLoss. Place stop-loss. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ tp (float) : TakeProfit. Place take-profit. Computation is based on the Target Type selected in the EA. Default is 0(inactive)
โโโโ beTrigger (float) : Breakeven will be activated after the position gains this number of pips. Ensure > 0
โโโโ beOffset (float) : Offset from entry price. 0 means the SL will be placed exactly at entry price. 1 means 1 pip above the entry price for buy trades and 1 pip below for sell trades.
โโโโ trailTrig (int) : Trailing stop-loss will be activated after a trade gains this number of pips. Default is 0(inactive)
โโโโ trailDist (int) : SL will be opened at traildist after trailtrig is met, even if you do not have a SL placed.. Default is 0(inactive)
โโโโ trailStep (int) : Moves trailing stop-loss once price moves to favourable by a specified number of pips. Default is 0(inactive)
โโโโ atrTimeframe (string) : ATR Trailing Stop will be based on the specified timeframe in minutes and will only update once per bar close. Default is Timeframe.Period
โโโโ atrTrigger (float) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default is 0(inactive)
โโโโ atrPeriod (int) : ATR averaging period. Default is 0
โโโโ atrMultiplier (float) : Multiple of ATR to utilise in the new SL computation. Default is 1
โโโโ atrShift (float) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default is 0
โโโโ spread (float) : Enter the position only if the spread is equal or less than the specified value in pips. Default is 0(inactive)
โโโโ accFilter (float) : Enter the position only if the account requirement is met. Default is 0(inactive)
โโโโ secret (string)
โโโโ comment (string) : Comment. Add a string into the orderโs comment section. Default is "Symbol+Timeframe"
Milvetti_TraderPost_LibraryLibrary "Milvetti_TraderPost_Library"
This library has methods that provide practical signal transmission for traderpost.Developed By Milvetti
cancelOrders(symbol)
โโThis method generates a signal in JSON format that cancels all orders for the specified pair. (If you want to cancel stop loss and takeprofit orders together, use the โexitOrderโ method.
โโParameters:
โโโโ symbol (string)
exitOrders(symbol)
โโThis method generates a signal in JSON format that close all orders for the specified pair.
โโParameters:
โโโโ symbol (string)
createOrder(ticker, positionType, orderType, entryPrice, signalPrice, qtyType, qty, stopLoss, stopType, stopValue, takeProfit, profitType, profitValue, timeInForce)
โโThis function is designed to send buy or sell orders to traderpost. It can create customized orders by flexibly specifying parameters such as order type, position type, entry price, quantity calculation method, stop-loss, and take-profit. The purpose of the function is to consolidate all necessary details for opening a position into a single structure and present it as a structured JSON output. This format can be sent to trading platforms via webhooks.
โโParameters:
โโโโ ticker (string) : The ticker symbol of the instrument. Default value is the current chart's ticker (syminfo.ticker).
โโโโ positionType (string) : Determines the type of order (e.g., "long" or "buy" for buying and "short" or "sell" for selling).
โโโโ orderType (string) : Defines the order type for execution. Options: "market", "limit", "stop". Default is "market"
โโโโ entryPrice (float) : The price level for entry orders. Only applicable for limit or stop orders. Default is 0 (market orders ignore this).
โโโโ signalPrice (float) : Optional. Only necessary when using relative take profit or stop losses, and the broker does not support fetching quotes to perform the calculation. Default is 0
โโโโ qtyType (string) : Determines how the order quantity is calculated. Options: "fixed_quantity", "dollar_amount", "percent_of_equity", "percent_of_position".
โโโโ qty (float) : Quantity value. Can represent units of shares/contracts or a dollar amount, depending on qtyType.
โโโโ stopLoss (bool) : Enable or disable stop-loss functionality. Set to `true` to activate.
โโโโ stopType (string) : Specifies the stop-loss calculation type. Options: percent, "amount", "stopPrice", "trailPercent", "trailAmount". Default is "stopPrice"
โโโโ stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount, or a specific stop price. Default is "stopPrice"
โโโโ takeProfit (bool) : Enable or disable take-profit functionality. Set to `true` to activate.
โโโโ profitType (string) : Specifies the take-profit calculation type. Options: "percent", "amount", "limitPrice". Default is "limitPrice"
โโโโ profitValue (float) : Take-profit value based on profitType. Can be a percentage, dollar amount, or a specific limit price. Default is 0
โโโโ timeInForce (string) : The time in force for your order. Options: day, gtc, opg, cls, ioc and fok
โโReturns: Return result in Json format.
addTsl(symbol, stopType, stopValue, price)
โโThis method adds trailing stop loss to the current position. โPriceโ is the trailing stop loss starting level. You can leave price blank if you want it to start immediately
โโParameters:
โโโโ symbol (string)
โโโโ stopType (string) : Specifies the trailing stoploss calculation type. Options: "trailPercent", "trailAmount".
โโโโ stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount.
โโโโ price (float) : The trailing stop loss starting level. You can leave price blank if you want it to start immediately. Default is current price.






















