//+------------------------------------------------------------------+
//| IBR.mq5 |
//| Forex Robot |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Forex Robot"
#property link "https://www.mql5.com"
#property version "1.02" // Increased version for fixes
#property strict
// --- CORRECTED INCLUDE PATHS ---
#include <Trade/Trade.mqh>
#include <ChartObjects/ChartObjects.mqh> // For object functions
#include <Math/Math.mqh> // For MathAbs, DBL_MAX etc.
//--- Input Parameters ---
input string GeneralSettings = "--- General Settings ---";
input long EA_MagicNumber = 12345;
input int NY_TimeZone_Offset = -4; // -4 for EDT, -5 for EST (Adjust manually based on DST)
input string TimeSettings = "--- IOB Time Range (NY Time) ---";
input int StartTime_Hours = 8;
input int StartTime_Minutes = 20;
input int EndTime_Hours = 9;
input int EndTime_Minutes = 20;
input string RiskSettings = "--- Trading Settings ---";
input double Fixed_Lot_Size = 0.1;
input double Risk_Percentage = 1.0; // e.g., 1.0 for 1% risk
input bool Use_Risk_Management = true;
input string TrailingSettings = "--- Trailing Stop ---";
input bool Use_Trailing_Stop = true;
input double Trailing_Stop_Pips= 20; // Pips to trail by
input double Trailing_Stop_Step= 5; // Pips step for trailing
input string BreakevenSettings = "--- Breakeven ---";
input bool Use_Breakeven = true;
input double Breakeven_Trigger_Pips = 10; // Pips profit to trigger breakeven
input double Breakeven_Pips = 2; // Move SL to BE + this amount (in pips)
input string Visuals = "--- Visual Settings ---";
input bool Draw_IOB_Lines = true;
input bool Draw_Fibonacci_Lines = true;
//+------------------------------------------------------------------+
//--- Global Variables ---
CTrade m_trade;
static bool is_range_found = false;
static double iob_high = 0;
static double iob_low = 0;
static long position_ticket = 0;
static ENUM_POSITION_TYPE position_type;
static datetime current_day = 0; // To track daily reset
// --- Fibonacci Levels ---
static double fib_45_level = 0;
static double fib_80_level = 0;
static double fib_minus1_level = 0;
// Internal states
static bool breakout_occurred_bullish = false;
static bool breakout_occurred_bearish = false;
// --- Helper Functions Prototypes ---
datetime GetServerTimeFromNY(int hours, int minutes);
bool FindIOBRange();
void CalculateAndPlotFibonacci(bool is_bullish_breakout);
double CalculateLotSize(ENUM_POSITION_TYPE type, double sl_price);
void ManagePosition(long ticket);
void DeleteAllObjects(string prefix);
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
if(_Period != PERIOD_M3)
{
Print("This EA is designed for the M3 (3-minute) chart. Please attach it to an M3 chart.");
return INIT_FAILED;
}
m_trade.SetExpertMagicNumber(EA_MagicNumber);
m_trade.SetDeviationInPoints(5);
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check for new day to reset logic
datetime new_day_time_local = (datetime)TimeCurrent();
new_day_time_local = new_day_time_local - (new_day_time_local % (24 * 60 * 60));
if (new_day_time_local > current_day)
{
current_day = new_day_time_local;
is_range_found = false;
position_ticket = 0;
breakout_occurred_bullish = false;
breakout_occurred_bearish = false;
DeleteAllObjects("IOB_");
DeleteAllObjects("FIB_");
}
static datetime prev_bar_time = 0;
datetime current_bar_time = iTime(_Symbol, _Period, 0);
if (current_bar_time == prev_bar_time && position_ticket == 0) return;
prev_bar_time = current_bar_time;
// Phase 1: Find IOB Range
if (!is_range_found && TimeCurrent() >= GetServerTimeFromNY(EndTime_Hours, EndTime_Minutes))
{
if (FindIOBRange()) is_range_found = true;
else return; // If range not found, wait for next tick
}
if (!is_range_found) return;
// Phase 2 & 3: Check Breakout, Plot Fibs, and Wait for Entry
if (position_ticket == 0)
{
double current_bar_close = iClose(_Symbol, _Period, 1); // Check close of the PREVIOUS bar
if (!breakout_occurred_bullish && !breakout_occurred_bearish)
{
if (current_bar_close > iob_high) // Bullish Breakout
{
breakout_occurred_bullish = true;
CalculateAndPlotFibonacci(true);
}
else if (current_bar_close < iob_low) // Bearish Breakout
{
breakout_occurred_bearish = true;
CalculateAndPlotFibonacci(false);
}
}
// Check for trade entry if a breakout has been confirmed
if (breakout_occurred_bullish)
{
if (SymbolInfoDouble(_Symbol, SYMBOL_BID) <= fib_45_level) // Price taps the 45% level from above
{
if(m_trade.Buy(CalculateLotSize(POSITION_TYPE_BUY, fib_80_level), _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_ASK), fib_80_level, fib_minus1_level, "IBR Buy"))
{
// --- CORRECTED: Get result *after* successful trade ---
position_ticket = m_trade.ResultPosition();
position_type = POSITION_TYPE_BUY;
}
}
}
else if (breakout_occurred_bearish)
{
if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) >= fib_45_level) // Price taps the 45% level from below
{
if(m_trade.Sell(CalculateLotSize(POSITION_TYPE_SELL, fib_80_level), _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_BID), fib_80_level, fib_minus1_level, "IBR Sell"))
{
// --- CORRECTED: Get result *after* successful trade ---
position_ticket = m_trade.ResultPosition();
position_type = POSITION_TYPE_SELL;
}
}
}
}
// Phase 4: Manage Open Position
if (position_ticket != 0)
{
ManagePosition(position_ticket);
}
}
//+------------------------------------------------------------------+
//| Helper Functions |
//+------------------------------------------------------------------+
datetime GetServerTimeFromNY(int hours, int minutes)
{
// Get current GMT
datetime gmt_time = TimeGMT();
// Calculate NY time by applying offset
datetime ny_time = gmt_time + (NY_TimeZone_Offset * 3600);
// Deconstruct NY time to get today's date parts
MqlDateTime dt_ny;
TimeToStruct(ny_time, dt_ny);
// Set the desired time (hours, minutes) for today in NY
dt_ny.hour = hours;
dt_ny.min = minutes;
dt_ny.sec = 0;
// Convert this NY datetime back to a timestamp
datetime target_ny_timestamp = StructToTime(dt_ny);
// Convert the target NY timestamp back to GMT
datetime target_gmt_timestamp = target_ny_timestamp - (NY_TimeZone_Offset * 3600);
// Convert target GMT time to local server time for comparison
long server_offset = TimeCurrent() - TimeGMT();
return target_gmt_timestamp + server_offset;
}
bool FindIOBRange()
{
datetime start_time = GetServerTimeFromNY(StartTime_Hours, StartTime_Minutes);
datetime end_time = GetServerTimeFromNY(EndTime_Hours, EndTime_Minutes);
int start_bar_idx = iBarShift(_Symbol, _Period, start_time, false);
int end_bar_idx = iBarShift(_Symbol, _Period, end_time, false);
if(start_bar_idx < 0 || end_bar_idx < 0) return false;
double highs[], lows[];
int bars_to_copy = start_bar_idx - end_bar_idx + 1;
if(CopyHigh(_Symbol, _Period, end_bar_idx, bars_to_copy, highs) <= 0) return false;
if(CopyLow(_Symbol, _Period, end_bar_idx, bars_to_copy, lows) <= 0) return false;
iob_high = highs[ArrayMaximum(highs)];
iob_low = lows[ArrayMinimum(lows)];
if (iob_high <= iob_low) return false;
// Draw IOB lines if enabled
if(Draw_IOB_Lines)
{
ObjectCreate(0, "IOB_High", OBJ_HLINE, 0, 0, iob_high);
ObjectSetInteger(0, "IOB_High", OBJPROP_COLOR, clrRed);
ObjectCreate(0, "IOB_Low", OBJ_HLINE, 0, 0, iob_low);
ObjectSetInteger(0, "IOB_Low", OBJPROP_COLOR, clrBlue);
}
Print("IOB Range found: High=", DoubleToString(iob_high, _Digits), ", Low=", DoubleToString(iob_low, _Digits));
return true;
}
void CalculateAndPlotFibonacci(bool is_bullish_breakout)
{
DeleteAllObjects("FIB_"); // Clear previous Fibonacci objects
double fib_anchor0_price, fib_anchor1_price;
if (is_bullish_breakout)
{
fib_anchor0_price = iob_low; // 0% level
fib_anchor1_price = iob_high; // 100% level
}
else // Bearish breakout
{
fib_anchor0_price = iob_high; // 0% level
fib_anchor1_price = iob_low; // 100% level
}
double range = MathAbs(fib_anchor1_price - fib_anchor0_price);
// Calculate absolute prices for the levels
if (is_bullish_breakout)
{
fib_45_level = fib_anchor0_price + 0.45 * range;
fib_80_level = fib_anchor0_price + 0.80 * range;
fib_minus1_level = fib_anchor0_price - 1.0 * range;
}
else // Bearish breakout
{
fib_45_level = fib_anchor0_price - 0.45 * range;
fib_80_level = fib_anchor0_price - 0.80 * range;
fib_minus1_level = fib_anchor0_price + 1.0 * range;
}
if (!Draw_Fibonacci_Lines) return; // Don't draw if disabled
// --- Draw the visual Fibonacci object ---
string fib_name = "FIB_Levels_" + (string)TimeCurrent();
ObjectCreate(0, fib_name, OBJ_FIBO, 0, iTime(_Symbol, _Period, 10), fib_anchor0_price, iTime(_Symbol, _Period, 0), fib_anchor1_price);
ObjectSetInteger(0, fib_name, OBJPROP_COLOR, clrDarkGray);
ObjectSetInteger(0, fib_name, OBJPROP_STYLE, STYLE_DOT);
ObjectSetInteger(0, fib_name, OBJPROP_LEVELS, 3);
ObjectSetDouble(0, fib_name, OBJPROP_LEVELVALUE, 0, 0.45);
ObjectSetString(0, fib_name, OBJPROP_LEVELTEXT, 0, "45% (Entry)");
ObjectSetDouble(0, fib_name, OBJPROP_LEVELVALUE, 1, 0.80);
ObjectSetString(0, fib_name, OBJPROP_LEVELTEXT, 1, "80% (SL)");
ObjectSetDouble(0, fib_name, OBJPROP_LEVELVALUE, 2, -1.0);
ObjectSetString(0, fib_name, OBJPROP_LEVELTEXT, 2, "-100% (TP)");
ChartRedraw();
}
double CalculateLotSize(ENUM_POSITION_TYPE type, double sl_price)
{
if (!Use_Risk_Management) return Fixed_Lot_Size;
double lot_size = 0.01;
double account_balance = AccountInfoDouble(ACCOUNT_BALANCE);
double risk_amount = account_balance * (Risk_Percentage / 100.0);
double entry_price = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
double stop_loss_pips = MathAbs(entry_price - sl_price) / _Point;
if(stop_loss_pips <= 0)
{
Print("Stop loss distance is zero, cannot calculate lot size. Using min lot.");
return SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
}
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tick_size <= 0) tick_size = _Point;
double pip_value_per_lot = (tick_value / tick_size) * _Point;
if(pip_value_per_lot <= 0)
{
Print("Could not determine pip value. Using min lot.");
return SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
}
lot_size = risk_amount / (stop_loss_pips * pip_value_per_lot);
return NormalizeDouble(lot_size, 2);
}
void ManagePosition(long ticket)
{
if(!PositionSelectByTicket(ticket))
{
position_ticket = 0; // Reset as position is closed
return;
}
double current_sl = PositionGetDouble(POSITION_SL);
double current_price = (position_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
double profit_pips = (current_price - entry_price) / _Point;
if (position_type == POSITION_TYPE_SELL) profit_pips *= -1;
// Breakeven
if (Use_Breakeven && profit_pips >= Breakeven_Trigger_Pips)
{
double new_sl_price = entry_price + Breakeven_Pips * _Point * (position_type == POSITION_TYPE_BUY ? 1 : -1);
if ((position_type == POSITION_TYPE_BUY && new_sl_price > current_sl) ||
(position_type == POSITION_TYPE_SELL && new_sl_price < current_sl))
{
if (!m_trade.PositionModify(ticket, new_sl_price, PositionGetDouble(POSITION_TP)))
{
// --- CORRECTED ERROR PRINTING ---
Print("Breakeven failed: ", m_trade.ResultRetcode(), " - ", m_trade.ResultRetcodeDescription());
}
}
}
// Trailing Stop
if (Use_Trailing_Stop)
{
double new_sl_price;
if (position_type == POSITION_TYPE_BUY)
{
new_sl_price = current_price - Trailing_Stop_Pips * _Point;
if (new_sl_price > current_sl + Trailing_Stop_Step * _Point)
{
if (!m_trade.PositionModify(ticket, new_sl_price, PositionGetDouble(POSITION_TP)))
{
Print("Trailing Stop failed (Buy): ", m_trade.ResultRetcode(), " - ", m_trade.ResultRetcodeDescription());
}
}
}
else // Sell
{
new_sl_price = current_price + Trailing_Stop_Pips * _Point;
if (new_sl_price < current_sl - Trailing_Stop_Step * _Point)
{
if (!m_trade.PositionModify(ticket, new_sl_price, PositionGetDouble(POSITION_TP)))
{
Print("Trailing Stop failed (Sell): ", m_trade.ResultRetcode(), " - ", m_trade.ResultRetcodeDescription());
}
}
}
}
}
void DeleteAllObjects(string prefix)
{
for (int i = ObjectsTotal(0, -1, -1) - 1; i >= 0; i--)
{
string name = ObjectName(0, i, -1, -1);
if (StringFind(name, prefix) == 0) ObjectDelete(0, name);
}
ChartRedraw();
}
void OnDeinit(const int reason)
{
DeleteAllObjects("IOB_");
DeleteAllObjects("FIB_");
Print("EA deinitialized. Reason: ", reason);
}