### Install python-dotenv Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Installs the python-dotenv package, which is used for loading environment variables from a .env file. This is crucial for managing sensitive information like API keys. ```bash #!/usr/bin/env python import sys import subprocess subprocess.check_call([sys.executable, "-m", "pip", "install", "-U", "python-dotenv"]) ``` -------------------------------- ### Install Pip Package in Jupyter Kernel Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Installs or upgrades a Python package using pip within the current Jupyter kernel. This is a common way to manage dependencies in a notebook environment. ```python # Install a pip package in the current Jupyter kernel # import sys # !{sys.executable} -m pip install -U python-dotenv ``` -------------------------------- ### Execute Full Market Analysis Workflow Source: https://context7.com/edyatl/qqe-mod/llms.txt Demonstrates the complete pipeline for fetching Binance kline data, calculating QQE-Mod indicators, and filtering for actionable buy/sell signals. The output is saved to a CSV file for further analysis. ```python import pandas as pd import numpy as np from binance import Client import os # Fetch market data and process signals client = Client(os.environ.get("ENV_API_KEY"), os.environ.get("ENV_SECRET_KEY")) klines = client.get_klines(symbol="BTCUSDT", interval=Client.KLINE_INTERVAL_15MINUTE) data = pd.DataFrame(klines, columns=["open_time", "open", "high", "low", "close", "volume", "close_time", "qav", "num_trades", "taker_base_vol", "taker_quote_vol", "ignore"]) data["close"] = data["close"].astype(float) # Calculate indicators and filter signals qqe_up, qqe_down = qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, 50) results = pd.DataFrame({"timestamp": data["close_time"], "qqe_up": qqe_up, "qqe_down": qqe_down}) buy_signals = results[~np.isnan(results["qqe_up"])] sell_signals = results[~np.isnan(results["qqe_down"])] results.to_csv('qqe_mod-BTCUSDT-15m.csv', index=False) ``` -------------------------------- ### Define QQE Indicator Parameters Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Sets up configuration parameters for calculating the QQE (Quantitative Qualitative Estimation) indicator. This includes defining periods for RSI, smoothing factors, QQE factors, and thresholds. ```python import talib as tl import numpy as np CONST50 = 50 # 50 MA bollinger band RSI_Period: int = 6 # input(6, title='RSI Length') SF: int = 5 # input(5, title='RSI Smoothing') QQE: float = 3.0 # input(3, title='Fast QQE Factor') ThreshHold: int = 3 # input(3, title="Thresh-hold") src: pd.Series = data["close"] # input(close, title="RSI Source") RSI_Period2: int = 6 # input(6, title='RSI Length') SF2: int = 5 # input(5, title='RSI Smoothing') QQE2: float = 1.61 # input(1.61, title='Fast QQE2 Factor') ThreshHold2: int = 3 # input(3, title="Thresh-hold") src2: pd.Series = data["close"] # input(close, title="RSI Source") ``` -------------------------------- ### Define QQE Indicator Parameters Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Sets up input parameters for the QQE (Quantitative Qualitative Estimation) indicator. This includes periods for RSI calculation, smoothing factors, QQE factors, and threshold values. It also defines the source data series, typically the closing price. ```python # Common constant in calculations CONST50 = 50 # 50 MA bollinger band # First RSI input block RSI_Period: int = 6 # input(6, title='RSI Length') SF: int = 5 # input(5, title='RSI Smoothing') QQE: float = 3.0 # input(3, title='Fast QQE Factor') ThreshHold: int = 3 # input(3, title="Thresh-hold") - not used var src: pd.Series = data["close"] # input(close, title="RSI Source") # Second RSI input block RSI_Period2: int = 6 # input(6, title='RSI Length') SF2: int = 5 # input(5, title='RSI Smoothing') QQE2: float = 1.61 # input(1.61, title='Fast QQE2 Factor') ThreshHold2: int = 3 # input(3, title="Thresh-hold") src2: pd.Series = data["close"] # input(close, title="RSI Source") ``` -------------------------------- ### Import Standard Libraries and APIs Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Imports essential Python libraries for data analysis (pandas, numpy), technical analysis (talib), environment variable management (os, dotenv), and interacting with the Binance API (binance). ```python # Standard imports import pandas as pd import numpy as np # import matplotlib.pyplot as plt # import seaborn as sns import talib as tl import os from os import environ as env from dotenv import load_dotenv from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager # Nicest style for plots # sns.set(style="ticks") ``` -------------------------------- ### Load Environment Variables and Initialize API Client Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Loads API keys from a .env file located in the project's root directory and initializes a client object using these credentials. It checks if the .env file exists before attempting to load it. ```python import os from dotenv import load_dotenv from binance.client import Client project_dotenv = os.path.join(os.path.abspath(""), ".env") if os.path.exists(project_dotenv): load_dotenv(project_dotenv) api_key, api_secret = os.environ.get("ENV_API_KEY"), os.environ.get("ENV_SECRET_KEY") client = Client(api_key, api_secret) ``` -------------------------------- ### Initialize Trend and FastAtrRsiTL Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Demonstrates how to initialize the trend array and calculate the FastAtrRsiTL series using NumPy's where function, ensuring NaN values are handled to prevent downstream errors in TA-Lib. ```python trend[:][trend == 0] = 1 FastAtrRsiTL: pd.Series = np.zeros_like(src, dtype=float) FastAtrRsiTL = np.where(trend == 1, longband, shortband) FastAtrRsiTL = np.nan_to_num(FastAtrRsiTL) ``` -------------------------------- ### Initialize Binance API Client Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Initializes the Binance API client using API key and secret retrieved from environment variables. This client is used to interact with the Binance trading platform. ```python api_key, api_secret = env.get("ENV_API_KEY"), env.get("ENV_SECRET_KEY") client = Client(api_key, api_secret) ``` -------------------------------- ### Generate Buy and Sell Signals with Python Source: https://context7.com/edyatl/qqe-mod/llms.txt Generates trading signals by comparing RSI moving averages against threshold and Bollinger-style bands. Signals are only returned when both primary and secondary QQE conditions are met, otherwise returning NaN. ```python import numpy as np def qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, CONST50) -> tuple: Greenbar1 = RsiMa2 - CONST50 > ThreshHold2 Greenbar2 = RsiMa - CONST50 > upper Redbar1 = RsiMa2 - CONST50 < 0 - ThreshHold2 Redbar2 = RsiMa - CONST50 < lower qqe_up_cond = Greenbar1 & Greenbar2 qqe_down_cond = Redbar1 & Redbar2 qqe_up = np.where(qqe_up_cond, RsiMa2 - CONST50, np.nan) qqe_down = np.where(qqe_down_cond, RsiMa2 - CONST50, np.nan) return qqe_up, qqe_down ``` -------------------------------- ### Structure QQE Results in DataFrame Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Demonstrates how to aggregate QQE signal arrays into a Pandas DataFrame for easier analysis and visualization of the results. ```python qqe_up2, qqe_down2 = qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, CONST50) res2 = pd.DataFrame( { "qqe_up": qqe_up, "qqe_up2": qqe_up2, "qqe_down": qqe_down, "qqe_down2": qqe_down2, } ) res2.tail(20) ``` -------------------------------- ### QQE Mod Indicator Data Preparation (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Prepares data for QQE Mod indicators by calculating the main line and histogram values. It also integrates the previously calculated up and down momentum. This function is crucial for plotting and further analysis. ```Python qqe_up, qqe_down = qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, CONST50) qqe_line = FastAtrRsi2TL - CONST50 histo2 = RsiMa2 - CONST50 ``` -------------------------------- ### Calculate Bollinger Upper and Lower Bands (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Calculates the upper and lower Bollinger Bands based on the provided QQE indicator data (FastAtrRsiTL), length, multiplier, and a constant offset. It utilizes Simple Moving Average (SMA) and Standard Deviation (STDDEV) from the TA-Lib library. ```python def bollinger_uplower( FastAtrRsiTL: np.ndarray, length: int, mult: float, CONST50: int ) -> tuple: basis = tl.SMA(FastAtrRsiTL - CONST50, timeperiod=length) dev = mult * tl.STDDEV(FastAtrRsiTL - CONST50, length) upper = basis + dev lower = basis - dev return upper, lower ``` -------------------------------- ### Initialize QQE Signal Arrays Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Creates empty signal arrays for QQE up and down trends using numpy. The arrays are initialized with NaN values based on the shape of the input RSI moving average array. ```python qqe_up = np.full_like(RsiMa2, fill_value=np.nan) qqe_down = np.full_like(RsiMa2, fill_value=np.nan) ``` -------------------------------- ### Create DataFrame from QQE Results Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Creates a pandas DataFrame to store and display the results from two QQE histogram calculations (FastAtrRsiTL, FastAtrRsi2TL) and their corresponding RSI moving averages (RsiMa, RsiMa2). The `tail(20)` method displays the last 20 rows of the DataFrame. ```python res = pd.DataFrame( { "FastAtrRsiTL": FastAtrRsiTL, "FastAtrRsi2TL": FastAtrRsi2TL, "RsiMa": RsiMa, "RsiMa2": RsiMa2, } ) res.tail(20) ``` -------------------------------- ### Standard Imports for Data Analysis and Trading Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Imports essential Python libraries for data manipulation (pandas, numpy), visualization (matplotlib, seaborn), technical analysis (talib), environment variable management (os, dotenv), and interacting with the Binance API (binance). Sets a default style for seaborn plots. ```python # Standard imports import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import talib as tl import os from os import environ as env from dotenv import load_dotenv from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager # Nicest style for plots sns.set(style="ticks") ``` -------------------------------- ### Calculate Bollinger Bands for QQE Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Calculates the basis, standard deviation, and upper/lower bands for the QQE Mod indicator using TA-Lib SMA and STDDEV functions. ```python length: int = CONST50 mult: float = 0.35 basis = tl.SMA(FastAtrRsiTL - CONST50, timeperiod=length) dev = mult * tl.STDDEV(FastAtrRsiTL - CONST50, length) upper = basis + dev lower = basis - dev ``` -------------------------------- ### Execute QQE Histogram Calculation with Second Set of Parameters Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Executes the qqe_hist function with a second set of parameters (src2, RSI_Period2, SF2, QQE2). This allows for the calculation of a second QQE indicator, potentially for comparison or multi-timeframe analysis. ```python FastAtrRsi2TL, RsiMa2 = qqe_hist(src2, RSI_Period2, SF2, QQE2) ``` -------------------------------- ### Calculate QQE Histogram Values Source: https://context7.com/edyatl/qqe-mod/llms.txt Computes the Fast ATR RSI Trendline and RSI Moving Average using TA-Lib. It processes price data to determine adaptive bands based on RSI volatility and trend direction. ```python import pandas as pd import numpy as np import talib as tl def qqe_hist(src: pd.Series, RSI_Period: int, SF: int, QQE: float) -> tuple: Wilders_Period: int = RSI_Period * 2 - 1 Rsi = tl.RSI(src, RSI_Period) RsiMa = tl.EMA(Rsi, SF) AtrRsi = np.abs(np.roll(RsiMa.copy(), 1) - RsiMa) MaAtrRsi = tl.EMA(AtrRsi, Wilders_Period) dar = tl.EMA(MaAtrRsi, Wilders_Period) * QQE longband = np.zeros_like(src, dtype=float) shortband = np.zeros_like(src, dtype=float) trend = np.zeros_like(src, dtype=int) DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi for i in range(1, len(src)): if RSIndex[i - 1] > longband[i - 1] and RSIndex[i] > longband[i - 1]: longband[i] = max(longband[i - 1], newlongband[i]) else: longband[i] = newlongband[i] if RSIndex[i - 1] < shortband[i - 1] and RSIndex[i] < shortband[i - 1]: shortband[i] = min(shortband[i - 1], newshortband[i]) else: shortband[i] = newshortband[i] FastAtrRsiTL = np.where(trend == 1, longband, shortband) FastAtrRsiTL = np.nan_to_num(FastAtrRsiTL) return FastAtrRsiTL, RsiMa ``` -------------------------------- ### QQE Mod Indicator DataFrame Creation (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Creates a pandas DataFrame to consolidate the calculated QQE Mod indicator values, including the line, histogram, up momentum, and down momentum. This structured format is ideal for analysis and visualization. ```Python res2 = pd.DataFrame( { "qqe_line": qqe_line, "histo2": histo2, "qqe_up": qqe_up, "qqe_down": qqe_down, } ) res2.tail(20) ``` -------------------------------- ### Create QQE Indicator DataFrame in Python Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Constructs a pandas DataFrame to store the calculated QQE line, histogram values (histo2), and up/down trend indicators (qqe_up, qqe_down). The .tail(20) method is used to display the last 20 rows of the DataFrame. ```python res2 = pd.DataFrame({ "qqe_line": qqe_line, "histo2": histo2, "qqe_up": qqe_up, "qqe_down": qqe_down, }) res2.tail(20) ``` -------------------------------- ### Bollinger Bands for QQE Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Calculates the upper and lower Bollinger Bands based on the QQE histogram values. ```APIDOC ## POST /api/qqe/bollinger ### Description Calculates the upper and lower Bollinger Bands using the QQE histogram values as the basis. This helps in identifying volatility and potential price reversals. ### Method POST ### Endpoint /api/qqe/bollinger ### Parameters #### Request Body - **FastAtrRsiTL** (np.ndarray) - Required - The QQE histogram values. - **length** (int) - Required - The lookback period for the Simple Moving Average (SMA) and Standard Deviation. - **mult** (float) - Required - The multiplier for the standard deviation to determine the band width. - **CONST50** (int) - Required - A constant value, likely a baseline or offset, used in the calculation. ### Request Example ```json { "FastAtrRsiTL": [98.5, 101.2, 103.5, 102.1, 100.8, 103.0, 105.5, 107.2, 106.8, 105.1], "length": 20, "mult": 2.0, "CONST50": 50 } ``` ### Response #### Success Response (200) - **upper** (pd.Series) - The calculated upper Bollinger Band. - **lower** (pd.Series) - The calculated lower Bollinger Band. #### Response Example ```json { "upper": [110.5, 112.1, 114.0, 113.5, 112.8, 114.5, 116.2, 118.0, 117.5, 116.0], "lower": [86.5, 90.3, 93.0, 90.7, 88.8, 91.5, 94.8, 96.4, 96.1, 94.2] } ``` ``` -------------------------------- ### Load Environment Variables from .env File Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Loads environment variables from a .env file located in the project's root directory. This is crucial for securely managing API keys and other sensitive configurations. ```python project_dotenv = os.path.join(os.path.abspath(""), ".env") if os.path.exists(project_dotenv): load_dotenv(project_dotenv) ``` -------------------------------- ### Display Last 10 QQE Series Values (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Displays the last 10 values of a pandas Series named 'QQEzshort'. This is useful for inspecting the tail end of the QQE short signal data. ```python pd.Series(QQEzshort).tail(10) ``` -------------------------------- ### Calculate Bollinger Band Levels Source: https://context7.com/edyatl/qqe-mod/llms.txt Calculates upper and lower Bollinger Band levels relative to the QQE trendline. These bands act as dynamic thresholds for confirming market overbought or oversold conditions. ```python import numpy as np import talib as tl def bollinger_uplower( FastAtrRsiTL: np.ndarray, length: int, mult: float, CONST50: int ) -> tuple: basis = tl.SMA(FastAtrRsiTL - CONST50, timeperiod=length) dev = mult * tl.STDDEV(FastAtrRsiTL - CONST50, length) upper = basis + dev lower = basis - dev return upper, lower ``` -------------------------------- ### Define Bollinger Input Parameters Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Defines the input parameters for the Bollinger Bands calculation, including length and multiplier. These are typically used in trading strategy development. ```python length: int = CONST50 # input(50, minval=1, title="Bollinger Length") mult: float = ( 0.35 # input(0.35, minval=0.001, maxval=5, step=0.1, title="BB Multiplier") ) ``` -------------------------------- ### Calculate QQE Indicator Components Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Computes intermediate values for the QQE indicator, including RSI, smoothed RSI, Average True Range (ATR) of RSI, and the Delta of the ATR-smoothed RSI. These are essential steps before calculating the final QQE bands. ```python Wilders_Period: int = RSI_Period * 2 - 1 Rsi = tl.RSI(src, RSI_Period) RsiMa = tl.EMA(Rsi, SF) AtrRsi = np.abs(np.roll(RsiMa.copy(), 1) - RsiMa) MaAtrRsi = tl.EMA(AtrRsi, Wilders_Period) dar = tl.EMA(MaAtrRsi, Wilders_Period) * QQE longband: pd.Series = np.zeros_like(src, dtype=float) shortband: pd.Series = np.zeros_like(src, dtype=float) trend: pd.Series = np.zeros_like(src, dtype=int) ``` -------------------------------- ### Fetch Klines Data from Binance Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Fetches historical klines (candlestick) data for a specified trading pair (e.g., ATOMUSDT) and interval (e.g., 15-minute) from the Binance API. Defines column names for the retrieved data. ```python klines = client.get_klines(symbol="ATOMUSDT", interval=Client.KLINE_INTERVAL_15MINUTE) short_col_names = [ "open_time", "open", "high", "low", "close", "volume", "close_time", "qav", "num_trades", "taker_base_vol", "taker_quote_vol", "ignore", ] ``` -------------------------------- ### Calculate QQE and Histogram Lines in Python Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Calculates the QQE line and histogram values by subtracting a constant from FastAtrRsi2TL and RsiMa2 respectively. These are core components for the QQE indicator. ```python qqe_line = FastAtrRsi2TL - CONST50 histo2 = RsiMa2 - CONST50 ``` -------------------------------- ### Zero Cross Detection for QQE Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Identifies zero crosses for QQE long and short signals. ```APIDOC ## POST /api/qqe/zero_cross ### Description Detects when the QQE indicator crosses the zero line, signaling potential changes in trend direction for both long and short positions. ### Method POST ### Endpoint /api/qqe/zero_cross ### Parameters #### Request Body - **src** (pd.Series) - Required - The source price series. - **RSIndex** (np.ndarray) - Required - The QQE smoothed RSI values. - **CONST50** (int) - Required - A constant value used in the QQE calculation, likely a baseline. ### Request Example ```json { "src": [100, 102, 105, 103, 101, 104, 106, 108, 107, 105], "RSIndex": [55.2, 58.1, 61.5, 59.0, 57.5, 59.8, 62.3, 64.5, 63.9, 62.5], "CONST50": 50 } ``` ### Response #### Success Response (200) - **QQEzlong** (np.ndarray) - An array indicating QQE long zero crosses. - **QQEzshort** (np.ndarray) - An array indicating QQE short zero crosses. #### Response Example ```json { "QQEzlong": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "QQEzshort": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] } ``` ``` -------------------------------- ### Execute QQE Histogram Calculation Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Executes the qqe_hist function with specified parameters to obtain the QQE histogram and RSI moving average. This is a common step in applying the QQE indicator. ```python FastAtrRsiTL, RsiMa = qqe_hist(src, RSI_Period, SF, QQE) ``` -------------------------------- ### QQE Histogram Generation Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Generates the QQE histogram values and the smoothed RSI values. ```APIDOC ## POST /api/qqe/histogram ### Description Calculates the QQE histogram and the smoothed Relative Strength Index (RSI) values based on input price data and specified parameters. ### Method POST ### Endpoint /api/qqe/histogram ### Parameters #### Request Body - **src** (pd.Series) - Required - The source price series (e.g., closing prices). - **RSI_Period** (int) - Required - The period for calculating the RSI. - **SF** (int) - Required - The smoothing factor for the RSI moving average. - **QQE** (float) - Required - The multiplier for the Average True Range (ATR) in the QQE calculation. ### Request Example ```json { "src": [100, 102, 105, 103, 101, 104, 106, 108, 107, 105], "RSI_Period": 14, "SF": 5, "QQE": 4.2 } ``` ### Response #### Success Response (200) - **FastAtrRsiTL** (pd.Series) - The QQE histogram values. - **RsiMa** (pd.Series) - The smoothed RSI values. #### Response Example ```json { "FastAtrRsiTL": [98.5, 101.2, 103.5, 102.1, 100.8, 103.0, 105.5, 107.2, 106.8, 105.1], "RsiMa": [55.2, 58.1, 61.5, 59.0, 57.5, 59.8, 62.3, 64.5, 63.9, 62.5] } ``` ``` -------------------------------- ### Calculate QQE Indicator Signals Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Uses NumPy to generate QQE up and down signals based on conditional logic applied to RsiMa2. It returns an array of values or NaNs where conditions are not met. ```python import numpy as np # Calculate QQE up and down signals based on conditions qqe_up = np.where(qqe_up_cond, RsiMa2 - 50, np.nan) qqe_down = np.where(qqe_down_cond, RsiMa2 - 50, np.nan) ``` -------------------------------- ### Pandas Series Shift and NaN Handling Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb This Python code demonstrates how to create a pandas Series, shift its values by one position, and handle potential NaN values by converting them to 0 using `np.nan_to_num`. The shifted series is then displayed. ```python x = pd.Series(np.random.rand(10)) x ``` ```python pd.Series(np.nan_to_num(x.shift(1), nan=1)) ``` -------------------------------- ### QQE Histogram Calculation (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Calculates the Quantitative Qualitative Estimation (QQE) histogram and Relative Strength Index (RSI) moving average. This function uses pandas and TA-Lib for calculations and returns the QQE histogram and RSI moving average. ```python def qqe_hist(src: pd.Series, RSI_Period: int, SF: int, QQE: float) -> tuple: Wilders_Period: int = RSI_Period * 2 - 1 Rsi = tl.RSI(src, RSI_Period) RsiMa = tl.EMA(Rsi, SF) AtrRsi = np.abs(np.roll(RsiMa.copy(), 1) - RsiMa) MaAtrRsi = tl.EMA(AtrRsi, Wilders_Period) dar = tl.EMA(MaAtrRsi, Wilders_Period) * QQE longband: pd.Series = np.zeros_like(src, dtype=float) shortband: pd.Series = np.zeros_like(src, dtype=float) trend: pd.Series = np.zeros_like(src, dtype=int) FastAtrRsiTL: pd.Series = np.zeros_like(src, dtype=float) DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi for i in range(1, len(src)): if RSIndex[i - 1] > longband[i - 1] and RSIndex[i] > longband[i - 1]: longband[i] = max(longband[i - 1], newlongband[i]) else: longband[i] = newlongband[i] if RSIndex[i - 1] < shortband[i - 1] and RSIndex[i] < shortband[i - 1]: shortband[i] = min(shortband[i - 1], newshortband[i]) else: shortband[i] = newshortband[i] cross_1 = cross(np.roll(longband.copy(), 1), RSIndex) cross_2 = cross(RSIndex, np.roll(shortband.copy(), 1)) for i in range(1, len(src)): trend[i] = ( 1 if cross_2[i] else -1 if cross_1[i] else 1 if np.isnan(trend[i - 1]) else trend[i - 1] ) FastAtrRsiTL = np.where(trend == 1, longband, shortband) FastAtrRsiTL = np.nan_to_num(FastAtrRsiTL) return FastAtrRsiTL, RsiMa ``` -------------------------------- ### Accumulate QQE Long and Short Signals Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Iteratively calculates the cumulative count of consecutive long and short signals based on the relative strength index compared to a constant threshold. ```python QQEzlong: pd.Series = np.zeros_like(src, dtype=int) QQEzshort: pd.Series = np.zeros_like(src, dtype=int) for i in range(1, len(src)): QQEzlong[i] = QQEzlong[i - 1] QQEzshort[i] = QQEzshort[i - 1] QQEzlong[i] = QQEzlong[i] + 1 if RSIndex[i] >= CONST50 else 0 QQEzshort[i] = QQEzshort[i] + 1 if RSIndex[i] < CONST50 else 0 ``` -------------------------------- ### Apply Bollinger Bands Calculation Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Applies the bollinger_uplower function to calculate the upper and lower Bollinger Bands using the FastAtrRsiTL data and previously defined parameters (length, mult, CONST50). ```python upper, lower = bollinger_uplower(FastAtrRsiTL, length, mult, CONST50) ``` -------------------------------- ### Assigning Shortband Values in Python Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb This snippet demonstrates how to assign values from a new shortband array to an existing shortband array based on a condition. It utilizes Python's array manipulation capabilities, likely involving libraries like NumPy. ```python shortband[~short_cond] = newshortband[~short_cond] ``` -------------------------------- ### Load Jupyter Extension for Code Formatting Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Loads the nb_black Jupyter extension to automatically format Python code according to Black library standards. This is useful for maintaining consistent code style within Jupyter notebooks. ```python # Load Jupyter extension for auto correction coding style based on Black Lib %load_ext nb_black ``` -------------------------------- ### Fetch Kline Data from Binance API Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Retrieves historical kline (candlestick) data for a specified trading pair (ATOMUSDT) and interval (15 minutes) using the Binance API client. The data is then assigned to a pandas DataFrame with predefined column names. ```python import pandas as pd klines = client.get_klines(symbol="ATOMUSDT", interval=Client.KLINE_INTERVAL_15MINUTE) short_col_names = [ "open_time", "open", "high", "low", "close", "volume", "close_time", "qav", "num_trades", "taker_base_vol", "taker_quote_vol", "ignore", ] data = pd.DataFrame(klines, columns=short_col_names) data["open_time"] = pd.to_datetime(data["open_time"], unit="ms") data["close_time"] = pd.to_datetime(data["close_time"], unit="ms") ``` -------------------------------- ### QQE Mod Momentum Calculation (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Calculates the up and down momentum for the QQE indicator based on RSI thresholds. It uses numpy for efficient array operations. Inputs are RSI values and various thresholds, outputs are arrays representing up and down momentum. ```Python def qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, CONST50) -> tuple: Greenbar1: np.ndarray = RsiMa2 - CONST50 > ThreshHold2 Greenbar2: np.ndarray = RsiMa - CONST50 > upper Redbar1: np.ndarray = RsiMa2 - CONST50 < 0 - ThreshHold2 Redbar2: np.ndarray = RsiMa - CONST50 < lower qqe_up_cond = Greenbar1 & Greenbar2 qqe_down_cond = Redbar1 & Redbar2 qqe_up = np.full_like(RsiMa2, fill_value=np.nan) qqe_down = np.full_like(RsiMa2, fill_value=np.nan) qqe_up = np.where(qqe_up_cond, RsiMa2 - 50, np.nan) qqe_down = np.where(qqe_down_cond, RsiMa2 - 50, np.nan) return qqe_up, qqe_down ``` -------------------------------- ### Determine QQE Bands Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Calculates the final upper and lower bands for the QQE indicator based on the smoothed RSI and the calculated Delta Fast ATR RSI. These bands are used to identify potential trend changes and overbought/oversold conditions. ```python DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi ``` -------------------------------- ### Detect Zero Crossings (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Detects zero crossings for QQE long and short signals based on a reference index and a threshold. It iterates through the series to count consecutive values above or below the threshold. Dependencies include pandas and numpy. ```python def zero_cross(src: pd.Series, RSIndex: np.ndarray, CONST50: int) -> tuple: QQEzlong: np.ndarray = np.zeros_like(src, dtype=int) QQEzshort: np.ndarray = np.zeros_like(src, dtype=int) for i in range(1, len(src)): QQEzlong[i] = QQEzlong[i - 1] QQEzshort[i] = QQEzshort[i - 1] QQEzlong[i] = QQEzlong[i] + 1 if RSIndex[i] >= CONST50 else 0 QQEzshort[i] = QQEzshort[i] + 1 if RSIndex[i] < CONST50 else 0 return QQEzlong, QQEzshort ``` -------------------------------- ### Define QQE Trend Conditions Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Calculates boolean conditions for QQE up and down trends by evaluating consecutive bar states. It uses pandas Series to verify the trend status at the end of the dataset. ```python qqe_up_cond = Greenbar1 & Greenbar2 qqe_down_cond = Redbar1 & Redbar2 pd.Series(qqe_down_cond).tail(10) ``` -------------------------------- ### Calculate QQE Up and Down Signals Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb This function calculates QQE signals by comparing RSI moving averages against defined thresholds. It returns two NumPy arrays representing the up and down signals, with non-signal values set to NaN. ```python def qqe_up_down(RsiMa, RsiMa2, upper, lower, ThreshHold2, CONST50) -> tuple: Greenbar1: np.ndarray = RsiMa2 - CONST50 > ThreshHold2 Greenbar2: np.ndarray = RsiMa - CONST50 > upper Redbar1: np.ndarray = RsiMa2 - CONST50 < 0 - ThreshHold2 Redbar2: np.ndarray = RsiMa - CONST50 < lower qqe_up_cond = Greenbar1 & Greenbar2 qqe_down_cond = Redbar1 & Redbar2 qqe_up = np.full_like(RsiMa2, fill_value=np.nan) qqe_down = np.full_like(RsiMa2, fill_value=np.nan) qqe_up = np.where(qqe_up_cond, RsiMa2 - 50, np.nan) qqe_down = np.where(qqe_down_cond, RsiMa2 - 50, np.nan) return qqe_up, qqe_down ``` -------------------------------- ### Track Zero Line Crossings with Python Source: https://context7.com/edyatl/qqe-mod/llms.txt Calculates the duration of bullish and bearish momentum by tracking consecutive bars where the RSI index remains above or below the 50 level. It returns two arrays representing the count of consecutive bars for each state. ```python import pandas as pd import numpy as np def zero_cross(src: pd.Series, RSIndex: np.ndarray, CONST50: int) -> tuple: QQEzlong = np.zeros_like(src, dtype=int) QQEzshort = np.zeros_like(src, dtype=int) for i in range(1, len(src)): QQEzlong[i] = QQEzlong[i - 1] QQEzshort[i] = QQEzshort[i - 1] QQEzlong[i] = QQEzlong[i] + 1 if RSIndex[i] >= CONST50 else 0 QQEzshort[i] = QQEzshort[i] + 1 if RSIndex[i] < CONST50 else 0 return QQEzlong, QQEzshort ``` -------------------------------- ### Zero Cross Detection for QQE Indicator Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb A Python function designed to detect zero crosses for the QQE indicator. It initializes arrays for short and long zero crosses and iterates through the data to identify these crossing points. ```python def zero_cross(src: pd.Series, RSIndex: np.ndarray, CONST50: int) -> tuple: QQEzlong: np.ndarray = np.zeros_like(src, dtype=int) QQEzshort: np.ndarray = np.zeros_like(src, dtype=int) for i in range(1, len(src)): ``` -------------------------------- ### Indicator Band Calculation Logic Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb This Python code implements the logic for updating `longband` and `shortband` based on comparisons between `RSIndex`, `longband`, `shortband`, `newlongband`, and `newshortband`. It iterates through the series, applying conditional updates to maintain band values. ```python for i in range(1, len(src)): if RSIndex[i - 1] > longband[i - 1] and RSIndex[i] > longband[i - 1]: longband[i] = max(longband[i - 1], newlongband[i]) else: longband[i] = newlongband[i] if RSIndex[i - 1] < shortband[i - 1] and RSIndex[i] < shortband[i - 1]: shortband[i] = min(shortband[i - 1], newshortband[i]) else: shortband[i] = newshortband[i] # long_cond = (RSIndex[:-1] > longband[:-1]) & (RSIndex[1:] > longband[:-1]) # longband[long_cond] = np.maximum(longband[long_cond], newlongband[long_cond]) # longband[~long_cond] = newlongband[~long_cond] # short_cond = (RSIndex[:-1] < shortband[:-1]) & (RSIndex[1:] < shortband[:-1]) # shortband[short_cond] = np.minimum(shortband[short_cond], newshortband[short_cond]) ``` -------------------------------- ### Process Klines Data into Pandas DataFrame Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb Converts the fetched klines data into a pandas DataFrame and parses the 'open_time' and 'close_time' columns into datetime objects. Displays the last 5 rows of the processed data. ```python data = pd.DataFrame(klines, columns=short_col_names) data["open_time"] = pd.to_datetime(data["open_time"], unit="ms") data["close_time"] = pd.to_datetime(data["close_time"], unit="ms") data.tail(5) ``` -------------------------------- ### Pandas Series Generation and Display Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb This Python code snippet generates two pandas Series, `x` and `y`, filled with random numbers between 0 and 1. It then displays the content of each Series. ```python x = pd.Series(np.random.rand(10)) x ``` ```python y = pd.Series(np.random.rand(10)) y ``` -------------------------------- ### QQE MOD Indicator Pine Script Source: https://github.com/edyatl/qqe-mod/blob/master/README.md The core implementation of the QQE MOD indicator in Pine Script. It calculates two sets of QQE trendlines, applies Bollinger Bands for volatility filtering, and plots visual signals when both trendlines align. ```Pine Script //@version=4 study("QQE MOD") RSI_Period = input(6, title='RSI Length') SF = input(5, title='RSI Smoothing') QQE = input(3, title='Fast QQE Factor') ThreshHold = input(3, title="Thresh-hold") src = input(close, title="RSI Source") Wilders_Period = RSI_Period * 2 - 1 Rsi = rsi(src, RSI_Period) RsiMa = ema(Rsi, SF) AtrRsi = abs(RsiMa[1] - RsiMa) MaAtrRsi = ema(AtrRsi, Wilders_Period) dar = ema(MaAtrRsi, Wilders_Period) * QQE longband = 0.0 shortband = 0.0 trend = 0 DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband cross_1 = cross(longband[1], RSIndex) trend := cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1) FastAtrRsiTL = trend == 1 ? longband : shortband length = input(50, minval=1, title="Bollinger Length") mult = input(0.35, minval=0.001, maxval=5, step=0.1, title="BB Multiplier") basis = sma(FastAtrRsiTL - 50, length) dev = mult * stdev(FastAtrRsiTL - 50, length) upper = basis + dev lower = basis - dev color_bar = RsiMa - 50 > upper ? #00c3ff : RsiMa - 50 < lower ? #ff0062 : color.gray ``` -------------------------------- ### Display Last 10 Redbar2 Values (Python) Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_draft.ipynb Displays the last 10 boolean values of a pandas Series named 'Redbar2'. This series likely indicates whether a 'red bar' condition is met based on the 'lower' Bollinger Band threshold. ```python pd.Series(Redbar2).tail(10) ``` -------------------------------- ### QQE Cross Detection Source: https://github.com/edyatl/qqe-mod/blob/master/qqe_mod_clear.ipynb A utility function to detect when two pandas Series have crossed each other. ```APIDOC ## POST /api/qqe/cross ### Description Detects when two pandas Series have crossed each other. This is a fundamental operation used within the QQE indicator to identify trend changes. ### Method POST ### Endpoint /api/qqe/cross ### Parameters #### Request Body - **x** (pd.Series) - Required - The first pandas Series. - **y** (pd.Series) - Required - The second pandas Series. ### Request Example ```json { "x": [10, 12, 15, 13, 11], "y": [11, 13, 14, 14, 12] } ``` ### Response #### Success Response (200) - **crosses** (pd.Series) - A boolean Series indicating where the Series x and y have crossed. #### Response Example ```json { "crosses": [false, false, true, false, true] } ``` ```