Volume Sequence Indicator.txt 25 KB

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