Altcoin Long/Short Strategy//@version=5
strategy("Altcoin Long/Short Strategy", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=2, commission_type=strategy.commission.percent, commission_value=0.1)
// —————— Inputs ——————
emaFastLength = input.int(20, "Fast EMA")
emaSlowLength = input.int(50, "Slow EMA")
rsiLength = input.int(14, "RSI Length")
bbLength = input.int(20, "Bollinger Bands Length")
riskRewardRatio = input.float(1.5, "Risk/Reward Ratio")
stopLossPerc = input.float(2, "Stop Loss %") / 100
// —————— Indicators ——————
// Trend: EMAs
emaFast = ta.ema(close, emaFastLength)
emaSlow = ta.ema(close, emaSlowLength)
ema200 = ta.ema(close, 200)
// Momentum: RSI & MACD
rsi = ta.rsi(close, rsiLength)
= ta.macd(close, 12, 26, 9)
// Volatility: Bollinger Bands
basis = ta.sma(close, bbLength)
dev = ta.stdev(close, bbLength)
upperBand = basis + 2 * dev
lowerBand = basis - 2 * dev
// —————— Strategy Logic ——————
// Long Conditions
longCondition =
close > ema200 and // Long-term bullish
ta.crossover(emaFast, emaSlow) and // EMA crossover
rsi > 50 and // Momentum rising
close > lowerBand and // Bounce from lower Bollinger Band
macdLine > signalLine // MACD bullish
// Short Conditions
shortCondition =
close < ema200 and // Long-term bearish
ta.crossunder(emaFast, emaSlow) and // EMA crossunder
rsi < 50 and // Momentum weakening
close < upperBand and // Rejection from upper Bollinger Band
macdLine < signalLine // MACD bearish
// —————— Risk Management ——————
stopLoss = strategy.position_avg_price * (1 - stopLossPerc)
takeProfit = strategy.position_avg_price * (1 + (riskRewardRatio * stopLossPerc))
// —————— Execute Trades ——————
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=stopLoss, limit=takeProfit)
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=stopLoss, limit=takeProfit)
// —————— Plotting ——————
plot(emaFast, "Fast EMA", color=color.blue)
plot(emaSlow, "Slow EMA", color=color.orange)
plot(ema200, "200 EMA", color=color.gray)
plot(upperBand, "Upper Bollinger", color=color.red)
plot(lowerBand, "Lower Bollinger", color=color.green)
תבניות גרפים
Range, Initiation, Mitigation & ContinuationHere's the initial version of your TradingView indicator in Pine Script. It detects price ranges, breakouts, mitigations, and trend continuation, coloring the range boxes accordingly
Classic Patterns (Template)Script 3: “Classic Pattern Stubs: Double Tops, Triangles, Wedges, Channels”
Purpose: Provide an indicator that identifies or sketches multiple classical patterns (Double Top/Bottom, Asc/Desc Triangles, Wedges, and Channels). Each pattern can be toggled on or off.
How It’s Organized:
Each pattern has a checkbox: showDoubleTops, showTriangles, showWedge, showChannel.
Each pattern has an int input for the lookback window.
The code draws lines or shapes if the pattern is detected.
SMA + RSI + Volume + ATR StrategySMA + RSI + Volume + ATR Strategy
1. Indicators Used:
SMA (Simple Moving Average): This is a trend-following indicator that calculates the average price of a security over a specified period (50 periods in this case). It's used to identify the overall trend of the market.
RSI (Relative Strength Index): This measures the speed and change of price movements. It tells us if the market is overbought (too high) or oversold (too low). Overbought is above 70 and oversold is below 30.
Volume: This is the amount of trading activity. A higher volume often indicates strong interest in a particular price move.
ATR (Average True Range): This measures volatility, or how much the price is moving in a given period. It helps us adjust stop losses and take profits based on market volatility.
2. Conditions for Entering Trades:
Buy Signal (Green Up Arrow):
Price is above the 50-period SMA (indicating an uptrend).
RSI is below 30 (indicating the market might be oversold or undervalued, signaling a potential reversal).
Current volume is higher than average volume (indicating strong interest in the move).
ATR is increasing (indicating higher volatility, suggesting that the market might be ready for a move).
Sell Signal (Red Down Arrow):
Price is below the 50-period SMA (indicating a downtrend).
RSI is above 70 (indicating the market might be overbought or overvalued, signaling a potential reversal).
Current volume is higher than average volume (indicating strong interest in the move).
ATR is increasing (indicating higher volatility, suggesting that the market might be ready for a move).
3. Take Profit & Stop Loss:
Take Profit: When a trade is made, the strategy will set a target price at a certain percentage above or below the entry price (1.5% in this case) to automatically exit the trade once that target is hit.
Stop Loss: If the price goes against the position, a stop loss is set at a percentage below or above the entry price (0.5% in this case) to limit losses.
4. Execution of Trades:
When the buy condition is met, the strategy will enter a long position (buying).
When the sell condition is met, the strategy will enter a short position (selling).
5. Visual Representation:
Green Up Arrow: Appears on the chart when the buy condition is met.
Red Down Arrow: Appears on the chart when the sell condition is met.
These arrows help you see at a glance when the strategy suggests you should buy or sell.
In Summary:
This strategy uses a combination of trend-following (SMA), momentum (RSI), volume, and volatility (ATR) to decide when to buy or sell a stock. It looks for opportunities when the market is either oversold (buy signal) or overbought (sell signal) and makes sure there’s enough volume and volatility to back up the move. It also includes take-profit and stop-loss levels to manage risk.
MI-Advanced Long/Short StrategyAdvanced Multi-Indicator Trading Strategy
Combining Trend Following, Momentum Confirmation & Risk Management
This sophisticated trading strategy is designed to identify high-probability long/short opportunities using a confluence of technical indicators while maintaining strict risk control. It combines trend analysis, momentum confirmation, and volume-based validation to generate clear buy/sell signals across various markets and timeframes.
Core Components
Trend Identification Engine
Dual EMA System (12/26 periods):
Bullish bias when 12-EMA > 26-EMA
Bearish bias when 12-EMA < 26-EMA
Supertrend Indicator:
Dynamic trend filter using price volatility
Green line = Bullish trend (longs enabled)
Red line = Bearish trend (shorts enabled)
Momentum Confirmation
MACD Histogram:
Bullish crossover (signal line cross) for entries
Bearish crossover for exits/reversals
RSI Threshold:
50-level as momentum baseline
Longs only when RSI > 50
Shorts only when RSI < 50
Volume Validation
20-period volume moving average
Entry requires 150%+ volume spike
Filters low-confidence moves
Risk Management Framework
ATR-Based Stops:
2x ATR (14-period) stop loss
3x ATR take profit (1:1.5 RR ratio)
Position Sizing:
Percentage-based equity management
Built-in commission calculation
Signal Generation Logic
Long Entry Conditions (All Must Be True):
12-EMA crosses above 26-EMA
MACD line crosses above signal line
RSI sustains above 50 level
Price above Supertrend line (green)
Volume spike confirmation
Short Entry Conditions (All Must Be True):
12-EMA crosses below 26-EMA
MACD line crosses below signal line
RSI holds below 50 level
Price below Supertrend line (red)
Volume spike confirmation
Exit Conditions:
Trailing stop via Supertrend reversal
EMA crossover in opposite direction
RSI crossing 50 threshold
Automatic profit targets/stops
Key Features
Multi-Timeframe Compatibility: Works on 1M-1D charts
Visual Clarity:
Colored EMA ribbons for trend direction
Label-based buy/sell markers
Supertrend overlay for real-time guidance
Alert System:
Built-in buy/sell alert conditions
Compatible with email/SMS notifications
Adaptive Risk:
Dynamic stop-loss adjustment
Position sizing relative to account equity
False Signal Filter:
Volume spike requirement
Triple confirmation (trend+momentum+volume)
Strategic Advantages
Trend-Riding Capability:
Captures sustained moves via Supertrend/EMA combo
Avoids choppy markets through volume filters
Confirmation Hierarchy:
Primary Trend: EMA crossover
Secondary Confirmation: MACD/RSI
Tertiary Validation: Volume/Supertrend
Risk-Controlled Execution:
Automatic stop-loss placement
Fixed risk/reward ratio enforcement
Commission-aware backtesting
Visual Trading Psychology:
Clear color-coded indicators reduce emotional trading
Objective entry/exit rules eliminate guesswork
Ideal Market Conditions
Best Performing: Trending markets (up/down)
Avoid During:
Low-volume periods
Consolidation/ranging markets
Major news events
Practical Usage Tips
Combine with higher timeframe analysis
Adjust ATR multiplier for volatile assets
Modify volume threshold for liquid markets
Use trailing stops for extended trends
Pair with fundamental catalysts for swing trades
This strategy provides a systematic approach to trading by combining technical analysis with disciplined risk management. Its multi-layered confirmation process aims to filter out market noise while capturing high-quality setups, making it suitable for both discretionary traders and automated trading systems.
Midnight Opening Ranges [TDL]
Midnight Opening Ranges with Standard Deviations as taught by Micheal J. Huddleston
- Custom colors
- Up to 10 Std dev levels
- Midnight opening price
- Current and previous ranges with dates and midpoints
Petru Indicator14 Day range. Percentage move. Analyzes first 14 days and percentage move after given window.
Smart Money Concepts + EMA Signals [DeepEye_crypto]
Concept Description: Moving Averages
A moving average (MA) is a statistical calculation used to analyze data points by creating a series of averages of different subsets of the full data set. In trading, moving averages are commonly used to smooth out price data to identify the direction of the trend.
Types of Moving Averages:
Simple Moving Average (SMA):
The SMA is calculated by taking the arithmetic mean of a given set of values. For example, a 10-day SMA is the average of the closing prices for the last 10 days.
Exponential Moving Average (EMA):
The EMA gives more weight to recent prices, making it more responsive to new information. It is calculated using a smoothing factor that applies exponential decay to past prices.
Weighted Moving Average (WMA):
The WMA assigns a higher weight to recent prices, but the weights decrease linearly.
Hull Moving Average (HMA):
The HMA aims to reduce lag while maintaining a smooth average. It uses WMA in its calculation to achieve this.
Volume Weighted Moving Average (VWMA):
The VWMA weights prices based on trading volume, giving more importance to prices with higher trading volume.
Feature Description: TradingView Alerts
TradingView alerts are a powerful feature that allows traders to receive notifications when specific conditions are met on their charts. Alerts can be set up for various types of conditions, such as price levels, indicator values, or custom Pine Script conditions.
How to Set Up Alerts:
Create an Alert:
Click on the "Alert" button (clock icon) on the TradingView toolbar or right-click on the chart and select "Add Alert".
Configure the Alert:
Choose the condition for the alert (e.g., crossing a specific price level or indicator value).
Set the frequency of the alert (e.g., once, every time, or once per bar).
Customize the alert message and notification options (e.g., pop-up, email, SMS).
Use Pine Script for Custom Alerts:
My strategyimport pandas as pd
import ta
import time
from dhan import DhanHQ
# Dhan API Credentials
API_KEY = "your_api_key"
ACCESS_TOKEN = "your_access_token"
dhan = DhanHQ(api_key=API_KEY, access_token=ACCESS_TOKEN)
# Strategy Parameters
SYMBOL = "RELIANCE" # Replace with your stock symbol
INTERVAL = "1min" # Scalping requires a short timeframe
STOPLOSS_PERCENT = 0.2 # Stop loss percentage (0.2% per trade)
TARGET_RR_RATIO = 2 # Risk-Reward Ratio (1:2)
QUANTITY = 10 # Number of shares per trade
def get_historical_data(symbol, interval="1min", limit=50):
"""Fetch historical data from Dhan API."""
response = dhan.get_historical_data(symbol=symbol, interval=interval, limit=limit)
if response == "success":
df = pd.DataFrame(response )
df = df .astype(float)
df = df .astype(float)
df = df .astype(float)
df = df .astype(float)
return df
else:
raise Exception("Failed to fetch data: ", response )
def add_indicators(df):
"""Calculate EMA (9 & 20), VWAP, and RSI."""
df = ta.trend.ema_indicator(df , window=9)
df = ta.trend.ema_indicator(df , window=20)
df = ta.volume.volume_weighted_average_price(df , df , df , df )
df = ta.momentum.rsi(df , window=14)
return df
def check_signals(df):
"""Identify Buy and Sell signals based on EMA, VWAP, and RSI."""
latest = df.iloc
# Buy Condition
if latest > latest and latest > latest and 40 <= latest <= 60:
return "BUY"
# Sell Condition
if latest < latest and latest < latest and 40 <= latest <= 60:
return "SELL"
return None
def place_order(symbol, side, quantity):
"""Execute a market order."""
order_type = "BUY" if side == "BUY" else "SELL"
order = dhan.place_order(symbol=symbol, order_type="MARKET", quantity=quantity, transaction_type=order_type)
if order == "success":
print(f"{order_type} Order Placed: {order }")
return float(order ) # Return entry price
else:
raise Exception("Order Failed: ", order )
def scalping_strategy():
position = None
entry_price = 0
stoploss = 0
target = 0
while True:
try:
# Fetch and process data
df = get_historical_data(SYMBOL, INTERVAL)
df = add_indicators(df)
signal = check_signals(df)
# Execute trade
if signal == "BUY" and position is None:
entry_price = place_order(SYMBOL, "BUY", QUANTITY)
stoploss = entry_price * (1 - STOPLOSS_PERCENT / 100)
target = entry_price + (entry_price - stoploss) * TARGET_RR_RATIO
position = "LONG"
print(f"BUY @ {entry_price}, SL: {stoploss}, Target: {target}")
elif signal == "SELL" and position is None:
entry_price = place_order(SYMBOL, "SELL", QUANTITY)
stoploss = entry_price * (1 + STOPLOSS_PERCENT / 100)
target = entry_price - (stoploss - entry_price) * TARGET_RR_RATIO
position = "SHORT"
print(f"SELL @ {entry_price}, SL: {stoploss}, Target: {target}")
# Exit logic
if position:
current_price = df .iloc
if (position == "LONG" and (current_price <= stoploss or current_price >= target)) or \
(position == "SHORT" and (current_price >= stoploss or current_price <= target)):
print(f"Exiting {position} @ {current_price}")
position = None
time.sleep(60) # Wait for the next candle
except Exception as e:
print(f"Error: {e}")
time.sleep(60)
# Run the strategy
try:
scalping_strategy()
except KeyboardInterrupt:
print("Trading stopped manually.")
Previous HTF Highs, Lows & Equilibriums [ᴅᴀɴɪ]#Previous HTF Highs, Lows & Equilibriums
Indicator Description
This powerful and user-friendly indicator is designed to help traders visualize key levels from multiple higher timeframes directly on their chart. It plots the previous session's high, low, and equilibrium (EQ) levels for up to 4 customizable timeframes, allowing you to analyze price action across different time horizons simultaneously.
Key Features
#1 Multi-Timeframe Support:
Choose up to 4 higher timeframes (e.g., 1H, 4H, 1D, 1W) to plot levels on your chart.
Each timeframe's levels are displayed with clear, customizable lines.
#2 Previous Session Levels:
Plots the previous session's high, low, and EQ (EQ = (high + low) / 2) for each selected timeframe.
Levels are dynamically updated at the start of each new session.
#3 Customizable Line Styles:
Choose between solid, dashed, or dotted lines for each level.
Customize colors for high, low, and EQ levels to suit your preferences.
#4 Dynamic Labels:
Each level is labeled with the corresponding timeframe (e.g., "1D - H" for daily high, "4H - L" for 4-hour low).
Labels are positioned dynamically to avoid clutter and ensure readability.
#5 Toggle On/Off:
Easily toggle the visibility of all levels with a single button, making it simple to declutter your chart when needed.
#6 Compatible with All Markets:
Works seamlessly across all instruments (stocks, forex, crypto, futures, etc.) and timeframes.
How to Use?
1. Add the indicator to your chart.
2. Select up to 4 higher timeframes to plot levels.
3. Customize line styles and colors to match your trading style.
4. Toggle levels on/off as needed to keep your chart clean and focused
Disclaimer
This indicator is not a trading signal generator . It does not predict market direction or provide buy/sell signals. Instead, it is a tool to help you visualize key levels from higher timeframes, enabling you to make more informed trading decisions. Always combine this tool with your own analysis, risk management, and trading strategy.
Thank you for choosing this indicator! I hope it becomes a valuable part of your trading toolkit. Remember, trading is a journey, and having the right tools can make all the difference. Whether you're a seasoned trader or just starting out, this indicator is designed to help you stay organized and focused on what matters most—price action. Happy trading, and may your charts be ever in your favor! 😊
6 Medias Móviles con RSI, Dólar MEP y Tendencia Tendencia Mayoritaria:
La variable trend se inicializa con el valor "Neutral", de forma explícita.
Usé la palabra clave var para asegurarnos de que el valor de la variable trend se mantenga a través de las barras.
Manejo del na:
Se ha eliminado el uso de na de manera incorrecta y se ha utilizado una forma correcta de asignación, con valores explícitos para variables de tipo string.
Valor del label:
Se ha cambiado la posición del label a una forma más correcta de manejarlo, usando el índice de la barra.
Tendencia:
La variable trend ahora se evalúa correctamente sin errores.
gold 1m stgyye script gold me 1m sahi kaam karta hai chaho to aap test Karke dekh sakte ho iska Norman Maine Kiya ware
Pre-Pump Alert Systemdesigned to identify potential pre-pump opportunities in cryptocurrencies by scanning for specific technical conditions. It combines multiple indicators and conditions to alert you when certain criteria are met, signaling a possible price movement. Here's a detailed breakdown of what your script does:
Key Features of the Script
RSI (Relative Strength Index) Conditions:
Detects when the RSI crosses below 35 (oversold condition) or above 75 (overbought condition).
These levels indicate potential reversal points or local tops/bottoms.
MACD (Moving Average Convergence Divergence) Crossover:
Identifies MACD crossovers on the 4-hour timeframe.
A bullish crossover (MACD line crossing above the signal line) suggests potential upward momentum.
Volume Spikes:
Detects when the current volume is >150% of the 24-hour average volume.
Volume spikes often indicate increased interest and potential price movement.
Price Touching Key EMAs (Exponential Moving Averages):
Monitors when the price touches or crosses key EMAs: 13, 48, and 200.
These EMAs act as dynamic support/resistance levels.
Bollinger Band Squeeze:
Identifies when the Bollinger Bands narrow significantly (a squeeze).
A squeeze often precedes a breakout or strong price movement.
Breakout of Key Support/Resistance Levels:
Alerts when the price breaks above a resistance level or below a support level with volume confirmation.
This indicates a potential trend continuation or reversal.
EMA and SMA Crossover with RSI14 FilteringExplanation of the Script:
Indicators:
EMA 5 and SMA 10: These are the two moving averages used to determine the trend direction.
Buy signal is triggered when EMA 5 crosses above SMA 10.
Sell signal is triggered when EMA 5 crosses below SMA 10.
RSI 14: This is used to filter buy and sell signals.
Buy trades are allowed only if RSI 14 is above 60.
Sell trades are allowed only if RSI 14 is below 50.
Buy Conditions:
The strategy waits for the EMA crossover (EMA 5 crosses above SMA 10).
The strategy checks if RSI 14 is above 60 for confirmation.
If the price is below 60 on RSI 14 at the time of crossover, the strategy will wait until the price crosses above 60 on RSI 14 to initiate the buy.
Sell Conditions:
The strategy waits for the EMA crossover (EMA 5 crosses below SMA 10).
The strategy checks if RSI 14 is below 50 for confirmation.
If the price is above 50 on RSI 14 at the time of crossover, the strategy will wait until the price crosses below 50 on RSI 14 to initiate the sell.
Exit Conditions:
The Buy position is closed if the EMA crossover reverses (EMA 5 crosses below SMA 10) or RSI 14 drops below 50.
The Sell position is closed if the EMA crossover reverses (EMA 5 crosses above SMA 10) or RSI 14 rises above 60.
Plotting:
The script plots the EMA 5, SMA 10, and RSI 14 on the chart for easy visualization.
Horizontal lines are drawn at RSI 60 and RSI 50 levels for reference.
Key Features:
Price Confirmation: The strategy ensures that buy trades are only initiated if RSI 14 crosses above 60, and sell trades are only initiated if RSI 14 crosses below 50. Additionally, price action must cross these RSI levels to confirm the trade.
Reversal Exits: Positions are closed when the EMA crossover or RSI condition reverses.
Backtesting:
Paste this script into the Pine Editor on TradingView to test it with historical data.
You can adjust the EMA, SMA, and RSI lengths based on your preferences.
Let me know if you need further adjustments or clarification!
Indicador XAU/USD - Compras e VendasSegundo Indicador feito por Aneilton para analise do XAUUSD quando estiver em tendência de Baixa
Gold Trade Setup Strategy BrokerirProfitable Gold Setup Strategy with Adaptive Moving Average & Supertrend – Brokerir’s Exclusive Strategy
Introduction:
This Gold (XAU/USD) trading strategy, developed by Brokerir, leverages the power of the Adaptive Moving Average (AMA) and Supertrend indicators to identify high-probability trade setups. This approach is designed to work seamlessly for both swing traders and intraday traders, optimizing trading times for maximum precision and profitability. The AMA helps in recognizing the prevailing market trend, while the Supertrend indicator confirms the best entry and exit points. This strategy is fine-tuned for Gold’s price movements, providing clear guidance for disciplined and profitable trading.
Strategy Components:
Adaptive Moving Average (AMA):
Responsive to Market Conditions: The AMA adjusts to market volatility, making it an ideal trend-following tool.
Trend Indicator: It acts as the primary tool for identifying the overall trend direction, reducing noise in volatile markets.
Supertrend:
Signal Confirmation: The Supertrend indicator provides reliable buy and sell signals by confirming the trend direction indicated by the AMA.
Trailing Stop-Loss: It also acts as a trailing stop-loss, helping to protect profits by dynamically adjusting as the market moves in your favor.
Trading Rules:
Trading Hours:
Trades should only be taken between 8:30 AM and 10:30 PM IST, avoiding low-volume periods to reduce market noise and increase the probability of successful setups.
Buy Setup:
Trend Confirmation: Ensure the Adaptive Moving Average (AMA) is green, confirming an uptrend.
Signal Confirmation: Wait for the Supertrend to turn green, confirming the continuation of the uptrend.
Trigger: Enter the trade when the high of the trigger candle (the candle that turned the Supertrend green) is broken.
Sell Setup (Optional):
If seeking short trades, reverse the rules:
The AMA and Supertrend should both be red, confirming a downtrend.
Enter the trade when the low of the trigger candle (the candle that turned the Supertrend red) is broken.
Stop-Loss and Targets:
Stop-Loss Placement: Set the stop-loss at the low of the trigger candle for long trades.
Risk-Reward Ratio: Aim for a 1:2 risk-reward ratio or use the Supertrend line as a trailing stop-loss, adjusting the stop-loss as the market moves in your favor.
Timeframes:
Swing Trading: Best suited for 1-hour (1H), 4-hour (4H), or Daily charts to capture larger price moves.
Intraday Trading: For more precise, quick setups, use 15-minute (15M) or 30-minute (30M) charts.
Why This Strategy Works:
Combination of Indicators: The strategy combines trend-following (AMA) with momentum-based entries (Supertrend), allowing you to enter trades at the optimal points in the market.
Filtered Trading Hours: Focusing on specific trading hours (8:30 AM to 10:30 PM IST) helps to filter out low-probability setups, reducing noise.
Clear Entry, Stop-Loss, and Target: Precise entry points, stop-loss placement, and targets ensure disciplined and calculated risk-taking.
Conclusion:
This Brokerir Gold Setup Strategy is tailored for traders who are seeking a structured and effective approach to trading Gold. By combining the power of AMA and Supertrend, traders can make informed, high-probability trades. Adhering to the specified trading hours, along with strict rules for entry, stop-loss, and profit targets, helps ensure consistent results. Remember to backtest the strategy and adjust based on market conditions. Let’s master the Gold market and maximize profits together!
⚡ Stay tuned with Brokerir for more advanced trading strategies and tips!
YCLK Al-Sat İndikatörüRSI Period (RSI Periyodu): Adjustable RSI period (default is 14).
Overbought Level (RSI Aşırı Alım): Sets the RSI threshold for overbought conditions (default is 70).
Oversold Level (RSI Aşırı Satım): Sets the RSI threshold for oversold conditions (default is 30).
Take Profit Ratio (Kâr Alma Oranı): Percentage ratio for take-profit levels (default is 1.05 or 5% profit).
Stop Loss Ratio (Zarar Durdurma Oranı): Percentage ratio for stop-loss levels (default is 0.95 or 5% loss).
RSI Calculation: The script calculates the Relative Strength Index (RSI) using the defined period.
Buy Signal: Generated when RSI crosses above the oversold level.
Sell Signal: Generated when RSI crosses below the overbought level.
Buy/Sell Signal Visualization:
Buy Signal: Green upward arrow labeled as "BUY".
Sell Signal: Red downward arrow labeled as "SELL".
Dynamic Take Profit and Stop Loss Levels:
Entry Price: Tracks the price at which a Buy signal occurs.
Take Profit (TP): Automatically calculated as Entry Price * Take Profit Ratio.
Stop Loss (SL): Automatically calculated as Entry Price * Stop Loss Ratio.
These levels are plotted on the chart with:
Blue circles for TP levels.
Red circles for SL levels.
Fibonacci Targets: The script also calculates Fibonacci levels based on the entry price:
Fibonacci 1.236 Level: Shown in purple.
Fibonacci 1.618 Level: Shown in orange.
Additional Visual Details:
Displays the current RSI value at each bar as a yellow label above the chart.
How to Use:
Apply the indicator to your TradingView chart.
Adjust the input parameters (RSI period, overbought/oversold levels, profit/loss ratios) based on your strategy.
Use the Buy and Sell signals to identify potential trade entries.
Use the TP and SL levels to manage risk and lock in profits.
Refer to the Fibonacci levels for extended profit targets.
MA Crossover with Demand/Supply Zones + Stop Loss/Take ProfitStop Loss and Take Profit Inputs:
Added stopLossPerc and takeProfitPerc as inputs to allow the user to define the stop loss and take profit levels as a percentage of the entry price.
Stop Loss and Take Profit Calculation:
For long positions, the stop loss is calculated as strategy.position_avg_price * (1 - stopLossPerc), and the take profit is calculated as strategy.position_avg_price * (1 + takeProfitPerc).
For short positions, the stop loss is calculated as strategy.position_avg_price * (1 + stopLossPerc), and the take profit is calculated as strategy.position_avg_price * (1 - takeProfitPerc).
Exit Strategy:
Added strategy.exit to define the stop loss and take profit levels for each trade. The from_entry parameter ensures that the exit is tied to the specific entry order.
Flexibility:
The stop loss and take profit levels are dynamic and adjust based on the entry price of the trade.
How It Works:
When a buy signal is generated (MA crossover near a demand zone), the strategy enters a long position and sets a stop loss and take profit level based on the input percentages.
When a sell signal is generated (MA crossunder near a supply zone), the strategy enters a short position and sets a stop loss and take profit level based on the input percentages.
The trade will exit automatically if either the stop loss or take profit level is hit.
Example:
If the entry price for a long position is $100, and the stop loss is set to 1% while the take profit is set to 2%:
Stop loss level =
100
∗
(
1
−
0.01
)
=
100∗(1−0.01)=99
Take profit level =
100
∗
(
1
+
0.02
)
=
100∗(1+0.02)=102
Notes:
You can adjust the stopLossPerc and takeProfitPerc inputs to suit your risk management preferences.
Always backtest the strategy to ensure the stop loss and take profit levels are appropriate for your trading instrument and timeframe.