SequentialVolumeProfileWithFVG.mq5 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. //+------------------------------------------------------------------+
  2. //| SequentialVolumeProfileWithFVG.mq5 |
  3. //| Copyright 2025 |
  4. //+------------------------------------------------------------------+
  5. #property copyright "Copyright 2025"
  6. #property link "https://www.mql5.com"
  7. #property version "1.00"
  8. #property indicator_chart_window
  9. //--- Input parameters for Volume Profile
  10. input int BinsCount=100; // Number of price bins
  11. input double ValueAreaPercent=70; // Value Area percentage (70% default)
  12. input color VALColor=clrDarkBlue; // Value Area Low color
  13. input color VAHColor=clrDarkBlue; // Value Area High color
  14. input color AbsLowColor=clrBlack; // Absolute Low color
  15. input color AbsHighColor=clrBlack; // Absolute High color
  16. input color TimeLineColor=clrRed; // Time marker line color
  17. input int LineWidth=2; // Line width for all value lines
  18. input int TimeLineWidth=2; // Line width for time marker lines
  19. input int MaxDaysBack=30; // Maximum number of trading days to look back
  20. input ENUM_LINE_STYLE VALStyle=STYLE_SOLID; // Value Area Low line style
  21. input ENUM_LINE_STYLE VAHStyle=STYLE_SOLID; // Value Area High line style
  22. input ENUM_LINE_STYLE AbsLowStyle=STYLE_SOLID; // Absolute Low line style
  23. input ENUM_LINE_STYLE AbsHighStyle=STYLE_SOLID; // Absolute High line style
  24. input bool ShowLabels=true; // Show price labels
  25. input bool ShowComment=true; // Show comment with most recent levels
  26. //--- Input parameters for Fair Value Gap (FVG)
  27. input bool ShowFVG=true; // Enable Fair Value Gap detection
  28. input color BullishFVGColor=clrLime; // Bullish FVG color
  29. input color BearishFVGColor=clrDeepPink; // Bearish FVG color
  30. input double MinFVGSize=0.0; // Minimum FVG size in points (0 = any size)
  31. input int MaxBarsBack=300; // How many bars to look back for FVG
  32. // Structure to hold volume profile data for a day
  33. struct VolumeProfileData
  34. {
  35. datetime date; // Trading day date
  36. datetime startTime; // Start time for calculation (23:00 previous day)
  37. datetime endTime; // End time for calculation (23:00 current day)
  38. datetime displayStart; // When to start displaying this profile (= endTime)
  39. datetime displayEnd; // When to stop displaying this profile (= next day's endTime)
  40. double val; // Value Area Low
  41. double vah; // Value Area High
  42. double poc; // Point of Control (needed for internal calculation)
  43. double absLow; // Absolute Low
  44. double absHigh; // Absolute High
  45. bool calculated; // Whether the calculation is complete
  46. };
  47. // Array to store volume profile data for multiple days
  48. VolumeProfileData g_Profiles[];
  49. // Prefix for FVG objects
  50. string prefix;
  51. //+------------------------------------------------------------------+
  52. //| Custom indicator initialization function |
  53. //+------------------------------------------------------------------+
  54. int OnInit()
  55. {
  56. // Set up FVG object prefix
  57. prefix = "VProfFVG_";
  58. // Initialize profile storage
  59. ArrayResize(g_Profiles, MaxDaysBack);
  60. for(int i = 0; i < MaxDaysBack; i++)
  61. {
  62. g_Profiles[i].date = 0;
  63. g_Profiles[i].startTime = 0;
  64. g_Profiles[i].endTime = 0;
  65. g_Profiles[i].displayStart = 0;
  66. g_Profiles[i].displayEnd = 0;
  67. g_Profiles[i].val = 0;
  68. g_Profiles[i].vah = 0;
  69. g_Profiles[i].poc = 0;
  70. g_Profiles[i].absLow = 0;
  71. g_Profiles[i].absHigh = 0;
  72. g_Profiles[i].calculated = false;
  73. }
  74. // Initialize all profiles
  75. CalculateAllVolumeProfiles();
  76. // Set up timer to check for new day
  77. EventSetTimer(60); // Check every minute
  78. return(INIT_SUCCEEDED);
  79. }
  80. //+------------------------------------------------------------------+
  81. //| Custom indicator deinitialization function |
  82. //+------------------------------------------------------------------+
  83. void OnDeinit(const int reason)
  84. {
  85. // Clean up chart objects
  86. ObjectsDeleteAll(0, "VProfile_");
  87. ObjectsDeleteAll(0, prefix);
  88. // Kill the timer
  89. EventKillTimer();
  90. // Clear the comment
  91. Comment("");
  92. }
  93. //+------------------------------------------------------------------+
  94. //| Timer function |
  95. //+------------------------------------------------------------------+
  96. void OnTimer()
  97. {
  98. // Check if we need to update the profiles
  99. datetime currentTime = TimeCurrent();
  100. MqlDateTime mdt;
  101. TimeToStruct(currentTime, mdt);
  102. // Check if it's near the 23:00 boundary (update a bit before and after)
  103. // if((mdt.hour == 22 && mdt.min >= 59) || (mdt.hour == 23 && mdt.min <= 5))
  104. if(newDayBar())
  105. {
  106. CalculateAllVolumeProfiles();
  107. }
  108. }
  109. //+------------------------------------------------------------------+
  110. //| Helper function to round a value to the specified tick size |
  111. //+------------------------------------------------------------------+
  112. double RoundToTickSize(double value, double tickSize)
  113. {
  114. return MathRound(value / tickSize) * tickSize;
  115. }
  116. //+------------------------------------------------------------------+
  117. //| Custom indicator iteration function |
  118. //+------------------------------------------------------------------+
  119. int OnCalculate(const int rates_total,
  120. const int prev_calculated,
  121. const datetime &time[],
  122. const double &open[],
  123. const double &high[],
  124. const double &low[],
  125. const double &close[],
  126. const long &tick_volume[],
  127. const long &volume[],
  128. const int &spread[])
  129. {
  130. // Check for insufficient data
  131. if(rates_total < 3)
  132. return 0;
  133. if(newDayBar())
  134. {
  135. CalculateAllVolumeProfiles();
  136. }
  137. // Calculate Volume Profiles if needed
  138. //if(prev_calculated == 0)
  139. // {
  140. // CalculateAllVolumeProfiles();
  141. // }
  142. // Detect Fair Value Gaps if enabled
  143. // if(ShowFVG)
  144. // {
  145. // // Prepare arrays
  146. // ArraySetAsSeries(open, true);
  147. // ArraySetAsSeries(high, true);
  148. // ArraySetAsSeries(low, true);
  149. // ArraySetAsSeries(close, true);
  150. // ArraySetAsSeries(time, true);
  151. //
  152. // // Clear existing FVG objects if recalculating all
  153. // if(prev_calculated == 0)
  154. // {
  155. // ObjectsDeleteAll(0, prefix);
  156. // }
  157. //
  158. // // Determine calculation starting point
  159. // int limit;
  160. // if(prev_calculated == 0)
  161. // {
  162. // // Calculate for all bars within MaxBarsBack
  163. // limit = MathMin(MaxBarsBack, rates_total - 3);
  164. // }
  165. // else
  166. // {
  167. // // Recalculate only for new bars plus a few previous ones
  168. // limit = rates_total - prev_calculated + 3;
  169. // limit = MathMin(limit, MaxBarsBack);
  170. // }
  171. //
  172. // // Ensure we don't exceed available bars
  173. // limit = MathMin(limit, rates_total - 3);
  174. //
  175. // // Scan for Fair Value Gaps
  176. // for(int i = 0; i < limit && !IsStopped(); i++)
  177. // {
  178. // // Check for bullish FVG (gap up)
  179. // // A bullish FVG occurs when low[i] > high[i+2]
  180. // if(low[i] - high[i+2] >= MinFVGSize * Point())
  181. // {
  182. // // Calculate the FVG boundaries
  183. // double upper = MathMin(high[i], low[i]);
  184. // double lower = MathMax(high[i+2], low[i+2]);
  185. //
  186. // // Draw the bullish FVG area
  187. // DrawFVGArea(i, upper, lower, time, BullishFVGColor, 1);
  188. // }
  189. //
  190. // // Check for bearish FVG (gap down)
  191. // // A bearish FVG occurs when low[i+2] > high[i]
  192. // if(low[i+2] - high[i] >= MinFVGSize * Point())
  193. // {
  194. // // Calculate the FVG boundaries
  195. // double upper = MathMin(high[i+2], low[i+2]);
  196. // double lower = MathMax(high[i], low[i]);
  197. //
  198. // // Draw the bearish FVG area
  199. // DrawFVGArea(i, upper, lower, time, BearishFVGColor, 0);
  200. // }
  201. // }
  202. // }
  203. return(rates_total);
  204. }
  205. //+------------------------------------------------------------------+
  206. //| Draw Fair Value Gap area as a rectangle |
  207. //+------------------------------------------------------------------+
  208. void DrawFVGArea(const int index, const double price_up, const double price_dn,
  209. const datetime &time[], const color color_area, const char dir)
  210. {
  211. string name = prefix + (dir > 0 ? "up_" : "dn_") + TimeToString(time[index]);
  212. // Create or update the rectangle object
  213. if(ObjectFind(0, name) < 0)
  214. ObjectCreate(0, name, OBJ_RECTANGLE, 0, 0, 0, 0);
  215. // Set object properties
  216. ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
  217. ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
  218. ObjectSetInteger(0, name, OBJPROP_FILL, true);
  219. ObjectSetInteger(0, name, OBJPROP_BACK, true);
  220. ObjectSetString(0, name, OBJPROP_TOOLTIP, "\n");
  221. // Set rectangle coordinates and color
  222. ObjectSetInteger(0, name, OBJPROP_COLOR, color_area);
  223. ObjectSetInteger(0, name, OBJPROP_TIME, 0, time[index+2]);
  224. ObjectSetInteger(0, name, OBJPROP_TIME, 1, time[index]);
  225. ObjectSetDouble(0, name, OBJPROP_PRICE, 0, price_up);
  226. ObjectSetDouble(0, name, OBJPROP_PRICE, 1, price_dn);
  227. }
  228. //+------------------------------------------------------------------+
  229. //| Calculate all volume profiles up to MaxDaysBack |
  230. //+------------------------------------------------------------------+
  231. void CalculateAllVolumeProfiles()
  232. {
  233. // Clear existing objects
  234. ObjectsDeleteAll(0, "VProfile_");
  235. // Get current time
  236. datetime currentTime = TimeCurrent();
  237. // Create a list of trading days going back MaxDaysBack days
  238. int calculatedDays = 0;
  239. datetime tradingDays[];
  240. ArrayResize(tradingDays, MaxDaysBack);
  241. // Get the current day
  242. datetime currentDay = currentTime;
  243. MqlDateTime mdt;
  244. TimeToStruct(currentDay, mdt);
  245. mdt.hour = 0;
  246. mdt.min = 0;
  247. mdt.sec = 0;
  248. currentDay = StructToTime(mdt);
  249. // Fill the array with trading days
  250. for(int i = 0; i < MaxDaysBack * 2; i++) // Check twice as many days to account for weekends
  251. {
  252. // Go back one day
  253. datetime checkDay = currentDay - (i * 86400);
  254. // Skip weekends
  255. TimeToStruct(checkDay, mdt);
  256. if(mdt.day_of_week == 0 || mdt.day_of_week == 6) // Sunday or Saturday
  257. continue;
  258. tradingDays[calculatedDays++] = checkDay;
  259. if(calculatedDays >= MaxDaysBack)
  260. break;
  261. }
  262. // Now, calculate volume profiles for each trading day
  263. for(int i = 0; i < calculatedDays; i++)
  264. {
  265. datetime tradingDay = tradingDays[i];
  266. // Store the date
  267. g_Profiles[i].date = tradingDay;
  268. // Calculate time boundaries
  269. CalculateTimeBoundaries(i);
  270. // For display purposes, set the display end of the current profile
  271. // to the display start of the previous profile
  272. if(i > 0)
  273. {
  274. g_Profiles[i].displayEnd = g_Profiles[i-1].displayStart;
  275. }
  276. else
  277. {
  278. // For the most recent profile, display until far future
  279. g_Profiles[i].displayEnd = D'2050.01.01 00:00:00';
  280. }
  281. // Check if we have a valid calculation for this day
  282. //if(!g_Profiles[i].calculated)
  283. {
  284. CalculateVolumeProfileForDay(i);
  285. }
  286. // Draw this profile's time markers and levels
  287. DrawVolumeProfile(i);
  288. }
  289. // Update comment with the most recent profile (index 0)
  290. if(ShowComment && calculatedDays > 0)
  291. {
  292. string info = "Volume Profile (TradingView 23:00-23:00 UTC+2)\n" +
  293. "Date: " + TimeToString(g_Profiles[0].date, TIME_DATE) + " (" + GetDayOfWeekName(g_Profiles[0].date) + ")\n" +
  294. "Value Area: " + DoubleToString(ValueAreaPercent, 0) + "%\n" +
  295. "VAL: " + DoubleToString(g_Profiles[0].val, _Digits) + "\n" +
  296. "VAH: " + DoubleToString(g_Profiles[0].vah, _Digits) + "\n" +
  297. "AbsLow: " + DoubleToString(g_Profiles[0].absLow, _Digits) + "\n" +
  298. "AbsHigh: " + DoubleToString(g_Profiles[0].absHigh, _Digits);
  299. Comment(info);
  300. }
  301. }
  302. //+------------------------------------------------------------------+
  303. //| |
  304. //+------------------------------------------------------------------+
  305. bool newDayBar()
  306. {
  307. static datetime lastbar;
  308. datetime curbar = iTime(Symbol(), PERIOD_D1, 0);
  309. if(lastbar != curbar)
  310. {
  311. lastbar = curbar;
  312. Print(" ---------------------- New Day Bar :: ---------------------- ",lastbar);
  313. return (true);
  314. }
  315. else
  316. {
  317. return (false);
  318. }
  319. }
  320. //+------------------------------------------------------------------+
  321. //| Calculate time boundaries for a profile |
  322. //+------------------------------------------------------------------+
  323. void CalculateTimeBoundaries(int index)
  324. {
  325. // Get trading day
  326. datetime tradingDay = g_Profiles[index].date;
  327. // Get the day before trading day
  328. datetime dayBeforeTradingDay = tradingDay - 86400;
  329. // Check and adjust for weekends
  330. MqlDateTime mdt;
  331. TimeToStruct(dayBeforeTradingDay, mdt);
  332. int dayOfWeek = mdt.day_of_week;
  333. // For Sunday, go back 2 more days to Friday
  334. if(dayOfWeek == 0)
  335. {
  336. int twoDaysInSeconds = 172800; // 2*86400
  337. dayBeforeTradingDay = dayBeforeTradingDay - twoDaysInSeconds;
  338. }
  339. // For Saturday, go back 1 more day to Friday
  340. if(dayOfWeek == 6)
  341. {
  342. int oneDayInSeconds = 86400;
  343. dayBeforeTradingDay = dayBeforeTradingDay - oneDayInSeconds;
  344. }
  345. // Format date strings for times
  346. MqlDateTime tradingDayMdt;
  347. TimeToStruct(tradingDay, tradingDayMdt);
  348. string tradingDayStr = StringFormat("%04d.%02d.%02d", tradingDayMdt.year, tradingDayMdt.mon, tradingDayMdt.day);
  349. MqlDateTime beforeMdt;
  350. TimeToStruct(dayBeforeTradingDay, beforeMdt);
  351. string dayBeforeTradingDayStr = StringFormat("%04d.%02d.%02d", beforeMdt.year, beforeMdt.mon, beforeMdt.day);
  352. // Calculate start and end times
  353. g_Profiles[index].startTime = StringToTime(dayBeforeTradingDayStr + " 23:00:00");
  354. g_Profiles[index].endTime = StringToTime(tradingDayStr + " 23:00:00");
  355. g_Profiles[index].displayStart = g_Profiles[index].endTime;
  356. }
  357. //+------------------------------------------------------------------+
  358. //| Calculate volume profile for a specific day |
  359. //+------------------------------------------------------------------+
  360. void CalculateVolumeProfileForDay(int index)
  361. {
  362. datetime tradingDay = g_Profiles[index].date;
  363. datetime startTime = g_Profiles[index].startTime;
  364. datetime endTime = g_Profiles[index].endTime;
  365. Print("Calculating volume profile for ", TimeToString(tradingDay, TIME_DATE),
  366. " (", GetDayOfWeekName(tradingDay), ")");
  367. Print("Time range: ", TimeToString(startTime), " to ", TimeToString(endTime), " Index: ", index);
  368. // Copy the OHLCV data for this day - using M1 timeframe for precision
  369. MqlRates rates[];
  370. int copied = CopyRates(_Symbol, PERIOD_M1, startTime, endTime, rates);
  371. if(copied <= 0)
  372. {
  373. Print("Failed to copy rates data for ", TimeToString(tradingDay, TIME_DATE), ". Error: ", GetLastError());
  374. g_Profiles[index].calculated = false;
  375. return;
  376. }
  377. Print("Copied ", copied, " bars for volume profile calculation");
  378. // Find high and low for the day
  379. double dayHigh = DBL_MIN;
  380. double dayLow = DBL_MAX;
  381. for(int i = 0; i < copied; i++)
  382. {
  383. if(rates[i].high > dayHigh)
  384. dayHigh = rates[i].high;
  385. if(rates[i].low < dayLow)
  386. dayLow = rates[i].low;
  387. }
  388. // Check if we have valid high and low
  389. if(dayHigh <= dayLow || dayLow == DBL_MAX || dayHigh == DBL_MIN)
  390. {
  391. Print("Invalid high/low values. Calculation aborted.");
  392. g_Profiles[index].calculated = false;
  393. return;
  394. }
  395. // EXACTLY MATCH TRADINGVIEW LOGIC: Calculate tick size as in PineScript
  396. // First get minimum tick size for the instrument
  397. double minTick = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
  398. // Calculate default tick size based on price range and bin count (matches TradingView more closely)
  399. double priceRange = dayHigh - dayLow;
  400. // Match the PineScript index_num calculation: math.floor(1000/lb_days)-1
  401. int index_num = (int)MathFloor(1000.0 / BinsCount) - 1;
  402. // Match TradingView tick_size calculation:
  403. // tick_size = round_to(math.max(((roof - base)/index_num),syminfo.mintick),(syminfo.mintick/100))
  404. double tickSize = MathMax((priceRange / index_num), minTick);
  405. tickSize = RoundToTickSize(tickSize, minTick / 100.0);
  406. Print("Using tick size: ", tickSize, " for volume profile calculation");
  407. // Base and roof price levels (direct from TradingView code)
  408. double base = dayLow;
  409. double roof = dayHigh;
  410. // Calculate maximum number of bins needed
  411. int bins = (int)MathCeil((roof - base) / tickSize) + 1;
  412. // Arrays to store volume at each price level
  413. double binVolume[];
  414. ArrayResize(binVolume, bins);
  415. // Initialize to zeros
  416. for(int i = 0; i < bins; i++)
  417. binVolume[i] = 0;
  418. // Process candles as in TradingView code
  419. for(int i = 0; i < copied; i++)
  420. {
  421. // Round high and low to the tickSize (match TradingView's c_hi and c_lo)
  422. double c_hi = RoundToTickSize(rates[i].high, tickSize);
  423. double c_lo = RoundToTickSize(rates[i].low, tickSize);
  424. // Calculate candle range and index as in TradingView
  425. double candle_range = c_hi - c_lo;
  426. int candle_index = (int)(candle_range / tickSize) + 1;
  427. // Calculate tick volume (matching PineScript tick_vol calculation)
  428. // In TradingView: tick_vol = _mp?1:volume/candle_index
  429. // We're always using real volume (mp = false), so:
  430. double tick_vol = rates[i].tick_volume / candle_index;
  431. // Loop through price levels covered by this candle
  432. for(int priceLevel = 0; priceLevel < bins; priceLevel++)
  433. {
  434. double index_price = base + (priceLevel * tickSize);
  435. // Check if this price level is within the candle's range
  436. if(index_price <= c_hi && index_price >= c_lo)
  437. {
  438. binVolume[priceLevel] += tick_vol;
  439. }
  440. }
  441. }
  442. // Store absolute high and low - use the exact values from calculation
  443. g_Profiles[index].absLow = base;
  444. g_Profiles[index].absHigh = roof;
  445. // Calculate total volume
  446. double totalVolume = 0;
  447. for(int i = 0; i < bins; i++)
  448. {
  449. totalVolume += binVolume[i];
  450. }
  451. // Safety check for total volume
  452. if(totalVolume <= 0)
  453. {
  454. Print("No volume data for ", TimeToString(tradingDay, TIME_DATE), ". Calculation aborted.");
  455. g_Profiles[index].calculated = false;
  456. return;
  457. }
  458. // Find max volume index - EXACTLY match TradingView's POC calculation
  459. // In TradingView: max_index = math.round(math.avg(array.indexof(main,array.max(main)), array.lastindexof(main,array.max(main))))
  460. double maxVolume = 0;
  461. int firstMaxIdx = 0;
  462. int lastMaxIdx = 0;
  463. // First find the maximum volume
  464. for(int i = 0; i < bins; i++)
  465. {
  466. if(binVolume[i] > maxVolume)
  467. {
  468. maxVolume = binVolume[i];
  469. }
  470. }
  471. // Then find first and last indices with this max volume
  472. for(int i = 0; i < bins; i++)
  473. {
  474. if(binVolume[i] == maxVolume)
  475. {
  476. firstMaxIdx = i;
  477. break;
  478. }
  479. }
  480. for(int i = bins - 1; i >= 0; i--)
  481. {
  482. if(binVolume[i] == maxVolume)
  483. {
  484. lastMaxIdx = i;
  485. break;
  486. }
  487. }
  488. // Calculate POC index as average of first and last max volume index (exactly as TradingView)
  489. int pocIndex = (int)MathRound((firstMaxIdx + lastMaxIdx) / 2.0);
  490. // Calculate POC price
  491. double poc = base + (pocIndex * tickSize);
  492. g_Profiles[index].poc = poc;
  493. // EXACTLY match TradingView Value Area calculation
  494. double valueAreaThreshold = totalVolume * ValueAreaPercent / 100.0;
  495. double accumulatedVolume = pocIndex >= 0 ? binVolume[pocIndex] : 0;
  496. int upCount = pocIndex;
  497. int downCount = pocIndex;
  498. // Follow the TradingView algorithm precisely
  499. while(accumulatedVolume < valueAreaThreshold && (upCount < bins - 1 || downCount > 0))
  500. {
  501. // Get upper and lower volumes exactly as in TradingView
  502. double upperVol = (upCount < bins - 1) ? binVolume[upCount + 1] : 0;
  503. double lowerVol = (downCount > 0) ? binVolume[downCount - 1] : 0;
  504. // Implement the exact TradingView condition:
  505. // if ((uppervol >= lowervol) and not na(uppervol)) or na(lowervol)
  506. if((upperVol >= lowerVol && upperVol > 0) || lowerVol == 0)
  507. {
  508. upCount += 1;
  509. accumulatedVolume += upperVol;
  510. }
  511. else
  512. {
  513. downCount -= 1;
  514. accumulatedVolume += lowerVol;
  515. }
  516. }
  517. // Calculate VAL and VAH exactly as in TradingView
  518. double val = base + (downCount * tickSize);
  519. double vah = base + (upCount * tickSize);
  520. // Store VAL and VAH
  521. g_Profiles[index].val = val;
  522. g_Profiles[index].vah = vah;
  523. // Mark as calculated
  524. g_Profiles[index].calculated = true;
  525. Print("Volume profile levels calculated for ", TimeToString(tradingDay, TIME_DATE),
  526. ": POC=", poc,
  527. ", VAL=", val,
  528. ", VAH=", vah,
  529. ", AbsLow=", base,
  530. ", AbsHigh=", roof);
  531. }
  532. //+------------------------------------------------------------------+
  533. //| Draw volume profile lines and time markers |
  534. //+------------------------------------------------------------------+
  535. void DrawVolumeProfile(int index)
  536. {
  537. // Skip if not calculated
  538. if(!g_Profiles[index].calculated)
  539. return;
  540. // Create a unique suffix based on the date
  541. string dateSuffix = TimeToString(g_Profiles[index].date, TIME_DATE);
  542. // Draw time markers at the boundaries (start and end of calculation)
  543. DrawTimeLine("StartTime_" + dateSuffix, g_Profiles[index].startTime, TimeLineColor, TimeLineWidth);
  544. DrawTimeLine("EndTime_" + dateSuffix, g_Profiles[index].endTime, TimeLineColor, TimeLineWidth);
  545. // Draw the volume profile levels between displayStart and displayEnd times
  546. DrawHorizontalLineWithinRange("VAL_" + dateSuffix, g_Profiles[index].val,
  547. VALColor, VALStyle, LineWidth, g_Profiles[index].displayStart, g_Profiles[index].displayEnd);
  548. DrawHorizontalLineWithinRange("VAH_" + dateSuffix, g_Profiles[index].vah,
  549. VAHColor, VAHStyle, LineWidth, g_Profiles[index].displayStart, g_Profiles[index].displayEnd);
  550. DrawHorizontalLineWithinRange("AbsLow_" + dateSuffix, g_Profiles[index].absLow,
  551. AbsLowColor, AbsLowStyle, LineWidth, g_Profiles[index].displayStart, g_Profiles[index].displayEnd);
  552. DrawHorizontalLineWithinRange("AbsHigh_" + dateSuffix, g_Profiles[index].absHigh,
  553. AbsHighColor, AbsHighStyle, LineWidth, g_Profiles[index].displayStart, g_Profiles[index].displayEnd);
  554. }
  555. //+------------------------------------------------------------------+
  556. //| Helper function to get day of week name |
  557. //+------------------------------------------------------------------+
  558. string GetDayOfWeekName(datetime date)
  559. {
  560. MqlDateTime mdt;
  561. TimeToStruct(date, mdt);
  562. // Use direct if statements instead of arrays
  563. if(mdt.day_of_week == 0)
  564. return "Sunday";
  565. if(mdt.day_of_week == 1)
  566. return "Monday";
  567. if(mdt.day_of_week == 2)
  568. return "Tuesday";
  569. if(mdt.day_of_week == 3)
  570. return "Wednesday";
  571. if(mdt.day_of_week == 4)
  572. return "Thursday";
  573. if(mdt.day_of_week == 5)
  574. return "Friday";
  575. if(mdt.day_of_week == 6)
  576. return "Saturday";
  577. return "Unknown";
  578. }
  579. //+------------------------------------------------------------------+
  580. //| Draw a time marker vertical line |
  581. //+------------------------------------------------------------------+
  582. void DrawTimeLine(string name, datetime time, color clr, int width)
  583. {
  584. string objName = "VProfile_" + name;
  585. if(ObjectFind(0, objName) >= 0)
  586. ObjectDelete(0, objName);
  587. ObjectCreate(0, objName, OBJ_VLINE, 0, time, 0);
  588. ObjectSetInteger(0, objName, OBJPROP_COLOR, clr);
  589. ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_SOLID);
  590. ObjectSetInteger(0, objName, OBJPROP_WIDTH, width);
  591. ObjectSetInteger(0, objName, OBJPROP_BACK, false);
  592. }
  593. //+------------------------------------------------------------------+
  594. //| Draw a horizontal line between two time points |
  595. //+------------------------------------------------------------------+
  596. void DrawHorizontalLineWithinRange(string name, double price, color clr, ENUM_LINE_STYLE style, int width, datetime startTime, datetime endTime)
  597. {
  598. string objName = "VProfile_" + name;
  599. if(ObjectFind(0, objName) >= 0)
  600. ObjectDelete(0, objName);
  601. // Create a trend line instead of a horizontal line to limit its display range
  602. ObjectCreate(0, objName, OBJ_TREND, 0, startTime, price, endTime, price);
  603. ObjectSetInteger(0, objName, OBJPROP_COLOR, clr);
  604. ObjectSetInteger(0, objName, OBJPROP_STYLE, style);
  605. ObjectSetInteger(0, objName, OBJPROP_WIDTH, width);
  606. ObjectSetInteger(0, objName, OBJPROP_BACK, false);
  607. ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false);
  608. ObjectSetInteger(0, objName, OBJPROP_RAY_RIGHT, false); // Don't extend line past end point
  609. // Add price label if enabled
  610. if(ShowLabels)
  611. {
  612. string labelName = objName + "_Label";
  613. if(ObjectFind(0, labelName) >= 0)
  614. ObjectDelete(0, labelName);
  615. // Place label at the middle of the line
  616. datetime labelTime = startTime + ((endTime - startTime) / 2);
  617. ObjectCreate(0, labelName, OBJ_TEXT, 0, labelTime, price);
  618. ObjectSetString(0, labelName, OBJPROP_TEXT, name + ": " + DoubleToString(price, _Digits));
  619. ObjectSetInteger(0, labelName, OBJPROP_COLOR, clr);
  620. ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 8);
  621. ObjectSetInteger(0, labelName, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
  622. }
  623. }
  624. //+------------------------------------------------------------------+