### Complex Trading Strategy with Multiple Indicators (Python) Source: https://context7.com/mpquant/mytt/llms.txt This example illustrates a comprehensive trading strategy that combines multiple technical indicators for robust decision-making. It calculates various indicators including Moving Averages, Bollinger Bands (BOLL), RSI, MACD, and ATR. The strategy defines multi-condition buy and sell signals based on crossovers, price levels, indicator values, and includes risk management parameters like stop-loss and take-profit levels derived from ATR. ```python from MyTT import * import numpy as np # Generate sample data (in practice, load real market data) CLOSE = np.random.uniform(95, 105, 120) HIGH = CLOSE + np.random.uniform(0, 2, 120) LOW = CLOSE - np.random.uniform(0, 2, 120) VOL = np.random.uniform(1e8, 1e9, 120) # Calculate multiple indicators MA5 = MA(CLOSE, 5) MA10 = MA(CLOSE, 10) MA20 = MA(CLOSE, 20) UPPER, MID, LOWER = BOLL(CLOSE, N=20, P=2) rsi = RSI(CLOSE, N=14) DIF, DEA, MACD_val = MACD(CLOSE) atr = ATR(CLOSE, HIGH, LOW, N=14) # Multi-condition buy signal buy_signal = ( RET(CROSS(MA5, MA10)) and # MA5 crosses above MA10 CLOSE[-1] > RET(MA20) and # Price above MA20 RET(rsi) < 70 and RET(rsi) > 50 and # RSI in bullish zone RET(MACD_val) > 0 and # MACD positive CLOSE[-1] > RET(MID) # Price above BB middle ) # Multi-condition sell signal sell_signal = ( RET(CROSS(MA10, MA5)) and # MA10 crosses above MA5 CLOSE[-1] < RET(MA20) and # Price below MA20 RET(rsi) > 30 and RET(rsi) < 50 and # RSI in bearish zone RET(MACD_val) < 0 # MACD negative ) # Risk management stop_loss_distance = RET(atr) * 2 if buy_signal: entry_price = CLOSE[-1] stop_loss = entry_price - stop_loss_distance take_profit = entry_price + (stop_loss_distance * 2) print(f"BUY SIGNAL at {entry_price:.2f}") print(f"Stop Loss: {stop_loss:.2f}") print(f"Take Profit: {take_profit:.2f}") elif sell_signal: print("SELL SIGNAL - Close positions") else: print("No clear signal - Hold position") ``` -------------------------------- ### Calculate MACD and Generate Trading Signals (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates the MACD (Moving Average Convergence Divergence) indicator and generates buy/sell signals based on its values and crossovers with its signal line. It uses the RET function to get the latest values and CROSS to detect crossovers. This snippet assumes the availability of DIF, DEA, and MACD values. ```Python latest_dif = RET(DIF) latest_dea = RET(DEA) latest_macd = RET(MACD) print(f"DIF: {latest_dif:.2f}") print(f"DEA: {latest_dea:.2f}") print(f"MACD: {latest_macd:.2f}") # Trading signal if latest_macd > 0 and RET(CROSS(DIF, DEA)): print("MACD bullish crossover - Buy signal") elif latest_macd < 0 and RET(CROSS(DEA, DIF)): print("MACD bearish crossover - Sell signal") ``` -------------------------------- ### Integrate Huobi API for Crypto Data and Technical Analysis (Python) Source: https://context7.com/mpquant/mytt/llms.txt This snippet demonstrates integrating the Huobi API to fetch historical cryptocurrency price data and then applying technical indicators from MyTT. It shows how to retrieve daily OHLCV data for BTC, calculate Moving Averages (MA) and MACD, and identify trading signals like golden crosses and sustained trends. ```python from hb_hq_api import * from MyTT import * # Get 120 days of BTC daily data df = get_price('btc.usdt', count=120, frequency='1d') # Extract OHLCV arrays CLOSE = df.close.values OPEN = df.open.values HIGH = df.high.values LOW = df.low.values VOL = df.vol.values # Calculate indicators MA5 = MA(CLOSE, 5) MA10 = MA(CLOSE, 10) DIF, DEA, MACD = MACD(CLOSE) print(f"BTC Last Price: {CLOSE[-1]:.2f}") print(f"MA5: {MA5[-1]:.2f}") print(f"MA10: {MA10[-1]:.2f}") # Check for golden cross if RET(CROSS(MA5, MA10)): print("Golden Cross detected on BTC!") # Check if last 5 days all above MA10 if EVERY(CLOSE > MA10, 5): print("BTC sustained above MA10 for 5 days - Strong trend") ``` -------------------------------- ### Calculate Simple Moving Average (MA) - Python Source: https://context7.com/mpquant/mytt/llms.txt Calculates the simple moving average (MA) for a given period. It takes closing prices as input and returns a series of MA values. This is useful for trend identification and support/resistance levels. ```Python from MyTT import * import numpy as np # Sample closing prices for 20 days CLOSE = np.array([100, 102, 105, 103, 107, 110, 108, 112, 115, 113, 116, 119, 117, 120, 122, 121, 124, 126, 125, 128]) # Calculate 5-day and 10-day moving averages MA5 = MA(CLOSE, 5) MA10 = MA(CLOSE, 10) print(f"Latest 5-day MA: {MA5[-1]:.2f}") # Output: Latest 5-day MA: 124.80 print(f"Latest 10-day MA: {MA10[-1]:.2f}") # Output: Latest 10-day MA: 120.70 ``` -------------------------------- ### Calculate Bollinger Bands (BOLL) (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates Bollinger Bands, which consist of an upper band, middle band (simple moving average), and lower band. These bands are used to measure volatility and identify potential price reversals. The function requires closing prices and parameters for the period (N) and standard deviations (P). Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 105, 103, 107, 110, 108, 112, 115, 113, 116, 119, 117, 120, 122, 121, 124, 126, 125, 128]) # Calculate Bollinger Bands (20-period, 2 standard deviations) UPPER, MID, LOWER = BOLL(CLOSE, N=20, P=2) current_price = CLOSE[-1] upper_band = RET(UPPER) mid_band = RET(MID) lower_band = RET(LOWER) print(f"Price: {current_price:.2f}") print(f"Upper Band: {upper_band:.2f}") print(f"Middle Band: {mid_band:.2f}") print(f"Lower Band: {lower_band:.2f}") # Trading signals if current_price >= upper_band: print("Price at upper band - Potential overbought") elif current_price <= lower_band: print("Price at lower band - Potential oversold") ``` -------------------------------- ### Retrieve Previous Values (REF) - Python Source: https://context7.com/mpquant/mytt/llms.txt Retrieves historical data points from a specified number of periods ago. This function is essential for calculating changes, returns, and comparing current values with past values. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 105, 103, 107, 110, 108, 112, 115, 113]) # Get yesterday's closing price yesterday = REF(CLOSE, 1) # Get price from 5 days ago five_days_ago = REF(CLOSE, 5) # Calculate daily returns daily_return = (CLOSE - REF(CLOSE, 1)) / REF(CLOSE, 1) * 100 print(f"Today's close: {CLOSE[-1]}") # Output: Today's close: 113 print(f"Yesterday: {yesterday[-1]}") # Output: Yesterday: 115 print(f"Daily return: {daily_return[-1]:.2f}%") # Output: Daily return: -1.74% ``` -------------------------------- ### Calculate KDJ Indicator and Trading Signals (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates the KDJ oscillator (Stochastic oscillator) which indicates momentum and overbought/oversold conditions. It takes closing, high, and low prices as input and outputs K, D, and J lines. Trading signals are generated based on the levels of K and D, and their crossovers. Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np # Sample OHLC data for 30 days CLOSE = np.random.uniform(95, 105, 30) HIGH = CLOSE + np.random.uniform(0, 3, 30) LOW = CLOSE - np.random.uniform(0, 3, 30) # Calculate KDJ with standard parameters K, D, J = KDJ(CLOSE, HIGH, LOW, N=9, M1=3, M2=3) k_val = RET(K) d_val = RET(D) j_val = RET(J) print(f"K: {k_val:.2f}, D: {d_val:.2f}, J: {j_val:.2f}") # Trading signals if k_val < 20 and d_val < 20: print("Oversold - Potential buy signal") elif k_val > 80 and d_val > 80: print("Overbought - Potential sell signal") elif RET(CROSS(K, D)) and k_val < 50: print("K crosses above D in lower zone - Buy signal") ``` -------------------------------- ### Calculate HHV and LLV (Highest/Lowest Values) (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates the Highest High Value (HHV) and Lowest Low Value (LLV) over a specified period (N). These are useful for identifying potential support and resistance levels. The function takes a price series and the period as input. Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 105, 103, 107, 110, 108, 112, 115, 113, 116, 119, 117, 120, 122, 121, 124, 126, 125, 128]) # Highest close in last 20 days highest_20 = HHV(CLOSE, 20) # Lowest close in last 20 days lowest_20 = LLV(CLOSE, 20) print(f"20-day highest: {RET(highest_20):.2f}") print(f"20-day lowest: {RET(lowest_20):.2f}") # Check if current price is at new high if CLOSE[-1] == RET(highest_20): print("Price at 20-day high - Strong bullish momentum") elif CLOSE[-1] == RET(lowest_20): print("Price at 20-day low - Strong bearish momentum") ``` -------------------------------- ### Check EVERY Condition (Python) Source: https://context7.com/mpquant/mytt/llms.txt Checks if a given condition has been true for all of the last N periods. This is useful for confirming sustained trends or patterns. The function takes a boolean condition and the number of periods (N) as input. Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 105, 107, 110, 112, 115, 118, 120, 123]) OPEN = np.array([99, 101, 104, 106, 109, 111, 114, 117, 119, 122]) # Check if all last 5 days were bullish all_bullish = EVERY(CLOSE > OPEN, 5) # Check if price stayed above MA10 for last 5 days MA10 = MA(CLOSE, 10) above_ma = EVERY(CLOSE > MA10, 5) if RET(all_bullish): print("All last 5 days were bullish - Strong uptrend") if RET(above_ma): print("Price above MA10 for 5 days - Confirmed uptrend") ``` -------------------------------- ### Detect Crossovers (CROSS) - Python Source: https://context7.com/mpquant/mytt/llms.txt Detects when one data series crosses above or below another. This is commonly used to identify golden crosses (bullish) and death crosses (bearish) between moving averages. It returns a boolean series indicating the crossover event. ```Python from MyTT import * import numpy as np # Sample price data CLOSE = np.array([100, 102, 98, 95, 93, 96, 99, 103, 107, 110, 112, 115, 118, 116, 119, 122, 125, 127, 124, 128]) MA5 = MA(CLOSE, 5) MA10 = MA(CLOSE, 10) # Detect golden cross (MA5 crosses above MA10) golden_cross = CROSS(MA5, MA10) # Detect death cross (MA10 crosses above MA5) death_cross = CROSS(MA10, MA5) # Get today's signal if RET(golden_cross): print("Golden Cross detected - Bullish signal") elif RET(death_cross): print("Death Cross detected - Bearish signal") else: print("No cross signal today") ``` -------------------------------- ### Calculate Tang An Qi Channel / Donchian Channel (Python) Source: https://context7.com/mpquant/mytt/llms.txt The TAQ function calculates the Tang An Qi Channel, also known as the Donchian Channel or Turtle Trading indicator. It identifies breakout levels based on the highest high and lowest low over a specified period. The function returns the upper band, middle band, and lower band of the channel. ```python from MyTT import * import numpy as np HIGH = np.array([102, 105, 108, 110, 107, 109, 112, 115, 118, 120, 119, 122, 125, 123, 126, 129, 127, 130, 133, 135]) LOW = np.array([98, 100, 103, 105, 102, 104, 107, 110, 113, 115, 114, 117, 120, 118, 121, 124, 122, 125, 128, 130]) CLOSE = np.array([100, 103, 106, 108, 105, 107, 110, 113, 116, 118, 117, 120, 123, 121, 124, 127, 125, 128, 131, 133]) # Calculate 20-period Donchian Channel UP, MID, DOWN = TAQ(HIGH, LOW, 20) upper_channel = RET(UP) mid_channel = RET(MID) lower_channel = RET(DOWN) print(f"Upper Channel: {upper_channel:.2f}") print(f"Mid Channel: {mid_channel:.2f}") print(f"Lower Channel: {lower_channel:.2f}") # Turtle Trading signals if CLOSE[-1] > RET(UP): print("Breakout above upper channel - Long entry signal") elif CLOSE[-1] < RET(DOWN): print("Breakdown below lower channel - Short entry signal") ``` -------------------------------- ### Calculate RSI Indicator and Trading Signals (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates the Relative Strength Index (RSI), a momentum oscillator measuring the speed and change of price movements. It evaluates overbought or oversold conditions. The function takes closing prices as input and returns the RSI value. Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 101, 103, 105, 104, 106, 108, 107, 110, 112, 111, 113, 115, 114, 116, 118, 117, 119, 121, 120, 122, 124, 123, 125]) # Calculate 14-period RSI rsi = RSI(CLOSE, N=14) rsi_value = RET(rsi) print(f"RSI(14): {rsi_value:.2f}") if rsi_value > 70: print("Overbought - Consider selling") elif rsi_value < 30: print("Oversold - Consider buying") else: print("Neutral zone") ``` -------------------------------- ### Calculate Exponential Moving Average (EMA) - Python Source: https://context7.com/mpquant/mytt/llms.txt Calculates the exponential moving average (EMA), which gives more weight to recent prices. Requires a significant number of periods (e.g., 120+) for accurate results. It accepts price data and returns EMA series. ```Python from MyTT import * import numpy as np # Generate sample data (requires 120+ periods for precision) CLOSE = np.random.uniform(90, 110, 150) # Calculate 12-period and 26-period EMA EMA12 = EMA(CLOSE, 12) EMA26 = EMA(CLOSE, 26) print(f"Latest 12-period EMA: {EMA12[-1]:.2f}") print(f"Latest 26-period EMA: {EMA26[-1]:.2f}") ``` -------------------------------- ### Calculate ATR (Average True Range) (Python) Source: https://context7.com/mpquant/mytt/llms.txt Calculates the Average True Range (ATR), a measure of market volatility. It averages the 'true range' over a specified number of periods (N). The function requires closing, high, and low prices. This snippet also demonstrates using ATR to calculate stop-loss levels for long and short positions. Requires MyTT and NumPy libraries. ```Python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 98, 95, 93, 96, 99, 103, 107, 110, 112, 115, 111, 108, 105, 109, 113, 116, 119, 122]) HIGH = CLOSE + np.random.uniform(1, 3, 20) LOW = CLOSE - np.random.uniform(1, 3, 20) # Calculate 14-period ATR atr = ATR(CLOSE, HIGH, LOW, N=14) atr_value = RET(atr) print(f"ATR(14): {atr_value:.2f}") # Use ATR for stop-loss placement stop_loss_multiplier = 2 long_stop_loss = CLOSE[-1] - (atr_value * stop_loss_multiplier) short_stop_loss = CLOSE[-1] + (atr_value * stop_loss_multiplier) print(f"Long position stop-loss: {long_stop_loss:.2f}") print(f"Short position stop-loss: {short_stop_loss:.2f}") ``` -------------------------------- ### Calculate Bars Since Last True Condition (Python) Source: https://context7.com/mpquant/mytt/llms.txt The BARSLAST function returns the number of periods since a specified condition was last met. This is useful for timing analysis, such as identifying how many periods have passed since a significant price movement. It requires a boolean condition as input and returns an integer. ```python from MyTT import * import numpy as np CLOSE = np.array([100, 102, 105, 110, 108, 106, 109, 112, 115, 118]) # Days since last 10% single-day gain days_since_rally = BARSLAST(CLOSE / REF(CLOSE, 1) >= 1.10) # Days since last 5% drop days_since_drop = BARSLAST(CLOSE / REF(CLOSE, 1) <= 0.95) print(f"Days since last 10% rally: {RET(days_since_rally)}") print(f"Days since last 5% drop: {RET(days_since_drop)}") ``` -------------------------------- ### Calculate MACD Indicator - Python Source: https://context7.com/mpquant/mytt/llms.txt Calculates the Moving Average Convergence Divergence (MACD) indicator. This momentum oscillator shows the relationship between two exponential moving averages. Requires a substantial amount of historical data for accurate EMA calculations. ```Python from MyTT import * import numpy as np # Requires 120+ periods for accurate EMA calculation CLOSE = np.random.uniform(90, 110, 120) # Calculate MACD with standard parameters (12, 26, 9) DIF, DEA, MACD = MACD(CLOSE, SHORT=12, LONG=26, M=9) ``` -------------------------------- ### Count Conditional Occurrences (COUNT) - Python Source: https://context7.com/mpquant/mytt/llms.txt Counts the number of times a specified condition is met within a given number of preceding periods. It takes a boolean condition and a period length as input, returning the count. ```Python from MyTT import * import numpy as np OPEN = np.array([100, 101, 103, 102, 106, 108, 107, 111, 114, 112]) CLOSE = np.array([102, 103, 102, 104, 107, 109, 108, 112, 115, 113]) # Count how many bullish days (close > open) in last 10 days bullish_days = COUNT(CLOSE > OPEN, 10) # Check last 5 days recent_bullish = RET(COUNT(CLOSE > OPEN, 5)) print(f"Bullish days in last 10 periods: {RET(bullish_days)}") print(f"Bullish days in last 5 periods: {recent_bullish}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.