# Alert Limitations, Delivery, and History Source: https://takeprofit.com/docs/guide/alerts/Alert-limitations-delivery-history ### Alert Limits * Free users can create 1 alert with up to 3 months expiration * Premium users can create up to 50 alerts with extended expiration periods * All alerts remain active as long as the user maintains premium status ### Notifications Limits * Real-time platform updates are limited to 10 times per second * On-platform notifications have no delivery limitations * Email notifications are limited to once per minute per email address * Webhook notifications are subject to rate limiting (limits are being adjusted and will be updated soon). ### Alert History ![](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/guide/alerts/2.16.7_Logs.png) * Complete trigger history is available in the platform's alerts log * Alert history is maintained for the entire lifetime of the alert * Alert logs are automatically removed when the corresponding alert is deleted. # Alert Trigger Criteria Source: https://takeprofit.com/docs/guide/alerts/Alert-trigger-criteria This guide provides a detailed description of the various alert trigger criteria available in the **TakeProfit** platform. Understanding these criteria will help you set up alerts that align with your trading strategies and preferences, allowing you to respond promptly to market changes. ![](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/guide/alerts/9.png) ## Introduction Alerts are an important tool for traders, allowing them to respond promptly to market changes. In **TakeProfit**, you can set up alerts with various trigger criteria tailored to your trading strategies. This guide will help you understand and effectively use these criteria, providing examples involving cryptocurrencies, stocks, and technical indicators. List of availbale criteria: The trigger activates when the price or indicator value increases by a specified amount. The trigger activates when the price or indicator value decreases by a specified amount. The trigger activates when the price or indicator value increases by a specified percentage. The trigger activates when the price or indicator value decreases by a specified percentage. The trigger activates when two data series cross at any point. The trigger activates when one data series crosses another from below. The trigger activates when one data series crosses another from above. The trigger activates when the price or indicator value exceeds a specified value. The trigger activates when the price or indicator value falls below a specified value. The trigger activates when the price or indicator value enters a specified range. The trigger activates when the price or indicator value exits a specified range. The trigger activates as long as the price or indicator value remains within a specified range. The trigger activates when the price or indicator value is outside a specified range. *** ## Moving Up **Description:** The trigger activates when an asset's price or indicator value increases by a specified amount within a certain number of bars. **Usage:** * Monitoring significant increases in price or indicator over a short period. * Identifying the start of an upward trend. * Tracking strong bullish momentum. **Examples:** | Asset | Condition | | -------------------- | --------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when the price of **Apple (AAPL)** increases by **5** over the last **3 hours**. | | **Cryptocurrencies** | Notify when **Bitcoin (BTC)** rises by **1,000** within the last **2 hours**. | | **Indicators** | Notify when the **RSI** value increases by **10 points** over the last **5 bars**, indicating strengthening momentum. | **Tips:** * Adjust the amount of change according to the asset's volatility. * Use to spot entry opportunities in a rising market. * When monitoring indicators, pay attention to significant shifts that may signal a trend change. *** ## Moving Down **Description:** The trigger activates when an asset's price or indicator value decreases by a specified amount within a certain number of bars. **Usage:** * Monitoring sharp declines in price or indicator. * Identifying the start of a downward trend or buying opportunities during a pullback. * Monitoring weakening market momentum. **Examples:** | Asset | Condition | | -------------------- | ----------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when the price of **Tesla (TSLA)** decreases by **10** over the last **4 hours**. | | **Cryptocurrencies** | Notify when **Ethereum (ETH)** drops by **200** within the last **6 hours**. | | **Indicators** | Notify when the **MACD** value decreases by **5 points** over the last **3 bars**, indicating weakening momentum. | **Tips:** * Helps in timely decision-making for exiting positions or entering at a better level. * Combine with volume analysis to confirm the strength of the movement. * When monitoring indicators, track declines that may precede price reversals. *** ## Moving Up % **Description:** The trigger activates when an asset's price or indicator value increases by a specified percentage over a defined period. **Usage:** * Monitoring significant percentage gains. * Identifying assets or indicators with strong upward momentum. * Tracking market dynamics. **Examples:** | Asset | Condition | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when **Netflix (NFLX)** shares rise by **5%** over the last **2 days**. | | **Cryptocurrencies** | Notify when **Ripple (XRP)** increases by **10%** within the last **24 hours**. | | **Indicators** | Notify when the **On-Balance Volume (OBV)** increases by **8%** over the last **10 bars**, indicating strong buying pressure. | **Tips:** * Percentage changes are convenient for comparing assets with different price levels. * Useful when screening the market for assets or indicators showing strong momentum. * Apply to percentage-based indicators for consistent analysis. *** ## Moving Down % **Description:** The trigger activates when an asset's price or indicator value decreases by a specified percentage over a defined period. **Usage:** * Monitoring significant percentage declines. * Identifying buying opportunities after a price correction. * Monitoring weakening indicators that may precede a reversal. **Examples:** | Asset | Condition | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | **Stocks** | Notify when **Amazon (AMZN)** shares fall by **8%** over the last **3 days**. | | **Cryptocurrencies** | Notify when **Litecoin (LTC)** decreases by **15%** within the last **12 hours**. | | **Indicators** | Notify when the **Stochastic Oscillator** decreases by **20%** over the last **5 bars**, indicating approaching oversold conditions. | **Tips:** * Helps identify oversold assets or weakening indicators. * Combine with technical analysis for signal confirmation. * Monitoring indicator declines can help anticipate potential reversals. *** ## Crossing **Description:** The trigger activates when two data series cross at any point. **Usage:** * Identifying potential trend reversals. * Monitoring crossovers between moving averages or indicators. * Detecting significant market signals. **Examples:** | Asset | Condition | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | **Indicators** | Notify when the **50-day SMA** crosses the **200-day SMA** on **Google (GOOGL)** chart (Golden Cross or Death Cross). | | **Cryptocurrencies** | Notify when the **MACD line** crosses the **signal line** on **Bitcoin (BTC)** chart, signaling a potential change in momentum. | | **Stocks** | Notify when the **Price** crosses the **Ichimoku Cloud** on **NVIDIA (NVDA)** chart, indicating a potential trend change. | **Tips:** * Crossovers of moving averages or indicators can signal significant market shifts. * Use in combination with other technical tools to confirm signals. * Be aware of false signals in volatile markets. *** ## Cross Up **Description:** The trigger activates when one data series crosses another from below. **Usage:** * Signals a possible start of an upward trend. * Identifying bullish signals. * Monitoring increasing market momentum. **Examples:** | Asset | Condition | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when the price of **Microsoft (MSFT)** crosses above the **100-day SMA** from below, indicating a bullish trend. | | **Indicators** | Notify when the **RSI** crosses above the **30** level on **Ethereum (ETH)** chart, indicating exit from the oversold zone. | | **Cryptocurrencies** | Notify when the **Chaikin Money Flow (CMF)** crosses above zero on **Cardano (ADA)** chart, suggesting increasing buying pressure. | **Tips:** * Cross Up is often considered a buy signal. * Confirm signals with volume and other indicators for increased reliability. * Consider the context and overall market conditions. *** ## Cross Down **Description:** The trigger activates when one data series crosses another from above. **Usage:** * Signals a possible start of a downward trend. * Identifying bearish signals. * Monitoring decreasing market momentum. **Examples:** | Asset | Condition | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when the price of **Facebook (FB)** crosses below the **50-day SMA** from above, indicating potential weakness. | | **Indicators** | Notify when the **RSI** crosses below the **70** level on **Litecoin (LTC)** chart, indicating exit from the overbought zone. | | **Cryptocurrencies** | Notify when the **MACD line** crosses below the **signal line** on **Bitcoin Cash (BCH)** chart, signaling a potential bearish reversal. | **Tips:** * Cross Down can serve as a signal to sell or close long positions. * Use stop-loss orders to manage risks when trading on these signals. * Consider the timeframe to filter out short-term noise. *** ## Greater Than **Description:** The trigger activates when the price or indicator value exceeds a specified value or another data series. **Usage:** * Monitoring breakouts above key resistance levels. * Identifying the start of bullish movement. * Tracking extreme indicator values. **Examples:** | Asset | Condition | | -------------------- | ---------------------------------------------------------------------------------------------- | | **Stocks** | Notify when **Tesla (TSLA)** exceeds **800**, indicating a potential breakout. | | **Cryptocurrencies** | Notify when **Bitcoin (BTC)** surpasses its all-time high, signaling strong bullish sentiment. | | **Indicators** | Notify when the **RSI** on **Apple (AAPL)** exceeds **70**, entering overbought territory. | **Tips:** * Useful for setting price targets and automating notifications when key levels are reached. * Combine with volume analysis to confirm breakouts. * For indicators, be cautious as overbought conditions may precede reversals. *** ## Lower Than **Description:** The trigger activates when the price or indicator value falls below a specified value or another data series. **Usage:** * Monitoring breakdowns below support levels. * Identifying the start of bearish movement. * Tracking extreme low indicator values. **Examples:** | Asset | Condition | | -------------------- | --------------------------------------------------------------------------------------------- | | **Stocks** | Notify when **Netflix (NFLX)** drops below **500**, possibly indicating further downside. | | **Cryptocurrencies** | Notify when **Ethereum (ETH)** falls below **2,000**, breaking a key support level. | | **Indicators** | Notify when the **RSI** on **Amazon (AMZN)** drops below **30**, entering oversold territory. | **Tips:** * Helps react promptly to price declines and make decisions about exiting positions. * Can be used to set stop-loss levels or identify buying opportunities. * For indicators, oversold conditions may suggest potential rebounds. *** ## Entering Channel **Description:** The trigger activates when the price or indicator value enters a specified range between upper and lower boundaries. **Usage:** * Monitoring price consolidation within a certain range. * Preparing for range-bound trading strategies. * Tracking reduced volatility. **Examples:** | Asset | Condition | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when **Apple (AAPL)** enters the price range between **130** and **135**, indicating consolidation. | | **Cryptocurrencies** | Notify when **Bitcoin (BTC)** enters the Bollinger Bands after being outside, suggesting reduced volatility. | | **Indicators** | Notify when the **ADX (Average Directional Index)** on **Tesla (TSLA)** enters the range between **20** and **25**, indicating a non-trending market. | **Tips:** * Use to monitor sideways markets and plan trades within the range. * Combine with other indicators to assess potential breakouts. * Be prepared for increased volatility when exiting the channel. *** ## Exiting Channel **Description:** The trigger activates when the price or indicator value exits a specified range. **Usage:** * Identifying breakouts upwards or downwards. * Signaling the start of a new trend or increased volatility. * Monitoring significant market changes. **Examples:** | Asset | Condition | | -------------------- | --------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify when **Tesla (TSLA)** breaks out of the **700** - **750** price range. | | **Cryptocurrencies** | Notify when **Ethereum (ETH)** moves outside the Keltner Channel, indicating a potential trend change. | | **Indicators** | Notify when the **Volatility Index (VIX)** exits a low volatility range, signaling potential market turbulence. | **Tips:** * Breaking out of a channel may indicate the start of a significant movement. * Confirm breakouts using volume and other technical indicators. * Be cautious of false breakouts; consider waiting for confirmation. *** ## Inside Channel **Description:** The trigger activates as long as the price or indicator value remains within a specified range. **Usage:** * Monitoring stable periods for trading within the range. * Tracking assets or indicators during consolidation phases. * Planning entry and exit strategies. **Examples:** | Asset | Condition | | -------------------- | ------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Continuously notify while **Microsoft (MSFT)** trades between **250** and **260**. | | **Cryptocurrencies** | Notify while **Bitcoin (BTC)** is within the **45,000** - **50,000** range. | | **Indicators** | Notify when the **Stochastic Oscillator** on **Ethereum (ETH)** remains between **40** and **60**, indicating neutrality. | **Tips:** * Useful for range-bound trading strategies. * Be vigilant for signs of an impending breakout. * Adjust range boundaries as market conditions change. *** ## Outside Channel **Description:** The trigger activates when the price or indicator value is outside a specified range. **Usage:** * Monitoring extreme price levels or indicator readings. * Identifying assets with increased volatility or trend strength. * Tracking significant market events. **Examples:** | Asset | Condition | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | **Stocks** | Notify if **Facebook (FB)** trades above **350** or below **300**, indicating significant movement. | | **Cryptocurrencies** | Notify if **Ripple (XRP)** moves outside the Bollinger Bands, suggesting increased volatility. | | **Indicators** | Notify when the **RSI** on **Litecoin (LTC)** is above **70** or below **30**, indicating overbought or oversold conditions. | **Tips:** * Helps react promptly to significant market events. * Combine with news analysis to understand underlying causes. * For indicators, extreme values may precede reversals. *** ## Best Practices Understand exactly what you want to monitor and why. Set up alerts according to your trading strategy. Avoid notification overload. Focus on the most important criteria for you. Confirm signals using technical indicators and fundamental analysis. Adjust criteria in line with changing market conditions. Analyze alert effectiveness and make necessary changes. Choose time intervals that match your trading style (day trading, swing trading, long-term investing). Set up alert delivery methods (mobile app, email, messengers) for quick response. Start with small thresholds to ensure alerts are working correctly. Adjust parameters based on results. Keep an eye on market news that may affect your alerts. Be aware of scheduled events like earnings reports or economic data releases. *** ## Conclusion Effectively using the various alert trigger criteria in the **TakeProfit** platform allows you to stay ahead in dynamic markets. By understanding and correctly applying these criteria, you can tailor alerts to your specific trading strategies, helping you make timely and informed decisions. Remember, the key to successful alert management is continuous learning and adaptation. Regularly refine your alerts based on market changes and personal experience to optimize your trading outcomes. *** > **Note:** Always consider the individual characteristics of the assets and indicators you work with, as well as the current market environment when setting up alerts. This will enhance the relevance and effectiveness of your notifications. # Alerts overview Source: https://takeprofit.com/docs/guide/alerts/Alerts-overview TakeProfit alerts notify you when market conditions meet your custom criteria. Set up notifications for price movements, indicator conditions, or custom indicators you've developed.
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Built-in symbols of Indie language. *** ## Variables Built-in Indie object (similar to Python's). Built-in Indie object (similar to Python's). Built-in Indie object (similar to Python's). *** ## Functions ### `abs()` *function* Returns the absolute value of a number. It is a built-in Indie function (similar to Python's). Number on which the function will be calculated. Returns the absolute value of a number. It is a built-in Indie function (similar to Python's). Number on which the function will be calculated. *** ### `len()` *function* Returns the length (the number of items) of an object. It is a built-in Indie function (similar to Python's). Value on which the function will be calculated. *** ### `max()` *function* Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Third number to calculate the function. Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Third number to calculate the function. Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). List on which the function will be calculated. Returns the largest of two or more arguments. It is a built-in Indie function (similar to Python's). List on which the function will be calculated. *** ### `min()` *function* Returns the smallest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Returns the smallest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Third number to calculate the function. Returns the smallest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Returns the smallest of two or more arguments. It is a built-in Indie function (similar to Python's). First number to calculate the function. Second number to calculate the function. Third number to calculate the function. *** ### `range()` *function* Creates a list containing the specified range of numbers that is used in `for` loops. It is a built-in Indie function (similar to Python's). Last value of the range (exclusive). ```py Example x = 0 for i in range(10): x += i ``` The behavior of this function is similar to Python's 2 built-in function `range` and is ineffective. This will be fixed in future versions of Indie. Creates a list containing the specified range of numbers that is used in `for` loops. It is a built-in Indie function (similar to Python's). First value of the range. Last value of the range (exclusive). Step value of the range. ```py Example x = 0 for i in range(10): x += i ``` The behavior of this function is similar to Python's 2 built-in function `range` and is ineffective. This will be fixed in future versions of Indie. *** ### `round()` *function* Returns number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. It is a built-in Indie function (similar to Python's). Number on which the function will be calculated. Returns number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. It is a built-in Indie function (similar to Python's). Number on which the function will be calculated. Rounding precision. *** ### `sum()` *function* Sums start and the items of a list from left to right and returns the total. It is a built-in Indie function (similar to Python's). List on which the function will be calculated. Initial value to calculate sum of the list. Sums start and the items of a list from left to right and returns the total. It is a built-in Indie function (similar to Python's). List on which the function will be calculated. Initial value to calculate sum of the list. *** ## Types ### `bool` *type* Built-in Indie type (similar to Python's). Cast constructor for built-in Indie type. Returns a `bool` value, i.e. one of `True` or `False`. The argument is converted using the standard [Python's truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). Value to cast from. Cast constructor for built-in Indie type. Returns a `bool` value, i.e. one of `True` or `False`. The argument is converted using the standard [Python's truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). Value to cast from. Cast constructor for built-in Indie type. Returns a `bool` value, i.e. one of `True` or `False`. The argument is converted using the standard [Python's truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). Value to cast from. Cast constructor for built-in Indie type. Returns a `bool` value, i.e. one of `True` or `False`. The argument is converted using the standard [Python's truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). Value to cast from. Cast constructor for built-in Indie type. Returns a `bool` value, i.e. one of `True` or `False`. The argument is converted using the standard [Python's truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). Value to cast from. *** ### `dict[K, V]` *type* Built-in Indie type (similar to Python's). *** ### `float` *type* Built-in Indie type (similar to Python's). Cast constructor for built-in Indie type. Returns a `float` number constructed from a number or a string. Value to cast from. Cast constructor for built-in Indie type. Returns a `float` number constructed from a number or a string. Value to cast from. Cast constructor for built-in Indie type. Returns a `float` number constructed from a number or a string. Value to cast from. Cast constructor for built-in Indie type. Returns a `float` number constructed from a number or a string. Value to cast from. *** ### `int` *type* Built-in Indie type (similar to Python's). Cast constructor for built-in Indie type. Returns an `int` object constructed from a number or a string, or return 0 if no arguments are given. Value to cast from. Cast constructor for built-in Indie type. Returns an `int` object constructed from a number or a string, or return 0 if no arguments are given. Value to cast from. Cast constructor for built-in Indie type. Returns an `int` object constructed from a number or a string, or return 0 if no arguments are given. Value to cast from. Cast constructor for built-in Indie type. Returns an `int` object constructed from a number or a string, or return 0 if no arguments are given. Value to cast from. *** ### `list[T]` *type* Built-in Indie type (similar to Python's). Appends given param to the end of the list. New value that will be put to the list. Returns list element at given index. Index of an element in the list. ```py Example nums = [40, 41, 42, 43] meaning_of_life = nums[2] # returns 42 (this implicitly calls `nums.__getitem__(2)`) ``` Method `__getitem__` should never be called directly, instead `list_obj[key]` syntax should be used. Assigns value to some\_list\[key]. Index of an element in the list. New value that will be put to the list. ```py Example nums = [40, 41, 42, 43] nums[2] = 100500 # this implicitly calls `nums.__setitem__(2, 100500)` # and now `nums` are [40, 41, 100500, 43] ``` Method `__setitem__` should never be called directly, instead `list_obj[key] = value` syntax should be used. Delete an item from the list at the given index. Index of an element in the list. ```py Example nums = [40, 41, 42, 43] del nums[2] # this implicitly calls `nums.__delitem__(2)` ``` Method `__delitem__` should never be called directly, instead `del list_obj[key]` syntax should be used. Delete a slice from the list. Starting index for slice. Can be omitted. See more examples below. Ending index for slice (not included). Can be omitted. See more examples below. Step between indexes of slice. Can be omitted. See more examples below. ```py Example nums = [40, 41, 42, 43] del nums[0:2] # this implicitly calls `nums.__delslice__(0, 2, 1)` ``` Method `__delslice__` should never be called directly, instead `del list_obj[slice]` syntax should be used. Returns the length (the number of items) of a list\[T]. ```py Example nums = [40, 41, 42, 43] len(nums) # returns 4 (this implicitly calls `nums.__len__()`) ``` Method `__len__` should never be called directly, instead `len(list_obj)` syntax should be used. Returns `True` if the list is not empty. Returns `True` if the list contains the given value, otherwise `False`. Element to find in the list. ```py Example nums = [40, 41, 42, 43] my_bool = 41 in nums # this implicitly calls `nums.__contains__(41)` ``` Method `__contains__` should never be called directly, instead `val in lst` syntax should be used. Removes the first item from list `s` where `s[i]` is equal to given param. Value that will be removed from the list ```py Example nums = [40, 41, 42, 40, 41, 42] nums.remove(42) # now `nums` are [40, 41, 40, 41, 42] ``` Retrieves the item at given index and also removes it from the list. Index of an element in the list. ```py Example nums = [40, 41, 42, 43] meaning_of_life = nums.pop(2) # now `nums` are [40, 41, 43], `meaning_of_life` is 42 ``` Insert a value at the specified index. Index of an element in the list. New value that will be put to the list. ```py Example nums = [40, 41, 42, 43] nums.insert(2, 50) # now `nums` are [40, 41, 50, 42, 43] ``` Remove all items from the list. ```py Example nums = [40, 41, 42, 43] nums.clear() # now `nums` is [] ``` Reverses the elements of the list in place. Returns index of the first occurrence of the item in the list. If not found returns `-1`. Element to find in the list. Returns a slice of the list elements. Starting index for slice. Can be omitted. See more examples below. Ending index for slice (not included). Can be omitted. See more examples below. Step between indexes of slice. Can be omitted. See more examples below. ```py Example nums = [40, 41, 42, 43] meaning_of_life = nums[1:3] # returns [41, 42] (this implicitly calls `nums.__getslice__(1, 3, 1)`) ``` Method `__getslice__` should never be called directly, instead `list_obj[slice]` syntax should be used. Assigns given list to some\_list\[slice]. Starting index for slice. Can be omitted. See more examples below. Ending index for slice (not included). Can be omitted. See more examples below. Step between indexes of slice. Can be omitted. See more examples below. List to get values from. ```py Example nums = [40, 41, 42, 43] nums[1:3] = [50, 51, 52] # this implicitly calls `nums.__setslice__(1, 3, 1, [50, 51, 52])` # and now `nums` are [40, 50, 51, 52, 43] ``` Method `__setslice__` should never be called directly, instead `list_obj[slice] = other_list` syntax should be used. Returns a copy of the list. Extends the list by appending elements from the given list. List to concatenate with the current. Returns a concatenation of two lists. List to concatenate with the current. ```py Example nums1 = [40, 41] nums2 = [42, 43] nums3 = nums1 + nums2 # this implicitly calls `nums1.__add__(nums2)` ``` Method `__add__` should never be called directly, instead `list1 + list2` syntax should be used. Returns a concatenation of the list with `n` its copies. How many copies of the list to concatenate. ```py Example nums1 = [40, 41] nums2 = nums1 * 3 # this implicitly calls `nums1.__mul__(3)` # and now `nums2` is [40, 41, 40, 41, 40, 41] ``` Method `__mul__` should never be called directly, instead `lst * n` syntax should be used. ```py Example # examples of list creation: a = [1, 2, 3] # `a` has type `list[int]` b = [1, 2, 3, 4.2] # `b` has type `list[float]` c = ["a", "b", "c"] # `c` has type `list[str]` d = [(1, "a"), (2, "b"), (3, "c")] # `d` has type `list[tuple[int, str]]` e = [0, 1, 2, 3, 4, 5, 6, 7] f = e[2:5] # `f` is `[2, 3, 4]` g = e[:5] # `g` is `[0, 1, 2, 3, 4]` h = e[2:] # `h` is `[2, 3, 4, 5, 6, 7]` i = e[:] # `i` is a copy of `e` j = e[1:7:2] # `j` is `[1, 3, 5]` k = e[5:2:-1] # `k` is `[5, 4, 3]` l = e[5::-1] # `l` is `[5, 4, 3, 2, 1, 0]` m = e[::-1] # `m` is `[7, 6, 5, 4, 3, 2, 1, 0]` ``` *** ### `NoneType` *type* Builtin Indie type (similar to Python's `NoneType` type). *** ### `str` *type* Built-in Indie type (similar to Python's). Returns the length (the number of characters) of a `str`. ```py Example s = 'foobar' len(s) # returns 6 (this implicitly calls `s.__len__()`) ``` Method `__len__` should never be called directly, instead `len(str_obj)` syntax should be used. Cast constructor for built-in Indie type. Returns a `str` version of object. Value to cast from. Cast constructor for built-in Indie type. Returns a `str` version of object. Value to cast from. Cast constructor for built-in Indie type. Returns a `str` version of object. Value to cast from. Cast constructor for built-in Indie type. Returns a `str` version of object. Value to cast from. Returns `True` if the string contains the given substring, otherwise `False`. Substring to find in the string. ```py Example my_bool = 'cd' in 'abcdef' # this implicitly calls `'abcdef'.__contains__('cd')` ``` Method `__contains__` should never be called directly, instead `str1 in str2` syntax should be used. Returns a concatenation of two strings. String to concatenate with the current. ```py Example str1 = 'ab' str2 = 'cf' str3 = str1 + str2 # this implicitly calls `str1.__add__(str2)` ``` Method `__add__` should never be called directly, instead `str1 + str2` syntax should be used. Returns a concatenation of the string with `n` its copies. How many copies of the string to concatenate. ```py Example my_str = 'abc' my_str2 = 'abc' * 3 # this implicitly calls `'abc'.__mul__(3)` # and now `my_str2` is 'abcabcabc' ``` Method `__mul__` should never be called directly, instead `my_str * n` syntax should be used. Returns substring at given index. Index of an element in the string. ```py Example my_str = 'abc' substr = my_str[1] # returns "b" (this implicitly calls `my_str.__getitem__(1)`) ``` Method `__getitem__` should never be called directly, instead `my_str[key]` syntax should be used. Returns a slice of the string elements. Starting index for slice. Can be omitted. See more examples below. Ending index for slice (not included). Can be omitted. See more examples below. Step between indexes of slice. Can be omitted. See more examples below. ```py Example my_str = '0123' meaning_of_life = my_str[1:3] # returns '12' (this implicitly calls `my_str.__getslice__(1, 3, 1)`) ``` Method `__getslice__` should never be called directly, instead `str_obj[slice]` syntax should be used. Returns the string with the first letter capitalized. Centers the string within the specified width using a fill character. Length of the result string. Fill character. Returns the count of non-overlapping occurrences of a substring within \[start, end]. Value to search for. Start index to search. End index to search. Returns `True` if the string ends with the suffix, otherwise `False`. Value to check if the end of the string equals. Start index to check the end of the string. End index to check the end of the string. Returns the lowest index where the substring is found. Value to search for. Start index for searching. End index for searching. Use the `find()` method to get the position of a substring. To check for its presence, use the `in` operator. Returns the lowest index of the substring within \[start, end], raising an error if not found. Value to search for. Start index for searching. End index for searching. Returns `True` if the string contains only alphabetic characters and is not empty; otherwise, `False`. Returns `True` if all cased characters are lowercase and there is at least one, otherwise `False`. Returns `True` if the string contains only whitespace and is not empty, otherwise `False`. Returns `True` if all cased characters are uppercase and there is at least one, otherwise `False`. Returns a string that joins the elements of the list, using the string as a separator. List of strings to join. Left justifies the string within the specified width, padding with the fill character. Returns the original string if width is less than or equal to its length. Length of the result string. Fill character. Returns a copy of the string with all cased characters in lowercase. Returns a copy of the string with leading characters removed. Characters to remove. Splits the string at the first occurrence of sep and returns a list with the parts before, the separator, and after. String separator value. Returns a copy of the string with all occurrences of old replaced by new, or the first count occurrences if specified. Old value to search. New value to replace with. How many occurrences to replace. Returns the highest index of sub within \[start, end], or -1 if not found. Value to search for. Start index for searching. End index for searching. Returns the highest index of sub within \[start, end], raising an error if not found. Value to search for. Start index for searching. End index for searching. Right justifies the string within the specified width, padding with the fill character. Returns the original string if width is less than or equal to its length. Length of the result string. Fill character. Splits the string at the last occurrence of sep and returns a list with the parts before, the separator, and after. String separator value. Splits the string into words using sep as the delimiter, with an optional maxsplit from the right. String separator value. Number of splits. Returns a copy of the string with trailing characters removed. Characters to remove. Splits the string into words using sep as the delimiter, with at most maxsplit splits, resulting in up to maxsplit+1 elements. String separator value. Number of splits. Returns `True` if string starts with the prefix, otherwise `False`. Value to check if the beginning of the string equals. Start index to check the beginning of the string. End index to check the beginning of the string. Returns a string with the leading and trailing characters removed. Characters to remove. Returns a copy of the string with case swapped. Returns a copy of the string with all cased characters in uppercase. ```py Example # examples of slices extraction: a = '01234567' b = a[2:5] # `b` is '234' c = a[:5] # `c` is '01234' d = a[2:] # `d` is '234567' e = a[:] # `e` is a copy of `a` f = a[1:7:2] # `f` is '135' g = a[5:2:-1] # `g` is '543' h = a[5::-1] # `h` is '543210' i = a[::-1] # `i` is '76543210' ``` *** ### `tuple[...]` *type* Built-in Indie type (similar to Python's). *** # Package datetime Source: https://takeprofit.com/docs/indie/Library-reference/package-datetime export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; The datetime package supplies classes for manipulating dates and times. See description in the [official Python docs](https://docs.python.org/3.10/library/datetime.html). *** ## Types ### `datetime` *type* Represents date and time information. The year value of the datetime object. The month value of the datetime object. The day value of the datetime object. The hour value of the datetime object. The minute value of the datetime object. The second value of the datetime object. The microsecond value of the datetime object. Class constructor (initializer for the data type). Year value. Month value. Day value. Hour value. Minute value. Second value. Microsecond value. Returns the total number of seconds since the Unix epoch. Returns the day of the week as an integer, where Monday is 0 and Sunday is 6. `+` operator for `datetime` objects. Timedelta to add to the current datetime. `-` operator for `datetime` objects. Timedelta to subtract from the current datetime. `-` operator for `datetime` objects. Datetime to subtract from the current datetime. Returns the UTC datetime corresponding to the POSIX timestamp. Timestamp in UTC. Returns a datetime corresponding to `date_string`, parsed according to `format`. Datetime to parse. Datetime format. Supported codes: `%Y`, `%y`, `%m`, `%b`, `%d`, `%H`, `%I`, `%M`, `%S`, `%p`, `%f`, `%z`. See more details [here](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes). *** ### `time` *type* Represents a time of day, independent of any particular day. The hour value of the time object. The minute value of the time object. The second value of the time object. The microsecond value of the time object. Class constructor (initializer for the data type). Hour value. Minute value. Second value. Microsecond value. `+` operator for `time` objects. Timedelta to add to the current time. `-` operator for `time` objects. Timedelta to subtract from the current time. *** ### `timedelta` *type* A timedelta object represents a duration, the difference between two datetimes. The days value of the timedelta object. The seconds value of the timedelta object. The microseconds value of the timedelta object. Class constructor (initializer for the data type). Number of days. Number of seconds. Number of microseconds. Number of milliseconds. Number of minutes. Number of hours. Number of weeks. Returns the total number of seconds contained in the duration. *** # Package indie Source: https://takeprofit.com/docs/indie/Library-reference/package-indie export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Main package of Indie language. *** ## Decorators ### `@algorithm()` *decorator* Decorates a function, making it a *series processor* algorithm. Such algorithms are specifically designed to process series of data, like close prices of an instrument of a candle chart. One way of using such an algorithm is to call `new` static method, read more [here](/indie/How-Indies-syntactic-sugar-works#algorithmnew-method). Most of the functions in the `indie.algorithms` package are decorated with `@indie.algorithm` decorator. Read more about it in [Series processors](/indie/Algorithms-for-series-processing) chapter. See also: [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) *** ### `@band()` *decorator* Use this decorator to add a band (two horizontal lines usually with a semi-transparent fill in between them) to indicator. Value of the first horizontal line of a band on a vertical scale of an indicator. Value of the second horizontal line of a band on a vertical scale of an indicator. Human readable title which is visible in the indicator's Settings panel. Color of the background. Color of the plot on a chart. This color can be overwritten if the plot is a multicolored one. Example of an indicator with a multicolored plot is *Awesome Oscillator (AO)*. Style of the line. It is represented as enum value of type `line_style`. Width of the line. ```py Example @indicator('Band example') @band(145, 155, line_color=color.RED, line_width=4) def Main(self): return self.close[0] ``` See also: [`@level()`](/indie/Library-reference/package-indie#decor_level) *** ### `@indicator()` *decorator* Decorator that should be applied to the `Main` entry point of any indicator. Abbreviated title of the indicator. Whether or not to overlay the indicator over the main pane of the chart. The main pane of a chart is the one with the main instrument on it. Formatting style of indicator output values represented as enum value of type `format`. Number of digits after floating point for indicator output values. See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) *** ### `@level()` *decorator* Decorator that is used to create a level (horizontal line) in an indicator. Value of the level on a vertical scale of an indicator. Human readable title which is visible in the indicator's Settings panel. Color of the plot on a chart. This color can be overwritten if the plot is a multicolored one. Example of an indicator with a multicolored plot is *Awesome Oscillator (AO)*. Style of the line. It is represented as enum value of type `line_style`. Width of the line. ```py Example @indicator('Level example') @level(150, line_color=color.RED, line_width=4) def Main(self): return self.close[0] ``` See also: [`@band()`](/indie/Library-reference/package-indie#decor_band) *** ### `@param_ref()` *decorator* Declares an input parameter for `@sec_context` function that is linked to the input parameter of `Main` by `id`. Name of `Main` function or class parameter bound to the input parameter. ```py Example @sec_context @param_ref('referenced_param') def SecMain(self, referenced_param) -> float: # Use referenced_param variable... @indicator('Referenced param example') @param.int('referenced_param', default=50) class Main(MainContext): def __init__(self): self._calc_on_result = self.calc_on(time_frame=TimeFrame.from_str('1D'), sec_context=SecMain) def calc(self): return self._calc_on_result[0] ``` See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) [`param`](/indie/Library-reference/package-indie#class_param) *** ### `param` *type* Class with decorators of indicator input parameters of various types. Declares a bool input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.bool('is_something_enabled', default=False) def Main(self, is_something_enabled): # Use is_something_enabled variable... ``` Declares an integer input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. Minimum value of the parameter. Maximum value of the parameter. Step between values of the parameter. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.int('meaning_of_life', default=42) def Main(self, meaning_of_life): # Use meaning_of_life variable... ``` Declares a float input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. Minimum value of the parameter. Maximum value of the parameter. Step between values of the parameter. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.float('speed_of_light', default=299_792.458) def Main(self, speed_of_light): # Use speed_of_light variable... ``` Declares a str input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. List of the possible values of the parameter. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.str('name', default='Lisa', options=['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']) def Main(self, name): # Use name variable... ``` If `options` parameter is used then in Settings panel there will be a combobox widget for changing value of this input. Declares a source input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. List of the possible values of the parameter. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.source('src', default=source.CLOSE, options=[source.CLOSE, source.HL2, source.HLC3, source.OHLC4]) def Main(self, src): # Use src variable... ``` Even if `options` parameter is not used then in Settings panel nevertheless there will be a combobox widget with all possible values from the `source` enum. See also: [`param`](/indie/Library-reference/package-indie#class_param) [`source`](/indie/Library-reference/package-indie#enum_source) Declares a time frame input parameter of indicator. Values of input parameters can be changed in indicator's Settings panel. Input parameters are used in combination with corresponding parameter declaration in `Main` entry point. Name of `Main` function or class parameter bound to the input parameter. Default value for the parameter in settings pane. List of the possible values of the parameter. Human readable title which is visible in the indicator's Settings panel. ```py Example @param.time_frame('time_frame', default='30m', options=['1m', '30m', '1h', '4h', '1D', '1W', '1M', '1Y']) def Main(self, time_frame): # Use time_frame variable... ``` The type of `time_frame` in the example variable will be `TimeFrame`. But please note, that for the convenience, default value has `str` type. String representation of `TimeFrame` has a form of `[m|h|D|W|M|Y]` where suffixes mean: `m` - minutes, `h` - hours, `D` - days, `W` - weeks, `M` - months, `Y` - years. If `options` parameter is used then in Settings panel there will be a combobox widget for changing value of this input. See also: [`TimeFrame`](/indie/Library-reference/package-indie#class_TimeFrame) *** ### `@sec_context()` *decorator* Decorates a function, making it a secondary `Main` entry point for additional instrument of an indicator. Additional instruments are requested with the help of `Context.calc_on` function and this decorator. ```py Example # indie:lang_version = 5 from indie import indicator, sec_context, param @sec_context def Main2(self): return self.high[0], self.low[0] @indicator('Minimal calc_on example', overlay_main_pane=True) @param.time_frame('sec_time_frame', default='1D') class Main(MainContext): def __init__(self, sec_time_frame): self._sec_high, self._sec_low = self.calc_on(time_frame=sec_time_frame, sec_context=Main2) def calc(self): return self._sec_high[0], self._sec_low[0] ``` More info on this topic you can find in [Request additional instruments](/indie/Request-additional-instruments) chapter. See also: [`@indicator()`](/indie/Library-reference/package-indie#decor_indicator) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) [`Context.calc_on()`](/indie/Library-reference/package-indie#method_Context_calc_on) *** ## Types ### `Algorithm` *type* Base class for the classes that perform some processing of series data. Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. See also: [`@algorithm()`](/indie/Library-reference/package-indie#decor_algorithm) [`MainContext`](/indie/Library-reference/package-indie#class_MainContext) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) *** ### `Color` *type* Data type to represent color. Creates a new Color instance with the given transparency applied to the existing color. Alpha channel (component) of color which ranges from `0.0` (fully transparent) to `1.0` (fully opaque). ```py Example half_transparent_red = color.RED(0.5) # This implicitly calls `color.RED.__call__(0.5)` ``` Method `__call__` should never be called directly, instead `color_obj(value)` syntax should be used. See also: [`color`](/indie/Library-reference/package-indie-color) *** ### `Context` *type* Data type that represents an instrument with OHLCV series values and other related information. Series of timestamps (as unix time UTC seconds) of the context's instrument. Every timestamp corresponds to start time of some bar on a chart. Series of 'open' prices of the context's instrument. Series of 'high' prices of the context's instrument. Series of 'low' prices of the context's instrument. Series of 'close' prices of the context's instrument. Series of 'volume' values of the context's instrument. Series of '(high + low) / 2' values of the context's instrument. Series of '(high + low + close) / 3' values of the context's instrument. Series of '(open + high + low + close) / 4' values of the context's instrument. Information about the context's instrument. Index of a last (current) bar in this context's instrument which the indicator has received. The very first bar has index equal to `0` and this is the oldest bar. Current total number of bars in this context's instrument which the indicator has received. It is always true that `self.bar_count` is equal to `self.bar_index + 1`. Flag that is `True` if the current bar is a historical bar or it is a final update for a realtime bar. Flag that is `True` if the current bar is a historical bar. Flag that is `True` if the current bar is the last bar in the history or it is a realtime bar. Flag that is `True` if the current bar is the last bar of the historical part of prices data. Flag that is `True` if the current bar is a historical bar or it is a first update for a realtime bar. Flag that is `True` if the last (current) bar is a realtime bar. Time frame of the context's instrument. Trading session of the context's instrument. Requests additional instrument (creates a secondary context object for it) for indicator and returns one or more `SeriesF` objects which match with the arity of values that `sec_context` function returns. All the returned series values are merged into the timescale of current context's instrument. Function decorated with `@indie.sec_context`. This function has the same semantics as Indie `Main`, but for additional instrument (not the main one). Alias for exchange of additional instrument. If omitted, then the exchange of the current context's instrument will be used. Ticker of an additional instrument. If omitted, then the ticker of the current context's instrument will be used. Time frame of additional instrument. If omitted, then the time frame of current context's instrument will be used. At the moment it is allowed to request only time frames which are higher or equal to the time frame of current context's instrument. If this flag is true, then when calculating history, the bars of the secondary context are merged with the bars of the current context based on their opening time. Such a data merge strategy may result in unintended use of data from future history. At least one of optional arguments (`exchange`, `ticker` or `time_frame`) must be provided. More info about this function as well as code examples you may find in [Request additional instruments](/indie/Request-additional-instruments) chapter. See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) Creates a `MutSeriesF` (an alias for `MutSeries[float]`) object, which is a container for `float` values in Indie code. The main feature of the `MutSeriesF` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeriesF` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeriesF` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. See also: [`MutSeriesF`](/indie/Library-reference/package-indie#class_MutSeriesF) Creates a `MutSeries[T]` object, which is a container for `T` values in Indie code. The main feature of the `MutSeries[T]` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeries` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeries` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. Creates a `Var[T]` object, which is a container for `T` value in Indie code. The main feature of the `Var[T]` container is its ability to rollback the value of the variable when a new realtime update appears to its value after the previous bar. Value that is written into `Var` object only once after the `Var` object was created. Detects whether the current bar is the first bar of a new trading session (extended session included). Returns `True` if the current bar is the first bar of the trading session or `False` if the current bar is not the first in the session or if no session has started. The function will return `False` if the first bar of the session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the first bar of the regular trading session (excluding pre-market session). Returns `True` if the current bar is the first bar of the regular trading session or `False` if the current bar is not the first in the regular session or if no session has started. The function will return `False` if the first bar of the regular session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the last bar of the trading session (extended session included). Returns `True` if the current bar is the last bar of the trading session or `False` if the current bar is not the last in the session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). Detects whether the current bar is the last bar of the regular trading session (excluding after-hours session). Returns `True` if the current bar is the last bar of the regular trading session or `False` if the current bar is not the last in the regular session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). See also: [`MainContext`](/indie/Library-reference/package-indie#class_MainContext) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) [`SymbolInfo`](/indie/Library-reference/package-indie#class_SymbolInfo) [`Series[T]`](/indie/Library-reference/package-indie#class_Series) [`MutSeries[T]`](/indie/Library-reference/package-indie#class_MutSeries) [`TradingSession`](/indie/Library-reference/package-indie#class_TradingSession) *** ### `IndieError` *type* Data type for Indie errors. Class constructor (initializer for the data type). Error message. *** ### `MainContext` *type* Base class for the class that represents main context. [`Context`](/indie/Library-reference/package-indie#class_Context) Series of timestamps (as unix time UTC seconds) of the context's instrument. Every timestamp corresponds to start time of some bar on a chart. Series of 'open' prices of the context's instrument. Series of 'high' prices of the context's instrument. Series of 'low' prices of the context's instrument. Series of 'close' prices of the context's instrument. Series of 'volume' values of the context's instrument. Series of '(high + low) / 2' values of the context's instrument. Series of '(high + low + close) / 3' values of the context's instrument. Series of '(open + high + low + close) / 4' values of the context's instrument. Information about the context's instrument. Index of a last (current) bar in this context's instrument which the indicator has received. The very first bar has index equal to `0` and this is the oldest bar. Current total number of bars in this context's instrument which the indicator has received. It is always true that `self.bar_count` is equal to `self.bar_index + 1`. Flag that is `True` if the current bar is a historical bar or it is a final update for a realtime bar. Flag that is `True` if the current bar is a historical bar. Flag that is `True` if the current bar is the last bar in the history or it is a realtime bar. Flag that is `True` if the current bar is the last bar of the historical part of prices data. Flag that is `True` if the current bar is a historical bar or it is a first update for a realtime bar. Flag that is `True` if the last (current) bar is a realtime bar. Time frame of the context's instrument. Trading session of the context's instrument. Requests additional instrument (creates a secondary context object for it) for indicator and returns one or more `SeriesF` objects which match with the arity of values that `sec_context` function returns. All the returned series values are merged into the timescale of current context's instrument. Function decorated with `@indie.sec_context`. This function has the same semantics as Indie `Main`, but for additional instrument (not the main one). Alias for exchange of additional instrument. If omitted, then the exchange of the current context's instrument will be used. Ticker of an additional instrument. If omitted, then the ticker of the current context's instrument will be used. Time frame of additional instrument. If omitted, then the time frame of current context's instrument will be used. At the moment it is allowed to request only time frames which are higher or equal to the time frame of current context's instrument. If this flag is true, then when calculating history, the bars of the secondary context are merged with the bars of the current context based on their opening time. Such a data merge strategy may result in unintended use of data from future history. At least one of optional arguments (`exchange`, `ticker` or `time_frame`) must be provided. More info about this function as well as code examples you may find in [Request additional instruments](/indie/Request-additional-instruments) chapter. See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) Creates a `MutSeriesF` (an alias for `MutSeries[float]`) object, which is a container for `float` values in Indie code. The main feature of the `MutSeriesF` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeriesF` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeriesF` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. See also: [`MutSeriesF`](/indie/Library-reference/package-indie#class_MutSeriesF) Creates a `MutSeries[T]` object, which is a container for `T` values in Indie code. The main feature of the `MutSeries[T]` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeries` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeries` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. Creates a `Var[T]` object, which is a container for `T` value in Indie code. The main feature of the `Var[T]` container is its ability to rollback the value of the variable when a new realtime update appears to its value after the previous bar. Value that is written into `Var` object only once after the `Var` object was created. Detects whether the current bar is the first bar of a new trading session (extended session included). Returns `True` if the current bar is the first bar of the trading session or `False` if the current bar is not the first in the session or if no session has started. The function will return `False` if the first bar of the session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the first bar of the regular trading session (excluding pre-market session). Returns `True` if the current bar is the first bar of the regular trading session or `False` if the current bar is not the first in the regular session or if no session has started. The function will return `False` if the first bar of the regular session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the last bar of the trading session (extended session included). Returns `True` if the current bar is the last bar of the trading session or `False` if the current bar is not the last in the session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). Detects whether the current bar is the last bar of the regular trading session (excluding after-hours session). Returns `True` if the current bar is the last bar of the regular trading session or `False` if the current bar is not the last in the regular session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). See also: [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) [`Context`](/indie/Library-reference/package-indie#class_Context) [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) *** ### `MutSeries[T]` *type* Generic data type that represents read-write series of values of type `T`. Type `T` can be float, int, str, or almost any other type. ```py MutSeriesF = MutSeries[float] ``` [`Series[T]`](/indie/Library-reference/package-indie#class_Series) Sets value of `MutSeries[T]` object at the specified index. Index to assign value at. New value. ```py Example ms = MutSeries[float].new(init=0) ms[0] = 42 # This implicitly calls `ms.__setitem__(0, 42)` ``` (1) The index must be equal to 0 (because historical values cannot be updated), otherwise the function will raise an error at runtime. Yes, this looks very weird and maybe it would be much better just to have a method `MutSeriesF.set_last(value: float)` but we like the syntax of square brackets. Maybe this will be fixed in the future versions of Indie, hard to say for sure. (2) Method `__setitem__` should never be called directly, instead syntax `series_obj[index] = value` should be used. Recalculates a `MutSeries[T]` object. In most cases, you can simply use the `s[i] = ...` syntax instead, but this method allows you to pass an initialization value to the series. Value that is written into the most recent element of the `MutSeries` every time `MutSeries.new` function is executed. Value that is written into the most recent element of the `MutSeries` object only once after the `MutSeries` object was created. Number of elements that `MutSeries` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeries` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. Creates a `MutSeries[T]` object, which is a container for `T` values in Indie code. The main feature of the `MutSeries[T]` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Value that is written into the most recent element of the `MutSeries` every time `MutSeries.new` function is executed. Value that is written into the most recent element of the `MutSeries` object only once after the `MutSeries` object was created. Number of elements that `MutSeries` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeries` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. See also: [`Context.new_mut_series()`](/indie/Library-reference/package-indie#method_Context_new_mut_series) Returns value of `Series[T]` object at the specified index or given `default` if the value is missing. Offset to extract value at. Default value that will be used if an element at the specified index cannot be extracted. If `False` then `get` method raises an error on any `offset < 0`. If `True` then `get` method returns `default` value on negative offsets too. Default value is `False`. Expands the capacity of `Series[T]` object (number of elements that `Series[T]` object should store in memory). Number of elements that `SeriesF` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. Returns value of `Series[T]` object at the specified index. If the value is missing, then the default value of type `T` is returned (e.g. `math.nan` if `T` is float). Index to extract value at. ```py Example @indicator('Example') def Main(self): return self.close[0] # This implicitly calls `self.close.__getitem__(0)` ``` Method `__getitem__` should never be called directly. Instead syntax `series_obj[index]` should be used. Returns length (number of elements) of a `Series[T]` object. ```py Example l = len(self.close) # this implicitly calls `self.close.__len__()` ``` Method `__len__` should never be called directly. Instead syntax `len(series_obj)` should be used. See also: [`Context.new_mut_series()`](/indie/Library-reference/package-indie#method_Context_new_mut_series) [`Series[T]`](/indie/Library-reference/package-indie#class_Series) *** ### `Optional[T]` *type* Builtin Indie type (similar to Python's `typing.Optional`). Class constructor (initializer for the data type). Value to cast from. Class constructor (initializer for the data type). Returns value of `indie.Optional[T]` object. Raises a runtime error if the optional object is `None`. Returns value of `indie.Optional[T]` object or given `default` if the optional object is `None`. Default value that will be used if there is no value. Casts `Optional` object to bool. This method is present for `Optional[T]` only if `T` can be converted to `bool`. Returns `True` if the optional value is `None`, otherwise `False`. ```py Example my_val: Optional[int] = 4 my_bool = my_val is None ``` Method `__isnone__` should never be called directly, instead `val is None` syntax should be used. *** ### `SecContext` *type* Base class for the classes that represent additional contexts besides the main one. [`Context`](/indie/Library-reference/package-indie#class_Context) Series of timestamps (as unix time UTC seconds) of the context's instrument. Every timestamp corresponds to start time of some bar on a chart. Series of 'open' prices of the context's instrument. Series of 'high' prices of the context's instrument. Series of 'low' prices of the context's instrument. Series of 'close' prices of the context's instrument. Series of 'volume' values of the context's instrument. Series of '(high + low) / 2' values of the context's instrument. Series of '(high + low + close) / 3' values of the context's instrument. Series of '(open + high + low + close) / 4' values of the context's instrument. Information about the context's instrument. Index of a last (current) bar in this context's instrument which the indicator has received. The very first bar has index equal to `0` and this is the oldest bar. Current total number of bars in this context's instrument which the indicator has received. It is always true that `self.bar_count` is equal to `self.bar_index + 1`. Flag that is `True` if the current bar is a historical bar or it is a final update for a realtime bar. Flag that is `True` if the current bar is a historical bar. Flag that is `True` if the current bar is the last bar in the history or it is a realtime bar. Flag that is `True` if the current bar is the last bar of the historical part of prices data. Flag that is `True` if the current bar is a historical bar or it is a first update for a realtime bar. Flag that is `True` if the last (current) bar is a realtime bar. Time frame of the context's instrument. Trading session of the context's instrument. Requests additional instrument (creates a secondary context object for it) for indicator and returns one or more `SeriesF` objects which match with the arity of values that `sec_context` function returns. All the returned series values are merged into the timescale of current context's instrument. Function decorated with `@indie.sec_context`. This function has the same semantics as Indie `Main`, but for additional instrument (not the main one). Alias for exchange of additional instrument. If omitted, then the exchange of the current context's instrument will be used. Ticker of an additional instrument. If omitted, then the ticker of the current context's instrument will be used. Time frame of additional instrument. If omitted, then the time frame of current context's instrument will be used. At the moment it is allowed to request only time frames which are higher or equal to the time frame of current context's instrument. If this flag is true, then when calculating history, the bars of the secondary context are merged with the bars of the current context based on their opening time. Such a data merge strategy may result in unintended use of data from future history. At least one of optional arguments (`exchange`, `ticker` or `time_frame`) must be provided. More info about this function as well as code examples you may find in [Request additional instruments](/indie/Request-additional-instruments) chapter. See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) [`SecContext`](/indie/Library-reference/package-indie#class_SecContext) Creates a `MutSeriesF` (an alias for `MutSeries[float]`) object, which is a container for `float` values in Indie code. The main feature of the `MutSeriesF` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeriesF` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeriesF` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. See also: [`MutSeriesF`](/indie/Library-reference/package-indie#class_MutSeriesF) Creates a `MutSeries[T]` object, which is a container for `T` values in Indie code. The main feature of the `MutSeries[T]` container is its ability to store (or 'remember') the historical values of a variable. These values can be accessed later using the square brackets operator (via the `__getitem__` method). Default value that will be used if an element at the specified index cannot be extracted. Number of elements that `MutSeries` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. `MutSeries` objects also have a method `request_size(new_size: int)` which can be used to expand the size explicitly. Creates a `Var[T]` object, which is a container for `T` value in Indie code. The main feature of the `Var[T]` container is its ability to rollback the value of the variable when a new realtime update appears to its value after the previous bar. Value that is written into `Var` object only once after the `Var` object was created. Detects whether the current bar is the first bar of a new trading session (extended session included). Returns `True` if the current bar is the first bar of the trading session or `False` if the current bar is not the first in the session or if no session has started. The function will return `False` if the first bar of the session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the first bar of the regular trading session (excluding pre-market session). Returns `True` if the current bar is the first bar of the regular trading session or `False` if the current bar is not the first in the regular session or if no session has started. The function will return `False` if the first bar of the regular session does not exist or is unavailable (e.g., due to data gaps or missing information). Detects whether the current bar is the last bar of the trading session (extended session included). Returns `True` if the current bar is the last bar of the trading session or `False` if the current bar is not the last in the session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). Detects whether the current bar is the last bar of the regular trading session (excluding after-hours session). Returns `True` if the current bar is the last bar of the regular trading session or `False` if the current bar is not the last in the regular session. The function will return `False` if the session ends without a valid last bar (e.g., due to missing data). See also: [`@sec_context()`](/indie/Library-reference/package-indie#decor_sec_context) [`MainContext`](/indie/Library-reference/package-indie#class_MainContext) [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) *** ### `Series[T]` *type* Generic data type that represents read only series of values of type `T`. Type `T` can be float, int, str, or almost any other type. ```py SeriesF = Series[float] ``` Returns value of `Series[T]` object at the specified index or given `default` if the value is missing. Offset to extract value at. Default value that will be used if an element at the specified index cannot be extracted. If `False` then `get` method raises an error on any `offset < 0`. If `True` then `get` method returns `default` value on negative offsets too. Default value is `False`. Expands the capacity of `Series[T]` object (number of elements that `Series[T]` object should store in memory). Number of elements that `SeriesF` object should store in memory. Default and possible minimum size is 2, which means that series of `size = 2` stores in memory value at the time of the last candle and value at the time of previous candle. Size is automatically expanded during history calculation of an indicator. Returns value of `Series[T]` object at the specified index. If the value is missing, then the default value of type `T` is returned (e.g. `math.nan` if `T` is float). Index to extract value at. ```py Example @indicator('Example') def Main(self): return self.close[0] # This implicitly calls `self.close.__getitem__(0)` ``` Method `__getitem__` should never be called directly. Instead syntax `series_obj[index]` should be used. Returns length (number of elements) of a `Series[T]` object. ```py Example l = len(self.close) # this implicitly calls `self.close.__len__()` ``` Method `__len__` should never be called directly. Instead syntax `len(series_obj)` should be used. See also: [`MutSeries[T]`](/indie/Library-reference/package-indie#class_MutSeries) [`Context`](/indie/Library-reference/package-indie#class_Context) *** ### `SymbolInfo` *type* Data type to represent information about the context's instrument. Ticker of the context's instrument. Exchange code of the context's instrument. For stocks it is a [MIC](https://en.wikipedia.org/wiki/Market_Identifier_Code). For crypto instruments it is just some identifier, not commonly recognized as MIC but unique within TakeProfit. For example, `exchange_code` for the New York Stock Exchange, Inc. is `'XNYS'`. Commonly recognized (but not exactly standardized) alias for an exchange. For example, an alias for the New York Stock Exchange, Inc. is `'NYSE'`. In most cases exchange alias matches with the exchange acronym (see ISO10383). Price precision of the context's instrument. For example, price precision of `100` means that prices have two digits after the floating point. Absolute value of a minimal movement of a price of the context's instrument in corresponding currency. Name of the exchange timezone of the context's instrument. For example, `'America/New_York'`. See also: [`Context`](/indie/Library-reference/package-indie#class_Context) *** ### `TimeFrame` *type* Data type that represents time frame. Class constructor (initializer for the data type). Numeric part of time frame. Unit of time frame, can be 'm', 'h', 'D', 'W' or 'M'. Converts `TimeFrame` object to corresponding number of minutes. Month is always considered to be of 30 days long, and year is always of 365 days long. Converts string representation of time frame to `TimeFrame` type. String representation of `TimeFrame` has a form of `[m|h|D|W|M|Y]` where suffixes mean: `m` - minutes, `h` - hours, `D` - days, `W` - weeks, `M` - months, `Y` - years. For example `TimeFrame.from_str('15m')` creates a `TimeFrame` object which corresponds to 15 minute time frame. String representation of time frame. *** ### `TradingSession` *type* Data type to represent different trading periods within a day, including pre-market, regular, and after-hours sessions. Each period is defined by its own schedule. Schedule instance that defines the rules and exceptions for the pre-market trading session. Schedule instance that defines the rules and exceptions for the regular trading session. Schedule instance that defines the rules and exceptions for the after-hours trading session. Schedule instance that defines the rules and exceptions for the extended session (pre-market + after-hours). Checks whether a given timestamp falls within the defined trading session. Returns `True` if the timestamp falls within the trading session's active periods, otherwise returns `False`. Timestamp to check in defined trading session. Checks whether a given timestamp falls within the defined trading session. Returns `True` if the timestamp falls within the trading session's active periods, otherwise returns `False`. Datetime to check in defined trading session. Determines whether two timestamps fall within the same trading session period on the same day. Returns `True` if both timestamps fall within the same period of the trading session, even if they are in different calendar days. False if the timestamps belong to different periods within the trading session. First timestamp to check. Second timestamp to check. This method checks if two timestamps, which may belong to different calendar days, are part of the same trading session period. It handles cases where a trading session spans across two consecutive days (e.g., a trading schedule that extends past midnight) and ensures both timestamps belong to the same logical period within the schedule. Determines whether a given timestamp falls within a regular trading session. Timestamp to check against the specific part of trading sessions. Determines whether a given timestamp falls within an extended trading session (either pre-market or after-hours). Timestamp to check against the specific part of trading sessions. Returns `True` if the provided timestamp falls within either the pre-market or after-hours session. Returns `False` otherwise. Determines whether a given timestamp falls within a pre-market trading session. Timestamp to check against the specific part of trading sessions. Determines whether a given timestamp falls within a after-hours trading session. Timestamp to check against the specific part of trading sessions. See also: [`Context`](/indie/Library-reference/package-indie#class_Context) [`Schedule`](/indie/Library-reference/package-indie-schedule#class_Schedule) [`ScheduleRule`](/indie/Library-reference/package-indie-schedule#class_ScheduleRule) *** ### `Var[T]` *type* Generic data type that represents a rollbackable container for value of type `T`. Type `T` can be float, int, str, or almost any other type. Returns value of `Var[T]` object. Sets value of `Var[T]` object. New value that will be put to `Var` object. Creates a `Var[T]` object, which is a container for `T` value in Indie code. The main feature of the `Var[T]` container is its ability to rollback the value of the variable when a new realtime update appears to its value after the previous bar. Value that is written into `Var` object only once after the `Var` object was created. See also: [`Context.new_var()`](/indie/Library-reference/package-indie#method_Context_new_var) [`MutSeries[T]`](/indie/Library-reference/package-indie#class_MutSeries) *** ## Enums ### `format` *enum* Enum-like class with constants that determine how to format the indicator value on the price scale. Indicator output values are formatted same as values of the main chart instrument. Indicator output values are formatted using fixed number of digits after the floating point. The number of digits is set with additional parameter `precision` of `@indicator()`. The `precision` param has effect only in combination with the `format.PRICE` format. Indicator output values are formatted according to the rules of formatting large numbers, such as volumes of trades. For example `100500.0` will be formatted as `100.5K`. See also: [`@indicator()`](/indie/Library-reference/package-indie#decor_indicator) *** ### `line_style` *enum* Enum-like class with constants of line styles. Built-in line style constant that determines how the line is rendered. Built-in line style constant that determines how the line is rendered. Built-in line style constant that determines how the line is rendered. See also: [`@line()`](/indie/Library-reference/package-indie-plot#decor_line) [`@level()`](/indie/Library-reference/package-indie#decor_level) [`@fill()`](/indie/Library-reference/package-indie-plot#decor_fill) *** ### `source` *enum* Enum-like class with constants for various price sources (it is used in `@indie.param.source`). Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. Built-in source kind constant which corresponds to `Context`'s series field and is used to initialize source input parameter. See also: [`@param.source()`](/indie/Library-reference/package-indie#decor_param_source) *** ### `time_frame_unit` *enum* Enum-like class with constants for time frame units. Built-in constants that represent time frame units. Built-in constants that represent time frame units. Built-in constants that represent time frame units. Built-in constants that represent time frame units. Built-in constants that represent time frame units. See also: [`TimeFrame`](/indie/Library-reference/package-indie#class_TimeFrame) *** # Package indie.algorithms Source: https://takeprofit.com/docs/indie/Library-reference/package-indie-algorithms export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Algorithms package of Indie language. *** ## Types ### `Adx` *type* Average directional index algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Minus Directional Indicator*, *Average Directional Index* and *Plus Directional Indicator*. Number of bars to calculate smoothing. Number of bars to calculate directional indicator. Returns series of *Minus Directional Indicator*, *Average Directional Index* and *Plus Directional Indicator*. Number of bars to calculate smoothing. Number of bars to calculate directional indicator. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Adx @indicator('Example') def Main(self): minus_di, adx, plus_di = Adx.new(adx_len=9, di_len=12) return minus_di[0], adx[0], plus_di[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Change, Rma, Tr, FixNan from indie.math import divide @algorithm def Adx(self, adx_len: int, di_len: int) -> tuple[SeriesF, SeriesF, SeriesF]: '''Average Directional Index''' up = Change.new(self.ctx.high)[0] down = -Change.new(self.ctx.low)[0] plus_dm = MutSeriesF.new(0 if up <= down or up <= 0 else up) minus_dm = MutSeriesF.new(0 if down <= up or down <= 0 else down) truerange = Rma.new(Tr.new(), di_len) plus = MutSeriesF.new(100 * divide(Rma.new(plus_dm, di_len)[0], truerange[0])) minus = MutSeriesF.new(100 * divide(Rma.new(minus_dm, di_len)[0], truerange[0])) plus[0] = FixNan.new(plus)[0] minus[0] = FixNan.new(minus)[0] sum = plus[0] + minus[0] res = 100 * Rma.new(MutSeriesF.new(abs(plus[0] - minus[0]) / (sum if sum != 0 else 1)), adx_len)[0] return minus, MutSeriesF.new(res), plus ``` *** ### `Atr` *type* Average true range algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Average True Range* values calculated for the `length` bars period using moving average specified by `ma_algorithm` argument. Number of bars in calculation taken into account. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. Returns series of *Average True Range* values calculated for the `length` bars period using moving average specified by `ma_algorithm` argument. Number of bars in calculation taken into account. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Atr @indicator('Example') def Main(self): atr = Atr.new(length=12, ma_algorithm='SMA') return atr[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF from indie.algorithms import Tr, Ma @algorithm def Atr(self, length: int, ma_algorithm: str = 'RMA') -> SeriesF: '''Average True Range''' return Ma.new(Tr.new(True), length, ma_algorithm) ``` *** ### `Bb` *type* Bollinger bands algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns middle, upper and lower series of *Bollinger Bands* calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Multiplier for standard deviation. Returns middle, upper and lower series of *Bollinger Bands* calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Multiplier for standard deviation. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Bb @indicator('Example', overlay_main_pane=True) def Main(self): lower, middle, upper = Bb.new(self.close, length=20, mult=2.0) return lower[0], middle[0], upper[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma, StdDev @algorithm def Bb(self, src: SeriesF, length: int, mult: float) -> tuple[SeriesF, SeriesF, SeriesF]: '''Bollinger Bands''' middle = Sma.new(src, length)[0] dev = mult * StdDev.new(src, length)[0] lower = middle - dev upper = middle + dev return MutSeriesF.new(lower), MutSeriesF.new(middle), MutSeriesF.new(upper) ``` *** ### `Cci` *type* Commodity channel index algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Commodity Channel Index* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Commodity Channel Index* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Cci @indicator('Example') def Main(self): cci = Cci.new(self.close, length=20) return cci[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma, Dev from indie.math import divide @algorithm def Cci(self, src: SeriesF, length: int) -> SeriesF: '''Commodity Channel Index''' ma = Sma.new(src, length)[0] dv = Dev.new(src, length)[0] res = divide(src[0] - ma, 0.015 * dv) return MutSeriesF.new(res) ``` *** ### `Change` *type* Algorithm to calculate change of a series of values. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns the difference between current `src` value and its value `length` bars ago. Series data to perform the calculation. Number of bars ago to compare the current value. Returns the difference between current `src` value and its value `length` bars ago. Series data to perform the calculation. Number of bars ago to compare the current value. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Change @indicator('Example') def Main(self): ch = Change.new(self.close) return ch[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def Change(self, src: SeriesF, length: int = 1) -> SeriesF: return MutSeriesF.new(src[0] - src[length]) ``` *** ### `Corr` *type* Correlation coefficient algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Correlation Coefficient* values calculated from `x` and `y` series for the `length` bars period. First series to calculate correlation with. Second series to calculate correlation with. Number of bars in calculation taken into account. Returns series of *Correlation Coefficient* values calculated from `x` and `y` series for the `length` bars period. First series to calculate correlation with. Second series to calculate correlation with. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Corr @indicator('Example') def Main(self): corr = Corr.new(self.close, self.open, length=14) return corr[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma, StdDev from indie.math import divide @algorithm def Corr(self, x: SeriesF, y: SeriesF, length: int) -> SeriesF: # NOTE: `cov` could be calculated as `E(x*y) - E(x)*E(y)`, # but that may cause precision issues with floating-point arithmetic e_x = Sma.new(x, length)[0] e_y = Sma.new(y, length)[0] cov = 0.0 for i in range(length): cov += (x[i] - e_x) * (y[i] - e_y) cov /= length std_devs = StdDev.new(x, length)[0] * StdDev.new(y, length)[0] corr = divide(cov, std_devs, 0.0) return MutSeriesF.new(corr) ``` *** ### `CumSum` *type* Cumulative sum algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of cumulative sum of `src` values. Series data to perform the calculation. Returns series of cumulative sum of `src` values. Series data to perform the calculation. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import CumSum @indicator('Example') def Main(self): cs = CumSum.new(self.close) return cs[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def CumSum(self, src: SeriesF) -> SeriesF: res = MutSeriesF.new(init=0) res[0] += src[0] return res ``` *** ### `Dev` *type* Mean absolute deviation algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Mean Absolute Deviation* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Mean Absolute Deviation* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Dev @indicator('Example') def Main(self): dev = Dev.new(self.close, length=12) return dev[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma @algorithm def Dev(self, src: SeriesF, length: int) -> SeriesF: '''Mean Absolute Deviation''' mean = Sma.new(src, length)[0] sum = 0.0 for i in range(length): sum += abs(src[i] - mean) return MutSeriesF.new(sum / length) ``` *** ### `Donchian` *type* Donchian channels algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Middle Channel* of *Donchian Channels* calculated for the `length` bars period. Number of bars in calculation taken into account. Returns series of *Middle Channel* of *Donchian Channels* calculated for the `length` bars period. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Donchian @indicator('DC', overlay_main_pane=True) def Main(self): d = Donchian.new(length=20) return d[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, MutSeriesF, SeriesF from indie.algorithms import Lowest, Highest @algorithm def Donchian(self, length: int) -> SeriesF: lowest = Lowest.new(self.ctx.low, length)[0] highest = Highest.new(self.ctx.high, length)[0] return MutSeriesF.new((lowest + highest) / 2) ``` *** ### `Ema` *type* Exponential moving average algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Exponential Moving Average* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Exponential Moving Average* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Ema @indicator('Example', overlay_main_pane=True) def Main(self): ema = Ema.new(self.close, length=9) return ema[0] ``` ```py Source code # indie:lang_version = 5 from math import isnan, nan from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma @algorithm def Ema(self, src: SeriesF, length: int) -> SeriesF: '''Exponential Moving Average''' alpha = 2 / (length + 1) s = MutSeriesF.new(init=0) res_sma = Sma.new(src, length)[0] result = 0.0 if isnan(src[0]): s[0] = nan result = res_sma elif isnan(s[1]): s[0] = res_sma result = s[0] else: s[0] = alpha * src[0] + (1 - alpha) * s[1] result = s[0] return MutSeriesF.new(result) ``` *** ### `FixNan` *type* Algorithm that replaces all `math.nan` values with the most recent corresponding non-nan values in a series. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series created from `src` by replacing `math.nan` values with previous nearest non-`nan` value. Series data to perform the calculation. Returns series created from `src` by replacing `math.nan` values with previous nearest non-`nan` value. Series data to perform the calculation. ```py Example # indie:lang_version = 5 import math from indie import indicator, MutSeriesF from indie.algorithms import FixNan @indicator('Example', overlay_main_pane=True) def Main(self): # Variable `s` is just an example of a series with `nan` values: s = MutSeriesF.new(math.nan) if self.close[0] > self.open[0]: s[0] = self.close[0] # `FixNan` replaces every `nan` value in `s` with the closest non-`nan` value on the left of it: s2 = FixNan.new(s) return s2[0] ``` ```py Source code # indie:lang_version = 5 from math import isnan from indie import algorithm, SeriesF, MutSeriesF @algorithm def FixNan(self, src: SeriesF) -> SeriesF: res = MutSeriesF.new(init=src[0]) if not isnan(src[0]): res[0] = src[0] return res ``` See also: [`NanToZero`](/indie/Library-reference/package-indie-algorithms#class_NanToZero) *** ### `Highest` *type* Algorithm that returns the maximum value over a given period. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns maximum value of given `src` series over a period of `length` bars. Series data to perform the calculation. Number of bars in calculation taken into account. Returns maximum value of given `src` series over a period of `length` bars. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Highest @indicator('My Indie 1', overlay_main_pane=True) def Main(self): h = Highest.new(self.high, length=12) return h[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def Highest(self, src: SeriesF, length: int) -> SeriesF: src.request_size(length) result = src[0] for i in range(1, length): result = max(src[i], result) return MutSeriesF.new(result) ``` See also: [`SinceHighest`](/indie/Library-reference/package-indie-algorithms#class_SinceHighest) *** ### `LinReg` *type* Linear regression algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Linear Regression Curve* values calculated on `src` series for the `length` bars period (with possible offset `offset`). Series data to perform the calculation. Number of bars in calculation taken into account. Offset of the argument to calculate *LinReg*. Returns series of *Linear Regression Curve* values calculated on `src` series for the `length` bars period (with possible offset `offset`). Series data to perform the calculation. Number of bars in calculation taken into account. Offset of the argument to calculate *LinReg*. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import LinReg @indicator('Example') def Main(self): lr = LinReg.new(self.close, length=14, offset=0) return lr[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma, StdDev, Corr from indie.math import divide @algorithm def LinReg(self, y: SeriesF, length: int, offset: int = 0) -> SeriesF: x = MutSeriesF.new(self.ctx.bar_index) e_x = Sma.new(x, length)[0] e_y = Sma.new(y, length)[0] dev_x = StdDev.new(x, length)[0] dev_y = StdDev.new(y, length)[0] corr = Corr.new(x, y, length)[0] slope = corr * divide(dev_y, dev_x) inter = e_y - slope * e_x reg = (x[0] - offset) * slope + inter return MutSeriesF.new(reg) ``` *** ### `Lowest` *type* Algorithm that returns the minimum value over a given period. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns minimum value of given `src` series over a period of `length` bars. Series data to perform the calculation. Number of bars in calculation taken into account. Returns minimum value of given `src` series over a period of `length` bars. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Lowest @indicator('My Indie 1', overlay_main_pane=True) def Main(self): l = Lowest.new(self.low, length=12) return l[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def Lowest(self, src: SeriesF, length: int) -> SeriesF: src.request_size(length) result = src[0] for i in range(1, length): result = min(src[i], result) return MutSeriesF.new(result) ``` See also: [`SinceLowest`](/indie/Library-reference/package-indie-algorithms#class_SinceLowest) *** ### `Ma` *type* Moving average algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns a moving average of `src` specified by `algorithm` argument. Series data to perform the calculation. Number of bars in calculation taken into account. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. Returns a moving average of `src` specified by `algorithm` argument. Series data to perform the calculation. Number of bars in calculation taken into account. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. ```py Example # indie:lang_version = 5 from indie.algorithms import Ma @indicator('Example', overlay_main_pane=True) def Main(self): ma = Ma.new(self.close, length=12, algorithm='SMA') return ma[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, Optional, IndieError from indie.algorithms import Ema, Sma, Rma, Vwma, Wma @algorithm def Ma(self, src: SeriesF, length: int, algorithm: str) -> SeriesF: '''Moving Average''' result: Optional[SeriesF] if algorithm == 'EMA': result = Ema.new(src, length) elif algorithm == 'SMA': result = Sma.new(src, length) elif algorithm == 'SMMA (RMA)' or algorithm == 'RMA': result = Rma.new(src, length) elif algorithm == 'VWMA': result = Vwma.new(src, length) elif algorithm == 'WMA': result = Wma.new(src, length) else: raise IndieError("moving average algorithm should be one of 'EMA', 'SMA', " "'SMMA (RMA)', 'RMA', 'VWMA' or 'WMA' but it is " + algorithm) return result.value() ``` *** ### `Macd` *type* Moving average convergence/divergence algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Moving Average Convergence/Divergence*, *Signal Line* and *Histogram Line* values calculated from series of `src` for `fast_len`, `slow_len` and `sig_len` bars periods using moving averages specified by `ma_source` and `ma_signal` argument. Series data to perform the calculation. Fast length. Slow length. Signal length. Moving average algorithm name, should be one of `'EMA'` or `'SMA'`. Moving average algorithm name, should be one of `'EMA'` or `'SMA'`. Returns series of *Moving Average Convergence/Divergence*, *Signal Line* and *Histogram Line* values calculated from series of `src` for `fast_len`, `slow_len` and `sig_len` bars periods using moving averages specified by `ma_source` and `ma_signal` argument. Series data to perform the calculation. Fast length. Slow length. Signal length. Moving average algorithm name, should be one of `'EMA'` or `'SMA'`. Moving average algorithm name, should be one of `'EMA'` or `'SMA'`. ```py Example # indie:lang_version = 5 from indie.algorithms import Macd @indicator('Example', overlay_main_pane=True) def Main(self): macd = Macd.new(self.close, fast_length=12, slow_length=26, sig_length=9, ma_source='EMA', ma_signal='EMA') return macd[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Ma @algorithm def Macd(self, src: SeriesF, fast_len: int, slow_len: int, sig_len: int, ma_source: str = 'EMA', ma_signal: str = 'EMA') -> tuple[SeriesF, SeriesF, SeriesF]: '''Moving Average Convergence Divergence''' fast_ma = Ma.new(src, fast_len, ma_source) slow_ma = Ma.new(src, slow_len, ma_source) macd = MutSeriesF.new(fast_ma[0] - slow_ma[0]) signal = Ma.new(macd, sig_len, ma_signal) hist = MutSeriesF.new(macd[0] - signal[0]) return macd, signal, hist ``` *** ### `Median` *type* Moving median algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Moving Median* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Moving Median* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Median @indicator('Example', overlay_main_pane=True) def Main(self): m = Median.new(self.close, length=10) return m[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from statistics import median as stats_median # TODO: Use quickselect median find algorithm, see more https://rcoh.me/posts/linear-time-median-finding/ @algorithm def Median(self, src: SeriesF, length: int) -> SeriesF: prices: list[float] = [] # TODO: Create list of size=length only once and clear+refill it for i in range(length): prices.append(src[i]) res = stats_median(prices) # type: ignore return MutSeriesF.new(res) ``` *** ### `Mfi` *type* Money flow index algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Money Flow Index* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Money Flow Index* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie.algorithms import Mfi @indicator('Example', overlay_main_pane=True) def Main(self): mfi = Mfi.new(self.hlc3, length=14) return mfi[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, MutSeriesF, SeriesF from indie.math import divide @algorithm def Mfv(self) -> SeriesF: '''Money Flow Volume''' h = self.ctx.high[0] l = self.ctx.low[0] c = self.ctx.close[0] v = self.ctx.volume[0] res = v * divide((c - l) - (h - c), (h - l), 0.0) return MutSeriesF.new(res) ``` *** ### `Mfv` *type* Money flow volume algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Money Flow Volume*. Returns series of *Money Flow Volume*. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Mfv @indicator('Example') def Main(self): mfv = Mfv.new() return mfv[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, MutSeriesF, SeriesF from indie.math import divide @algorithm def Mfv(self) -> SeriesF: '''Money Flow Volume''' h = self.ctx.high[0] l = self.ctx.low[0] c = self.ctx.close[0] v = self.ctx.volume[0] res = v * divide((c - l) - (h - c), (h - l), 0.0) return MutSeriesF.new(res) ``` *** ### `NanToZero` *type* Algorithm that replaces all `math.nan` values with zeros in a series. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series created from `src` by replacing `math.nan` values with zeros. Series data to perform the calculation. Returns series created from `src` by replacing `math.nan` values with zeros. Series data to perform the calculation. ```py Example # indie:lang_version = 5 import math from indie import indicator, MutSeriesF from indie.algorithms import NanToZero @indicator('Example') def Main(self): # Variable `s` is just an example of a series with `nan` values: s = MutSeriesF.new(math.nan) if self.close[0] > self.open[0]: s[0] = 0 if math.isnan(s[1]) else s[1] + 1 # `NanToZero` replaces every `nan` value in `s` with zero s2 = NanToZero.new(s) return s2[0] ``` ```py Source code # indie:lang_version = 5 from math import isnan from indie import algorithm, SeriesF, MutSeriesF @algorithm def NanToZero(self, src: SeriesF) -> SeriesF: res = 0 if isnan(src[0]) else src[0] return MutSeriesF.new(res) ``` See also: [`FixNan`](/indie/Library-reference/package-indie-algorithms#class_FixNan) *** ### `NetVolume` *type* Net volume algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Net Volume* values calculated on `src` series. Series data to perform the calculation. Returns series of *Net Volume* values calculated on `src` series. Series data to perform the calculation. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import NetVolume @indicator('Example') def Main(self): nv = NetVolume.new(self.close) return nv[0] ``` ```py Source code # indie:lang_version = 5 from math import nan from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Change @algorithm def NetVolume(self, src: SeriesF) -> SeriesF: der = Change.new(src)[0] nv = MutSeriesF.new(init=nan) if der > 0: nv[0] = self.ctx.volume[0] elif der < 0: nv[0] = -self.ctx.volume[0] elif der == 0: nv[0] = 0 return nv ``` *** ### `PercentRank` *type* Percent rank algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Percent Rank* (number of previous values that are less or equal to the current value) calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Percent Rank* (number of previous values that are less or equal to the current value) calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import PercentRank @indicator('Example') def Main(self): pr = PercentRank.new(self.close, length=12) return pr[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def PercentRank(self, src: SeriesF, length: int) -> SeriesF: num_leq = 0 for idx in range(1, length + 1): if src[idx] <= src[0]: num_leq += 1 return MutSeriesF.new(100.0 * num_leq / length) ``` *** ### `Rma` *type* RMA algorithm is a moving average algorithm that is used to calculate RSI. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns a *Moving Average* that is used in calculations of `Rsi`. Series data to perform the calculation. Number of bars in calculation taken into account. Returns a *Moving Average* that is used in calculations of `Rsi`. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Rma @indicator('My Indie 1', overlay_main_pane=True) def Main(self): rma = Rma.new(self.close, length=12) return rma[0] ``` ```py Source code # indie:lang_version = 5 from math import isnan from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma @algorithm def Rma(self, src: SeriesF, length: int) -> SeriesF: '''RSI Moving Average''' result = MutSeriesF.new(init=0) if isnan(result[1]): result[0] = Sma.new(src, length)[0] else: result[0] = (src[0] + (length - 1) * result[1]) / length return result ``` *** ### `Roc` *type* Rate of change algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Rate Of Change* (percentage of change between the current value and value `length` bars ago) calculated on `src` series. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Rate Of Change* (percentage of change between the current value and value `length` bars ago) calculated on `src` series. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Roc @indicator('Example') def Main(self): roc = Roc.new(self.close, length=9) return roc[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Change from indie.math import divide @algorithm def Roc(self, src: SeriesF, length: int) -> SeriesF: '''Rate Of Change''' res = 100 * divide(Change.new(src, length)[0], src[length]) return MutSeriesF.new(res) ``` *** ### `Rsi` *type* Relative strength index algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Relative Strength Index* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Relative Strength Index* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Rsi @indicator('Example') def Main(self): rsi = Rsi.new(self.close, length=12) return rsi[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import NanToZero, Change, Rma from indie.math import divide @algorithm def Rsi(self, src: SeriesF, length: int) -> SeriesF: '''Relative Strength Index''' u = max(NanToZero.new(Change.new(src))[0], 0) # upward change rma_u = Rma.new(MutSeriesF.new(u), length)[0] d = max(-NanToZero.new(Change.new(src))[0], 0) # downward change rma_d = Rma.new(MutSeriesF.new(d), length)[0] res = 100 * divide(rma_u, rma_u + rma_d, 1.0) return MutSeriesF.new(res) ``` *** ### `Sar` *type* Parabolic stop and reverse algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Parabolic Stop And Reverse* values. Initial value for acceleration. Increment value for acceleration. Maximum value for acceleration. Returns series of *Parabolic Stop And Reverse* values. Initial value for acceleration. Increment value for acceleration. Maximum value for acceleration. ```py Example # indie:lang_version = 5 from indie.algorithms import Sar @indicator('Example', overlay_main_pane=True) def Main(self): sar = Sar.new(start=0.02, increment=0.02, maximum=0.2) return sar[0] ``` ```py Source code # indie:lang_version = 5 from math import nan from indie import algorithm, SeriesF, Var, MutSeriesF @algorithm def Sar(self, start: float, increment: float, maximum: float) -> SeriesF: result = Var[float].new(init=nan) max_min = Var[float].new(init=nan) acceleration = Var[float].new(init=nan) is_below = Var[bool].new(init=False) is_first_trend_bar = False if self.ctx.bar_index == 1: if self.ctx.close[0] > self.ctx.close[1]: is_below.set(True) max_min.set(self.ctx.high[0]) result.set(self.ctx.low[1]) else: is_below.set(False) max_min.set(self.ctx.low[0]) result.set(self.ctx.high[1]) is_first_trend_bar = True acceleration.set(start) result.set(result.get() + acceleration.get() * (max_min.get() - result.get())) if is_below.get(): if result.get() > self.ctx.low[0]: is_first_trend_bar = True is_below.set(False) result.set(max(self.ctx.high[0], max_min.get())) max_min.set(self.ctx.low[0]) acceleration.set(start) else: if result.get() < self.ctx.high[0]: is_first_trend_bar = True is_below.set(True) result.set(min(self.ctx.low[0], max_min.get())) max_min.set(self.ctx.high[0]) acceleration.set(start) if not is_first_trend_bar: if is_below.get(): if self.ctx.high[0] > max_min.get(): max_min.set(self.ctx.high[0]) acceleration.set(min(acceleration.get() + increment, maximum)) else: if self.ctx.low[0] < max_min.get(): max_min.set(self.ctx.low[0]) acceleration.set(min(acceleration.get() + increment, maximum)) if is_below.get(): result.set(min(result.get(), self.ctx.low[1])) if self.ctx.bar_index > 1: result.set(min(result.get(), self.ctx.low[2])) else: result.set(max(result.get(), self.ctx.high[1])) if self.ctx.bar_index > 1: result.set(max(result.get(), self.ctx.high[2])) return MutSeriesF.new(result.get()) ``` *** ### `SinceHighest` *type* Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns the number of bars after the maximum price for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns the number of bars after the maximum price for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import SinceHighest @indicator('Example') def Main(self): sh = SinceHighest.new(self.high, length=10) return sh[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, Series, MutSeries @algorithm def SinceHighest(self, src: SeriesF, length: int) -> Series[int]: offset = 0 for idx in range(length): if src[idx] >= src[offset]: offset = idx return MutSeries[int].new(offset) ``` See also: [`Highest`](/indie/Library-reference/package-indie-algorithms#class_Highest) *** ### `SinceLowest` *type* Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns the number of bars after the minimum price for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns the number of bars after the minimum price for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import SinceLowest @indicator('Example') def Main(self): sl = SinceLowest.new(self.high, length=10) return sl[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, Series, MutSeries @algorithm def SinceLowest(self, src: SeriesF, length: int) -> Series[int]: offset = 0 for idx in range(length): if src[idx] <= src[offset]: offset = idx return MutSeries[int].new(offset) ``` See also: [`Lowest`](/indie/Library-reference/package-indie-algorithms#class_Lowest) *** ### `SinceTrue` *type* Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns an index of the last `True` in `condition` series; if no such `True` is found, returns `-1`. Bool series to find `True`. Returns an index of the last `True` in `condition` series; if no such `True` is found, returns `-1`. Bool series to find `True`. ```py Example # indie:lang_version = 5 from indie import indicator, MutSeries from indie.algorithms import SinceTrue @indicator('Example') def Main(self): cond = MutSeries[bool].new(self.close[0] > self.open[0]) index = SinceTrue.new(cond) return index ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, Series, MutSeries @algorithm def SinceTrue(self, condition: Series[bool]) -> Series[int]: result = MutSeries[int].new(init=-1) if condition[0]: result[0] = 0 elif result[0] != -1: result[0] += 1 return result ``` *** ### `Sma` *type* Simple moving average algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Simple Moving Average* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Simple Moving Average* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Sma @indicator('Example') def Main(self): sma = Sma.new(self.close, length=12) return sma[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sum @algorithm def Sma(self, src: SeriesF, length: int) -> SeriesF: '''Simple Moving Average''' s = Sum.new(src, length) return MutSeriesF.new(s[0] / length) ``` *** ### `StdDev` *type* Standard deviation algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Standard Deviation* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Standard Deviation* values calculated from series of `src` for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import StdDev @indicator('Example') def Main(self): sd = StdDev.new(self.close, length=12) return sd[0] ``` ```py Source code # indie:lang_version = 5 from math import sqrt from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma @algorithm def StdDev(self, src: SeriesF, length: int) -> SeriesF: # NOTE: `var_` could be calculated as `E(src^2) - E(src)^2`, # but that may cause precision issues with floating-point arithmetic avg = Sma.new(src, length)[0] var_ = 0.0 for i in range(length): dev = src[i] - avg var_ += dev * dev var_ /= length return MutSeriesF.new(sqrt(var_)) ``` *** ### `Stoch` *type* Stochastic algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Stochastic* on `src` series with `high` and `low` highs and lows of the source over a period of `length` bars. Series data to perform the calculation. Series of low values. Series of high values. Number of bars in calculation taken into account. Returns series of *Stochastic* on `src` series with `high` and `low` highs and lows of the source over a period of `length` bars. Series data to perform the calculation. Series of low values. Series of high values. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Stoch @indicator('Example') def Main(self): s = Stoch.new(self.close, self.low, self.high, length=14) return s[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Lowest, Highest from indie.math import divide @algorithm def Stoch(self, src: SeriesF, low: SeriesF, high: SeriesF, length: int) -> SeriesF: lowest_low = Lowest.new(low, length)[0] highest_high = Highest.new(high, length)[0] res = 100 * divide(src[0] - lowest_low, highest_high - lowest_low, 1.0) return MutSeriesF.new(res) ``` *** ### `Sum` *type* Sliding sum algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Sliding Sum* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Sliding Sum* values calculated on `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Sum @indicator('Example') def Main(self): s = Sum.new(self.close, length=10) return s[0] ``` ```py Source code # indie:lang_version = 5 from math import isnan, nan from indie import algorithm, SeriesF, MutSeriesF, Var def nan_to_zero(val: float) -> float: return 0 if isnan(val) else val @algorithm def Sum(self, src: SeriesF, length: int) -> SeriesF: src.request_size(length + 1) nan_count = Var[int].new(0) sum = Var[float].new(0) sum.set(sum.get() + nan_to_zero(src[0])) result = 0.0 if isnan(src[0]): nan_count.set(nan_count.get() + 1) result = nan else: if len(src) - nan_count.get() > length: sum.set(sum.get() - src[length]) if len(src) - nan_count.get() < length: result = nan else: result = sum.get() return MutSeriesF.new(result) ``` *** ### `Supertrend` *type* Supertrend algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns a tuple of two *Supertrend* series: *Supertrend Line* and *Direction Of Trend*. The multiplier by which the *ATR* will get multiplied. Number of bars to calculate *ATR*. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. Returns a tuple of two *Supertrend* series: *Supertrend Line* and *Direction Of Trend*. The multiplier by which the *ATR* will get multiplied. Number of bars to calculate *ATR*. Moving average algorithm name, should be one of `'EMA'`, `'SMA'`, `'SMMA (RMA)'`, `'RMA'`, `'VWMA'` or `'WMA'`. ```py Example # indie:lang_version = 5 from indie import indicator, color, plot from indie.algorithms import Supertrend @indicator('Example', overlay_main_pane=True) def Main(self): st, dir = Supertrend.new(factor=3.0, atr_period=10, ma_algorithm='SMA') c = color.RED if dir[0] > 0 else color.GREEN return plot.Line(st[0], color=c) ``` ```py Source code # indie:lang_version = 5 from math import isnan from indie import algorithm, MutSeriesF, SeriesF from indie.algorithms import Atr def nan_to_val(maybe_nan: float, val: float) -> float: return val if isnan(maybe_nan) else maybe_nan @algorithm def Supertrend(self, factor: float, atr_period: int, ma_algorithm: str) -> tuple[SeriesF, SeriesF]: src = self.ctx.hl2 atr = Atr.new(atr_period, ma_algorithm) upper_band = MutSeriesF.new(src[0] + factor * atr[0]) lower_band = MutSeriesF.new(src[0] - factor * atr[0]) prev_lower_band = nan_to_val(lower_band[1], 0) prev_upper_band = nan_to_val(upper_band[1], 0) lower_band[0] = lower_band[0] \ if lower_band[0] > prev_lower_band or self.ctx.close[1] < prev_lower_band \ else prev_lower_band upper_band[0] = upper_band[0] \ if upper_band[0] < prev_upper_band or self.ctx.close[1] > prev_upper_band \ else prev_upper_band direction: float super_trend = MutSeriesF.new(init=0) prev_super_trend = super_trend[1] if isnan(atr[1]): direction = 1.0 elif prev_super_trend == prev_upper_band: direction = -1.0 if self.ctx.close[0] > upper_band[0] else 1.0 else: direction = 1.0 if self.ctx.close[0] < lower_band[0] else -1.0 super_trend[0] = lower_band[0] if direction < 0 else upper_band[0] return super_trend, MutSeriesF.new(direction) ``` *** ### `Tr` *type* True range algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *True Range* values. Flag that says how `NaN` close values of the previous day are handled. Returns series of *True Range* values. Flag that says how `NaN` close values of the previous day are handled. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Tr @indicator('Example') def Main(self): tr = Tr.new() return tr[0] ``` ```py Source code # indie:lang_version = 5 from math import nan, isnan from indie import algorithm, SeriesF, MutSeriesF @algorithm def Tr(self, handle_na: bool = False) -> SeriesF: '''True Range''' res = nan if handle_na else self.ctx.high[0] - self.ctx.low[0] if not isnan(self.ctx.close[1]): res = max( self.ctx.high[0] - self.ctx.low[0], abs(self.ctx.high[0] - self.ctx.close[1]), abs(self.ctx.low[0] - self.ctx.close[1]), ) return MutSeriesF.new(res) ``` *** ### `Tsi` *type* True strength index algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *True Strength Index* values. Series data to perform the calculation. Long length. Short length. Returns series of *True Strength Index* values. Series data to perform the calculation. Long length. Short length. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Tsi @indicator('Example') def Main(self): tsi = Tsi.new(self.close, long_len=21, short_len=12) return tsi[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Ema, Change from indie.math import divide @algorithm def DoubleSmooth(self, src: SeriesF, long_len: int, short_len: int) -> SeriesF: return Ema.new(Ema.new(src, long_len), short_len) @algorithm def Tsi(self, src: SeriesF, long_len: int, short_len: int) -> SeriesF: '''True Strength Index''' pc = Change.new(src) double_smoothed_pc = DoubleSmooth.new(pc, long_len, short_len)[0] abs_pc = MutSeriesF.new(abs(pc[0])) double_smoothed_abs_pc = DoubleSmooth.new(abs_pc, long_len, short_len)[0] res = divide(double_smoothed_pc, double_smoothed_abs_pc) return MutSeriesF.new(res) ``` *** ### `Uo` *type* Ultimate oscillator algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Ultimate Oscillator* values calculated for `fast_len`, `middle_len` and `slow_len` bars periods. Fast length. Middle length. Slow length. Returns series of *Ultimate Oscillator* values calculated for `fast_len`, `middle_len` and `slow_len` bars periods. Fast length. Middle length. Slow length. ```py Example # indie:lang_version = 5 from indie.algorithms import Uo @indicator('Example', overlay_main_pane=True) def Main(self): uo = Uo.new(fast_len=7, middle_len=14, slow_len=28) return uo[0] ``` ```py Source code # indie:lang_version = 5 from math import nan from indie import algorithm, SeriesF, Var, MutSeriesF @algorithm def Sar(self, start: float, increment: float, maximum: float) -> SeriesF: result = Var[float].new(init=nan) max_min = Var[float].new(init=nan) acceleration = Var[float].new(init=nan) is_below = Var[bool].new(init=False) is_first_trend_bar = False if self.ctx.bar_index == 1: if self.ctx.close[0] > self.ctx.close[1]: is_below.set(True) max_min.set(self.ctx.high[0]) result.set(self.ctx.low[1]) else: is_below.set(False) max_min.set(self.ctx.low[0]) result.set(self.ctx.high[1]) is_first_trend_bar = True acceleration.set(start) result.set(result.get() + acceleration.get() * (max_min.get() - result.get())) if is_below.get(): if result.get() > self.ctx.low[0]: is_first_trend_bar = True is_below.set(False) result.set(max(self.ctx.high[0], max_min.get())) max_min.set(self.ctx.low[0]) acceleration.set(start) else: if result.get() < self.ctx.high[0]: is_first_trend_bar = True is_below.set(True) result.set(min(self.ctx.low[0], max_min.get())) max_min.set(self.ctx.high[0]) acceleration.set(start) if not is_first_trend_bar: if is_below.get(): if self.ctx.high[0] > max_min.get(): max_min.set(self.ctx.high[0]) acceleration.set(min(acceleration.get() + increment, maximum)) else: if self.ctx.low[0] < max_min.get(): max_min.set(self.ctx.low[0]) acceleration.set(min(acceleration.get() + increment, maximum)) if is_below.get(): result.set(min(result.get(), self.ctx.low[1])) if self.ctx.bar_index > 1: result.set(min(result.get(), self.ctx.low[2])) else: result.set(max(result.get(), self.ctx.high[1])) if self.ctx.bar_index > 1: result.set(max(result.get(), self.ctx.high[2])) return MutSeriesF.new(result.get()) ``` *** ### `Vwap` *type* Volume weighted average price algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Volume Weighted Average Price* values with band of its standard deviation. Series data to perform the calculation. At what points in time do we need to reset the accumulated amounts. Valid values are: 'day', 'week', 'month', 'year'. Multiplier for standard deviation. Returns series of *Volume Weighted Average Price* values with band of its standard deviation. Series data to perform the calculation. At what points in time do we need to reset the accumulated amounts. Valid values are: 'day', 'week', 'month', 'year'. Multiplier for standard deviation. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Vwap @indicator('Example', overlay_main_pane=True) def Main(self): main_line, upper, lower = Vwap.new(self.close, anchor='Day', std_dev_mult=1.0) return main_line[0], upper[0], lower[0] ``` ```py Source code # indie:lang_version = 5 from math import sqrt from datetime import datetime from indie import algorithm, SeriesF, MutSeriesF, Var @algorithm def Vwap(self, src: SeriesF, anchor: str, std_dev_mult: float) -> tuple[SeriesF, SeriesF, SeriesF]: ''' Volume Weighted Average Price anchor can be 'Session', 'Week', 'Month', 'Year' ''' cum_weighted_price = Var[float].new(0) cum_volume = Var[float].new(0) vwap_sum = Var[float].new(0) vwap_count = Var[int].new(0) vwap_dev_squares = Var[float].new(0) current_datetime = datetime.utcfromtimestamp(self.ctx.time[0]) prev_datetime = datetime.utcfromtimestamp(self.ctx.time.get(1, 0)) need_reset = False if anchor == 'Session' and \ not self.ctx.trading_session.is_same_period(self.ctx.time[0], self.ctx.time.get(1, 0)): need_reset = True elif anchor == 'Week' and ((current_datetime.weekday() == 0 and prev_datetime.weekday() != 0) or (current_datetime-prev_datetime).days >= 7): need_reset = True elif anchor == 'Month' and (current_datetime.month != prev_datetime.month or (current_datetime-prev_datetime).days >= 31): need_reset = True elif anchor == 'Year' and current_datetime.year != prev_datetime.year: need_reset = True if need_reset: cum_weighted_price.set(0) cum_volume.set(0) vwap_sum.set(0) vwap_count.set(0) vwap_dev_squares.set(0) cum_weighted_price.set(cum_weighted_price.get() + src[0] * self.ctx.volume[0]) cum_volume.set(cum_volume.get() + self.ctx.volume[0]) vwap_value = cum_weighted_price.get() / cum_volume.get() vwap_sum.set(vwap_sum.get() + vwap_value) vwap_count.set(vwap_count.get() + 1) vwap_avg = vwap_sum.get() / vwap_count.get() vwap_dev_squares.set(vwap_dev_squares.get() + (vwap_value - vwap_avg) ** 2) vwap_std_dev = sqrt(vwap_dev_squares.get() / vwap_count.get()) std_dev = std_dev_mult * vwap_std_dev lower = MutSeriesF.new(vwap_value - std_dev) upper = MutSeriesF.new(vwap_value + std_dev) return MutSeriesF.new(vwap_value), upper, lower ``` *** ### `Vwma` *type* Volume weighted moving average algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Volume Weighted Moving Average* values calculated for `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Volume Weighted Moving Average* values calculated for `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Vwma @indicator('Example', overlay_main_pane=True) def Main(self): vwma = Vwma.new(self.close, length=12) return vwma[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF from indie.algorithms import Sma from indie.math import divide @algorithm def Vwma(self, src: SeriesF, length: int) -> SeriesF: '''Volume Weighted Moving Average''' src_vol = MutSeriesF.new(src[0] * self.ctx.volume[0]) sma_src_vol = Sma.new(src_vol, length) sma_vol = Sma.new(self.ctx.volume, length) res = divide(sma_src_vol[0], sma_vol[0]) return MutSeriesF.new(res) ``` *** ### `Wma` *type* Weighted moving average algorithm. Read [here](/indie/Algorithms-for-series-processing#tl-dr-how-to-use-classes-from-indie-algorithms-package-in-my-indicator) about how to use it. [`Algorithm`](/indie/Library-reference/package-indie#class_Algorithm) Represents context of an instrument which is currently bound to this algorithm instance. An indicator has at least one instrument — the main instrument of a chart where the indicator was added to. Besides the main instrument an indicator may have several additional instruments, which is done with the help of `Context.calc_on` function. Class constructor (initializer for the data type). Context object. Returns series of *Weighted Moving Average* values calculated for `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. Returns series of *Weighted Moving Average* values calculated for `src` series for the `length` bars period. Series data to perform the calculation. Number of bars in calculation taken into account. ```py Example # indie:lang_version = 5 from indie import indicator from indie.algorithms import Wma @indicator('Example', overlay_main_pane=True) def Main(self): wma = Wma.new(self.close, length=12) return wma[0] ``` ```py Source code # indie:lang_version = 5 from indie import algorithm, SeriesF, MutSeriesF @algorithm def Wma(self, src: SeriesF, length: int) -> SeriesF: '''Weighted Moving Average''' norm = 0.0 s = 0.0 for i in range(length): weight = length - i norm += weight s += src[i] * weight return MutSeriesF.new(s / norm) ``` *** # Package indie.color Source: https://takeprofit.com/docs/indie/Library-reference/package-indie-color export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Package for builtin colors and `rgba` function. See also: [`@line()`](/indie/Library-reference/package-indie-plot#decor_line) [`Line`](/indie/Library-reference/package-indie-plot#class_Line) [`Color`](/indie/Library-reference/package-indie#class_Color) *** ## Variables Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. Built-in color. *** ## Functions ### `rgba()` *function* Creates a `Color` object by its RGB components and alpha channel. Red component of color. Green component of color. Blue component of color. Alpha channel (component) of color which ranges from `0.0` (fully transparent) to `1.0` (fully opaque). *** # Package indie.math Source: https://takeprofit.com/docs/indie/Library-reference/package-indie-math export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Utility functions for simple calculations in Indie indicators. *** ## Functions ### `cross()` *function* Checks if two series just have crossed each other. First series to make crossing check. Second series to make crossing check. Checks if two series just have crossed each other. Series to make crossing check. Constant level to make crossing check. *** ### `cross_over()` *function* Checks if the first series just have crossed over the second one. First series to make crossing check. Second series to make crossing check. Checks if the first series just have crossed over the second one. Series to make crossing check. Constant level to make crossing check. *** ### `cross_under()` *function* Checks if the first series just have crossed under the second one. First series to make crossing check. Second series to make crossing check. Checks if the first series just have crossed under the second one. Series to make crossing check. Constant level to make crossing check. *** ### `divide()` *function* Safely divides two numbers, returning a default value if the denominator is near zero. Numerator. Denominator. Default value. *** # Package indie.plot Source: https://takeprofit.com/docs/indie/Library-reference/package-indie-plot export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Package for plotting series-like data. *** ## Decorators ### `@columns()` *decorator* Declares attributes of a columns plot of an indicator. Can be applied only to the `Main` entry point of the indicator. When applied, it must match with the result of the `Main` indicator entry point. A unique identifier of plot, reserved for internal use. Human readable title which is visible in the indicator's Settings panel. Color of the plot. Base level from which to start plot. Relative width. Determines the ways to display plot data. ```py Example @plot.line() @plot.columns(line_width=2) @plot.columns(color=color.YELLOW) # @plot.line() - for the fourth plot can be omitted def Main(self): return self.open[0], self.high[0], self.low[0], self.close[0] ``` See also: [`Columns`](/indie/Library-reference/package-indie-plot#class_Columns) *** ### `@fill()` *decorator* Declares attributes of a fill plot of an indicator. Can be applied only to the `Main` entry point of the indicator. When applied, it must match with the result of the `Main` indicator entry point. Identifier of the first plot to which the fill is applied. Identifier of the second plot to which the fill is applied. A unique identifier of plot, reserved for internal use. Human readable title which is visible in the indicator's Settings panel. Color of the plot. ```py Example @plot.line('plot1') @plot.line('plot2') @plot.fill('plot1', 'plot2') def Main(self): return self.open[0], self.high[0], plot.Fill() ``` See also: [`Fill`](/indie/Library-reference/package-indie-plot#class_Fill) *** ### `@histogram()` *decorator* Declares attributes of a histogram plot of an indicator. Can be applied only to the `Main` entry point of the indicator. When applied, it must match with the result of the `Main` indicator entry point. A unique identifier of plot, reserved for internal use. Human readable title which is visible in the indicator's Settings panel. Color of the plot. Width of the line. Base level from which to start plot. Determines the ways to display plot data. ```py Example @plot.line() @plot.histogram(line_width=2) @plot.histogram(color=color.YELLOW) # @plot.line() - for the fourth plot can be omitted def Main(self): return self.open[0], self.high[0], self.low[0], self.close[0] ``` See also: [`Histogram`](/indie/Library-reference/package-indie-plot#class_Histogram) *** ### `@line()` *decorator* Declares attributes of a line plot of an indicator. Can be applied only to the `Main` entry point of the indicator. It is optional, so may be omitted in some simple use cases and plot will be rendered using defaults. When applied, it must match with the result of the `Main` indicator entry point. A unique identifier of plot which is used in cases when a `@plot.fill()` should be applied between some of the two plots of an indicator. Human readable title which is visible in the indicator's Settings panel. Color of the plot on a chart. This color can be overwritten if the plot is a multicolored one. Example of an indicator with a multicolored plot is *Awesome Oscillator (AO)*. Style of the line. It is represented as enum value of type `line_style`. Width of the line. Whether the plot should be continuous when the indicator has `NaN` values. Determines the ways to display plot data. ```py Example @plot.line() @plot.line(line_width=2) @plot.line(color=color.YELLOW) # @plot.line() - for the fourth plot can be omitted def Main(self): return self.open[0], self.high[0], self.low[0], self.close[0] ``` See also: [`Line`](/indie/Library-reference/package-indie-plot#class_Line) *** ### `@marker()` *decorator* Declares attributes of a marker plot of an indicator. Can be applied only to the `Main` entry point of the indicator. When applied, it must match with the result of the `Main` indicator entry point. Human readable title which is visible in the indicator's Settings panel. Color of the plot. Default value for the text label of markers. Determines how the plot data is rendered. It is represented as enum value of type `marker_style`. Determines how the data and text are rendered. Size of markers. Determines the ways to display plot data. ```py Example @plot.line() @plot.marker(line_width=2) @plot.marker(color=color.YELLOW) # @plot.line() - for the fourth plot can be omitted def Main(self): return self.open[0], self.high[0], self.low[0], self.close[0] ``` See also: [`Marker`](/indie/Library-reference/package-indie-plot#class_Marker) *** ### `@steps()` *decorator* Declares attributes of a steps plot of an indicator. Can be applied only to the `Main` entry point of the indicator. When applied, it must match with the result of the `Main` indicator entry point. A unique identifier of plot, reserved for internal use. Human readable title which is visible in the indicator's Settings panel. Color of the plot. Width of the line. Determines the ways to display plot data. ```py Example @plot.line() @plot.steps(line_width=2) @plot.steps(color=color.YELLOW) # @plot.line() - for the fourth plot can be omitted def Main(self): return self.open[0], self.high[0], self.low[0], self.close[0] ``` See also: [`Steps`](/indie/Library-reference/package-indie-plot#class_Steps) *** ## Types ### `Columns` *type* Class which objects represent an element of columns plot. Value of the plot element. Color of the plot element. Offset of the plot element. Class constructor (initializer for the data type). Value of the plot element. Color of the plot element. Offset of the plot element. See also: [`@columns()`](/indie/Library-reference/package-indie-plot#decor_columns) *** ### `ColumnsDisplayOptions` *type* Class with options that control how to display plot data on a chart. Class constructor (initializer for the data type). Whether or not to draw (by default) the plot on the pane. Whether or not to show the value of the plot in the status line. Whether or not to show the value label of the plot on the price axis. *** ### `Fill` *type* Class which objects represent an element of fill plot. Color of the plot element. Offset of the plot element. Class constructor (initializer for the data type). Color of the plot element. Offset of the plot element. See also: [`@fill()`](/indie/Library-reference/package-indie-plot#decor_fill) *** ### `Histogram` *type* Class which objects represent an element of histogram plot. Value of the plot element. Color of the plot element. Offset of the plot element. Class constructor (initializer for the data type). Value of the plot element. Color of the plot element. Offset of the plot element. See also: [`@histogram()`](/indie/Library-reference/package-indie-plot#decor_histogram) *** ### `HistogramDisplayOptions` *type* Class with options that control how to display plot data on a chart. Class constructor (initializer for the data type). Whether or not to draw (by default) the plot on the pane. Whether or not to show the value of the plot in the status line. Whether or not to show the value label of the plot on the price axis. *** ### `Line` *type* Class which objects represent an element of line plot. Value of the plot element. Color of the plot element. Offset of the plot element. Class constructor (initializer for the data type). Value of the plot element. Color of the plot element. Offset of the plot element. See also: [`@line()`](/indie/Library-reference/package-indie-plot#decor_line) *** ### `LineDisplayOptions` *type* Class with options that control how to display plot data on a chart. Class constructor (initializer for the data type). Whether or not to draw (by default) the plot on the pane. Whether or not to show the value of the plot in the status line. Whether or not to show the value label of the plot on the price axis. *** ### `Marker` *type* Class which objects represent an element of marker plot. Value of the plot element. Color of the plot element. Marker text. Offset of the plot element. Class constructor (initializer for the data type). Value of the plot element. Color of the plot element. Marker text. Offset of the plot element. See also: [`@marker()`](/indie/Library-reference/package-indie-plot#decor_marker) *** ### `MarkerDisplayOptions` *type* Class with options that control how to display plot data on a chart. Class constructor (initializer for the data type). Whether or not to draw (by default) the plot on the pane. Whether or not to show the value of the plot in the status line. Whether or not to show the value label of the plot on the price axis. *** ### `Steps` *type* Class which objects represent an element of steps plot. Value of the plot element. Color of the plot element. Offset of the plot element. Class constructor (initializer for the data type). Value of the plot element. Color of the plot element. Offset of the plot element. See also: [`@steps()`](/indie/Library-reference/package-indie-plot#decor_steps) *** ### `StepsDisplayOptions` *type* Class with options that control how to display plot data on a chart. Class constructor (initializer for the data type). Whether or not to draw (by default) the plot on the pane. Whether or not to show the value of the plot in the status line. Whether or not to show the value label of the plot on the price axis. *** ## Enums ### `marker_position` *enum* Enum-like class with constants of marker positions. Built-in marker position constant that determines how the marker is rendered. Built-in marker position constant that determines how the marker is rendered. Built-in marker position constant that determines how the marker is rendered. Built-in marker position constant that determines how the marker is rendered. Built-in marker position constant that determines how the marker is rendered. *** ### `marker_style` *enum* Enum-like class with constants of marker styles. Built-in marker style constant that determines how the marker is rendered. Built-in marker style constant that determines how the marker is rendered. Built-in marker style constant that determines how the marker is rendered. Built-in marker style constant that determines how the marker is rendered. *** # Package indie.schedule Source: https://takeprofit.com/docs/indie/Library-reference/package-indie-schedule export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Schedule package that contains classes for working with schedules. *** ## Variables List of `week_day`'s from week\_day.MONDAY to week\_day.SUNDAY List of `week_day`'s from week\_day.SATURDAY to week\_day.SUNDAY List of `week_day`'s from week\_day.MONDAY to week\_day.FRIDAY *** ## Types ### `Schedule` *type* Data type that manages a collection of scheduling rules, allowing for specific times and exceptions to be defined. Class constructor (initializer for the data type). List of ScheduleRule instances that define the active scheduling rules. List of dates that are excluded from the schedule only once. List of dates that are excluded from the schedule every year. Timezone for schedule. Checks if the rules list in Schedule is empty. Returns `True` if list of rules is empty; otherwise, returns `False`. Checks whether a given timestamp falls within the defined schedule. Returns `True` if the timestamp falls within the schedule's active periods, otherwise returns `False`. Timestamp to check in defined schedule. Checks whether a given timestamp falls within the defined schedule. Returns `True` if the timestamp falls within the schedule's active periods, otherwise returns `False`. Datetime to check in defined schedule. Determines whether two timestamps fall within the same schedule period on the same day. Returns `True` if both timestamps fall within the same period of the schedule, even if they are in different calendar days. False if the timestamps belong to different periods within the schedule. First timestamp to check. Second timestamp to check. This method checks if two timestamps, which may belong to different calendar days, are part of the same schedule period. It handles cases where a schedule spans across two consecutive days (e.g., a trading schedule that extends past midnight) and ensures both timestamps belong to the same logical period within the schedule. See also: [`TradingSession`](/indie/Library-reference/package-indie#class_TradingSession) [`TradingSession`](/indie/Library-reference/package-indie#class_TradingSession) *** ### `ScheduleRule` *type* Data type to represent a rule for a schedule, specifying the start and end times, along with the weekdays when the rule is active. Class constructor (initializer for the data type). Start time of the rule. End time of the rule. List of weekdays when the rule is active. ```py Example # this rule applies from 9:00 AM to 6:30 PM (6:30 is not included) on weekdays (Monday through Friday). rule = ScheduleRule(start=time(hour=9), end=time(hour=18, minute=30), days=WORKDAYS) # this overnight_rule applies from 8:15 PM to 7:30 AM on weekdays (Monday through Friday). overnight_rule = ScheduleRule(start=time(hour=20, minute=15), end=time(hour=7, minute=30), days=WORKDAYS) ``` For rules that span overnight (e.g., from 10:00 PM to 6:00 AM), the end time should be on the day listed in days, while the start time is understood to be on the previous day. This allows the rule to cover activities that occur late in the evening and extend into the early hours of the next day. See also: [`Schedule`](/indie/Library-reference/package-indie-schedule#class_Schedule) [`TradingSession`](/indie/Library-reference/package-indie#class_TradingSession) *** ## Enums ### `week_day` *enum* Enum-like class with constants for days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. Built-in constants that represent days of week. *** # Package math Source: https://takeprofit.com/docs/indie/Library-reference/package-math export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Math package. See description in the [official Python docs](https://docs.python.org/3.10/library/math.html). *** ## Variables Standard constant of Indie math package (similar to Python's). Standard constant of Indie math package (similar to Python's). Standard constant of Indie math package (similar to Python's). *** ## Functions ### `acos()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `asin()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `atan()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `ceil()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `cos()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `exp()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `exp2()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `floor()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `isclose()` *function* Standard function of Indie math package (similar to Python's). First value to check for proximity. Second value to check for proximity. Relative tolerance for proximity check. Absolute tolerance for proximity check. *** ### `isnan()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `log()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `log10()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `log2()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `pow()` *function* Standard function of Indie math package (similar to Python's). Base value to calculate exponentiation. Exponent (power) value to calculate exponentiation. *** ### `sin()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `sqrt()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** ### `tan()` *function* Standard function of Indie math package (similar to Python's). Number on which the function will be calculated. *** # Package statistics Source: https://takeprofit.com/docs/indie/Library-reference/package-statistics export const Anchor = ({id}) => { return
; }; export const Field = ({id, name, type, required, defaultVal, children}) => { return
{id && }
{name}
{type}
{required && required } {defaultVal &&
default: {defaultVal}
}
{children}
; }; Statistics package. See description in the [official Python docs](https://docs.python.org/3.10/library/statistics.html). *** ## Functions ### `fmean()` *function* Standard statistics function. List on which the function will be calculated. *** ### `mean()` *function* Standard statistics function. List on which the function will be calculated. Standard statistics function. List on which the function will be calculated. *** ### `median()` *function* Standard statistics function. List on which the function will be calculated. *** # null Source: https://takeprofit.com/docs/indie/Quick-start To get you started quickly, let's write some indicators, starting with simple examples and gradually moving on to more complex ones. ## Minimal indicator Here is a minimal indicator for TakeProfit, which simply plots the 'close' price of the current chart instrument as a solid line: ```py # indie:lang_version = 5 from indie import indicator @indicator('Example 1') def Main(self): return self.close[0] ``` Let us take a closer look to what is happening in this example. First of all, the *entry point* of every indicator is the `Main` function (it must be named `Main` to keep all things in a 'standardized' way). The `Main` function is a function that is called per every candle of a chart instrument from left to right and after that it is continued to be called on every realtime update of the last (rightmost) candle. To sum up, it returns an *indicator value* for every candle of the main instrument. There is a `self` parameter in the `Main` function and it is an object of type [`MainContext`](/indie/Library-reference/package-indie#class_MainContext). It represents the main instrument of the chart, for example it gives access to OHLCV values of the instrument (e.g. [`self.close`](/indie/Library-reference/package-indie#obj_Context_close)). If you are familiar with Python, then you probably know that `self` is a reference to the instance of the class that is currently being used. It has the exact same meaning in Indie, though there are no classes in the code (yet). The `@indicator` decorator is a syntactic sugar that turns `def Main` function into a `class Main`. Read more about this in [How Indie's syntactic sugar works](/indie/How-Indies-syntactic-sugar-works) section. [*Context*](/indie/Library-reference/package-indie#class_Context), another new term (represented by a `self` parameter of `Main` function) is a representation of a current instrument displayed on a candle chart, with all it's prices (open, high, low, close, volume, etc.), some state and any other possible attributes it may have. In our example we take a series of close prices `self.close` and apply a square brackets operator to it, to get the last (most recent) value of that price: `self.close[0]`. Zero offset always corresponds to the last value (value on the last candle). Offset `1` corresponds to the value of the previous candle and so on. Our `Main` function is decorated with a required [`@indicator`](/indie/Library-reference/package-indie#decor_indicator) decorator with a required `title` param (`title` is the first param of this decorator, but you may write it in a kwarg form: `@indicator(title='Example 1')`). In general, decorators (things which names start with a `@` character) provide *meta*-information about indicators to TakeProfit's runtime. Meta-information describes indicator in some way, we will see a lot of this further. Finally, please note, that we have to `import` symbols like `indicator`, because they are not a part of Indie's built-in symbols. For now, the list of things that are allowed to be imported in the indicator code is very limited. But as the platform grows, the library will be expanded accordingly. After you type (or better copy-paste) the above code into the *Code Editor* (which is a widget and it should be added to your workspace first as **More Widgets** -> **Indicators Code Editor**) click on the button **Add to Chart**. As you can see, the indicator was added on a separate pane, below the main pane with candle chart. ![Figure 1.1. The minimal indicator.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-1.png) ## Overlay main pane If we want to add our indicator as an overlay on candle chart, we may add `overlay_main_pane=True` param to the `@indicator` decorator: ```py # indie:lang_version = 5 from indie import indicator @indicator('Example 2', overlay_main_pane=True) def Main(self): return self.close[0] ``` ![Figure 1.2. Indicator which overlays the main pane with the candle chart.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-2.png) ## Apply the SMA algorithm TakeProfit has a library of standard algorithms, such as *Simple Moving Average* ([SMA](/indie/Library-reference/package-indie-algorithms#class_alg_Sma)), let us import and use it: ```py # indie:lang_version = 5 from indie import indicator from indie.algorithms import Sma @indicator('Example 3', overlay_main_pane=True) def Main(self): s = Sma.new(self.close, 12) return s[0] ``` ![Figure 1.3. Usage of the SMA algorithm from the standard library.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-3.png) There are two essential parts that make it work: 1) import of the `Sma` algorithm from package `indie.algorithms` and 2) invocation of `Sma.new` in the indicator's code: `Sma.new(self.close, 12)`. Algorithms that process series of prices (like `self.close`) usually return series of numeric values (variable `s`). More about algorithms in [this chapter](/indie/Algorithms-for-series-processing). Let us make our indicator more interesting and calculate two SMAs with different lengths: ```py # indie:lang_version = 5 from indie import indicator from indie.algorithms import Sma @indicator('Example 4', overlay_main_pane=True) def Main(self): l = Sma.new(self.close, 42) s = Sma.new(self.close, 12) return l[0], s[0] ``` This indicator returns a *tuple* consisting of two values: `l[0]` and `s[0]`, that is why it plots two lines. ![Figure 1.4. Long and short SMAs in one indicator.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-4.png) ## Plot with different colors There are two different ways to colorize indicator's plot lines. First one is to use one single color for the whole plot. In such a way, colors are actually not involved in calculation over the candle prices, they are part of indicator's meta-information. We use `@plot.line` decorator for such way of coloring: ```py # indie:lang_version = 5 from indie import indicator, color, plot from indie.algorithms import Sma @indicator('Example 5', overlay_main_pane=True) @plot.line(color=color.GRAY) @plot.line(color=color.WHITE) def Main(self): l = Sma.new(self.close, 42) s = Sma.new(self.close, 12) return l[0], s[0] ``` ![Figure 1.5. Applying different colors to the plots of indicator.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-5.png) What if we would like to make a multicolored plot line? We may want to calculate the color depending on the candle prices data. If so, we would return from `Main` function not plain numbers, but `plot.Line` objects: ```py # indie:lang_version = 5 from indie import indicator, color, plot from indie.algorithms import Sma @indicator('Example 6', overlay_main_pane=True) @plot.line(color=color.GRAY) def Main(self): l = Sma.new(self.close, 42) s = Sma.new(self.close, 12) s_color = color.GREEN if s[0] > l[0] else color.RED return l[0], plot.Line(s[0], color=s_color) ``` ![Figure 1.6. Example of a dynamically colored plot (with red and green).](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-6.png) ## Input parameters It would be better not to hardcode the lengths of our two SMAs (literal constants `42` and `12`) but instead use named parameters. Named parameters are very convenient because they can be modified in the indicator's **Settings** panel without modifying the indicator's source code. For this purpose there are a whole set of decorators, starting with `@param.` prefix, for example: `@param.int`, `@param.bool`, `@param.string` and so on. Let us incorporate them in our example indicator: ```py # indie:lang_version = 5 from indie import indicator, color, plot, param from indie.algorithms import Sma @indicator('Example 7', overlay_main_pane=True) @param.int('long_length', default=42) @param.int('short_length', default=12) @plot.line(color=color.GRAY) def Main(self, long_length, short_length): l = Sma.new(self.close, long_length) s = Sma.new(self.close, short_length) s_color = color.GREEN if s[0] > l[0] else color.RED return l[0], plot.Line(s[0], color=s_color) ``` ![Figure 1.7. Indicator with integer input parameters.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Quick-start/image-7.png) More info about input parameters in [this](/indie/Input-parameters) chapter. # null Source: https://takeprofit.com/docs/indie/Request-additional-instruments An indicator written in Indie is executed after it is added to a candle chart. The symbol and time frame of the instrument of that chart is the main indicator instrument which is bound to the `Main` context of the indicator. It is possible to request additional instrument data in indicator. For that purpose there are `@sec_context` decorator and `indie.SecContext` class in combination with `Context.calc_on()` function. ## `@sec_context()` and `Context.calc_on()` Decorator `@sec_context` is a syntactic sugar that can be applied to a function definition which is an equivalent of writing a class inherited from `indie.SecContext` (more about the mechanics how this works can be found [here](https://takeprofit.com/docs/indie/How-Indies-syntactic-sugar-works#functions-decorated-with-sec_context)). The body of such a decorated function becomes an entry point for calculation when a data update is occurred on the corresponding additional instrument. Function call of `Context.calc_on` creates a connection between the `Main` context and the secondary one. Here is an example of an indicator that requests one additional instrument: ```py # indie:lang_version = 5 from indie import indicator, MainContext, sec_context, param @sec_context def SecMain(self): return self.high[0], self.low[0] @indicator('Minimal calc_on example', overlay_main_pane=True) @param.time_frame('sec_time_frame', default='1D') class Main(MainContext): def __init__(self, sec_time_frame): self._sec_high, self._sec_low = self.calc_on(SecMain, time_frame=sec_time_frame) def calc(self): return self._sec_high[0], self._sec_low[0] ``` NOTE: It is required that `Context.calc_on` function is called from `__init__` constructor method of a main or secondary context. ![Figure 9.1. Minimal Context.calc\_on() and @sec\_context example.](https://mintlify.s3.us-west-1.amazonaws.com/takeprofit-a5dc0462/images/indie/Standard-library/calc_on_example.png) If this indicator is added on a AAPL 15m chart it will draw two blue lines showing daily prices of the AAPL symbol. There are two instrument contexts in this indicator: * main context `Main` which is executed every time a data update on the main instrument AAPL 15m happens and * secondary context `SecMain` which is executed every time a data update on the secondary instrument AAPL 1D happens. Function [`Context.calc_on`](/indie/Library-reference/package-indie#func_Context_calc_on) has more parameters besides `sec_context` and `time_frame`. Here is its signature: ```txt Context.calc_on( sec_context: typing.Type[indie.SecContext], exchange: indie.Optional[str] = None, ticker: indie.Optional[str] = None, time_frame: indie.Optional[indie.TimeFrame] = None, lookahead: bool = False ) -> indie.SeriesF | tuple[indie.SeriesF, ...] ``` If `exchange`, `ticker` and `time_frame` are not given, then the corresponding values are taken from the current instrument. # null Source: https://takeprofit.com/docs/indie/Schedules-and-Trading-Sessions Managing trading activities in financial markets requires accounting for various time periods, such as pre-market, regular, and after-hours sessions. To efficiently manage these time periods and perform related calculations, we use the `indie.schedule.ScheduleRule`, `indie.schedule.Schedule` and `indie.TradingSession` classes. ## `ScheduleRule` The `ScheduleRule` class defines the specific time window and list of weekdays during which it applies. To create a `ScheduleRule` you need to specify: * start time of the rule * end time of the rule * list of weekdays: we have constants `indie.schedule.WORKDAYS`, `indie.schedule.WEEKEND` and `indie.schedule.ALL_DAYS`. You can also create a custom list of weekdays as a regular list of enums, e.g. `[indie.schedule.week_day.SATURDAY, indie.schedule.week_day.SUNDAY]` (which is exactly the same as `indie.schedule.WEEKEND` by the way). ### Types of `ScheduleRule` Depending on the start and end time values, there are three types of `ScheduleRules`. #### Simple basic rule Simple basic rule is a `ScheduleRule` object with `start < end`. If `end` is a midnight, then `end = time(0, 0, 0, 0)` This type of rule applies from start time to end time on specified weekdays. Example: ```py rule1 = ScheduleRule(start=time(hour=0), end=time(hour=5), days=ALL_DAYS) # from 00:00 am to 5:00 am everyday rule2 = ScheduleRule(start=time(hour=9), end=time(hour=18, minute=30), days=WORKDAYS) # from 9:00 am to 6:30 pm Monday through Friday rule3 = ScheduleRule(start=time(hour=20), end=time(hour=0), days=[week_day.WEDNESDAY]) # from 8:00 pm to 12:00 am on Wednesdays ``` #### Simple 24h rule Simple 24-hours rule is a `ScheduleRule` object with `start == end == time(hour=0, minute=0, second=0, microsecond=0)`. This type of rule applies 24 hours on specified weekdays. Example: ```py rule24 = ScheduleRule(start=time(hour=0), end=time(hour=0), days=ALL_DAYS) # from 12:00 am to 12:00 am every day (24/7) ``` #### Overnight rule Overnight rule is a `ScheduleRule` object with `start > end` or `start == end != time(hour=0, minute=0, second=0, microsecond=0)`. This type of rule applies from start time of the day before specified to end time of specified day. Example: ```py overnight_rule1 = ScheduleRule(start=time(hour=19), end=time(hour=7), days=[week_day.MONDAY]) # from 7:00 pm on Sunday to 7:00 am on Mondays overnight_rule2 = ScheduleRule(start=time(hour=21), end=time(hour=3), days=WORKDAYS) # for the whole week: from 9:00 pm on Sunday to 3:00 am on Friday overnight_rule3 = ScheduleRule(start=time(hour=15), end=time(hour=15), days=WORKDAYS) # from 3:00 pm on Sunday to 3:00 pm on Friday ``` Another way to represent an overnight rule is to use a combination of two different non-overnight rules. The first rule will have the same start time, the end time will be `time(0, 0, 0, 0)`, the second rule will have the start time equal to `time(0, 0, 0, 0)` and the end time will be the same as the original rule. ```py overnight_rule = ScheduleRule(start=time(hour=19), end=time(hour=7), days=[week_day.MONDAY]) # from 7:00 pm on Sunday to 7:00 am on Mondays # it is equivalent to simple_rule1 = ScheduleRule(start=time(hour=19), end=time(hour=0), days=[week_day.SUNDAY]) simple_rule2 = ScheduleRule(start=time(hour=0), end=time(hour=7), days=[week_day.MONDAY]) ``` ## `Schedule` Each `Schedule` instance defines specific time windows and exceptions to a regular schedule. To create your own schedule, you need to define: * `rules` - a list of ScheduleRules * `except_once` - a list of specific dates for one-time exceptions (e.g., special events or emergencies) that deviate from the usual schedule * `except_yearly` - a list of dates representing annual exceptions (e.g., holidays) * `timezone` - the time zone in which the schedule is defined. The time zone should be indicated according to the [IANA library standards](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) (e.g., "America/New\_York" or "Europe/London"). It is quite resource-inefficient to create `Schedule` objects within the `Context.calc` method, as this would instantiate a new object on each bar, resulting in a high number of short-lived objects. Therefore, it is recommended to declare them in the `__init__` function in the class definition, which will create them once during the indicator's initialization. Example: ```py # indie:lang_version = 5 from indie import indicator, MainContext from indie.schedule import ScheduleRule, Schedule, WORKDAYS, WEEKEND from datetime import time, datetime @indicator('Example') class Main(MainContext): def __init__(self): rule1 = ScheduleRule(start=time(hour=9), end=time(hour=18), days=WORKDAYS) rule2 = ScheduleRule(start=time(hour=12), end=time(hour=15), days=WEEKEND) self.schedule = Schedule(rules=[rule1, rule2], except_once=[datetime(year=2025, month=4, day=5)], timezone="America/New_York") def calc(self): # using self.schedule, e.g. return 1 if self.time[0] in self.schedule else 0 ``` If you want to use `self.info.timezone` as the timezone in a `Schedule()`, you need to define a `pre_calc` function in your class and initialize the field inside this function. This is necessary because in the `__init__` method, `self.info` and `self.trading_session` data are not yet available. Example: ```py # indie:lang_version = 5 from indie import indicator, MainContext, Optional from indie.schedule import ScheduleRule, Schedule, WORKDAYS, WEEKEND from datetime import time, datetime @indicator('Example') class Main(MainContext): def __init__(self): self.schedule: Optional[Schedule] = None def pre_calc(self): rule1 = ScheduleRule(start=time(hour=9), end=time(hour=18), days=WORKDAYS) rule2 = ScheduleRule(start=time(hour=12), end=time(hour=15), days=WEEKEND) self.schedule = Schedule(rules=[rule1, rule2], except_once=[datetime(year=2025, month=4, day=5)], timezone=self.info.timezone) def calc(self): # using self.schedule, e.g. return 1 if self.time[0] in self.schedule.value() else 0 ``` `Schedule` class provides several key functionalities for working with schedules. One of the primary actions is checking whether the schedule is empty using the [`is_empty`](/indie/Library-reference/package-indie-schedule#func_Schedule_is_empty) method. Additionally, the [`in`](/indie/Library-reference/package-indie-schedule#func_Schedule_contains) operator allows you to verify if a given timestamp falls within the time periods defined by the schedule. Another useful method is [`is_same_period`](/indie/Library-reference/package-indie-schedule#func_Schedule_is_same_period), which checks whether two timestamps belong to the same schedule period or fall on different days. ## `TradingSession` The `TradingSession` class represents the different phases of market trading. These phases correspond to specific trading windows with unique rules that vary depending on the market. It is not allowed to create objects of the `TradingSession` class in Indie code; an already created instance of the class is available in `self.trading_session`. There are three fields in `TradingSession` class: * `pre_market` * `regular` * `after_hours` Each of these fields is an instance of the `Schedule` class. The `pre_market` and `after_hours` schedules can be empty, which can be verified using the `is_empty` method. The main operations with `TradingSession` objects include using the [`in`](/indie/Library-reference/package-indie-schedule#func_TradingSession_contains) operator to check if a specific timestamp falls within any of the trading session periods, and the [`is_same_period`](/indie/Library-reference/package-indie-schedule#func_TradingSession_is_same_period) method to determine whether two timestamps belong to the same trading period. The `Context` class provides four methods to determine whether the current bar is the first or last bar of a trading session: * `is_first_in_session()` * `is_first_in_regular_session()` * `is_last_in_session()` * `is_last_in_regular_session()` If `pre_market` is empty, the `is_first_in_session` and `is_first_in_regular_session` methods will return the same value. Similarly, if `after_hours` is empty, `is_last_in_session` and `is_last_in_regular_session` will return the same value. If the first or last bar of the session does not exist or is unavailable, these methods will not return `True`. # What is Indie? Source: https://takeprofit.com/docs/indie/What-is-Indie **Indie** is a *technical analysis-oriented* programming language and runtime for developing indicators for the TakeProfit platform. All built-in indicators on the platform are implemented in Indie, and TakeProfit has integrated IDE tools that allow users to create their own indicators. Indie is a dialect of Python and is essentially a subset of Python language constructs, with added [syntactic sugar](/indie/How-Indies-syntactic-sugar-works) in the form of decorators (such as `@indicator` or `@algorithm`) and a few differences in semantics. You can learn more about these differences in [this section](/indie/Language-differences-with-Python). For a quick understanding of the Indie code, it is recommended to go directly to the [Quick start](/indie/Quick-start) chapter. As a product of TakeProfit, Indie is under ongoing development and many new features and capabilities are expected to be added in the future. To get you started quickly, let’s write some indicators, starting with simple examples and gradually moving on to more complex ones. The main differences between the Python language and Indie. An overview of the Indie library and its functions. All changes and updates to the Indie language.