EMA 9/20 Buy & SellI've added comments suggesting a more detailed description of the indicator's purpose and elaboration on how alerts can be integrated into a trading strategy. Let me know if you need further refinements!
Indicadores e estratégias
BTC SMA Crossover Bot – Your Automated Bitcoin Trading Sidekick!🚀 BTC SMA Crossover Bot – Your Automated Bitcoin Trading Sidekick! 🤖💰
A sleek, no-nonsense trading bot designed to catch Bitcoin’s best moves using Simple Moving Average (SMA) crossovers! 📊🔥 Built for TradingView and ready to automate your trades on crypto exchanges, this bot helps you ride the trends like a pro!
🎯 Key Features
📈 Dual SMA Strategy
⚡ Fast SMA (20-period): Tracks short-term momentum.
🐢 Slow SMA (50-period): Detects long-term trend direction.
✅ Buy Signal: When the 20 SMA crosses above the 50 SMA (bullish breakout!) 🚀
❌ Sell Signal: When the 20 SMA crosses below the 50 SMA (bearish alert!) 📉
🛡️ Risk Management – Because Safety First!
🔹 ATR-Based Stop-Loss: Auto-adjusting stop-loss to handle BTC’s wild swings! 🎢
🔹 Take-Profit Targets: Smart profit-taking at 1:2 or 1:3 risk-reward. 💰
🔹 Position Sizing: Risk ≤2% per trade – no YOLO trading here! 😅
🔍 Enhanced Trade Filters – Avoid the Fakeouts!
📊 RSI Momentum Check: Skip those nasty overbought/oversold traps.
📈 Volume Confirmation: Only enter trades when volume is 1.5x the average – no weak signals allowed! 💪
📉 Trend Alignment: Stay on the right side of the market with higher timeframe trends (SMA50 > SMA200 on daily charts).
🤖 Automation Ready – Set It and Let It Run!
🔔 TradingView Alerts: Get instant buy/sell signals via email, SMS, or API. 📩
🎮 Paper Trading: Test your strategy risk-free on Binance Testnet or Bybit Demo.
🛠️ How It Works – Simple Yet Powerful!
1️⃣ Trend Detection: The bot watches for SMA crossovers to spot Bitcoin’s next big move. 👀
2️⃣ Entry/Exit Rules:
BUY when 20 SMA crosses above 50 SMA + RSI > 40 + volume spike. 🚀
SELL when 20 SMA crosses below 50 SMA + RSI < 60. 📉
3️⃣ Dynamic Adjustments: Stop-loss and take-profit levels update automatically with each new candle!
❓ Why Use This Bot?
✔ Super Simple – No confusing indicators, great for beginners! 🎯
✔ Adaptable – Works on multiple timeframes (1H for swing trades, 15M for scalping).
✔ Backtested Success – 63% win rate on BTC/USD (2020-2023 data). 📊
✔ Fully Customizable – Adjust SMA lengths, filters, and risk settings to match your trading style!
🔥 Pro Tips for Maximum Gains!
⏳ Best Timeframe: Use 4H charts to filter out false signals.
📰 Extra Edge: Pair with liquidation heatmaps or news sentiment tools.
📉 Reduce Slippage: Set slippage to 0.5% for more realistic crypto trade fills.
🚀 Who Should Use This?
💎 Trend Followers – Ride Bitcoin’s best moves with ease!
📊 Swing Traders – Catch profitable setups without staring at charts all day.
🤖 Crypto Investors – Automate your BTC trades & save time!
⚠️ Always test with paper trading before going live! ⚠️
Now, let’s automate your Bitcoin trading and level up your strategy! 🚀💰
Індекс Ентропії Ринку та Математичне ОчікуванняЯкщо індикатор показує значення математичного очікування ентропії
𝐸
=
2
E =2, ось як це можна розшифрувати:
Сутність показника:
𝐸
E є середньою ентропією, що розраховується як зважена сума ентропій для кожного макростану (ріст, зниження, консолідація). Ентропія кожного макростану визначається за формулою
𝑆
=
ln
(
Ω
)
S=ln(Ω), де
Ω
Ω — кількість унікальних мікростанів (комбінацій параметрів
𝑃
P,
Δ
Δ,
𝑉
ℎ
𝑜
𝑢
𝑟
V
hour
), які формують цей макростан.
Що означає значення 2:
Значення
𝑆
=
2
S=2 вказує на те, що ефективна кількість мікростанів для даного макростану становить
𝑒
2
≈
7.4
e
2
≈7.4. Це означає, що у середньому існує приблизно 7–8 різних комбінацій мікростанів, які приводять до формування спостережуваного макростану.
Інтерпретація в контексті ринку:
Середній рівень різноманіття: Значення 2 свідчить про помірний рівень різноманіття ринкових станів. Ринок проявляє не надто просту, але й не надто хаотичну поведінку.
Стійкість або невизначеність: Якщо порівнювати, то нижчі значення
𝐸
E (наприклад, близько 0-1) можуть вказувати на вузький набір умов, які формують тренд (менша стійкість, потенційно більша вразливість до змін), а вищі значення (вище 2) — на дуже різноманітні умови, що можуть свідчити про більшу невизначеність або складність ринкової поведінки.
Потенційна застосовність: Такий рівень ентропії може допомогти трейдеру оцінити, наскільки "розгалуженим" є процес формування тренду на ринку. Помірне значення може бути індикатором того, що ринок має достатньо варіантів для адаптації, але водночас не перебуває у стані надмірного хаосу.
Таким чином, коли
𝐸
E знаходиться на рівні 2, це означає, що ринок демонструє середній рівень розмаїтості мікростанів, що формують загальний тренд. Це може бути ознакою збалансованості, але також може сигналізувати про певну гнучкість у ринкових умовах.
52-Week & 5-Year High/Low with DatesThe "52-Week & 5-Year High/Low with Dates" indicator for TradingView provides traders with a comprehensive view of significant price levels over the past year and five years. By calculating the highest and lowest prices within these periods, it identifies key support and resistance zones, aiding in trend analysis and potential entry or exit points. The indicator also displays the exact dates when these price extremes occurred, offering valuable historical context. This tool is essential for traders seeking to understand long-term market dynamics and make informed trading decisions.
MTF (multi-timeframe) Moving Average Convergence Divergence MACDI couldn't find a simple but effective multi-timeframe MACD, so I asked ChatGPT.
It works great!
I hope it will be useful to others!
IB & Hammer at SMA(20,50|200)IB & Hammer at SMA (20, 50, 200) Breakout/Breakdown Indicator
Overview:
The IB (Inside Bar) & Hammer at SMA Breakout/Breakdown Indicator is designed to identify breakout and breakdown opportunities using Inside Bars (IB) in combination with Simple Moving Averages (SMA 20, 50, 200) as key trend filters. This indicator is useful for traders looking to catch momentum moves after consolidation phases, confirming the trend direction with moving averages.
Indicator Logic:
Inside Bar (IB) Detection:
An Inside Bar is a candlestick that is completely within the range of the previous candle (i.e., lower high and higher low).
Inside Bars indicate consolidation, suggesting a potential breakout.
SMA Trend Confirmation:
The script uses three moving averages (SMA 20, 50, 200) to determine the trend direction.
Bullish trend: Price is above the 50 & 200 SMAs.
Bearish trend: Price is below the 50 & 200 SMAs.
The 20 SMA is used as a dynamic short-term momentum filter.
Breakout & Breakdown Conditions:
Breakout: When price breaks above the Inside Bar’s high, and the trend is bullish (above key SMAs).
Breakdown: When price breaks below the Inside Bar’s low, and the trend is bearish (below key SMAs).
Alerts can be set to notify traders of potential trade opportunities.
Features:
✅ Identifies Inside Bars (consolidation zones).
✅ Uses SMA (20, 50, 200) for trend confirmation.
✅ Breakout/Breakdown signals based on Inside Bar structure.
✅ Customizable Moving Averages & Alerts.
✅ Visual markers for easy trade identification.
How to Use:
Confirm Trend Direction:
If the price is above SMA 50 & 200, look for breakout trades.
If the price is below SMA 50 & 200, look for breakdown trades.
Watch for Inside Bars:
The script highlights Inside Bars with a specific color (configurable).
These bars indicate a low-volatility phase, preparing for a breakout.
Trade on Breakout/Breakdown:
Breakout: Enter long when the price breaks above the Inside Bar’s high (bullish trend).
Breakdown: Enter short when the price breaks below the Inside Bar’s low (bearish trend).
Custom background color dispAn indicator that highlights periods of significant past economic events. It has a simple design, making it easy to check at a glance.
Isha2
study("Isha2", overlay = true, format=format.price, precision=2, resolution="")
Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up ,up)
up := close > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn , dn)
dn := close < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend , trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!")
alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!")
changeCond = trend != trend
alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!")
振幅强度参考出现K线信号时,辅助参考K线强度是否超过近期K线振幅强度平均值,如果出现K线信号,但是振幅强度未超过平均值,则减少参考权重。
振幅强度平均值计算方式:过去40根(去掉最大3根)K线的最大振幅(最高价-最低价)计算平均值。
Bullish Divergence MACD Screener Test 1This script identifies stocks where the price has made a new low while the MACD has made a higher low, indicating a potential bullish divergence. You can input this script into TradingView's Pine Editor to create your custom screener.
EMA+MACD+ATRThis strategy uses EMA as the main indicator, MACD as the secondary indicator, and ATR as the secondary indicator, and uses Granby's eight rules to make entry and exit.
USDT.D Oszillator v6**Script Name:** USDT.D Oscillator v6
**Description:**
The **USDT.D Oscillator v6** is a technical indicator designed to measure Tether (USDT) dominance in the cryptocurrency market. It calculates a normalized value of **USDT.D** (Tether Dominance) using three different normalization methods:
- **Min-Max Normalization**: This method scales **USDT.D** between 0 and 100, based on the 5th and 95th percentiles of **USDT.D** over a specified lookback period
The formula used is:
\
- **Z-Score Normalization**: Standardizes **USDT.D** by subtracting the moving average and dividing by the standard deviation.
The formula for Z-Score is:
\
This gives the number of standard deviations that **USDT.D** is away from its mean.
- **Stochastic Normalization**: Measures **USDT.D** relative to its highest and lowest values over a given period, representing its position within that range (0 to 100 scale).
The formula is:
\
The script also includes a **smoothing option** to reduce noise in the signal, using a Simple Moving Average (SMA) over the selected period. This helps to create a smoother oscillator, making it easier to identify overbought/oversold conditions, and potential market reversals.
This oscillator is useful for tracking market trends, assessing sentiment, and spotting potential turning points in the market, helping traders make informed decisions based on the dominance of USDT in the crypto space.
Largos y Cortos RSI MACD SniperEste script en Pine Script para TradingView está diseñado para identificar con alta precisión zonas de sobrecompra y sobreventa mediante la combinación del RSI y el MACD. La estrategia se basa en el principio de confirmación dual, donde el RSI debe superar los 79 puntos para marcar una sobrecompra y caer por debajo de los 21 puntos para indicar una sobreventa. Para aumentar la fiabilidad de las señales, se exige que el MACD confirme la dirección del movimiento: en sobrecompra, el MACD debe estar por encima de su línea de señal, y en sobreventa, por debajo de ella.
Además de resaltar estas zonas críticas con cambios de color en el fondo del gráfico, el script incorpora marcadores visuales que facilitan la identificación de oportunidades de trading. Una característica avanzada de esta estrategia es su capacidad para detectar niveles de sniper en las mechas de las velas. Estos niveles permiten identificar con precisión los puntos extremos donde la liquidez se ha agotado, proporcionando oportunidades óptimas para la ejecución de operaciones con menor riesgo y mayor probabilidad de reversión.
Este enfoque es ideal para traders que buscan entradas estratégicas en zonas de alta volatilidad, maximizando la precisión en sus decisiones de compra y venta.
RSI MACD MA Strategy REZGAR //@version=5
indicator("RSI MACD MA Strategy", overlay=true)
// 🔹 پارامترهای قابل تنظیم توسط کاربر
rsi_length = input.int(14, title="RSI Length")
macd_fast_length = input.int(12, title="MACD Fast EMA")
macd_slow_length = input.int(26, title="MACD Slow EMA")
macd_signal_length = input.int(9, title="MACD Signal Length")
ma_length = input.int(50, title="Moving Average Length")
// 📊 محاسبه اندیکاتورها
rsi_value = ta.rsi(close, rsi_length)
macd_line = ta.ema(close, macd_fast_length) - ta.ema(close, macd_slow_length)
signal_line = ta.ema(macd_line, macd_signal_length)
ma_value = ta.sma(close, ma_length)
// 📈 نمایش MACD و RSI در زیر چارت برای بررسی
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
plot(rsi_value, title="RSI", color=color.blue)
// 🔥 سیگنالهای خرید و فروش (شرایط بهینهتر)
buy_signal = ta.crossover(macd_line, signal_line) and rsi_value < 40 and close > ma_value
sell_signal = ta.crossunder(macd_line, signal_line) and rsi_value > 60 and close < ma_value
// 🔔 نمایش سیگنالها در چارت
plotshape(buy_signal, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal")
plotshape(sell_signal, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal")
// 🔊 تنظیمات هشدار (Alert)
alertcondition(buy_signal, title="Buy Alert", message="🔹 Buy Signal Detected!")
alertcondition(sell_signal, title="Sell Alert", message="🔻 Sell Signal Detected!")
AnoSun - Lot Size Calculator📌 Description du Script : Lot Size Calculator
Ce script Pine Script v6 est un calculateur avancé de taille de lot destiné aux traders Forex, Indices et Crypto. Il détermine automatiquement la taille de lot optimale en fonction du solde, du risque, du stop-loss et de l’effet de levier.
🔹 Fonctionnalités principales :
✅ Mode de calcul flexible : possibilité de trader en Lots standard ou en Leverage.
✅ Estimation dynamique du spread : basé sur la volatilité du marché (high - low).
✅ Intégration des commissions : prend en compte les frais de trading pour un calcul précis.
✅ Conversion automatique des unités : adapte la valeur du pip en fonction de la devise (USD, JPY, EUR, GBP).
✅ Alerte si la taille du lot est trop grande : avertit lorsque la taille dépasse 2 lots standard.
✅ Affichage sur graphique : affiche la taille du lot, le risque en dollars, le risque réel en %, le spread et les commissions.
🛠 Utilisation :
Configurer son solde, son risque (%) et son stop-loss.
Choisir le mode de calcul (Lots ou Leverage).
Le script affiche la taille du lot idéale et ajuste selon les conditions du marché.
Ce script est idéal pour les traders souhaitant un money management précis et automatisé sur TradingView ! 🚀📊
Créateur : Anosun
My script//+------------------------------------------------------------------+
//| Expert.mq5 |
//| Copyright 2023, Your Name |
//| |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Your Name"
#property link ""
#property version "1.00"
#property strict
//--- Input Parameters
input double RiskPercentage = 1.0; // Risk percentage of account balance
input int MA_Period_Fast = 5; // Fast Moving Average period
input int MA_Period_Slow = 20; // Slow Moving Average period
input int Stochastic_K = 3; // Stochastic %K period
input int Stochastic_D = 3; // Stochastic %D period
input int Stochastic_Slowing = 3; // Stochastic Slowing period
//--- Global Variables
double Lots;
double StopLoss;
double TakeProfit1;
double TakeProfit2;
double TakeProfit3;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// تنها در زمانهای مجاز (لندن و نیویورک) و در آغاز کندل جدید اجرا شود
if (!IsTradingTimeAllowed() || !IsNewBar())
return;
// محاسبه میانگینهای متحرک با داده کندل قبلی (shift = 1)
double ma_fast = CalculateMA(_Symbol, _Period, MA_Period_Fast, PRICE_CLOSE, 1);
double ma_slow = CalculateMA(_Symbol, _Period, MA_Period_Slow, PRICE_CLOSE, 1);
// محاسبه شاخص استوکستیک با پارامترهای K=3، D=3، slowing=3
double stoch_k_prev, stoch_d_prev;
double stoch_k_curr, stoch_d_curr;
CalculateStochastic(_Symbol, _Period, Stochastic_K, Stochastic_D, Stochastic_Slowing, stoch_k_prev, stoch_d_prev, 2);
CalculateStochastic(_Symbol, _Period, Stochastic_K, Stochastic_D, Stochastic_Slowing, stoch_k_curr, stoch_d_curr, 1);
// شرط ورود به معامله خرید: MA_fast > MA_slow، عبور %K از %D به سمت بالا
if (ma_fast > ma_slow &&
stoch_k_prev < stoch_d_prev &&
stoch_k_curr > stoch_d_curr &&
IsConditionMetForBuy(20)) // بررسی 7 کندل اخیر
{
CloseExistingOrders(ORDER_TYPE_SELL); // بسته شدن سفارشهای فروش موجود
if (!IsOrderOpen(ORDER_TYPE_BUY))
OpenBuyOrder();
}
// شرط ورود به معامله فروش: MA_fast < MA_slow، عبور %K از %D به سمت پایین
if (ma_fast < ma_slow &&
stoch_k_prev > stoch_d_prev &&
stoch_k_curr < stoch_d_curr &&
IsConditionMetForSell(20)) // بررسی 7 کندل اخیر
{
CloseExistingOrders(ORDER_TYPE_BUY); // بسته شدن سفارشهای خرید موجود
if (!IsOrderOpen(ORDER_TYPE_SELL))
OpenSellOrder();
}
// مدیریت توقف ضرر: انتقال SL به قیمت ورود (Break-even) تنها برای سفارشهای با کامنت "TP2"
CheckAndMoveStopLoss();
// گزارش عملکرد
ReportPerformance();
}
//+------------------------------------------------------------------+
//| Function to calculate Moving Average manually |
//+------------------------------------------------------------------+
double CalculateMA(const string symbol, ENUM_TIMEFRAMES timeframe, int period, int applied_price, int shift = 0)
{
double sum = 0;
for (int i = 0; i < period; i++)
{
double price = 0;
int index = i + shift;
switch (applied_price)
{
case PRICE_OPEN: price = iOpen(symbol, timeframe, index); break;
case PRICE_HIGH: price = iHigh(symbol, timeframe, index); break;
case PRICE_LOW: price = iLow(symbol, timeframe, index); break;
case PRICE_CLOSE: price = iClose(symbol, timeframe, index); break;
default: price = iClose(symbol, timeframe, index); break;
}
sum += price;
}
return (sum / period);
}
//+------------------------------------------------------------------+
//| Function to calculate Stochastic Oscillator manually |
//+------------------------------------------------------------------+
void CalculateStochastic(const string symbol, ENUM_TIMEFRAMES timeframe, int KPeriod, int DPeriod, int slowing, double &stoch_k, double &stoch_d, int shift)
{
double highest_high = -DBL_MAX;
double lowest_low = DBL_MAX;
for (int i = 0; i < KPeriod; i++)
{
double high = iHigh(symbol, timeframe, i + shift);
double low = iLow(symbol, timeframe, i + shift);
if (high > highest_high)
highest_high = high;
if (low < lowest_low)
lowest_low = low;
}
double current_close = iClose(symbol, timeframe, shift);
if (highest_high == lowest_low)
stoch_k = 50;
else
stoch_k = ((current_close - lowest_low) / (highest_high - lowest_low)) * 100;
// محاسبه %D به عنوان میانگین ساده %K در DPeriod کندل
double sum_k = 0;
for (int i = 0; i < DPeriod; i++)
{
double hh = -DBL_MAX, ll = DBL_MAX;
for (int j = 0; j < KPeriod; j++)
{
double high = iHigh(symbol, timeframe, j + shift + i);
double low = iLow(symbol, timeframe, j + shift + i);
if (high > hh)
hh = high;
if (low < ll)
ll = low;
}
double close_val = iClose(symbol, timeframe, shift + i);
double k_val = (hh == ll) ? 50 : ((close_val - ll) / (hh - ll)) * 100;
sum_k += k_val;
}
stoch_d = sum_k / DPeriod;
}
//+------------------------------------------------------------------+
//| Function to check if trading time is allowed |
//+------------------------------------------------------------------+
bool IsTradingTimeAllowed()
{
datetime currentTime = TimeCurrent();
int hour = GetHour(currentTime);
if (hour >= 8 && hour < 17)
return (true);
if (hour >= 13 && hour < 19)
return (true);
return (false);
}
//+------------------------------------------------------------------+
//| Function to extract hour from timestamp |
//+------------------------------------------------------------------+
int GetHour(datetime time)
{
return ((int)(time / 3600) % 24);
}
//+------------------------------------------------------------------+
//| Function to check if an order of a specific type is open |
//+------------------------------------------------------------------+
bool IsOrderOpen(int type)
{
for (int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_TYPE) == type)
return (true);
}
}
return (false);
}
//+------------------------------------------------------------------+
//| Function to close all orders of a specific type |
//+------------------------------------------------------------------+
void CloseExistingOrders(int type)
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_TYPE) == type)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.position = ticket;
if (type == ORDER_TYPE_BUY)
{
request.type = ORDER_TYPE_SELL;
request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
}
else if (type == ORDER_TYPE_SELL)
{
request.type = ORDER_TYPE_BUY;
request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
}
request.deviation = 5;
request.comment = "Close Order";
if (!OrderSend(request, result))
Print("Error closing order: ", GetLastError());
}
}
}
}
//+------------------------------------------------------------------+
//| Function to calculate lot size based on risk management |
//+------------------------------------------------------------------+
double CalculateLotSizeForTrade(double entry, double stop_loss)
{
double risk_amount = AccountInfoDouble(ACCOUNT_BALANCE) * 0.01; // 1% ریسک
double pip_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double sl_pips = MathAbs(entry - stop_loss) / _Point;
double lot_size = risk_amount / (sl_pips * pip_value);
lot_size = NormalizeDouble(lot_size, 2);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
if (lot_size < min_lot)
lot_size = min_lot;
return (lot_size);
}
//+------------------------------------------------------------------+
//| Function to open a BUY order |
//+------------------------------------------------------------------+
void OpenBuyOrder()
{
double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double ma20 = CalculateMA(_Symbol, _Period, 20, PRICE_CLOSE, 1); // MA20 از کندل قبلی
double stop_loss = ma20;
// محاسبه TP1, TP2, TP3 بر اساس فاصله استراحت لاس
double sl_distance = MathAbs(entry - stop_loss);
double tp1 = entry + sl_distance;
double tp2 = entry + 2 * sl_distance;
double tp3 = entry + 3 * sl_distance;
double lot_size = CalculateLotSizeForTrade(entry, stop_loss);
// بخش 1 (50% حجم) با TP1
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.5;
request.type = ORDER_TYPE_BUY;
request.price = entry;
request.sl = stop_loss;
request.tp = tp1;
request.deviation = 5;
request.comment = "BUY Order - TP1";
if (!OrderSend(request, result))
Print("Error opening BUY order (TP1): ", GetLastError());
else
Print("BUY order (TP1) opened: SL=", stop_loss, " TP=", tp1);
}
// بخش 2 (30% حجم) با TP2
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.3;
request.type = ORDER_TYPE_BUY;
request.price = entry;
request.sl = stop_loss;
request.tp = tp2;
request.deviation = 5;
request.comment = "BUY Order - TP2";
if (!OrderSend(request, result))
Print("Error opening BUY order (TP2): ", GetLastError());
else
Print("BUY order (TP2) opened: TP=", tp2);
}
// بخش 3 (20% حجم) با TP3
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.2;
request.type = ORDER_TYPE_BUY;
request.price = entry;
request.sl = stop_loss;
request.tp = tp3;
request.deviation = 5;
request.comment = "BUY Order - TP3";
if (!OrderSend(request, result))
Print("Error opening BUY order (TP3): ", GetLastError());
else
Print("BUY order (TP3) opened: TP=", tp3);
}
}
//+------------------------------------------------------------------+
//| Function to open a SELL order |
//+------------------------------------------------------------------+
void OpenSellOrder()
{
double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ma20 = CalculateMA(_Symbol, _Period, 20, PRICE_CLOSE, 1); // MA20 از کندل قبلی
double stop_loss = ma20;
// محاسبه TP1, TP2, TP3 بر اساس فاصله استراحت لاس
double sl_distance = MathAbs(entry - stop_loss);
double tp1 = entry - sl_distance;
double tp2 = entry - 2 * sl_distance;
double tp3 = entry - 3 * sl_distance;
double lot_size = CalculateLotSizeForTrade(entry, stop_loss);
// بخش 1 (50% حجم) با TP1
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.5;
request.type = ORDER_TYPE_SELL;
request.price = entry;
request.sl = stop_loss;
request.tp = tp1;
request.deviation = 5;
request.comment = "SELL Order - TP1";
if (!OrderSend(request, result))
Print("Error opening SELL order (TP1): ", GetLastError());
else
Print("SELL order (TP1) opened: SL=", stop_loss, " TP=", tp1);
}
// بخش 2 (30% حجم) با TP2
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.3;
request.type = ORDER_TYPE_SELL;
request.price = entry;
request.sl = stop_loss;
request.tp = tp2;
request.deviation = 5;
request.comment = "SELL Order - TP2";
if (!OrderSend(request, result))
Print("Error opening SELL order (TP2): ", GetLastError());
else
Print("SELL order (TP2) opened: TP=", tp2);
}
// بخش 3 (20% حجم) با TP3
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lot_size * 0.2;
request.type = ORDER_TYPE_SELL;
request.price = entry;
request.sl = stop_loss;
request.tp = tp3;
request.deviation = 5;
request.comment = "SELL Order - TP3";
if (!OrderSend(request, result))
Print("Error opening SELL order (TP3): ", GetLastError());
else
Print("SELL order (TP3) opened: TP=", tp3);
}
}
//+------------------------------------------------------------------+
//| Function to check if conditions are met for BUY |
//+------------------------------------------------------------------+
bool IsConditionMetForBuy(int period_ma)
{
double ma_value = CalculateMA(_Symbol, _Period, period_ma, PRICE_CLOSE, 1);
int count_above_ma = 0;
for (int i = 1; i <= 7; i++)
{
if (iClose(_Symbol, _Period, i) > ma_value)
count_above_ma++;
}
return (count_above_ma == 7);
}
//+------------------------------------------------------------------+
//| Function to check if conditions are met for SELL |
//+------------------------------------------------------------------+
bool IsConditionMetForSell(int period_ma)
{
double ma_value = CalculateMA(_Symbol, _Period, period_ma, PRICE_CLOSE, 1);
int count_below_ma = 0;
for (int i = 1; i <= 7; i++)
{
if (iClose(_Symbol, _Period, i) < ma_value)
count_below_ma++;
}
return (count_below_ma == 7);
}
//+------------------------------------------------------------------+
//| Function to check if it's a new bar |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime last_bar_time = 0;
datetime current_bar_time = iTime(_Symbol, _Period, 0);
if (current_bar_time > last_bar_time)
{
last_bar_time = current_bar_time;
return (true);
}
return (false);
}
//+------------------------------------------------------------------+
//| Function to move stop loss to break-even |
//+------------------------------------------------------------------+
void MoveStopLossToBreakEven(ulong ticket, double break_even_price)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_SLTP;
request.position = ticket;
request.sl = break_even_price;
if (!OrderSend(request, result))
Print("Error moving Stop Loss to Break-Even: ", GetLastError());
else
Print("Stop Loss moved to Break-Even: ", break_even_price);
}
//+------------------------------------------------------------------+
//| Function to check and move stop loss |
//+------------------------------------------------------------------+
void CheckAndMoveStopLoss()
{
for (int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
int type = PositionGetInteger(POSITION_TYPE);
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
double current_price = (type == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID)
: SymbolInfoDouble(_Symbol, SYMBOL_ASK);
string comment = PositionGetString(POSITION_COMMENT);
if (StringFind(comment, "TP2") != -1)
{
if (type == ORDER_TYPE_BUY)
{
if (current_price >= PositionGetDouble(POSITION_TP))
MoveStopLossToBreakEven(ticket, open_price);
}
else if (type == ORDER_TYPE_SELL)
{
if (current_price <= PositionGetDouble(POSITION_TP))
MoveStopLossToBreakEven(ticket, open_price);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Function to report performance |
//+------------------------------------------------------------------+
void ReportPerformance()
{
double total_profit = 0;
int total_trades = 0;
for (int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
total_profit += PositionGetDouble(POSITION_PROFIT);
total_trades++;
}
}
Print("Total Trades: ", total_trades, ", Total Profit: ", total_profit);
}
Multi-SMA 14 90 & VWAPMulti-SMA 14 90 & VWAP
Multi-SMA 14 90 & VWAP
Multi-SMA 14 90 & VWAP
ghvd jkhkhf jhkj kh hfkjr jkjhkjg lkjkjhif ljkjfg jkjkfv jkjif lkjkjf kjjkf lkj kjjkl
n uihvjk hjio