Bitcoin Futures vs. Spot Tri-Frame - Strategy [presentTrading]Prove idea with a backtest is always true for trading.
I developed and open-sourced it as an educational material for crypto traders to understand that the futures and spot spread may be effective but not be as effective as they might think. It serves as an indicator of sentiment rather than a reliable predictor of market trends over certain periods. It is better suited for specific trading environments, which require further research.
█ Introduction and How it is Different
The "Bitcoin Futures vs. Spot Tri-Frame Strategy" utilizes three different timeframes to calculate the Z-Score of the spread between BTC futures and spot prices on Binance and OKX exchanges. The strategy executes long or short trades based on composite Z-Score conditions across the three timeframes.
The spread refers to the difference in price between BTC futures and BTC spot prices, calculated by taking a weighted average of futures prices from multiple exchanges (Binance and OKX) and subtracting a weighted average of spot prices from the same exchanges.
BTCUSD 1D L/S Performance
█ Strategy, How It Works: Detailed Explanation
🔶 Calculation of the Spread
The spread is the difference in price between BTC futures and BTC spot prices. The strategy calculates the spread by taking a weighted average of futures prices from multiple exchanges (Binance and OKX) and subtracting a weighted average of spot prices from the same exchanges. This spread serves as the primary metric for identifying trading opportunities.
Spread = Weighted Average Futures Price - Weighted Average Spot Price
🔶 Z-Score Calculation
The Z-Score measures how many standard deviations the current spread is from its historical mean. This is calculated for each timeframe as follows:
Spread Mean_tf = SMA(Spread_tf, longTermSMA)
Spread StdDev_tf = STDEV(Spread_tf, longTermSMA)
Z-Score_tf = (Spread_tf - Spread Mean_tf) / Spread StdDev_tf
Local performance
🔶 Composite Entry Conditions
The strategy triggers long and short entries based on composite Z-Score conditions across all three timeframes:
- Long Condition: All three Z-Scores must be greater than the long entry threshold.
Long Condition = (Z-Score_tf1 > zScoreLongEntryThreshold) and (Z-Score_tf2 > zScoreLongEntryThreshold) and (Z-Score_tf3 > zScoreLongEntryThreshold)
- Short Condition: All three Z-Scores must be less than the short entry threshold.
Short Condition = (Z-Score_tf1 < zScoreShortEntryThreshold) and (Z-Score_tf2 < zScoreShortEntryThreshold) and (Z-Score_tf3 < zScoreShortEntryThreshold)
█ Trade Direction
The strategy allows the user to specify the trading direction:
- Long: Only long trades are executed.
- Short: Only short trades are executed.
- Both: Both long and short trades are executed based on the Z-Score conditions.
█ Usage
The strategy can be applied to BTC or Crypto trading on major exchanges like Binance and OKX. By leveraging discrepancies between futures and spot prices, traders can exploit market inefficiencies. This strategy is suitable for traders who prefer a statistical approach and want to diversify their timeframes to validate signals.
█ Default Settings
- Input TF 1 (60 minutes): Sets the first timeframe for Z-Score calculation.
- Input TF 2 (120 minutes): Sets the second timeframe for Z-Score calculation.
- Input TF 3 (180 minutes): Sets the third timeframe for Z-Score calculation.
- Long Entry Z-Score Threshold (3): Defines the threshold above which a long trade is triggered.
- Short Entry Z-Score Threshold (-3): Defines the threshold below which a short trade is triggered.
- Long-Term SMA Period (100): The period used to calculate the simple moving average for the spread.
- Use Hold Days (true): Enables holding trades for a specified number of days.
- Hold Days (5): Number of days to hold the trade before exiting.
- TPSL Condition (None): Defines the conditions for taking profit and stop loss.
- Take Profit (%) (30.0): The percentage at which the trade will take profit.
- Stop Loss (%) (20.0): The percentage at which the trade will stop loss.
By fine-tuning these settings, traders can optimize the strategy to suit their risk tolerance and trading style, enhancing overall performance.
Indicadores e estratégias
Double Vegas SuperTrend Enhanced - Strategy [presentTrading]
█ Introduction and How It Is Different
The "Double Vegas SuperTrend Enhanced" strategy is a sophisticated trading system that combines two Vegas SuperTrend Enhanced. Very Powerful!
Let's celebrate the joy of Children's Day on June 1st! Enjoyyy!
BTCUSD LS performance
The strategy aims to pinpoint market trends with greater accuracy and generate trades that align with the overall market direction.
This approach differentiates itself by integrating volatility adjustments and leveraging the Vegas Channel's width to refine the SuperTrend calculations, resulting in a dynamic and responsive trading system.
Additionally, the strategy incorporates customizable take-profit and stop-loss levels, providing traders with a robust framework for risk management.
-> check Vegas SuperTrend Enhanced - Strategy
█ Strategy, How It Works: Detailed Explanation
🔶 Vegas Channel and SuperTrend Calculations
The strategy initiates by calculating the Vegas Channel, which is derived from a simple moving average (SMA) and the standard deviation (STD) of the closing prices over a specified window length. This channel helps in measuring market volatility and forms the basis for adjusting the SuperTrend indicator.
Vegas Channel Calculation:
- vegasMovingAverage = SMA(close, vegasWindow)
- vegasChannelStdDev = STD(close, vegasWindow)
- vegasChannelUpper = vegasMovingAverage + vegasChannelStdDev
- vegasChannelLower = vegasMovingAverage - vegasChannelStdDev
SuperTrend Multiplier Adjustment:
- channelVolatilityWidth = vegasChannelUpper - vegasChannelLower
- adjustedMultiplier = superTrendMultiplierBase + volatilityAdjustmentFactor * (channelVolatilityWidth / vegasMovingAverage)
The adjusted multiplier enhances the SuperTrend's sensitivity to market volatility, making it more adaptable to changing market conditions.
BTCUSD Local picture.
🔶 Average True Range (ATR) and SuperTrend Values
The ATR is computed over a specified period to measure market volatility. Using the ATR and the adjusted multiplier, the SuperTrend upper and lower levels are determined.
ATR Calculation:
- averageTrueRange = ATR(atrPeriod)
**SuperTrend Calculation:**
- superTrendUpper = hlc3 - (adjustedMultiplier * averageTrueRange)
- superTrendLower = hlc3 + (adjustedMultiplier * averageTrueRange)
The SuperTrend levels are continuously updated based on the previous values and the current market trend direction. The market trend is determined by comparing the closing prices with the SuperTrend levels.
Trend Direction:
- If close > superTrendLowerPrev, then marketTrend = 1 (bullish)
- If close < superTrendUpperPrev, then marketTrend = -1 (bearish)
🔶 Trade Entry and Exit Conditions
The strategy generates trade signals based on the alignment of both SuperTrends. Trades are executed only when both SuperTrends indicate the same market direction.
Entry Conditions:
- Long Position: Both SuperTrends must signal a bullish trend.
- Short Position: Both SuperTrends must signal a bearish trend.
Exit Conditions:
- Positions are exited if either SuperTrend reverses its trend direction.
- Additional conditions include holding periods and configurable take-profit and stop-loss levels.
█ Trade Direction
The strategy allows traders to specify the desired trade direction through a customizable input setting. Options include:
- Long: Only enter long positions.
- Short: Only enter short positions.
- Both: Enter both long and short positions based on the market conditions.
█ Usage
To utilize the "Double Vegas SuperTrend Enhanced" strategy, traders need to configure the input settings according to their trading preferences and market conditions. The strategy includes parameters for ATR periods, Vegas Channel window lengths, SuperTrend multipliers, volatility adjustment factors, and risk management settings such as hold days, take-profit, and stop-loss percentages.
█ Default Settings
The strategy comes with default settings that can be adjusted to fit individual trading styles:
- trade Direction: Both (allows trading in both long and short directions for maximum flexibility).
- ATR Periods: 10 for SuperTrend 1 and 5 for SuperTrend 2 (shorter ATR period results in more sensitivity to recent price movements).
- Vegas Window Lengths: 100 for SuperTrend 1 and 200 for SuperTrend 2 (longer window length results in smoother moving averages and less sensitivity to short-term volatility).
- SuperTrend Multipliers: 5 for SuperTrend 1 and 7 for SuperTrend 2 (higher multipliers lead to wider SuperTrend channels, reducing the frequency of trades).
- Volatility Adjustment Factors: 5 for SuperTrend 1 and 7 for SuperTrend 2 (higher adjustment factors increase the responsiveness to changes in market volatility).
- Hold Days: 5 (defines the minimum duration a position is held, ensuring trades are not exited prematurely).
- Take Profit: 30% (sets the target profit level to lock in gains).
- Stop Loss: 20% (sets the maximum acceptable loss level to mitigate risk).
Mateo's Time of Day Analysis LEThis strategy takes a trade every day at a specified time and then closes it at a specified time.
The purpose of this strategy is to help determine if there are better times to day to buy or sell.
I was originally inspired to write this when a YouTuber stated that SPX had been up during the last 30 minutes of the day over 80% of the time the past year. No matter who says it, test it, and in my opinion, TradingView is one of the easiest placed to do that! Unfortunately, that particular claim did not turn out to be accurate, but this tool remains for those who want to optimize timing their entries and exits at specific times of day.
market slayerInput Parameters:
Various input parameters allow customization of the strategy, including options to show trend confirmation, specify trend timeframes and values, set SMA lengths, enable take profit and stop loss, and define their respective values.
Calculations:
Simple Moving Averages (SMAs) are calculated based on the specified lengths.
Buy and sell signals are generated based on the crossover and crossunder of the short and long SMAs.
Confirmation Bars:
Functions are defined to determine bullish or bearish confirmation bars based on certain conditions.
These confirmation bars are used to confirm trend direction and generate additional signals.
Plotting:
SMAs are plotted on the chart.
Trend labels and signal markers are plotted based on the calculated conditions.
Trade Signals:
Buy and sell conditions are defined based on the crossover/crossunder of SMAs and confirmation of trend direction.
Strategy entries and exits are executed accordingly.
Take Profit and Stop Loss:
Optional take profit and stop loss functionality is included.
Trades are automatically closed when profit or loss thresholds are reached.
Closing Trades:
Trades are also closed based on changes in trend confirmation bars to ensure alignment with the overall market direction.
Alerts:
Alert conditions are defined for opening and closing trades, providing notifications when certain conditions are met.
Overall, this script aims to provide a systematic approach to trading by combining moving average crossovers with trend confirmation bars, along with options for risk management through take profit and stop loss orders. Users can customize various parameters to adapt the strategy to different market conditions and trading preferences.
The script uses the request.security() function with the lookahead parameter set to barmerge.lookahead_on to access data from a higher timeframe within the Pine Script on TradingView. Let's break down why it's used:
Higher Timeframe Analysis:
By default, Pine Script operates on the timeframe of the chart it's applied to. However, in trading strategies, it's common to incorporate signals or data from higher timeframes to confirm or validate signals generated on lower timeframes. This helps traders to align their trades with the broader market trend.
Trend Confirmation:
In this script, the confirmationTrendTimeframe parameter allows users to specify a higher timeframe for trend confirmation. The request.security() function fetches the data from this higher timeframe and applies the defined conditions to confirm the trend direction.
Lookahead Behavior:
The lookahead parameter set to barmerge.lookahead_on ensures that the script considers the most up-to-date information available on the higher timeframe when making trading decisions on the lower timeframe. This prevents the script from lagging behind or using outdated data, enhancing the accuracy of trend confirmation.
Usage in confirmationTrendBullish and confirmationTrendBearish:
These variables are assigned the values returned by the request.security() function, which represents the bullish or bearish trend confirmation based on the conditions applied to the data from the higher timeframe.
Entry Fragger - Strategy
For basic instructions please visit my other script "Entry Fragger".
The Signal Logic is explained there.
v1.4:
- Added advanced backtesting with fully customizable entries.
- Fully automated Buy Signals (profitable).
- Adjustable timeframes for signal logic. (requested)
Every setting affects the accuracy and profitability greatly now, based on settings applied.
The strategy performs best on high timeframes with larger capital and no leverage.
Useless for Forex, but absolutely smashes stocks and crypto on mid to high timeframes.
Please read through my other scripts description.
Set values as preferred and try your assets.
It does NOT work on low timeframes and forex!
Hint: BTC 4H, Custom Timeframe 1h, Moon Mode and Show Sell Signals enabled, R2R: 2.
KumoTrade Ichimoku StrategyThe KumoTrade Ichimoku Strategy is an advanced trading strategy designed to help users identify market trends and potential trading opportunities using the Ichimoku Kinko Hyo technical analysis indicator. This strategy leverages the Ichimoku cloud (Kumo) along with other crucial indicators such as the Tenkan-sen and Kijun-sen lines to generate strong signals.
Main Components of the Strategy:
Tenkan-sen (Conversion Line): Indicates the short-term direction of the price, typically calculated as the average of the highest high and the lowest low over the past 9 periods.
Kijun-sen (Base Line): Indicates the medium-term direction of the price, usually calculated as the average of the highest high and the lowest low over the past 26 periods.
Senkou Span A and Senkou Span B: These two lines form the cloud (Kumo), which projects future support and resistance levels.
Chikou Span (Lagging Span): Plots the current closing price 26 periods back to measure the market's momentum.
Strategy Rules:
Bullish Bias (Bias Bull): Indicates that the prices are in a long-term uptrend. In this strategy, this is confirmed if the low prices are above the daily EMA (Exponential Moving Average).
Kijun Sen Touch Down: Occurs when prices cross below the Kijun-sen line and then close back above it, indicating a potential bullish reversal.
Tenkan-Kijun Cross Up: A bullish signal generated when the Tenkan-sen line crosses above the Kijun-sen line.
Close Over Tenkan and Kijun: A strong bullish signal when the close price crosses above both the Tenkan-sen and Kijun-sen lines.
Trading Setups:
Long Setup: Generated when the Kijun-sen is above the highest point of the Kumo (senkou_max) and the closing price is below the lowest point of the Kumo (senkou_min). This setup is checked over the last 21 bars.
Short Setup: Generated when the Kijun-sen is below the lowest point of the Kumo (senkou_min) and the closing price is above the highest point of the Kumo (senkou_max). This setup is also checked over the last 21 bars. (Not avalible yet)
Entry Conditions:
Ultra Long Entry: This condition checks for a bullish bias, the Tenkan-Kijun cross up or Kijun Sen touch down, high volume, and that the price is not within the Kumo cloud.
Main Long Entry: This condition requires the closing price to be above the Kumo cloud, a green Kumo cloud, a bullish bias, the Tenkan rule, and that the price is not within the Kumo cloud.
Exit Conditions:
A trailing stop loss is implemented to protect profits. The stop loss level is dynamically updated based on the highest high of the last 5 bars minus three times the ATR (Average True Range) value.
Visuals on the Chart:
The Tenkan-sen and Kijun-sen lines are plotted for visual reference.
The Kumo cloud is displayed with different colors indicating bullish (green) or bearish (red) conditions.
Entry points are marked on the chart, and the trailing stop loss levels are plotted as well.
The KumoTrade Ichimoku Strategy aims to provide a comprehensive approach to trading by combining multiple aspects of the Ichimoku indicator to generate reliable trading signals and manage risk effectively.
Korneev Reverse RSIRethinking the Legendary Relative Strength Index by John Welles Wilder
The essence of the new approach lies in the reverse use of the so-called "overbought" and "oversold" zones. In his 1978 book, "New Concepts in Technical Trading Systems," where the RSI mechanism was thoroughly described, Wilder writes that one way to use the oscillator is to open a long position when the RSI drops into oversold territory (below 30) and to open a short position when the RSI rises to overbought levels (above 70). However, backtesting this strategy with such inputs yields rather mediocre results.
Based on the calculation formula, the RSI calculates the rate of price change over a certain period. Therefore, overbought and oversold zones will have relative significance (relative to the set calculation period). It is no coincidence that the word "relative" was added to the name of the oscillator. It is worth accepting as an axiom the assertion that the price of an asset is fair at every moment in time.
Essentially, the RSI calculates the strength of a trend. If the oscillator value is above 70, it is highly likely that an upward movement is occurring in the market. Therefore, in the current strategy, a long position is opened precisely at the moment of greatest buyer strength (when RSI > 80), i.e., in the direction of the trend, since counter-trend trading with the RSI has proven to be ineffective. The position is closed after the buyers lose their advantage and the RSI drops to 40.
The strategy is recommended to be used only with long positions, as short positions show negative results. The strategy uses a moving average for the RSI with a period of 14 to smooth the oscillator data.
--------------------------------------------------------------------------------------------
Переосмысление легендарного осциллятора Relative strength index Джона Уэллса Уайлдера
Суть нового подхода заключается в реверсивном использовании так называемых зон "перекупленности" и "перепроданности". В своей книге от 1978 года "New concepts in tecnical trading systems", в которой был подробно описан механизм работы RSI, Уайлдер пишет, что один из способов использования осциллятора - открытие длинной позиции при снижении RSI в перепроданность (ниже 30) и открытие короткой позиции при повышении RSI до перекупленности (выше 70). Однако бэктест стратегии с такими вводными дает весьма посредственные результаты.
Исходя из формулы расчета, RSI рассчитывает скорость изменения цены за определенный период. Поэтому зоны перекупленности и перепроданности будут иметь относительное значение (относительно установленного периода расчета). Не зря ведь в названии осциллятора было добавлено слово "относительной". Стоит принять за аксиому утверждение, что цена актива справедлива в каждый момент времени.
По сути, RSI рассчитывает силу тренда. Если значение осциллятора выше 70, то на рынке с высокой долей вероятности происходит восходящее движение. Поэтому в текущей стратегии открытие лонга происходит именно в момент наибольшей силы покупателей (когда RSI > 80), то есть в сторону тренда, поскольку контртрендовая торговля по RSI показала свою несостоятельность. Закрытие позиции происходит после того, как покупатели теряют преимущество и RSI снижается до 40.
Стратегию рекомендуется использовать только с длинными позициями, поскольку короткие позиции показывают отрицательный результат. В стратегии используется скользящая средняя для RSI с периодом 14 для сглаживания данных осциллятора.
trend_switch
█ Description
Asset price data was time series data, commonly consisting of trends, seasonality, and noise. Many applicable indicators help traders to determine between trend or momentum to make a better trading decision based on their preferences. In some cases, there is little to no clear market direction, and price range. It feels much more appropriate to use a shorter trend identifier, until clearly defined market trend. The indicator/strategy developed with the notion aims to automatically switch between shorter and longer trend following indicator. There were many methods that can be applied and switched between, however in this indicator/strategy will be limited to the use of predictive moving average and MESA adaptive moving average (Ehlers), by first determining if there is a strong trend identified by calculating the slope, if slope value is between upper and lower threshold assumed there is not much price direction.
█ Formula
// predictive moving average
predict = (2*wma1-wma2)
trigger = (4*predict+3*predict +2*predict *predict)
// MESA adaptive moving average
mama = alpha*src+(1-alpha)*mama
fama = .5*alpha*mama+(1-.5-alpha)*fama
█ Feature
The indicator will have a specified default parameter of:
source = ohlc4
lookback period = 10
threshold = 10
fast limit = 0.5
slow limit = 0.05
Strategy type can be switched between Long/Short only and Long-Short strategy
Strategy backtest period
█ How it works
If slope between the upper (red) and lower (green) threshold line, assume there is little to no clear market direction, thus signal predictive moving average indicator
If slope is above the upper (red) or below the lower (green) threshold line, assume there is a clear trend forming, the signal generated from the MESA adaptive moving average indicator
█ Example 1 - Slope fall between the Threshold - activate shorter trend
█ Example 2 - Slope fall above/below Threshold - activate longer trend
Triple EMA + QQE Trend Following Strategy [TradeDots]The "Triple EMA + QQE Trend Following Strategy" harnesses the power of two sophisticated technical indicators, the Triple Exponential Moving Average (TEMA) and the Qualitative Quantitative Estimation (QQE), to generate precise buy and sell signals. This strategy excels in capturing shifts in trends by identifying short-term price momentum and dynamic overbought or oversold conditions.
HOW IT WORKS
This strategy integrates two pivotal indicators:
Triple Exponential Moving Average (TEMA): TEMA enhances traditional moving averages by reducing lag and smoothing the data more effectively. It achieves this by applying the EMA formula three times onto the price, as follows:
tema(src, length) =>
ema1 = ta.ema(src, length)
ema2 = ta.ema(ema1, length)
ema3 = ta.ema(ema2, length)
tema = 3*ema1 - 3*ema2 + ema3
This computation helps to sharpen the sensitivity to price movements.
Qualitative Quantitative Estimation (QQE): The QQE indicator improves upon the standard RSI by incorporating a smoothing mechanism. It starts with the standard RSI, overlays a 5-period EMA on this RSI, and then enhances the result using a double application of a 27-period EMA. A slow trailing line is then derived by multiplying the result with a factor number. This approach establishes a more refined and less jittery trend-following signal, complementing the TEMA to enhance overall market timing during fluctuating conditions.
APPLICATION
Referenced from insights on "Trading Tact," the strategy implementation follows:
First of all, we utilize two TEMA lines: one set at a 20-period and the other at a 40-period. Then following the rules below:
40-period TEMA is rising
20-period TEMA is above 40-period TEMA
Price closes above 20-period TEMA
Today is not Monday
RSI MA crosses the Slow trailing line
This strategy does not employ an active take profit mechanism; instead, it utilizes a trailing stop loss to allow the price to reach the stop loss naturally, thereby maximizing potential profit margins.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 80%
Users are advised to adjust and personalize this trading strategy to better match their individual trading preferences and style.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Reference:
Trading Tact. What Is the QQE Indicator? Retrieved from: tradingtact.com
Kaufman Adaptive Moving Average (KAMA) Strategy [TradeDots]"The Kaufman Adaptive Moving Average (KAMA) Strategy" is a trend-following system that leverages the adaptive qualities of the Kaufman Adaptive Moving Average (KAMA). This strategy is distinguished by its ability to adjust dynamically to market volatility, enhancing trading accuracy by minimizing the effects of false and delayed signals often associated with the Simple Moving Average (SMA).
HOW IT WORKS
This strategy is centered around use of the Kaufman Adaptive Moving Average (KAMA) indicator, which refines the principles of the Exponential Moving Average (EMA) with a superior smoothing technique.
KAMA distinguishes itself by its responsiveness to changes in market prices through an "Efficiency Ratio (ER)." This ratio is computed by dividing the recent absolute net price change by the cumulative sum of the absolute price changes over a specified period. The resulting ER value ranges between 0 and 1, where 0 indicates high market noise and 1 reflects stronger market momentum.
Using ER, we could get the smoothing constant (SC) for the moving average derived using the following formula:
fastest = 2/(fastma_length + 1)
slowest = 2/(slowma_length + 1)
SC = math.pow((ER * (fastest-slowest) + slowest), 2)
The KAMA line is then calculated by applying the SC to the difference between the current price and the previous KAMA.
APPLICATION
For entering long positions, this strategy initializes when there is a sequence of 10 consecutive rising KAMA lines. Conversely, a sequence of 10 consecutive falling KAMA lines triggers sell orders for long positions. The same logic applies inversely for short positions.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 80%
Users are advised to adjust and personalize this trading strategy to better match their individual trading preferences and style.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Multi-Timeframe Trend Following with 200 EMA Filter - Longs OnlyOverview
This strategy is designed to trade long positions based on multiple timeframe Exponential Moving Averages (EMAs) and a 200 EMA filter. The strategy ensures that trades are only entered in strong uptrends and aims to capitalize on sustained upward movements while minimizing risk with a defined stop-loss and take-profit mechanism.
Key Components
Initial Capital and Position Sizing
Initial Capital: $1000.
Lot Size: 1 unit per trade.
Inputs
Fast EMA Length (fast_length): The period for the fast EMA.
Slow EMA Length (slow_length): The period for the slow EMA.
200 EMA Length (filter_length_200): Set to 200 periods for the primary trend filter.
Stop Loss Percentage (stop_loss_perc): Set to 1% of the entry price.
Take Profit Percentage (take_profit_perc): Set to 3% of the entry price.
Timeframes and EMAs
EMAs are calculated for the following timeframes using the request.security function:
5-minute: Short-term trend detection.
15-minute: Intermediate-term trend detection.
30-minute: Long-term trend detection.
The strategy also calculates a 200-period EMA on the 5-minute timeframe to serve as a primary trend filter.
Trend Calculation
The strategy determines the trend for each timeframe by comparing the fast and slow EMAs:
If the fast EMA is above the slow EMA, the trend is considered positive (1).
If the fast EMA is below the slow EMA, the trend is considered negative (-1).
Combined Trend Signal
The combined trend signal is derived by summing the individual trends from the 5-minute, 15-minute, and 30-minute timeframes.
A combined trend value of 3 indicates a strong uptrend across all timeframes.
Any combined trend value less than 3 indicates a weakening or negative trend.
Entry and Exit Conditions
Entry Condition:
A long position is entered if:
The combined trend signal is 3 (indicating a strong uptrend across all timeframes).
The current close price is above the 200 EMA on the 5-minute timeframe.
Exit Condition:
The long position is exited if:
The combined trend signal is less than 3 (indicating a weakening trend).
The current close price falls below the 200 EMA on the 5-minute timeframe.
Stop Loss and Take Profit
Stop Loss: Set at 1% below the entry price.
Take Profit: Set at 3% above the entry price.
These levels are automatically set when entering a trade using the strategy.entry function with stop and limit parameters.
Plotting
The strategy plots the fast and slow EMAs for the 5-minute timeframe and the 200 EMA for visual reference on the chart:
Fast EMA (5-min): Plotted in blue.
Slow EMA (5-min): Plotted in red.
200 EMA (5-min): Plotted in green.
Adaptive RSI StrategyThe Adaptive RSI Strategy is designed to give you an edge by adapting to changing market conditions more effectively than the traditional RSI. By adjusting dynamically to recent price movements, this strategy aims to provide more timely and accurate trade signals.
How Does It Work?
You can set the number of periods for the RSI calculation. The default is 14, but feel free to experiment with different lengths to suit your trading style.
Choose the price data to base the RSI on, typically the closing price.
Decide if you want the strategy to visually highlight upward and downward movements of the Adaptive RSI (ARSI) on the chart. This can help you quickly spot trends.
Adaptive Calculation:
Alpha: The strategy uses an adaptive factor called alpha, which changes based on recent RSI values. This makes the RSI more sensitive to recent market conditions.
Adaptive RSI (ARSI): This is the core of our strategy. It calculates the ARSI using the adaptive alpha, making it more responsive to price changes compared to the traditional RSI.
Trade Signals:
Long Entry (Buy Signal): The strategy triggers a buy signal when the ARSI value crosses above its previous value. This indicates a potential upward trend, suggesting it's a good time to enter a long position.
Short Entry (Sell Signal): Conversely, a sell signal is triggered when the ARSI value crosses below its previous value, indicating a potential downward trend and suggesting it's a good time to enter a short position.
Visual Representation:
If you enable the highlight movements feature, the ARSI line on the chart will change color: green for upward movements and red for downward movements. This makes it easier to see potential trade opportunities at a glance.
Why Use the Adaptive RSI Strategy?
Responsiveness: The adaptive nature of this strategy means it's more sensitive to market changes, helping you react quicker to new trends.
Customization: You can tailor the length of the RSI period and decide whether to highlight movements, allowing you to adapt the strategy to your specific needs and preferences.
Visual Clarity: Highlighting the ARSI movements on the chart makes it easier to spot trends and potential entry points, giving you a clearer picture of the market.
Golden Cross VWMA & EMA 4h PinescriptlabsThis strategy combines the 50-period Volume-Weighted Moving Average (VWMA) on the current timeframe with a 200-period Simple Moving Average (SMA) on the 4-hour timeframe. This combination of indicators with different characteristics and time horizons aims to identify strong and sustained trends across multiple timeframes.
The VWMA is a variant of the moving average that assigns greater weight to periods of higher volatility, helping to avoid misleading signals. On the other hand, the 4-hour SMA is used as an additional trend filter in a shorter-term horizon. By combining these two indicators, the strategy can leverage the strength of the VWMA to capture the main trend, but only when confirmed by the SMA in the lower timeframe.
Buy signals are generated when the VWMA crosses above the 4-hour SMA, indicating a potential bullish trend aligned in both timeframes. Sell signals occur on a bearish cross, suggesting a possible reversal of the main trend.
The default parameters are a 50-period VWMA and a 200-period 4-hour SMA. It is recommended to adjust these lengths according to the traded instrument and the desired timeframe. It is also crucial to use stop losses and profit targets to properly manage risk.
By combining indicators of different types and timeframes, this strategy aims to provide a more comprehensive view of trend strength.
Español:
Esta estrategia combina la Volume-Weighted Moving Average (VWMA) de 50 períodos en el timeframe actual con una Simple Moving Average (SMA) de 200 períodos en el timeframe de 4 horas. Esta combinación de indicadores de distinta naturaleza y horizontes temporales busca identificar tendencias fuertes y sostenidas en múltiples timeframes.
La VWMA es una variante de la media móvil que asigna mayor ponderación a los períodos de mayor volatilidad, lo que ayuda a evitar señales engañosas. Por otro lado, la SMA de 4 horas se utiliza como un filtro adicional de tendencia en un horizonte de corto plazo. Al combinar estos dos indicadores, la estrategia puede aprovechar la fortaleza de la VWMA para capturar la tendencia principal, pero sólo cuando es confirmada por la SMA en el timeframe menor.
Las señales de compra se generan cuando la VWMA cruza al alza la SMA de 4 horas, indicando una potencial tendencia alcista alineada en ambos horizontes temporales. Las señales de venta ocurren en el cruce bajista, sugiriendo una posible reversión de la tendencia principal.
Los parámetros predeterminados son: VWMA de 50 períodos y SMA de 4 horas de 200 períodos. Se recomienda ajustar estas longitudes según el instrumento operado y el horizonte temporal deseado. También es crucial utilizar stops y objetivos de ganancias para controlar adecuadamente el riesgo.
Al combinar indicadores de diferentes tipos y timeframes, esta estrategia busca brindar una visión más completa de la fuerza de la tendencia.
Trend Following Parabolic Buy Sell Strategy [TradeDots]The Trend Following Parabolic Buy-Sell Strategy leverages the Parabolic SAR in combination with moving average crossovers to deliver buy and sell signals within a trend-following framework.
This strategy synthesizes proven methodologies sourced from various trading tutorials available on platforms such as YouTube and blogs, enabling traders to conduct robust backtesting on their selected trading pairs to assess the strategy's effectiveness.
HOW IT WORKS
This strategy employs four key indicators to orchestrate its trading signals:
1. Trend Alignment: It first assesses the relationship between the price and the predominant trendline to determine the directional stance—taking long positions only when the price trends above the moving average, signaling an upward market trajectory.
2. Momentum Confirmation: Subsequent to trend alignment, the strategy looks for moving average crossovers as a confirmation that the price is gaining momentum in the direction of the intended trades.
3. Signal Finalization: Finally, buy or sell signals are validated using the Parabolic SAR indicator. A long order is validated when the closing price is above the Parabolic SAR dots, and similarly, conditions are reversed for short orders.
4. Risk Management: The strategy institutes a fixed stop-loss at the moving average trendline and a take-profit level determinable by a prefixed risk-reward ratio calculated from the moving average trendline. These parameters are customizable by the users within the strategy settings.
APPLICATION
Designed for assets exhibiting pronounced directional momentum, this strategy aims to capitalize on clear trend movements conducive to achieving set take-profit targets.
As a lagging strategy that waits for multiple confirmatory signals, entry into trades might occasionally lag beyond optimal timing.
Furthermore, in periods of consolidation or sideways movement, the strategy may generate several false signals, suggesting the potential need for additional market condition filters to enhance signal accuracy during volatile phases.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 70%
Users are advised to adjust and personalize this trading strategy to better match their individual trading preferences and style.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
TASC 2024.06 REIT ETF Trading System█ OVERVIEW
This strategy script demonstrates the application of the Real Estate Investment Trust (REIT) ETF trading system presented in the article by Markos Katsanos titled "Is The Price REIT?" from TASC's June 2024 edition of Traders' Tips .
█ CONCEPTS
REIT stocks and ETFs offer a simplified, diversified approach to real estate investment. They exhibit sensitivity to interest rates, often moving inversely to interest rate and treasury yield changes. Markos Katsanos explores this relationship and the correlation of prices with the broader market to develop a trading strategy for REIT ETFs.
The script employs Bollinger Bands and Donchian channel indicators to identify oversold conditions and trends in REIT ETFs. It incorporates the 10-year treasury yield index (TNX) as a proxy for interest rates and the S&P 500 ETF (SPY) as a benchmark for the overall market. The system filters trade entries based on their behavior and correlation with the REIT ETF price.
█ CALCULATIONS
The strategy initiates long entries (buy signals) under two conditions:
1. Oversold condition
The weekly ETF low price dips below the 15-week Bollinger Band bottom, the closing price is above the value by at least 0.2 * ATR ( Average True Range ), and the price exceeds the week's median.
Either of the following:
– The TNX index is down over 15% from its 25-week high, and its correlation with the ETF price is less than 0.3.
– The yield is below 2%.
2. Uptrend
The weekly ETF price crosses above the previous week's 30-week Donchian channel high.
The SPY ETF is above its 20-week moving average.
Either of the following:
– Over ten weeks have passed since the TNX index was at its 30-week high.
– The correlation between the TNX value and the ETF price exceeds 0.3.
– The yield is below 2%.
The strategy also includes three exit (sell) rules:
1. Trailing (Chandelier) stop
The weekly close drops below the highest close over the last five weeks by over 1.5 * ATR.
The TNX value rises over the latest 25 weeks, with a yield exceeding 4%, or its value surges over 15% above the 25-week low.
2. Stop-loss
The ETF's price declines by at least 8% of the previous week's close and falls below the 30-week moving average.
The SPY price is down by at least 8%, or its correlation with the ETF's price is negative.
3. Overbought condition
The ETF's value rises above the 100-week low by over 50%.
The ETF's price falls over 1.5 * ATR below the 3-week high.
The ETF's 10-week Stochastic indicator exceeds 90 within the last three weeks.
█ DISCLAIMER
This strategy script educates users on the system outlined by the TASC article. However, note that its default properties might not fully represent real-world trading conditions for an individual. By default, it uses 10% of equity as the order size and a slippage amount of 5 ticks. Traders should adjust these settings and the commission amount when using this script. Additionally, since this strategy utilizes compound conditions on weekly data to trigger orders, it will generate significantly fewer trades than other, higher-frequency strategies.
Dual RSI Differential - Strategy [presentTrading]█ Introduction and How it is Different
The Dual RSI Differential Strategy introduces a nuanced approach to market analysis and trading decisions by utilizing two Relative Strength Index (RSI) indicators calculated over different time periods. Unlike traditional strategies that employ a single RSI and may signal premature or delayed entries, this method leverages the differential between a shorter and a longer RSI. This approach pinpoints more precise entry and exit points, providing a refined tool for traders to exploit market conditions effectively, particularly in overbought and oversold scenarios.
Most important: it is a good eductional code for swing trading.
For beginners, this Pine Script provides a complete function that includes crucial elements such as holding days and the option to configure take profit/stop loss settings:
- Hold Days: This feature ensures that trades are not exited too hastily, helping traders to ride out short-term market volatility. It's particularly valuable for swing trading where maintaining positions slightly longer can lead to capturing significant trends.
- TPSL Condition (None by default): This setting allows traders to focus solely on the strategy's robust entry and exit signals without being constrained by preset profit or loss limits. This flexibility is crucial for learning to adjust strategy settings based on personal risk tolerance and market observations.
BTCUSD 6h LS Performance
█ Strategy, How It Works: Detailed Explanation
🔶 RSI Calculation:
The RSI is a momentum oscillator that measures the speed and change of price movements. It is calculated using the formula:
RSI = 100 - (100 / (1 + RS))
Where RS (Relative Strength) = Average Gain of up periods / Average Loss of down periods.
🔶 Dual RSI Setup:
This strategy involves two RSI indicators:
RSI_Short (RSI_21): Calculated over a short period (21 days).
RSI_Long (RSI_42): Calculated over a longer period (42 days).
Differential Calculation:
The strategy focuses on the differential between these two RSIs:
RSI Differential = RSI_Long - RSI_Short
This differential helps to identify when the shorter-term sentiment diverges from longer-term trends, signaling potential trading opportunities.
BTCUSD Local picuture
🔶 Signal Triggers:
Entry Signal: A buy (long) signal is triggered when the RSI Differential exceeds -5, suggesting strengthening short-term momentum. Conversely, a sell (short) signal occurs when the RSI Differential falls below +5, indicating weakening short-term momentum.
Exit Signal: Trades are generally exited when the RSI Differential reverses past these thresholds, indicating a potential momentum shift.
█ Trade Direction
This strategy accommodates various trading preferences by allowing selections among long, short, or both directions, thus enabling traders to capitalize on diverse market movements and volatility.
█ Usage
The Dual RSI Differential Strategy is particularly suited for:
Traders who prefer a systematic approach to capture market trends.
Those who seek to minimize risks associated with rapid and unexpected market movements.
Traders who value strategies that can be finely tuned to different market conditions.
█ Default Settings
- Trading Direction: Both — allows capturing of upward and downward market movements.
- Short RSI Period: 21 days — balances sensitivity to market movements.
- Long RSI Period: 42 days — smoothens out longer-term fluctuations to provide a clearer market trend.
- RSI Difference Level: 5 — minimizes false signals by setting a moderate threshold for action.
Use Hold Days: True — introduces a temporal element to trading strategy, holding positions to potentially enhance outcomes.
- Hold Days: 5 — ensures that trades are not exited too hastily, helping to ride out short-term volatility.
- TPSL Condition: None — enables traders to focus solely on the strategy's entry and exit signals without preset profit or loss limits.
- Take Profit Percentage: 15% — aims for significant market moves to lock in profits.
- Stop Loss Percentage: 10% — safeguards against large losses, essential for long-term capital preservation.
Trailing Take Profit - Close Based📝 Description
This script demonstrates a new approach to the trailing take profit.
Trailing Take Profit is a price-following technique. When used, instead of setting a limit order for the take profit target exiting from your position at the specified price, a stop order is conditionally set when the take profit target is reached. Then, the stop price (a.k.a trailing price), is placed below the take profit target at a distance defined by the user percentagewise. On regular time intervals, the stop price gets updated by following the "Trail Barrier" price (high by default) upwards. When the current price hits the stop price you exit the trade. Check the chart for more details.
This script demonstrates how to implement the close-based Trailing Take Profit logic for long positions, but it can also be applied for short positions if the logic is "reversed".
📢 NOTE
To generate some entries and showcase the "Trailing Take Profit" technique, this script uses the crossing of two moving averages. Please keep in mind that you should not relate the Backtesting results you see in the "Strategy Tester" tab with the success of the technique itself.
This is not a complete strategy per se, and the backtest results are affected by many parameters that are outside of the scope of this publication. If you choose to use this new approach of the "Trailing Take Profit" in your logic you have to make sure that you are backtesting the whole strategy.
⚔️ Comparison
In contrast to my older "Trailing Take Profit" publication where the trailing take profit implementation was tick-based, this new approach is close-based, meaning that the update of the stop price occurs at the bar close instead of every tick.
While comparing the real-time results of the two implementations is like comparing apples to oranges, because they have different dynamic behavior, the new approach offers better consistency between the backtesting results and the real-time results.
By updating the stop price on every bar close, you do not rely on the backtester assumptions anymore (check the Reasoning section below for more info).
The new approach resembles the conditional "Trailing Exit" technique, where the condition is true when the current price crosses over the take profit target. Then, the stop order is placed at the trailing price and it gets updated on every bar close to "follow" the barrier price (high). On the other hand, the older tick-based approach had more "tight" dynamics since the trailing price gets updated on every tick leaving less room for price fluctuations by making it more probable to reach the trailing price.
🤔 Reasoning
This new close-based approach addresses several practical issues the older tick-based approach had. Those issues arise mainly from the technicalities of the TV Backtester. More specifically, due to the assumptions the Broker Emulator makes for the price action of the history bars, the backtesting results in the TV Backtester are exaggerated, and depending on the timeframe, the backtesting results look way better than they are in reality.
The effect above, and the inability to reason about the performance of a strategy separated people into two groups. Those who never use this feature, because they couldn't know for sure the actual effect it might have in their strategy, (even if it turned out to be more profitable) and those who abused this type of "repainting" behavior to show off, and hijack some boosts from the community by boasting about the "fake" results of their strategies.
Even if there are ways to evaluate the effectiveness of the tick-based approach that is applied in an existing strategy (this is out of the topic of this publication), it requires extra effort to do the analysis. Using this closed-based approach we can have more predictable results, without surprises.
⚠️ Caveats
Since this approach updates the trailing price on bar close, you must wait for at least one bar to close after the price crosses over the take profit target.
Turn of the Month Strategy [Honestcowboy]The end of month effect is a well known trading strategy in the stock market. Quite simply, most stocks go up at the end of the month. What's even better is that this effect spills over to the next phew days of the next month.
In this script we backtest this theory which should work especially well on SP500 pair.
By default the strategy buys 2 days before the end of each month and exits the position 3 days into the next month.
The strategy is a long only strategy and is extremely simple. The SP500 is one of the #1 assets people use for long term investing due to it's "9.8%" annualised return. However as a trader you want the best deal possible. This strategy is only inside the market for about 25% of the time while delivering a similar return per exposure with a lower drawdown.
Here are some hypothesis why turn of the month effect happens in the stock markets:
Increased inflow from savings accounts to stocks at end of month
Rebalancing of portfolios by fund managers at end of month
The timing of monthly cash flows received by pension funds, which are reinvested in the stock market.
The script also has some inputs to define how many days before end of the month you want to buy the asset and how long you want to hold it into the next month.
It is not possible to buy the asset exactly on this day every month as the market closes on the weekend. I've added some logic where it will check if that day is a friday, saturdady or sunday. If that is the case it will send the buy signal on the end of thursday, this way we enter on the friday and don't lose that months trading opportunity.
The backtest below uses 4% exposure per trade as to show the equity curve more clearly and because of publishing rules. However, most fund managers and investors use 100% exposure. This way you actually risk money to earn money. Feel free to adjust the settings to your risk profile to get a clearer picture of risks and rewards before implementing in your portfolio.
Moving average strategyNAME : Moving average strategy
SUMMARY
Long when Short MA period > Long MA period
Exit when Short MA period < Long MA period
Long only strategy, but you can modify this script.
==============================
This strategy uses a moving average line.
It buys when the short-term moving average crosses the long-term moving average and sells when the long-term moving average crosses the short-term moving average.
You can use different moving average lines by setting the MA type.
You can use SMA, EMA, DEMA, TEMA, WMA, and VWMA.
You can also adjust the period of the moving average line.
Price Type sets the type of price that will be used for the moving average line. The options are Close price, Open price, High price, Low price, Typical price, and center price.
High MDD and long periods of sideways movement make it difficult to use in practice, even though the returns may seem high.
Hopefully, you can combine it with other indicators to create a good strategy.
Thank you.
Price and Volume Breakout Buy Strategy [TradeDots]The "Price and Volume Breakout Buy Strategy" is a trading strategy designed to identify buying opportunities by detecting concurrent price and volume breakouts over a specified range of candlesticks.
This strategy is optimized for assets demonstrating high volatility and significant momentum spikes.
HOW IT WORKS
The strategy first takes the specific number of candlesticks as the examination window for both price and volume.
These values are used as benchmarks to identify breakout conditions.
A trade is initiated when both the closing price and the trading volume surpass the maximum values observed within the predetermined window.
Price must be above a designated moving average, serving as the trend indicator, ensuring that all trades align with the prevailing market trend.
APPLICATION
This strategy is particularly effective for highly volatile assets such as Bitcoin and Ethereum, capitalizing on the cues from sudden price and volume breakouts indicative of significant market movement, often driven by market smart money traders.
However, for broader markets like the S&P 500, this strategy may be less effective due to less pronounced volume and price shifts compared to the cryptocurrency markets.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 70%
Backtest result sometimes gives fewer than 100 trades under certain higher timeframes, as most trades tend to have a long holding period. Entry conditions are also more stringent, which, combined with the relatively brief history of cryptocurrencies, results in fewer trades on longer timeframes.
Users are advised to adjust and personalize this trading strategy to better match their individual trading preferences and style.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Alligator + MA Trend Catcher [TradeDots]The "Alligator + MA Trend Catcher" is a trading strategy that integrates the William Alligator indicator with a Moving Average (MA) to establish robust entry and exit conditions, optimized for capturing trends.
HOW IT WORKS
This strategy combines the traditional William Alligator set up with an additional Moving Average indicator for enhanced trend confirmation, creating a user-friendly backtesting tool for traders who prefer the Alligator method.
The original Alligator strategy can frequently present fluctuations, even in well-established trends, leading to potentially premature exits. To mitigate this, we incorporate a Moving Average as a secondary confirmation measure to ensure the market trend has indeed shifted.
Here’s the operational flow for long orders:
Entry Signal: When the price rises above the Moving Average, it confirms a bullish market state. Enter if Alligator spread in an upward direction. The trade remains active even if the Alligator indicator suggests a trend reversal.
Exit Signal: The position is closed when the price falls below the Moving Average, and the Alligator spreads in the downward direction. This setup helps traders to maintain positions through the entirety of the trend for maximum gain.
APPLICATION
This strategy is tailored for assets with significant, well-defined trends, such as Bitcoin and Ethereum, which are known for their high volatility and substantial price movements.
This strategy offers a low win-rate but high reward configuration, making asset selection critical for long-term profitability. If you choose assets that lack strong price momentum, there's a high chance that this strategy may not be effective.
For traders seeking to maximize gains from large trends without exiting prematurely, this strategy provides an aggressive yet controlled approach to riding out substantial market waves.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 80%
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Multi Timeframe RSI Buy Sell Strategy [TradeDots]The "Multi Timeframe RSI Buy/Sell Strategy" is a trading strategy that utilizes Relative Strength Index (RSI) indicators from multiple timeframes to provide buy and sell signals.
This strategy allows for extensive customization, supporting up to three distinct RSIs, each configurable with its own timeframe, length, and data source.
HOW DOES IT WORK
This strategy integrates up to three RSIs, each selectable from different timeframes and customizable in terms of length and source. Users have the flexibility to define the number of active RSIs. These selections visualize as plotted lines on the chart, enhancing interpretability.
Users can also manage the moving average of the selected RSI lines. When multiple RSIs are active, the moving average is calculated based on these active lines' average value.
The color intensity of the moving average line changes as it approaches predefined buying or selling thresholds, alerting users to potential signal generation.
A buy or sell signal is generated when all active RSI lines simultaneously cross their respective threshold lines. Concurrently, a label will appear on the chart to signify the order placement.
For those preferring not to display order information or activate the strategy, an "Enable backtest" option is provided in the settings for toggling activation.
APPLICATION
The strategy leverages multiple RSIs to detect extreme market conditions across various timeframes without the need for manual timeframe switching.
This feature is invaluable for identifying divergences across timeframes, such as detecting potential short-term reversals within broader trends, thereby aiding traders in making better trading decisions and potentially avoiding losses.
DEFAULT SETUP
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 60%
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
TradeDots Stochastic Z-Score
Khaled Tamim's Avellaneda-Stoikov StrategyDescription:
This strategy applies the Avellaneda-Stoikov (A-S) model to generate buy and sell signals for underlying assets based on option pricing theory. The A-S model estimates bid and ask quotes for options contracts considering factors like volatility (sigma), time to expiration (T), and risk aversion (gamma).
Key Concepts:
Avellaneda-Stoikov Model: A mathematical framework for option pricing that incorporates volatility, time decay, and risk tolerance.
Bid-Ask Quotes: The theoretical buy and sell prices for an option contract.
Inventory Management: The strategy tracks its long or short position based on signals.
How it Works:
A-S Model Calculation: The avellanedaStoikov function calculates bid and ask quotes using the underlying asset's closing price, user-defined parameters (gamma, sigma, T, k, and M), and a small fee (adjustable).
Signal Generation: The strategy generates long signals when the closing price falls below the adjusted bid quote and short signals when it exceeds the adjusted ask quote.
Trade Execution: Buy and sell orders are triggered based on the generated signals (long for buy, short for sell).
Inventory Tracking: The strategy's net profit reflects the current inventory level (long or short position).
Customization:
Gamma (γ): Controls risk aversion in the A-S model (higher values imply lower risk tolerance).
Sigma (σ): Represents the underlying asset's expected volatility.
T: Time to expiration for the hypothetical option (defaults to a short-term option).
k: A constant factor in the A-S model calculations.
M: Minimum price buffer for buy/sell signals (prevents excessive churn).
Important Note:
This strategy simulates option pricing behavior for a theoretical option and does not directly trade options contracts. Backtesting results may not reflect actual market conditions.
Further Considerations:
The 0.1% fee is a placeholder and may need adjustment based on real-world trading costs.
Consider using realistic timeframes for T (e.g., expiry for a real option)
Disclaimer: This strategy is for educational purposes only and does not constitute financial advice.