Repository: EarnForex/MarketProfile
Branch: master
Commit: f819c3c78379
Files: 46
Total size: 661.1 KB
Directory structure:
gitextract_kb5h78b7/
├── LICENSE
├── MarketProfile/
│ ├── MarketProfile/
│ │ ├── Calculator/
│ │ │ ├── MarketProfileCalculator.cs
│ │ │ └── MatrixPoint.cs
│ │ ├── Enums/
│ │ │ ├── AlertCheckBar.cs
│ │ │ ├── AlertTypes.cs
│ │ │ ├── Direction.cs
│ │ │ ├── PilingMode.cs
│ │ │ ├── SatSunSolution.cs
│ │ │ ├── SessionPeriod.cs
│ │ │ ├── SessionsToDrawRays.cs
│ │ │ ├── SinglePrintType.cs
│ │ │ ├── Transitions.cs
│ │ │ └── WaysToStopRays.cs
│ │ ├── EventArgs/
│ │ │ └── CalculateEventArgs.cs
│ │ ├── Helpers.cs
│ │ ├── Interfaces/
│ │ │ └── IIndicatorResources.cs
│ │ ├── ManagersAndFeatures/
│ │ │ ├── AlertManager.cs
│ │ │ ├── HideRaysFromInvisibleSessionsFeature.cs
│ │ │ ├── HotkeyStateManager.cs
│ │ │ ├── NewHighLowManager.cs
│ │ │ ├── OutputDevelopingValuesManager.cs
│ │ │ ├── SeamlessScrollingManager.cs
│ │ │ └── SessionChangeManager.cs
│ │ ├── MarketProfile.cs
│ │ ├── MarketProfile.csproj
│ │ ├── MarketProfileRenderer.cs
│ │ ├── Models/
│ │ │ ├── MarketProfileModel.cs
│ │ │ ├── MarketProfileSession.cs
│ │ │ └── SessionState.cs
│ │ ├── RangeCalculators/
│ │ │ ├── AnnualSessionProfileStrategy.cs
│ │ │ ├── DailySessionProfileStrategy.cs
│ │ │ ├── IRenderingModesResources.cs
│ │ │ ├── ISessionProfileStrategy.cs
│ │ │ ├── IntradaySessionProfileStrategy.cs
│ │ │ ├── MonthlySessionProfileStrategy.cs
│ │ │ ├── QuarterlySessionProfileStrategy.cs
│ │ │ ├── RectangleSessionProfileStrategy.cs
│ │ │ ├── SemiannualSessionProfileStrategy.cs
│ │ │ ├── SessionProfileStrategyFactory.cs
│ │ │ ├── SessionRange.cs
│ │ │ └── WeeklySessionProfileStrategy.cs
│ │ └── RectangleModeProcessor.cs
│ └── MarketProfile.sln
├── MarketProfile.mq4
├── MarketProfile.mq5
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: MarketProfile/MarketProfile/Calculator/MarketProfileCalculator.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo;
public interface IMarketProfileResources
{
double ValueAreaPercentage { get; }
TimeFrame TimeFrame { get; }
Bars Bars { get; }
Symbol Symbol { get; }
Chart Chart { get; }
double OneTickSize { get; }
void Print(object message);
}
///
///
///
///
/// Colors should not be tied to the calculations, but so far I found it convenient to do so
/// Inside MarketProfileRenderer, the color might be overriden with the direction of the bar
///
public class MarketProfileCalculator : IMarketProfileResources
{
private readonly IMarketProfileResources _resources;
public TimeSpan BarTimeSpan { get; set; }
public MarketProfileCalculator(IMarketProfileResources resources)
{
_resources = resources;
BarTimeSpan = Helpers.GetBarTimeSpan(TimeFrame);
}
///
/// Get a section of bars between startTime and endTime
///
public IEnumerable GetBarSection(DateTime startTime, DateTime endTime)
{
return Bars.Where(x => x.OpenTime >= startTime && x.OpenTime <= endTime);
}
///
/// The number of histograms is determined by the number of slices you want from the range you have
///
///
///
///
public double GetHistogramSize(Bar[] bars, int numberOfSlices)
{
var max = bars.Select(x => x.High).Max();
var min = bars.Select(x => x.Low).Min();
var range = max - min;
return range / numberOfSlices;
}
public int GetSlices(Bar[] bars)
{
var highMinusLow = bars.Max(x => x.High) - bars.Min(x => x.Low);
return (int) (highMinusLow / OneTickSize);
}
///
/// This way of calculating the matrix is a bit different from the one above, because it fills and piles on each iteration
/// instead of looping though the rows first, now it loops through the columns first, when it's done, it piles the matrix to the left
/// this is useful to calculate the developing PoC and VAH/VAL
///
///
///
///
///
///
public MarketProfileModel FillAndPileMatrixCalculation(Bar[] bars, int numberOfSlices, Color startColor, Color endColor)
{
var rows = numberOfSlices;
var columns = bars.Length;
var startTime = bars.First().OpenTime;
var endTime = bars.Last().OpenTime;
var histogramSize = GetHistogramSize(bars, numberOfSlices);
var bottomOfRegion = bars.Select(x => x.Low).Min();
var colors = Helpers.GenerateColorGradient(startColor, endColor, columns);
var marketProfileModel = new MarketProfileModel();
var matrix = new MatrixPoint[rows, columns];
for (var column = 0; column < columns; column++)
{
var bar = bars[column];
var pointsPerColumn = new Dictionary();
for (var row = 0; row < rows; row++)
{
var sliceBottom = bottomOfRegion + histogramSize * row;
var sliceTop = sliceBottom + histogramSize;
if (sliceTop < bar.Low || sliceBottom > bar.High)
continue;
var point = new MatrixPoint
{
Direction = bar.Close > bar.Open ? Direction.Up : Direction.Down,
StartTime = bar.OpenTime,
EndTime = column + 1 < columns ? bars[column + 1].OpenTime: bar.OpenTime.Add(BarTimeSpan),
Top = sliceBottom + histogramSize,
Bottom = sliceBottom,
Color = colors[column]
};
pointsPerColumn.Add(row, point);
}
//now we will pile all the points to the existing matrix
foreach (var point in pointsPerColumn)
{
var row = point.Key;
var pointToPile = point.Value;
var newColumnIndex = GetTotalRowPoints(matrix, row);
var newColumnBar = bars[newColumnIndex];
var piledPoint = new MatrixPoint
{
Direction = pointToPile.Direction,
StartTime = newColumnBar.OpenTime,
EndTime = newColumnIndex + 1 < columns ? bars[newColumnIndex + 1].OpenTime : newColumnBar.OpenTime.Add(BarTimeSpan),
Top = pointToPile.Top,
Bottom = pointToPile.Bottom,
Color = pointToPile.Color
};
matrix[row, newColumnIndex] = piledPoint;
}
var pocRowIndex = GetPointOfControlRowIndex(matrix);
if (matrix[pocRowIndex, 0] == null)
{
marketProfileModel.DevelopingPoC.Add(bar.OpenTime, double.NaN);
marketProfileModel.DevelopingAreaHigh.Add(bar.OpenTime, double.NaN);
marketProfileModel.DevelopingAreaLow.Add(bar.OpenTime, double.NaN);
continue;
}
var poc = GetPointOfControlPrice(matrix, pocRowIndex);
var (valueAreaHigh, valueAreaLow) = GetValueArea(matrix, ValueAreaPercentage);
marketProfileModel.DevelopingPoC.Add(bar.OpenTime, poc);
if (!double.IsNaN(valueAreaHigh))
marketProfileModel.DevelopingAreaHigh.Add(bar.OpenTime, valueAreaHigh);
if (!double.IsNaN(valueAreaLow))
marketProfileModel.DevelopingAreaLow.Add(bar.OpenTime, valueAreaLow);
}
marketProfileModel.Matrix = matrix;
marketProfileModel.StartTime = startTime;
marketProfileModel.EndTime = endTime;
return marketProfileModel;
}
public MarketProfileModel FillAndPileMatrixCalculationCropped(
Bar[] bars,
int numberOfSlices,
Color startColor,
Color endColor,
double cropTop,
double cropBottom)
{
var rows = numberOfSlices;
var columns = bars.Length;
var startTime = bars.First().OpenTime;
var endTime = bars.Last().OpenTime;
var histogramSize = GetHistogramSize(bars, numberOfSlices);
var bottomOfRegion = bars.Select(x => x.Low).Min();
var colors = Helpers.GenerateColorGradient(startColor, endColor, columns);
var marketProfileModel = new MarketProfileModel();
var matrix = new MatrixPoint[rows, columns];
for (var column = 0; column < columns; column++)
{
var bar = bars[column];
var pointsPerColumn = new Dictionary();
for (var row = 0; row < rows; row++)
{
var sliceBottom = bottomOfRegion + histogramSize * row;
var sliceTop = sliceBottom + histogramSize;
// Only include slices within the crop range
if (sliceTop < bar.Low || sliceBottom > bar.High)
continue;
if (sliceTop > cropTop || sliceBottom < cropBottom)
continue;
var point = new MatrixPoint
{
Direction = bar.Close > bar.Open ? Direction.Up : Direction.Down,
StartTime = bar.OpenTime,
EndTime = column + 1 < columns ? bars[column + 1].OpenTime : bar.OpenTime.Add(BarTimeSpan),
Top = sliceBottom + histogramSize,
Bottom = sliceBottom,
Color = colors[column]
};
pointsPerColumn.Add(row, point);
}
foreach (var point in pointsPerColumn)
{
var row = point.Key;
var pointToPile = point.Value;
var newColumnIndex = GetTotalRowPoints(matrix, row);
var newColumnBar = bars[newColumnIndex];
var piledPoint = new MatrixPoint
{
Direction = pointToPile.Direction,
StartTime = newColumnBar.OpenTime,
EndTime = newColumnIndex + 1 < columns ? bars[newColumnIndex + 1].OpenTime : newColumnBar.OpenTime.Add(BarTimeSpan),
Top = pointToPile.Top,
Bottom = pointToPile.Bottom,
Color = pointToPile.Color
};
matrix[row, newColumnIndex] = piledPoint;
}
var pocRowIndex = GetPointOfControlRowIndex(matrix);
if (matrix[pocRowIndex, 0] == null)
{
marketProfileModel.DevelopingPoC.Add(bar.OpenTime, double.NaN);
marketProfileModel.DevelopingAreaHigh.Add(bar.OpenTime, double.NaN);
marketProfileModel.DevelopingAreaLow.Add(bar.OpenTime, double.NaN);
continue;
}
var poc = GetPointOfControlPrice(matrix, pocRowIndex);
var (valueAreaHigh, valueAreaLow) = GetValueArea(matrix, ValueAreaPercentage);
marketProfileModel.DevelopingPoC.Add(bar.OpenTime, poc);
if (!double.IsNaN(valueAreaHigh))
marketProfileModel.DevelopingAreaHigh.Add(bar.OpenTime, valueAreaHigh);
if (!double.IsNaN(valueAreaLow))
marketProfileModel.DevelopingAreaLow.Add(bar.OpenTime, valueAreaLow);
}
marketProfileModel.Matrix = matrix;
marketProfileModel.StartTime = startTime;
marketProfileModel.EndTime = endTime;
return marketProfileModel;
}
///
/// Fills a matrix with the bars' values (it would overlap the bars if you draw this matrix on the chart, little blocks would be drawn)
///
///
///
///
///
///
/// This is the old method, the new one works better for calculating the developing POC, VAH and VAL
[Obsolete("Use FillAndPileMatrixCalculation instead")]
public MarketProfileModel FillMatrix(Bar[] bars, int numberOfSlices, Color startColor, Color endColor)
{
var rows = numberOfSlices;
var columns = bars.Length;
var startTime = bars.First().OpenTime;
var endTime = bars.Last().OpenTime;
var histogramSize = GetHistogramSize(bars, numberOfSlices);
var bottomOfRegion = bars.Select(x => x.Low).Min();
var colors = Helpers.GenerateColorGradient(startColor, endColor, columns);
var matrix = new MatrixPoint[rows, columns];
for (var row = 0; row < rows; row++)
{
for (var column = 0; column < columns; column++)
{
var bar = bars[column];
//slice goes from the bottom to the top
var sliceBottom = bottomOfRegion + histogramSize * row;
var sliceTop = sliceBottom + histogramSize;
if (sliceTop < bar.Low || sliceBottom > bar.High)
continue;
var point = new MatrixPoint
{
Direction = bar.Close > bar.Open ? Direction.Up : Direction.Down,
StartTime = bar.OpenTime,
EndTime = column + 1 < columns ? bars[column + 1].OpenTime: bar.OpenTime.Add(BarTimeSpan),
Top = sliceBottom + histogramSize,
Bottom = sliceBottom,
Color = colors[column]
};
matrix[row, column] = point;
}
}
return new MarketProfileModel
{
Matrix = matrix,
StartTime = startTime,
EndTime = endTime
};
}
///
/// Moves all matrix points to the left, so it looks like a profile
///
///
///
///
[Obsolete("We are piling the matrix on every bar now, so this is not needed anymore")]
// ReSharper disable once UnusedMember.Global
public MatrixPoint[,] PileMatrixPointsToLeft(Bar[] bars, MatrixPoint[,] matrix)
{
var piled = new MatrixPoint[matrix.GetLength(0), matrix.GetLength(1)];
/// we're traversing each row === of the matrix, getting the values of each column
for (var rowIndex = 0; rowIndex < matrix.GetLength(0); rowIndex++)
{
var columnValues = new List();
for (var columnIndex = 0; columnIndex < matrix.GetLength(1); columnIndex++)
{
var point = matrix[rowIndex, columnIndex];
if (point == null)
continue;
columnValues.Add(point);
}
for (var newColumnIndex = 0; newColumnIndex < columnValues.Count; newColumnIndex++)
{
var rowValue = columnValues[newColumnIndex];
var bar = bars[newColumnIndex];
var piledPoint = new MatrixPoint
{
Direction = rowValue.Direction,
StartTime = bar.OpenTime,
EndTime = newColumnIndex + 1 < columnValues.Count ? bars[newColumnIndex + 1].OpenTime : bar.OpenTime.Add(BarTimeSpan),
Top = rowValue.Top,
Bottom = rowValue.Bottom,
Color = rowValue.Color
};
piled[rowIndex, newColumnIndex] = piledPoint;
}
}
return piled;
}
///
/// Moves the matrix points to the right, so it looks like a profile
///
///
///
///
[Obsolete("We are piling the matrix on every bar now, so this is not needed anymore")]
// ReSharper disable once UnusedMember.Global
public MatrixPoint[,] PileMatrixPointsToRight(Bar[] bars, MatrixPoint[,] matrix)
{
var piled = new MatrixPoint[matrix.GetLength(0), matrix.GetLength(1)];
for (var rowIndex = 0; rowIndex < matrix.GetLength(0); rowIndex++)
{
var columnValues = new List();
for (var columnIndex = 0; columnIndex < matrix.GetLength(1); columnIndex++)
{
var point = matrix[rowIndex, columnIndex];
if (point == null)
continue;
columnValues.Add(point);
}
for (var newColumnIndex = 0; newColumnIndex < columnValues.Count; newColumnIndex++)
{
var rowValue = columnValues[newColumnIndex];
// Place at the rightmost available columns
var bar = bars[bars.Length - columnValues.Count + newColumnIndex];
var piledPoint = new MatrixPoint
{
Direction = rowValue.Direction,
StartTime = bar.OpenTime,
EndTime = newColumnIndex + 1 < columnValues.Count ? bars[newColumnIndex + 1].OpenTime : bar.OpenTime.Add(BarTimeSpan),
Top = rowValue.Top,
Bottom = rowValue.Bottom,
Color = rowValue.Color
};
piled[rowIndex, bars.Length - columnValues.Count + newColumnIndex] = piledPoint;
}
}
return piled;
}
public static double GetPointOfControlPrice(MatrixPoint[,] matrix, int rowIndex)
{
return (matrix[rowIndex, 0].Top + matrix[rowIndex, 0].Bottom) / 2.0;
}
public static int GetPointOfControlRowIndex(MatrixPoint[,] matrix)
{
var maxPoints = 0;
var pointOfControlRow = 0;
for (var row = 0; row < matrix.GetLength(0); row++)
{
var point = 0;
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
continue;
point++;
}
if (point > maxPoints)
{
pointOfControlRow = row;
maxPoints = point;
}
}
return pointOfControlRow;
}
///
/// The median is the price level at which 50% of the total volume occurred above and 50% occurred below.
///
///
///
public double GetMedianPrice(MatrixPoint[,] matrix)
{
//from bottom to top
var halfOfBlocks = GetTotalBlocks(matrix) / 2;
var blocks = 0;
var price = 0.0;
for (var row = 0; row < matrix.GetLength(0); row++)
{
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
continue;
blocks++;
price = (matrix[row, column].Top + matrix[row, column].Bottom) / 2.0;
}
if (blocks >= halfOfBlocks)
break;
}
return price;
}
public int GetMedianRowIndex(MatrixPoint[,] matrix)
{
//from bottom to top
var halfOfBlocks = GetTotalBlocks(matrix) / 2;
var blocks = 0;
for (var row = 0; row < matrix.GetLength(0); row++)
{
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
continue;
blocks++;
}
if (blocks > halfOfBlocks)
return row;
}
throw new Exception("Median row not found");
}
public DateTime GetMedianRowEndTime(MatrixPoint[,] matrix)
{
var medianRow = GetMedianRowIndex(matrix);
var endTimeColumnIndex = 0;
for (var columnIndex = 0; columnIndex < matrix.GetLength(1); columnIndex++)
{
if (matrix[medianRow, columnIndex] == null)
break;
endTimeColumnIndex = columnIndex;
}
return matrix[medianRow, endTimeColumnIndex].EndTime;
}
public DateTime GetPointOfControlRowEndTime(MatrixPoint[,] matrix)
{
var pointOfControlRow = GetPointOfControlRowIndex(matrix);
var endTimeColumnIndex = 0;
for (var columnIndex = 0; columnIndex < matrix.GetLength(1); columnIndex++)
{
if (matrix[pointOfControlRow, columnIndex] == null)
break;
endTimeColumnIndex = columnIndex;
}
return matrix[pointOfControlRow, endTimeColumnIndex].EndTime;
}
public static (int totalTopBlocks, int totalBottomBlocks) GetValuesAroundPointOfControl(MatrixPoint[,] matrix)
{
//from bottom to top
var topBlocks = 0;
var bottomBlocks = 0;
var pointOfControlIndex = GetPointOfControlRowIndex(matrix);
if (matrix[pointOfControlIndex, 0] == null)
return (-1, -1);
for (var row = 0; row < matrix.GetLength(0); row++)
{
if (matrix[row, 0] == null)
continue;
var rowTotalTpo = GetTotalRowPoints(matrix, row);
if (row < pointOfControlIndex)
bottomBlocks += rowTotalTpo;
else if (row > pointOfControlIndex)
topBlocks += rowTotalTpo;
}
return (topBlocks, bottomBlocks);
}
public (double vahPrice, double valPrice) GetValueArea(MatrixPoint[,] matrix, double percentage = 0.7)
{
var totalBlocks = GetTotalBlocks(matrix);
var targetBlocks = (int)Math.Round(totalBlocks * percentage);
var pointOfControlRowIndex = GetPointOfControlRowIndex(matrix);
var blockCounter = GetTotalRowPoints(matrix, pointOfControlRowIndex);
var topCounter = pointOfControlRowIndex;
var bottomCounter = pointOfControlRowIndex;
while (blockCounter < targetBlocks)
{
var canMoveUp = topCounter + 1 < matrix.GetLength(0) && matrix[topCounter + 1, 0] != null;
var canMoveDown = bottomCounter - 1 >= 0 && matrix[bottomCounter - 1, 0] != null;
if (!canMoveUp && !canMoveDown)
break;
int topRowPoints = 0, bottomRowPoints = 0;
if (canMoveUp)
{
topCounter++;
topRowPoints = GetTotalRowPoints(matrix, topCounter);
}
if (canMoveDown)
{
bottomCounter--;
bottomRowPoints = GetTotalRowPoints(matrix, bottomCounter);
}
blockCounter += topRowPoints + bottomRowPoints;
}
var vah = matrix[topCounter, 0] != null ? matrix[topCounter, 0].Middle : double.NaN;
var val = matrix[bottomCounter, 0] != null ? matrix[bottomCounter, 0].Middle : double.NaN;
return (vah, val);
}
public bool IsProminentLine(MatrixPoint[,] matrix, double prominencePercentage)
{
var totalBlocks = GetTotalBlocks(matrix);
var targetBlocks = totalBlocks * prominencePercentage;
var pointOfControlRowIndex = GetPointOfControlRowIndex(matrix);
var totalPointOfControlBlocks = GetTotalRowPoints(matrix, pointOfControlRowIndex);
return totalPointOfControlBlocks > targetBlocks;
}
public static double GetTopPrice(MatrixPoint[,] matrix)
{
return matrix[matrix.GetLength(0) - 1, 0].Top;
}
public static double GetBottomPrice(MatrixPoint[,] matrix)
{
return matrix[0, 0].Bottom;
}
public static SinglePrint[] GetSinglePrints(MatrixPoint[,] matrix)
{
var singlePrints = new List();
var singlePrintRowIndexes = new List();
for (var row = 0; row < matrix.GetLength(0); row++)
{
var columns = 0;
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
break;
columns++;
}
if (columns == 1)
{
singlePrintRowIndexes.Add(row);
}
}
var groups = Helpers.GroupAdjacent(singlePrintRowIndexes.ToArray());
foreach (var group in groups)
{
var startTime = matrix[group[0], 0].StartTime;
var endTime = matrix[group[0], 0].EndTime;
var high = matrix[group[^1], 0].Top;
var low = matrix[group[0], 0].Bottom;
var topTpoIndex = group[^1];
var bottomTpoIndex = group[0];
singlePrints.Add(new SinglePrint(startTime, endTime, high, low, topTpoIndex, bottomTpoIndex));
}
return singlePrints.ToArray();
}
private static int GetTotalBlocks(MatrixPoint[,] matrix)
{
var totalBlocks = 0;
for (var row = 0; row < matrix.GetLength(0); row++)
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
continue;
totalBlocks++;
}
return totalBlocks;
}
private static int GetTotalRowPoints(MatrixPoint[,] matrix, int row)
{
var point = 0;
for (var column = 0; column < matrix.GetLength(1); column++)
{
if (matrix[row, column] == null)
continue;
point++;
}
return point;
}
#region Resources
public double ValueAreaPercentage => _resources.ValueAreaPercentage;
public TimeFrame TimeFrame => _resources.TimeFrame;
public Bars Bars => _resources.Bars;
public Symbol Symbol => _resources.Symbol;
public Chart Chart => _resources.Chart;
public double OneTickSize => _resources.OneTickSize;
public void Print(object message) => _resources.Print(message);
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/Calculator/MatrixPoint.cs
================================================
using System;
using cAlgo.API;
namespace cAlgo;
public class MatrixPoint
{
public Direction Direction { get; init; }
public DateTime StartTime { get; init; }
public DateTime EndTime { get; init; }
public double Top { get; init; }
public double Bottom { get; init; }
public double Middle => (Top + Bottom) / 2.0;
public Color Color { get; init; }
}
================================================
FILE: MarketProfile/MarketProfile/Enums/AlertCheckBar.cs
================================================
namespace cAlgo;
public enum AlertCheckBar
{
CheckCurrentBar,
CheckPreviousBar
}
================================================
FILE: MarketProfile/MarketProfile/Enums/AlertTypes.cs
================================================
namespace cAlgo;
public enum AlertTypes
{
PriceBreak,
CandleCloseCrossover,
GapCrossover
}
================================================
FILE: MarketProfile/MarketProfile/Enums/Direction.cs
================================================
namespace cAlgo;
public enum Direction
{
Up,
Down
}
================================================
FILE: MarketProfile/MarketProfile/Enums/PilingMode.cs
================================================
namespace cAlgo;
public enum PilingMode
{
Left,
Right
}
================================================
FILE: MarketProfile/MarketProfile/Enums/SatSunSolution.cs
================================================
namespace cAlgo;
public enum SatSunSolution
{
// Normal sessions
SaturdaySundayNormalDays,
IgnoreSaturdaySunday,
AppendSaturdaySunday
}
================================================
FILE: MarketProfile/MarketProfile/Enums/SessionPeriod.cs
================================================
namespace cAlgo;
public enum SessionPeriod
{
Daily,
Weekly,
Monthly,
Quarterly,
Semiannual,
Annual,
Intraday,
Rectangle
}
================================================
FILE: MarketProfile/MarketProfile/Enums/SessionsToDrawRays.cs
================================================
namespace cAlgo;
public enum SessionsToDrawRays
{
None,
Previous,
Current,
PreviousCurrent,
// Previous & Current
AllPrevious,
// All Previous
All
}
================================================
FILE: MarketProfile/MarketProfile/Enums/SinglePrintType.cs
================================================
namespace cAlgo;
public enum SinglePrintType
{
No,
LeftSide,
RightSide
}
================================================
FILE: MarketProfile/MarketProfile/Enums/Transitions.cs
================================================
namespace cAlgo;
public enum Transitions
{
Initialized,
ChangedByHotkey,
ChangedByParameter,
}
================================================
FILE: MarketProfile/MarketProfile/Enums/WaysToStopRays.cs
================================================
namespace cAlgo;
public enum WaysToStopRays
{
StopNoRays,
StopAllRays,
StopAllRaysExceptPrevSession,
StopOnlyPreviousSession
}
================================================
FILE: MarketProfile/MarketProfile/EventArgs/CalculateEventArgs.cs
================================================
using System;
namespace cAlgo;
public class CalculateEventArgs : EventArgs
{
public bool IsNewBar { get; set; }
public bool IsLastBar { get; set; }
public int Index { get; set; }
}
================================================
FILE: MarketProfile/MarketProfile/Helpers.cs
================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using cAlgo.API;
namespace cAlgo;
public static class Helpers
{
public static Color[] GenerateColorGradient(Color startColor, Color endColor, int numberOfBars)
{
if (numberOfBars <= 0)
throw new ArgumentException("numberOfBars must be positive.");
var colors = new Color[numberOfBars];
for (int i = 0; i < numberOfBars; i++)
{
double t = numberOfBars == 1 ? 0 : (double)i / (numberOfBars - 1);
int a = (int)Math.Round(startColor.A + (endColor.A - startColor.A) * t);
int r = (int)Math.Round(startColor.R + (endColor.R - startColor.R) * t);
int g = (int)Math.Round(startColor.G + (endColor.G - startColor.G) * t);
int b = (int)Math.Round(startColor.B + (endColor.B - startColor.B) * t);
// colors[i] = Color.FromArgb(opacity, r, g, b);
// users can set the opacity from the parameters
colors[i] = Color.FromArgb(a, r, g, b);
}
return colors;
}
public static TimeSpan GetBarTimeSpan(TimeFrame timeFrame) =>
timeFrame.ToString() switch
{
"Minute" => TimeSpan.FromMinutes(1),
"Minute2" => TimeSpan.FromMinutes(2),
"Minute3" => TimeSpan.FromMinutes(3),
"Minute4" => TimeSpan.FromMinutes(4),
"Minute5" => TimeSpan.FromMinutes(5),
"Minute6" => TimeSpan.FromMinutes(6),
"Minute7" => TimeSpan.FromMinutes(7),
"Minute8" => TimeSpan.FromMinutes(8),
"Minute9" => TimeSpan.FromMinutes(9),
"Minute10" => TimeSpan.FromMinutes(10),
"Minute15" => TimeSpan.FromMinutes(15),
"Minute20" => TimeSpan.FromMinutes(20),
"Minute30" => TimeSpan.FromMinutes(30),
"Minute45" => TimeSpan.FromMinutes(45),
"Hour" => TimeSpan.FromHours(1),
"Hour2" => TimeSpan.FromHours(2),
"Hour3" => TimeSpan.FromHours(3),
"Hour4" => TimeSpan.FromHours(4),
"Hour6" => TimeSpan.FromHours(6),
"Hour8" => TimeSpan.FromHours(8),
"Hour12" => TimeSpan.FromHours(12),
"Daily" => TimeSpan.FromDays(1),
"Day2" => TimeSpan.FromDays(2),
"Day3" => TimeSpan.FromDays(3),
"Weekly" => TimeSpan.FromDays(7),
"Monthly" => TimeSpan.FromDays(30),
_ => throw new ArgumentOutOfRangeException(nameof(timeFrame), timeFrame, "TimeFrame not supported")
};
public static List GroupAdjacent(int[] input)
{
var result = new List();
if (input == null || input.Length == 0)
return result;
var group = new List { input[0] };
for (int i = 1; i < input.Length; i++)
{
if (input[i] == input[i - 1] + 1)
{
group.Add(input[i]);
}
else
{
result.Add(group.ToArray());
group = new List { input[i] };
}
}
result.Add(group.ToArray());
return result;
}
public static bool IsInIntradaySession(DateTime time, IntradaySessionDefinition session)
{
var timeOfDay = time.TimeOfDay;
return session.Start <= session.End
? timeOfDay >= session.Start && timeOfDay < session.End
: timeOfDay >= session.Start || timeOfDay < session.End;
}
public static bool SameSessionDay(DateTime sessionStart, DateTime barTime)
{
// Implement logic to check if two times belong to the same session day
// This would need to account for market open times
return sessionStart.Date == barTime.Date;
}
public static int GetWeekNumber(DateTime time)
{
// Get ISO week number
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
time, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}
public static int GetQuarter(DateTime time)
{
return (time.Month - 1) / 3 + 1;
}
}
================================================
FILE: MarketProfile/MarketProfile/Interfaces/IIndicatorResources.cs
================================================
using cAlgo.API;
namespace cAlgo;
public interface IIndicatorResources
{
TimeFrame TimeFrame { get; }
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/AlertManager.cs
================================================
using System;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo;
public interface IAlertManagerResources
{
INotifications Notifications { get; }
Bars Bars { get; }
IAccount Account { get; }
Chart Chart { get; }
DateTime Time { get; }
Symbol Symbol { get; }
string ObjPrefix { get; }
//--
bool InputAlertNative { get; }
SoundType InputAlertSoundType { get; }
bool InputAlertEmail { get; }
string InputAlertEmailFrom { get; }
string InputAlertEmailTo { get; }
bool InputAlertArrows { get; }
AlertCheckBar InputAlertCheckBar { get; }
bool InputAlertForValueArea { get; }
bool InputAlertForMedian { get; }
bool InputAlertForSinglePrint { get; }
bool InputAlertOnPriceBreak { get; }
bool InputAlertOnCandleClose { get; }
bool InputAlertOnGapCross { get; }
Color InputAlertArrowColorPb { get; }
Color InputAlertArrowColorCc { get; }
Color InputAlertArrowColorGc { get; }
}
public class AlertManager : IAlertManagerResources
{
private readonly IAlertManagerResources _resources;
private DateTime _lastAlertTime = DateTime.MinValue; // For CheckPreviousBar alerts;
private double _closePrev = double.NaN; // Previous price value for Price Break alerts.
private int _arrowsCounter; // Counter for naming of alert arrows.
private DateTime _lastAlertTimeCandleCross = DateTime.MinValue;
private DateTime _lastAlertTimeGapCross = DateTime.MinValue; // For CheckCurrentBar alerts.
public AlertManager(IAlertManagerResources resources)
{
_resources = resources;
}
///
/// Checks all alert conditions and issues alerts if needed.
///
///
public void CheckAlerts(int index)
{
// No need to check further if no alert method is chosen.
if (!InputAlertNative && !InputAlertEmail && !InputAlertArrows)// && !AlertPush)
return;
// Skip alerts if alerts are disabled for Median, for Value Area, and for Single Print rays.
if (!InputAlertForMedian && !InputAlertForValueArea && !InputAlertForSinglePrint)
return;
// Skip alerts if no cross type is chosen.
if (!InputAlertOnPriceBreak && !InputAlertOnCandleClose && !InputAlertOnGapCross)
return;
// Skip alerts if only closed bar should be checked and it has already been done.
if (InputAlertCheckBar == AlertCheckBar.CheckPreviousBar && _lastAlertTime == Bars[index].OpenTime) return;
// Cycle through rays starts here.
foreach (var ctl in Chart.FindAllObjects())
{
var objectName = ctl.Name;
// Skip if it is either a non-ray or if this particular ray shouldn't get alerted.
if (!(InputAlertForMedian && objectName.Contains("PointOfControlRay") ||
(InputAlertForValueArea && (objectName.Contains("ValueAreaRayHigh") || objectName.Contains("ValueAreaRayLow"))) ||
(InputAlertForSinglePrint && objectName.Contains("SinglePrintRay") && ctl.Color != Color.Transparent)))
continue;
// If everything is fine, go on:
var level = ctl.Y1; //NormalizeDouble(ObjectGetDouble(ChartID(), object_name, OBJPROP_PRICE1), _Digits);
// Price breaks, candle closes, and gap crosses using Close[0].
if (InputAlertCheckBar == AlertCheckBar.CheckCurrentBar)
{
if (InputAlertOnPriceBreak) // Price break alerts.
{
if (!double.IsNaN(_closePrev) && ((Bars[index].Close >= level && _closePrev < level) || (Bars[index].Close <= level && _closePrev > level)))
{
DoAlerts(AlertTypes.PriceBreak, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrPB{objectName}", Bars[index].OpenTime, Bars[index].Close, InputAlertArrowColorPb, ChartIconType.Circle);
}
_closePrev = Bars[index].Close;
}
if (InputAlertOnCandleClose) // Candle close alerts.
{
if ((Bars[index].Close >= level && Bars[index - 1].Close < level) || (Bars[index].Close <= level && Bars[index - 1].Close > level))
{
DoAlerts(AlertTypes.CandleCloseCrossover, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrCC{objectName}", Bars[index].OpenTime, Bars[index].Close, InputAlertArrowColorCc, ChartIconType.Square);
}
}
if (InputAlertOnGapCross) // Gap cross alerts.
{
if ((Bars[index].Open > level && Bars[index - 1].High < level) || (Bars[index].Open < level && Bars[index - 1].Low > level))
{
DoAlerts(AlertTypes.GapCrossover, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrGC{objectName}", Bars[index].OpenTime, level, InputAlertArrowColorGc, ChartIconType.Diamond);
}
}
}
// Price breaks (using pre-previous High and previous Close), candle closes, and gap crosses using Close[1].
else if (InputAlertCheckBar == AlertCheckBar.CheckPreviousBar)
{
if (InputAlertOnPriceBreak) // Price break alerts.
{
if ((Bars[index - 1].High >= level && Bars[index - 1].Close < level && Bars[index - 2].Close < level) ||
(Bars[index - 1].Low <= level && Bars[index - 1].Close > level && Bars[index - 2].Close > level))
{
DoAlerts(AlertTypes.PriceBreak, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrPB{objectName}", Bars[index - 1].OpenTime, Bars[index - 1].Close, InputAlertArrowColorPb, ChartIconType.Circle);
}
}
if (InputAlertOnCandleClose) // Candle close alerts.
{
if ((Bars[index - 1].Close >= level && Bars[index - 2].Close < level) || (Bars[index - 1].Close <= level && Bars[index - 2].Close > level))
{
DoAlerts(AlertTypes.CandleCloseCrossover, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrCC{objectName}", Bars[index - 1].OpenTime, Bars[index - 1].Close, InputAlertArrowColorCc, ChartIconType.Square);
}
}
if (InputAlertOnGapCross) // Gap cross alerts.
{
if ((Bars[index - 1].Low > level && Bars[index - 2].High < level) || (Bars[index - 2].Low > level && Bars[index - 1].High < level))
{
DoAlerts(AlertTypes.GapCrossover, objectName);
if (InputAlertArrows) CreateArrowObject($"ArrGC{objectName}", Bars[index - 1].OpenTime, level, InputAlertArrowColorGc, ChartIconType.Diamond);
}
}
_lastAlertTime = Bars[index].OpenTime;
}
}
}
///
/// Issues alerts based on the alert type and includes object name in the message.
///
///
///
private void DoAlerts(AlertTypes alertType, string objectName)
{
// Price Breaks for Current Bar should not be be checked for LastAlertTime.
// Candle Close and Gap Cross for Current Bar need to be checked against LastAlertTime.
// All CheckPreviousBar alerts can use a single LastAlertTime (they either trigger at the start of the bar or not). The actual check is performed in CheckAlerts().
// Using TimeCurrent() for all CheckCurrentBar alerts.
// Using Time[0] for all CheckPreviousBar alerts.
// Check last alert time for Candle Close alert type.
if (alertType == AlertTypes.CandleCloseCrossover && InputAlertCheckBar == AlertCheckBar.CheckCurrentBar && Time <= _lastAlertTimeCandleCross)
return;
// Check last alert time for Gap Cross alert type.
if (alertType == AlertTypes.GapCrossover && InputAlertCheckBar == AlertCheckBar.CheckCurrentBar && Time <= _lastAlertTimeGapCross)
return;
var subject = $"Market Profile: {Symbol.Name} {alertType} on {objectName}";
if (InputAlertNative)
{
Alert(subject);
}
if (InputAlertEmail)
{
var emailSubject = subject;
var emailBody = $"{Account.BrokerName} - {Account.Number}\r\n\r\n{subject}";
Notifications.SendEmail(InputAlertEmailFrom, InputAlertEmailTo, emailSubject, emailBody);
}
// Remember that this alert has already been sent. For CheckPreviousBar, this is done in CheckAlerts().
if (alertType == AlertTypes.CandleCloseCrossover && InputAlertCheckBar == AlertCheckBar.CheckCurrentBar)
_lastAlertTimeCandleCross = Time;
else if (alertType == AlertTypes.GapCrossover && InputAlertCheckBar == AlertCheckBar.CheckCurrentBar)
_lastAlertTimeGapCross = Time;
}
// Creates an arrow object and sets its properties.
public void CreateArrowObject(string name, DateTime time, double price, Color colour, ChartIconType type)
{
var objName = $"{ObjPrefix}name{_arrowsCounter}";
_arrowsCounter++;
Chart.DrawIcon(objName, type, time, price, colour);
}
#region Resources
public void Alert(string alertText)
{
Notifications.PlaySound(InputAlertSoundType);
MessageBox.Show(alertText, "Alert", MessageBoxButton.OK);
}
public INotifications Notifications => _resources.Notifications;
public Bars Bars => _resources.Bars;
public IAccount Account => _resources.Account;
public Chart Chart => _resources.Chart;
public DateTime Time => _resources.Time;
public Symbol Symbol => _resources.Symbol;
public string ObjPrefix => _resources.ObjPrefix;
//--
public bool InputAlertNative => _resources.InputAlertNative;
public SoundType InputAlertSoundType => _resources.InputAlertSoundType;
public bool InputAlertEmail => _resources.InputAlertEmail;
public string InputAlertEmailFrom => _resources.InputAlertEmailFrom;
public string InputAlertEmailTo => _resources.InputAlertEmailTo;
public bool InputAlertArrows => _resources.InputAlertArrows;
public AlertCheckBar InputAlertCheckBar => _resources.InputAlertCheckBar;
public bool InputAlertForValueArea => _resources.InputAlertForValueArea;
public bool InputAlertForMedian => _resources.InputAlertForMedian;
public bool InputAlertForSinglePrint => _resources.InputAlertForSinglePrint;
public bool InputAlertOnPriceBreak => _resources.InputAlertOnPriceBreak;
public bool InputAlertOnCandleClose => _resources.InputAlertOnCandleClose;
public bool InputAlertOnGapCross => _resources.InputAlertOnGapCross;
public Color InputAlertArrowColorPb => _resources.InputAlertArrowColorPb;
public Color InputAlertArrowColorCc => _resources.InputAlertArrowColorCc;
public Color InputAlertArrowColorGc => _resources.InputAlertArrowColorGc;
public DataSeries Open => Bars.OpenPrices;
public DataSeries High => Bars.HighPrices;
public DataSeries Low => Bars.LowPrices;
public DataSeries Close => Bars.ClosePrices;
public TimeSeries Times => Bars.OpenTimes;
public int Index => Bars.Count - 1;
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/HideRaysFromInvisibleSessionsFeature.cs
================================================
using System.Collections.Generic;
using cAlgo.API;
namespace cAlgo;
public interface IHideRaysFromInvisibleSessionsFeatureResources
{
Chart Chart { get; }
Bars Bars { get; }
public List Sessions { get; }
}
public class HideRaysFromInvisibleSessionsFeature : IHideRaysFromInvisibleSessionsFeatureResources
{
private readonly IHideRaysFromInvisibleSessionsFeatureResources _resources;
public HideRaysFromInvisibleSessionsFeature(IHideRaysFromInvisibleSessionsFeatureResources resources)
{
_resources = resources;
}
public void Start()
{
ChangeRaysVisibility();
Chart.ScrollChanged += ChartScrollChanged;
Chart.ZoomChanged += ChartZoomChanged;
}
private void ChartZoomChanged(ChartZoomEventArgs obj)
{
ChangeRaysVisibility();
}
private void ChartScrollChanged(ChartScrollEventArgs obj)
{
ChangeRaysVisibility();
}
public void ChangeRaysVisibility()
{
foreach (var session in Sessions)
SetVisibility(session, session.Model.EndTime < Bars.OpenTimes[Chart.FirstVisibleBarIndex]);
}
private static void SetVisibility(MarketProfileSession session, bool isHidden)
{
foreach (var ray in session.MedianRays)
ray.IsHidden = isHidden;
foreach (var ray in session.ValueAreaRays)
ray.IsHidden = isHidden;
}
public Chart Chart => _resources.Chart;
public Bars Bars => _resources.Bars;
public List Sessions => _resources.Sessions;
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/HotkeyStateManager.cs
================================================
using System;
using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo;
public interface IHotkeyStateManagerResources
{
Chart Chart { get; }
void Print(object message);
TimeFrame TimeFrame { get; }
SessionState SessionState { get; set; }
SessionChangeManager SessionChangeManager { get; }
List Sessions { get; }
INotifications Notifications { get; }
MarketProfileRenderer Renderer { get; }
bool InputSeamlessScrollingMode { get; }
int InputSessionsToCount { get; }
bool InputDisableAlertsOnWrongTimeframes { get; }
SoundType InputAlertSoundType { get; }
void CheckZeroIntradaySessions();
bool SetSessionsAndAddMarketProfiles(int sessionsToCount, DateTime? endAt = null);
//--
string InputHotkeyDaily { get; }
string InputHotkeyWeekly { get; }
string InputHotkeyMonthly { get; }
string InputHotkeyQuarterly { get; }
string InputHotkeySemiannual { get; }
string InputHotkeyAnnual { get; }
string InputHotkeyIntraday { get; }
string InputHotkeyRectangle { get; }
}
public class HotkeyStateManager : IHotkeyStateManagerResources
{
private readonly IHotkeyStateManagerResources _resources;
public HotkeyStateManager(IHotkeyStateManagerResources resources)
{
_resources = resources;
}
public void AddHotkeys()
{
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Daily), InputHotkeyDaily);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Weekly), InputHotkeyWeekly);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Monthly), InputHotkeyMonthly);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Quarterly), InputHotkeyQuarterly);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Semiannual), InputHotkeySemiannual);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Annual), InputHotkeyAnnual);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Intraday), InputHotkeyIntraday);
Chart.AddHotkey(() => SwitchSessionTo(SessionPeriod.Rectangle), InputHotkeyRectangle);
}
private void SwitchSessionTo(SessionPeriod sessionPeriod)
{
if (sessionPeriod == SessionPeriod.Rectangle && InputSeamlessScrollingMode)
throw new ArgumentException("Seamless scrolling mode doesn't work with Rectangle sessions.");
if (sessionPeriod == SessionState.LastSessionState)
{
Alert($"Session is already set to {sessionPeriod}.");
return;
}
Print($"Switching session to {sessionPeriod}.");
if (!SessionChangeManager.CheckSessions(sessionPeriod))
return;
SessionChangeManager.UpdateSessionStateTo(sessionPeriod);
foreach (var session in Sessions)
Renderer.DeleteAllFromSession(session);
SetSessionsAndAddMarketProfiles(InputSessionsToCount);
}
public void Alert(string alertText)
{
if (InputDisableAlertsOnWrongTimeframes)
{
Print($"Initialization failed: {alertText}");
}
else
{
Notifications.PlaySound(InputAlertSoundType);
MessageBox.Show(alertText, "Alert", MessageBoxButton.OK);
}
}
#region MyRegion
public Chart Chart => _resources.Chart;
public SessionState SessionState
{
get => _resources.SessionState;
set => _resources.SessionState = value;
}
public void Print(object message) => _resources.Print(message);
public TimeFrame TimeFrame => _resources.TimeFrame;
public SessionChangeManager SessionChangeManager => _resources.SessionChangeManager;
public List Sessions => _resources.Sessions;
public INotifications Notifications => _resources.Notifications;
public MarketProfileRenderer Renderer => _resources.Renderer;
public bool InputSeamlessScrollingMode => _resources.InputSeamlessScrollingMode;
public int InputSessionsToCount => _resources.InputSessionsToCount;
public bool InputDisableAlertsOnWrongTimeframes => _resources.InputDisableAlertsOnWrongTimeframes;
public SoundType InputAlertSoundType => _resources.InputAlertSoundType;
public void CheckZeroIntradaySessions() =>
_resources.CheckZeroIntradaySessions();
public bool SetSessionsAndAddMarketProfiles(int sessionsToCount, DateTime? endAt = null) =>
_resources.SetSessionsAndAddMarketProfiles(sessionsToCount, endAt);
public string InputHotkeyDaily => _resources.InputHotkeyDaily;
public string InputHotkeyWeekly => _resources.InputHotkeyWeekly;
public string InputHotkeyMonthly => _resources.InputHotkeyMonthly;
public string InputHotkeyQuarterly => _resources.InputHotkeyQuarterly;
public string InputHotkeySemiannual => _resources.InputHotkeySemiannual;
public string InputHotkeyAnnual => _resources.InputHotkeyAnnual;
public string InputHotkeyIntraday => _resources.InputHotkeyIntraday;
public string InputHotkeyRectangle => _resources.InputHotkeyRectangle;
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/NewHighLowManager.cs
================================================
using System;
using cAlgo.API;
namespace cAlgo;
public class NewHighLowEventArgs : EventArgs
{
public double Value { get; set; }
}
public interface INewHighLowManagerResources
{
event EventHandler CalculateEvent;
Bars Bars { get; }
}
///
/// Has events to handle when the last bar is making a new high/low
///
public class NewHighLowManager : INewHighLowManagerResources
{
private readonly INewHighLowManagerResources _resources;
private double _lastHigh = double.NaN;
private double _lastLow = double.NaN;
public event EventHandler NewHighOnLastBar;
public event EventHandler NewLowOnLastBar;
public NewHighLowManager(INewHighLowManagerResources resources)
{
_resources = resources;
CalculateEvent += NewHighLowFeature_CalculateEvent;
}
private void NewHighLowFeature_CalculateEvent(object sender, CalculateEventArgs e)
{
if (!e.IsLastBar)
return;
var index = e.Index;
if (e.IsNewBar)
{
_lastHigh = High[index];
_lastLow = Low[index];
}
else
{
if (High[index] > _lastHigh)
{
_lastHigh = High[index];
NewHighOnLastBar?.Invoke(this, new NewHighLowEventArgs { Value = High[index] });
}
if (Low[index] < _lastLow)
{
_lastLow = Low[index];
NewLowOnLastBar?.Invoke(this, new NewHighLowEventArgs { Value = Low[index] });
}
}
}
public event EventHandler CalculateEvent
{
add => _resources.CalculateEvent += value;
remove => _resources.CalculateEvent -= value;
}
public Bars Bars => _resources.Bars;
public DataSeries Open => Bars.OpenPrices;
public DataSeries High => Bars.HighPrices;
public DataSeries Low => Bars.LowPrices;
public DataSeries Close => Bars.ClosePrices;
public TimeSeries Times => Bars.OpenTimes;
public int Index => Bars.Count - 1;
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/OutputDevelopingValuesManager.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public interface IOutputDevelopingValuesManagerResources
{
Chart Chart { get; }
Bars Bars { get; }
TimeFrame TimeFrame { get; }
//--
int InputOutputDevelopingSessionsToCount { get; }
int InputValueAreaPercentage { get; }
Color InputStartColor { get; }
Color InputEndColor { get; }
bool InputEnableDevelopingPoC { get; }
bool InputEnableDevelopingValueAtHighValueAtLow { get; }
MarketProfileCalculator Calculator { get; }
MarketProfileRenderer Renderer { get; }
SessionState SessionState { get; }
List IntradaySessions { get; }
double OneTickSize { get; }
bool IsNewSessionRequired(MarketProfileSession lastSession, DateTime newBarTime);
//--
IndicatorDataSeries OutputDevelopingPoC { get; }
IndicatorDataSeries OutputDevelopingVah { get; }
IndicatorDataSeries OutputDevelopingVaL { get; }
}
public class OutputDevelopingValuesManager :
IOutputDevelopingValuesManagerResources,
IIndicatorResources,
IRenderingModesResources
{
private readonly IOutputDevelopingValuesManagerResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public List OutputSessions { get; } = new();
public OutputDevelopingValuesManager(IOutputDevelopingValuesManagerResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
// Chart.ScrollChanged += ChartScrollChanged;
// Chart.ZoomChanged += ChartZoomChanged;
Bars.BarOpened += OnBarOpened;
}
public void SetOutputSessions(int sessionsToCount)
{
//var firstVisibleIndex = Chart.FirstVisibleBarIndex;
var lastVisibleIndex = Chart.LastVisibleBarIndex;
//var indexRange = lastVisibleIndex - firstVisibleIndex;
//var renderingStartIndex = (int)Math.Max(0, (firstVisibleIndex - indexRange * 0.5));
var renderingStartIndex = 0;
var renderingEndIndex = lastVisibleIndex;
var renderingStartTime = Bars.OpenTimes[renderingStartIndex];
var renderingEndTime = Bars.OpenTimes[renderingEndIndex];
var bars = Bars.Where(x => x.OpenTime >= renderingStartTime && x.OpenTime <= renderingEndTime).ToArray();
var strategy = SessionState.LastSessionState switch
{
SessionPeriod.Daily => SessionProfileStrategyFactory.CreateDaily(this, this),
SessionPeriod.Weekly => SessionProfileStrategyFactory.CreateWeekly(this, this),
SessionPeriod.Monthly => SessionProfileStrategyFactory.CreateMonthly(this, this),
SessionPeriod.Quarterly => SessionProfileStrategyFactory.CreateQuarterly(this, this),
SessionPeriod.Semiannual => SessionProfileStrategyFactory.CreateSemiannual(this, this),
SessionPeriod.Annual => SessionProfileStrategyFactory.CreateAnnual(this, this),
SessionPeriod.Intraday => SessionProfileStrategyFactory.CreateIntradaySessions(IntradaySessions, this, this),
SessionPeriod.Rectangle => null,
_ => null
};
if (strategy == null)
return;
var ranges = sessionsToCount == 0
? strategy.GetSessionRanges(Bars, InputStartColor, InputEndColor, renderingStartTime, renderingEndTime).ToArray()
: strategy.GetSessionRanges(Bars, sessionsToCount, InputStartColor, InputEndColor).ToArray();
for (var index = 0; index < ranges.Length; index++)
{
var range = ranges[index];
var session = new MarketProfileSession
{
Range = range,
};
var rangeBars = range.Bars.ToArray();
if (bars.Length == 0)
continue;
var highMinusLow = bars.Max(x => x.High) - bars.Min(x => x.Low);
var slices = (int) (highMinusLow / OneTickSize);
var profileModel = Calculator.FillAndPileMatrixCalculation(rangeBars, slices, range.StartColor, range.EndColor);
session.Model = profileModel;
if (InputEnableDevelopingPoC)
Renderer.RenderDevelopingPoc(profileModel.DevelopingPoC);
if (InputEnableDevelopingValueAtHighValueAtLow)
{
Renderer.RenderDevelopingVahs(profileModel.DevelopingAreaHigh);
Renderer.RenderDevelopingVals(profileModel.DevelopingAreaLow);
}
OutputSessions.Add(session);
}
}
private void OnBarOpened(BarOpenedEventArgs obj)
{
if (SessionState.LastSessionState == SessionPeriod.Rectangle)
return;
var lastSession = OutputSessions.LastOrDefault();
if (lastSession == null)
{
SetOutputSessions(1);
return;
}
var parsed = DateTime.TryParse(InputStartFromDate, out var startFrom);
if (parsed && !InputStartFromCurrentSession)
return;
var needNewSession = IsNewSessionRequired(lastSession, Bars.LastBar.OpenTime);
if (needNewSession)
SetOutputSessions(1);
else
UpdateLastOutputSession(session: lastSession);
//
// ClearOutputsFromSession(lastSession);
// OutputSessions.Remove(lastSession);
// SetOutputSessions(1);
}
private void UpdateLastOutputSession(MarketProfileSession session)
{
var strategy = SessionState.LastSessionState switch
{
SessionPeriod.Daily => SessionProfileStrategyFactory.CreateDaily(this, this),
SessionPeriod.Weekly => SessionProfileStrategyFactory.CreateWeekly(this, this),
SessionPeriod.Monthly => SessionProfileStrategyFactory.CreateMonthly(this, this),
SessionPeriod.Quarterly => SessionProfileStrategyFactory.CreateQuarterly(this, this),
SessionPeriod.Semiannual => SessionProfileStrategyFactory.CreateSemiannual(this, this),
SessionPeriod.Annual => SessionProfileStrategyFactory.CreateAnnual(this, this),
SessionPeriod.Intraday => SessionProfileStrategyFactory.CreateIntradaySessions(IntradaySessions, this, this),
SessionPeriod.Rectangle => null,
_ => null
};
if (strategy == null)
return;
var ranges = strategy.GetSessionRanges(Bars, 1, InputStartColor, InputEndColor).ToArray();
//there should be only one range
if (ranges.Length != 1)
throw new Exception("There should be only one range");
if (session.Range.Start != ranges[0].Start)
return;
session.Range = ranges[0];
if (!session.Range.Bars.Any())
{
// Skip this session or handle empty range
//Print($"Warning: No bars found for session range {session.Range.Start} to {session.Range.End}");
return; // or continue to next session
}
var bars = session.Range.Bars.ToArray();
var highMinusLow = bars.Max(x => x.High) - bars.Min(x => x.Low);
var slices = (int) (highMinusLow / OneTickSize);
if (slices == 0)
{
//Print($"Slices is 0 | This can't be processed Bars is {bars.Length} (High {bars.Max(x => x.High)} | Low {bars.Min(x => x.Low)} Minus Low is {highMinusLow}) | OneTickSize is {OneTickSize}");
return;
}
var profileModel = Calculator.FillAndPileMatrixCalculation(bars, slices, session.Range.StartColor, session.Range.EndColor);
//these two below could be totally removed and reference the latest "developing" values
var (vah, val) = Calculator.GetValueArea(profileModel.Matrix, InputValueAreaPercentage / 100.0);
var pointOfControlRowIndex = MarketProfileCalculator.GetPointOfControlRowIndex(profileModel.Matrix);
if (profileModel.Matrix[pointOfControlRowIndex, 0] == null)
{
//Print($"Unable to calculate POC because the row is null");
return;
}
session.Model = profileModel;
if (InputEnableDevelopingPoC)
Renderer.RenderDevelopingPoc(profileModel.DevelopingPoC);
if (InputEnableDevelopingValueAtHighValueAtLow)
{
Renderer.RenderDevelopingVahs(profileModel.DevelopingAreaHigh);
Renderer.RenderDevelopingVals(profileModel.DevelopingAreaLow);
}
}
public void ClearOutputsFromSession(MarketProfileSession session)
{
var sessionStartIndex = Bars.OpenTimes.GetIndexByTime(session.Range.Start);
var sessionEndIndex = Bars.OpenTimes.GetIndexByTime(session.Range.End);
for (var i = sessionStartIndex; i <= sessionEndIndex; i++)
{
if (!double.IsNaN(OutputDevelopingPoC[i]))
OutputDevelopingPoC[i] = double.NaN;
if (!double.IsNaN(OutputDevelopingVah[i]))
OutputDevelopingVah[i] = double.NaN;
if (!double.IsNaN(OutputDevelopingVaL[i]))
OutputDevelopingVaL[i] = double.NaN;
}
}
#region Outputs
public Chart Chart => _resources.Chart;
public Bars Bars => _resources.Bars;
public TimeFrame TimeFrame => _resources.TimeFrame;
public int InputOutputDevelopingSessionsToCount => _resources.InputOutputDevelopingSessionsToCount;
public int InputValueAreaPercentage => _resources.InputValueAreaPercentage;
public Color InputStartColor => _resources.InputStartColor;
public Color InputEndColor => _resources.InputEndColor;
public bool InputEnableDevelopingPoC => _resources.InputEnableDevelopingPoC;
public bool InputEnableDevelopingValueAtHighValueAtLow => _resources.InputEnableDevelopingValueAtHighValueAtLow;
public MarketProfileCalculator Calculator => _resources.Calculator;
public MarketProfileRenderer Renderer => _resources.Renderer;
public SessionState SessionState => _resources.SessionState;
public List IntradaySessions => _resources.IntradaySessions;
public double OneTickSize => _resources.OneTickSize;
public bool IsNewSessionRequired(MarketProfileSession lastSession, DateTime newBarTime) =>
_resources.IsNewSessionRequired(lastSession, newBarTime);
public IndicatorDataSeries OutputDevelopingPoC => _resources.OutputDevelopingPoC;
public IndicatorDataSeries OutputDevelopingVah => _resources.OutputDevelopingVah;
public IndicatorDataSeries OutputDevelopingVaL => _resources.OutputDevelopingVaL;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/SeamlessScrollingManager.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public interface ISeamlessScrollingManagerResources
{
Bars Bars { get; }
Chart Chart { get; }
bool SetSessionsAndAddMarketProfiles(int sessionsToCount, DateTime? endAt = null);
MarketProfileRenderer Renderer { get; }
List Sessions { get; }
SessionState SessionState { get; }
int InputSessionsToCount { get; }
void Print(object message);
void Sleep(TimeSpan timeSpan);
}
public class SeamlessScrollingManager : ISeamlessScrollingManagerResources
{
//--to do seamless scrolling I need to:
//Check we're not in Rectangle Mode (just in case)
//Check if the last MarketProfileSession time is not visible in the current screen
//If it is not visible
//I delete everything
//Render them again
//But the bars used for rendering have changed, the latest bar is the one visible
private readonly ISeamlessScrollingManagerResources _resources;
public SeamlessScrollingManager(ISeamlessScrollingManagerResources resources)
{
_resources = resources;
// var button = new Button
// {
// Text = "Seamless Scrolling Mode",
// HorizontalAlignment = HorizontalAlignment.Center,
// VerticalAlignment = VerticalAlignment.Bottom,
// Width = 200,
// Height = 50,
// FontSize = 12,
// };
//
// button.Click += _ => ResetSessions();
//
// Chart.AddControl(button);
//
// var justDeleteButton = new Button
// {
// Text = "Delete All",
// HorizontalAlignment = HorizontalAlignment.Right,
// VerticalAlignment = VerticalAlignment.Bottom,
// Width = 200,
// Height = 50,
// FontSize = 12,
// };
//
// justDeleteButton.Click += _ =>
// {
// DeleteAllSessions();
// Sessions.Clear();
// };
//
// Chart.AddControl(justDeleteButton);
}
public void Start()
{
Chart.ScrollChanged += _ => ResetSessions();
//Chart.ZoomChanged += _ => ResetSessions();
//Chart.SizeChanged += _ => ResetSessions();
}
private void ResetSessions()
{
if (SessionState.LastSessionState == SessionPeriod.Rectangle)
return;
//Sleeping so that it doesn't redraw immediately and slows down the process by doing this too often
Sleep(TimeSpan.FromSeconds(1));
var lastSessionStartTime = Sessions.LastOrDefault()?.Range.Start;
//In other words, if the date of the last session is visible, don't delete it
if (!lastSessionStartTime.HasValue)
return;
// if (lastSessionStartTime.Value >= Bars.OpenTimes[Chart.LastVisibleBarIndex] ||
// lastSessionStartTime.Value < Bars.OpenTimes[Chart.FirstVisibleBarIndex])
// {
//
// }
Renderer.DeleteAllSessions(Sessions);
Sessions.Clear();
SetSessionsAndAddMarketProfiles(InputSessionsToCount, Bars.OpenTimes[Chart.LastVisibleBarIndex]);
}
public Bars Bars => _resources.Bars;
public Chart Chart => _resources.Chart;
public bool SetSessionsAndAddMarketProfiles(int sessionsToCount, DateTime? endAt = null) =>
_resources.SetSessionsAndAddMarketProfiles(sessionsToCount,endAt);
public MarketProfileRenderer Renderer => _resources.Renderer;
public List Sessions => _resources.Sessions;
public SessionState SessionState => _resources.SessionState;
public int InputSessionsToCount => _resources.InputSessionsToCount;
public void Print(object message) => _resources.Print(message);
public void Sleep(TimeSpan timeSpan)
{
_resources.Sleep(timeSpan);
}
}
================================================
FILE: MarketProfile/MarketProfile/ManagersAndFeatures/SessionChangeManager.cs
================================================
using System;
using cAlgo.API;
namespace cAlgo;
public interface ISessionChangeManagerResources
{
LocalStorage LocalStorage { get; }
SessionState SessionState { get; set; }
SessionPeriod InputSession { get; }
bool InputSeamlessScrollingMode { get; }
string ObjPrefix { get; }
string StoragePrefix { get; }
int TpoSize { get; }
TimeFrame ResolvedTPOTimeframe { get; }
Chart Chart { get; }
TimeFrame TimeFrame { get; }
void Print(object message);
}
public class SessionChangeManager : ISessionChangeManagerResources
{
private readonly ISessionChangeManagerResources _resources;
public SessionChangeManager(ISessionChangeManagerResources resources)
{
_resources = resources;
}
public void UpdateSessionStateTo(SessionPeriod sessionPeriod)
{
SessionState.LastSessionState = sessionPeriod;
SessionState.LastTransition = Transitions.ChangedByHotkey;
LocalStorage.SetObject(StoragePrefix + "SessionState", SessionState);
LocalStorage.Flush(LocalStorageScope.Instance);
}
public void LoadSessionState()
{
var sessionState = LocalStorage.GetObject(StoragePrefix + "SessionState", LocalStorageScope.Instance);
//- There's no storage for this instance
// - The indicator is initialized with the values from the parameter
if (sessionState == null)
{
Print($"No storage for this instance. Initializing with the values from the parameter.");
SessionState = new SessionState
{
LastSessionState = InputSession,
LastSessionStateByParameter = InputSession,
LastTransition = Transitions.Initialized
};
return;
}
SessionState = new SessionState();
// - The input-parameter has changed from last run, SessionState needs to be updated
// with the current input-parameter, this change takes priority over the hotkey-state change
if (InputSession != sessionState.LastSessionStateByParameter)
{
Print($"The input-parameter has changed from last run, SessionState will be changed from {sessionState.LastSessionStateByParameter} to {InputSession}.");
SessionState.LastSessionState = InputSession;
SessionState.LastSessionStateByParameter = InputSession;
SessionState.LastTransition = Transitions.ChangedByParameter;
}
//The input-parameter has not changed from last run
else
{
Print($"The input-parameter has not changed from last run");
//if a hotkey was used, SessionState needs to be updated with the last hotkey-state used
//since I'm loading from the file, no need to change anything
if (sessionState.LastTransition == Transitions.ChangedByHotkey)
{
Print($"A Hotkey was used, Session State will be changed to {SessionState.LastSessionState}.");
SessionState = new SessionState
{
LastSessionState = sessionState.LastSessionState,
LastSessionStateByParameter = sessionState.LastSessionStateByParameter,
LastTransition = Transitions.ChangedByHotkey
};
}
//Also nothing to change here
//if a hotkey was not used, SessionState and input-parameter should be the same,
//no need to update anything
else
{
Print($"No hotkey was used, SessionState will be assigned {sessionState.LastSessionState}.");
SessionState = new SessionState
{
LastSessionState = sessionState.LastSessionState,
LastSessionStateByParameter = sessionState.LastSessionStateByParameter,
LastTransition = sessionState.LastTransition
};
}
}
}
///
/// Returns true if it can draw the session
/// But also handles if the TimeFrame needs to be changed
///
///
///
///
public bool CheckSessions(SessionPeriod sessionPeriod) =>
sessionPeriod switch
{
SessionPeriod.Daily => CheckSession(sessionPeriod, TimeFrame.Minute5, TimeFrame.Minute30),
SessionPeriod.Weekly => CheckSession(sessionPeriod, TimeFrame.Minute30, TimeFrame.Hour4),
SessionPeriod.Monthly => CheckSession(sessionPeriod, TimeFrame.Hour, TimeFrame.Daily),
SessionPeriod.Quarterly => CheckSession(sessionPeriod, TimeFrame.Hour4, TimeFrame.Daily),
SessionPeriod.Semiannual => CheckSession(sessionPeriod, TimeFrame.Hour4, TimeFrame.Weekly),
SessionPeriod.Annual => CheckSession(sessionPeriod, TimeFrame.Hour4, TimeFrame.Weekly),
SessionPeriod.Intraday => CheckSession(sessionPeriod),
SessionPeriod.Rectangle => CheckSession(sessionPeriod),
_ => true
};
private bool CheckSession(SessionPeriod sessionPeriod)
{
var effectiveTf = TpoSize > 1 ? ResolvedTPOTimeframe : TimeFrame;
if (effectiveTf <= TimeFrame.Minute30)
return true;
if (TpoSize > 1)
{
MessageBox.Show($"TPO Timeframe should not be higher than M30 for {sessionPeriod} sessions. Please change the TPO Timeframe parameter.", "Alert", MessageBoxButton.OK);
return false;
}
var result = MessageBox.Show($"Timeframe should not be higher than M30 for an {sessionPeriod} sessions, do you want to change it?", "Alert", MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
UpdateSessionStateTo(sessionPeriod);
Chart.TryChangeTimeFrame(TimeFrame.Minute30);
}
return false;
}
public bool CheckSession(SessionPeriod sessionPeriod, TimeFrame lowerTf, TimeFrame upperTf)
{
var effectiveTf = TpoSize > 1 ? ResolvedTPOTimeframe : TimeFrame;
if (effectiveTf >= lowerTf && effectiveTf <= upperTf)
return true;
if (TpoSize > 1)
{
MessageBox.Show($"TPO Timeframe should be between {lowerTf} and {upperTf} for a {sessionPeriod} session. Please change the TPO Timeframe parameter.", "Alert", MessageBoxButton.OK);
return false;
}
var result = MessageBox.Show($"Timeframe should be between {lowerTf} and {upperTf} for a {sessionPeriod} session, do you want to change it?", "Alert", MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
UpdateSessionStateTo(sessionPeriod);
Chart.TryChangeTimeFrame(TimeFrame < lowerTf ? lowerTf : upperTf);
}
return false;
}
public LocalStorage LocalStorage => _resources.LocalStorage;
public SessionState SessionState
{
get => _resources.SessionState;
set => _resources.SessionState = value;
}
public string ObjPrefix => _resources.ObjPrefix;
public string StoragePrefix => _resources.StoragePrefix;
public int TpoSize => _resources.TpoSize;
public TimeFrame ResolvedTPOTimeframe => _resources.ResolvedTPOTimeframe;
public TimeFrame TimeFrame => _resources.TimeFrame;
public void Print(object message) => _resources.Print(message);
public SessionPeriod InputSession => _resources.InputSession;
public bool InputSeamlessScrollingMode => _resources.InputSeamlessScrollingMode;
public Chart Chart => _resources.Chart;
}
================================================
FILE: MarketProfile/MarketProfile/MarketProfile.cs
================================================
// -------------------------------------------------------------------------------
//
// Displays the Market Profile indicator for intraday, daily, weekly, monthly, quarterly, semiannual, annual, and free-form trading sessions.
// Daily - should be attached to M5-M30 timeframes. M30 is recommended.
// Weekly - should be attached to M30-H4 timeframes. H1 is recommended.
// Weeks start on Sunday.
// Monthly - should be attached to H1-D1 timeframes. H4 is recommended.
// Quarterly - should be attached to H4-D1 timeframes. D1 is recommended.
// Semiannual - should be attached to H4-W1 timeframes. D1 is recommended.
// Annual - should be attached to H4-W1 timeframes. D1 is recommended.
// Intraday - should be attached to M1-M30 timeframes. M5 is recommended.
// Designed for major currency pairs, but should work also with exotic pairs, CFDs, or commodities.
//
// Version 1.25
// Copyright 2010-2026, EarnForex.com
// https://www.earnforex.com/indicators/MarketProfile/
// -------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using cAlgo.API;
using static cAlgo.Helpers;
namespace cAlgo;
[Indicator(AccessRights = AccessRights.FullAccess, IsOverlay = true)]
public class MarketProfile : Indicator,
IMarketProfileResources,
IIndicatorResources,
IMarketProfileRendererSettings,
ISessionChangeManagerResources,
IHotkeyStateManagerResources,
ISeamlessScrollingManagerResources,
IAlertManagerResources,
IOutputDevelopingValuesManagerResources,
IHideRaysFromInvisibleSessionsFeatureResources,
IRenderingModesResources,
INewHighLowManagerResources,
IRectangleModeProcessorResources
{
#region Parameters
#region Main
[Parameter("Session", DefaultValue = SessionPeriod.Daily, Group = "Main")]
public SessionPeriod InputSession { get; set; }
[Parameter("Start From Date: Lower Priority.", DefaultValue = "", Group = "Main")]
public string InputStartFromDate { get; set; }
[Parameter("Start From Current Session: Higher Priority.", DefaultValue = true, Group = "Main")]
public bool InputStartFromCurrentSession { get; set; }
[Parameter("Sessions To Count: Number of sessions to count Market Profile.", DefaultValue = 2, Group = "Main")]
public int InputSessionsToCount { get; set; }
public int InputOutputDevelopingSessionsToCount => InputSessionsToCount;
[Parameter("Seamless Scrolling Mode: Show Sessions on Current Screen.", DefaultValue = false, Group = "Main")]
public bool InputSeamlessScrollingMode { get; set; }
[Parameter("Enable Developing POC.", DefaultValue = false, Group = "Main")]
public bool InputEnableDevelopingPoC { get; set; }
[Parameter("Enable Developing VAH/VAL.", DefaultValue = false, Group = "Main")]
public bool InputEnableDevelopingValueAtHighValueAtLow { get; set; }
[Parameter("ValueAreaPercentage: Percentage of TPO's inside Value Area.", DefaultValue = 70, Group = "Main")]
public int InputValueAreaPercentage { get; set; }
[Parameter("InstancePrefix: prefix for objects to allow multiple instances.", DefaultValue = "", Group = "Main")]
public string InputInstancePrefix { get; set; }
[Parameter("TPO Timeframe: timeframe for TPO data. Equal or higher than chart's. Set to chart TF or lower for normal mode.", DefaultValue = "Minute")]
public TimeFrame InputTPOTimeframe { get; set; }
#endregion
#region ColorsAndLooks
[Parameter("Start Color", DefaultValue = "#990000FF", Group = "Colors and Looks")]
public Color InputStartColor { get; set; }
[Parameter("End Color", DefaultValue = "#99FF0000", Group = "Colors and Looks")]
public Color InputEndColor { get; set; }
[Parameter("ColorBullBear: If true, colors are from bars' direction.", DefaultValue = false, Group = "Colors and Looks")]
public bool InputColorBullBear { get; set; }
[Parameter("MedianColor", DefaultValue = "White", Group = "Colors and Looks")]
public Color InputMedianColor { get; set; }
[Parameter("Value Area Sides Color", DefaultValue = "White", Group = "Colors and Looks")]
public Color InputValueAreaSidesColor { get; set; }
[Parameter("Value Area High Low Color", DefaultValue = "White", Group = "Colors and Looks")]
public Color InputValueAreaHighLowColor { get; set; }
[Parameter("Median Style", DefaultValue = LineStyle.Solid, Group = "Colors and Looks")]
public LineStyle InputMedianStyle { get; set; }
[Parameter("Median Ray Style", DefaultValue = LineStyle.Lines, Group = "Colors and Looks")]
public LineStyle InputMedianRayStyle { get; set; }
[Parameter("Value Area Sides Style", DefaultValue = LineStyle.Solid, Group = "Colors and Looks")]
public LineStyle InputValueAreaSidesStyle { get; set; }
[Parameter("Value Area High Low Style", DefaultValue = LineStyle.Solid, Group = "Colors and Looks")]
public LineStyle InputValueAreaHighLowStyle { get; set; }
[Parameter("Value Area Ray High Low Style", DefaultValue = LineStyle.Dots, Group = "Colors and Looks")]
public LineStyle InputValueAreaRayHighLowStyle { get; set; }
[Parameter("Median Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputMedianWidth { get; set; }
[Parameter("Median Ray Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputMedianRayWidth { get; set; }
[Parameter("Value Area Sides Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputValueAreaSidesWidth { get; set; }
[Parameter("Value Area High Low Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputValueAreaHighLowWidth { get; set; }
[Parameter("Value Area Ray High Low Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputValueAreaRayHighLowWidth { get; set; }
[Parameter("Show Value Area Rays: draw previous value area high/low rays.", DefaultValue = SessionsToDrawRays.None, Group = "Colors and Looks")]
public SessionsToDrawRays InputShowValueAreaRays { get; set; }
[Parameter("Show Median Rays: draw previous median rays.", DefaultValue = SessionsToDrawRays.None, Group = "Colors and Looks")]
public SessionsToDrawRays InputShowMedianRays { get; set; }
[Parameter("Rays Until Intersection: which rays stop when hit another MP.", DefaultValue = WaysToStopRays.StopNoRays, Group = "Colors and Looks")]
public WaysToStopRays InputRaysUntilIntersection { get; set; }
[Parameter("Hide Rays From Invisible Sessions: hide rays from behind the screen.", DefaultValue = false, Group = "Colors and Looks")]
public bool InputHideRaysFromInvisibleSessions { get; set; }
[Parameter("Time Shift Minutes: shift session + to the left, - to the right.", DefaultValue = 0, Group = "Colors and Looks")]
public int InputTimeShiftMinutes { get; set; }
[Parameter("Show Key Values: print out VAH, VAL, POC on chart.", DefaultValue = true, Group = "Colors and Looks")]
public bool InputShowKeyValues { get; set; }
[Parameter("Key Values Color: color for VAH, VAL, POC printout.", DefaultValue = "White", Group = "Colors and Looks")]
public Color InputKeyValuesColor { get; set; }
[Parameter("Key Values Size: font size for VAH, VAL, POC printout.", DefaultValue = 12, Group = "Colors and Looks")]
public int InputKeyValuesSize { get; set; }
[Parameter("Show Single Print: mark Single Print profile levels.", DefaultValue = SinglePrintType.No, Group = "Colors and Looks")]
public SinglePrintType InputShowSinglePrint { get; set; }
[Parameter("Single Print Color", DefaultValue = "Gold", Group = "Colors and Looks")]
public Color InputSinglePrintColor { get; set; }
[Parameter("Single Print Rays: mark Single Print edges with rays.", DefaultValue = false, Group = "Colors and Looks")]
public bool InputSinglePrintRays { get; set; }
[Parameter("Single Print Ray Style", DefaultValue = LineStyle.Solid, Group = "Colors and Looks")]
public LineStyle InputSinglePrintRayStyle { get; set; }
[Parameter("Single Print Ray Width", DefaultValue = 1, Group = "Colors and Looks")]
public int InputSinglePrintRayWidth { get; set; }
[Parameter("SP Rays Until Intersection: which Single Print rays stop when hit another MP.", DefaultValue = WaysToStopRays.StopNoRays, Group = "Colors and Looks")]
public WaysToStopRays InputSPRaysUntilIntersection { get; set; }
[Parameter("Prominent Median Color", DefaultValue = "Yellow", Group = "Colors and Looks")]
public Color InputProminentMedianColor { get; set; }
[Parameter("Prominent Median Style", DefaultValue = LineStyle.Solid, Group = "Colors and Looks")]
public LineStyle InputProminentMedianStyle { get; set; }
[Parameter("Prominent Median Width", DefaultValue = 4, Group = "Colors and Looks")]
public int InputProminentMedianWidth { get; set; }
[Parameter("Show TPO Counts", DefaultValue = false, Group = "Colors and Looks")]
public bool InputShowTpoCounts { get; set; }
[Parameter("TPO Count Above Color", DefaultValue = "Honeydew", Group = "Colors and Looks")]
public Color InputTpoCountAboveColor { get; set; }
[Parameter("TPO Count Below Color", DefaultValue = "MistyRose", Group = "Colors and Looks")]
public Color InputTpoCountBelowColor { get; set; }
[Parameter("Right To Left: Draw histogram from right to left.", DefaultValue = false, Group = "Colors and Looks")]
public bool InputRightToLeft { get; set; }
#endregion
#region Performance
[Parameter("Point Multiplier: higher value = fewer objects. 0 - adaptive.", DefaultValue = 0, MinValue = 0, Step = 10, Group = "Performance")]
public int InputPointMultiplier { get; set; }
[Parameter("Draw Only Histogram Border", DefaultValue = false, Group = "Performance")]
public bool InputDrawOnlyHistogramBorder { get; set; }
[Parameter("Disable Histogram: do not draw profile, VAH, VAL, and POC still visible.", DefaultValue = false, Group = "Performance")]
public bool InputDisableHistogram { get; set; }
[Parameter("Enable Old Profiles Cleanup: delete old profiles exceeding SessionsToCount.", DefaultValue = false, Group = "Performance")]
public bool InputEnableOldProfilesCleanup { get; set; }
#endregion
#region Alerts
[Parameter("Alert Native: issue native pop-up alerts.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertNative { get; set; }
[Parameter("Alert Native: sound type.", DefaultValue = SoundType.Announcement, Group = "Alerts")]
public SoundType InputAlertSoundType { get; set; }
[Parameter("Alert Email: issue email alerts.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertEmail { get; set; }
[Parameter("Alert Email: Email From.", DefaultValue = "", Group = "Alerts")]
public string InputAlertEmailFrom { get; set; }
[Parameter("Alert Email: Email To.", DefaultValue = "", Group = "Alerts")]
public string InputAlertEmailTo { get; set; }
[Parameter("Alert Arrows: draw chart arrows on alerts.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertArrows { get; set; }
[Parameter("Alert Check Bar: which bar to check for alerts?", DefaultValue = AlertCheckBar.CheckPreviousBar, Group = "Alerts")]
public AlertCheckBar InputAlertCheckBar { get; set; }
[Parameter("Alert For Value Area: alerts for Value Area (VAH, VAL) rays.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertForValueArea { get; set; }
[Parameter("Alert For Median: alerts for POC (Median) rays' crossing.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertForMedian { get; set; }
[Parameter("Alert For Single Print: alerts for single print rays' crossing.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertForSinglePrint { get; set; }
[Parameter("Alert On Price Break: price breaking above/below the ray.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertOnPriceBreak { get; set; }
[Parameter("Alert On Candle Close: candle closing above/below the ray.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertOnCandleClose { get; set; }
[Parameter("Alert On Gap Cross: bar gap above/below the ray.", DefaultValue = false, Group = "Alerts")]
public bool InputAlertOnGapCross { get; set; }
[Parameter("Alert Arrow Color PB: arrow color for price break alerts.", DefaultValue = "Red", Group = "Alerts")]
public Color InputAlertArrowColorPb { get; set; }
[Parameter("Alert Arrow Color CC: arrow color for candle close alerts.", DefaultValue = "Blue", Group = "Alerts")]
public Color InputAlertArrowColorCc { get; set; }
[Parameter("Alert Arrow Color GC: arrow color for gap crossover alerts.", DefaultValue = "Yellow", Group = "Alerts")]
public Color InputAlertArrowColorGc { get; set; }
#endregion
#region IntradaySettings
#region IntradaySession1
[Parameter("Enable", DefaultValue = true, Group = "Intraday Session 1")]
public bool InputEnableIntradaySession1 { get; set; }
[Parameter("Start Time", DefaultValue = "00:00", Group = "Intraday Session 1")]
public string InputIntradaySession1StartTime { get; set; }
[Parameter("End Time", DefaultValue = "06:00", Group = "Intraday Session 1")]
public string InputIntradaySession1EndTime { get; set; }
[Parameter("Color Start", DefaultValue = "#990000FF", Group = "Intraday Session 1")]
public Color InputIntradaySession1ColorStart { get; set; }
[Parameter("Color End", DefaultValue = "#99FF0000", Group = "Intraday Session 1")]
public Color InputIntradaySession1ColorEnd { get; set; }
#endregion
#region IntradaySession2
[Parameter("Enable ", DefaultValue = true, Group = "Intraday Session 2")]
public bool InputEnableIntradaySession2 { get; set; }
[Parameter("Start Time", DefaultValue = "06:00", Group = "Intraday Session 2")]
public string InputIntradaySession2StartTime { get; set; }
[Parameter("End Time", DefaultValue = "12:00", Group = "Intraday Session 2")]
public string InputIntradaySession2EndTime { get; set; }
[Parameter("Color Start", DefaultValue = "#99FF0000", Group = "Intraday Session 2")]
public Color InputIntradaySession2ColorStart { get; set; }
[Parameter("Color End", DefaultValue = "#9900FF00", Group = "Intraday Session 2")]
public Color InputIntradaySession2ColorEnd { get; set; }
#endregion
#region IntradaySession3
[Parameter("Enable ", DefaultValue = true, Group = "Intraday Session 3")]
public bool InputEnableIntradaySession3 { get; set; }
[Parameter("Start Time", DefaultValue = "12:00", Group = "Intraday Session 3")]
public string InputIntradaySession3StartTime { get; set; }
[Parameter("End Time", DefaultValue = "18:00", Group = "Intraday Session 3")]
public string InputIntradaySession3EndTime { get; set; }
[Parameter("Color Start", DefaultValue = "#9900FF00", Group = "Intraday Session 3")]
public Color InputIntradaySession3ColorStart { get; set; }
[Parameter("Color End", DefaultValue = "#990000FF", Group = "Intraday Session 3")]
public Color InputIntradaySession3ColorEnd { get; set; }
#endregion
#region IntradaySession4
[Parameter("Enable", DefaultValue = true, Group = "Intraday Session 4")]
public bool InputEnableIntradaySession4 { get; set; }
[Parameter("Start Time", DefaultValue = "18:00", Group = "Intraday Session 4")]
public string InputIntradaySession4StartTime { get; set; }
[Parameter("End Time", DefaultValue = "00:00", Group = "Intraday Session 4")]
public string InputIntradaySession4EndTime { get; set; }
[Parameter("Color Start", DefaultValue = "#99FFFF00", Group = "Intraday Session 4")]
public Color InputIntradaySession4ColorStart { get; set; }
[Parameter("Color End", DefaultValue = "#9900FFFF", Group = "Intraday Session 4")]
public Color InputIntradaySession4ColorEnd { get; set; }
#endregion
#endregion
#region Miscellaneous
///
/// This seems to only work for the sessions Daily, Weekly and Intraday
///
[Parameter("Saturday Sunday", DefaultValue = SatSunSolution.SaturdaySundayNormalDays, Group = "Miscellaneous")]
public SatSunSolution InputSaturdaySunday { get; set; }
[Parameter("Disable alerts on wrong timeframes.", DefaultValue = false, Group = "Miscellaneous")]
public bool InputDisableAlertsOnWrongTimeframes { get; set; }
[Parameter("Percentage of Median TPOs out of total for a Prominent one.", DefaultValue = 101, Group = "Miscellaneous")]
public int InputProminentMedianPercentage { get; set; }
[Parameter("Debug - Show Exceptions.", DefaultValue = false, Group = "Miscellaneous")]
public bool InputShowExceptions { get; set; }
#endregion
#region Hotkeys
[Parameter("Daily", DefaultValue = "Ctrl+1", Group = "Hotkeys")]
public string InputHotkeyDaily { get; set; }
[Parameter("Weekly", DefaultValue = "Ctrl+2", Group = "Hotkeys")]
public string InputHotkeyWeekly { get; set; }
[Parameter("Monthly", DefaultValue = "Ctrl+3", Group = "Hotkeys")]
public string InputHotkeyMonthly { get; set; }
[Parameter("Quarterly", DefaultValue = "Ctrl+4", Group = "Hotkeys")]
public string InputHotkeyQuarterly { get; set; }
[Parameter("Semiannual", DefaultValue = "Ctrl+5", Group = "Hotkeys")]
public string InputHotkeySemiannual { get; set; }
[Parameter("Annual", DefaultValue = "Ctrl+6", Group = "Hotkeys")]
public string InputHotkeyAnnual { get; set; }
[Parameter("Intraday", DefaultValue = "Ctrl+7", Group = "Hotkeys")]
public string InputHotkeyIntraday { get; set; }
[Parameter("Rectangle", DefaultValue = "Ctrl+8", Group = "Hotkeys")]
public string InputHotkeyRectangle { get; set; }
#endregion
#endregion
#region Outputs
[Output("Developing POC", LineColor = "Green", PlotType = PlotType.Points, Thickness = 4)]
public IndicatorDataSeries OutputDevelopingPoC { get; set; }
[Output("Developing VAH", LineColor = "Goldenrod", PlotType = PlotType.Points, Thickness = 4)]
public IndicatorDataSeries OutputDevelopingVah { get; set; }
[Output("Developing VAL 1", LineColor = "Salmon", PlotType = PlotType.Points, Thickness = 4)]
public IndicatorDataSeries OutputDevelopingVaL { get; set; }
#endregion
private double _numberOfSlices;
private int _digitsM;
private int _tpoSize = 1;
private TimeFrame _tpoTimeFrame;
private Bars _htfBars;
public string ObjPrefix { get; private set; }
public string StoragePrefix { get; private set; }
public int TpoSize => _tpoSize;
public TimeFrame ResolvedTPOTimeframe => _tpoTimeFrame;
public double OneTickSize { get; private set; }
public double ValueAreaPercentage { get; private set; }
public List IntradaySessions { get; private set; }
public List Sessions { get; } = new();
public MarketProfileCalculator Calculator { get; private set; }
public MarketProfileRenderer Renderer { get; private set; }
public HideRaysFromInvisibleSessionsFeature HideRaysFromInvisibleSessionsFeature { get; private set; }
public SessionState SessionState { get; set; }
public SessionChangeManager SessionChangeManager { get; private set; }
public HotkeyStateManager HotkeyStateManager { get; private set; }
public SeamlessScrollingManager SeamlessScrollingManager { get; set; }
public AlertManager AlertManager { get; private set; }
public NewHighLowManager NewHighLowManager { get; set; }
public RectangleModeProcessor RectangleModeProcessor { get; private set; }
public event EventHandler CalculateEvent;
private int _lastBarIndex;
private bool _canDraw;
protected override void Initialize()
{
//System.Diagnostics.Debugger.Launch();
ObjPrefix = InputInstancePrefix + "_";
StoragePrefix = string.IsNullOrEmpty(InputInstancePrefix) ? "" : InputInstancePrefix + " ";
InitializeOneTickSize();
ValueAreaPercentage = InputValueAreaPercentage / 100.0;
// Resolve TPO timeframe: use chart's if selected is lower.
var chartSpan = Helpers.GetBarTimeSpan(TimeFrame);
var tpoSpan = Helpers.GetBarTimeSpan(InputTPOTimeframe);
_tpoSize = (int)(tpoSpan.TotalSeconds / chartSpan.TotalSeconds);
if (_tpoSize < 1) _tpoSize = 1;
_tpoTimeFrame = _tpoSize > 1 ? InputTPOTimeframe : TimeFrame;
// Load HTF bars if needed.
if (_tpoSize > 1)
_htfBars = MarketData.GetBars(_tpoTimeFrame);
SessionChangeManager = new SessionChangeManager(this);
SessionChangeManager.LoadSessionState();
_canDraw = SessionChangeManager.CheckSessions(SessionState.LastSessionState);
if (!_canDraw)
{
Chart.DrawStaticText(ObjPrefix + "MarketProfile-NoSessions", "Please choose a suitable timeframe", VerticalAlignment.Center, HorizontalAlignment.Center, Color.Red);
return;
}
HotkeyStateManager = new HotkeyStateManager(this);
AlertManager = new AlertManager(this);
HideRaysFromInvisibleSessionsFeature = new HideRaysFromInvisibleSessionsFeature(this);
NewHighLowManager = new NewHighLowManager(this);
//ParameterChecks
CheckIsNotStartFromDateAndSeamlessScrollingMode();
IntradaySessions = GetIntradaySessions();
CheckZeroIntradaySessions();
RemoveAllOwnObjects();
Calculator = new MarketProfileCalculator(this);
// Override the calculator's bar timespan for MTF mode.
if (_tpoSize > 1)
Calculator.BarTimeSpan = Helpers.GetBarTimeSpan(_tpoTimeFrame);
Renderer = new MarketProfileRenderer(this, this);
SetSessionsAndAddMarketProfiles(InputSessionsToCount);
RectangleModeProcessor = new RectangleModeProcessor(this);
Bars.BarOpened += _ => AddOrUpdateSessions();
NewHighLowManager.NewHighOnLastBar += (_, _) => AddOrUpdateSessions();
NewHighLowManager.NewLowOnLastBar += (_, _) => AddOrUpdateSessions();
HotkeyStateManager.AddHotkeys();
SeamlessScrollingManager = new SeamlessScrollingManager(this);
if (InputSeamlessScrollingMode)
SeamlessScrollingManager.Start();
if (InputHideRaysFromInvisibleSessions)
HideRaysFromInvisibleSessionsFeature.Start();
}
public override void Calculate(int index)
{
CalculateEvent?.Invoke(this, new CalculateEventArgs { IsLastBar = IsLastBar, Index = index, IsNewBar = index > _lastBarIndex });
if (index > _lastBarIndex)
_lastBarIndex = index;
if (IsLastBar)
AlertManager?.CheckAlerts(index);
}
protected override void OnException(Exception exception)
{
if (InputShowExceptions)
{
var sb = new StringBuilder();
sb.AppendLine($"Exception: {exception.Message}");
sb.AppendLine($"StackTrace: {exception.StackTrace}");
Chart.DrawStaticText(
$"{ObjPrefix}MarketProfile-Exception",
sb.ToString(),
VerticalAlignment.Top,
HorizontalAlignment.Right,
Color.Red);
}
Print($"Exception: {exception.Message}");
Print($"StackTrace: {exception.StackTrace}");
}
private void AddOrUpdateSessions()
{
//must update last volume profile
if (SessionState.LastSessionState == SessionPeriod.Rectangle)
return;
if (Bars.OpenTimes[Chart.LastVisibleBarIndex] != Bars.Last().OpenTime)
return;
var lastSession = Sessions.LastOrDefault();
if (lastSession == null)
{
SetSessionsAndAddMarketProfiles(1);
return;
}
var parsed = DateTime.TryParse(InputStartFromDate, out var startFrom);
if (parsed && !InputStartFromCurrentSession)
return;
// Check if new bar belongs to current session or requires new session
var needNewSession = IsNewSessionRequired(lastSession, Bars.LastBar.OpenTime);
if (needNewSession)
{
SetSessionsAndAddMarketProfiles(1);
// Clean up old profiles if their number exceeds the given SessionsToCount.
if (InputEnableOldProfilesCleanup && Sessions.Count > InputSessionsToCount)
{
var excess = Sessions.Count - InputSessionsToCount;
for (var i = 0; i < excess; i++)
{
Renderer.DeleteAllFromSession(Sessions[0]);
Sessions.RemoveAt(0);
}
}
}
else
UpdateLastSession(session: lastSession);
}
private void RemoveAllOwnObjects()
{
if (string.IsNullOrEmpty(ObjPrefix))
{
Chart.RemoveAllObjects();
return;
}
var toRemove = new List();
foreach (var obj in Chart.Objects)
{
if (obj.Name.StartsWith(ObjPrefix))
toRemove.Add(obj.Name);
}
foreach (var name in toRemove)
Chart.RemoveObject(name);
}
#region MTF Helpers
///
/// Gets higher-timeframe bars covering the given session time range.
/// Uses GetIndexByTime to find the HTF bar that contains the session start time,
/// mirroring the MT5 iBarShift approach.
///
private Bar[] GetHTFBarsForRange(DateTime start, DateTime end)
{
if (_htfBars == null || _tpoSize <= 1) return null;
var htfStartIdx = _htfBars.OpenTimes.GetIndexByTime(start);
var htfEndIdx = _htfBars.OpenTimes.GetIndexByTime(end);
if (htfStartIdx < 0) htfStartIdx = 0;
if (htfEndIdx < 0) return null;
if (htfStartIdx > htfEndIdx) return null;
var result = new List();
for (var i = htfStartIdx; i <= htfEndIdx; i++)
result.Add(_htfBars[i]);
return result.Count > 0 ? result.ToArray() : null;
}
///
/// In MTF mode, the developing POC/VAH/VAL output buffers only have values at HTF bar boundaries.
/// This fills the gaps between them so intermediate chart bars display the same value.
///
private void ForwardFillDevelopingValues(DateTime sessionStart, DateTime sessionEnd)
{
var startIdx = Bars.OpenTimes.GetIndexByTime(sessionStart);
var endIdx = Math.Min(Bars.OpenTimes.GetIndexByTime(sessionEnd), Bars.Count - 1);
// Fill NaN gaps between HTF bar anchor values written by RenderDeveloping*.
// ClearOutputsOnRange was called first, so only anchor positions have values — gaps are NaN.
for (var i = startIdx + 1; i <= endIdx; i++)
{
if (InputEnableDevelopingPoC && double.IsNaN(OutputDevelopingPoC[i]) && !double.IsNaN(OutputDevelopingPoC[i - 1]))
OutputDevelopingPoC[i] = OutputDevelopingPoC[i - 1];
if (InputEnableDevelopingValueAtHighValueAtLow)
{
if (double.IsNaN(OutputDevelopingVah[i]) && !double.IsNaN(OutputDevelopingVah[i - 1]))
OutputDevelopingVah[i] = OutputDevelopingVah[i - 1];
if (double.IsNaN(OutputDevelopingVaL[i]) && !double.IsNaN(OutputDevelopingVaL[i - 1]))
OutputDevelopingVaL[i] = OutputDevelopingVaL[i - 1];
}
}
}
#endregion
private void UpdateLastSession(MarketProfileSession session)
{
var strategy = SessionState.LastSessionState switch
{
SessionPeriod.Daily => SessionProfileStrategyFactory.CreateDaily(this, this),
SessionPeriod.Weekly => SessionProfileStrategyFactory.CreateWeekly(this, this),
SessionPeriod.Monthly => SessionProfileStrategyFactory.CreateMonthly(this, this),
SessionPeriod.Quarterly => SessionProfileStrategyFactory.CreateQuarterly(this, this),
SessionPeriod.Semiannual => SessionProfileStrategyFactory.CreateSemiannual(this, this),
SessionPeriod.Annual => SessionProfileStrategyFactory.CreateAnnual(this, this),
SessionPeriod.Intraday => SessionProfileStrategyFactory.CreateIntradaySessions(IntradaySessions, this, this),
SessionPeriod.Rectangle => null,
_ => null
};
if (strategy == null)
return;
var ranges = strategy.GetSessionRanges(Bars, 1, InputStartColor, InputEndColor).ToArray();
//there should be only one range
if (ranges.Length != 1)
throw new Exception("There should be only one range");
if (session.Range.Start != ranges[0].Start)
return;
session.Range = ranges[0];
if (!session.Range.Bars.Any())
{
// Skip this session or handle empty range
Print($"Warning: No bars found for session range {session.Range.Start} to {session.Range.End}");
return; // or continue to next session
}
// In MTF mode, use higher-timeframe bars for the calculation.
var bars = _tpoSize > 1 ? GetHTFBarsForRange(session.Range.Start, session.Range.End) : session.Range.Bars.ToArray();
if (bars == null || bars.Length == 0)
{
Print($"Warning: No bars available for session range {session.Range.Start} to {session.Range.End}");
return;
}
var highMinusLow = bars.Max(x => x.High) - bars.Min(x => x.Low);
var slices = (int) (highMinusLow / OneTickSize);
if (slices == 0)
{
Print($"Slices is 0 | This can't be processed Bars is {bars.Length} (High {bars.Max(x => x.High)} | Low {bars.Min(x => x.Low)} Minus Low is {highMinusLow}) | OneTickSize is {OneTickSize}");
return;
}
var profileModel = Calculator.FillAndPileMatrixCalculation(bars, slices, session.Range.StartColor, session.Range.EndColor);
//these two below could be totally removed and reference the latest "developing" values
var (vah, val) = Calculator.GetValueArea(profileModel.Matrix, InputValueAreaPercentage / 100.0);
var pointOfControlRowIndex = MarketProfileCalculator.GetPointOfControlRowIndex(profileModel.Matrix);
if (profileModel.Matrix[pointOfControlRowIndex, 0] == null)
{
Print($"Unable to calculate POC because the row is null");
return;
}
var pointOfControlPrice = MarketProfileCalculator.GetPointOfControlPrice(profileModel.Matrix, pointOfControlRowIndex);
var (totalTopBlocksAbovePointOfControl, totalBottomBlocksBelowPointOfControl) = MarketProfileCalculator.GetValuesAroundPointOfControl(profileModel.Matrix);
profileModel.ValueAreaHigh = vah;
profileModel.ValueAreaLow = val;
profileModel.PointOfControl = pointOfControlPrice;
profileModel.Median = Calculator.GetMedianPrice(profileModel.Matrix);
profileModel.TpoCountAbove = totalTopBlocksAbovePointOfControl;
profileModel.TpoCountBelow = totalBottomBlocksBelowPointOfControl;
profileModel.SinglePrints.AddRange(MarketProfileCalculator.GetSinglePrints(profileModel.Matrix));
profileModel.IsProminentLine = Calculator.IsProminentLine(profileModel.Matrix, InputProminentMedianPercentage / 100.0);
session.Model = profileModel;
// Clear output buffers for this session range, then re-render developing values.
// Must happen BEFORE DeleteAllFromSession which empties the developing dictionaries.
Renderer.ClearOutputsOnRange(session.Range.Start, session.Range.End);
if (InputEnableDevelopingPoC)
Renderer.RenderDevelopingPoc(profileModel.DevelopingPoC);
if (InputEnableDevelopingValueAtHighValueAtLow)
{
Renderer.RenderDevelopingVahs(profileModel.DevelopingAreaHigh);
Renderer.RenderDevelopingVals(profileModel.DevelopingAreaLow);
}
// In MTF mode, forward-fill developing values across intermediate chart bars.
if (_tpoSize > 1 && (InputEnableDevelopingPoC || InputEnableDevelopingValueAtHighValueAtLow))
ForwardFillDevelopingValues(session.Range.Start, session.Range.End);
Renderer.DeleteAllFromSession(session);
if (InputRightToLeft)
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderHorizontallyFlippedProfile(profileModel.Matrix, session);
session.ValueArea = Renderer.RenderHorizontallyFlippedValueArea(profileModel, session);
session.KeyValues = Renderer.RenderHorizontallyFlippedKeyValues(profileModel, session);
session.TpoCounts = Renderer.RenderHorizontallyFlippedTpoCounts(profileModel, session);
session.ProminentLine = Renderer.RenderHorizontallyFlippedProminentLine(profileModel, session);
}
else
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderProfile(profileModel.Matrix);
session.ValueArea = Renderer.RenderValueArea(profileModel);
session.ValueAreaRays = Renderer.RenderValueAreaRays(profileModel, Sessions.Count - 1);
session.MedianRays = Renderer.RenderPointOfControlRays(profileModel, Sessions.Count - 1);
session.KeyValues = Renderer.RenderKeyValues(profileModel);
session.TpoCounts = Renderer.RenderTpoCounts(profileModel);
session.SinglePrints = Renderer.RenderSinglePrints(profileModel);
session.ProminentLine = Renderer.RenderProminentLine(profileModel);
Renderer.PostProcessPointOfControlRays(Sessions);
Renderer.PostProcessValueAreaRays(Sessions);
Renderer.PostProcessSinglePrintRays(Sessions);
}
}
public bool IsNewSessionRequired(MarketProfileSession lastSession, DateTime newBarTime)
{
// If new bar's time is after the session's end time, we need a new session
if (newBarTime > lastSession.Range.End)
return true;
return SessionState.LastSessionState switch
{
SessionPeriod.Daily =>
// For daily, check if we've crossed into a new day (adjusted for market open)
!SameSessionDay(lastSession.Range.Start, newBarTime),
SessionPeriod.Weekly =>
// For weekly, check if we've crossed into a new week
GetWeekNumber(lastSession.Range.Start) != GetWeekNumber(newBarTime),
SessionPeriod.Monthly =>
// For monthly, check if we've crossed into a new month
lastSession.Range.Start.Month != newBarTime.Month || lastSession.Range.Start.Year != newBarTime.Year,
SessionPeriod.Quarterly =>
// For quarterly, check if we've crossed into a new quarter
GetQuarter(lastSession.Range.Start) != GetQuarter(newBarTime) || lastSession.Range.Start.Year != newBarTime.Year,
SessionPeriod.Semiannual =>
// For semiannual, check if we've crossed into a new half-year
(lastSession.Range.Start.Month <= 6 && newBarTime.Month > 6) || (lastSession.Range.Start.Month > 6 && newBarTime.Month <= 6) || lastSession.Range.Start.Year != newBarTime.Year,
SessionPeriod.Annual =>
// For annual, check if we've crossed into a new year
lastSession.Range.Start.Year != newBarTime.Year,
SessionPeriod.Intraday =>
// For intraday, check if the new bar is in a different intraday session
!SameIntradaySession(lastSession.Range.Start, newBarTime),
_ => false
};
}
private bool SameIntradaySession(DateTime sessionStart, DateTime barTime)
{
// Implement logic to check if a bar belongs to the same intraday session
// This would need to check the intraday session definitions
foreach (var session in IntradaySessions)
{
// Check if both times fall within the same intraday session
// This is a simplified check and may need to be enhanced
if (IsInIntradaySession(sessionStart, session) &&
IsInIntradaySession(barTime, session))
return true;
}
return false;
}
private void InitializeOneTickSize()
{
if (InputPointMultiplier == 0)
{
var quote = Ask;
//Get chart dimensions and price range
var chartHeight = Chart.Height;
var chartPriceMax = Chart.TopY;
var chartPriceMin = Chart.BottomY;
var priceDiff = chartPriceMax - chartPriceMin;
//todo Chart.BottomY is -0 when backtesting, should report for fixing
//Print($"Chart Price Max {chartPriceMax} Min {chartPriceMin} Diff {priceDiff}");
if ((chartHeight <= 0) || (priceDiff <= 0)) //If no chart yet, do it old fashion
{
var s = quote.ToString($"F{Symbol.Digits}");
var totalDigits = s.Length;
// If there is a dot in a quote.
if (s.Contains(',') || s.Contains('.'))
totalDigits--; // Decrease the count of digits by one.
_numberOfSlices = totalDigits <= 5 ? 1 : (int)Math.Pow(10, totalDigits - 5);
}
else // otherwise, calculate the multiplier so that 1 TPO = 1 pixel
{
var pricePerPixel = priceDiff / chartHeight;
_numberOfSlices = (int)Math.Round(pricePerPixel / Symbol.TickSize);
}
}
else
{
_numberOfSlices = InputPointMultiplier;
}
// Based on number of digits in PointMultiplier_calculated. -1 because if PointMultiplier_calculated < 10, it does not modify the number of digits.
_digitsM = Math.Max(0, Symbol.Digits - (_numberOfSlices.ToString(CultureInfo.InvariantCulture).Length - 1));
OneTickSize = Math.Round(Symbol.TickSize * _numberOfSlices, _digitsM);
// Adjust for TickSize granularity if needed.
var tickSize = Symbol.TickSize;
if (OneTickSize < tickSize)
{
_digitsM = Symbol.Digits - (((int)Math.Round(tickSize / Symbol.TickSize)).ToString().Length - 1);
OneTickSize = Math.Round(tickSize, _digitsM);
}
}
public bool SetSessionsAndAddMarketProfiles(int sessionsToCount, DateTime? endAt = null)
{
var strategy = SessionState.LastSessionState switch
{
SessionPeriod.Daily => SessionProfileStrategyFactory.CreateDaily(this, this),
SessionPeriod.Weekly => SessionProfileStrategyFactory.CreateWeekly(this, this),
SessionPeriod.Monthly => SessionProfileStrategyFactory.CreateMonthly(this, this),
SessionPeriod.Quarterly => SessionProfileStrategyFactory.CreateQuarterly(this, this),
SessionPeriod.Semiannual => SessionProfileStrategyFactory.CreateSemiannual(this, this),
SessionPeriod.Annual => SessionProfileStrategyFactory.CreateAnnual(this, this),
SessionPeriod.Intraday => SessionProfileStrategyFactory.CreateIntradaySessions(IntradaySessions, this, this),
SessionPeriod.Rectangle => null,
_ => null
};
if (strategy == null)
return false;
var ranges = strategy.GetSessionRanges(Bars, sessionsToCount, InputStartColor, InputEndColor, endAt).ToArray();
for (var index = 0; index < ranges.Length; index++)
{
var range = ranges[index];
Renderer.ClearOutputsOnRange(range.Start, range.End);
var session = new MarketProfileSession
{
Range = range,
};
BuildAndRender(range, session, index, ranges.Length);
}
Renderer.PostProcessPointOfControlRays(Sessions);
Renderer.PostProcessValueAreaRays(Sessions);
Renderer.PostProcessSinglePrintRays(Sessions);
return true;
}
private bool BuildAndRender(SessionRange range, MarketProfileSession session, int index, int total)
{
if (!range.Bars.Any())
{
// Skip this session or handle empty range
Print($"Warning: No bars found for session range {range.Start} to {range.End}");
return false; // or continue to next session
}
// In MTF mode, use higher-timeframe bars for the calculation.
var bars = _tpoSize > 1 ? GetHTFBarsForRange(range.Start, range.End) : range.Bars.ToArray();
if (bars == null || bars.Length == 0)
{
Print($"Warning: No bars available for session range {range.Start} to {range.End}");
return false;
}
var slices = Calculator.GetSlices(bars);
if (slices == 0)
{
Print($"Slices is 0 | This can't be processed Bars is {bars.Length} (High {bars.Max(x => x.High)} | Low {bars.Min(x => x.Low)} | OneTickSize is {OneTickSize}");
return false;
}
var profileModel = Calculator.FillAndPileMatrixCalculation(bars, slices, range.StartColor, range.EndColor);
//these two below could be totally removed and reference the latest "developing" values
//var (vah, val) = Calculator.GetValueArea(profileModel.Matrix, InputValueAreaPercentage / 100.0);
var vah = profileModel.DevelopingAreaHigh.LastOrDefault().Value;
var val = profileModel.DevelopingAreaLow.LastOrDefault().Value;
var pointOfControlRowIndex = MarketProfileCalculator.GetPointOfControlRowIndex(profileModel.Matrix);
if (profileModel.Matrix[pointOfControlRowIndex, 0] == null)
{
Print($"Unable to calculate POC because the row is null");
return false;
}
var pointOfControlPrice = MarketProfileCalculator.GetPointOfControlPrice(profileModel.Matrix, pointOfControlRowIndex);
var (totalTopBlocksAbovePointOfControl, totalBottomBlocksBelowPointOfControl) = MarketProfileCalculator.GetValuesAroundPointOfControl(profileModel.Matrix);
profileModel.ValueAreaHigh = vah;
profileModel.ValueAreaLow = val;
profileModel.PointOfControl = pointOfControlPrice;
profileModel.Median = Calculator.GetMedianPrice(profileModel.Matrix);
profileModel.TpoCountAbove = totalTopBlocksAbovePointOfControl;
profileModel.TpoCountBelow = totalBottomBlocksBelowPointOfControl;
profileModel.SinglePrints.AddRange(MarketProfileCalculator.GetSinglePrints(profileModel.Matrix));
profileModel.IsProminentLine = Calculator.IsProminentLine(profileModel.Matrix, InputProminentMedianPercentage / 100.0);
session.Model = profileModel;
if (index == 0 && InputRightToLeft)
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderHorizontallyFlippedProfile(profileModel.Matrix, session);
session.ValueArea = Renderer.RenderHorizontallyFlippedValueArea(profileModel, session);
session.KeyValues = Renderer.RenderHorizontallyFlippedKeyValues(profileModel, session);
session.TpoCounts = Renderer.RenderHorizontallyFlippedTpoCounts(profileModel, session);
session.ProminentLine = Renderer.RenderHorizontallyFlippedProminentLine(profileModel, session);
}
else
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderProfile(profileModel.Matrix);
session.ValueArea = Renderer.RenderValueArea(profileModel);
session.ValueAreaRays = Renderer.RenderValueAreaRays(profileModel, index);
session.MedianRays = Renderer.RenderPointOfControlRays(profileModel, index);
session.KeyValues = Renderer.RenderKeyValues(profileModel);
session.TpoCounts = Renderer.RenderTpoCounts(profileModel);
session.ProminentLine = Renderer.RenderProminentLine(profileModel);
}
if (InputEnableDevelopingPoC)
Renderer.RenderDevelopingPoc(profileModel.DevelopingPoC);
if (InputEnableDevelopingValueAtHighValueAtLow)
{
Renderer.RenderDevelopingVahs(profileModel.DevelopingAreaHigh);
Renderer.RenderDevelopingVals(profileModel.DevelopingAreaLow);
}
// In MTF mode, forward-fill developing values across intermediate chart bars.
if (_tpoSize > 1 && (InputEnableDevelopingPoC || InputEnableDevelopingValueAtHighValueAtLow))
ForwardFillDevelopingValues(range.Start, range.End);
session.SinglePrints = Renderer.RenderSinglePrints(profileModel);
Sessions.Add(session);
return true;
}
public List GetIntradaySessions()
{
//initialize intraday sessions
var sessions = new List();
if (InputEnableIntradaySession1)
sessions.Add(new IntradaySessionDefinition
{
Name = "Intraday 1",
Start = TimeSpan.Parse(InputIntradaySession1StartTime),
End = TimeSpan.Parse(InputIntradaySession1EndTime),
StartColor = InputIntradaySession1ColorStart,
EndColor = InputIntradaySession1ColorEnd
});
if (InputEnableIntradaySession2)
sessions.Add(new IntradaySessionDefinition
{
Name = "Intraday 2",
Start = TimeSpan.Parse(InputIntradaySession2StartTime),
End = TimeSpan.Parse(InputIntradaySession2EndTime),
StartColor = InputIntradaySession2ColorStart,
EndColor = InputIntradaySession2ColorEnd
});
if (InputEnableIntradaySession3)
sessions.Add(new IntradaySessionDefinition
{
Name = "Intraday 3",
Start = TimeSpan.Parse(InputIntradaySession3StartTime),
End = TimeSpan.Parse(InputIntradaySession3EndTime),
StartColor = InputIntradaySession3ColorStart,
EndColor = InputIntradaySession3ColorEnd
});
if (InputEnableIntradaySession4)
sessions.Add(new IntradaySessionDefinition
{
Name = "Intraday 4",
Start = TimeSpan.Parse(InputIntradaySession4StartTime),
End = TimeSpan.Parse(InputIntradaySession4EndTime),
StartColor = InputIntradaySession4ColorStart,
EndColor = InputIntradaySession4ColorEnd
});
return sessions;
}
#region Checks
private void CheckIsNotStartFromDateAndSeamlessScrollingMode()
{
var parsed = DateTime.TryParse(InputStartFromDate, out var startFrom);
if (parsed && InputSeamlessScrollingMode && !InputStartFromCurrentSession)
throw new ArgumentException("Seamless scrolling mode doesn't work with Start From Date Mode.");
}
public void CheckZeroIntradaySessions()
{
if (IntradaySessions.Count == 0 && SessionState.LastSessionState == SessionPeriod.Intraday)
throw new ArgumentException("Enable at least one intraday session if you want to use Intraday mode.");
}
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/MarketProfile.csproj
================================================
net6.0
================================================
FILE: MarketProfile/MarketProfile/MarketProfileRenderer.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo;
public interface IMarketProfileRendererSettings
{
bool InputColorBullBear { get; }
Color InputStartColor { get; }
Color InputEndColor { get; }
Color InputMedianColor { get; }
Color InputValueAreaSidesColor { get; }
Color InputValueAreaHighLowColor { get; }
LineStyle InputMedianStyle { get; }
LineStyle InputMedianRayStyle { get; }
LineStyle InputValueAreaSidesStyle { get; }
LineStyle InputValueAreaHighLowStyle { get; }
LineStyle InputValueAreaRayHighLowStyle { get; }
int InputMedianWidth { get; }
int InputMedianRayWidth { get; }
int InputValueAreaSidesWidth { get; }
int InputValueAreaHighLowWidth { get; }
int InputValueAreaRayHighLowWidth { get; }
SessionsToDrawRays InputShowValueAreaRays { get; }
SessionsToDrawRays InputShowMedianRays { get; }
WaysToStopRays InputRaysUntilIntersection { get; }
// bool InputHideRaysFromInvisibleSessions { get; }
int InputTimeShiftMinutes { get; }
bool InputShowKeyValues { get; }
Color InputKeyValuesColor { get; }
int InputKeyValuesSize { get; }
SinglePrintType InputShowSinglePrint { get; }
Color InputSinglePrintColor { get; }
bool InputSinglePrintRays { get; }
LineStyle InputSinglePrintRayStyle { get; }
int InputSinglePrintRayWidth { get; }
WaysToStopRays InputSPRaysUntilIntersection { get; }
Color InputProminentMedianColor { get; }
bool InputDrawOnlyHistogramBorder { get; }
LineStyle InputProminentMedianStyle { get; }
int InputProminentMedianWidth { get; }
bool InputShowTpoCounts { get; }
Color InputTpoCountAboveColor { get; }
Color InputTpoCountBelowColor { get; }
// bool InputRightToLeft { get; }
MarketProfileCalculator Calculator { get; }
string ObjPrefix { get; }
Bars Bars { get; }
IndicatorDataSeries OutputDevelopingPoC { get; }
IndicatorDataSeries OutputDevelopingVah { get; }
IndicatorDataSeries OutputDevelopingVaL { get; }
}
public class MarketProfileRenderer : IMarketProfileResources, IMarketProfileRendererSettings
{
private readonly IMarketProfileResources _resources;
private readonly IMarketProfileRendererSettings _settings;
private readonly string _format;
private readonly TimeSpan _barTimeSpan;
public MarketProfileRenderer(IMarketProfileResources resources, IMarketProfileRendererSettings settings)
{
_resources = resources;
_settings = settings;
_format = $"0.{new string('0', Symbol.Digits)}";
_barTimeSpan = Helpers.GetBarTimeSpan(TimeFrame);
}
public List RenderProfile(MatrixPoint[,] matrix)
{
// var stopwatch = Stopwatch.StartNew();
var result = new List();
var matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < matrix.GetLength(0); row++)
{
if (matrix[row, 0] == null)
continue;
matrixStartTime = matrix[row, 0].StartTime.Ticks;
break;
}
for (var row = 0; row < matrix.GetLength(0); row++)
for (var column = 0; column < matrix.GetLength(1); column++)
{
var point = matrix[row, column];
if (point == null)
continue;
var nextPoint = matrix[row, Math.Min(column + 1, matrix.GetLength(1) - 1)];
if (InputDrawOnlyHistogramBorder && nextPoint != null)
continue;
//Override the color with the direction if InputColorBullBear is true
Color color;
if (InputColorBullBear)
color = point.Direction == Direction.Up ? InputStartColor : InputEndColor;
else
color = point.Color;
var r = Chart.DrawRectangle(
$"{ObjPrefix}{matrixStartTime}-row{row}column{column}",
point.StartTime.AddMinutes(-InputTimeShiftMinutes),
point.Bottom,
point.EndTime.AddMinutes(-InputTimeShiftMinutes),
point.Top,
color);
//r.LineStyle = LineStyle.DotsVeryRare;
r.Thickness = 0;
r.IsFilled = true;
//r.IsInteractive = true;
result.Add(r);
}
// stopwatch.Stop();
// Print($"RenderProfile Took: {stopwatch.ElapsedMilliseconds} ms");
//
return result;
}
public List RenderHorizontallyFlippedProfile(MatrixPoint[,] matrix, MarketProfileSession session)
{
var result = new List();
// Find the earliest and latest times in the matrix
DateTime earliestTime = DateTime.MaxValue;
DateTime latestTime = DateTime.MinValue;
var startPoint = session.Range.Bars.Last().OpenTime;
for (var row = 0; row < matrix.GetLength(0); row++)
for (var column = 0; column < matrix.GetLength(1); column++)
{
var point = matrix[row, column];
if (point == null)
continue;
earliestTime = DateTime.Compare(earliestTime, point.StartTime) > 0 ? point.StartTime : earliestTime;
latestTime = DateTime.Compare(latestTime, point.EndTime) < 0 ? point.EndTime : latestTime;
}
var timeOffset = startPoint - latestTime;
var matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < matrix.GetLength(0); row++)
{
if (matrix[row, 0] == null)
continue;
matrixStartTime = matrix[row, 0].StartTime.Ticks;
break;
}
// Draw each point with flipped times
for (var row = 0; row < matrix.GetLength(0); row++)
{
for (var column = 0; column < matrix.GetLength(1); column++)
{
var point = matrix[row, column];
if (point == null)
continue;
var nextPoint = matrix[row, Math.Min(column + 1, matrix.GetLength(1) - 1)];
if (InputDrawOnlyHistogramBorder && nextPoint != null)
continue;
// Calculate flipped times
TimeSpan startOffset = point.StartTime - earliestTime;
TimeSpan endOffset = point.EndTime - earliestTime;
DateTime flippedStartTime = latestTime - endOffset + timeOffset;
DateTime flippedEndTime = latestTime - startOffset + timeOffset;
// Set color
Color color;
if (InputColorBullBear)
color = point.Direction == Direction.Up ? InputStartColor : InputEndColor;
else
color = point.Color;
var r = Chart.DrawRectangle(
$"{ObjPrefix}{matrixStartTime}-{row}{column}",
flippedStartTime.AddMinutes(-InputTimeShiftMinutes),
point.Bottom,
flippedEndTime.AddMinutes(-InputTimeShiftMinutes),
point.Top,
color);
r.Thickness = 0;
r.IsFilled = true;
result.Add(r);
}
}
return result;
}
public List RenderValueArea(MarketProfileModel model)
{
var vah = model.ValueAreaHigh;
var val = model.ValueAreaLow;
var pointOfControl = model.PointOfControl;
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
var matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < model.Matrix.GetLength(0); row++)
{
if (model.Matrix[row, 0] == null)
continue;
matrixStartTime = model.Matrix[row, 0].StartTime.Ticks;
break;
}
//Print($"Median: {median} val: {val} vah: {vah}");
//Chart.DrawVerticalLine($"Left-{Guid.NewGuid()}", model.EndTime, Color.White);
var result = new List
{
Chart.DrawTrendLine($"{ObjPrefix}VAH-{matrixStartTime}", model.StartTime, val, pointOfControlRowEndTime, val, InputValueAreaHighLowColor, InputValueAreaHighLowWidth, InputValueAreaHighLowStyle),
Chart.DrawTrendLine($"{ObjPrefix}VAL-{matrixStartTime}", model.StartTime, vah, pointOfControlRowEndTime, vah, InputValueAreaHighLowColor, InputValueAreaHighLowWidth, InputValueAreaHighLowStyle),
Chart.DrawTrendLine($"{ObjPrefix}Left-Boundary-{matrixStartTime}", model.StartTime, val, model.StartTime, vah, InputValueAreaSidesColor, InputValueAreaSidesWidth, InputValueAreaSidesStyle),
Chart.DrawTrendLine($"{ObjPrefix}Right-Boundary-{matrixStartTime}", pointOfControlRowEndTime, val, pointOfControlRowEndTime, vah, InputValueAreaSidesColor, InputValueAreaSidesWidth, InputValueAreaSidesStyle),
Chart.DrawTrendLine($"{ObjPrefix}PointOfControl-{matrixStartTime}", model.StartTime, pointOfControl, pointOfControlRowEndTime, pointOfControl, InputMedianColor, InputMedianWidth, InputMedianStyle),
};
return result;
}
public List RenderHorizontallyFlippedValueArea(MarketProfileModel model, MarketProfileSession session)
{
var valueAreaObjects = RenderValueArea(model);
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
var timeSpan = pointOfControlRowEndTime - model.StartTime;
foreach (var obj in valueAreaObjects)
{
if (obj is not ChartTrendLine trendLine)
continue;
if (trendLine.Name.Contains("VAH") || trendLine.Name.Contains("VAL"))
{
trendLine.Time1 = session.Range.Bars.Last().OpenTime;
trendLine.Time2 = trendLine.Time1.Add(-timeSpan);
}
else if (trendLine.Name.Contains("Left"))
{
trendLine.Time1 = session.Range.Bars.Last().OpenTime;
trendLine.Time2 = session.Range.Bars.Last().OpenTime;
}
else if (trendLine.Name.Contains("Right"))
{
trendLine.Time1 = session.Range.Bars.Last().OpenTime.Add(-timeSpan);
trendLine.Time2 = session.Range.Bars.Last().OpenTime.Add(-timeSpan);
}
else if (trendLine.Name.Contains("PointOfControl"))
{
trendLine.Time1 = session.Range.Bars.Last().OpenTime;
trendLine.Time2 = trendLine.Time1.Add(-timeSpan);
}
}
return valueAreaObjects;
}
public List RenderPointOfControlRays(MarketProfileModel model, int index)
{
var result = new List();
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
var medianRowEndTime1MinAfter = pointOfControlRowEndTime.AddMinutes(1);
switch (InputShowMedianRays)
{
case SessionsToDrawRays.None:
break;
case SessionsToDrawRays.Previous when index == 1:
case SessionsToDrawRays.Current when index == 0:
case SessionsToDrawRays.PreviousCurrent when index <= 1:
case SessionsToDrawRays.AllPrevious when index > 0:
case SessionsToDrawRays.All:
var pointOfControlRay = Chart.DrawTrendLine($"{ObjPrefix}PointOfControlRay-Previous-{model.StartTime}", pointOfControlRowEndTime, model.PointOfControl, medianRowEndTime1MinAfter, model.PointOfControl, InputMedianColor, InputMedianRayWidth, InputMedianRayStyle);
pointOfControlRay.ExtendToInfinity = true;
result.Add(pointOfControlRay);
break;
}
return result;
}
public void RenderDevelopingVals(Dictionary developingVals)
{
foreach (var (col, valRow) in developingVals)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingVaL[idx] = valRow;
}
}
public void ClearDevelopingVals(Dictionary developingVals)
{
foreach (var (col, valRow) in developingVals)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingVaL[idx] = double.NaN;
}
}
public void RenderDevelopingVahs(Dictionary developingVahs)
{
foreach (var (col, vahRow) in developingVahs)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingVah[idx] = vahRow;
}
}
public void ClearDevelopingVahs(Dictionary developingVahs)
{
foreach (var (col, vahRow) in developingVahs)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingVah[idx] = double.NaN;
}
}
public void RenderDevelopingPoc(Dictionary developingPoC)
{
foreach (var (col, pocRow) in developingPoC)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingPoC[idx] = pocRow;
}
}
public void ClearDevelopingPoc(Dictionary developingPoC)
{
foreach (var (col, pocRow) in developingPoC)
{
var idx = Bars.OpenTimes.GetIndexByTime(col);
OutputDevelopingPoC[idx] = double.NaN;
}
}
public void PostProcessPointOfControlRays(List sessions)
{
var sortedSessions = sessions.OrderBy(s => s.Model.StartTime).ToList();
for (var i = 0; i < sortedSessions.Count; i++)
{
if (sortedSessions[i].MedianRays != null)
PostProcessPointOfControlRay(sortedSessions[i].MedianRays.FirstOrDefault(), i, sortedSessions);
}
}
public void PostProcessPointOfControlRay(ChartObject pointOfControlRay, int index, List sessions)
{
if (pointOfControlRay is not ChartTrendLine trendLine)
return;
//let's try only with index = 0
var session = sessions[index];
if (index == sessions.Count - 1)
return;
for (var i = index + 1; i < sessions.Count; i++)
{
var nextSession = sessions[i];
var nextSessionTopPrice = MarketProfileCalculator.GetTopPrice(nextSession.Model.Matrix);
var nextSessionBottomPrice = MarketProfileCalculator.GetBottomPrice(nextSession.Model.Matrix);
//For debugging
// switch (InputRaysUntilIntersection)
// {
// case WaysToStopRays.StopNoRays:
// break;
// case WaysToStopRays.StopAllRays:
// break;
// case WaysToStopRays.StopAllRaysExceptPrevSession:
// if (index != sessions.Count - 2)
// trendLine.Color = Color.HotPink;
// break;
// case WaysToStopRays.StopOnlyPreviousSession:
// if (index == sessions.Count - 2)
// trendLine.Color = Color.Lime;
// break;
// }
if (session.Model.PointOfControl >= nextSessionBottomPrice && session.Model.PointOfControl <= nextSessionTopPrice)
{
switch (InputRaysUntilIntersection)
{
case WaysToStopRays.StopNoRays:
trendLine.ExtendToInfinity = true;
return;
case WaysToStopRays.StopAllRays:
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
return;
case WaysToStopRays.StopAllRaysExceptPrevSession:
if (index != sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;;
}
return;
case WaysToStopRays.StopOnlyPreviousSession:
if (index == sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
}
return;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
public List RenderValueAreaRays(MarketProfileModel model, int index)
{
var result = new List();
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
//since this is a ray, I just need 1 min after to draw in the right direction
var pointOfControlRowEndTime1MinAfter = pointOfControlRowEndTime.AddMinutes(1);
var matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < model.Matrix.GetLength(0); row++)
{
if (model.Matrix[row, 0] == null)
continue;
matrixStartTime = model.Matrix[row, 0].StartTime.Ticks;
break;
}
switch (InputShowValueAreaRays)
{
case SessionsToDrawRays.None:
break;
case SessionsToDrawRays.Previous when index == 1:
case SessionsToDrawRays.Current when index == 0:
case SessionsToDrawRays.PreviousCurrent when index <= 1:
case SessionsToDrawRays.AllPrevious when index > 0:
case SessionsToDrawRays.All:
var varHigh = Chart.DrawTrendLine($"{ObjPrefix}ValueAreaRayHigh-Previous-{matrixStartTime}", pointOfControlRowEndTime, model.ValueAreaHigh, pointOfControlRowEndTime1MinAfter, model.ValueAreaHigh, InputValueAreaHighLowColor, InputValueAreaRayHighLowWidth, InputValueAreaRayHighLowStyle);
varHigh.ExtendToInfinity = true;
result.Add(varHigh);
var varLow = Chart.DrawTrendLine($"{ObjPrefix}ValueAreaRayLow-Previous-{matrixStartTime}", pointOfControlRowEndTime, model.ValueAreaLow, pointOfControlRowEndTime1MinAfter, model.ValueAreaLow, InputValueAreaHighLowColor, InputValueAreaRayHighLowWidth, InputValueAreaRayHighLowStyle);
varLow.ExtendToInfinity = true;
result.Add(varLow);
break;
}
return result;
}
public void PostProcessValueAreaRays(List sessions)
{
var sortedSessions = sessions.OrderBy(s => s.Model.StartTime).ToList();
for (var i = 0; i < sortedSessions.Count; i++)
{
if (sortedSessions[i].ValueAreaRays == null)
continue;
//PostProcessValueAreaRay(sessions[i].ValueAreaRays, i, sessions);
PostProcessValueAreaRay(sortedSessions[i].ValueAreaRays.FirstOrDefault(), i, sortedSessions);
PostProcessValueAreaRay(sortedSessions[i].ValueAreaRays.LastOrDefault(), i, sortedSessions);
}
}
private void PostProcessValueAreaRay(ChartObject valueAreaRay, int index, List sessions)
{
if (valueAreaRay is not ChartTrendLine trendLine)
return;
var referencePrice = trendLine.Name.Contains("High") ? sessions[index].Model.ValueAreaHigh : sessions[index].Model.ValueAreaLow;
if (index == sessions.Count - 1)
return;
for (var i = index + 1; i < sessions.Count; i++)
{
var nextSession = sessions[i];
var nextSessionTopPrice = MarketProfileCalculator.GetTopPrice(nextSession.Model.Matrix);
var nextSessionBottomPrice = MarketProfileCalculator.GetBottomPrice(nextSession.Model.Matrix);
//For debugging
// switch (InputRaysUntilIntersection)
// {
// case WaysToStopRays.StopNoRays:
// break;
// case WaysToStopRays.StopAllRays:
// break;
// case WaysToStopRays.StopAllRaysExceptPrevSession:
// if (index != sessions.Count - 2)
// trendLine.Color = Color.HotPink;
// break;
// case WaysToStopRays.StopOnlyPreviousSession:
// if (index == sessions.Count - 2)
// trendLine.Color = Color.Lime;
// break;
// }
if (referencePrice >= nextSessionBottomPrice && referencePrice <= nextSessionTopPrice)
{
switch (InputRaysUntilIntersection)
{
case WaysToStopRays.StopNoRays:
trendLine.ExtendToInfinity = true;
return;
case WaysToStopRays.StopAllRays:
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
return;
case WaysToStopRays.StopAllRaysExceptPrevSession:
if (index != sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;;
}
return;
case WaysToStopRays.StopOnlyPreviousSession:
if (index == sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
}
return;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
public void PostProcessSinglePrintRays(List sessions)
{
if (InputSPRaysUntilIntersection == WaysToStopRays.StopNoRays)
return;
if (!InputSinglePrintRays)
return;
var sortedSessions = sessions.OrderBy(s => s.Model.StartTime).ToList();
for (var i = 0; i < sortedSessions.Count; i++)
{
if (sortedSessions[i].SinglePrints == null)
continue;
// Filter only the trend line rays (not the rectangle blocks) from SinglePrints.
foreach (var obj in sortedSessions[i].SinglePrints)
{
if (obj is ChartTrendLine trendLine && trendLine.Name.Contains(ObjPrefix + "SinglePrintRay"))
PostProcessSinglePrintRay(trendLine, i, sortedSessions);
}
}
}
private void PostProcessSinglePrintRay(ChartTrendLine trendLine, int index, List sessions)
{
// The ray's price level is its Y1 coordinate.
var referencePrice = trendLine.Y1;
if (index == sessions.Count - 1)
return;
for (var i = index + 1; i < sessions.Count; i++)
{
var nextSession = sessions[i];
var nextSessionTopPrice = MarketProfileCalculator.GetTopPrice(nextSession.Model.Matrix);
var nextSessionBottomPrice = MarketProfileCalculator.GetBottomPrice(nextSession.Model.Matrix);
if (referencePrice >= nextSessionBottomPrice && referencePrice <= nextSessionTopPrice)
{
switch (InputSPRaysUntilIntersection)
{
case WaysToStopRays.StopNoRays:
trendLine.ExtendToInfinity = true;
return;
case WaysToStopRays.StopAllRays:
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
return;
case WaysToStopRays.StopAllRaysExceptPrevSession:
if (index != sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
}
return;
case WaysToStopRays.StopOnlyPreviousSession:
if (index == sessions.Count - 2)
{
trendLine.ExtendToInfinity = false;
trendLine.Time2 = nextSession.Model.StartTime;
}
return;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
public List RenderKeyValues(MarketProfileModel model)
{
var result = new List();
if (!InputShowKeyValues)
return result;
var vah = model.ValueAreaHigh;
var val = model.ValueAreaLow;
var pointOfControl = model.PointOfControl;
var matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < model.Matrix.GetLength(0); row++)
{
if (model.Matrix[row, 0] == null)
continue;
matrixStartTime = model.Matrix[row, 0].StartTime.Ticks;
break;
}
var vahText = Chart.DrawText($"{ObjPrefix}VAH-Text-{matrixStartTime}", $"{vah.ToString(_format)}", model.StartTime, vah, InputKeyValuesColor);
vahText.FontSize = InputKeyValuesSize;
vahText.HorizontalAlignment = HorizontalAlignment.Left;
vahText.VerticalAlignment = VerticalAlignment.Center;
var valText = Chart.DrawText($"{ObjPrefix}VAL-Text-{matrixStartTime}", $"{val.ToString(_format)}", model.StartTime, val, InputKeyValuesColor);
valText.FontSize = InputKeyValuesSize;
valText.HorizontalAlignment = HorizontalAlignment.Left;
valText.VerticalAlignment = VerticalAlignment.Center;
var pointOfControlText = Chart.DrawText($"{ObjPrefix}PointOfControl-Text-{matrixStartTime}", $"{pointOfControl.ToString(_format)}", model.StartTime, pointOfControl, InputKeyValuesColor);
pointOfControlText.FontSize = InputKeyValuesSize;
pointOfControlText.HorizontalAlignment = HorizontalAlignment.Left;
pointOfControlText.VerticalAlignment = VerticalAlignment.Center;
result.Add(vahText);
result.Add(valText);
result.Add(pointOfControlText);
return result;
}
public List RenderHorizontallyFlippedKeyValues(MarketProfileModel model, MarketProfileSession session)
{
var result = new List();
if (!InputShowKeyValues)
return result;
result = RenderKeyValues(model);
foreach (var obj in result)
{
if (obj is not ChartText text)
continue;
text.HorizontalAlignment = HorizontalAlignment.Right;
text.Time = session.Range.Bars.Last().OpenTime;
}
return result;
}
public List RenderTpoCounts(MarketProfileModel model)
{
var result = new List();
if (!InputShowTpoCounts)
return result;
var pointOfControl = model.PointOfControl;
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
if (model.TpoCountAbove == -1 || model.TpoCountBelow == -1)
return result;
var matrixStartTime = model.Matrix.GetLength(0) > 0 ? model.Matrix[0, 0].StartTime.Ticks : DateTime.MinValue.Ticks;
var tpoCountAbove = Chart.DrawText($"{ObjPrefix}TPO-Above-{matrixStartTime}", $"{model.TpoCountAbove}", pointOfControlRowEndTime, pointOfControl, InputTpoCountAboveColor);
tpoCountAbove.FontSize = InputKeyValuesSize;
tpoCountAbove.HorizontalAlignment = HorizontalAlignment.Right;
tpoCountAbove.VerticalAlignment = VerticalAlignment.Top;
var tpoCountBelow = Chart.DrawText($"{ObjPrefix}TPO-Below-{matrixStartTime}", $"{model.TpoCountBelow}", pointOfControlRowEndTime, pointOfControl, InputTpoCountBelowColor);
tpoCountBelow.FontSize = InputKeyValuesSize;
tpoCountBelow.HorizontalAlignment = HorizontalAlignment.Right;
tpoCountBelow.VerticalAlignment = VerticalAlignment.Bottom;
result.Add(tpoCountAbove);
result.Add(tpoCountBelow);
return result;
}
public List RenderHorizontallyFlippedTpoCounts(MarketProfileModel model, MarketProfileSession session)
{
if (!InputShowTpoCounts)
return new List();
var matrix = model.Matrix;
var earliestTime = DateTime.MaxValue;
var latestTime = DateTime.MinValue;
for (var row = 0; row < matrix.GetLength(0); row++)
for (var column = 0; column < matrix.GetLength(1); column++)
{
var point = matrix[row, column];
if (point == null)
continue;
earliestTime = point.StartTime < earliestTime ? point.StartTime : earliestTime;
latestTime = point.EndTime > latestTime ? point.EndTime : latestTime;
}
var startPoint = session.Range.Bars.Last().OpenTime;
var timeOffset = startPoint - latestTime;
DateTime Flip(DateTime t) => latestTime - (t - earliestTime) + timeOffset;
var pointOfControl = model.PointOfControl;
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
var flippedEnd = Flip(pointOfControlRowEndTime);
var result = new List();
if (model.TpoCountAbove == -1 || model.TpoCountBelow == -1)
return result;
double matrixStartTime = DateTime.MinValue.Ticks;
for (var row = 0; row < model.Matrix.GetLength(0); row++)
{
if (model.Matrix[row, 0] == null)
continue;
matrixStartTime = model.Matrix[row, 0].StartTime.Ticks;
break;
}
var tpoCountAbove = Chart.DrawText($"{ObjPrefix}TPO-Above-Flipped-{matrixStartTime}", $"{model.TpoCountAbove}", flippedEnd, pointOfControl, InputTpoCountAboveColor);
tpoCountAbove.FontSize = InputKeyValuesSize;
tpoCountAbove.HorizontalAlignment = HorizontalAlignment.Right;
tpoCountAbove.VerticalAlignment = VerticalAlignment.Top;
var tpoCountBelow = Chart.DrawText($"{ObjPrefix}TPO-Below-Flipped-{matrixStartTime}", $"{model.TpoCountBelow}", flippedEnd, pointOfControl, InputTpoCountBelowColor);
tpoCountBelow.FontSize = InputKeyValuesSize;
tpoCountBelow.HorizontalAlignment = HorizontalAlignment.Right;
tpoCountBelow.VerticalAlignment = VerticalAlignment.Bottom;
result.Add(tpoCountAbove);
result.Add(tpoCountBelow);
return result;
}
public List RenderSinglePrints(MarketProfileModel model)
{
return InputShowSinglePrint switch
{
SinglePrintType.No => new List(),
SinglePrintType.LeftSide => RenderLeftSideSinglePrints(model),
SinglePrintType.RightSide => RenderRightSideSinglePrints(model),
_ => throw new ArgumentOutOfRangeException()
};
}
public List RenderRightSideSinglePrints(MarketProfileModel model)
{
var result = new List();
//must draw 1 rectangle per each tpo point
//must draw 1 ray but going backwards in time
for (var index = 0; index < model.SinglePrints.Count; index++)
{
var singlePrint = model.SinglePrints[index];
var startIndex = singlePrint.BottomTpoIndex;
var endIndex = singlePrint.TopTpoIndex;
for (var i = startIndex; i <= endIndex; i++)
{
var tpoBlock = model.Matrix[i, 0];
var tpoStartTime = tpoBlock.StartTime;
var tpoEndTime = tpoBlock.EndTime;
var tpoHigh = tpoBlock.Top;
var tpoLow = tpoBlock.Bottom;
result.Add(Chart.DrawRectangle($"{ObjPrefix}SinglePrintBlock-{i}-{model.StartTime}-{index}", tpoStartTime, tpoHigh, tpoEndTime, tpoLow, InputSinglePrintColor));
}
//now draw the rays backwards in time, starting from startTime
var s = singlePrint.StartTime;
var top = singlePrint.High;
var bottom = singlePrint.Low;
//
result.Add(Chart.DrawTrendLine($"{ObjPrefix}SinglePrintRay-top-{model.StartTime}-{index}", s, top, s.AddYears(-10), bottom, InputSinglePrintColor, InputSinglePrintRayWidth, InputSinglePrintRayStyle));
result.Add(Chart.DrawTrendLine($"{ObjPrefix}SinglePrintRay-bottom-{model.StartTime}-{index}", s, bottom, s.AddYears(-10), top, InputSinglePrintColor, InputSinglePrintRayWidth, InputSinglePrintRayStyle));
}
return result;
}
public List RenderLeftSideSinglePrints(MarketProfileModel model)
{
var result = new List();
for (var index = 0; index < model.SinglePrints.Count; index++)
{
var singlePrint = model.SinglePrints[index];
//get time of 2 bars behind model.StartTime
var rectangleStartTime = Bars.OpenTimes[Bars.OpenTimes.GetIndexByTime(model.StartTime) - 2];
var high = singlePrint.High;
var low = singlePrint.Low;
var singlePrintRay = Chart.DrawRectangle($"{ObjPrefix}SinglePrintBlock-{model.StartTime}-{index}", rectangleStartTime, high, model.StartTime, low, InputSinglePrintColor);
singlePrintRay.Thickness = 0;
singlePrintRay.IsFilled = true;
result.Add(singlePrintRay);
if (InputSinglePrintRays)
{
var topLine = Chart.DrawTrendLine($"{ObjPrefix}SinglePrintRay-top-{model.StartTime}-{index}", model.StartTime, high, model.StartTime.AddSeconds(1), high, InputSinglePrintColor, InputSinglePrintRayWidth,
InputSinglePrintRayStyle);
topLine.ExtendToInfinity = true;
result.Add(topLine);
var bottomLine = Chart.DrawTrendLine($"{ObjPrefix}SinglePrintRay-bottom-{model.StartTime}-{index}", model.StartTime, low, model.StartTime.AddSeconds(1), low, InputSinglePrintColor,
InputSinglePrintRayWidth, InputSinglePrintRayStyle);
bottomLine.ExtendToInfinity = true;
result.Add(bottomLine);
}
}
return result;
}
public ChartObject RenderProminentLine(MarketProfileModel profileModel)
{
if (!profileModel.IsProminentLine)
return null;
var startTime = profileModel.StartTime;
var endTime = Calculator.GetPointOfControlRowEndTime(profileModel.Matrix);
var pointOfControl = profileModel.PointOfControl;
var matrixStartTime = profileModel.Matrix.GetLength(0) > 0 ? profileModel.Matrix[0, 0].StartTime.Ticks : DateTime.MinValue.Ticks;
return Chart.DrawTrendLine($"{ObjPrefix}ProminentLine-{matrixStartTime}", startTime, pointOfControl, endTime, pointOfControl, InputProminentMedianColor, InputProminentMedianWidth, InputProminentMedianStyle);
}
public ChartObject RenderHorizontallyFlippedProminentLine(MarketProfileModel model, MarketProfileSession session)
{
if (!model.IsProminentLine)
return null;
var pointOfControlRowEndTime = Calculator.GetPointOfControlRowEndTime(model.Matrix);
var timeSpan = pointOfControlRowEndTime - model.StartTime;
var valueAreaObj = RenderProminentLine(model);
if (valueAreaObj is not ChartTrendLine trendLine)
return null;
trendLine.Time1 = session.Range.Bars.Last().OpenTime;
trendLine.Time2 = trendLine.Time1.Add(-timeSpan);
return trendLine;
}
public void DeleteObjects(IEnumerable objects)
{
if (objects == null)
return;
foreach (var obj in objects)
{
if (obj == null)
continue;
Chart.RemoveObject(obj.Name);
}
}
public void DeleteObject(ChartObject obj)
{
if (obj == null)
return;
Chart.RemoveObject(obj.Name);
}
public void ClearOutputsTillDate(DateTime start)
{
for (int i = 0; Bars.OpenTimes[i] < start; i++)
{
OutputDevelopingPoC[i] = double.NaN;
OutputDevelopingVah[i] = double.NaN;
OutputDevelopingVaL[i] = double.NaN;
}
}
public void ClearOutputsOnRange(DateTime start, DateTime end)
{
for (int i = Bars.OpenTimes.GetIndexByTime(start); i < Bars.OpenTimes.GetIndexByTime(end); i++)
{
OutputDevelopingPoC[i] = double.NaN;
OutputDevelopingVah[i] = double.NaN;
OutputDevelopingVaL[i] = double.NaN;
}
}
public void ClearOutputsAfterDate(DateTime start)
{
for (int i = Bars.OpenTimes.GetIndexByTime(start); i < Bars.OpenTimes.Count; i++)
{
OutputDevelopingPoC[i] = double.NaN;
OutputDevelopingVah[i] = double.NaN;
OutputDevelopingVaL[i] = double.NaN;
}
}
public void DeleteAllFromSession(MarketProfileSession session)
{
DeleteObjects(session.Profile);
DeleteObjects(session.ValueArea);
DeleteObjects(session.ValueAreaRays);
DeleteObjects(session.MedianRays);
DeleteObjects(session.KeyValues);
DeleteObjects(session.TpoCounts);
DeleteObjects(session.SinglePrints);
DeleteObject(session.ProminentLine);
session.ClearObjects();
}
public void DeleteAllSessions(List sessions)
{
foreach (var session in sessions)
DeleteAllFromSession(session);
}
#region SettingsAndResources
public double ValueAreaPercentage => _resources.ValueAreaPercentage;
public TimeFrame TimeFrame => _resources.TimeFrame;
public Bars Bars => _resources.Bars;
public IndicatorDataSeries OutputDevelopingPoC => _settings.OutputDevelopingPoC;
public IndicatorDataSeries OutputDevelopingVah => _settings.OutputDevelopingVah;
public IndicatorDataSeries OutputDevelopingVaL => _settings.OutputDevelopingVaL;
public Symbol Symbol => _resources.Symbol;
public Chart Chart => _resources.Chart;
public double OneTickSize => _resources.OneTickSize;
public void Print(object message) => _resources.Print(message);
public bool InputColorBullBear => _settings.InputColorBullBear;
public Color InputStartColor => _settings.InputStartColor;
public Color InputEndColor => _settings.InputEndColor;
public Color InputMedianColor => _settings.InputMedianColor;
public Color InputValueAreaSidesColor => _settings.InputValueAreaSidesColor;
public Color InputValueAreaHighLowColor => _settings.InputValueAreaHighLowColor;
public LineStyle InputMedianStyle => _settings.InputMedianStyle;
public LineStyle InputMedianRayStyle => _settings.InputMedianRayStyle;
public LineStyle InputValueAreaSidesStyle => _settings.InputValueAreaSidesStyle;
public LineStyle InputValueAreaHighLowStyle => _settings.InputValueAreaHighLowStyle;
public LineStyle InputValueAreaRayHighLowStyle => _settings.InputValueAreaRayHighLowStyle;
public int InputMedianWidth => _settings.InputMedianWidth;
public int InputMedianRayWidth => _settings.InputMedianRayWidth;
public int InputValueAreaSidesWidth => _settings.InputValueAreaSidesWidth;
public int InputValueAreaHighLowWidth => _settings.InputValueAreaHighLowWidth;
public int InputValueAreaRayHighLowWidth => _settings.InputValueAreaRayHighLowWidth;
public SessionsToDrawRays InputShowValueAreaRays => _settings.InputShowValueAreaRays;
public SessionsToDrawRays InputShowMedianRays => _settings.InputShowMedianRays;
public WaysToStopRays InputRaysUntilIntersection => _settings.InputRaysUntilIntersection;
public int InputTimeShiftMinutes => _settings.InputTimeShiftMinutes;
public bool InputShowKeyValues => _settings.InputShowKeyValues;
public Color InputKeyValuesColor => _settings.InputKeyValuesColor;
public int InputKeyValuesSize => _settings.InputKeyValuesSize;
public SinglePrintType InputShowSinglePrint => _settings.InputShowSinglePrint;
public Color InputSinglePrintColor => _settings.InputSinglePrintColor;
public bool InputSinglePrintRays => _settings.InputSinglePrintRays;
public LineStyle InputSinglePrintRayStyle => _settings.InputSinglePrintRayStyle;
public int InputSinglePrintRayWidth => _settings.InputSinglePrintRayWidth;
public WaysToStopRays InputSPRaysUntilIntersection => _settings.InputSPRaysUntilIntersection;
public Color InputProminentMedianColor => _settings.InputProminentMedianColor;
public bool InputDrawOnlyHistogramBorder => _settings.InputDrawOnlyHistogramBorder;
public LineStyle InputProminentMedianStyle => _settings.InputProminentMedianStyle;
public int InputProminentMedianWidth => _settings.InputProminentMedianWidth;
public bool InputShowTpoCounts => _settings.InputShowTpoCounts;
public Color InputTpoCountAboveColor => _settings.InputTpoCountAboveColor;
public Color InputTpoCountBelowColor => _settings.InputTpoCountBelowColor;
public MarketProfileCalculator Calculator => _settings.Calculator;
public string ObjPrefix => _settings.ObjPrefix;
#endregion
}
================================================
FILE: MarketProfile/MarketProfile/Models/MarketProfileModel.cs
================================================
using System;
using System.Collections.Generic;
namespace cAlgo;
public class MarketProfileModel
{
//I'm not sure if I should keep the original matrix or just stick with the piled one
public MatrixPoint[,] Matrix { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public double ValueAreaHigh { get; set; }
public Dictionary DevelopingAreaHigh { get; } = new();
public double ValueAreaLow { get; set; }
public Dictionary DevelopingAreaLow { get; } = new();
public double Median { get; set; }
public double PointOfControl { get; set; }
public Dictionary DevelopingPoC { get; } = new();
///
/// TPO stands for Time Price Opportunity
///
public int TpoCountAbove { get; set; }
///
/// TPO stands for Time Price Opportunity
///
public int TpoCountBelow { get; set; }
public List SinglePrints { get; } = new();
///
/// A Prominent line is when the Median TPO is > X% of the total amount of TPOs
///
public bool IsProminentLine { get; set; }
// public MarketProfileModel(MatrixPoint[,] matrix, DateTime startTime, DateTime endTime)
// {
// Matrix = matrix;
// StartTime = startTime;
// EndTime = endTime;
// }
}
public class SinglePrint
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public double High { get; set; }
public double Low { get; set; }
public int TopTpoIndex { get; set; }
public int BottomTpoIndex { get; set; }
public SinglePrint(DateTime startTime, DateTime endTime, double high, double low, int topTpoIndex, int bottomTpoIndex)
{
StartTime = startTime;
EndTime = endTime;
High = high;
Low = low;
TopTpoIndex = topTpoIndex;
BottomTpoIndex = bottomTpoIndex;
}
}
================================================
FILE: MarketProfile/MarketProfile/Models/MarketProfileSession.cs
================================================
using System.Collections.Generic;
using cAlgo.API;
namespace cAlgo;
public class MarketProfileSession
{
public SessionRange Range { get; set; }
public MarketProfileModel Model { get; set; }
public List Profile { get; set; }
public List ValueArea { get; set; }
public List ValueAreaRays { get; set; }
public List MedianRays { get; set; }
public List KeyValues { get; set; }
public List TpoCounts { get; set; }
public List SinglePrints { get; set; }
public ChartObject ProminentLine { get; set; }
public ChartRectangle Rectangle { get; set; }
public void ClearObjects()
{
Profile?.Clear();
ValueArea?.Clear();
ValueAreaRays?.Clear();
MedianRays?.Clear();
KeyValues?.Clear();
TpoCounts?.Clear();
SinglePrints?.Clear();
Model.DevelopingPoC?.Clear();
Model.DevelopingAreaHigh?.Clear();
Model.DevelopingAreaLow?.Clear();
ProminentLine = null;
}
}
================================================
FILE: MarketProfile/MarketProfile/Models/SessionState.cs
================================================
namespace cAlgo;
//Creating a sort of "state machine" with enums, rather than the MQL4 approach
//Possible scenarios:
//- There's no storage for this instance
// - The indicator is initialized with the values from the parameter
//- There's a storage for this instance
// - The input-parameter has changed from last run, SessionState needs to be updated with the current input-parameter, this change takes priority over the hotkey-state change
// - The input-parameter has not changed from last run, if a hotkey was used, SessionState needs to be updated with the last hotkey-state used
// - The input-parameter has not changed from last run, if a hotkey was not used, SessionState and input-parameter should be the same, no need to update anything
public class SessionState
{
// public DateTime LastHotkeyStateChanged { get; set; }
// public DateTime LastParameterStateChanged { get; set; }
public SessionPeriod LastSessionStateByParameter { get; set; }
public SessionPeriod LastSessionState { get; set; }
public Transitions LastTransition { get; set; }
public override string ToString()
{
return $"LastSessionState: {LastSessionState}, LastSessionStateByParameter: {LastSessionStateByParameter}, LastTransition: {LastTransition}";
}
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/AnnualSessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class AnnualSessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public AnnualSessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
var result = new List();
// Group by year
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars.GroupBy(b => new DateTime(b.OpenTime.Year, 1, 1))
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars.GroupBy(b => new DateTime(b.OpenTime.Year, 1, 1))
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime,
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
// Group by year
var grouped = filteredBars.GroupBy(b => new DateTime(b.OpenTime.Year, 1, 1))
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime,
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/DailySessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class DailySessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public DailySessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
// Find last N daily sessions, regardless of chart timeframe
var result = new List();
// Handle different weekend solutions
switch (InputSaturdaySunday)
{
case SatSunSolution.IgnoreSaturdaySunday:
// Filter out Saturday and Sunday before grouping
filteredBars = bars.Where(b =>
b.OpenTime.DayOfWeek != DayOfWeek.Saturday &&
b.OpenTime.DayOfWeek != DayOfWeek.Sunday);
break;
case SatSunSolution.AppendSaturdaySunday:
// Group by custom date that adds weekend days to the following Monday
var customGroups = bars
.GroupBy(b => {
var date = b.OpenTime.Date;
if (b.OpenTime.DayOfWeek == DayOfWeek.Saturday || b.OpenTime.DayOfWeek == DayOfWeek.Sunday)
{
// Calculate days until next Monday
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)b.OpenTime.DayOfWeek + 7) % 7;
return date.AddDays(daysUntilMonday);
}
return date;
});
IEnumerable> orderedGroups;
if (useStartFromDate)
{
orderedGroups = customGroups
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
orderedGroups = customGroups
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in orderedGroups)
{
var orderedBars = group.OrderBy(b => b.OpenTime).ToList();
var first = orderedBars.First();
var last = orderedBars.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = orderedBars
});
}
return result;
}
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => b.OpenTime.Date)
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => b.OpenTime.Date)
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
//todo I think "End" should be last.OpenTime and that's it
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
var grouped = filteredBars.GroupBy(b => b.OpenTime.Date)
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
public class IntradaySessionDefinition
{
public TimeSpan Start { get; init; }
public TimeSpan End { get; init; }
public string Name { get; init; }
public Color StartColor { get; init; }
public Color EndColor { get; init; }
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/IRenderingModesResources.cs
================================================
namespace cAlgo;
public interface IRenderingModesResources
{
string InputStartFromDate { get; }
bool InputStartFromCurrentSession { get; }
bool InputSeamlessScrollingMode { get; }
SatSunSolution InputSaturdaySunday { get; }
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/ISessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using cAlgo.API;
namespace cAlgo;
public interface ISessionProfileStrategy
{
// Keep existing method for backward compatibility
IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? startFrom = null);
// Add new method for date range filtering without sessionsToCount
IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt);
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/IntradaySessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using cAlgo.API;
namespace cAlgo;
public class IntradaySessionProfileStrategy : ISessionProfileStrategy, IRenderingModesResources
{
private readonly List _sessions;
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public IntradaySessionProfileStrategy(List sessions, IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
foreach (var session in _sessions)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
// Handle different weekend solutions
switch (InputSaturdaySunday)
{
case SatSunSolution.IgnoreSaturdaySunday:
filteredBars = filteredBars.Where(b => b.OpenTime.DayOfWeek != DayOfWeek.Saturday && b.OpenTime.DayOfWeek != DayOfWeek.Sunday);
break;
case SatSunSolution.AppendSaturdaySunday:
// Group Sat/Sun bars with the following Monday
var customGroups = filteredBars.GroupBy(b => {
var date = b.OpenTime.Date;
if (b.OpenTime.DayOfWeek == DayOfWeek.Saturday || b.OpenTime.DayOfWeek == DayOfWeek.Sunday)
{
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)b.OpenTime.DayOfWeek + 7) % 7;
return date.AddDays(daysUntilMonday);
}
return date;
});
IEnumerable> orderedGroups;
if (useStartFromDate)
{
orderedGroups = customGroups
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
orderedGroups = customGroups
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in orderedGroups)
{
if (!group.Any()) continue;
var sessionSpan = session.End > session.Start
? session.End - session.Start
: (session.End + TimeSpan.FromDays(1)) - session.Start;
var date = group.Key;
var start = date.Add(session.Start);
var end = start.Add(sessionSpan);
var sessionBars = bars.Where(b => b.OpenTime >= start && b.OpenTime <= end).ToList();
if (!sessionBars.Any()) continue;
yield return new SessionRange
{
Start = start,
End = end,
StartColor = session.StartColor,
EndColor = session.EndColor,
Bars = sessionBars
};
}
continue;
}
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => b.OpenTime.Date)
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => b.OpenTime.Date)
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
if (!group.Any()) continue;
var sessionSpan = session.End > session.Start
? session.End - session.Start
: (session.End + TimeSpan.FromDays(1)) - session.Start;
var date = group.Key;
var start = date.Add(session.Start);
var end = start.Add(sessionSpan);
var sessionBars = bars.Where(b => b.OpenTime >= start && b.OpenTime <= end).ToList();
if (!sessionBars.Any()) continue;
yield return new SessionRange
{
Start = start,
End = end,
StartColor = session.StartColor,
EndColor = session.EndColor,
Bars = sessionBars
};
}
}
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
foreach (var session in _sessions)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var grouped = filteredBars
.Where(b => b.OpenTime.DayOfWeek != DayOfWeek.Saturday)
.GroupBy(b => b.OpenTime.Date)
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var sessionSpan = session.End > session.Start
? session.End - session.Start
: (session.End + TimeSpan.FromDays(1)) - session.Start;
var date = group.Key;
var start = date.Add(session.Start);
var end = start.Add(sessionSpan);
yield return new SessionRange
{
Start = start,
End = end,
StartColor = session.StartColor,
EndColor = session.EndColor,
Bars = bars.Where(b => b.OpenTime >= start && b.OpenTime <= end)
};
}
}
}
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/MonthlySessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class MonthlySessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public MonthlySessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
var result = new List();
// Group by month (year, month)
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => new DateTime(b.OpenTime.Year, b.OpenTime.Month, 1))
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => new DateTime(b.OpenTime.Year, b.OpenTime.Month, 1))
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
var grouped = filteredBars.GroupBy(b => new DateTime(b.OpenTime.Year, b.OpenTime.Month, 1))
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/QuarterlySessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class QuarterlySessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public QuarterlySessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
var result = new List();
// Group by quarter (year, quarter start month)
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => GetQuarterStart(b.OpenTime))
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => GetQuarterStart(b.OpenTime))
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
var grouped = filteredBars.GroupBy(b => GetQuarterStart(b.OpenTime))
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
private static DateTime GetQuarterStart(DateTime date)
{
int quarter = ((date.Month - 1) / 3) + 1;
int startMonth = (quarter - 1) * 3 + 1;
return new DateTime(date.Year, startMonth, 1);
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/RectangleSessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class RectangleSessionProfileStrategy : ISessionProfileStrategy
{
private readonly IIndicatorResources _resources;
private readonly DateTime _startTime;
private readonly DateTime _endTime;
public RectangleSessionProfileStrategy(IIndicatorResources resources, DateTime startTime, DateTime endTime)
{
_resources = resources;
_startTime = startTime;
_endTime = endTime;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var start = _startTime;
var end = endAt ?? _endTime;
yield return new SessionRange
{
Start = start,
End = end,
StartColor = startColor,
EndColor = endColor,
Bars = bars.Where(b => b.OpenTime >= start && b.OpenTime <= end)
};
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
throw new NotSupportedException("GetSessionRanges with date range is not supported for RectangleSessionProfileStrategy.");
}
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/SemiannualSessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class SemiannualSessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public SemiannualSessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
var result = new List();
// Group by semiannual (year, half)
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => GetSemiannualStart(b.OpenTime))
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => GetSemiannualStart(b.OpenTime))
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
var grouped = filteredBars.GroupBy(b => GetSemiannualStart(b.OpenTime))
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
private static DateTime GetSemiannualStart(DateTime date)
{
int half = (date.Month - 1) / 6;
int startMonth = half * 6 + 1;
return new DateTime(date.Year, startMonth, 1);
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/SessionProfileStrategyFactory.cs
================================================
using System;
using System.Collections.Generic;
namespace cAlgo;
public static class SessionProfileStrategyFactory
{
public static ISessionProfileStrategy CreateDaily(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new DailySessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateWeekly(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new WeeklySessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateMonthly(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new MonthlySessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateQuarterly(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new QuarterlySessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateSemiannual(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new SemiannualSessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateAnnual(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
return new AnnualSessionProfileStrategy(resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateIntradaySessions(List sessionDefinitions, IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
if (sessionDefinitions.Count == 0)
throw new ArgumentException("At least one intraday session must be defined");
return new IntradaySessionProfileStrategy(sessionDefinitions, resources, renderingModesResources);
}
public static ISessionProfileStrategy CreateRectangle(IIndicatorResources resources, DateTime startTime, DateTime endTime)
{
return new RectangleSessionProfileStrategy(resources, startTime, endTime);
}
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/SessionRange.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class SessionRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public Color StartColor { get; set; }
public Color EndColor { get; set; }
public IEnumerable Bars { get; set; }
public override string ToString()
{
return $"Start: {Start} - End: {End} | Bars: {Bars.Count()}";
}
}
================================================
FILE: MarketProfile/MarketProfile/RangeCalculators/WeeklySessionProfileStrategy.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public class WeeklySessionProfileStrategy : ISessionProfileStrategy, IIndicatorResources, IRenderingModesResources
{
private readonly IIndicatorResources _resources;
private readonly IRenderingModesResources _renderingModesResources;
public WeeklySessionProfileStrategy(IIndicatorResources resources, IRenderingModesResources renderingModesResources)
{
_resources = resources;
_renderingModesResources = renderingModesResources;
}
public IEnumerable GetSessionRanges(Bars bars, int sessionsToCount, Color startColor, Color endColor, DateTime? endAt = null)
{
var useStartFromDate = false;
var startFrom = DateTime.MinValue;
if (!InputStartFromCurrentSession)
{
if (DateTime.TryParse(InputStartFromDate, out startFrom) && !InputSeamlessScrollingMode)
{
useStartFromDate = true;
}
}
// Filter bars up to endAt if provided
IEnumerable filteredBars = bars;
var result = new List();
// Handle different weekend solutions
switch (InputSaturdaySunday)
{
case SatSunSolution.IgnoreSaturdaySunday:
// Filter out Saturday and Sunday before grouping
filteredBars = filteredBars.Where(b =>
b.OpenTime.DayOfWeek != DayOfWeek.Saturday &&
b.OpenTime.DayOfWeek != DayOfWeek.Sunday);
break;
case SatSunSolution.AppendSaturdaySunday:
case SatSunSolution.SaturdaySundayNormalDays:
// Weeks should start on Sunday
break;
}
// Group by week starting on Sunday for both AppendSaturdaySunday and SaturdaySundayNormalDays
Func getWeekStart = (InputSaturdaySunday == SatSunSolution.AppendSaturdaySunday || InputSaturdaySunday == SatSunSolution.SaturdaySundayNormalDays)
? GetWeekStartSunday
: GetWeekStartMonday;
IEnumerable> grouped;
if (useStartFromDate)
{
grouped = filteredBars
.GroupBy(b => getWeekStart(b.OpenTime))
.OrderBy(g => g.Key)
.Where(b => b.Key >= startFrom)
.Take(sessionsToCount);
}
else
{
grouped = filteredBars
.GroupBy(b => getWeekStart(b.OpenTime))
.OrderByDescending(g => g.Key)
.Where(g => !endAt.HasValue || g.Key <= endAt.Value)
.Take(sessionsToCount);
}
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
public IEnumerable GetSessionRanges(Bars bars, Color startColor, Color endColor, DateTime startFrom, DateTime endAt)
{
var filteredBars = bars.Where(b => b.OpenTime >= startFrom && b.OpenTime <= endAt);
var result = new List();
var grouped = filteredBars.GroupBy(b => GetWeekStartMonday(b.OpenTime))
.OrderBy(g => g.Key);
foreach (var group in grouped)
{
var first = group.First();
var last = group.Last();
result.Add(new SessionRange
{
Start = first.OpenTime,
End = last.OpenTime.Add(Helpers.GetBarTimeSpan(TimeFrame)),
StartColor = startColor,
EndColor = endColor,
Bars = group
});
}
return result;
}
private static DateTime GetWeekStartMonday(DateTime date)
{
int diff = (7 + (date.DayOfWeek - DayOfWeek.Monday)) % 7;
return date.Date.AddDays(-diff);
}
private static DateTime GetWeekStartSunday(DateTime date)
{
int diff = (7 + (date.DayOfWeek - DayOfWeek.Sunday)) % 7;
return date.Date.AddDays(-diff);
}
public TimeFrame TimeFrame => _resources.TimeFrame;
public string InputStartFromDate => _renderingModesResources.InputStartFromDate;
public bool InputStartFromCurrentSession => _renderingModesResources.InputStartFromCurrentSession;
public bool InputSeamlessScrollingMode => _renderingModesResources.InputSeamlessScrollingMode;
public SatSunSolution InputSaturdaySunday => _renderingModesResources.InputSaturdaySunday;
}
================================================
FILE: MarketProfile/MarketProfile/RectangleModeProcessor.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using cAlgo.API;
namespace cAlgo;
public interface IRectangleModeProcessorResources
{
TimeFrame TimeFrame { get; }
Chart Chart { get; }
Bars Bars { get; }
MarketProfileRenderer Renderer { get; }
MarketProfileCalculator Calculator { get; }
List Sessions { get; }
SessionState SessionState { get; }
string ObjPrefix { get; }
//--
Color InputStartColor { get; }
Color InputEndColor { get; }
void Print(object obj);
double OneTickSize { get; }
int InputProminentMedianPercentage { get; }
bool InputRightToLeft { get; }
bool InputDisableHistogram { get; }
bool InputEnableDevelopingPoC { get; }
bool InputEnableDevelopingValueAtHighValueAtLow { get; }
}
public class RectangleModeProcessor : IRectangleModeProcessorResources, IIndicatorResources
{
private readonly IRectangleModeProcessorResources _resources;
public RectangleModeProcessor(IRectangleModeProcessorResources resources)
{
_resources = resources;
Chart.KeyDown += ChartKeyDown;
Chart.ObjectsMoveEnded += ChartObjectsMoveEnded;
Chart.ObjectsRemoved += ChartObjectsRemoved;
}
private void ChartObjectsRemoved(ChartObjectsRemovedEventArgs obj)
{
if (SessionState.LastSessionState != SessionPeriod.Rectangle)
return;
if (obj.ChartObjects.First() is not ChartRectangle rectangle)
return;
var rectangleSession = Sessions.FirstOrDefault(x => x.Rectangle.Name == rectangle.Name);
if (rectangleSession == null)
return;
//need to delete all relevant to this rectangleSession
Renderer.DeleteAllFromSession(rectangleSession);
Sessions.Remove(rectangleSession);
}
private void ChartObjectsMoveEnded(ChartObjectsMoveEndedEventArgs obj)
{
if (SessionState.LastSessionState != SessionPeriod.Rectangle)
return;
if (obj.ChartObjects.First() is not ChartRectangle rectangle)
return;
var rectangleSession = Sessions.FirstOrDefault(x => x.Rectangle.Name == rectangle.Name);
if (rectangleSession == null)
return;
Renderer.DeleteAllFromSession(rectangleSession);
//now redo the calculation
var startOfRectangleTime = rectangle.Time1;
var endOfRectangleTime = rectangle.Time2;
var strategy = SessionProfileStrategyFactory.CreateRectangle(this, startOfRectangleTime, endOfRectangleTime);
var ranges = strategy.GetSessionRanges(Bars, 1, InputStartColor, InputEndColor).ToArray();
if (ranges.Length != 0)
{
Renderer.ClearOutputsTillDate(ranges.Last().Start);
Renderer.ClearOutputsAfterDate(ranges.First().End);
}
for (var index = 0; index < ranges.Length; index++)
{
var range = ranges[index];
var session = Sessions.FirstOrDefault(x => x.Rectangle.Name == rectangle.Name);
if (session == null)
throw new Exception("Rectangle session not found");
session.Range = range;
BuildAndRender(range, session, index, ranges.Length, cropTop: Math.Max(rectangle.Y1, rectangle.Y2), cropBottom: Math.Min(rectangle.Y1, rectangle.Y2));
}
}
private void ChartKeyDown(ChartKeyboardEventArgs obj)
{
if (obj.Key != Key.R)
return;
if (SessionState.LastSessionState != SessionPeriod.Rectangle)
return;
//var strategy = SessionProfileStrategyFactory.CreateRectangle(this);
var startIndex = Chart.FirstVisibleBarIndex;
var endIndex = Chart.LastVisibleBarIndex;
//I want to divide the screen into 3/5, so the rectangle occupy 3/5 of the screen and be located around the center
var startOfRectangleIndex = startIndex + (endIndex - startIndex) / 5;
var endOfRectangleIndex = endIndex - (endIndex - startIndex) / 5;
var startOfRectangleTime = Bars.OpenTimes[startOfRectangleIndex];
var endOfRectangleTime = Bars.OpenTimes[endOfRectangleIndex];
var selectedBars = Bars.Where(x => x.OpenTime >= startOfRectangleTime && x.OpenTime <= endOfRectangleTime).ToArray();
var minPrice = selectedBars.Min(x => x.Low);
var maxPrice = selectedBars.Max(x => x.High);
var rectangleRange = (maxPrice - minPrice) * 0.9;
var rectangleLow = maxPrice - rectangleRange;
var rectangleHigh = minPrice + rectangleRange;
var rectangle = Chart.DrawRectangle($"{ObjPrefix}MarketProfileRectangle-{Guid.NewGuid()}", startOfRectangleTime, rectangleLow, endOfRectangleTime, rectangleHigh, Color.Blue);
rectangle.IsInteractive = true;
var strategy = SessionProfileStrategyFactory.CreateRectangle(this, startOfRectangleTime, endOfRectangleTime);
var ranges = strategy.GetSessionRanges(Bars, 1, InputStartColor, InputEndColor).ToArray();
if (ranges.Length != 0)
{
Renderer.ClearOutputsTillDate(ranges.Last().Start);
Renderer.ClearOutputsAfterDate(ranges.First().End);
}
for (var index = 0; index < ranges.Length; index++)
{
var range = ranges[index];
var session = new MarketProfileSession
{
Range = range,
Rectangle = rectangle
};
BuildAndRender(range, session, index, ranges.Length, rectangleHigh, rectangleLow);
}
}
private bool BuildAndRender(SessionRange range, MarketProfileSession session, int index, int total, double cropTop, double cropBottom)
{
if (!range.Bars.Any())
{
// Skip this session or handle empty range
Print($"Warning: No bars found for session range {range.Start} to {range.End}");
return false; // or continue to next session
}
var bars = range.Bars.ToArray();
var slices = Calculator.GetSlices(bars);
if (slices == 0)
{
Print($"Slices is 0 | This can't be processed Bars is {bars.Length} (High {bars.Max(x => x.High)} | Low {bars.Min(x => x.Low)} | OneTickSize is {OneTickSize}");
return false;
}
var profileModel = Calculator.FillAndPileMatrixCalculationCropped(bars, slices, range.StartColor, range.EndColor, cropTop, cropBottom);
//these two below could be totally removed and reference the latest "developing" values
//var (vah, val) = Calculator.GetValueArea(profileModel.Matrix, InputValueAreaPercentage / 100.0);
var vah = profileModel.DevelopingAreaHigh.LastOrDefault().Value;
var val = profileModel.DevelopingAreaLow.LastOrDefault().Value;
var pointOfControlRowIndex = MarketProfileCalculator.GetPointOfControlRowIndex(profileModel.Matrix);
if (profileModel.Matrix[pointOfControlRowIndex, 0] == null)
{
Print($"Unable to calculate POC because the row is null");
return false;
}
var pointOfControlPrice = MarketProfileCalculator.GetPointOfControlPrice(profileModel.Matrix, pointOfControlRowIndex);
var (totalTopBlocksAbovePointOfControl, totalBottomBlocksBelowPointOfControl) = MarketProfileCalculator.GetValuesAroundPointOfControl(profileModel.Matrix);
profileModel.ValueAreaHigh = vah;
profileModel.ValueAreaLow = val;
profileModel.PointOfControl = pointOfControlPrice;
profileModel.Median = Calculator.GetMedianPrice(profileModel.Matrix);
profileModel.TpoCountAbove = totalTopBlocksAbovePointOfControl;
profileModel.TpoCountBelow = totalBottomBlocksBelowPointOfControl;
profileModel.SinglePrints.AddRange(MarketProfileCalculator.GetSinglePrints(profileModel.Matrix));
profileModel.IsProminentLine = Calculator.IsProminentLine(profileModel.Matrix, InputProminentMedianPercentage / 100.0);
session.Model = profileModel;
if (index == 0 && InputRightToLeft)
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderHorizontallyFlippedProfile(profileModel.Matrix, session);
session.ValueArea = Renderer.RenderHorizontallyFlippedValueArea(profileModel, session);
session.KeyValues = Renderer.RenderHorizontallyFlippedKeyValues(profileModel, session);
session.TpoCounts = Renderer.RenderHorizontallyFlippedTpoCounts(profileModel, session);
session.ProminentLine = Renderer.RenderHorizontallyFlippedProminentLine(profileModel, session);
}
else
{
if (!InputDisableHistogram)
session.Profile = Renderer.RenderProfile(profileModel.Matrix);
session.ValueArea = Renderer.RenderValueArea(profileModel);
session.ValueAreaRays = Renderer.RenderValueAreaRays(profileModel, index);
session.MedianRays = Renderer.RenderPointOfControlRays(profileModel, index);
session.KeyValues = Renderer.RenderKeyValues(profileModel);
session.TpoCounts = Renderer.RenderTpoCounts(profileModel);
session.ProminentLine = Renderer.RenderProminentLine(profileModel);
}
if (InputEnableDevelopingPoC)
Renderer.RenderDevelopingPoc(profileModel.DevelopingPoC);
if (InputEnableDevelopingValueAtHighValueAtLow)
{
Renderer.RenderDevelopingVahs(profileModel.DevelopingAreaHigh);
Renderer.RenderDevelopingVals(profileModel.DevelopingAreaLow);
}
session.SinglePrints = Renderer.RenderSinglePrints(profileModel);
Sessions.Add(session);
return true;
}
#region Resources
public TimeFrame TimeFrame => _resources.TimeFrame;
public Chart Chart => _resources.Chart;
public Bars Bars => _resources.Bars;
public MarketProfileRenderer Renderer => _resources.Renderer;
public MarketProfileCalculator Calculator => _resources.Calculator;
public List Sessions => _resources.Sessions;
public SessionState SessionState => _resources.SessionState;
public string ObjPrefix => _resources.ObjPrefix;
public Color InputStartColor => _resources.InputStartColor;
public Color InputEndColor => _resources.InputEndColor;
public void Print(object obj) => _resources.Print(obj);
public double OneTickSize => _resources.OneTickSize;
public int InputProminentMedianPercentage => _resources.InputProminentMedianPercentage;
public bool InputRightToLeft => _resources.InputRightToLeft;
public bool InputDisableHistogram => _resources.InputDisableHistogram;
public bool InputEnableDevelopingPoC => _resources.InputEnableDevelopingPoC;
public bool InputEnableDevelopingValueAtHighValueAtLow => _resources.InputEnableDevelopingValueAtHighValueAtLow;
#endregion
}
================================================
FILE: MarketProfile/MarketProfile.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30011.22
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MarketProfile", "MarketProfile\MarketProfile.csproj", "{c903ce3b-8d87-4cc3-a6b9-8811032f5b1b}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{c903ce3b-8d87-4cc3-a6b9-8811032f5b1b}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{c903ce3b-8d87-4cc3-a6b9-8811032f5b1b}.Debug|Any CPU.Build.0 = Debug|Any CPU
{c903ce3b-8d87-4cc3-a6b9-8811032f5b1b}.Release|Any CPU.ActiveCfg = Release|Any CPU
{c903ce3b-8d87-4cc3-a6b9-8811032f5b1b}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
================================================
FILE: MarketProfile.mq4
================================================
//+------------------------------------------------------------------+
//| MarketProfile.mq4 |
//| Copyright © 2010-2026, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "EarnForex.com"
#property link "https://www.earnforex.com/indicators/MarketProfile/"
#property version "1.25"
#property strict
#property description "Displays the Market Profile indicator. Supports the following sessions:"
#property description "Intraday, daily, weekly, monthly, quarterly, semiannual, annual and free-form rectangle."
#property description ""
#property description "Designed for major currency pairs, but should work also with exotic pairs, CFDs, or commodities."
//+------------------------------------------------------------------+
// Rectangle session - a rectangle's name should start with 'MPR' and must not contain an underscore ('_').
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_plots 3
#property indicator_buffers 3
#property indicator_color1 clrGreen
#property indicator_width1 2
#property indicator_type1 DRAW_ARROW
#property indicator_label1 "Developing POC"
#property indicator_color2 clrGoldenrod
#property indicator_width2 2
#property indicator_type2 DRAW_ARROW
#property indicator_label2 "Developing VAH"
#property indicator_color3 clrSalmon
#property indicator_width3 2
#property indicator_type3 DRAW_ARROW
#property indicator_label3 "Developing VAL"
enum color_scheme
{
Blue_to_Red, // Blue to Red
Red_to_Green, // Red to Green
Green_to_Blue, // Green to Blue
Yellow_to_Cyan, // Yellow to Cyan
Magenta_to_Yellow, // Magenta to Yellow
Cyan_to_Magenta, // Cyan to Magenta
Single_Color // Single Color
};
enum session_period
{
Daily,
Weekly,
Monthly,
Quarterly,
Semiannual,
Annual,
Intraday,
Rectangle
};
enum sat_sun_solution
{
Saturday_Sunday_Normal_Days, // Normal sessions
Ignore_Saturday_Sunday, // Ignore Saturday and Sunday
Append_Saturday_Sunday // Append Saturday and Sunday
};
enum sessions_to_draw_rays
{
None,
Previous,
Current,
PreviousCurrent, // Previous & Current
AllPrevious, // All Previous
All
};
enum ways_to_stop_rays
{
Stop_No_Rays, // Stop no rays
Stop_All_Rays, // Stop all rays
Stop_All_Rays_Except_Prev_Session, // Stop all rays except previous session
Stop_Only_Previous_Session, // Stop only previous session's rays
};
// Only for dot coloring choice in PutDot() when ColorBullBear == true.
enum bar_direction
{
Bullish,
Bearish,
Neutral
};
enum single_print_type
{
No,
Leftside,
Rightside
};
enum alert_check_bar
{
CheckCurrentBar, // Current
CheckPreviousBar // Previous
};
enum alert_types // Required to type a parameter of DoAlerts().
{
PriceBreak, // Price Break
CandleCloseCrossover, // Candle Close Crossover
GapCrossover // Gap Crossover
};
input group "Main"
input string ____Main = "================";
input session_period Session = Daily;
input datetime StartFromDate = __DATE__; // StartFromDate: lower priority.
input bool StartFromCurrentSession = true; // StartFromCurrentSession: higher priority.
input int SessionsToCount = 2; // SessionsToCount: Number of sessions to count Market Profile.
input bool SeamlessScrollingMode = false; // SeamlessScrollingMode: Show sessions on current screen.
input bool EnableDevelopingPOC = false; // Enable Developing POC
input bool EnableDevelopingVAHVAL = false; // Enable Developing VAH/VAL
input int ValueAreaPercentage = 70; // ValueAreaPercentage: Percentage of TPO's inside Value Area.
input string InstancePrefix = ""; // InstancePrefix: prefix for objects to allow multiple instances.
input ENUM_TIMEFRAMES TPOTimeframe = PERIOD_CURRENT; // TPOTimeframe: timeframe for TPO data. Equal or higher than chart's.
input group "Colors and looks"
input string ____Colors_and_looks = "================";
input color_scheme ColorScheme = Blue_to_Red;
input color SingleColor = clrBlue; // SingleColor: if ColorScheme is set to Single Color.
input bool ColorBullBear = false; // ColorBullBear: If true, colors are from bars' direction.
input color MedianColor = clrWhite;
input color ValueAreaSidesColor = clrWhite;
input color ValueAreaHighLowColor = clrWhite;
input ENUM_LINE_STYLE MedianStyle = STYLE_SOLID;
input ENUM_LINE_STYLE MedianRayStyle = STYLE_DASH;
input ENUM_LINE_STYLE ValueAreaSidesStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaHighLowStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaRayHighLowStyle= STYLE_DOT;
input int MedianWidth = 1;
input int MedianRayWidth = 1;
input int ValueAreaSidesWidth = 1;
input int ValueAreaHighLowWidth = 1;
input int ValueAreaRayHighLowWidth = 1;
input sessions_to_draw_rays ShowValueAreaRays = None; // ShowValueAreaRays: draw previous value area high/low rays.
input sessions_to_draw_rays ShowMedianRays = None; // ShowMedianRays: draw previous median rays.
input ways_to_stop_rays RaysUntilIntersection = Stop_No_Rays; // RaysUntilIntersection: which rays stop when hit another MP.
input bool HideRaysFromInvisibleSessions = false; // HideRaysFromInvisibleSessions: hide rays from behind the screen.
input int TimeShiftMinutes = 0; // TimeShiftMinutes: shift session + to the left, - to the right.
input bool ShowKeyValues = true; // ShowKeyValues: print out VAH, VAL, POC on chart.
input color KeyValuesColor = clrWhite; // KeyValuesColor: color for VAH, VAL, POC printout.
input int KeyValuesSize = 8; // KeyValuesSize: font size for VAH, VAL, POC printout.
input single_print_type ShowSinglePrint = No; // ShowSinglePrint: mark Single Print profile levels.
input color SinglePrintColor = clrGold;
input bool SinglePrintRays = false; // SinglePrintRays: mark Single Print edges with rays.
input ENUM_LINE_STYLE SinglePrintRayStyle = STYLE_SOLID;
input int SinglePrintRayWidth = 1;
input ways_to_stop_rays SPRaysUntilIntersection = Stop_No_Rays; // SPRaysUntilIntersection: which Single Print rays stop when hit another MP.
input color ProminentMedianColor = clrYellow;
input ENUM_LINE_STYLE ProminentMedianStyle = STYLE_SOLID;
input int ProminentMedianWidth = 4;
input bool ShowTPOCounts = false; // ShowTPOCounts: Show TPO counts above/below POC.
input color TPOCountAboveColor = clrHoneydew; // TPOCountAboveColor: Color for TPO count above POC.
input color TPOCountBelowColor = clrMistyRose; // TPOCountBelowColor: Color for TPO count below POC.
input bool RightToLeft = false; // RightToLeft: Draw histogram from right to left.
input group "Performance"
input string ____Performance = "================";
input int PointMultiplier = 0; // PointMultiplier: higher value = fewer objects. 0 - adaptive.
input int ThrottleRedraw = 0; // ThrottleRedraw: delay (in seconds) for updating Market Profile.
input bool DisableHistogram = false; // DisableHistogram: do not draw profile, VAH, VAL, and POC still visible.
input bool EnableOldProfilesCleanup = false; // EnableOldProfilesCleanup: delete old profiles exceeding SessionsToCount.
input group "Alerts"
input string ____Alerts = "================";
input bool AlertNative = false; // AlertNative: issue native pop-up alerts.
input bool AlertEmail = false; // AlertEmail: issue email alerts.
input bool AlertPush = false; // AlertPush: issue push-notification alerts.
input bool AlertArrows = false; // AlertArrows: draw chart arrows on alerts.
input alert_check_bar AlertCheckBar = CheckPreviousBar;// AlertCheckBar: which bar to check for alerts?
input bool AlertForValueArea = false; // AlertForValueArea: alerts for Value Area (VAH, VAL) rays.
input bool AlertForMedian = false; // AlertForMedian: alerts for POC (Median) rays' crossing.
input bool AlertForSinglePrint = false; // AlertForSinglePrint: alerts for single print rays' crossing.
input bool AlertOnPriceBreak = false; // AlertOnPriceBreak: price breaking above/below the ray.
input bool AlertOnCandleClose = false; // AlertOnCandleClose: candle closing above/below the ray.
input bool AlertOnGapCross = false; // AlertOnGapCross: bar gap above/below the ray.
input int AlertArrowCodePB = 108; // AlertArrowCodePB: arrow code for price break alerts.
input int AlertArrowCodeCC = 110; // AlertArrowCodeCC: arrow code for candle close alerts.
input int AlertArrowCodeGC = 117; // AlertArrowCodeGC: arrow code for gap crossover alerts.
input color AlertArrowColorPB = clrRed; // AlertArrowColorPB: arrow color for price break alerts.
input color AlertArrowColorCC = clrBlue; // AlertArrowColorCC: arrow color for candle close alerts.
input color AlertArrowColorGC = clrYellow; // AlertArrowColorGC: arrow color for gap crossover alerts.
input int AlertArrowWidthPB = 1; // AlertArrowWidthPB: arrow width for price break alerts.
input int AlertArrowWidthCC = 1; // AlertArrowWidthCC: arrow width for candle close alerts.
input int AlertArrowWidthGC = 1; // AlertArrowWidthGC: arrow width for gap crossover alerts.
input group "Intraday settings"
input string ____Intraday_settings = "================";
input bool EnableIntradaySession1 = true;
input string IntradaySession1StartTime = "00:00";
input string IntradaySession1EndTime = "06:00";
input color_scheme IntradaySession1ColorScheme = Blue_to_Red;
input bool EnableIntradaySession2 = true;
input string IntradaySession2StartTime = "06:00";
input string IntradaySession2EndTime = "12:00";
input color_scheme IntradaySession2ColorScheme = Red_to_Green;
input bool EnableIntradaySession3 = true;
input string IntradaySession3StartTime = "12:00";
input string IntradaySession3EndTime = "18:00";
input color_scheme IntradaySession3ColorScheme = Green_to_Blue;
input bool EnableIntradaySession4 = true;
input string IntradaySession4StartTime = "18:00";
input string IntradaySession4EndTime = "00:00";
input color_scheme IntradaySession4ColorScheme = Yellow_to_Cyan;
input group "Miscellaneous"
input string ____Miscellaneous = "================";
input sat_sun_solution SaturdaySunday = Saturday_Sunday_Normal_Days;
input bool DisableAlertsOnWrongTimeframes = false; // Disable alerts on wrong timeframes.
input int ProminentMedianPercentage = 101; // Percentage of Median TPOs out of total for a Prominent one.
input bool ShowToggleButton = false; // ShowToggleButton: show on/off button.
input ENUM_BASE_CORNER ToggleButtonCorner = CORNER_LEFT_UPPER; // ToggleButtonCorner: chart corner for the toggle button.
int PointMultiplier_calculated; // Will have to be calculated based number digits in a quote if PointMultiplier input is 0.
int DigitsM; // Number of digits normalized based on PointMultiplier_calculated.
bool InitFailed; // Used for soft INIT_FAILED. Hard INIT_FAILED resets input parameters.
datetime StartDate; // Will hold either StartFromDate or Time[0].
double onetick; // One normalized pip.
bool FirstRunDone = false; // If true - OnCalculate() was already executed once.
string Suffix = "_"; // Will store object name suffix depending on timeframe.
color_scheme CurrentColorScheme; // Required due to intraday sessions.
int Max_number_of_bars_in_a_session = 1;
int Timer = 0; // For throttling updates of market profiles in slow systems.
bool NeedToRestartDrawing = false; // Global flag for RightToLeft redrawing;
int CleanedUpOn = 0; // To prevent cleaning up the buffers again and again when the platform just starts.
double ValueAreaPercentage_double = 0.7; // Will be calculated based on the input parameter in OnInit().
datetime LastAlertTime_CandleCross = 0, LastAlertTime_GapCross = 0; // For CheckCurrentBar alerts.
datetime LastAlertTime = 0; // For CheckPreviousBar alerts;
double Close_prev = EMPTY_VALUE; // Previous price value for Price Break alerts.
int ArrowsCounter = 0; // Counter for naming of alert arrows.
sat_sun_solution _SaturdaySunday; // To change the input value if incompatible with timeframe.
session_period _Session; // Can be modified during runtime (hotkeys).
string m_FileName; // File name to store the session type.
string ObjPrefix; // Prefix for chart object names based on InstancePrefix input.
bool IndicatorHidden = false; // True when indicator objects are hidden via the toggle button.
string ToggleButtonName; // Name of the toggle button object.
bool HiddenObjectsDrawn = false; // True when objects have been drawn at least once while hidden.
int TPOSize = 1; // Number of chart bars each TPO spans (1 when TPOTimeframe == chart's TF).
int _TPOTimeframe; // Resolved TPO timeframe (never lower than chart's).
// Used for ColorBullBear.
bar_direction CurrentBarDirection = Neutral;
bar_direction PreviousBarDirection = Neutral;
bool NeedToReviewColors = false;
// For intraday sessions' start and end times.
int IDStartHours[4];
int IDStartMinutes[4];
int IDStartTime[4]; // Stores IDStartHours x 60 + IDStartMinutes for comparison purposes.
int IDEndHours[4];
int IDEndMinutes[4];
int IDEndTime[4]; // Stores IDEndHours x 60 + IDEndMinutes for comparison purposes.
color_scheme IDColorScheme[4];
bool IntradayCheckPassed = false;
int IntradaySessionCount = 0;
int _SessionsToCount;
int IntradayCrossSessionDefined = -1; // For special case used only with Ignore_Saturday_Sunday on Monday.
// We need to know where each session starts and its price range for when RaysUntilIntersection != Stop_No_Rays.
// These are used also when RaysUntilIntersection == Stop_No_Rays for Intraday sessions counting.
double RememberSessionMax[], RememberSessionMin[];
datetime RememberSessionStart[];
datetime RememberSessionEnd[]; // Used only for Arrows.
string RememberSessionSuffix[];
int SessionsNumber = 0; // Different from _SessionsToCount when working with Intraday sessions and for RaysUntilIntersection != Stop_No_Rays.
// Rectangle variables:
class CRectangleMP
{
private:
datetime prev_Time0;
double prev_High, prev_Low;
double prev_RectanglePriceMax, prev_RectanglePriceMin;
int Number; // Order number of the rectangle;
public:
double RectanglePriceMax, RectanglePriceMin;
datetime RectangleTimeMax, RectangleTimeMin;
datetime t1, t2; // To avoid reading object properties in Process() after sorting was done.
string name;
CRectangleMP(string);
~CRectangleMP(void) {};
void Process(int);
void ResetPrevTime0();
};
CRectangleMP* MPR_Array[];
int mpr_total = 0;
uint LastRecalculationTime = 0;
double DevelopingPOC[], DevelopingVAH[], DevelopingVAL[]; // Indicator buffers for Developing POC and VAH/VAL.
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
ObjPrefix = InstancePrefix + "_";
ToggleButtonName = ObjPrefix + "MPToggle";
m_FileName = ObjPrefix + "MP_" + IntegerToString(ChartID()) + ".txt";
if (!LoadSettingsFromDisk()) // Trying to read the saved session type from file.
{
_Session = Session;
}
return Initialize();
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(ChartID(), ToggleButtonName);
Deinitialize();
if (reason == REASON_PARAMETERS) GlobalVariableSet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters", 1);
if ((reason == REASON_REMOVE) || (reason == REASON_CHARTCLOSE) || (reason == REASON_PROGRAM))
{
DeleteSettingsFile();
}
else
{
SaveSettingsOnDisk();
}
}
//+------------------------------------------------------------------+
//| Custom Market Profile main iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& time_timeseries[],
const double& open[],
const double& high[],
const double& low[],
const double& close[],
const long& tick_volume[],
const long& volume[],
const int& spread[]
)
{
if (InitFailed)
{
if (!DisableAlertsOnWrongTimeframes) Print("Initialization failed. Please see the alert message for details.");
return 0;
}
if (prev_calculated == 0) // Cannot do this inside OnInit() because chart not fully loaded yet.
{
InitializeOnetick();
}
return OnCalculateMain(rates_total, prev_calculated);
}
//+------------------------------------------------------------------+
//| Finds the session's starting bar number for any given bar number.|
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindSessionStart(const int n)
{
if (_Session == Daily) return FindDayStart(n);
else if (_Session == Weekly) return FindWeekStart(n);
else if (_Session == Monthly) return FindMonthStart(n);
else if (_Session == Quarterly) return FindQuarterStart(n);
else if (_Session == Semiannual) return FindHalfyearStart(n);
else if (_Session == Annual) return FindYearStart(n);
else if (_Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and n is on Monday.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60) == 1))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// "Monday" part of the day. Effective only for "end < start" sessions.
if ((TimeHour(Time[n]) * 60 + TimeMinute(Time[n]) >= IDEndTime[intraday_i]) && (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the first bar on Monday after the borderline session.
int x = n;
while ((x < Bars) && (TimeHour(Time[x]) * 60 + TimeMinute(Time[x]) >= IDEndTime[intraday_i]))
{
x++;
// If there is no Sunday session (stepped into Saturday or another non-Sunday/non-Monday day, return normal day start.
if (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) > 1) return FindDayStart(n);
}
return (x - 1);
}
else
{
// Find the first Sunday bar.
int x = n;
while ((x < Bars) && ((TimeDayOfYear(Time[n] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[x] + TimeShiftMinutes * 60)) || (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 0))) x++;
// Number of sessions should be increased as we "lose" one session to Sunday.
_SessionsToCount++;
return (x - 1);
}
}
}
}
return FindDayStart(n);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindDayStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
int time_n_day_of_week = time_x_day_of_week;
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or it is Friday but the bar n is on Saturday.
while ((TimeDayOfYear(Time[n] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[x] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_x_day_of_week == 5) && (time_n_day_of_week == 6)))))
{
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the week's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindWeekStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday.
while ((SameWeek(Time[n] + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)))
{
// If Ignore_Saturday_Sunday is on and we stepped into Sunday, stop.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (time_x_day_of_week == 0)) break;
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the month's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindMonthStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60);
int time_n_day = TimeDay(Time[n] + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(Time[n] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of month.
while ((time_n_month == TimeMonth(Time[x] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (time_n_day == 1)))))
{
// If month distance somehow becomes greater than 1, break.
int month_distance = time_n_month - TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (month_distance < 0) month_distance = 12 + month_distance;
if (month_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of month. Despite it being current month, it should be skipped because it is appended to the previous month. Unless it is the sessionend day, which is the Saturday of the next month attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if ((time_x_day_of_week == 6) && (TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) && (time_n_day != TimeDay(Time[x] + TimeShiftMinutes * 60))) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of month. Despite it being current month, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && ((TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) || (TimeDay(Time[x] + TimeShiftMinutes * 60) == 2))) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+--------------------------------------------------------------------+
//| Finds the quarter's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+--------------------------------------------------------------------+
int FindQuarterStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(Time[n] + TimeShiftMinutes * 60);
int time_n_day = TimeDay(Time[n] + TimeShiftMinutes * 60);
bool first_day_of_quarter = false;
if (time_n_day == 1)
{
if ((time_n_month == 1) || (time_n_month == 4) || (time_n_month == 7) || (time_n_month == 10)) first_day_of_quarter = true;
}
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of quarter.
while (((time_n_month - 1) / 3 == (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 3) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (first_day_of_quarter)))))
{
// If quarter distance somehow becomes greater than 1, break.
int quarter_distance = (time_n_month - 1) / 3 - (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 3;
if (quarter_distance < 0) quarter_distance = 4 + quarter_distance;
if (quarter_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of quarter. Despite it being current month, it should be skipped because it is appended to the previous quarter. Unless it is the sessionend day, which is the Saturday of the next quarter attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_quarter = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_day_of_quarter = true;
}
if ((time_x_day_of_week == 6) && (x_first_day_of_quarter) && (!first_day_of_quarter)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of quarter. Despite it being current quarter, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
bool x_first_or_second_day_of_quarter = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if ((time_x_day == 1) || (time_x_day == 2))
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_or_second_day_of_quarter = true;
}
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && (x_first_or_second_day_of_quarter)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+---------------------------------------------------------------------+
//| Finds the half-year's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+---------------------------------------------------------------------+
int FindHalfyearStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(Time[n] + TimeShiftMinutes * 60);
int time_n_day = TimeDay(Time[n] + TimeShiftMinutes * 60);
bool first_day_of_halfyear = false;
if (time_n_day == 1)
{
if ((time_n_month == 1) || (time_n_month == 7)) first_day_of_halfyear = true;
}
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of half-year.
while (((time_n_month - 1) / 6 == (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 6) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (first_day_of_halfyear)))))
{
// If half-year distance somehow becomes greater than 1, break.
int halfyear_distance = (time_n_month - 1) / 6 - (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 6;
if (halfyear_distance < 0) halfyear_distance = 2 + halfyear_distance;
if (halfyear_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of half-year. Despite it being current half-year, it should be skipped because it is appended to the previous half-year. Unless it is the sessionend day, which is the Saturday of the next half-year attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_halfyear = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_day_of_halfyear = true;
}
if ((time_x_day_of_week == 6) && (x_first_day_of_halfyear) && (!first_day_of_halfyear)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of half-year. Despite it being current half-year, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
bool x_first_or_second_day_of_halfyear = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if ((time_x_day == 1) || (time_x_day == 2))
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_or_second_day_of_halfyear = true;
}
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && (x_first_or_second_day_of_halfyear)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+----------------------------------------------------------------+
//| Finds the year's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+----------------------------------------------------------------+
int FindYearStart(const int n)
{
if (n >= Bars) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(Time[n] + TimeShiftMinutes * 60);
int time_n_day_of_year = TimeDayOfYear(Time[n] + TimeShiftMinutes * 60);
int time_n_year = TimeYear(Time[n] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of year.
while ((time_n_year == TimeYear(Time[x] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (time_n_day_of_year == 1)))))
{
// If year distance somehow becomes greater than 1, break.
int year_distance = time_n_year - TimeYear(Time[x] + TimeShiftMinutes * 60);
if (year_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of year. Despite it being current year, it should be skipped because it is appended to the previous year. Unless it is the sessionend day, which is the Saturday of the next year attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if ((time_x_day_of_week == 6) && (TimeDayOfYear(Time[x] + TimeShiftMinutes * 60) == 1) && (time_n_day_of_year != 1)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of year. Despite it being current year, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && ((TimeDayOfYear(Time[x] + TimeShiftMinutes * 60) == 1) || (TimeDayOfYear(Time[x] + TimeShiftMinutes * 60) == 2))) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the session's end bar by the session's date. |
//+------------------------------------------------------------------+
int FindSessionEndByDate(const datetime date)
{
if (_Session == Daily) return FindDayEndByDate(date);
else if (_Session == Weekly) return FindWeekEndByDate(date);
else if (_Session == Monthly) return FindMonthEndByDate(date);
else if (_Session == Quarterly) return FindQuarterEndByDate(date);
else if (_Session == Semiannual) return FindHalfyearEndByDate(date);
else if (_Session == Annual) return FindYearEndByDate(date);
else if (_Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and the date is on Sunday.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the last bar of this intraday session and return it as sessionend.
int x = 0;
int abs_day = TimeAbsoluteDay(date + TimeShiftMinutes * 60);
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < Bars) && (abs_day < TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60))) // It's Sunday.
{
// On Monday.
if (TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60) == abs_day + 1)
{
// Inside the session.
if (TimeHour(Time[x]) * 60 + TimeMinute(Time[x]) < IDEndTime[intraday_i]) break;
// Break out earlier (on Monday's end bar) if working with 00:00-XX:XX session.
if (IDStartTime[intraday_i] == 0) break;
}
x++;
}
return x;
}
}
}
return FindDayEndByDate(date);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's end bar by the day's date. |
//+------------------------------------------------------------------+
int FindDayEndByDate(const datetime date)
{
int x = 0;
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < Bars) && (TimeAbsoluteDay(date + TimeShiftMinutes * 60) < TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60)))
{
// Check if Append_Saturday_Sunday is on and if the found end of the day is on Saturday and the given date is the previous Friday; or it is a Monday and the sought date is the previous Sunday.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if (((TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 6) || (TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60) == 1)) && (TimeAbsoluteDay(Time[x] + TimeShiftMinutes * 60) - TimeAbsoluteDay(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the week's end bar by the week's date. |
//+------------------------------------------------------------------+
int FindWeekEndByDate(const datetime date)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameWeek(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the month's end bar by the month's date. |
//+------------------------------------------------------------------+
int FindMonthEndByDate(const datetime date)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameMonth(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// Today is Saturday the 1st day of the next month. Despite it being in a next month, it should be appended to the current month.
if ((time_x_day_of_week == 6) && (TimeDay(Time[x] + TimeShiftMinutes * 60) == 1) && (TimeYear(Time[x] + TimeShiftMinutes * 60) * 12 + TimeMonth(Time[x] + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
// Given date is Sunday of a previous month. It was rejected in the previous month and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the month.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (TimeYear(Time[x] + TimeShiftMinutes * 60) * 12 + TimeMonth(Time[x] + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the quarter's end bar by the quarter's date. |
//+------------------------------------------------------------------+
int FindQuarterEndByDate(const datetime date)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameQuarter(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_quarter = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_day_of_quarter = true;
}
int quarter_distance = (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 3 - (TimeMonth(date + TimeShiftMinutes * 60) - 1) / 3;
if (quarter_distance < 0) quarter_distance = 4 + quarter_distance;
// Today is Saturday the 1st day of the next quarter. Despite it being in a next quarter, it should be appended to the current quarter.
if ((time_x_day_of_week == 6) && (x_first_day_of_quarter) && (quarter_distance == 1)) break;
// Given date is Sunday of a previous quarter. It was rejected in the previous quarter and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the quarter.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (quarter_distance == 1)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the half-year's end bar by the half-year's date. |
//+------------------------------------------------------------------+
int FindHalfyearEndByDate(const datetime date)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameHalfyear(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_halfyear = false;
int time_x_day = TimeDay(Time[x] + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(Time[x] + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_day_of_halfyear = true;
}
int halfyear_distance = (TimeMonth(Time[x] + TimeShiftMinutes * 60) - 1) / 6 - (TimeMonth(date + TimeShiftMinutes * 60) - 1) / 6;
if (halfyear_distance < 0) halfyear_distance = 2 + halfyear_distance;
// Today is Saturday the 1st day of the next half-year. Despite it being in a next half-year, it should be appended to the current half-year.
if ((time_x_day_of_week == 6) && (x_first_day_of_halfyear) && (halfyear_distance == 1)) break;
// Given date is Sunday of a previous half-year. It was rejected in the previous half-year and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the half-year.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (halfyear_distance == 1)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the year's end bar by the year's date. |
//+------------------------------------------------------------------+
int FindYearEndByDate(const datetime date)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameYear(date + TimeShiftMinutes * 60, Time[x] + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
int time_x_day_of_year = TimeDayOfYear(Time[x] + TimeShiftMinutes * 60);
int year_distance = TimeYear(Time[x] + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60);
// Today is Saturday the 1st day of the next year. Despite it being in a next year, it should be appended to the current year.
if ((time_x_day_of_week == 6) && (time_x_day_of_year == 1) && (year_distance == 1)) break;
// Given date is Sunday of a previous year. It was rejected in the previous year and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the year.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (year_distance == 1)) break;
}
x++;
if (x >= Bars) break;
time_x_day_of_week = TimeDayOfWeek(Time[x] + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same week. |
//+------------------------------------------------------------------+
int SameWeek(const datetime date1, const datetime date2)
{
int seconds_from_start = TimeDayOfWeek(date1) * 24 * 3600 + TimeHour(date1) * 3600 + TimeMinute(date1) * 60 + TimeSeconds(date1);
if (date1 == date2) return true;
else if (date2 < date1)
{
if (date1 - date2 <= seconds_from_start) return true;
}
// 604800 - seconds in one week.
else if (date2 - date1 < 604800 - seconds_from_start) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same month. |
//+------------------------------------------------------------------+
int SameMonth(const datetime date1, const datetime date2)
{
if ((TimeMonth(date1) == TimeMonth(date2)) && (TimeYear(date1) == TimeYear(date2))) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same quarter. |
//+------------------------------------------------------------------+
int SameQuarter(const datetime date1, const datetime date2)
{
if (((TimeMonth(date1) - 1) / 3 == (TimeMonth(date2) - 1) / 3) && (TimeYear(date1) == TimeYear(date2))) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same half-year. |
//+------------------------------------------------------------------+
int SameHalfyear(const datetime date1, const datetime date2)
{
if (((TimeMonth(date1) - 1) / 6 == (TimeMonth(date2) - 1) / 6) && (TimeYear(date1) == TimeYear(date2))) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same year. |
//+------------------------------------------------------------------+
int SameYear(const datetime date1, const datetime date2)
{
if (TimeYear(date1) == TimeYear(date2)) return true;
return false;
}
//+------------------------------------------------------------------+
//| Puts a dot (rectangle) at a given position and color. |
//| price and time are coordinates. |
//| range is for the second coordinate. |
//| bar is to determine the color of the dot. |
//| Returns inverted end time only for the RightToLeft session. |
//+------------------------------------------------------------------+
datetime PutDot(const double price, const int start_bar, const int range, const int bar, string rectangle_prefix = "", datetime converted_time = 0)
{
double divisor, color_shift;
int colour = -1;
// All dots are with the same date/time for a given origin bar, but with a different price.
string LastNameStart = " " + TimeToString(Time[bar + start_bar]) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
if (ColorBullBear) colour = CalculateProperColor();
// Bull/bear coloring part.
if (NeedToReviewColors)
{
// Finding all dots (rectangle objects) with proper suffix and start of last name (date + time of the bar, but not price).
// This is needed to change their color if candle changed its direction.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_RECTANGLE);
for (int i = obj_total - 1; i >= 0; i--)
{
string obj = ObjectName(ChartID(), i, -1, OBJ_RECTANGLE);
// Probably some other object.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix)) != rectangle_prefix + "MP" + Suffix) continue;
// Previous bar's dot found.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix + LastNameStart)) != rectangle_prefix + "MP" + Suffix + LastNameStart) break;
// Change color.
ObjectSetInteger(0, obj, OBJPROP_COLOR, colour);
}
}
if (ObjectFind(0, rectangle_prefix + "MP" + Suffix + LastName) >= 0)
{
if ((!RightToLeft) || (converted_time == 0)) return 0; // Normal case;
}
datetime time_end, time_start;
datetime prev_time = converted_time; // For drawing, we need two times.
if (converted_time != 0) // This is the right-to-left mode and the right-most session.
{
// Check if we have started a new right-most session, so the previous one should be cleaned up.
static datetime prev_time_start_bar = 0;
if ((Time[start_bar] != prev_time_start_bar) && (prev_time_start_bar != 0)) // New right-most session arrived - recalculate everything.
{
NeedToRestartDrawing = true;
}
prev_time_start_bar = Time[start_bar];
// Find the time:
int x = -1;
for (int i = (range + 1) * TPOSize; i > 0; i--) // + 1 to get a bit "lefter" time in converted_time, and actual dot's time into prev_time.
{
prev_time = converted_time;
if (converted_time == Time[0]) // First time stepped into existing candles.
{
x = i + 1; // Remember the position.
converted_time = Time[1]; // Move further.
}
else if (converted_time < Time[0])
{
if (x == -1) x = iBarShift(Symbol(), Period(), converted_time) + i + 1;
converted_time = Time[x - i]; // While inside the existing candles, use existing Time for candles.
}
else converted_time -= PeriodSeconds(); // While beyond the current candle, subtract fixed time periods to move left on the time scale.
}
time_end = converted_time;
time_start = prev_time;
}
else
{
if (start_bar - (range + 1) * TPOSize < 0) time_end = Time[0] + PeriodSeconds(); // Protection from 'Array out of range' error.
else time_end = Time[start_bar - (range + 1) * TPOSize];
if (start_bar - range * TPOSize < 0) time_start = Time[0];
else time_start = Time[start_bar - range * TPOSize];
}
if (ObjectFind(0, rectangle_prefix + "MP" + Suffix + LastName) >= 0) // Need to move the rectangle.
{
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_TIME, 0, time_start);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_TIME, 1, time_end);
}
else ObjectCreate(0, rectangle_prefix + "MP" + Suffix + LastName, OBJ_RECTANGLE, 0, time_start, price, time_end, price - onetick);
if (!ColorBullBear) // Otherwise, colour is already calculated.
{
// Color switching depending on the distance of the bar from the session's beginning.
int offset1, offset2;
// Using 3 as a step for color switching because MT4 has buggy invalid color codes that mess up with the chart.
// Anyway, the number of supported colors is much lower than we get here, even with step = 3.
switch (CurrentColorScheme)
{
case Blue_to_Red:
colour = 0xFF0000; // clrBlue;
offset1 = 0x030000;
offset2 = 0x000003;
break;
case Red_to_Green:
colour = 0x0000FF; // clrDarkRed;
offset1 = 0x000003;
offset2 = 0x000300;
break;
case Green_to_Blue:
colour = 0x00FF00; // clrDarkGreen;
offset1 = 0x000300;
offset2 = 0x030000;
break;
case Yellow_to_Cyan:
colour = 0x00FFFF; // clrYellow;
offset1 = 0x000003;
offset2 = 0x030000;
break;
case Magenta_to_Yellow:
colour = 0xFF00FF; // clrMagenta;
offset1 = 0x030000;
offset2 = 0x000300;
break;
case Cyan_to_Magenta:
colour = 0xFFFF00; // clrCyan;
offset1 = 0x000300;
offset2 = 0x000003;
break;
case Single_Color:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
default:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
}
// No need to do these calculations if plain color is used.
if (CurrentColorScheme != Single_Color)
{
divisor = 3.0 / 0xFF * (double)Max_number_of_bars_in_a_session;
// bar is negative.
color_shift = MathFloor((double)bar / divisor);
// Prevents color overflow.
if ((int)color_shift < -85) color_shift = -85;
colour += (int)color_shift * offset1;
colour -= (int)color_shift * offset2;
}
}
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_COLOR, colour);
// Fills rectangle.
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_BACK, true);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_HIDDEN, true);
return time_end;
}
//+------------------------------------------------------------------+
//| Deletes all chart objects created by the indicator. |
//+------------------------------------------------------------------+
void ObjectCleanup(string rectangle_prefix = "")
{
rectangle_prefix = ObjPrefix + rectangle_prefix;
// Delete all rectangles with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "MP" + Suffix, 0, OBJ_RECTANGLE);
ObjectsDeleteAll(0, rectangle_prefix + "Median" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_LeftSide" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_RightSide" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Top" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Bottom" + Suffix, 0, OBJ_TREND);
if (ShowValueAreaRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Value Area HighRay" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "Value Area LowRay" + Suffix, 0, OBJ_TREND);
}
if (ShowMedianRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Median Ray" + Suffix, 0, OBJ_TREND);
}
if (ShowKeyValues)
{
// Delete all text labels with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "VAH" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "VAL" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "POC" + Suffix, 0, OBJ_TEXT);
}
if (ShowSinglePrint)
{
// Delete all Single Print marks.
ObjectsDeleteAll(0, rectangle_prefix + "MPSP" + Suffix, 0, OBJ_RECTANGLE);
}
if (SinglePrintRays)
{
// Delete all Single Print rays.
ObjectsDeleteAll(0, rectangle_prefix + "MPSPR" + Suffix, 0, OBJ_TREND);
}
if (AlertArrows)
{
DeleteArrowsByPrefix(rectangle_prefix);
}
if (ShowTPOCounts)
{
ObjectsDeleteAll(0, rectangle_prefix + "TPOCA" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "TPOCB" + Suffix, 0, OBJ_TEXT);
}
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool GetHoursAndMinutes(string time_string, int& hours, int& minutes, int& time)
{
if (StringLen(time_string) == 4) time_string = "0" + time_string;
if (
// Wrong length.
(StringLen(time_string) != 5) ||
// Wrong separator.
(time_string[2] != ':') ||
// Wrong first number (only 24 hours in a day).
((time_string[0] < '0') || (time_string[0] > '2')) ||
// 00 to 09 and 10 to 19.
(((time_string[0] == '0') || (time_string[0] == '1')) && ((time_string[1] < '0') || (time_string[1] > '9'))) ||
// 20 to 23.
((time_string[0] == '2') && ((time_string[1] < '0') || (time_string[1] > '3'))) ||
// 0M to 5M.
((time_string[3] < '0') || (time_string[3] > '5')) ||
// M0 to M9.
((time_string[4] < '0') || (time_string[4] > '9'))
)
{
Print("Wrong time string: ", time_string, ". Please use HH:MM format.");
return false;
}
string result[];
int number_of_substrings = StringSplit(time_string, ':', result);
hours = (int)StringToInteger(result[0]);
minutes = (int)StringToInteger(result[1]);
time = hours * 60 + minutes;
return true;
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool CheckIntradaySession(const bool enable, const string start_time, const string end_time, const color_scheme cs)
{
if (enable)
{
if (!GetHoursAndMinutes(start_time, IDStartHours[IntradaySessionCount], IDStartMinutes[IntradaySessionCount], IDStartTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", start_time, ".");
return false;
}
if (!GetHoursAndMinutes(end_time, IDEndHours[IntradaySessionCount], IDEndMinutes[IntradaySessionCount], IDEndTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", end_time, ".");
return false;
}
// Special case of the intraday session ending at "00:00".
if (IDEndTime[IntradaySessionCount] == 0)
{
// Turn it into "24:00".
IDEndHours[IntradaySessionCount] = 24;
IDEndMinutes[IntradaySessionCount] = 0;
IDEndTime[IntradaySessionCount] = 24 * 60;
}
IDColorScheme[IntradaySessionCount] = cs;
// For special case used only with Ignore_Saturday_Sunday on Monday.
if (IDEndTime[IntradaySessionCount] < IDStartTime[IntradaySessionCount]) IntradayCrossSessionDefined = IntradaySessionCount;
IntradaySessionCount++;
}
return true;
}
//+------------------------------------------------------------------+
//| Main procedure to draw the Market Profile based on a session |
//| start bar and session end bar. |
//| i - session number with 0 being the oldest one. |
//| Returns true on success, false - on failure. |
//+------------------------------------------------------------------+
bool ProcessSession(const int sessionstart, const int sessionend, const int i, CRectangleMP* rectangle = NULL)
{
string rectangle_prefix = ObjPrefix; // Only for rectangle sessions.
if (sessionstart >= Bars) return false; // Data not yet ready.
if (onetick == 0) return false; // onetick cannot be zero.
// double SessionMax = DBL_MIN, SessionMin = DBL_MAX;
// Map session boundaries to higher-TF bar indices when using multi-timeframe TPO.
int htf_sessionstart = sessionstart;
int htf_sessionend = sessionend;
if (TPOSize > 1)
{
htf_sessionstart = iBarShift(Symbol(), _TPOTimeframe, Time[sessionstart]);
htf_sessionend = iBarShift(Symbol(), _TPOTimeframe, Time[sessionend]);
if (htf_sessionstart < 0) htf_sessionstart = 0;
if (htf_sessionend < 0) htf_sessionend = 0;
}
// Find the session's high and low.
double SessionMax = iHigh(Symbol(), _TPOTimeframe, iHighest(Symbol(), _TPOTimeframe, MODE_HIGH, htf_sessionstart - htf_sessionend + 1, htf_sessionend));
double SessionMin = iLow( Symbol(), _TPOTimeframe, iLowest( Symbol(), _TPOTimeframe, MODE_LOW, htf_sessionstart - htf_sessionend + 1, htf_sessionend));
int session_counter = i;
if (_Session == Rectangle)
{
rectangle_prefix = ObjPrefix + rectangle.name + "_";
if (SessionMax > rectangle.RectanglePriceMax) SessionMax = NormalizeDouble(rectangle.RectanglePriceMax, DigitsM);
if (SessionMin < rectangle.RectanglePriceMin) SessionMin = NormalizeDouble(rectangle.RectanglePriceMin, DigitsM);
}
else
{
// Find Time[sessionstart] among RememberSessionStart[].
bool need_to_increment = true;
for (int j = 0; j < SessionsNumber; j++)
{
if (RememberSessionStart[j] == Time[sessionstart])
{
need_to_increment = false;
session_counter = j; // Real number of the session.
break;
}
}
// Raise the number of sessions and resize arrays.
if (need_to_increment)
{
SessionsNumber++;
session_counter = SessionsNumber - 1; // Newest session.
ArrayResize(RememberSessionMax, SessionsNumber);
ArrayResize(RememberSessionMin, SessionsNumber);
ArrayResize(RememberSessionStart, SessionsNumber);
ArrayResize(RememberSessionSuffix, SessionsNumber);
ArrayResize(RememberSessionEnd, SessionsNumber); // Used only for Arrows.
}
}
// Adjust SessionMin, SessionMax for onetick granularity.
SessionMax = NormalizeDouble(MathRound(SessionMax / onetick) * onetick, DigitsM);
SessionMin = NormalizeDouble(MathRound(SessionMin / onetick) * onetick, DigitsM);
RememberSessionMax[session_counter] = SessionMax;
RememberSessionMin[session_counter] = SessionMin;
RememberSessionStart[session_counter] = Time[sessionstart];
RememberSessionEnd[session_counter] = Time[sessionend]; // Used only for Arrows.
RememberSessionSuffix[session_counter] = Suffix;
// Used to make sure that SessionMax increments only by 'onetick' increments.
// This is needed only when updating the latest trading session and PointMultiplier_calculated > 1.
static double PreviousSessionMax = DBL_MIN;
static datetime PreviousSessionStartTime = 0;
// Reset PreviousSessionMax when a new session becomes the 'latest one'.
if (Time[sessionstart] > PreviousSessionStartTime)
{
PreviousSessionMax = DBL_MIN;
PreviousSessionStartTime = Time[sessionstart];
}
if ((FirstRunDone) && (i == _SessionsToCount - 1) && (PointMultiplier_calculated > 1)) // Updating the latest trading session.
{
if (SessionMax - PreviousSessionMax < onetick) // SessionMax increased only slightly - too small to use the new value with the current onetick.
{
SessionMax = PreviousSessionMax; // Do not update session max.
}
else
{
if (PreviousSessionMax != DBL_MIN)
{
// Calculate number of increments.
double nc = (SessionMax - PreviousSessionMax) / onetick;
// Adjust SessionMax.
SessionMax = NormalizeDouble(PreviousSessionMax + MathRound(nc) * onetick, DigitsM);
}
PreviousSessionMax = SessionMax;
}
}
int TPOperPrice[];
// Possible price levels if multiplied to integer.
int max = (int)MathRound((SessionMax - SessionMin) / onetick + 2); // + 2 because further we will be possibly checking array at SessionMax + 1.
ArrayResize(TPOperPrice, max);
ArrayInitialize(TPOperPrice, 0);
bool SinglePrintTracking_array[]; // For SinglePrint rays.
if (SinglePrintRays)
{
ArrayResize(SinglePrintTracking_array, max);
ArrayInitialize(SinglePrintTracking_array, false);
}
int MaxRange = 0; // Maximum distance from session start to the drawn dot.
double PriceOfMaxRange = 0; // Level of the maximum range, required to draw Median.
double DistanceToCenter = DBL_MAX; // Closest distance to center for the Median.
// Right to left for the final session:
// 1. Get rightmost time.
// 2a. If it <= Time[0] - use normal bar-walking, else:
// 2b. To "move" to the left - subtract PeriodSeconds().
// 3. Draw everything based on that Time.
// 4. Redraw everything every time the rightmost time changes.
// 5. Ray lines to the left.
// Right-to-left depiction of the rightmost session.
datetime converted_time = 0;
datetime converted_end_time = 0;
datetime min_converted_end_time = UINT_MAX;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
int dummy_subwindow;
double dummy_price;
if (_Session == Rectangle) converted_time = rectangle.RectangleTimeMax;
else ChartXYToTimePrice(0, (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS), 0, dummy_subwindow, converted_time, dummy_price);
}
int TotalTPO = 0; // Total amount of dots (TPO's).
// Going through all possible quotes from session's High to session's Low.
for (double price = SessionMax; price >= SessionMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int range = 0; // Distance from first bar to the current bar.
for (int bar = htf_sessionstart; bar >= htf_sessionend; bar--)
{
// Price is encountered in the given bar.
if ((price >= iLow(Symbol(), _TPOTimeframe, bar)) && (price <= iHigh(Symbol(), _TPOTimeframe, bar)))
{
// Map higher-TF bar to chart bar index for object naming and positioning.
int chart_bar = (TPOSize > 1) ? iBarShift(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, bar)) : bar;
// Update maximum distance from session's start to the found bar (needed for Median).
// Using the center-most Median if there are more than one.
if ((MaxRange < range) || ((MaxRange == range) && (MathAbs(price - (SessionMin + (SessionMax - SessionMin) / 2)) < DistanceToCenter)))
{
MaxRange = range;
PriceOfMaxRange = price;
DistanceToCenter = MathAbs(price - (SessionMin + (SessionMax - SessionMin) / 2));
}
if (!DisableHistogram)
{
if (ColorBullBear)
{
// These are needed in all cases when we color dots according to bullish/bearish bars.
double close_price = iClose(Symbol(), _TPOTimeframe, bar);
double open_price = iOpen(Symbol(), _TPOTimeframe, bar);
if (close_price == open_price) CurrentBarDirection = Neutral;
else if (close_price > open_price) CurrentBarDirection = Bullish;
else if (close_price < open_price) CurrentBarDirection = Bearish;
// This is for recoloring of the dots from the current (most-latest) bar.
if (bar == 0)
{
if (PreviousBarDirection == CurrentBarDirection) NeedToReviewColors = false;
else
{
NeedToReviewColors = true;
PreviousBarDirection = CurrentBarDirection;
}
}
}
// Draws rectangle.
if (!RightToLeft) PutDot(price, sessionstart, range, chart_bar - sessionstart, rectangle_prefix);
// Inverted drawing.
else
{
converted_end_time = PutDot(price, sessionstart, range, chart_bar - sessionstart, rectangle_prefix, converted_time);
if (converted_end_time < min_converted_end_time) min_converted_end_time = converted_end_time; // Find the leftmost time to use for the left border of the value area.
}
}
// Remember the number of encountered bars for this price.
int index = (int)MathRound((price - SessionMin) / onetick);
TPOperPrice[index]++;
range++;
TotalTPO++;
}
}
// Single print marking is due at this price.
if (ShowSinglePrint)
{
if (range == 1) PutSinglePrintMark(price, sessionstart, rectangle_prefix);
else if (range > 1) RemoveSinglePrintMark(price, sessionstart, rectangle_prefix); // Remove single print max if it exists.
}
if (SinglePrintRays)
{
int index = (int)MathRound((price - SessionMin) / onetick);
if (range == 1) SinglePrintTracking_array[index] = true; // Remember the single print's position relative to the price.
else SinglePrintTracking_array[index] = false;
}
}
// Single Print Rays
// Go through all prices again, check TPOs - whether they are single and whether they aren't bordered by another single print TPOs?
if (SinglePrintRays)
{
color spr_color = SinglePrintColor; // Normal ray color.
if ((HideRaysFromInvisibleSessions) && (Time[WindowFirstVisibleBar()] >= Time[sessionstart])) spr_color = clrNONE; // Hide rays if behind the screen.
for (double price = SessionMax; price >= SessionMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int index = (int)MathRound((price - SessionMin) / onetick);
if (SinglePrintTracking_array[index])
{
if (price == SessionMax) // Top of the session.
{
PutSinglePrintRay(price, sessionstart, rectangle_prefix, spr_color);
}
else
{
if (SinglePrintTracking_array[index + 1] == false) // Above is a non-single print.
{
PutSinglePrintRay(price, sessionstart, rectangle_prefix, spr_color);
}
else
{
RemoveSinglePrintRay(price, sessionstart, rectangle_prefix);
}
}
if (price == SessionMin) // Bottom of the session.
{
PutSinglePrintRay(price - onetick, sessionstart, rectangle_prefix, spr_color);
}
else
{
if (SinglePrintTracking_array[index - 1] == false) // Below is a non-single print.
{
PutSinglePrintRay(price - onetick, sessionstart, rectangle_prefix, spr_color);
}
else
{
RemoveSinglePrintRay(price - onetick, sessionstart, rectangle_prefix);
}
}
}
else
{
// Attempt to remove a horizontal line above and below the "potentially no longer existing" single print mark.
//RemoveSinglePrintRay(price, sessionstart, rectangle_prefix);
RemoveSinglePrintRay(price - onetick, sessionstart, rectangle_prefix);
}
}
}
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) CalculateDevelopingPOCVAHVAL(sessionstart, sessionend, rectangle); // Developing POC if necessary.
double TotalTPOdouble = TotalTPO;
// Calculate the number of TPO's in the Value Area.
int ValueControlTPO = (int)MathRound(TotalTPOdouble * ValueAreaPercentage_double);
// Start with the TPO's of the Median.
int index = (int)((PriceOfMaxRange - SessionMin) / onetick);
if (index < 0) return false; // Data not yet ready.
int TPOcount = TPOperPrice[index];
// Go through the price levels above and below median adding the biggest to TPO count until the 70% of TPOs are inside the Value Area.
int up_offset = 1;
int down_offset = 1;
while (TPOcount < ValueControlTPO)
{
double abovePrice = PriceOfMaxRange + up_offset * onetick;
double belowPrice = PriceOfMaxRange - down_offset * onetick;
// If belowPrice is out of the session's range then we should add only abovePrice's TPO's, and vice versa.
index = (int)MathRound((abovePrice - SessionMin) / onetick);
int index2 = (int)MathRound((belowPrice - SessionMin) / onetick);
if (((belowPrice < SessionMin) || (TPOperPrice[index] >= TPOperPrice[index2])) && (abovePrice <= SessionMax))
{
TPOcount += TPOperPrice[index];
up_offset++;
}
else if (belowPrice >= SessionMin)
{
TPOcount += TPOperPrice[index2];
down_offset++;
}
// Cannot proceed - too few data points.
else if (TPOcount < ValueControlTPO)
{
break;
}
}
string LastName = " " + TimeToString(Time[sessionstart]);
// Delete old Median.
ObjectDelete(rectangle_prefix + "Median" + Suffix + LastName);
// Draw a new one.
index = MathMax(sessionstart - (MaxRange + 1) * TPOSize, 0);
datetime time_start, time_end;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
time_end = min_converted_end_time;
time_start = converted_time;
}
else
{
time_end = Time[index];
time_start = Time[sessionstart];
}
ObjectCreate(0, rectangle_prefix + "Median" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange, time_end, PriceOfMaxRange);
color mc = MedianColor;
// Prominent Median (PPOC):
if ((double)(sessionstart - index) / (double)Max_number_of_bars_in_a_session * 100 >= ProminentMedianPercentage)
{
mc = ProminentMedianColor;
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_WIDTH, ProminentMedianWidth);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_STYLE, ProminentMedianStyle);
}
else
{
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_WIDTH, MedianWidth);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_STYLE, MedianStyle);
}
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_COLOR, mc);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_TOOLTIP, "Median (POC)");
// Delete old Value Area Sides.
ObjectDelete(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange + up_offset * onetick, time_start, PriceOfMaxRange - down_offset * onetick + onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_COLOR, ValueAreaSidesColor);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_STYLE, ValueAreaSidesStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaSidesWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Left Side");
ObjectDelete(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJ_TREND, 0, time_end, PriceOfMaxRange + up_offset * onetick, time_end, PriceOfMaxRange - down_offset * onetick + onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_COLOR, ValueAreaSidesColor);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_STYLE, ValueAreaSidesStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaSidesWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Right Side");
// Delete old Value Area Top and Bottom.
ObjectDelete(0, rectangle_prefix + "VA_Top" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange + up_offset * onetick, time_end, PriceOfMaxRange + up_offset * onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_STYLE, ValueAreaHighLowStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaHighLowWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Top");
ObjectDelete(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange - down_offset * onetick + onetick, time_end, PriceOfMaxRange - down_offset * onetick + onetick); // Adding onetick to put the value area bottom border to its real location as PriceOfMaxRange - down_offset * onetick puts it just below the bottom TPO, which itself is 1 tick deep.
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_STYLE, ValueAreaHighLowStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaHighLowWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Bottom");
// VAH, VAL, and POC printout.
if (ShowKeyValues)
{
ENUM_ANCHOR_POINT anchor_poc = ANCHOR_RIGHT, anchor_va = ANCHOR_RIGHT;
datetime value_time = time_start;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
value_time = time_end; // Inverting label display position.
// Value Area printout position.
if (((_Session != Rectangle) && ((ShowValueAreaRays == All) || (ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent))) // For non-rectangle sessions, it is already known that it is the current session, so just check if current session uses rays.
|| ((_Session == Rectangle) && ( // For rectangles, need to check which session is it and whether it has rays.
(((ShowValueAreaRays == AllPrevious) && (SessionsNumber - session_counter >= 2)) ||
(((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - session_counter == 2)) ||
(((ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - session_counter == 1)) ||
(ShowValueAreaRays == All)))
))
{
anchor_va = ANCHOR_RIGHT_LOWER;
}
// Median printout position.
if (((_Session != Rectangle) && ((ShowMedianRays == All) || (ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent))) // For non-rectangle sessions, it is already known that it is the current session, so just check if current session uses rays.
|| ((_Session == Rectangle) && ( // For rectangles, need to check which session is it and whether it has rays.
(((ShowMedianRays == AllPrevious) && (SessionsNumber - session_counter >= 2)) ||
(((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - session_counter == 2)) ||
(((ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - session_counter == 1)) ||
(ShowMedianRays == All)))
))
{
anchor_poc = ANCHOR_RIGHT_LOWER;
}
}
ValuePrintOut(rectangle_prefix + "VAH" + Suffix + LastName, value_time, PriceOfMaxRange + up_offset * onetick, "Value Area High Price: " + DoubleToString(PriceOfMaxRange + up_offset * onetick, _Digits), anchor_va);
ValuePrintOut(rectangle_prefix + "VAL" + Suffix + LastName, value_time, PriceOfMaxRange - down_offset * onetick, "Value Area Low Price: " + DoubleToString(PriceOfMaxRange - down_offset * onetick, _Digits), anchor_va);
ValuePrintOut(rectangle_prefix + "POC" + Suffix + LastName, value_time, PriceOfMaxRange, "POC (Median) Price: " + DoubleToString(PriceOfMaxRange, _Digits), anchor_poc);
}
// TPO counts for the number of TPOs above the POC and below the POC.
if (ShowTPOCounts)
{
// Go through the price levels above and below median/POC to calculate TPO counts above and below it.
// Above:
int TPOCountAbove = 0;
for (double abovePrice = PriceOfMaxRange + onetick; abovePrice <= SessionMax; abovePrice += onetick)
{
index = (int)MathRound((abovePrice - SessionMin) / onetick);
TPOCountAbove += TPOperPrice[index];
}
int TPOCountBelow = 0;
for (double belowPrice = PriceOfMaxRange - onetick; belowPrice >= SessionMin; belowPrice -= onetick)
{
index = (int)MathRound((belowPrice - SessionMin) / onetick);
TPOCountBelow += TPOperPrice[index];
}
ENUM_ANCHOR_POINT anchor_tpoca = ANCHOR_LEFT_LOWER, anchor_tpocb = ANCHOR_LEFT_UPPER;
datetime value_time = time_end;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
value_time = time_start; // Inverting label display position.
anchor_tpoca = ANCHOR_RIGHT_LOWER;
anchor_tpocb = ANCHOR_RIGHT_UPPER;
}
ValuePrintOut(rectangle_prefix + "TPOCA" + Suffix + LastName, value_time, PriceOfMaxRange, "Number of TPOs above the POC: " + IntegerToString(TPOCountAbove), anchor_tpoca, TPOCountAboveColor, TPOCountAbove);
ValuePrintOut(rectangle_prefix + "TPOCB" + Suffix + LastName, value_time, PriceOfMaxRange, "Number of TPOs below the POC: " + IntegerToString(TPOCountBelow), anchor_tpocb, TPOCountBelowColor, TPOCountBelow);
}
return true;
}
//+--------------------------------------------------------------------------+
//| A cycle through intraday sessions for a given day with necessary checks. |
//| Returns true on success, false - on failure. |
//+--------------------------------------------------------------------------+
bool ProcessIntradaySession(int sessionstart, int sessionend, int i)
{
// 'remember_*' vars point at day start and day end throughout this function.
int remember_sessionstart = sessionstart;
int remember_sessionend = sessionend;
if (remember_sessionend >= Bars) return false;
// Special case stuff.
bool ContinuePreventionFlag = false;
// Start a cycle through intraday sessions if needed.
// For each intraday session, find its own sessionstart and sessionend.
int IntradaySessionCount_tmp = IntradaySessionCount;
// If Ignore_Saturday_Sunday is on, day's start is on Monday, and there is a "22:00-06:00"-style intraday session defined, increase the counter to run the "later" "22:00-06:00" session and create this temporary dummy session.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 1) && (IntradayCrossSessionDefined > -1))
{
IntradaySessionCount_tmp++;
}
for (int intraday_i = 0; intraday_i < IntradaySessionCount_tmp; intraday_i++)
{
// Continue was triggered during the special case iteration.
if (ContinuePreventionFlag) break;
// Special case iteration.
if (intraday_i == IntradaySessionCount)
{
intraday_i = IntradayCrossSessionDefined;
ContinuePreventionFlag = true;
}
Suffix = "_ID" + IntegerToString(intraday_i);
CurrentColorScheme = IDColorScheme[intraday_i];
// Get minutes.
Max_number_of_bars_in_a_session = IDEndTime[intraday_i] - IDStartTime[intraday_i];
// If end is less than beginning:
if (Max_number_of_bars_in_a_session < 0)
{
Max_number_of_bars_in_a_session = 24 * 60 + Max_number_of_bars_in_a_session;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Day start is on Monday. And it is not a special additional intra-Monday session.
if ((TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag))
{
// Cut out Sunday part.
Max_number_of_bars_in_a_session -= 24 * 60 - IDStartTime[intraday_i];
}
// Day start is on Friday.
else if (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 5)
{
// Cut out Saturday part.
Max_number_of_bars_in_a_session -= IDEndTime[intraday_i];
}
}
}
// If Append_Saturday_Sunday is on:
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The intraday session starts on 00:00 or otherwise captures midnight, and remember_sessionstart points to Sunday:
if (((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i])) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 0))
{
// Add Sunday hours.
Max_number_of_bars_in_a_session += 24 * 60 - (TimeHour(Time[remember_sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[remember_sessionstart] + TimeShiftMinutes * 60));
// Remove the part of Sunday that has already been added before.
if (IDStartTime[intraday_i] > IDEndTime[intraday_i]) Max_number_of_bars_in_a_session -= 24 * 60 - IDStartTime[intraday_i];
}
// The intraday session ends on 00:00 or otherwise captures midnight, and remember_sessionstart points to Friday:
else if (((IDEndTime[intraday_i] == 24 * 60) || (IDStartTime[intraday_i] > IDEndTime[intraday_i])) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 5))
{
// Add Saturday hours. The thing is we don't know how many hours there will be on Saturday. So add to max.
Max_number_of_bars_in_a_session += 24 * 60;
// Remove the part of Saturday that has already been added before.
if (IDStartTime[intraday_i] > IDEndTime[intraday_i]) Max_number_of_bars_in_a_session -= 24 * 60 - IDEndTime[intraday_i];
}
}
Max_number_of_bars_in_a_session = Max_number_of_bars_in_a_session / (PeriodSeconds() / 60); // Convert minutes to bars.
// If it is the updating stage, we need to recalculate only those intraday sessions that include the current bar.
int hour, minute, time;
if (FirstRunDone)
{
//sessionstart = day_start;
hour = TimeHour(Time[0] + TimeShiftMinutes * 60);
minute = TimeMinute(Time[0] + TimeShiftMinutes * 60);
time = hour * 60 + minute;
// For example, 13:00-18:00.
if (IDStartTime[intraday_i] < IDEndTime[intraday_i])
{
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// Skip all sessions that do not absorb Sunday session:
if ((IDStartTime[intraday_i] != 0) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 0)) continue;
// Skip all sessions that do not absorb Saturday session:
if ((IDEndTime[intraday_i] != 24 * 60) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 6)) continue;
}
// If Append_Saturday_Sunday is on and the session starts on 00:00, and now is either Sunday or Monday before the session's end:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && ((TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 0) || ((TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
else if (((time < IDEndTime[intraday_i]) && (time >= IDStartTime[intraday_i]))
// If Append_Saturday_Sunday is on and the session ends on 24:00, and now is Saturday, then go on in case, for example, of 18:00 Saturday time and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 6)))
{
sessionstart = 0;
int sessiontime = TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60);
while (((sessiontime > IDStartTime[intraday_i])
// Prevents problems when the day has partial data (e.g. Sunday) when neither appending not ignoring Saturday/Sunday. Alternatively, continue looking for the sessionstart bar if we moved from Saturday to Friday with Append_Saturday_Sunday and for XX:XX-00:00 session.
&& ((TimeDayOfYear(Time[sessionstart] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[0] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 6))))
// If Append_Saturday_Sunday is on and the session ends on 24:00 and the session start is now going through Saturday, then go on in case, for example, of 13:00 Saturday time and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 6)))
{
sessionstart++;
sessiontime = TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60);
}
// This check is necessary because sessionstart may pass to the wrong day in some cases.
if (sessionstart > remember_sessionstart) sessionstart = remember_sessionstart;
}
else continue;
}
// For example, 22:00-6:00.
else if (IDStartTime[intraday_i] > IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and now is either Sunday or Monday before the session's end:
if ((_SaturdaySunday == Append_Saturday_Sunday) && ((TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 0) || ((TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
// If Ignore_Saturday_Sunday is on and it is Monday before the session's end:
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
else if (((time < IDEndTime[intraday_i]) || (time >= IDStartTime[intraday_i]))
// If Append_Saturday_Sunday is on and now is Saturday, then go on in case, for example, of 18:00 Saturday time and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[0] + TimeShiftMinutes * 60) == 6)))
{
sessionstart = 0;
int sessiontime = TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60);
// Within 24 hours of the current time - but can be today or yesterday.
while (((sessiontime > IDStartTime[intraday_i]) && (Time[0] - Time[sessionstart] <= 3600 * 24))
// Same day only.
|| ((sessiontime < IDEndTime[intraday_i]) && (TimeDayOfYear(Time[sessionstart] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[0] + TimeShiftMinutes * 60)))
// If Append_Saturday_Sunday is on and the session start is now going through Saturday, then go on in case, for example, of 18:00 Saturday time and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 6)))
{
sessionstart++;
sessiontime = TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60);
}
// When the same condition in the above while cycle fails and sessionstart is one step farther than needed.
if (Time[0] - Time[sessionstart] > 3600 * 24) sessionstart--;
}
else continue;
}
// If start time equals end time, we can skip the session.
else continue;
// Because apparently, we are still inside the session.
sessionend = 0;
if (!ProcessSession(sessionstart, sessionend, i)) return false;
}
// If it is the first run.
else
{
sessionend = remember_sessionend;
// Process the sessions that start today.
// For example, 13:00-18:00.
if (IDStartTime[intraday_i] < IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and the session ends on 24:00, and day's start is on Friday and day's end is on Saturday, then do not trigger 'continue' in case, for example, of 15:00 Saturday end and 16:00-00:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday)/* && (IDEndTime[intraday_i] == 24 * 60)*/ && (TimeDayOfWeek(Time[remember_sessionend] + TimeShiftMinutes * 60) == 6) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 5))
{
}
// Intraday session starts after the today's actual session ended (for Friday/Saturday cases).
else if (TimeHour(Time[remember_sessionend] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[remember_sessionend] + TimeShiftMinutes * 60) < IDStartTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session starts on 00:00, and the session end points to Sunday or end points to Monday and start points to Sunday, then do not trigger 'continue' in case, for example, of 18:00 Sunday start and 00:00-16:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (((IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(Time[remember_sessionend] + TimeShiftMinutes * 60) == 0)) || ((TimeDayOfWeek(Time[remember_sessionend] + TimeShiftMinutes * 60) == 1) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 0))))
{
}
// Intraday session ends before the today's actual session starts (for Sunday cases).
else if (TimeHour(Time[remember_sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[remember_sessionstart] + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session ends on 24:00, and the start points to Friday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 5))
{
// We already have sessionend right because it is the same as remember_sessionend (end of Saturday).
}
// If Append_Saturday_Sunday is on and the session starts on 00:00 and the session end points to Sunday (it is current Sunday session , no Monday bars yet):
else if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(Time[sessionend] + TimeShiftMinutes * 60) == 0))
{
// We already have sessionend right because it is the same as remember_sessionend (current bar and it is on Sunday).
}
// Otherwise find the session end.
else while ((sessionend < Bars) && ((TimeHour(Time[sessionend] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionend] + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) || ((TimeDayOfWeek(Time[sessionend] + TimeShiftMinutes * 60) == 6) && (_SaturdaySunday == Append_Saturday_Sunday))))
{
sessionend++;
}
if (sessionend == Bars) sessionend--;
// If Append_Saturday_Sunday is on and the session starts on 00:00 and the session start is now going through Sunday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 0))
{
// We already have sessionstart right because it is the same as remember_sessionstart (start of Sunday).
sessionstart = remember_sessionstart;
}
else
{
sessionstart = sessionend;
while ((sessionstart < Bars) && (((TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60) >= IDStartTime[intraday_i])
// Same day - for cases when the day does not contain intraday session start time. Alternatively, continue looking for the sessionstart bar if we moved from Saturday to Friday with Append_Saturday_Sunday and for XX:XX-00:00 session.
&& ((TimeDayOfYear(Time[sessionstart] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[sessionend] + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[sessionend] + TimeShiftMinutes * 60) == 6))))
// If Append_Saturday_Sunday is on and the session ends on 24:00, and the session start is now going through Saturday, then go on in case, for example, of 15:00 Saturday end and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 6))
))
{
sessionstart++;
}
sessionstart--;
}
}
// For example, 22:00-6:00.
else if (IDStartTime[intraday_i] > IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and the start points to Friday, then do not trigger 'continue' in case, for example, of 15:00 Saturday end and 22:00-06:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (((TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 5) && (TimeDayOfWeek(Time[remember_sessionend] + TimeShiftMinutes * 60) == 6)) || ((TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 0) && (TimeDayOfWeek(Time[remember_sessionend] + TimeShiftMinutes * 60) == 1))))
{
}
// Today's intraday session starts after the end of the actual session (for Friday/Saturday cases).
else if (TimeHour(Time[remember_sessionend] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[remember_sessionend] + TimeShiftMinutes * 60) < IDStartTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session start is on Sunday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 0))
{
// We already have sessionstart right because it is the same as remember_sessionstart (start of Sunday).
sessionstart = remember_sessionstart;
}
// If Ignore_Saturday_Sunday is on and it is Monday: (and it is not a special additional intra-Monday session.)
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
// Monday starts on 7:00 and we have 22:00-6:00. Skip it.
if (TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) continue;
}
else
{
// Find starting bar.
sessionstart = remember_sessionend; // Start from the end.
while ((sessionstart < Bars) && (((TimeHour(Time[sessionstart] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionstart] + TimeShiftMinutes * 60) >= IDStartTime[intraday_i])
// Same day - for cases when the day does not contain intraday session start time.
&& ((TimeDayOfYear(Time[sessionstart] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[remember_sessionend] + TimeShiftMinutes * 60)) || (TimeDayOfYear(Time[sessionstart] + TimeShiftMinutes * 60) == TimeDayOfYear(Time[remember_sessionstart] + TimeShiftMinutes * 60)) ))
// If Append_Saturday_Sunday is on and the session start is now going through Saturday, then go on in case, for example, of 15:00 Saturday end and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 6))
))
{
sessionstart++;
}
sessionstart--;
}
int sessionlength; // In seconds.
// If Append_Saturday_Sunday is on and the end points to Saturday, don't go through this calculation because sessionend = remember_sessionend.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionend] + TimeShiftMinutes * 60) == 6))
{
// We already have sessionend right because it is the same as remember_sessionend (end of Saturday).
}
// If Append_Saturday_Sunday is on and the start points to Sunday, use a simple method to find the end.
else if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 0))
{
// While we are on Monday and sessionend is pointing on bar after IDEndTime.
while ((sessionend < Bars) && (TimeDayOfWeek(Time[sessionend] + TimeShiftMinutes * 60) == 1) && (TimeHour(Time[sessionend] + TimeShiftMinutes * 60) * 60 + TimeMinute(Time[sessionend] + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]))
{
sessionend++;
}
}
// If Ignore_Saturday_Sunday is on and the session starts on Friday:
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(Time[remember_sessionstart] + TimeShiftMinutes * 60) == 5))
{
// Then it also ends on Friday.
sessionend = remember_sessionend;
}
else
{
sessionend = sessionstart;
sessionlength = (24 * 60 - IDStartTime[intraday_i] + IDEndTime[intraday_i]) * 60;
// If ignoring Sundays and session start is on Monday, cut out Sunday part of the intraday session. And it is not a special additional intra-Monday session.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(Time[sessionstart] + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag)) sessionlength -= (24 * 60 - IDStartTime[intraday_i]) * 60;
while ((sessionend >= 0) && (Time[sessionend] - Time[sessionstart] < sessionlength))
{
sessionend--;
}
sessionend++;
}
}
// If start time equals end time, we can skip the session.
else continue;
if (sessionend == sessionstart) continue; // No need to process such an intraday session.
if (!ProcessSession(sessionstart, sessionend, i)) return false;
}
}
Suffix = "_ID";
return true;
}
//+------------------------------------------------------------------+
//| Returns absolute day number. |
//+------------------------------------------------------------------+
int TimeAbsoluteDay(const datetime time)
{
return ((int)time / 86400);
}
//+------------------------------------------------------------------+
//| Checks whether Median/VA/Single Print rays are required and |
//| whether they should be cut. |
//+------------------------------------------------------------------+
void CheckRays()
{
for (int i = 0; i < SessionsNumber; i++)
{
string last_name = " " + TimeToString(RememberSessionStart[i]);
string suffix = RememberSessionSuffix[i];
string rec_name = ObjPrefix;
if (_Session == Rectangle) rec_name = ObjPrefix + MPR_Array[i].name + "_";
// Process Single Print Rays to hide those that shouldn't be visible.
if ((HideRaysFromInvisibleSessions) && (SinglePrintRays))
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
if (StringSubstr(obj_name, 0, StringLen(rec_name + "MPSPR" + suffix + last_name)) != rec_name + "MPSPR" + suffix + last_name) continue; // Not a Single Print ray.
if (Time[WindowFirstVisibleBar()] >= RememberSessionStart[i]) // Too old.
{
ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, clrNONE); // Hide.
}
else ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, SinglePrintColor); // Unhide.
}
}
// If the median rays have to be created for the given trading session:
if (((ShowMedianRays == AllPrevious) && (SessionsNumber - i >= 2)) ||
(((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 2)) ||
(((ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 1)) ||
(ShowMedianRays == All))
{
double median_price = ObjectGetDouble(0, rec_name + "Median" + suffix + last_name, OBJPROP_PRICE, 0);
datetime median_time = (datetime)ObjectGetInteger(0, rec_name + "Median" + suffix + last_name, OBJPROP_TIME, 1);
// Create the rays only if the median doesn't end behind the screen's edge.
if (!((HideRaysFromInvisibleSessions) && (Time[WindowFirstVisibleBar()] >= median_time)))
{
// Delete old Median Ray.
ObjectDelete(0, rec_name + "Median Ray" + suffix + last_name);
// Draw a new Median Ray.
ObjectCreate(0, rec_name + "Median Ray" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], median_price, median_time, median_price);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_COLOR, MedianColor);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_STYLE, MedianRayStyle);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_WIDTH, MedianRayWidth);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY, false);
}
else
{
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY, true);
}
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_HIDDEN, true);
ObjectSetString(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_TOOLTIP, "Median Ray");
}
else ObjectDelete(0, rec_name + "Median Ray" + suffix + last_name); // Delete the ray that starts from behind the screen.
}
// We should also delete outdated rays that no longer should be there.
if ((((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i > 2)) ||
((ShowMedianRays == Current) && (SessionsNumber - i > 1)))
{
ObjectDelete(0, rec_name + "Median Ray" + suffix + last_name);
}
// If the value area rays have to be created for the given trading session:
if (((ShowValueAreaRays == AllPrevious) && (SessionsNumber - i >= 2)) ||
(((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 2)) ||
(((ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 1)) ||
(ShowValueAreaRays == All))
{
double va_high_price = ObjectGetDouble(0, rec_name + "VA_Top" + suffix + last_name, OBJPROP_PRICE, 0);
double va_low_price = ObjectGetDouble(0, rec_name + "VA_Bottom" + suffix + last_name, OBJPROP_PRICE, 0);
datetime va_time = (datetime)ObjectGetInteger(0, rec_name + "VA_Top" + suffix + last_name, OBJPROP_TIME, 1);
// Create the rays only if the value area doesn't end behind the screen's edge.
if (!((HideRaysFromInvisibleSessions) && (Time[WindowFirstVisibleBar()] >= va_time)))
{
// Delete old Value Area Rays.
ObjectDelete(0, rec_name + "Value Area HighRay" + suffix + last_name);
ObjectDelete(0, rec_name + "Value Area LowRay" + suffix + last_name);
// Draw a new Value Area High Ray.
ObjectCreate(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], va_high_price, va_time, va_high_price);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_STYLE, ValueAreaRayHighLowStyle);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_WIDTH, ValueAreaRayHighLowWidth);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY, false);
}
else
{
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY, true);
}
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_HIDDEN, true);
ObjectSetString(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_TOOLTIP, "Value Area High Ray");
// Draw a new Value Area Low Ray.
ObjectCreate(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], va_low_price, va_time, va_low_price);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_STYLE, ValueAreaRayHighLowStyle);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_WIDTH, ValueAreaRayHighLowWidth);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY, false);
}
else
{
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY, true);
}
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_HIDDEN, true);
ObjectSetString(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_TOOLTIP, "Value Area Low Ray");
}
else
{
ObjectDelete(0, rec_name + "Value Area HighRay" + suffix + last_name);
ObjectDelete(0, rec_name + "Value Area LowRay" + suffix + last_name);
}
}
// We should also delete outdated rays that no longer should be there.
if ((((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i > 2)) ||
((ShowValueAreaRays == Current) && (SessionsNumber - i > 1)))
{
ObjectDelete(0, rec_name + "Value Area HighRay" + suffix + last_name);
ObjectDelete(0, rec_name + "Value Area LowRay" + suffix + last_name);
}
if (RaysUntilIntersection != Stop_No_Rays)
{
if ((((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 2)) || (((ShowMedianRays == AllPrevious) || (ShowMedianRays == All)) && (SessionsNumber - i >= 2)))
{
if ((RaysUntilIntersection == Stop_All_Rays)
|| ((RaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((RaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
CheckRayIntersections(rec_name + "Median Ray" + suffix + last_name, i + 1);
}
if ((((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 2)) || (((ShowValueAreaRays == AllPrevious) || (ShowValueAreaRays == All)) && (SessionsNumber - i >= 2)))
{
if ((RaysUntilIntersection == Stop_All_Rays)
|| ((RaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((RaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
{
CheckRayIntersections(rec_name + "Value Area HighRay" + suffix + last_name, i + 1);
CheckRayIntersections(rec_name + "Value Area LowRay" + suffix + last_name, i + 1);
}
}
}
if ((SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays) && (SessionsNumber - i >= 2))
{
if ((SPRaysUntilIntersection == Stop_All_Rays)
|| ((SPRaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((SPRaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
if (StringSubstr(obj_name, 0, StringLen(rec_name + "MPSPR" + suffix + last_name)) != rec_name + "MPSPR" + suffix + last_name) continue; // Not this session's Single Print ray.
CheckRayIntersections(obj_name, i + 1);
}
}
}
// Historical arrow placement.
// Here we are inside a cycle through all sessions.
// For each session, we will pass its rays and add arrows if they are visible.
// Before that, it's best to check if any arrows have already been created for this session. If they have, skip.
if (AlertArrows)
{
// We will start checking from the next bar after session's end because previous crosses could be at different places in an uncompleted session.
int bar_start = iBarShift(Symbol(), Period(), RememberSessionEnd[i]) - 1; // Same for all rays of this session.
// Single Print rays.
if (AlertForSinglePrint)
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
string obj_prefix = rec_name + "MPSPR" + suffix + last_name;
if (StringSubstr(obj_name, 0, StringLen(obj_prefix)) != obj_prefix) continue; // Not a Single Print ray (or not this seesion's).
if ((color)ObjectGetInteger(ChartID(), obj_name, OBJPROP_COLOR) != clrNONE) // Visible.
{
// Proceed only if no arrow has been found for this ray.
if (!FindAtLeastOneArrowForRay(obj_prefix))
{
for (int k = bar_start; k >= 0; k--) // Check all bars for the given single print ray.
{
CheckAndDrawArrow(k, ObjectGetDouble(ChartID(), obj_name, OBJPROP_PRICE, 0), obj_prefix);
}
}
}
else // Invisible.
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
}
// Value Area rays.
if (AlertForValueArea)
{
string obj_prefix = rec_name + "Value Area HighRay" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
obj_prefix = rec_name + "Value Area LowRay" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
// Median rays.
if (AlertForMedian)
{
string obj_prefix = rec_name + "Median Ray" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
}
}
ChartRedraw();
}
// Delete arrows by prefix (complete or incomplete).
void DeleteArrowsByPrefix(const string prefix)
{
// Delete all arrows.
ObjectsDeleteAll(ChartID(), "ArrCC" + prefix, 0, OBJ_ARROW);
ObjectsDeleteAll(ChartID(), "ArrGC" + prefix, 0, OBJ_ARROW);
ObjectsDeleteAll(ChartID(), "ArrPB" + prefix, 0, OBJ_ARROW);
}
// Returns true if at least one arrow is found, false otherwise.
bool FindAtLeastOneArrowForRay(const string ray_name)
{
int objects_total = ObjectsTotal(ChartID(), 0, OBJ_ARROW);
for (int i = 0; i < objects_total; i++)
{
string obj_name = ObjectName(ChartID(), i, 0, OBJ_ARROW);
if (StringFind(obj_name, ray_name) != -1) return true; // Found an rrrow for a given ray.
}
return false; // No arrows found for the ray.
}
// Checks and draws historical arrow alerts for Median or Value Area ray.
void CheckHistoricalArrowsForNonMPSPRRays(const int bar_start, const string ray_name)
{
int end_bar = 0;
if (ObjectGetInteger(ChartID(), ray_name, OBJPROP_RAY) != true) // Ray was stopped, need to find its end.
{
datetime end_time = (datetime)ObjectGetInteger(ChartID(), ray_name, OBJPROP_TIME, 1);
end_bar = iBarShift(Symbol(), Period(), end_time) + 1; // End before the new session starts.
}
for (int k = bar_start; k >= end_bar; k--) // Check all bars for the given ray.
{
CheckAndDrawArrow(k, ObjectGetDouble(ChartID(), ray_name, OBJPROP_PRICE, 0), ray_name);
}
}
// Checks if any of the arrow alerts triggered on a given candle (n) with a given ray's level and places a chart object using name.
void CheckAndDrawArrow(const int n, const double level, const string ray_name)
{
// Price breaks (using pre-previous High and previous Close), candle closes, and gap crosses using Close[1].
if (AlertOnPriceBreak) // Price break alerts.
{
if (((High[n] >= level) && (Close[n] < level) && (Close[n + 1] < level)) || ((Low[n] <= level) && (Close[n] > level) && (Close[n + 1] > level)))
{
// Draw arrow object:
string obj_name = "ArrPB" + ray_name;
CreateArrowObject(obj_name, Time[n], Close[n], AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((Close[n] >= level) && (Close[n + 1] < level)) || ((Close[n] <= level) && (Close[n + 1] > level)))
{
// Draw arrow object:
string obj_name = "ArrCC" + ray_name;
CreateArrowObject(obj_name, Time[n], Close[n], AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((Low[n] > level) && (High[n + 1] < level)) || ((Low[n + 1] > level) && (High[n] < level)))
{
string obj_name = "ArrGC" + ray_name;
CreateArrowObject(obj_name, Time[n], level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
}
// Creates an arrow object and sets its properties.
void CreateArrowObject(const string name, const datetime time, const double price, const int code, const color colour, const int width, const string tooltip)
{
string obj_name = name + IntegerToString(ArrowsCounter);
ArrowsCounter++;
ObjectCreate(ChartID(), obj_name, OBJ_ARROW, 0, time, price);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_ARROWCODE, code);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, colour);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_ANCHOR, ANCHOR_CENTER);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_WIDTH, width);
ObjectSetString(ChartID(), obj_name, OBJPROP_TOOLTIP, tooltip);
}
//+------------------------------------------------------------------+
//| Checks price intersection and cuts a ray for a given object. |
//+------------------------------------------------------------------+
void CheckRayIntersections(const string object, const int start_j)
{
if (ObjectFind(0, object) < 0) return;
double price = ObjectGetDouble(0, object, OBJPROP_PRICE, 0);
for (int j = start_j; j < SessionsNumber; j++) // Find the nearest intersecting session.
{
if ((price <= RememberSessionMax[j]) && (price >= RememberSessionMin[j]))
{
ObjectSetInteger(0, object, OBJPROP_RAY, false);
ObjectSetInteger(0, object, OBJPROP_TIME, 1, RememberSessionStart[j]);
break;
}
}
}
//+------------------------------------------------------------------+
//| Print out VAH, VAL, or POC value on the chart. |
//+------------------------------------------------------------------+
void ValuePrintOut(const string obj_name, const datetime time, const double price, const string tooltip, const ENUM_ANCHOR_POINT anchor = ANCHOR_RIGHT, color value_color = 0, const int value = 0)
{
// Find object if it exists.
if (ObjectFind(0, obj_name) >= 0)
{
// Move it.
ObjectMove(0, obj_name, 0, time, price);
}
else
{
if (value_color == 0) value_color = KeyValuesColor;
// Draw a new one.
ObjectCreate(0, obj_name, OBJ_TEXT, 0, time, price);
ObjectSetInteger(0, obj_name, OBJPROP_COLOR, value_color);
ObjectSetInteger(0, obj_name, OBJPROP_FONTSIZE, KeyValuesSize);
ObjectSetInteger(0, obj_name, OBJPROP_BACK, false);
ObjectSetInteger(0, obj_name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, obj_name, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, obj_name, OBJPROP_ANCHOR, anchor);
}
// Should be updated anyway.
string text = DoubleToString(price, _Digits);
if (value > 0) text = IntegerToString(value);
ObjectSetString(0, obj_name, OBJPROP_TEXT, text);
ObjectSetString(0, obj_name, OBJPROP_TOOLTIP, tooltip);
}
//+------------------------------------------------------------------+
//| Calculates dot color based on bar direction and color scheme. |
//| Used only when ColorBullBear == true. |
//+------------------------------------------------------------------+
int CalculateProperColor()
{
int colour = 0;
switch (CurrentColorScheme)
{
case Blue_to_Red:
if (CurrentBarDirection == Bullish)
{
colour = clrBlue;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrDarkRed;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrPink;
}
break;
case Red_to_Green:
if (CurrentBarDirection == Bullish)
{
colour = clrDarkRed;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrDarkGreen;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrBrown;
}
break;
case Green_to_Blue:
if (CurrentBarDirection == Bullish)
{
colour = clrDarkGreen;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrBlue;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrDarkGray;
}
break;
case Yellow_to_Cyan:
if (CurrentBarDirection == Bullish)
{
colour = clrYellow;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrCyan;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Magenta_to_Yellow:
if (CurrentBarDirection == Bullish)
{
colour = clrMagenta;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrYellow;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Cyan_to_Magenta:
if (CurrentBarDirection == Bullish)
{
colour = clrCyan;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrMagenta;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Single_Color:
if (CurrentBarDirection == Bullish)
{
colour = SingleColor;
}
else if (CurrentBarDirection == Bearish)
{
colour = 0x00FFFFFF - SingleColor;
}
else if (CurrentBarDirection == Neutral)
{
colour = (int)MathMax(SingleColor, 0x00FFFFFF - SingleColor) / 2;
}
break;
default:
if (CurrentBarDirection == Bullish)
{
colour = SingleColor;
}
else if (CurrentBarDirection == Bearish)
{
colour = 0x00FFFFFF - SingleColor;
}
else if (CurrentBarDirection == Neutral)
{
colour = (int)MathMax(SingleColor, 0x00FFFFFF - SingleColor) / 2;
}
break;
}
return colour;
}
void OnTimer()
{
if (IndicatorHidden) return;
if (GetTickCount() - LastRecalculationTime < 500) return; // Do not recalculate on timer if less than 500 ms passed.
if (HideRaysFromInvisibleSessions) CheckRays(); // Should be checked regularly if the input parameter requires ray hiding/unhiding.
if (_Session == Rectangle)
{
if (onetick == 0) InitializeOnetick(); // Can fail to initialize via OnTick() when the market is closed and a Rectangle session is used.
CheckRectangles();
return; // No need to call RedrawLastSession() even if RightToLeft is on because in that case all Rectangles are all right-to-left and are redrawn as needed.
}
if (((!RightToLeft) && (!SeamlessScrollingMode)) || (!FirstRunDone)) return; // Need to finish normal drawing before reacting to timer.
// This what goes below works for RightToLeft mode and for seamless scrolling mode, but only after the first run has been finished.
static datetime prev_converted_time = 0;
datetime converted_time = 0;
int dummy_subwindow;
double dummy_price;
ChartXYToTimePrice(0, (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS), 0, dummy_subwindow, converted_time, dummy_price);
if (converted_time == prev_converted_time) return; // Do not call RedrawLastSession() if the screen hasn't been scrolled.
prev_converted_time = converted_time;
if (SeamlessScrollingMode)
{
ObjectCleanup(); // Delete everything to make sure there are no leftover sessions behind the screen.
if (_Session == Intraday) FirstRunDone = false; // Turn off because FirstRunDone should be false for Intraday sessions to draw properly in the past.
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL))
{
for (int i = 0; i < Bars; i++) // Clean indicator buffers.
{
DevelopingPOC[i] = EMPTY_VALUE;
DevelopingVAH[i] = EMPTY_VALUE;
DevelopingVAL[i] = EMPTY_VALUE;
}
}
}
// Check right-most time - did it change?
RedrawLastSession();
if ((SeamlessScrollingMode) && (_Session == Intraday)) FirstRunDone = true; // Turn back on after processing Intraday sessions.
LastRecalculationTime = GetTickCount(); // Remember last calculation time.
}
// Find rectangles, create objects, process rectangle sessions, delete unneeded sessions (where rectangle no longer exists).
// Make sure rectangles are added to the array in a sorted manner from oldest T1 to newest T1.
void CheckRectangles()
{
// Check if any existing MPR objects need to be deleted or moved:
for (int i = mpr_total - 1; i >= 0 ; i--)
{
if (ObjectFind(0, MPR_Array[i].name) < 0)
{
ObjectCleanup(MPR_Array[i].name + "_");
// Buffer cleanup for the Developing POC.
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL))
{
int sessionstart = iBarShift(Symbol(), Period(), MPR_Array[i].RectangleTimeMin, true);
int sessionend = iBarShift(Symbol(), Period(), MPR_Array[i].RectangleTimeMax, true);
if (sessionend < 0) sessionend = 0; // If the rectangle's rightmost side is in the future, reset it to the current bar.
// Re-initialize all bars using old rectangle borders:
for (int j = sessionstart; j >= sessionend; j--)
{
DevelopingPOC[j] = EMPTY_VALUE;
DevelopingVAH[j] = EMPTY_VALUE;
DevelopingVAL[j] = EMPTY_VALUE;
}
}
delete MPR_Array[i];
// Move all array elements with greater index down:
for (int j = i; j < mpr_total - 1; j++)
MPR_Array[j] = MPR_Array[j + 1];
mpr_total--;
ArrayResize(MPR_Array, mpr_total);
}
}
// Find all objects of rectangle type with the name starting with MPR.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_RECTANGLE);
for (int i = 0; i < obj_total; i++)
{
string name = ObjectName(ChartID(), i, -1, OBJ_RECTANGLE);
if (StringSubstr(name, 0, 3) != "MPR") continue;
if (StringFind(name, "_") != -1) continue; // Skip chart objects created based on a rectangle session.
// Find the rectangle among the array's elements by its name.
bool name_found = false;
for (int j = 0; j < mpr_total; j++)
{
if (MPR_Array[j].name == name)
{
name_found = true;
// Check if it should be moved inside the array to keep sorting intact.
datetime t1 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 0);
datetime t2 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 1);
MPR_Array[j].t1 = t1;
MPR_Array[j].t2 = t2;
if (mpr_total == 1) continue; // No need to sort the array if its size is 1.
t1 = MathMin(t1, t2); // Leftmost side.
if (t1 == MPR_Array[j].RectangleTimeMin) continue; // No movement needed.
int k = 0;
if (k == j) k++; // Skip self.
while ((k < mpr_total) && (MPR_Array[k].RectangleTimeMin < t1))
{
k++;
if (k == j) k++; // Skip self.
}
// Now k points either to the first newer rectangle or to beyond the end of the array.
if (j == k - 1) continue; // Already there.
CRectangleMP* tmp = MPR_Array[j]; // Moved rectangle -> to temp.
if (t1 > MPR_Array[j].RectangleTimeMin)
{
// Run a cycle to move others elements lower.
for (int n = j; n < k - 1; n++)
MPR_Array[n] = MPR_Array[n + 1];
MPR_Array[k - 1] = tmp; // Assign the moved rectangle to the final element of the array.
}
else
{
// Run a cycle to move others elements higher.
for (int n = j; n > k; n--)
MPR_Array[n] = MPR_Array[n - 1];
MPR_Array[k] = tmp; // Assign the moved rectangle to the final element of the array.
}
break;
}
}
// New rectangle:
if (!name_found)
{
// Check if it should be moved inside the array to keep sorting intact.
datetime t1 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 0);
datetime t2 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 1);
datetime t = MathMin(t1, t2); // Leftmost side.
int k = 0;
while ((k < mpr_total) && (MPR_Array[k].RectangleTimeMin < t)) k++;
// Now k points either to the first newer rectangle or to beyond the end of the array.
mpr_total++;
ArrayResize(MPR_Array, mpr_total);
// Run a cycle to move others elements higher.
for (int n = mpr_total - 1; n > k; n--)
MPR_Array[n] = MPR_Array[n - 1];
MPR_Array[k] = new CRectangleMP(name); // Assign the new rectangle to the kth element of the array.
MPR_Array[k].RectangleTimeMin = t; // Fill in the leftmost time to enable further sorting.
MPR_Array[k].t1 = t1;
MPR_Array[k].t2 = t2;
}
}
if (SessionsNumber != mpr_total)
{
SessionsNumber = mpr_total;
ArrayResize(RememberSessionMax, SessionsNumber);
ArrayResize(RememberSessionMin, SessionsNumber);
ArrayResize(RememberSessionStart, SessionsNumber);
ArrayResize(RememberSessionSuffix, SessionsNumber);
ArrayResize(RememberSessionEnd, SessionsNumber); // Used only for Arrows.
}
// Process each rectangle.
for (int i = 0; i < mpr_total; i++)
MPR_Array[i].Process(i);
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
LastRecalculationTime = GetTickCount(); // Remember last calculation time.
}
CRectangleMP::CRectangleMP(string given_name = "MPR")
{
name = given_name;
RectanglePriceMax = -DBL_MAX;
RectanglePriceMin = DBL_MAX;
prev_RectanglePriceMax = -DBL_MAX;
prev_RectanglePriceMin = DBL_MAX;
RectangleTimeMax = 0;
RectangleTimeMin = D'31.12.3000';
prev_Time0 = 0;
prev_High = -DBL_MAX;
prev_Low = DBL_MAX;
Number = -1;
}
// i - order number of the rectangle.
void CRectangleMP::Process(const int i)
{
double p1 = ObjectGetDouble(0, name, OBJPROP_PRICE, 0);
double p2 = ObjectGetDouble(0, name, OBJPROP_PRICE, 1);
if (Number == -1) Number = i;
bool rectangle_changed = false;
bool rectangle_time_changed = false;
bool rectangle_price_changed = false;
// If any of the rectangle parameters changed.
if ((RectangleTimeMax != MathMax(t1, t2)) || (RectangleTimeMin != MathMin(t1, t2)))
{
rectangle_changed = true;
rectangle_time_changed = true;
}
if ((RectanglePriceMax != MathMax(p1, p2)) || (RectanglePriceMin != MathMin(p1, p2)))
{
rectangle_changed = true;
rectangle_price_changed = true;
}
// Buffer cleanup for the Developing POC. Should be run only for a changed rectangle, which isn't brand new.
if (((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) && (rectangle_changed) && (RectangleTimeMax != D'01.01.1970'))
{
int sessionstart = iBarShift(Symbol(), Period(), RectangleTimeMin, true);
int sessionend = iBarShift(Symbol(), Period(), RectangleTimeMax, true);
if (sessionend < 0) sessionend = 0; // If the rectangle's rightmost side is in the future, reset it to the current bar.
// Re-initialize all bars using old rectangle borders:
for (int j = sessionstart; j >= sessionend; j--)
{
DevelopingPOC[j] = EMPTY_VALUE;
DevelopingVAH[j] = EMPTY_VALUE;
DevelopingVAL[j] = EMPTY_VALUE;
}
prev_Time0 = 0;
}
RectangleTimeMax = MathMax(t1, t2);
RectangleTimeMin = MathMin(t1, t2);
RectanglePriceMax = MathMax(p1, p2);
RectanglePriceMin = MathMin(p1, p2);
bool new_bars_are_not_within_rectangle = true;
bool current_bar_changed_within_boundaries = false;
if (Time[0] != prev_Time0)
{
new_bars_are_not_within_rectangle = false;
// Check if any of the new bars fall into rectangle's boundaries:
if (((prev_Time0 < RectangleTimeMin) && (Time[0] < RectangleTimeMin)) || ((prev_Time0 > RectangleTimeMax) && (Time[0] > RectangleTimeMax))) new_bars_are_not_within_rectangle = true;
// Now check if the price of any of the new bars is within the rectangle's boundaries:
if (!new_bars_are_not_within_rectangle)
{
int max_index = iHighest(Symbol(), Period(), MODE_HIGH, iBarShift(Symbol(), Period(), prev_Time0, true), 0);
int min_index = iLowest(Symbol(), Period(), MODE_LOW, iBarShift(Symbol(), Period(), prev_Time0, true), 0);
if ((High[max_index] < RectanglePriceMin) || (Low[min_index] > RectanglePriceMax)) new_bars_are_not_within_rectangle = true;
}
prev_Time0 = Time[0];
}
else // No new bars - check if the current bar's high or low changed within the rectangle's boundaries:
{
if ((Time[0] >= RectangleTimeMin) && (Time[0] <= RectangleTimeMax)) // Bar within time boundaries.
{
if (prev_High != High[0])
{
if ((High[0] <= RectanglePriceMax) && (High[0] >= RectanglePriceMin)) current_bar_changed_within_boundaries = true;
}
if (prev_Low != Low[0])
{
if ((Low[0] <= RectanglePriceMax) && (Low[0] >= RectanglePriceMin)) current_bar_changed_within_boundaries = true;
}
}
}
prev_High = High[0];
prev_Low = Low[0];
// Calculate rectangle session's actual time and price boundaries.
int sessionstart = iBarShift(Symbol(), Period(), (int)MathMin(t1, t2), true);
int sessionend = iBarShift(Symbol(), Period(), (int)MathMax(t1, t2), true);
if (sessionend < 0) sessionend = 0; // If the rectangles rightmost side is in the future, reset it to the current bar.
bool need_to_clean_up_dots = false;
bool rectangle_changed_and_recalc_is_due = false;
// If rectangle changed:
if (rectangle_changed)
{
if (rectangle_price_changed)
{
// Max/min bars of the price range within rectangle's boundaries before and after change:
int max_index = iHighest(Symbol(), Period(), MODE_HIGH, sessionstart - sessionend, sessionend);
int min_index = iLowest(Symbol(), Period(), MODE_LOW, sessionstart - sessionend, sessionend);
if ((max_index != -1) && (min_index != -1))
{
if ((RectanglePriceMax > High[max_index]) && (RectanglePriceMin < Low[min_index]) && (prev_RectanglePriceMax > High[max_index]) && (prev_RectanglePriceMin < Low[min_index])) rectangle_changed_and_recalc_is_due = false;
else
{
need_to_clean_up_dots = true;
rectangle_changed_and_recalc_is_due = true;
}
}
}
if (rectangle_time_changed)
{
need_to_clean_up_dots = true;
if (sessionstart >= 0) rectangle_changed_and_recalc_is_due = true;
}
}
prev_RectanglePriceMax = RectanglePriceMax;
prev_RectanglePriceMin = RectanglePriceMin;
// Need to continue drawing profile in the following cases only:
// 1. New bar came in and it is within the rectangle's borders.
// 2. Current bar changed its High or Low and it is now within the borders.
// 3. Rectangle changed its borders.
// 4. Order of rectangles changed - need recalculation for stopping the rays (only when it is really needed).
// Need to delete previous dots before going to drawing in the following cases:
// 1. Rectangle changed its borders.
// 2. When Max_number_of_bars_in_a_session changes.
// Number of bars in the rectangle session changed, need to update colors, so a cleanup is due.
if (sessionstart - sessionend + 1 != Max_number_of_bars_in_a_session)
{
Max_number_of_bars_in_a_session = sessionstart - sessionend + 1;
if (!new_bars_are_not_within_rectangle) need_to_clean_up_dots = true;
}
if (need_to_clean_up_dots) ObjectCleanup(name + "_");
if (sessionstart < 0) return; // Rectangle is drawn in the future.
RememberSessionStart[i] = RectangleTimeMin;
// Used only for Arrows:
if (Time[0] < RectangleTimeMax) RememberSessionEnd[i] = Time[0];
else RememberSessionEnd[i] = RectangleTimeMax;
if ((!new_bars_are_not_within_rectangle) || (current_bar_changed_within_boundaries) || (rectangle_changed_and_recalc_is_due) || ((Number != i) && ((RaysUntilIntersection != Stop_No_Rays) && ((ShowMedianRays != None) || (ShowValueAreaRays != None))))) ProcessSession(sessionstart, sessionend, i, &this);
Number = i;
}
void CRectangleMP::ResetPrevTime0()
{
prev_Time0 = 0;
}
void PutSinglePrintMark(const double price, const int sessionstart, const string rectangle_prefix)
{
int t1 = sessionstart + 1, t2 = sessionstart;
bool fill = true;
if (ShowSinglePrint == Rightside)
{
t1 = sessionstart;
t2 = sessionstart - 1;
fill = false;
}
string LastNameStart = " " + TimeToString(Time[t1]) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
// If already there - ignore.
if (ObjectFind(0, rectangle_prefix + "MPSP" + Suffix + LastName) >= 0) return;
ObjectCreate(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJ_RECTANGLE, 0, Time[t1], price, Time[t2], price - onetick);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_COLOR, SinglePrintColor);
// Fills rectangle.
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_BACK, fill);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetString(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_TOOLTIP, "Single Print Mark");
}
void RemoveSinglePrintMark(const double price, const int sessionstart, const string rectangle_prefix)
{
int t = sessionstart + 1;
if (ShowSinglePrint == Rightside) t = sessionstart;
string LastNameStart = " " + TimeToString(Time[t]) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
ObjectDelete(rectangle_prefix + "MPSP" + Suffix + LastName);
}
void PutSinglePrintRay(const double price, const int sessionstart, const string rectangle_prefix, const color spr_color)
{
datetime t1 = Time[sessionstart], t2;
if (sessionstart - 1 >= 0) t2 = Time[sessionstart - 1];
else t2 = Time[sessionstart] + 1;
if (ShowSinglePrint == Rightside)
{
t1 = Time[sessionstart];
t2 = Time[sessionstart + 1];
}
string LastNameStart = " " + TimeToString(t1) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
// If already there - ignore.
if (ObjectFind(0, rectangle_prefix + "MPSPR" + Suffix + LastName) >= 0) return;
ObjectCreate(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJ_TREND, 0, t1, price, t2, price);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_COLOR, spr_color);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_STYLE, SinglePrintRayStyle);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_WIDTH, SinglePrintRayWidth);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_RAY, true);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetString(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_TOOLTIP, "Single Print Ray");
}
void RemoveSinglePrintRay(const double price, const int sessionstart, const string rectangle_prefix)
{
datetime t = Time[sessionstart];
string LastNameStart = " " + TimeToString(t) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
ObjectDelete(0, rectangle_prefix + "MPSPR" + Suffix + LastName);
}
// Called only when RightToLeft is on to update the right-most session.
void RedrawLastSession()
{
if (SeamlessScrollingMode)
{
int last_visible_bar = WindowFirstVisibleBar() - WindowBarsPerChart() + 1;
if (last_visible_bar < 0) last_visible_bar = 0;
StartDate = Time[last_visible_bar];
}
else if (StartFromCurrentSession) StartDate = Time[0];
else StartDate = StartFromDate;
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(StartDate);
int sessionstart = FindSessionStart(sessionend);
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return;
}
int SessionToStart = 0;
// In all cases except for the seamless scrolling mode, jump to the latest session.
if (!SeamlessScrollingMode) SessionToStart = _SessionsToCount - 1;
else
{
// Move back to the oldest session to count to start from it.
for (int i = 1; i < _SessionsToCount; i++)
{
sessionend = sessionstart + 1;
if (sessionend >= Bars) return;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionend]) == 0) || (TimeDayOfWeek(Time[sessionend]) == 6))
{
sessionend++;
if (sessionend >= Bars) break;
}
}
sessionstart = FindSessionStart(sessionend);
}
SessionsNumber = 0; // Reset previously remembered sessions as there won't be any need for them.
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (_Session == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i)) return;
}
else
{
if (_Session == Daily) Max_number_of_bars_in_a_session = PeriodSeconds(PERIOD_D1) / PeriodSeconds();
else if (_Session == Weekly) Max_number_of_bars_in_a_session = 604800 / PeriodSeconds();
else if (_Session == Monthly) Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds();
else if (_Session == Quarterly) Max_number_of_bars_in_a_session = 8035200 / PeriodSeconds();
else if (_Session == Semiannual) Max_number_of_bars_in_a_session = 16070400 / PeriodSeconds();
else if (_Session == Annual) Max_number_of_bars_in_a_session = 31622400 / PeriodSeconds();
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if (TimeDayOfWeek(Time[sessionstart]) == 0) Max_number_of_bars_in_a_session += (24 * 3600 - (TimeHour(Time[sessionstart]) * 3600 + TimeMinute(Time[sessionstart]) * 60)) / PeriodSeconds();
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if (TimeDayOfWeek(Time[sessionend]) == 6) Max_number_of_bars_in_a_session += ((TimeHour(Time[sessionend]) * 3600 + TimeMinute(Time[sessionend]) * 60)) / PeriodSeconds() + 1;
}
if (!ProcessSession(sessionstart, sessionend, i)) return;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend - 1;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionstart]) == 0) || (TimeDayOfWeek(Time[sessionstart]) == 6))
{
sessionstart--;
if (sessionstart == 0) break;
}
}
sessionend = FindSessionEndByDate(Time[sessionstart]);
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
}
//+----------------------------------------------------------------------------------+
//| Go through all prices on all N session bars from 1st to kth bar, where k = 1..N. |
//+----------------------------------------------------------------------------------+
void CalculateDevelopingPOCVAHVAL(int sessionstart, int sessionend, CRectangleMP* rectangle = NULL)
{
// Map session boundaries to higher-TF bar indices.
int htf_start = sessionstart;
int htf_end = sessionend;
if (TPOSize > 1)
{
htf_start = iBarShift(Symbol(), _TPOTimeframe, Time[sessionstart]);
htf_end = iBarShift(Symbol(), _TPOTimeframe, Time[sessionend]);
if (htf_start < 0) htf_start = 0;
if (htf_end < 0) htf_end = 0;
}
// Cycle through all possible end bars to calculate the Developing POC.
for (int htf_max = htf_start; htf_max >= htf_end; htf_max--)
{
// Determine which chart bar this HTF bar corresponds to.
int max_bar = (TPOSize > 1) ? iBarShift(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max)) : htf_max;
if (max_bar < 0) max_bar = 0;
if (max_bar >= Bars) continue;
if (DevelopingPOC[max_bar] != EMPTY_VALUE && htf_max > 1) continue; // One of the buffers already filled and it isn't/wasn't the latest bar - skip. Valid only for non-Rectangle sessions.
// Determine the local price minimum and maximum from higher-TF bars.
double LocalMax = iHigh(Symbol(), _TPOTimeframe, iHighest(Symbol(), _TPOTimeframe, MODE_HIGH, htf_start - htf_max + 1, htf_max));
double LocalMin = iLow( Symbol(), _TPOTimeframe, iLowest( Symbol(), _TPOTimeframe, MODE_LOW, htf_start - htf_max + 1, htf_max));
// For rectangles, further restrictions may apply.
if (_Session == Rectangle)
{
if (LocalMax > rectangle.RectanglePriceMax) LocalMax = NormalizeDouble(rectangle.RectanglePriceMax, DigitsM);
if (LocalMin < rectangle.RectanglePriceMin) LocalMin = NormalizeDouble(rectangle.RectanglePriceMin, DigitsM);
}
double DistanceToCenter = DBL_MAX; // Reset the distance because each piece of the Developing POC should be using its own.
int DevMaxRange = 0; // Maximum range for the Developing POC.
double PriceOfMaxRange = EMPTY_VALUE;
// Will be necessary for Developing VAH/VAL calculation.
int TotalTPO = 0; // Total amount of dots (TPO's).
int TPOperPrice[];
// Possible price levels if multiplied to integer.
int max = (int)MathRound((LocalMax - LocalMin) / onetick + 2); // + 2 because further we will be possibly checking array at LocalMax + 1.
ArrayResize(TPOperPrice, max);
ArrayInitialize(TPOperPrice, 0);
// Cycle by price inside the local boundaries:
for (double price = LocalMax; price >= LocalMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int range = 0; // Distance from first bar to the current bar.
// Going through all bars of the session until the current htf_max to see if the price was encountered here.
for (int bar = htf_start; bar >= htf_max; bar--)
{
// Price is encountered in the given bar.
if ((price >= iLow(Symbol(), _TPOTimeframe, bar)) && (price <= iHigh(Symbol(), _TPOTimeframe, bar)))
{
// Update maximum distance from session's start to the found bar for the Developing POC.
// Using the center-most POC if there are more than one.
if ((DevMaxRange < range) || ((DevMaxRange == range) && (MathAbs(price - (LocalMin + (LocalMax - LocalMin) / 2)) < DistanceToCenter))) //SessionMax and SessionMin should be replaced with current N bars' max High and min Low.
{
DevMaxRange = range;
PriceOfMaxRange = price;
DistanceToCenter = MathAbs(price - (LocalMin + (LocalMax - LocalMin) / 2));
}
// Remember the number of encountered bars for this price for Developing VAH/VAL.
int index = (int)MathRound((price - LocalMin) / onetick);
TPOperPrice[index]++;
TotalTPO++;
range++;
}
}
}
if (EnableDevelopingVAHVAL)
{
double TotalTPOdouble = TotalTPO;
// Calculate amount of TPO's in the Value Area.
int ValueControlTPO = (int)MathRound(TotalTPOdouble * ValueAreaPercentage_double);
// Start with the TPO's of the Median.
int index = (int)((PriceOfMaxRange - LocalMin) / onetick);
if (index < 0) continue; // Data wasn't available yet.
int TPOcount = TPOperPrice[index];
// Go through the price levels above and below median adding the biggest to TPO count until the 70% of TPOs are inside the Value Area.
int up_offset = 1;
int down_offset = 1;
while (TPOcount < ValueControlTPO)
{
double abovePrice = PriceOfMaxRange + up_offset * onetick;
double belowPrice = PriceOfMaxRange - down_offset * onetick;
// If belowPrice is out of the session's range then we should add only abovePrice's TPO's, and vice versa.
index = (int)MathRound((abovePrice - LocalMin) / onetick);
int index2 = (int)MathRound((belowPrice - LocalMin) / onetick);
if (((belowPrice < LocalMin) || (TPOperPrice[index] >= TPOperPrice[index2])) && (abovePrice <= LocalMax))
{
TPOcount += TPOperPrice[index];
up_offset++;
}
else if (belowPrice >= LocalMin)
{
TPOcount += TPOperPrice[index2];
down_offset++;
}
// Cannot proceed - too few data points.
else if (TPOcount < ValueControlTPO)
{
break;
}
}
DevelopingVAH[max_bar] = PriceOfMaxRange + up_offset * onetick;
DevelopingVAL[max_bar] = PriceOfMaxRange - down_offset * onetick + onetick;
// Fill intermediate chart bars within this HTF bar with the same values.
if (TPOSize > 1)
{
int next_chart_bar = (htf_max > htf_end) ? iBarShift(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max - 1)) : sessionend;
if (next_chart_bar == sessionend) next_chart_bar--;
for (int fill = max_bar - 1; fill > next_chart_bar; fill--)
{
DevelopingVAH[fill] = DevelopingVAH[max_bar];
DevelopingVAL[fill] = DevelopingVAL[max_bar];
}
}
}
if (EnableDevelopingPOC)
{
DevelopingPOC[max_bar] = PriceOfMaxRange;
if (TPOSize > 1)
{
// Fill intermediate chart bars within this HTF bar with the same Developing POC value.
int next_chart_bar = (htf_max > htf_end) ? iBarShift(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max - 1)) : sessionend;
if (next_chart_bar == sessionend) next_chart_bar--;
for (int fill = max_bar - 1; fill > next_chart_bar; fill--)
{
DevelopingPOC[fill] = PriceOfMaxRange;
}
}
}
}
}
//+------------------------------------------------------------------+
//| For keystroke processing in Rectangle sessions. |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam)
{
if (id == CHARTEVENT_KEYDOWN)
{
if (lparam == 82) // 'r' key pressed.
{
if (_Session != Rectangle) return;
// Find the next untaken MPR rectangle name.
for (int i = 0; i < 1000; i++) // No more than 1000 rectangles!
{
string name = "MPR" + IntegerToString(i);
if (ObjectFind(0, name) >= 0) continue;
// If name not found, create a new rectangle.
// Position it at the chart's center with width and height equal to the half of those of the chart.
int pixel_width = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int pixel_height = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
int half_width = pixel_width / 2;
int half_height = pixel_height / 2;
int x1 = half_width / 2;
int x2 = int(half_width * 1.5);
int y1 = half_height / 2;
int y2 = int(half_height * 1.5);
int dummy_subwindow; // Filler variable.
datetime time1, time2;
double price1, price2;
ChartXYToTimePrice(0, x1, y1, dummy_subwindow, time1, price1); // Convert the first pair of coordinates into a time/price pair.
ChartXYToTimePrice(0, x2, y2, dummy_subwindow, time2, price2); // Convert the second pair of coordinates into a time/price pair.
ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, price1, time2, price2);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, true);
ObjectSetInteger(0, name, OBJPROP_HIDDEN, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, true);
ObjectSetInteger(0, name, OBJPROP_BACK, false);
break;
}
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 49) && (_Session != Daily)) // Ctrl+1
{
Print("Switching session to Daily");
Deinitialize();
_Session = Daily;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 50) && (_Session != Weekly)) // Ctrl+2
{
Print("Switching session to Weekly");
Deinitialize();
_Session = Weekly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 51) && (_Session != Monthly)) // Ctrl+3
{
Print("Switching session to Monthly");
Deinitialize();
_Session = Monthly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 52) && (_Session != Quarterly)) // Ctrl+4
{
Print("Switching session to Quarterly");
Deinitialize();
_Session = Quarterly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 53) && (_Session != Semiannual)) // Ctrl+5
{
Print("Switching session to Semiannual");
Deinitialize();
_Session = Semiannual;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 54) && (_Session != Annual)) // Ctrl+6
{
Print("Switching session to Annual");
Deinitialize();
_Session = Annual;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 55) && (_Session != Intraday)) // Ctrl+7
{
Print("Switching session to Intraday");
Deinitialize();
_Session = Intraday;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 56) && (_Session != Rectangle)) // Ctrl+8
{
Print("Switching session to Rectangle");
Deinitialize();
_Session = Rectangle;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
}
else if (id == CHARTEVENT_OBJECT_CLICK)
{
if ((ShowToggleButton) && (sparam == ToggleButtonName))
{
ToggleIndicatorVisibility();
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_STATE, false); // Reset button state.
}
}
}
//+------------------------------------------------------------------+
//| Checks all alert conditions and issues alerts if needed. |
//+------------------------------------------------------------------+
void CheckAlerts()
{
// No need to check further if no alert method is chosen.
if ((!AlertNative) && (!AlertEmail) && (!AlertPush) && (!AlertArrows)) return;
// Skip alerts if alerts are disabled for Median, for Value Area, and for Single Print rays.
if ((!AlertForMedian) && (!AlertForValueArea) && (!AlertForSinglePrint)) return;
// Skip alerts if no cross type is chosen.
if ((!AlertOnPriceBreak) && (!AlertOnCandleClose) && (!AlertOnGapCross)) return;
// Skip alerts if only closed bar should be checked and it has already been done.
if ((AlertCheckBar == CheckPreviousBar) && (LastAlertTime == Time[0])) return;
// Cycle through rays starts here.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_TREND);
for (int i = 0; i < obj_total; i++)
{
string object_name = ObjectName(ChartID(), i, -1, OBJ_TREND);
// Skip objects not belonging to this instance.
if ((ObjPrefix != "") && (StringSubstr(object_name, 0, StringLen(ObjPrefix)) != ObjPrefix)) continue;
// Skip if it is either a non-ray or if this particular ray shouldn't get alerted.
if (!(((AlertForMedian) && (StringFind(object_name, "Median Ray") > -1)) ||
((AlertForValueArea) && ((StringFind(object_name, "Value Area HighRay") > -1) || (StringFind(object_name, "Value Area LowRay") > -1))) ||
((AlertForSinglePrint)&& (StringFind(object_name, "MPSPR") > -1) && ((color)ObjectGetInteger(ChartID(), object_name, OBJPROP_COLOR) != clrNONE)))) continue;
// If everything is fine, go on:
double level = NormalizeDouble(ObjectGetDouble(ChartID(), object_name, OBJPROP_PRICE1), _Digits);
// Price breaks, candle closes, and gap crosses using Close[0].
if (AlertCheckBar == CheckCurrentBar)
{
if (AlertOnPriceBreak) // Price break alerts.
{
if ((Close_prev != EMPTY_VALUE) && (((Close[0] >= level) && (Close_prev < level)) || ((Close[0] <= level) && (Close_prev > level))))
{
DoAlerts(PriceBreak, object_name);
if (AlertArrows) CreateArrowObject("ArrPB" + object_name, Time[0], Close[0], AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
Close_prev = Close[0];
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((Close[0] >= level) && (Close[1] < level)) || ((Close[0] <= level) && (Close[1] > level)))
{
DoAlerts(CandleCloseCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrCC" + object_name, Time[0], Close[0], AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((Open[0] > level) && (High[1] < level)) || ((Open[0] < level) && (Low[1] > level)))
{
DoAlerts(GapCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrGC" + object_name, Time[0], level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
}
// Price breaks (using pre-previous High and previous Close), candle closes, and gap crosses using Close[1].
else if (AlertCheckBar == CheckPreviousBar)
{
if (AlertOnPriceBreak) // Price break alerts.
{
if (((High[1] >= level) && (Close[1] < level) && (Close[2] < level)) || ((Low[1] <= level) && (Close[1] > level) && (Close[2] > level)))
{
DoAlerts(PriceBreak, object_name);
if (AlertArrows) CreateArrowObject("ArrPB" + object_name, Time[1], Close[1], AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((Close[1] >= level) && (Close[2] < level)) || ((Close[1] <= level) && (Close[2] > level)))
{
DoAlerts(CandleCloseCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrCC" + object_name, Time[1], Close[1], AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((Low[1] > level) && (High[2] < level)) || ((Low[2] > level) && (High[1] < level)))
{
DoAlerts(GapCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrGC" + object_name, Time[1], level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
LastAlertTime = Time[0];
}
}
}
//+------------------------------------------------------------------+
//| Issues alerts based on the alert type and includes object name |
//| in the message. |
//+------------------------------------------------------------------+
void DoAlerts(const alert_types alert_type, const string object_name)
{
// Price Breaks for Current Bar should not be be checked for LastAlertTime.
// Candle Close and Gap Cross for Current Bar need to be checked against LastAlertTime.
// All CheckPreviousBar alerts can use a single LastAlertTime (they either trigger at the start of the bar or not). The actual check is performed in CheckAlerts().
// Using TimeCurrent() for all CheckCurrentBar alerts.
// Using Time[0] for all CheckPreviousBar alerts.
// Check last alert time for Candle Close alert type.
if ((alert_type == CandleCloseCrossover) && (AlertCheckBar == CheckCurrentBar) && (TimeCurrent() <= LastAlertTime_CandleCross)) return;
// Check last alert time for Gap Cross alert type.
if ((alert_type == GapCrossover) && (AlertCheckBar == CheckCurrentBar) && (TimeCurrent() <= LastAlertTime_GapCross)) return;
string Subject = "Market Profile: " + Symbol() + " " + EnumToString(alert_type) + " on " + object_name;
if (AlertNative)
{
string AlertText = Subject;
Alert(AlertText);
}
if (AlertEmail)
{
string EmailSubject = Subject;
string EmailBody = AccountCompany() + " - " + AccountName() + " - " + IntegerToString(AccountNumber()) + "\r\n\r\n" + Subject;
if (!SendMail(EmailSubject, EmailBody)) Print("Error sending email: " + IntegerToString(GetLastError()) + ".");
}
if (AlertPush)
{
string AppText = Subject;
if (!SendNotification(AppText)) Print("Error sending notification: " + IntegerToString(GetLastError()) + ".");
}
// Remember that this alert has already been sent. For CheckPreviousBar, this is done in CheckAlerts().
if ((alert_type == CandleCloseCrossover) && (AlertCheckBar == CheckCurrentBar)) LastAlertTime_CandleCross = TimeCurrent();
else if ((alert_type == GapCrossover) && (AlertCheckBar == CheckCurrentBar)) LastAlertTime_GapCross = TimeCurrent();
}
// Calculating onetick based on the chart parameters and settings.
void InitializeOnetick()
{
// Adaptive point multiplier. Calculate based on number of digits in the quote (before plus after the dot).
if (PointMultiplier == 0)
{
double quote;
bool success = SymbolInfoDouble(Symbol(), SYMBOL_ASK, quote);
if (!success)
{
Print("Failed to get price data. Error #", GetLastError(), ". Using PointMultiplier = 1.");
PointMultiplier_calculated = 1;
}
else
{
double chart_height = (double)ChartGetInteger(ChartID(), CHART_HEIGHT_IN_PIXELS);
double chart_price_max = ChartGetDouble(ChartID(), CHART_PRICE_MAX);
double chart_price_min = ChartGetDouble(ChartID(), CHART_PRICE_MIN);
double price_diff = chart_price_max - chart_price_min;
if ((chart_height == 0) || (price_diff <= 0)) // If no chart yet, do it old fashioned way.
{
string s = DoubleToString(quote, _Digits);
int total_digits = StringLen(s);
// If there is a dot in a quote.
if (StringFind(s, ".") != -1) total_digits--; // Decrease the count of digits by one.
if (total_digits <= 5) PointMultiplier_calculated = 1;
else PointMultiplier_calculated = (int)MathPow(10, total_digits - 5);
}
else // Otherwise, calculate the multiplier so that 1 TPO = 1 pixel.
{
double price_per_pixel = price_diff / chart_height;
PointMultiplier_calculated = (int)MathRound(price_per_pixel / _Point);
}
}
}
else // Normal point multiplier.
{
PointMultiplier_calculated = PointMultiplier;
}
// Based on number of digits in PointMultiplier_calculated. -1 because if PointMultiplier_calculated < 10, it does not modify the number of digits.
DigitsM = _Digits - (StringLen(IntegerToString(PointMultiplier_calculated)) - 1);
onetick = NormalizeDouble(_Point * PointMultiplier_calculated, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = MarketInfo(Symbol(), MODE_TICKSIZE);
if (onetick < TickSize)
{
DigitsM = _Digits - (StringLen(IntegerToString((int)MathRound(TickSize / _Point))) - 1);
onetick = NormalizeDouble(TickSize, DigitsM);
}
}
bool SaveSettingsOnDisk()
{
int fh = FileOpen("MP_Settings\\" + m_FileName, FILE_CSV | FILE_WRITE);
if (fh == INVALID_HANDLE)
{
Print("Failed to open file for writing: MP_Settings\\" + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
// Order does not matter.
FileWrite(fh, "Session");
FileWrite(fh, IntegerToString(_Session));
FileWrite(fh, "IndicatorHidden");
FileWrite(fh, IntegerToString(IndicatorHidden));
// These are not part of settings but are input parameters.
// When the indicator is reloaded due to its input parameters change, these should be compared to the new values.
// If the value is changed, it should be updated in the variables too.
// Is the indicator reloading due to the input parameters change?
if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0)
{
FileWrite(fh, "Parameter_Session");
FileWrite(fh, IntegerToString(Session));
}
FileClose(fh);
Print("Settings saved to file.");
return true;
}
bool LoadSettingsFromDisk()
{
int fh;
if (FileIsExist("MP_Settings\\" + m_FileName))
{
fh = FileOpen("MP_Settings\\" + m_FileName, FILE_CSV | FILE_READ);
if (fh == INVALID_HANDLE)
{
Print("Failed to open file for reading: MP_Settings\\" + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
}
else return false;
while (!FileIsEnding(fh))
{
string var_name = FileReadString(fh);
string var_content = FileReadString(fh);
if (var_name == "Session")
_Session = (session_period)StringToInteger(var_content);
else if (var_name == "IndicatorHidden")
IndicatorHidden = (bool)StringToInteger(var_content);
// Is indicator reloading due to the input parameters change?
else if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0)
{
// These are not part of settings but are input parameters.
// When the indicator is reloaded due to its input parameters change, these should be compared to the new values.
// If the value is changed, it should be updated in the variables too.
if (var_name == "Parameter_Session")
{
if ((session_period)StringToInteger(var_content) != Session) _Session = Session;
}
}
}
FileClose(fh);
Print("Settings loaded from file.");
// Is indicator reloading due to the input parameters change? Delete the flag variable.
if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0) GlobalVariableDel(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters");
return true;
}
bool DeleteSettingsFile()
{
string fn_with_path = "MP_Settings\\" + m_FileName;
if (!FileIsExist(fn_with_path)) return false; // Nothing to delete.
if (!FileDelete(fn_with_path))
{
Print("Failed to delete settings file: " + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
Print("Settings file deleted.");
return true;
}
int Initialize()
{
InitFailed = false;
// Re-initialize global variables in case this function is called from OnChartEvent().
FirstRunDone = false;
Timer = 0;
NeedToRestartDrawing = false;
CleanedUpOn = 0;
LastAlertTime_CandleCross = 0;
LastAlertTime_GapCross = 0;
LastAlertTime = 0;
Close_prev = EMPTY_VALUE;
ArrowsCounter = 0;
CurrentBarDirection = Neutral;
PreviousBarDirection = Neutral;
NeedToReviewColors = false;
IntradayCrossSessionDefined = -1;
SessionsNumber = 0;
mpr_total = 0;
LastRecalculationTime = 0;
HiddenObjectsDrawn = false;
_SessionsToCount = SessionsToCount; // Sessions to count for the object creation.
_SaturdaySunday = SaturdaySunday;
// Resolve TPO timeframe: use chart's if PERIOD_CURRENT or if selected is lower than chart's.
_TPOTimeframe = (TPOTimeframe == PERIOD_CURRENT) ? Period() : TPOTimeframe;
if (PeriodSeconds(_TPOTimeframe) < PeriodSeconds()) _TPOTimeframe = Period();
TPOSize = (int)(PeriodSeconds(_TPOTimeframe) / PeriodSeconds());
if (TPOSize < 1) TPOSize = 1;
if (PeriodSeconds(_TPOTimeframe) > PERIOD_D1) _SaturdaySunday = Saturday_Sunday_Normal_Days; // Cannot distinct between normal days and Sat/Sun sessions if timeframe is higher than daily.
// Check for user Session settings.
if (_Session == Daily)
{
Suffix = "_D";
if ((_TPOTimeframe < PERIOD_M5) || (_TPOTimeframe > PERIOD_M30))
{
string alert_text = "Timeframe should be between M5 and M30 for a Daily session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Weekly)
{
Suffix = "_W";
if ((_TPOTimeframe < PERIOD_M30) || (_TPOTimeframe > PERIOD_H4))
{
string alert_text = "Timeframe should be between M30 and H4 for a Weekly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Monthly)
{
Suffix = "_M";
if ((_TPOTimeframe < PERIOD_H1) || (_TPOTimeframe > PERIOD_D1))
{
string alert_text = "Timeframe should be between H1 and D1 for a Monthly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Quarterly)
{
Suffix = "_Q";
if ((_TPOTimeframe < PERIOD_H4) || (_TPOTimeframe > PERIOD_D1))
{
string alert_text = "Timeframe should be between H4 and D1 for a Quarterly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Semiannual)
{
Suffix = "_S";
if ((_TPOTimeframe < PERIOD_H4) || (_TPOTimeframe > PERIOD_W1))
{
string alert_text = "Timeframe should be between H4 and W1 for a Semiannual session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Annual)
{
Suffix = "_A";
if ((_TPOTimeframe < PERIOD_H4) || (_TPOTimeframe > PERIOD_W1))
{
string alert_text = "Timeframe should be between H4 and W1 for an Annual session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Intraday)
{
if (_TPOTimeframe > PERIOD_M30)
{
string alert_text = "Timeframe should not be higher than M30 for an Intraday sessions.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
// Check if intraday user settings are valid.
IntradaySessionCount = 0;
if (!CheckIntradaySession(EnableIntradaySession1, IntradaySession1StartTime, IntradaySession1EndTime, IntradaySession1ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession2, IntradaySession2StartTime, IntradaySession2EndTime, IntradaySession2ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession3, IntradaySession3StartTime, IntradaySession3EndTime, IntradaySession3ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession4, IntradaySession4StartTime, IntradaySession4EndTime, IntradaySession4ColorScheme)) return INIT_PARAMETERS_INCORRECT;
// Warn user about Intraday mode
if (IntradaySessionCount == 0)
{
string alert_text = "Enable at least one intraday session if you want to use Intraday mode.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if ((_Session == Rectangle) && (SeamlessScrollingMode)) // No point in seamless scrolling mode with rectangle sessions.
{
string alert_text = "Seamless scrolling mode doesn't work with Rectangle sessions.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
// Indicator Name.
IndicatorSetString(INDICATOR_SHORTNAME, ObjPrefix + "MarketProfile " + EnumToString(_Session));
// Get color scheme from user input.
CurrentColorScheme = ColorScheme;
// To clean up potential leftovers when applying a chart template.
ObjectCleanup();
// Enable timer if user wants Session mode as Rectangle or if it is a right-to-left session, or if rays should be constantly monitored, or seamless scrolling is on.
if ((_Session == Rectangle) || (RightToLeft) || (HideRaysFromInvisibleSessions) || (SeamlessScrollingMode))
{
EventSetMillisecondTimer(500);
}
// Better do this unconditionally to avoid buffer errors.
SetIndexBuffer(0, DevelopingPOC);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
SetIndexArrow(0, 167);
SetIndexBuffer(1, DevelopingVAH);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
SetIndexArrow(1, 167);
SetIndexBuffer(2, DevelopingVAL);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
SetIndexArrow(2, 167);
ValueAreaPercentage_double = ValueAreaPercentage * 0.01;
// Create or remove the toggle button.
if (ShowToggleButton)
{
CreateToggleButton();
}
else
{
ObjectDelete(ChartID(), ToggleButtonName);
}
// If the indicator was hidden (restored from settings), suppress buffer plots.
if (IndicatorHidden)
{
SetIndexStyle(0, DRAW_NONE);
SetIndexStyle(1, DRAW_NONE);
SetIndexStyle(2, DRAW_NONE);
}
// Initialization successful
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Creates the toggle button on the chart. |
//+------------------------------------------------------------------+
void CreateToggleButton()
{
int button_width = 32;
int button_height = 18;
int button_spacing = 1;
int x_margin = (ToggleButtonCorner == CORNER_LEFT_UPPER || ToggleButtonCorner == CORNER_LEFT_LOWER) ? 5 : 5 + button_width;
int base_y = (ToggleButtonCorner == CORNER_LEFT_UPPER || ToggleButtonCorner == CORNER_RIGHT_UPPER) ? 25 : 5 + button_height;
int y_pos = base_y;
// Check if another MP on/off button already exists at that position.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_BUTTON);
for (int i = 0; i < obj_total; i++)
{
string name = ObjectName(ChartID(), i, -1, OBJ_BUTTON);
if (name == ToggleButtonName) continue; // Skip own button.
int len = StringLen(name);
if (len < 9) continue; // "_MPToggle" is 9 characters.
if (StringSubstr(name, len - 9) != "_MPToggle") continue; // Not a Market Profile toggle button.
if ((ENUM_BASE_CORNER)ObjectGetInteger(ChartID(), name, OBJPROP_CORNER) != ToggleButtonCorner) continue; // Not the same chart corner.
if (ObjectGetInteger(ChartID(), name, OBJPROP_YDISTANCE) == y_pos) // Position already taken.
{
y_pos += button_height + button_spacing; // Try next one.
}
else
{
break; // Position is available, use the current y_pos.
}
}
if (ObjectFind(ChartID(), ToggleButtonName) < 0)
{
ObjectCreate(ChartID(), ToggleButtonName, OBJ_BUTTON, 0, 0, 0);
}
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_CORNER, ToggleButtonCorner);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_XDISTANCE, x_margin);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_YDISTANCE, y_pos);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_XSIZE, button_width);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_YSIZE, button_height);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_FONTSIZE, 7);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_HIDDEN, true);
UpdateToggleButton();
}
//+------------------------------------------------------------------+
//| Updates the toggle button appearance based on visibility state. |
//+------------------------------------------------------------------+
void UpdateToggleButton()
{
if (ObjectFind(ChartID(), ToggleButtonName) < 0) return;
string label = (InstancePrefix != "") ? InstancePrefix : "MP";
if (IndicatorHidden)
{
ObjectSetString(ChartID(), ToggleButtonName, OBJPROP_TEXT, label);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BGCOLOR, clrDarkGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_COLOR, clrGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BORDER_COLOR, clrDimGray);
}
else
{
ObjectSetString(ChartID(), ToggleButtonName, OBJPROP_TEXT, label);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BGCOLOR, C'48,48,48');
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_COLOR, clrLightGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BORDER_COLOR, clrGray);
}
}
//+------------------------------------------------------------------+
//| Checks if a chart object belongs to this indicator instance. |
//+------------------------------------------------------------------+
bool IsOwnObject(const string name)
{
// Never toggle the button itself.
if (name == ToggleButtonName) return false;
if (ObjPrefix != "")
{
// All indicator objects (except alert arrows) start with ObjPrefix.
if (StringSubstr(name, 0, StringLen(ObjPrefix)) == ObjPrefix) return true;
// Alert arrow objects start with "ArrCC"/"ArrGC"/"ArrPB" followed by ObjPrefix.
if (((StringSubstr(name, 0, 5) == "ArrCC") || (StringSubstr(name, 0, 5) == "ArrGC") || (StringSubstr(name, 0, 5) == "ArrPB")) &&
(StringSubstr(name, 5, StringLen(ObjPrefix)) == ObjPrefix))
return true;
return false;
}
// When ObjPrefix is empty, indicator objects have OBJPROP_HIDDEN == true.
// This covers histogram dots, medians, VA lines, rays, key values, single prints, and TPO counts.
// User-created MPR rectangles have OBJPROP_HIDDEN == false, so they are safely excluded.
if (ObjectGetInteger(ChartID(), name, OBJPROP_HIDDEN) == true) return true;
// Alert arrows do not have OBJPROP_HIDDEN set, so check by their name prefix.
if ((StringSubstr(name, 0, 5) == "ArrCC") || (StringSubstr(name, 0, 5) == "ArrGC") || (StringSubstr(name, 0, 5) == "ArrPB")) return true;
return false;
}
//+------------------------------------------------------------------+
//| Hides all chart objects belonging to this indicator instance. |
//+------------------------------------------------------------------+
void HideOwnObjects()
{
int obj_total = ObjectsTotal(ChartID());
for (int i = obj_total - 1; i >= 0; i--)
{
string name = ObjectName(ChartID(), i);
if (!IsOwnObject(name)) continue;
ObjectSetInteger(ChartID(), name, OBJPROP_TIMEFRAMES, OBJ_NO_PERIODS);
}
}
//+------------------------------------------------------------------+
//| Toggles visibility of all indicator objects on the chart. |
//+------------------------------------------------------------------+
void ToggleIndicatorVisibility()
{
IndicatorHidden = !IndicatorHidden;
long timeframes = IndicatorHidden ? OBJ_NO_PERIODS : OBJ_ALL_PERIODS;
// Toggle all chart objects belonging to this indicator.
int obj_total = ObjectsTotal(ChartID());
for (int i = obj_total - 1; i >= 0; i--)
{
string name = ObjectName(ChartID(), i);
if (!IsOwnObject(name)) continue;
ObjectSetInteger(ChartID(), name, OBJPROP_TIMEFRAMES, timeframes);
}
// Toggle indicator buffer plots.
if (IndicatorHidden)
{
SetIndexStyle(0, DRAW_NONE);
SetIndexStyle(1, DRAW_NONE);
SetIndexStyle(2, DRAW_NONE);
}
else
{
SetIndexStyle(0, DRAW_ARROW);
SetIndexStyle(1, DRAW_ARROW);
SetIndexStyle(2, DRAW_ARROW);
}
UpdateToggleButton();
SaveSettingsOnDisk();
}
void Deinitialize()
{
if (_Session == Rectangle)
{
for (int i = 0; i < mpr_total; i++)
{
ObjectCleanup(MPR_Array[i].name + "_");
delete MPR_Array[i];
}
}
else ObjectCleanup();
EventKillTimer();
}
int OnCalculateMain(const int rates_total, const int prev_calculated)
{
// New bars arrived?
if (((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) && (rates_total - prev_calculated > 1) && (CleanedUpOn != rates_total))
{
// Initialize the indicator buffers.
for (int i = prev_calculated; i < rates_total; i++)
{
DevelopingPOC[i] = EMPTY_VALUE;
DevelopingVAH[i] = EMPTY_VALUE;
DevelopingVAL[i] = EMPTY_VALUE;
}
if ((prev_calculated == 0) && (_Session == Rectangle)) // If prev_calculated got reset for some reason, reset the rectangles.
{
for (int i = mpr_total - 1; i >= 0 ; i--)
{
MPR_Array[i].ResetPrevTime0();
}
}
CleanedUpOn = rates_total; // To prevent cleaning up the buffers again and again when the platform just starts.
}
// Skip processing when the indicator is hidden and objects have already been drawn.
if ((IndicatorHidden) && ((FirstRunDone) || (HiddenObjectsDrawn))) return rates_total;
CheckAlerts();
// Check if seamless scrolling mode should be on, else if user requests current session, else a specific date.
if (SeamlessScrollingMode)
{
int last_visible_bar = WindowFirstVisibleBar() - WindowBarsPerChart() + 1;
if (last_visible_bar < 0) last_visible_bar = 0;
StartDate = Time[last_visible_bar];
}
else if (StartFromCurrentSession) StartDate = Time[0];
else StartDate = StartFromDate;
// Adjust date if Ignore_Saturday_Sunday is set.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Saturday? Switch to Friday.
if (TimeDayOfWeek(StartDate) == 6) StartDate -= 86400;
// Sunday? Switch to Friday too.
else if (TimeDayOfWeek(StartDate) == 0) StartDate -= 2 * 86400;
}
// If we calculate profiles for the past sessions, no need to run it again.
if ((FirstRunDone) && (StartDate != Time[0])) return rates_total;
// Delay the update of Market Profile if ThrottleRedraw is given.
if ((ThrottleRedraw > 0) && (Timer > 0))
{
if ((int)TimeLocal() - Timer < ThrottleRedraw) return rates_total;
}
// Calculate rectangle.
if (_Session == Rectangle) // Everything becomes very simple if rectangle sessions are used.
{
CheckRectangles();
if ((IndicatorHidden) && (!HiddenObjectsDrawn))
{
HideOwnObjects();
HiddenObjectsDrawn = true;
}
Timer = (int)TimeLocal();
return rates_total;
}
// In MTF mode, verify that higher timeframe data is synchronized before cleaning up and redrawing.
// After reconnection from sleep mode, the HTF data may not be loaded yet. Proceeding would
// delete existing profiles (ObjectCleanup) and then redraw them incorrectly with incomplete data,
// resulting in missing older sessions and wiped Developing POC/VAH/VAL values.
if ((TPOSize > 1) && ((rates_total - prev_calculated > 1) || (NeedToRestartDrawing)))
{
if (iBars(Symbol(), _TPOTimeframe) <= 0)
{
return prev_calculated; // HTF data not ready yet. Retry on the next tick.
}
}
// Recalculate everything if there were missing bars or something like that. Or if RightToLeft is on and a new right-most session arrived.
if ((rates_total - prev_calculated > 1) || (NeedToRestartDrawing))
{
FirstRunDone = false;
ObjectCleanup();
NeedToRestartDrawing = false;
}
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(StartDate); // Finding the session's right-most bar using the date of the previous session or starting date.
int sessionstart = FindSessionStart(sessionend); // Finding the session's left-most bar using its end (right-most) bar.
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return prev_calculated;
}
int SessionToStart = 0;
// Clean up old profiles if their number exceeds the given SessionsToCount.
if ((EnableOldProfilesCleanup) && (FirstRunDone))
{
int max_sessions = _SessionsToCount;
if (_Session == Intraday) max_sessions *= IntradaySessionCount;
if (SessionsNumber > max_sessions)
{
ObjectCleanup();
FirstRunDone = false;
SessionsNumber = 0;
ArrayResize(RememberSessionMax, 0);
ArrayResize(RememberSessionMin, 0);
ArrayResize(RememberSessionStart, 0);
ArrayResize(RememberSessionSuffix, 0);
ArrayResize(RememberSessionEnd, 0);
if (EnableDevelopingPOC)
{
ArrayInitialize(DevelopingPOC, EMPTY_VALUE);
}
}
}
// If all sessions have already been counted, jump to the current one.
if (FirstRunDone) SessionToStart = _SessionsToCount - 1;
else
{
// Move back to the oldest session to count to start from it.
for (int i = 1; i < _SessionsToCount; i++)
{
sessionend = sessionstart + 1;
if (sessionend >= Bars) return prev_calculated;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionend]) == 0) || (TimeDayOfWeek(Time[sessionend]) == 6))
{
sessionend++;
if (sessionend >= Bars) break;
}
}
sessionstart = FindSessionStart(sessionend);
}
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (_Session == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i)) return 0;
}
else
{
if (_Session == Daily) Max_number_of_bars_in_a_session = PeriodSeconds(PERIOD_D1) / PeriodSeconds();
else if (_Session == Weekly) Max_number_of_bars_in_a_session = 604800 / PeriodSeconds();
else if (_Session == Monthly) Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds();
else if (_Session == Quarterly) Max_number_of_bars_in_a_session = 8035200 / PeriodSeconds();
else if (_Session == Semiannual) Max_number_of_bars_in_a_session = 16070400 / PeriodSeconds();
else if (_Session == Annual) Max_number_of_bars_in_a_session = 31622400 / PeriodSeconds();
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if (TimeDayOfWeek(Time[sessionstart]) == 0) Max_number_of_bars_in_a_session += (24 * 3600 - (TimeHour(Time[sessionstart]) * 3600 + TimeMinute(Time[sessionstart]) * 60)) / PeriodSeconds();
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if (TimeDayOfWeek(Time[sessionend]) == 6) Max_number_of_bars_in_a_session += ((TimeHour(Time[sessionend]) * 3600 + TimeMinute(Time[sessionend]) * 60)) / PeriodSeconds() + 1;
}
if (!ProcessSession(sessionstart, sessionend, i)) return 0;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend - 1;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(Time[sessionstart]) == 0) || (TimeDayOfWeek(Time[sessionstart]) == 6))
{
sessionstart--;
if (sessionstart == 0) break;
}
}
sessionend = FindSessionEndByDate(Time[sessionstart]);
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
FirstRunDone = true;
// If drawn while hidden, hide all newly created objects so they are ready for instant reveal on toggle.
if ((IndicatorHidden) && (!HiddenObjectsDrawn))
{
HideOwnObjects();
HiddenObjectsDrawn = true;
}
Timer = (int)TimeLocal();
return rates_total;
}
//+------------------------------------------------------------------+
================================================
FILE: MarketProfile.mq5
================================================
//+------------------------------------------------------------------+
//| MarketProfile.mq5 |
//| Copyright © 2010-2026, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "EarnForex.com"
#property link "https://www.earnforex.com/indicators/MarketProfile/"
#property version "1.25"
#property description "Displays the Market Profile indicator. Supports the following sessions:"
#property description "Intraday, daily, weekly, monthly, quarterly, semiannual, annual and free-form rectangle."
#property description ""
#property description "Designed for major currency pairs, but should work also with exotic pairs, CFDs, or commodities."
//+------------------------------------------------------------------+
// Rectangle session - a rectangle's name should start with 'MPR' and must not contain an underscore ('_').
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_plots 3
#property indicator_buffers 3
#property indicator_color1 clrGreen
#property indicator_width1 2
#property indicator_type1 DRAW_ARROW
#property indicator_label1 "Developing POC"
#property indicator_color2 clrGoldenrod
#property indicator_width2 2
#property indicator_type2 DRAW_ARROW
#property indicator_label2 "Developing VAH"
#property indicator_color3 clrSalmon
#property indicator_width3 2
#property indicator_type3 DRAW_ARROW
#property indicator_label3 "Developing VAL"
enum color_scheme
{
Blue_to_Red, // Blue to Red
Red_to_Green, // Red to Green
Green_to_Blue, // Green to Blue
Yellow_to_Cyan, // Yellow to Cyan
Magenta_to_Yellow, // Magenta to Yellow
Cyan_to_Magenta, // Cyan to Magenta
Single_Color // Single Color
};
enum session_period
{
Daily,
Weekly,
Monthly,
Quarterly,
Semiannual,
Annual,
Intraday,
Rectangle
};
enum sat_sun_solution
{
Saturday_Sunday_Normal_Days, // Normal sessions
Ignore_Saturday_Sunday, // Ignore Saturday and Sunday
Append_Saturday_Sunday // Append Saturday and Sunday
};
enum sessions_to_draw_rays
{
None,
Previous,
Current,
PreviousCurrent, // Previous & Current
AllPrevious, // All Previous
All
};
enum ways_to_stop_rays
{
Stop_No_Rays, // Stop no rays
Stop_All_Rays, // Stop all rays
Stop_All_Rays_Except_Prev_Session, // Stop all rays except previous session
Stop_Only_Previous_Session, // Stop only previous session's rays
};
// Only for dot coloring choice in PutDot() when ColorBullBear == true.
enum bar_direction
{
Bullish,
Bearish,
Neutral
};
enum single_print_type
{
No,
Leftside,
Rightside
};
enum alert_check_bar
{
CheckCurrentBar, // Current
CheckPreviousBar // Previous
};
enum alert_types // Required to type a parameter of DoAlerts().
{
PriceBreak, // Price Break
CandleCloseCrossover, // Candle Close Crossover
GapCrossover // Gap Crossover
};
input group "Main"
input session_period Session = Daily;
input datetime StartFromDate = __DATE__; // StartFromDate: lower priority.
input bool StartFromCurrentSession = true; // StartFromCurrentSession: higher priority.
input int SessionsToCount = 2; // SessionsToCount: Number of sessions to count Market Profile.
input bool SeamlessScrollingMode = false; // SeamlessScrollingMode: Show sessions on current screen.
input bool EnableDevelopingPOC = false; // Enable Developing POC
input bool EnableDevelopingVAHVAL = false; // Enable Developing VAH/VAL
input int ValueAreaPercentage = 70; // ValueAreaPercentage: Percentage of TPO's inside Value Area.
input ENUM_TIMEFRAMES TPOTimeframe = PERIOD_CURRENT; // TPOTimeframe: timeframe for TPO data. Equal or higher than chart's.
input string InstancePrefix = ""; // InstancePrefix: prefix for objects to allow multiple instances.
input group "Colors and looks"
input color_scheme ColorScheme = Blue_to_Red;
input color SingleColor = clrBlue; // SingleColor: if ColorScheme is set to Single Color.
input bool ColorBullBear = false; // ColorBullBear: If true, colors are from bars' direction.
input color MedianColor = clrWhite;
input color ValueAreaSidesColor = clrWhite;
input color ValueAreaHighLowColor = clrWhite;
input ENUM_LINE_STYLE MedianStyle = STYLE_SOLID;
input ENUM_LINE_STYLE MedianRayStyle = STYLE_DASH;
input ENUM_LINE_STYLE ValueAreaSidesStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaHighLowStyle = STYLE_SOLID;
input ENUM_LINE_STYLE ValueAreaRayHighLowStyle= STYLE_DOT;
input int MedianWidth = 1;
input int MedianRayWidth = 1;
input int ValueAreaSidesWidth = 1;
input int ValueAreaHighLowWidth = 1;
input int ValueAreaRayHighLowWidth = 1;
input sessions_to_draw_rays ShowValueAreaRays = None; // ShowValueAreaRays: draw previous value area high/low rays.
input sessions_to_draw_rays ShowMedianRays = None; // ShowMedianRays: draw previous median rays.
input ways_to_stop_rays RaysUntilIntersection = Stop_No_Rays; // RaysUntilIntersection: which rays stop when hit another MP.
input bool HideRaysFromInvisibleSessions = false; // HideRaysFromInvisibleSessions: hide rays from behind the screen.
input int TimeShiftMinutes = 0; // TimeShiftMinutes: shift session + to the left, - to the right.
input bool ShowKeyValues = true; // ShowKeyValues: print out VAH, VAL, POC on chart.
input color KeyValuesColor = clrWhite; // KeyValuesColor: color for VAH, VAL, POC printout.
input int KeyValuesSize = 8; // KeyValuesSize: font size for VAH, VAL, POC printout.
input single_print_type ShowSinglePrint = No; // ShowSinglePrint: mark Single Print profile levels.
input bool SinglePrintRays = false; // SinglePrintRays: mark Single Print edges with rays.
input color SinglePrintColor = clrGold;
input ENUM_LINE_STYLE SinglePrintRayStyle = STYLE_SOLID;
input int SinglePrintRayWidth = 1;
input ways_to_stop_rays SPRaysUntilIntersection = Stop_No_Rays; // SPRaysUntilIntersection: which SP rays stop when hit another MP.
input color ProminentMedianColor = clrYellow;
input ENUM_LINE_STYLE ProminentMedianStyle = STYLE_SOLID;
input int ProminentMedianWidth = 4;
input bool ShowTPOCounts = false; // ShowTPOCounts: Show TPO counts above/below POC.
input color TPOCountAboveColor = clrHoneydew; // TPOCountAboveColor: Color for TPO count above POC.
input color TPOCountBelowColor = clrMistyRose; // TPOCountBelowColor: Color for TPO count below POC.
input bool RightToLeft = false; // RightToLeft: Draw histogram from right to left.
input group "Performance"
input int PointMultiplier = 0; // PointMultiplier: higher value = fewer objects. 0 - adaptive.
input int ThrottleRedraw = 0; // ThrottleRedraw: delay (in seconds) for updating Market Profile.
input bool DisableHistogram = false; // DisableHistogram: do not draw profile, VAH, VAL, and POC still visible.
input bool EnableOldProfilesCleanup = false; // EnableOldProfilesCleanup: delete old profiles exceeding SessionsToCount.
input group "Alerts"
input bool AlertNative = false; // AlertNative: issue native pop-up alerts.
input bool AlertEmail = false; // AlertEmail: issue email alerts.
input bool AlertPush = false; // AlertPush: issue push-notification alerts.
input bool AlertArrows = false; // AlertArrows: draw chart arrows on alerts.
input alert_check_bar AlertCheckBar = CheckPreviousBar;// AlertCheckBar: which bar to check for alerts?
input bool AlertForValueArea = false; // AlertForValueArea: alerts for Value Area (VAH, VAL) rays.
input bool AlertForMedian = false; // AlertForMedian: alerts for POC (Median) rays' crossing.
input bool AlertForSinglePrint = false; // AlertForSinglePrint: alerts for single print rays' crossing.
input bool AlertOnPriceBreak = false; // AlertOnPriceBreak: price breaking above/below the ray.
input bool AlertOnCandleClose = false; // AlertOnCandleClose: candle closing above/below the ray.
input bool AlertOnGapCross = false; // AlertOnGapCross: bar gap above/below the ray.
input int AlertArrowCodePB = 108; // AlertArrowCodePB: arrow code for price break alerts.
input int AlertArrowCodeCC = 110; // AlertArrowCodeCC: arrow code for candle close alerts.
input int AlertArrowCodeGC = 117; // AlertArrowCodeGC: arrow code for gap crossover alerts.
input color AlertArrowColorPB = clrRed; // AlertArrowColorPB: arrow color for price break alerts.
input color AlertArrowColorCC = clrBlue; // AlertArrowColorCC: arrow color for candle close alerts.
input color AlertArrowColorGC = clrYellow; // AlertArrowColorGC: arrow color for gap crossover alerts.
input int AlertArrowWidthPB = 1; // AlertArrowWidthPB: arrow width for price break alerts.
input int AlertArrowWidthCC = 1; // AlertArrowWidthCC: arrow width for candle close alerts.
input int AlertArrowWidthGC = 1; // AlertArrowWidthGC: arrow width for gap crossover alerts.
input group "Intraday settings"
input bool EnableIntradaySession1 = true;
input string IntradaySession1StartTime = "00:00";
input string IntradaySession1EndTime = "06:00";
input color_scheme IntradaySession1ColorScheme = Blue_to_Red;
input bool EnableIntradaySession2 = true;
input string IntradaySession2StartTime = "06:00";
input string IntradaySession2EndTime = "12:00";
input color_scheme IntradaySession2ColorScheme = Red_to_Green;
input bool EnableIntradaySession3 = true;
input string IntradaySession3StartTime = "12:00";
input string IntradaySession3EndTime = "18:00";
input color_scheme IntradaySession3ColorScheme = Green_to_Blue;
input bool EnableIntradaySession4 = true;
input string IntradaySession4StartTime = "18:00";
input string IntradaySession4EndTime = "00:00";
input color_scheme IntradaySession4ColorScheme = Yellow_to_Cyan;
input group "Miscellaneous"
input sat_sun_solution SaturdaySunday = Saturday_Sunday_Normal_Days;
input bool DisableAlertsOnWrongTimeframes = false; // Disable alerts on wrong timeframes.
input int ProminentMedianPercentage = 101; // Percentage of Median TPOs out of total for a Prominent one.
input bool ShowToggleButton = false; // ShowToggleButton: show on/off button.
input ENUM_BASE_CORNER ToggleButtonCorner = CORNER_LEFT_UPPER; // ToggleButtonCorner: chart corner for the toggle button.
int PointMultiplier_calculated; // Will have to be calculated based number digits in a quote if PointMultiplier input is 0.
int DigitsM; // Number of digits normalized based on PointMultiplier_calculated.
bool InitFailed; // Used for soft INIT_FAILED. Hard INIT_FAILED resets input parameters.
datetime StartDate; // Will hold either StartFromDate or iTime(Symbol(), Period(), 0).
double onetick; // One normalized pip.
bool FirstRunDone = false; // If true - OnCalculate() was already executed once.
string Suffix = "_"; // Will store object name suffix depending on timeframe.
color_scheme CurrentColorScheme; // Required due to intraday sessions.
int Max_number_of_bars_in_a_session = 1;
int Timer = 0; // For throttling updates of market profiles in slow systems.
bool NeedToRestartDrawing = false; // Global flag for RightToLeft redrawing;
int CleanedUpOn = 0; // To prevent cleaning up the buffers again and again when the platform just starts.
double ValueAreaPercentage_double = 0.7; // Will be calculated based on the input parameter in OnInit().
datetime LastAlertTime_CandleCross = 0, LastAlertTime_GapCross = 0; // For CheckCurrentBar alerts.
datetime LastAlertTime = 0; // For CheckPreviousBar alerts;
double Close_prev = EMPTY_VALUE; // Previous price value for Price Break alerts.
int ArrowsCounter = 0; // Counter for naming of alert arrows.
sat_sun_solution _SaturdaySunday; // To change the input value if incompatible with timeframe.
session_period _Session; // Can be modified during runtime (hotkeys).
string m_FileName; // File name to store the session type.
string ObjPrefix; // Prefix for chart object names based on InstancePrefix input.
bool IndicatorHidden = false; // True when indicator objects are hidden via the toggle button.
string ToggleButtonName; // Name of the toggle button object.
bool HiddenObjectsDrawn = false; // True when objects have been drawn at least once while hidden.
int TPOSize = 1; // Number of chart bars each TPO spans (1 when TPOTimeframe == chart's TF).
ENUM_TIMEFRAMES _TPOTimeframe; // Resolved TPO timeframe (never lower than chart's).
// Used for ColorBullBear.
bar_direction CurrentBarDirection = Neutral;
bar_direction PreviousBarDirection = Neutral;
bool NeedToReviewColors = false;
// For intraday sessions' start and end times.
int IDStartHours[4];
int IDStartMinutes[4];
int IDStartTime[4]; // Stores IDStartHours x 60 + IDStartMinutes for comparison purposes.
int IDEndHours[4];
int IDEndMinutes[4];
int IDEndTime[4]; // Stores IDEndHours x 60 + IDEndMinutes for comparison purposes.
color_scheme IDColorScheme[4];
int IntradaySessionCount = 0;
int _SessionsToCount;
int IntradayCrossSessionDefined = -1; // For special case used only with Ignore_Saturday_Sunday on Monday.
// We need to know where each session starts and its price range for when RaysUntilIntersection != Stop_No_Rays.
// These are used also when RaysUntilIntersection == Stop_No_Rays for Intraday sessions counting.
double RememberSessionMax[], RememberSessionMin[];
datetime RememberSessionStart[];
datetime RememberSessionEnd[]; // Used only for Arrows.
string RememberSessionSuffix[];
int SessionsNumber = 0; // Different from _SessionsToCount when working with Intraday sessions and for RaysUntilIntersection != Stop_No_Rays.
// Rectangle variables:
class CRectangleMP
{
private:
datetime prev_Time0;
double prev_High, prev_Low;
double prev_RectanglePriceMax, prev_RectanglePriceMin;
int Number; // Order number of the rectangle;
public:
double RectanglePriceMax, RectanglePriceMin;
datetime RectangleTimeMax, RectangleTimeMin;
datetime t1, t2; // To avoid reading object properties in Process() after sorting was done.
string name;
CRectangleMP(string);
~CRectangleMP(void) {};
void Process(int, const int rates_total);
void ResetPrevTime0();
};
CRectangleMP* MPR_Array[];
int mpr_total = 0;
uint LastRecalculationTime = 0;
double DevelopingPOC[], DevelopingVAH[], DevelopingVAL[]; // Indicator buffers for Developing POC and VAH/VAL.
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
ObjPrefix = InstancePrefix + "_";
ToggleButtonName = ObjPrefix + "MPToggle";
m_FileName = ObjPrefix + "MP_" + IntegerToString(ChartID()) + ".txt";
if (!LoadSettingsFromDisk()) // Trying to read the saved session type from file.
{
_Session = Session;
}
return Initialize();
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(ChartID(), ToggleButtonName);
Deinitialize();
if (reason == REASON_PARAMETERS) GlobalVariableSet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters", 1);
if ((reason == REASON_REMOVE) || (reason == REASON_CHARTCLOSE) || (reason == REASON_PROGRAM))
{
DeleteSettingsFile();
}
else
{
SaveSettingsOnDisk();
}
}
//+------------------------------------------------------------------+
//| Custom Market Profile main iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& Time[],
const double& Open[],
const double& High[],
const double& Low[],
const double& Close[],
const long& tick_volume[],
const long& volume[],
const int& spread[]
)
{
if (InitFailed)
{
if (!DisableAlertsOnWrongTimeframes) Print("Initialization failed. Please see the alert message for details.");
return 0;
}
if (prev_calculated == 0) // Cannot do this inside OnInit() because chart not fully loaded yet.
{
InitializeOnetick();
}
return OnCalculateMain(rates_total, prev_calculated);
}
//+------------------------------------------------------------------+
//| Finds the session's starting bar number for any given bar number.|
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindSessionStart(const int n, const int rates_total)
{
if (_Session == Daily) return FindDayStart(n, rates_total);
else if (_Session == Weekly) return FindWeekStart(n, rates_total);
else if (_Session == Monthly) return FindMonthStart(n, rates_total);
else if (_Session == Quarterly) return FindQuarterStart(n, rates_total);
else if (_Session == Semiannual) return FindHalfyearStart(n, rates_total);
else if (_Session == Annual) return FindYearStart(n, rates_total);
else if (_Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and n is on Monday.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60) == 1))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// "Monday" part of the day. Effective only for "end < start" sessions.
if ((TimeHour(iTime(Symbol(), Period(), n)) * 60 + TimeMinute(iTime(Symbol(), Period(), n)) >= IDEndTime[intraday_i]) && (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the first bar on Monday after the borderline session.
int x = n;
while ((x < rates_total) && (TimeHour(iTime(Symbol(), Period(), x)) * 60 + TimeMinute(iTime(Symbol(), Period(), x)) >= IDEndTime[intraday_i]))
{
x++;
// If there is no Sunday session (stepped into Saturday or another non-Sunday/non-Monday day, return normal day start.
if (TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) > 1) return FindDayStart(n, rates_total);
}
return (x - 1);
}
else
{
// Find the first Sunday bar.
int x = n;
while ((x < rates_total) && ((TimeDayOfYear(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)) || (TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 0))) x++;
// Number of sessions should be increased as we "lose" one session to Sunday.
_SessionsToCount++;
return (x - 1);
}
}
}
}
return FindDayStart(n, rates_total);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindDayStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_n_day_of_week = time_x_day_of_week;
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or it is Friday but the bar n is on Saturday.
while ((TimeDayOfYear(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_x_day_of_week == 5) && (time_n_day_of_week == 6)))))
{
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the week's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindWeekStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday.
while ((SameWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)))
{
// If Ignore_Saturday_Sunday is on and we stepped into Sunday, stop.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (time_x_day_of_week == 0)) break;
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the month's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+------------------------------------------------------------------+
int FindMonthStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_day = TimeDay(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of month.
while ((time_n_month == TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (time_n_day == 1)))))
{
// If month distance somehow becomes greater than 1, break.
int month_distance = time_n_month - TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (month_distance < 0) month_distance = 12 + month_distance;
if (month_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of month. Despite it being current month, it should be skipped because it is appended to the previous month. Unless it is the sessionend day, which is the Saturday of the next month attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if ((time_x_day_of_week == 6) && (TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1) && (time_n_day != TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60))) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of month. Despite it being current month, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && ((TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1) || (TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 2))) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+--------------------------------------------------------------------+
//| Finds the quarter's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+--------------------------------------------------------------------+
int FindQuarterStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_day = TimeDay(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
bool first_day_of_quarter = false;
if (time_n_day == 1)
{
if ((time_n_month == 1) || (time_n_month == 4) || (time_n_month == 7) || (time_n_month == 10)) first_day_of_quarter = true;
}
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of quarter.
while (((time_n_month - 1) / 3 == (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 3) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (first_day_of_quarter)))))
{
// If quarter distance somehow becomes greater than 1, break.
int quarter_distance = (time_n_month - 1) / 3 - (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 3;
if (quarter_distance < 0) quarter_distance = 4 + quarter_distance;
if (quarter_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of quarter. Despite it being current month, it should be skipped because it is appended to the previous quarter. Unless it is the sessionend day, which is the Saturday of the next quarter attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_quarter = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_day_of_quarter = true;
}
if ((time_x_day_of_week == 6) && (x_first_day_of_quarter) && (!first_day_of_quarter)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of quarter. Despite it being current quarter, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
bool x_first_or_second_day_of_quarter = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if ((time_x_day == 1) || (time_x_day == 2))
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_or_second_day_of_quarter = true;
}
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && (x_first_or_second_day_of_quarter)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+---------------------------------------------------------------------+
//| Finds the half-year's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+---------------------------------------------------------------------+
int FindHalfyearStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_month = TimeMonth(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_day = TimeDay(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
bool first_day_of_halfyear = false;
if (time_n_day == 1)
{
if ((time_n_month == 1) || (time_n_month == 7)) first_day_of_halfyear = true;
}
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of half-year.
while (((time_n_month - 1) / 6 == (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 6) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (first_day_of_halfyear)))))
{
// If half-year distance somehow becomes greater than 1, break.
int halfyear_distance = (time_n_month - 1) / 6 - (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 6;
if (halfyear_distance < 0) halfyear_distance = 2 + halfyear_distance;
if (halfyear_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of half-year. Despite it being current half-year, it should be skipped because it is appended to the previous half-year. Unless it is the sessionend day, which is the Saturday of the next half-year attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_halfyear = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_day_of_halfyear = true;
}
if ((time_x_day_of_week == 6) && (x_first_day_of_halfyear) && (!first_day_of_halfyear)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of half-year. Despite it being current half-year, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
bool x_first_or_second_day_of_halfyear = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if ((time_x_day == 1) || (time_x_day == 2))
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_or_second_day_of_halfyear = true;
}
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && (x_first_or_second_day_of_halfyear)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+----------------------------------------------------------------+
//| Finds the year's starting bar number for any given bar number. |
//| n - bar number for which to find starting bar. |
//+----------------------------------------------------------------+
int FindYearStart(const int n, const int rates_total)
{
if (n >= rates_total) return -1;
int x = n;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// These don't change:
int time_n_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_day_of_year = TimeDayOfYear(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
int time_n_year = TimeYear(iTime(Symbol(), Period(), n) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday or Saturday the 1st day of year.
while ((time_n_year == TimeYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && ((time_x_day_of_week == 0) || ((time_n_day_of_week == 6) && (time_n_day_of_year == 1)))))
{
// If year distance somehow becomes greater than 1, break.
int year_distance = time_n_year - TimeYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (year_distance > 1) break;
// Check if Append_Saturday_Sunday is on and today is Saturday the 1st day of year. Despite it being current year, it should be skipped because it is appended to the previous year. Unless it is the sessionend day, which is the Saturday of the next year attached to this session.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if ((time_x_day_of_week == 6) && (TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1) && (time_n_day_of_year != 1)) break;
}
// Check if Ignore_Saturday_Sunday is on and today is Sunday or Saturday the 2nd or the 1st day of year. Despite it being current year, it should be skipped because it is ignored.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
if (((time_x_day_of_week == 0) || (time_x_day_of_week == 6)) && ((TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1) || (TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 2))) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return (x - 1);
}
//+------------------------------------------------------------------+
//| Finds the session's end bar by the session's date. |
//+------------------------------------------------------------------+
int FindSessionEndByDate(const datetime date, const int rates_total)
{
if (_Session == Daily) return FindDayEndByDate(date, rates_total);
else if (_Session == Weekly) return FindWeekEndByDate(date, rates_total);
else if (_Session == Monthly) return FindMonthEndByDate(date, rates_total);
else if (_Session == Quarterly) return FindQuarterEndByDate(date, rates_total);
else if (_Session == Semiannual) return FindHalfyearEndByDate(date, rates_total);
else if (_Session == Annual) return FindYearEndByDate(date, rates_total);
else if (_Session == Intraday)
{
// A special case when Append_Saturday_Sunday is on and the date is on Sunday.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0))
{
// One of the intraday sessions should start at 00:00 or have end < start.
for (int intraday_i = 0; intraday_i < IntradaySessionCount; intraday_i++)
{
if ((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i]))
{
// Find the last bar of this intraday session and return it as sessionend.
int x = 0;
int abs_day = TimeAbsoluteDay(date + TimeShiftMinutes * 60);
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < rates_total) && (abs_day < TimeAbsoluteDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60))) // It's Sunday.
{
// On Monday.
if (TimeAbsoluteDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == abs_day + 1)
{
// Inside the session.
if (TimeHour(iTime(Symbol(), Period(), x)) * 60 + TimeMinute(iTime(Symbol(), Period(), x)) < IDEndTime[intraday_i]) break;
// Break out earlier (on Monday's end bar) if working with 00:00-XX:XX session.
if (IDStartTime[intraday_i] == 0) break;
}
x++;
}
return x;
}
}
}
return FindDayEndByDate(date, rates_total);
}
return -1;
}
//+------------------------------------------------------------------+
//| Finds the day's end bar by the day's date. |
//+------------------------------------------------------------------+
int FindDayEndByDate(const datetime date, const int rates_total)
{
int x = 0;
// TimeAbsoluteDay is used for cases when the given date is Dec 30 (#364) and the current date is Jan 1 (#1) for example.
while ((x < rates_total) && (TimeAbsoluteDay(date + TimeShiftMinutes * 60) < TimeAbsoluteDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60)))
{
// Check if Append_Saturday_Sunday is on and if the found end of the day is on Saturday and the given date is the previous Friday; or it is a Monday and the sought date is the previous Sunday.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
if (((TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 6) || (TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1)) && (TimeAbsoluteDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - TimeAbsoluteDay(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the week's end bar by the week's date. |
//+------------------------------------------------------------------+
int FindWeekEndByDate(const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameWeek(date + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the month's end bar by the month's date. |
//+------------------------------------------------------------------+
int FindMonthEndByDate(const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameMonth(date + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// Today is Saturday the 1st day of the next month. Despite it being in a next month, it should be appended to the current month.
if ((time_x_day_of_week == 6) && (TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) == 1) && (TimeYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) * 12 + TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
// Given date is Sunday of a previous month. It was rejected in the previous month and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the month.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (TimeYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) * 12 + TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60) * 12 - TimeMonth(date + TimeShiftMinutes * 60) == 1)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the quarter's end bar by the quarter's date. |
//+------------------------------------------------------------------+
int FindQuarterEndByDate(const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameQuarter(date + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_quarter = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 4) || (time_x_month == 7) || (time_x_month == 10)) x_first_day_of_quarter = true;
}
int quarter_distance = (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 3 - (TimeMonth(date + TimeShiftMinutes * 60) - 1) / 3;
if (quarter_distance < 0) quarter_distance = 4 + quarter_distance;
// Today is Saturday the 1st day of the next quarter. Despite it being in a next quarter, it should be appended to the current quarter.
if ((time_x_day_of_week == 6) && (x_first_day_of_quarter) && (quarter_distance == 1)) break;
// Given date is Sunday of a previous quarter. It was rejected in the previous quarter and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the quarter.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (quarter_distance == 1)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the half-year's end bar by the half-year's date. |
//+------------------------------------------------------------------+
int FindHalfyearEndByDate(const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameHalfyear(date + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
bool x_first_day_of_halfyear = false;
int time_x_day = TimeDay(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int time_x_month = TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
if (time_x_day == 1)
{
if ((time_x_month == 1) || (time_x_month == 7)) x_first_day_of_halfyear = true;
}
int halfyear_distance = (TimeMonth(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - 1) / 6 - (TimeMonth(date + TimeShiftMinutes * 60) - 1) / 6;
if (halfyear_distance < 0) halfyear_distance = 2 + halfyear_distance;
// Today is Saturday the 1st day of the next half-year. Despite it being in a next half-year, it should be appended to the current half-year.
if ((time_x_day_of_week == 6) && (x_first_day_of_halfyear) && (halfyear_distance == 1)) break;
// Given date is Sunday of a previous half-year. It was rejected in the previous half-year and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the half-year.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (halfyear_distance == 1)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Finds the year's end bar by the year's date. |
//+------------------------------------------------------------------+
int FindYearEndByDate(const datetime date, const int rates_total)
{
int x = 0;
int time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
// Condition should pass also if Append_Saturday_Sunday is on and it is Sunday; and also if Ignore_Saturday_Sunday is on and it is Saturday or Sunday.
while ((SameYear(date + TimeShiftMinutes * 60, iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) != true) || ((_SaturdaySunday == Append_Saturday_Sunday) && (time_x_day_of_week == 0)) || ((_SaturdaySunday == Ignore_Saturday_Sunday) && ((time_x_day_of_week == 0) || (time_x_day_of_week == 6))))
{
// Check if Append_Saturday_Sunday is on.
if (_SaturdaySunday == Append_Saturday_Sunday)
{
int time_x_day_of_year = TimeDayOfYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
int year_distance = TimeYear(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60) - TimeYear(date + TimeShiftMinutes * 60);
// Today is Saturday the 1st day of the next year. Despite it being in a next year, it should be appended to the current year.
if ((time_x_day_of_week == 6) && (time_x_day_of_year == 1) && (year_distance == 1)) break;
// Given date is Sunday of a previous year. It was rejected in the previous year and should be appended to beginning of this one.
// Works because date here can be only the end or the beginning of the year.
if ((TimeDayOfWeek(date + TimeShiftMinutes * 60) == 0) && (year_distance == 1)) break;
}
x++;
if (x >= rates_total) break;
time_x_day_of_week = TimeDayOfWeek(iTime(Symbol(), Period(), x) + TimeShiftMinutes * 60);
}
return x;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same week. |
//+------------------------------------------------------------------+
int SameWeek(const datetime date1, const datetime date2)
{
MqlDateTime dt1, dt2;
TimeToStruct(date1, dt1);
TimeToStruct(date2, dt2);
int seconds_from_start = dt1.day_of_week * 24 * 3600 + dt1.hour * 3600 + dt1.min * 60 + dt1.sec;
if (date1 == date2) return true;
else if (date2 < date1)
{
if (date1 - date2 <= seconds_from_start) return true;
}
// 604800 - seconds in one week.
else if (date2 - date1 < 604800 - seconds_from_start) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same month. |
//+------------------------------------------------------------------+
int SameMonth(const datetime date1, const datetime date2)
{
MqlDateTime dt1, dt2;
TimeToStruct(date1, dt1);
TimeToStruct(date2, dt2);
if ((dt1.mon == dt2.mon) && (dt1.year == dt2.year)) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same quarter. |
//+------------------------------------------------------------------+
int SameQuarter(const datetime date1, const datetime date2)
{
if (((TimeMonth(date1) - 1) / 3 == (TimeMonth(date2) - 1) / 3) && (TimeYear(date1) == TimeYear(date2))) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same half-year. |
//+------------------------------------------------------------------+
int SameHalfyear(const datetime date1, const datetime date2)
{
if (((TimeMonth(date1) - 1) / 6 == (TimeMonth(date2) - 1) / 6) && (TimeYear(date1) == TimeYear(date2))) return true;
return false;
}
//+------------------------------------------------------------------+
//| Check if two dates are in the same year. |
//+------------------------------------------------------------------+
int SameYear(const datetime date1, const datetime date2)
{
if (TimeYear(date1) == TimeYear(date2)) return true;
return false;
}
//+------------------------------------------------------------------+
//| Puts a dot (rectangle) at a given position and color. |
//| price and time are coordinates. |
//| range is for the second coordinate. |
//| bar is to determine the color of the dot. |
//| Returns inverted end time only for the RightToLeft session. |
//+------------------------------------------------------------------+
datetime PutDot(const double price, const int start_bar, const int range, const int bar, string rectangle_prefix = "", datetime converted_time = 0)
{
double divisor, color_shift;
color colour = -1;
// All dots are with the same date/time for a given origin bar, but with a different price.
string LastNameStart = " " + TimeToString(iTime(Symbol(), Period(), bar + start_bar)) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
if (ColorBullBear) colour = CalculateProperColor();
// Bull/bear coloring part.
if (NeedToReviewColors)
{
// Finding all dots (rectangle objects) with proper suffix and start of last name (date + time of the bar, but not price).
// This is needed to change their color if candle changed its direction.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_RECTANGLE);
for (int i = obj_total - 1; i >= 0; i--)
{
string obj = ObjectName(ChartID(), i, -1, OBJ_RECTANGLE);
// Probably some other object.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix)) != rectangle_prefix + "MP" + Suffix) continue;
// Previous bar's dot found.
if (StringSubstr(obj, 0, StringLen(rectangle_prefix + "MP" + Suffix + LastNameStart)) != rectangle_prefix + "MP" + Suffix + LastNameStart) break;
// Change color.
ObjectSetInteger(0, obj, OBJPROP_COLOR, colour);
}
}
if (ObjectFind(0, rectangle_prefix + "MP" + Suffix + LastName) >= 0)
{
if ((!RightToLeft) || (converted_time == 0)) return 0; // Normal case;
}
datetime time_end, time_start;
datetime prev_time = converted_time; // For drawing, we need two times.
if (converted_time != 0) // This is the right-to-left mode and the right-most session.
{
// Check if we have started a new right-most session, so the previous one should be cleaned up.
static datetime prev_time_start_bar = 0;
if ((iTime(Symbol(), Period(), start_bar) != prev_time_start_bar) && (prev_time_start_bar != 0)) // New right-most session arrived - recalculate everything.
{
NeedToRestartDrawing = true;
}
prev_time_start_bar = iTime(Symbol(), Period(), start_bar);
// Find the time:
int x = -1;
for (int i = (range + 1) * TPOSize; i > 0; i--) // + 1 to get a bit "lefter" time in converted_time, and actual dot's time into prev_time.
{
prev_time = converted_time;
if (converted_time == iTime(Symbol(), Period(), 0)) // First time stepped into existing candles.
{
x = i + 1; // Remember the position.
converted_time = iTime(Symbol(), Period(), 1); // Move further.
}
else if (converted_time < iTime(Symbol(), Period(), 0))
{
if (x == -1) x = iBarShiftCustom(Symbol(), Period(), converted_time) + i + 1;
converted_time = iTime(Symbol(), Period(), x - i); // While inside the existing candles, use existing Time for candles.
}
else converted_time -= PeriodSeconds(); // While beyond the current candle, subtract fixed time periods to move left on the time scale.
}
time_end = converted_time;
time_start = prev_time;
}
else
{
if (start_bar - (range + 1) * TPOSize < 0) time_end = iTime(Symbol(), Period(), 0) + PeriodSeconds(); // Protection from 'Array out of range' error.
else time_end = iTime(Symbol(), Period(), start_bar - (range + 1) * TPOSize);
if (start_bar - range * TPOSize < 0) time_start = iTime(Symbol(), Period(), 0);
else time_start = iTime(Symbol(), Period(), start_bar - range * TPOSize);
}
if (ObjectFind(0, rectangle_prefix + "MP" + Suffix + LastName) >= 0) // Need to move the rectangle.
{
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_TIME, 0, time_start);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_TIME, 1, time_end);
}
else ObjectCreate(0, rectangle_prefix + "MP" + Suffix + LastName, OBJ_RECTANGLE, 0, time_start, price, time_end, price - onetick);
if (!ColorBullBear) // Otherwise, colour is already calculated.
{
// Color switching depending on the distance of the bar from the session's beginning.
int offset1, offset2;
switch (CurrentColorScheme)
{
case Blue_to_Red:
colour = 0x00FF0000; // clrBlue;
offset1 = 0x00010000;
offset2 = 0x00000001;
break;
case Red_to_Green:
colour = 0x000000FF; // clrDarkRed;
offset1 = 0x00000001;
offset2 = 0x00000100;
break;
case Green_to_Blue:
colour = 0x0000FF00; // clrDarkGreen;
offset1 = 0x00000100;
offset2 = 0x00010000;
break;
case Yellow_to_Cyan:
colour = 0x0000FFFF; // clrYellow;
offset1 = 0x00000001;
offset2 = 0x00010000;
break;
case Magenta_to_Yellow:
colour = 0x00FF00FF; // clrMagenta;
offset1 = 0x00010000;
offset2 = 0x00000100;
break;
case Cyan_to_Magenta:
colour = 0x00FFFF00; // clrCyan;
offset1 = 0x00000100;
offset2 = 0x00000001;
break;
case Single_Color:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
default:
colour = SingleColor;
offset1 = 0;
offset2 = 0;
break;
}
// No need to do these calculations if plain color is used.
if (CurrentColorScheme != Single_Color)
{
divisor = 1.0 / 0xFF * (double)Max_number_of_bars_in_a_session;
// bar is negative.
color_shift = MathFloor((double)bar / divisor);
// Prevents color overflow.
if ((int)color_shift < -255) color_shift = -255; // -0xFF doesn't work in MT5!
colour += color((int)color_shift * offset1);
colour -= color((int)color_shift * offset2);
}
}
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_COLOR, colour);
// Fills rectangle.
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_FILL, true);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MP" + Suffix + LastName, OBJPROP_HIDDEN, true);
return time_end;
}
//+------------------------------------------------------------------+
//| Deletes all chart objects created by the indicator. |
//+------------------------------------------------------------------+
void ObjectCleanup(string rectangle_prefix = "")
{
rectangle_prefix = ObjPrefix + rectangle_prefix;
// Delete all rectangles with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "MP" + Suffix, 0, OBJ_RECTANGLE);
ObjectsDeleteAll(0, rectangle_prefix + "Median" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_LeftSide" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_RightSide" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Top" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "VA_Bottom" + Suffix, 0, OBJ_TREND);
if (ShowValueAreaRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Value Area HighRay" + Suffix, 0, OBJ_TREND);
ObjectsDeleteAll(0, rectangle_prefix + "Value Area LowRay" + Suffix, 0, OBJ_TREND);
}
if (ShowMedianRays != None)
{
// Delete all trendlines with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "Median Ray" + Suffix, 0, OBJ_TREND);
}
if (ShowKeyValues)
{
// Delete all text labels with set prefix.
ObjectsDeleteAll(0, rectangle_prefix + "VAH" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "VAL" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "POC" + Suffix, 0, OBJ_TEXT);
}
if (ShowSinglePrint)
{
// Delete all Single Print marks.
ObjectsDeleteAll(0, rectangle_prefix + "MPSP" + Suffix, 0, OBJ_RECTANGLE);
}
if (SinglePrintRays)
{
// Delete all Single Print rays.
ObjectsDeleteAll(0, rectangle_prefix + "MPSPR" + Suffix, 0, OBJ_TREND);
}
if (AlertArrows)
{
DeleteArrowsByPrefix(rectangle_prefix);
}
if (ShowTPOCounts)
{
ObjectsDeleteAll(0, rectangle_prefix + "TPOCA" + Suffix, 0, OBJ_TEXT);
ObjectsDeleteAll(0, rectangle_prefix + "TPOCB" + Suffix, 0, OBJ_TEXT);
}
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool GetHoursAndMinutes(string time_string, int& hours, int& minutes, int& time)
{
if (StringLen(time_string) == 4) time_string = "0" + time_string;
if (
// Wrong length.
(StringLen(time_string) != 5) ||
// Wrong separator.
(time_string[2] != ':') ||
// Wrong first number (only 24 hours in a day).
((time_string[0] < '0') || (time_string[0] > '2')) ||
// 00 to 09 and 10 to 19.
(((time_string[0] == '0') || (time_string[0] == '1')) && ((time_string[1] < '0') || (time_string[1] > '9'))) ||
// 20 to 23.
((time_string[0] == '2') && ((time_string[1] < '0') || (time_string[1] > '3'))) ||
// 0M to 5M.
((time_string[3] < '0') || (time_string[3] > '5')) ||
// M0 to M9.
((time_string[4] < '0') || (time_string[4] > '9'))
)
{
Print("Wrong time string: ", time_string, ". Please use HH:MM format.");
return false;
}
string result[];
int number_of_substrings = StringSplit(time_string, ':', result);
hours = (int)StringToInteger(result[0]);
minutes = (int)StringToInteger(result[1]);
time = hours * 60 + minutes;
return true;
}
//+------------------------------------------------------------------+
//| Extract hours and minutes from a time string. |
//| Returns false in case of an error. |
//+------------------------------------------------------------------+
bool CheckIntradaySession(const bool enable, const string start_time, const string end_time, const color_scheme cs)
{
if (enable)
{
if (!GetHoursAndMinutes(start_time, IDStartHours[IntradaySessionCount], IDStartMinutes[IntradaySessionCount], IDStartTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", start_time, ".");
return false;
}
if (!GetHoursAndMinutes(end_time, IDEndHours[IntradaySessionCount], IDEndMinutes[IntradaySessionCount], IDEndTime[IntradaySessionCount]))
{
Alert("Wrong time string format: ", end_time, ".");
return false;
}
// Special case of the intraday session ending at "00:00".
if (IDEndTime[IntradaySessionCount] == 0)
{
// Turn it into "24:00".
IDEndHours[IntradaySessionCount] = 24;
IDEndMinutes[IntradaySessionCount] = 0;
IDEndTime[IntradaySessionCount] = 24 * 60;
}
IDColorScheme[IntradaySessionCount] = cs;
// For special case used only with Ignore_Saturday_Sunday on Monday.
if (IDEndTime[IntradaySessionCount] < IDStartTime[IntradaySessionCount]) IntradayCrossSessionDefined = IntradaySessionCount;
IntradaySessionCount++;
}
return true;
}
//+------------------------------------------------------------------+
//| Main procedure to draw the Market Profile based on a session |
//| start bar and session end bar. |
//| i - session number with 0 being the oldest one. |
//| Returns true on success, false - on failure. |
//+------------------------------------------------------------------+
bool ProcessSession(const int sessionstart, const int sessionend, const int i, const int rates_total, CRectangleMP* rectangle = NULL)
{
string rectangle_prefix = ObjPrefix; // Only for rectangle sessions.
if (sessionstart >= rates_total) return false; // Data not yet ready.
if (onetick == 0) return false; // onetick cannot be zero.
// Map session boundaries to higher-TF bar indices when using multi-timeframe TPO.
int htf_sessionstart = sessionstart;
int htf_sessionend = sessionend;
if (TPOSize > 1)
{
htf_sessionstart = iBarShiftCustom(Symbol(), _TPOTimeframe, iTime(Symbol(), Period(), sessionstart));
htf_sessionend = iBarShiftCustom(Symbol(), _TPOTimeframe, iTime(Symbol(), Period(), sessionend));
if (htf_sessionstart < 0) htf_sessionstart = 0;
if (htf_sessionend < 0) htf_sessionend = 0;
}
// Find the session's high and low.
double SessionMax = iHigh(Symbol(), _TPOTimeframe, iHighest(Symbol(), _TPOTimeframe, MODE_HIGH, htf_sessionstart - htf_sessionend + 1, htf_sessionend));
double SessionMin = iLow( Symbol(), _TPOTimeframe, iLowest( Symbol(), _TPOTimeframe, MODE_LOW, htf_sessionstart - htf_sessionend + 1, htf_sessionend));
int session_counter = i;
if (_Session == Rectangle)
{
rectangle_prefix = ObjPrefix + rectangle.name + "_";
if (SessionMax > rectangle.RectanglePriceMax) SessionMax = NormalizeDouble(rectangle.RectanglePriceMax, DigitsM);
if (SessionMin < rectangle.RectanglePriceMin) SessionMin = NormalizeDouble(rectangle.RectanglePriceMin, DigitsM);
}
else
{
// Find iTime(Symbol(), Period(), sessionstart) among RememberSessionStart[].
bool need_to_increment = true;
for (int j = 0; j < SessionsNumber; j++)
{
if (RememberSessionStart[j] == iTime(Symbol(), Period(), sessionstart))
{
need_to_increment = false;
session_counter = j; // Real number of the session.
break;
}
}
// Raise the number of sessions and resize arrays.
if (need_to_increment)
{
SessionsNumber++;
session_counter = SessionsNumber - 1; // Newest session.
ArrayResize(RememberSessionMax, SessionsNumber);
ArrayResize(RememberSessionMin, SessionsNumber);
ArrayResize(RememberSessionStart, SessionsNumber);
ArrayResize(RememberSessionSuffix, SessionsNumber);
ArrayResize(RememberSessionEnd, SessionsNumber); // Used only for Arrows.
}
}
// Adjust SessionMin, SessionMax for onetick granularity.
SessionMax = NormalizeDouble(MathRound(SessionMax / onetick) * onetick, DigitsM);
SessionMin = NormalizeDouble(MathRound(SessionMin / onetick) * onetick, DigitsM);
RememberSessionMax[session_counter] = SessionMax;
RememberSessionMin[session_counter] = SessionMin;
RememberSessionStart[session_counter] = iTime(Symbol(), Period(), sessionstart);
RememberSessionSuffix[session_counter] = Suffix;
RememberSessionEnd[session_counter] = iTime(Symbol(), Period(), sessionend); // Used only for Arrows.
// Used to make sure that SessionMax increments only by 'onetick' increments.
// This is needed only when updating the latest trading session and PointMultiplier_calculated > 1.
static double PreviousSessionMax = DBL_MIN;
static datetime PreviousSessionStartTime = 0;
// Reset PreviousSessionMax when a new session becomes the 'latest one'.
if (iTime(Symbol(), Period(), sessionstart) > PreviousSessionStartTime)
{
PreviousSessionMax = DBL_MIN;
PreviousSessionStartTime = iTime(Symbol(), Period(), sessionstart);
}
if ((FirstRunDone) && (i == _SessionsToCount - 1) && (PointMultiplier_calculated > 1)) // Updating the latest trading session.
{
if (SessionMax - PreviousSessionMax < onetick) // SessionMax increased only slightly - too small to use the new value with the current onetick.
{
SessionMax = PreviousSessionMax; // Do not update session max.
}
else
{
if (PreviousSessionMax != DBL_MIN)
{
// Calculate number of increments.
double nc = (SessionMax - PreviousSessionMax) / onetick;
// Adjust SessionMax.
SessionMax = NormalizeDouble(PreviousSessionMax + MathRound(nc) * onetick, DigitsM);
}
PreviousSessionMax = SessionMax;
}
}
int TPOperPrice[];
// Possible price levels if multiplied to integer.
int max = (int)MathRound((SessionMax - SessionMin) / onetick + 2); // + 2 because further we will be possibly checking array at SessionMax + 1.
ArrayResize(TPOperPrice, max);
ArrayInitialize(TPOperPrice, 0);
bool SinglePrintTracking_array[]; // For SinglePrint rays.
if (SinglePrintRays)
{
ArrayResize(SinglePrintTracking_array, max);
ArrayInitialize(SinglePrintTracking_array, false);
}
int MaxRange = 0; // Maximum distance from session start to the drawn dot.
double PriceOfMaxRange = 0; // Level of the maximum range, required to draw Median.
double DistanceToCenter = DBL_MAX; // Closest distance to center for the Median.
// Right to left for the final session:
// 1. Get rightmost time.
// 2a. If it <= iTime(Symbol(), Period(), 0) - use normal bar-walking, else:
// 2b. To "move" to the left - subtract PeriodSeconds().
// 3. Draw everything based on that Time.
// 4. Redraw everything every time the rightmost time changes.
// 5. Ray lines to the left.
// Right-to-left depiction of the rightmost session.
datetime converted_time = 0;
datetime converted_end_time = 0;
datetime min_converted_end_time = UINT_MAX;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
int dummy_subwindow;
double dummy_price;
if (_Session == Rectangle) converted_time = rectangle.RectangleTimeMax;
else ChartXYToTimePrice(0, (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS), 0, dummy_subwindow, converted_time, dummy_price);
}
int TotalTPO = 0; // Total amount of dots (TPO's).
// Going through all possible quotes from session's High to session's Low.
for (double price = SessionMax; price >= SessionMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int range = 0; // Distance from first bar to the current bar.
// Going through all bars of the session to see if the price was encountered here.
for (int bar = htf_sessionstart; bar >= htf_sessionend; bar--)
{
// Price is encountered in the given bar.
if ((price >= iLow(Symbol(), _TPOTimeframe, bar)) && (price <= iHigh(Symbol(), _TPOTimeframe, bar)))
{
// Map higher-TF bar to chart bar index for object naming and positioning.
int chart_bar = (TPOSize > 1) ? iBarShiftCustom(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, bar)) : bar;
// Update maximum distance from session's start to the found bar (needed for Median).
// Using the center-most Median if there are more than one.
if ((MaxRange < range) || ((MaxRange == range) && (MathAbs(price - (SessionMin + (SessionMax - SessionMin) / 2)) < DistanceToCenter)))
{
MaxRange = range;
PriceOfMaxRange = price;
DistanceToCenter = MathAbs(price - (SessionMin + (SessionMax - SessionMin) / 2));
}
if (!DisableHistogram)
{
if (ColorBullBear)
{
// These are needed in all cases when we color dots according to bullish/bearish bars.
double close = iClose(Symbol(), _TPOTimeframe, bar);
double open = iOpen(Symbol(), _TPOTimeframe, bar);
if (close == open) CurrentBarDirection = Neutral;
else if (close > open) CurrentBarDirection = Bullish;
else if (close < open) CurrentBarDirection = Bearish;
// This is for recoloring of the dots from the current (most-latest) bar.
if (bar == 0)
{
if (PreviousBarDirection == CurrentBarDirection) NeedToReviewColors = false;
else
{
NeedToReviewColors = true;
PreviousBarDirection = CurrentBarDirection;
}
}
}
// Draws rectangle.
if (!RightToLeft) PutDot(price, sessionstart, range, chart_bar - sessionstart, rectangle_prefix);
// Inverted drawing.
else
{
converted_end_time = PutDot(price, sessionstart, range, chart_bar - sessionstart, rectangle_prefix, converted_time);
if (converted_end_time < min_converted_end_time) min_converted_end_time = converted_end_time; // Find the leftmost time to use for the left border of the value area.
}
}
// Remember the number of encountered bars for this price.
int index = (int)MathRound((price - SessionMin) / onetick);
TPOperPrice[index]++;
range++;
TotalTPO++;
}
}
// Single print marking is due at this price.
if (ShowSinglePrint)
{
if (range == 1) PutSinglePrintMark(price, sessionstart, rectangle_prefix);
else if (range > 1) RemoveSinglePrintMark(price, sessionstart, rectangle_prefix); // Remove single print max if it exists.
}
if (SinglePrintRays)
{
int index = (int)MathRound((price - SessionMin) / onetick);
if (range == 1) SinglePrintTracking_array[index] = true; // Remember the single print's position relative to the price.
else SinglePrintTracking_array[index] = false;
}
}
// Single Print Rays
// Go through all prices again, check TPOs - whether they are single and whether they aren't bordered by another single print TPOs?
if (SinglePrintRays)
{
color spr_color = SinglePrintColor; // Normal ray color.
if ((HideRaysFromInvisibleSessions) && (iTime(Symbol(), Period(), (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR)) >= iTime(Symbol(), Period(), sessionstart))) spr_color = clrNONE; // Hide rays if behind the screen.
for (double price = SessionMax; price >= SessionMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int index = (int)MathRound((price - SessionMin) / onetick);
if (SinglePrintTracking_array[index])
{
if (price == SessionMax) // Top of the session.
{
PutSinglePrintRay(price, sessionstart, rectangle_prefix, spr_color);
}
else
{
if (SinglePrintTracking_array[index + 1] == false) // Above is a non-single print.
{
PutSinglePrintRay(price, sessionstart, rectangle_prefix, spr_color);
}
else
{
RemoveSinglePrintRay(price, sessionstart, rectangle_prefix);
}
}
if (price == SessionMin) // Bottom of the session.
{
PutSinglePrintRay(price - onetick, sessionstart, rectangle_prefix, spr_color);
}
else
{
if (SinglePrintTracking_array[index - 1] == false) // Below is a non-single print.
{
PutSinglePrintRay(price - onetick, sessionstart, rectangle_prefix, spr_color);
}
else
{
RemoveSinglePrintRay(price - onetick, sessionstart, rectangle_prefix);
}
}
}
else
{
// Attempt to remove a horizontal line below the "potentially no longer existing" single print mark.
RemoveSinglePrintRay(price - onetick, sessionstart, rectangle_prefix);
}
}
}
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) CalculateDevelopingPOCVAHVAL(sessionstart, sessionend, rectangle); // Developing POC if necessary.
// Calculate the number of TPO's in the Value Area.
int ValueControlTPO = (int)((double)TotalTPO * ValueAreaPercentage_double);
// Start with the TPO's of the Median.
int index = (int)((PriceOfMaxRange - SessionMin) / onetick);
if (index < 0) return false; // Data not yet ready.
int TPOcount = TPOperPrice[index];
// Go through the price levels above and below median adding the biggest to TPO count until the 70% of TPOs are inside the Value Area.
int up_offset = 1;
int down_offset = 1;
while (TPOcount < ValueControlTPO)
{
double abovePrice = PriceOfMaxRange + up_offset * onetick;
double belowPrice = PriceOfMaxRange - down_offset * onetick;
// If belowPrice is out of the session's range then we should add only abovePrice's TPO's, and vice versa.
index = (int)MathRound((abovePrice - SessionMin) / onetick);
int index2 = (int)MathRound((belowPrice - SessionMin) / onetick);
if (((belowPrice < SessionMin) || (TPOperPrice[index] >= TPOperPrice[index2])) && (abovePrice <= SessionMax))
{
TPOcount += TPOperPrice[index];
up_offset++;
}
else if (belowPrice >= SessionMin)
{
TPOcount += TPOperPrice[index2];
down_offset++;
}
// Cannot proceed - too few data points.
else if (TPOcount < ValueControlTPO)
{
break;
}
}
string LastName = " " + TimeToString(iTime(Symbol(), Period(), sessionstart));
// Delete old Median.
ObjectDelete(0, rectangle_prefix + "Median" + Suffix + LastName);
// Draw a new one.
index = (int)MathMax(sessionstart - (MaxRange + 1) * TPOSize, 0);
datetime time_start, time_end;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
time_end = min_converted_end_time;
time_start = converted_time;
}
else
{
time_end = iTime(Symbol(), Period(), index);
time_start = iTime(Symbol(), Period(), sessionstart);
}
ObjectCreate(0, rectangle_prefix + "Median" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange, time_end, PriceOfMaxRange);
color mc = MedianColor;
// Prominent Median (PPOC):
if ((double)(sessionstart - index) / (double)Max_number_of_bars_in_a_session * 100 >= ProminentMedianPercentage)
{
mc = ProminentMedianColor;
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_WIDTH, ProminentMedianWidth);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_STYLE, ProminentMedianStyle);
}
else
{
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_WIDTH, MedianWidth);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_STYLE, MedianStyle);
}
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_COLOR, mc);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "Median" + Suffix + LastName, OBJPROP_TOOLTIP, "Median (POC)");
// Delete old Value Area Sides.
ObjectDelete(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange + up_offset * onetick, time_start, PriceOfMaxRange - down_offset * onetick + onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_COLOR, ValueAreaSidesColor);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_STYLE, ValueAreaSidesStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaSidesWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_LeftSide" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Left Side");
ObjectDelete(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJ_TREND, 0, time_end, PriceOfMaxRange + up_offset * onetick, time_end, PriceOfMaxRange - down_offset * onetick + onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_COLOR, ValueAreaSidesColor);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_STYLE, ValueAreaSidesStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaSidesWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_RightSide" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Right Side");
// Delete old Value Area Top and Bottom.
ObjectDelete(0, rectangle_prefix + "VA_Top" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange + up_offset * onetick, time_end, PriceOfMaxRange + up_offset * onetick);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_STYLE, ValueAreaHighLowStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaHighLowWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_Top" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Top");
ObjectDelete(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName);
// Draw a new one.
ObjectCreate(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJ_TREND, 0, time_start, PriceOfMaxRange - down_offset * onetick + onetick, time_end, PriceOfMaxRange - down_offset * onetick + onetick); // Adding onetick to put the value area bottom border to its real location as PriceOfMaxRange - down_offset * onetick puts it just below the bottom TPO, which itself is 1 tick deep.
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_STYLE, ValueAreaHighLowStyle);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_WIDTH, ValueAreaHighLowWidth);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_BACK, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_RAY, false);
ObjectSetString(0, rectangle_prefix + "VA_Bottom" + Suffix + LastName, OBJPROP_TOOLTIP, "Value Area Bottom");
// VAH, VAL, and POC printout.
if (ShowKeyValues)
{
datetime value_time = time_start;
ENUM_ANCHOR_POINT anchor_poc = ANCHOR_RIGHT, anchor_va = ANCHOR_RIGHT;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
value_time = time_end; // Inverting label display position.
// Value Area printout position.
if (((_Session != Rectangle) && ((ShowValueAreaRays == All) || (ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent))) // For non-rectangle sessions, it is already known that it is the current session, so just check if current session uses rays.
|| ((_Session == Rectangle) && ( // For rectangles, need to check which session is it and whether it has rays.
(((ShowValueAreaRays == AllPrevious) && (SessionsNumber - session_counter >= 2)) ||
(((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - session_counter == 2)) ||
(((ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - session_counter == 1)) ||
(ShowValueAreaRays == All)))
))
{
anchor_va = ANCHOR_RIGHT_LOWER;
}
// Median printout position.
if (((_Session != Rectangle) && ((ShowMedianRays == All) || (ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent))) // For non-rectangle sessions, it is already known that it is the current session, so just check if current session uses rays.
|| ((_Session == Rectangle) && ( // For rectangles, need to check which session is it and whether it has rays.
(((ShowMedianRays == AllPrevious) && (SessionsNumber - session_counter >= 2)) ||
(((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - session_counter == 2)) ||
(((ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - session_counter == 1)) ||
(ShowMedianRays == All)))
))
{
anchor_poc = ANCHOR_RIGHT_LOWER;
}
}
ValuePrintOut(rectangle_prefix + "VAH" + Suffix + LastName, value_time, PriceOfMaxRange + up_offset * onetick, "Value Area High Price: " + DoubleToString(PriceOfMaxRange + up_offset * onetick, _Digits), anchor_va);
ValuePrintOut(rectangle_prefix + "VAL" + Suffix + LastName, value_time, PriceOfMaxRange - down_offset * onetick, "Value Area Low Price: " + DoubleToString(PriceOfMaxRange - down_offset * onetick, _Digits), anchor_va);
ValuePrintOut(rectangle_prefix + "POC" + Suffix + LastName, value_time, PriceOfMaxRange, "POC (Median) Price: " + DoubleToString(PriceOfMaxRange, _Digits), anchor_poc);
}
// TPO counts for the number of TPOs above the POC and below the POC.
if (ShowTPOCounts)
{
// Go through the price levels above and below median/POC to calculate TPO counts above and below it.
// Above:
int TPOCountAbove = 0;
for (double abovePrice = PriceOfMaxRange + onetick; abovePrice <= SessionMax; abovePrice += onetick)
{
index = (int)MathRound((abovePrice - SessionMin) / onetick);
TPOCountAbove += TPOperPrice[index];
}
int TPOCountBelow = 0;
for (double belowPrice = PriceOfMaxRange - onetick; belowPrice >= SessionMin; belowPrice -= onetick)
{
index = (int)MathRound((belowPrice - SessionMin) / onetick);
TPOCountBelow += TPOperPrice[index];
}
ENUM_ANCHOR_POINT anchor_tpoca = ANCHOR_LEFT_LOWER, anchor_tpocb = ANCHOR_LEFT_UPPER;
datetime value_time = time_end;
if ((RightToLeft) && ((sessionend == 0) || (_Session == Rectangle)))
{
value_time = time_start; // Inverting label display position.
anchor_tpoca = ANCHOR_RIGHT_LOWER;
anchor_tpocb = ANCHOR_RIGHT_UPPER;
}
ValuePrintOut(rectangle_prefix + "TPOCA" + Suffix + LastName, value_time, PriceOfMaxRange, "Number of TPOs above the POC: " + IntegerToString(TPOCountAbove), anchor_tpoca, TPOCountAboveColor, TPOCountAbove);
ValuePrintOut(rectangle_prefix + "TPOCB" + Suffix + LastName, value_time, PriceOfMaxRange, "Number of TPOs below the POC: " + IntegerToString(TPOCountBelow), anchor_tpocb, TPOCountBelowColor, TPOCountBelow);
}
return true;
}
//+--------------------------------------------------------------------------+
//| A cycle through intraday sessions for a given day with necessary checks. |
//| Returns true on success, false - on failure. |
//+--------------------------------------------------------------------------+
bool ProcessIntradaySession(int sessionstart, int sessionend, const int i, const int rates_total)
{
// 'remember_*' vars point at day start and day end throughout this function.
int remember_sessionstart = sessionstart;
int remember_sessionend = sessionend;
if (remember_sessionend >= rates_total) return false;
// Special case stuff.
bool ContinuePreventionFlag = false;
// Start a cycle through intraday sessions if needed.
// For each intraday session, find its own sessionstart and sessionend.
int IntradaySessionCount_tmp = IntradaySessionCount;
// If Ignore_Saturday_Sunday is on, day's start is on Monday, and there is a "22:00-06:00"-style intraday session defined, increase the counter to run the "later" "22:00-06:00" session and create this temporary dummy session.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 1) && (IntradayCrossSessionDefined > -1))
{
IntradaySessionCount_tmp++;
}
for (int intraday_i = 0; intraday_i < IntradaySessionCount_tmp; intraday_i++)
{
// Continue was triggered during the special case iteration.
if (ContinuePreventionFlag) break;
// Special case iteration.
if (intraday_i == IntradaySessionCount)
{
intraday_i = IntradayCrossSessionDefined;
ContinuePreventionFlag = true;
}
Suffix = "_ID" + IntegerToString(intraday_i);
CurrentColorScheme = IDColorScheme[intraday_i];
// Get minutes.
Max_number_of_bars_in_a_session = IDEndTime[intraday_i] - IDStartTime[intraday_i];
// If end is less than beginning:
if (Max_number_of_bars_in_a_session < 0)
{
Max_number_of_bars_in_a_session = 24 * 60 + Max_number_of_bars_in_a_session;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Day start is on Monday. And it is not a special additional intra-Monday session.
if ((TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag))
{
// Cut out Sunday part.
Max_number_of_bars_in_a_session -= 24 * 60 - IDStartTime[intraday_i];
}
// Day start is on Friday.
else if (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 5)
{
// Cut out Saturday part.
Max_number_of_bars_in_a_session -= IDEndTime[intraday_i];
}
}
}
// If Append_Saturday_Sunday is on:
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The intraday session starts on 00:00 or otherwise captures midnight, and remember_sessionstart points to Sunday:
if (((IDStartTime[intraday_i] == 0) || (IDStartTime[intraday_i] > IDEndTime[intraday_i])) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 0))
{
// Add Sunday hours.
Max_number_of_bars_in_a_session += 24 * 60 - (TimeHour(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60));
// Remove the part of Sunday that has already been added before.
if (IDStartTime[intraday_i] > IDEndTime[intraday_i]) Max_number_of_bars_in_a_session -= 24 * 60 - IDStartTime[intraday_i];
}
// The intraday session ends on 00:00 or otherwise captures midnight, and remember_sessionstart points to Friday:
else if (((IDEndTime[intraday_i] == 24 * 60) || (IDStartTime[intraday_i] > IDEndTime[intraday_i])) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 5))
{
// Add Saturday hours. The thing is we don't know how many hours there will be on Saturday. So add to max.
Max_number_of_bars_in_a_session += 24 * 60;
// Remove the part of Saturday that has already been added before.
if (IDStartTime[intraday_i] > IDEndTime[intraday_i]) Max_number_of_bars_in_a_session -= 24 * 60 - IDEndTime[intraday_i];
}
}
Max_number_of_bars_in_a_session = Max_number_of_bars_in_a_session / (PeriodSeconds() / 60); // Convert minutes to bars.
// If it is the updating stage, we need to recalculate only those intraday sessions that include the current bar.
int hour, minute, time;
if (FirstRunDone)
{
//sessionstart = day_start;
hour = TimeHour(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60);
minute = TimeMinute(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60);
time = hour * 60 + minute;
// For example, 13:00-18:00.
if (IDStartTime[intraday_i] < IDEndTime[intraday_i])
{
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// Skip all sessions that do not absorb Sunday session:
if ((IDStartTime[intraday_i] != 0) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 0)) continue;
// Skip all sessions that do not absorb Saturday session:
if ((IDEndTime[intraday_i] != 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 6)) continue;
}
// If Append_Saturday_Sunday is on and the session starts on 00:00, and now is either Sunday or Monday before the session's end:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && ((TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 0) || ((TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
else if (((time < IDEndTime[intraday_i]) && (time >= IDStartTime[intraday_i]))
// If Append_Saturday_Sunday is on and the session ends on 24:00, and now is Saturday, then go on in case, for example, of 18:00 Saturday time and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 6)))
{
sessionstart = 0;
int sessiontime = TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60);
while (((sessiontime > IDStartTime[intraday_i])
// Prevents problems when the day has partial data (e.g. Sunday) when neither appending not ignoring Saturday/Sunday. Alternatively, continue looking for the sessionstart bar if we moved from Saturday to Friday with Append_Saturday_Sunday and for XX:XX-00:00 session.
&& ((TimeDayOfYear(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 6))))
// If Append_Saturday_Sunday is on and the session ends on 24:00 and the session start is now going through Saturday, then go on in case, for example, of 13:00 Saturday time and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 6)))
{
sessionstart++;
sessiontime = TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60);
}
// This check is necessary because sessionstart may pass to the wrong day in some cases.
if (sessionstart > remember_sessionstart) sessionstart = remember_sessionstart;
}
else continue;
}
// For example, 22:00-6:00.
else if (IDStartTime[intraday_i] > IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and now is either Sunday or Monday before the session's end:
if ((_SaturdaySunday == Append_Saturday_Sunday) && ((TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 0) || ((TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
// If Ignore_Saturday_Sunday is on and it is Monday before the session's end:
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 1) && (time < IDEndTime[intraday_i]))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
}
else if (((time < IDEndTime[intraday_i]) || (time >= IDStartTime[intraday_i]))
// If Append_Saturday_Sunday is on and now is Saturday, then go on in case, for example, of 18:00 Saturday time and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60) == 6)))
{
sessionstart = 0;
int sessiontime = TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60);
// Within 24 hours of the current time - but can be today or yesterday.
while (((sessiontime > IDStartTime[intraday_i]) && (iTime(Symbol(), Period(), 0) - iTime(Symbol(), Period(), sessionstart) <= 3600 * 24))
// Same day only.
|| ((sessiontime < IDEndTime[intraday_i]) && (TimeDayOfYear(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), 0) + TimeShiftMinutes * 60)))
// If Append_Saturday_Sunday is on and the session start is now going through Saturday, then go on in case, for example, of 18:00 Saturday time and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 6)))
{
sessionstart++;
sessiontime = TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60);
}
// When the same condition in the above while cycle fails and sessionstart is one step farther than needed.
if (iTime(Symbol(), Period(), 0) - iTime(Symbol(), Period(), sessionstart) > 3600 * 24) sessionstart--;
}
else continue;
}
// If start time equals end time, we can skip the session.
else continue;
// Because apparently, we are still inside the session.
sessionend = 0;
if (!ProcessSession(sessionstart, sessionend, i, rates_total)) return false;
}
// If it is the first run.
else
{
sessionend = remember_sessionend;
// Process the sessions that start today.
// For example, 13:00-18:00.
if (IDStartTime[intraday_i] < IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and the session ends on 24:00, and day's start is on Friday and day's end is on Saturday, then do not trigger 'continue' in case, for example, of 15:00 Saturday end and 16:00-00:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday)/* && (IDEndTime[intraday_i] == 24 * 60)*/ && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) == 6) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 5))
{
}
// Intraday session starts after the today's actual session ended (for Friday/Saturday cases).
else if (TimeHour(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) < IDStartTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session starts on 00:00, and the session end points to Sunday or end points to Monday and start points to Sunday, then do not trigger 'continue' in case, for example, of 18:00 Sunday start and 00:00-16:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (((IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) == 0)) || ((TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) == 1) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 0))))
{
}
// Intraday session ends before the today's actual session starts (for Sunday cases).
else if (TimeHour(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session ends on 24:00, and the start points to Friday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 5))
{
// We already have sessionend right because it is the same as remember_sessionend (end of Saturday).
}
// If Append_Saturday_Sunday is on and the session starts on 00:00 and the session end points to Sunday (it is current Sunday session , no Monday bars yet):
else if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) == 0))
{
// We already have sessionend right because it is the same as remember_sessionend (current bar and it is on Sunday).
}
// Otherwise find the session end.
else while ((sessionend < rates_total) && ((TimeHour(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) || ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) == 6) && (_SaturdaySunday == Append_Saturday_Sunday))))
{
sessionend++;
}
if (sessionend == rates_total) sessionend--;
// If Append_Saturday_Sunday is on and the session starts on 00:00 and the session start is now going through Sunday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (IDStartTime[intraday_i] == 0) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 0))
{
// We already have sessionstart right because it is the same as remember_sessionstart (start of Sunday).
sessionstart = remember_sessionstart;
}
else
{
sessionstart = sessionend;
while ((sessionstart < rates_total) && (((TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) >= IDStartTime[intraday_i])
// Same day - for cases when the day does not contain intraday session start time. Alternatively, continue looking for the sessionstart bar if we moved from Saturday to Friday with Append_Saturday_Sunday and for XX:XX-00:00 session.
&& ((TimeDayOfYear(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60)) || ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) == 6))))
// If Append_Saturday_Sunday is on and the session ends on 24:00, and the session start is now going through Saturday, then go on in case, for example, of 15:00 Saturday end and 16:00-00:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (IDEndTime[intraday_i] == 24 * 60) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 6))
))
{
sessionstart++;
}
sessionstart--;
}
}
// For example, 22:00-6:00.
else if (IDStartTime[intraday_i] > IDEndTime[intraday_i])
{
// If Append_Saturday_Sunday is on and the start points to Friday, then do not trigger 'continue' in case, for example, of 15:00 Saturday end and 22:00-06:00 defined session.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (((TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 5) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) == 6)) || ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 0) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) == 1))))
{
}
// Today's intraday session starts after the end of the actual session (for Friday/Saturday cases).
else if (TimeHour(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60) < IDStartTime[intraday_i]) continue;
// If Append_Saturday_Sunday is on and the session start is on Sunday:
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 0))
{
// We already have sessionstart right because it is the same as remember_sessionstart (start of Sunday).
sessionstart = remember_sessionstart;
}
// If Ignore_Saturday_Sunday is on and it is Monday: (and it is not a special additional intra-Monday session.)
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag))
{
// Then we can use remember_sessionstart as the session's start.
sessionstart = remember_sessionstart;
// Monday starts on 7:00 and we have 22:00-6:00. Skip it.
if (TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]) continue;
}
else
{
// Find starting bar.
sessionstart = remember_sessionend; // Start from the end.
while ((sessionstart < rates_total) && (((TimeHour(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) >= IDStartTime[intraday_i])
// Same day - for cases when the day does not contain intraday session start time.
&& ((TimeDayOfYear(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), remember_sessionend) + TimeShiftMinutes * 60)) || (TimeDayOfYear(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == TimeDayOfYear(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60))))
// If Append_Saturday_Sunday is on and the session start is now going through Saturday, then go on in case, for example, of 15:00 Saturday end and 22:00-06:00 defined session.
|| ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 6))
))
{
sessionstart++;
}
sessionstart--;
}
int sessionlength; // In seconds.
// If Append_Saturday_Sunday is on and the end points to Saturday, don't go through this calculation because sessionend = remember_sessionend.
if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) == 6))
{
// We already have sessionend right because it is the same as remember_sessionend (end of Saturday).
}
// If Append_Saturday_Sunday is on and the start points to Sunday, use a simple method to find the end.
else if ((_SaturdaySunday == Append_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 0))
{
// While we are on Monday and sessionend is pointing on bar after IDEndTime.
while ((sessionend < rates_total) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) == 1) && (TimeHour(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) * 60 + TimeMinute(iTime(Symbol(), Period(), sessionend) + TimeShiftMinutes * 60) >= IDEndTime[intraday_i]))
{
sessionend++;
}
}
// If Ignore_Saturday_Sunday is on and the session starts on Friday:
else if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), remember_sessionstart) + TimeShiftMinutes * 60) == 5))
{
// Then it also ends on Friday.
sessionend = remember_sessionend;
}
else
{
sessionend = sessionstart;
sessionlength = (24 * 60 - IDStartTime[intraday_i] + IDEndTime[intraday_i]) * 60;
// If ignoring Sundays and session start is on Monday, cut out Sunday part of the intraday session. And it is not a special additional intra-Monday session.
if ((_SaturdaySunday == Ignore_Saturday_Sunday) && (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart) + TimeShiftMinutes * 60) == 1) && (!ContinuePreventionFlag)) sessionlength -= (24 * 60 - IDStartTime[intraday_i]) * 60;
while ((sessionend >= 0) && (iTime(Symbol(), Period(), sessionend) - iTime(Symbol(), Period(), sessionstart) < sessionlength))
{
sessionend--;
}
sessionend++;
}
}
// If start time equals end time, we can skip the session.
else continue;
if (sessionend == sessionstart) continue; // No need to process such an intraday session.
if (!ProcessSession(sessionstart, sessionend, i, rates_total)) return false;
}
}
Suffix = "_ID";
return true;
}
int TimeHour(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.hour;
}
int TimeMinute(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.min;
}
int TimeDay(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.day;
}
int TimeDayOfWeek(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.day_of_week;
}
int TimeDayOfYear(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.day_of_year;
}
int TimeMonth(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.mon;
}
int TimeYear(const datetime time)
{
MqlDateTime dt;
TimeToStruct(time, dt);
return dt.year;
}
//+------------------------------------------------------------------+
//| Returns absolute day number. |
//+------------------------------------------------------------------+
int TimeAbsoluteDay(const datetime time)
{
return ((int)time / 86400);
}
//+------------------------------------------------------------------+
//| Checks whether Median/VA/Single Print rays are required and |
//| whether they should be cut. |
//+------------------------------------------------------------------+
void CheckRays()
{
for (int i = 0; i < SessionsNumber; i++)
{
string last_name = " " + TimeToString(RememberSessionStart[i]);
string suffix = RememberSessionSuffix[i];
string rec_name = ObjPrefix;
if (_Session == Rectangle) rec_name = ObjPrefix + MPR_Array[i].name + "_";
// Process Single Print Rays to hide those that shouldn't be visible.
if ((HideRaysFromInvisibleSessions) && (SinglePrintRays))
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
if (StringSubstr(obj_name, 0, StringLen(rec_name + "MPSPR" + suffix + last_name)) != rec_name + "MPSPR" + suffix + last_name) continue; // Not a Single Print ray.
if (iTime(Symbol(), Period(), (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR)) >= RememberSessionStart[i]) // Too old.
{
ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, clrNONE); // Hide.
}
else {ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, SinglePrintColor);} // Unhide.
}
}
// If the median rays have to be created for the given trading session:
if (((ShowMedianRays == AllPrevious) && (SessionsNumber - i >= 2)) ||
(((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 2)) ||
(((ShowMedianRays == Current) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 1)) ||
(ShowMedianRays == All))
{
double median_price = ObjectGetDouble(0, rec_name + "Median" + suffix + last_name, OBJPROP_PRICE, 0);
datetime median_time = (datetime)ObjectGetInteger(0, rec_name + "Median" + suffix + last_name, OBJPROP_TIME, 1);
// Create the rays only if the median doesn't end behind the screen's edge.
if (!((HideRaysFromInvisibleSessions) && (iTime(Symbol(), Period(), (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR)) >= median_time)))
{
// Draw a new Median Ray.
if (ObjectFind(ChartID(), rec_name + "Median Ray" + suffix + last_name) < 0)
{
ObjectCreate(0, rec_name + "Median Ray" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], median_price, median_time, median_price);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_COLOR, MedianColor);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_STYLE, MedianRayStyle);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_WIDTH, MedianRayWidth);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY_LEFT, true);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY_RIGHT, false);
}
else
{
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_RAY_LEFT, false);
}
ObjectSetInteger(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_HIDDEN, true);
ObjectSetString(0, rec_name + "Median Ray" + suffix + last_name, OBJPROP_TOOLTIP, "Median Ray");
}
else
{
ObjectMove(ChartID(), rec_name + "Median Ray" + suffix + last_name, 0, RememberSessionStart[i], median_price);
ObjectMove(ChartID(), rec_name + "Median Ray" + suffix + last_name, 1, median_time, median_price);
}
}
else ObjectDelete(0, rec_name + "Median Ray" + suffix + last_name); // Delete the ray that starts from behind the screen.
}
// We should also delete outdated rays that no longer should be there.
if ((((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i > 2)) ||
((ShowMedianRays == Current) && (SessionsNumber - i > 1)))
{
ObjectDelete(0, rec_name + "Median Ray" + suffix + last_name);
}
// If the value area rays have to be created for the given trading session:
if (((ShowValueAreaRays == AllPrevious) && (SessionsNumber - i >= 2)) ||
(((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 2)) ||
(((ShowValueAreaRays == Current) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 1)) ||
(ShowValueAreaRays == All))
{
double va_high_price = ObjectGetDouble(0, rec_name + "VA_Top" + suffix + last_name, OBJPROP_PRICE, 0);
double va_low_price = ObjectGetDouble(0, rec_name + "VA_Bottom" + suffix + last_name, OBJPROP_PRICE, 0);
datetime va_time = (datetime)ObjectGetInteger(0, rec_name + "VA_Top" + suffix + last_name, OBJPROP_TIME, 1);
// Create the rays only if the value area doesn't end behind the screen's edge.
if (!((HideRaysFromInvisibleSessions) && (iTime(Symbol(), Period(), (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR)) >= va_time)))
{
// Draw a new Value Area High Ray.
if (ObjectFind(ChartID(), rec_name + "Value Area HighRay" + suffix + last_name) < 0)
{
ObjectCreate(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], va_high_price, va_time, va_high_price);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_STYLE, ValueAreaRayHighLowStyle);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_WIDTH, ValueAreaRayHighLowWidth);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY_LEFT, true);
}
else
{
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_RAY_LEFT, false);
}
ObjectSetInteger(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_HIDDEN, true);
ObjectSetString(0, rec_name + "Value Area HighRay" + suffix + last_name, OBJPROP_TOOLTIP, "Value Area High Ray");
}
else
{
ObjectMove(ChartID(), rec_name + "Value Area HighRay" + suffix + last_name, 0, RememberSessionStart[i], va_high_price);
ObjectMove(ChartID(), rec_name + "Value Area HighRay" + suffix + last_name, 1, va_time, va_high_price);
}
// Draw a new Value Area Low Ray.
if (ObjectFind(ChartID(), rec_name + "Value Area LowRay" + suffix + last_name) < 0)
{
ObjectCreate(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJ_TREND, 0, RememberSessionStart[i], va_low_price, va_time, va_low_price);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_COLOR, ValueAreaHighLowColor);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_STYLE, ValueAreaRayHighLowStyle);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_WIDTH, ValueAreaRayHighLowWidth);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_BACK, false);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_SELECTABLE, false);
if ((RightToLeft) && (i == SessionsNumber - 1) && (_Session != Rectangle))
{
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY_LEFT, true);
}
else
{
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_RAY_LEFT, false);
}
ObjectSetString(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_TOOLTIP, "Value Area Low Ray");
ObjectSetInteger(0, rec_name + "Value Area LowRay" + suffix + last_name, OBJPROP_HIDDEN, true);
}
else
{
ObjectMove(ChartID(), rec_name + "Value Area LowRay" + suffix + last_name, 0, RememberSessionStart[i], va_low_price);
ObjectMove(ChartID(), rec_name + "Value Area LowRay" + suffix + last_name, 1, va_time, va_low_price);
}
}
else
{
// Delete old Value Area Rays.
ObjectDelete(0, rec_name + "Value Area HighRay" + suffix + last_name);
ObjectDelete(0, rec_name + "Value Area LowRay" + suffix + last_name);
}
}
// We should also delete outdated rays that no longer should be there.
if ((((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i > 2)) ||
((ShowValueAreaRays == Current) && (SessionsNumber - i > 1)))
{
ObjectDelete(0, rec_name + "Value Area HighRay" + suffix + last_name);
ObjectDelete(0, rec_name + "Value Area LowRay" + suffix + last_name);
}
if (RaysUntilIntersection != Stop_No_Rays)
{
if ((((ShowMedianRays == Previous) || (ShowMedianRays == PreviousCurrent)) && (SessionsNumber - i == 2)) || (((ShowMedianRays == AllPrevious) || (ShowMedianRays == All)) && (SessionsNumber - i >= 2)))
{
if ((RaysUntilIntersection == Stop_All_Rays)
|| ((RaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((RaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
CheckRayIntersections(rec_name + "Median Ray" + suffix + last_name, i + 1);
}
if ((((ShowValueAreaRays == Previous) || (ShowValueAreaRays == PreviousCurrent)) && (SessionsNumber - i == 2)) || (((ShowValueAreaRays == AllPrevious) || (ShowValueAreaRays == All)) && (SessionsNumber - i >= 2)))
{
if ((RaysUntilIntersection == Stop_All_Rays)
|| ((RaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((RaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
{
CheckRayIntersections(rec_name + "Value Area HighRay" + suffix + last_name, i + 1);
CheckRayIntersections(rec_name + "Value Area LowRay" + suffix + last_name, i + 1);
}
}
}
if ((SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays) && (SessionsNumber - i >= 2))
{
if ((SPRaysUntilIntersection == Stop_All_Rays)
|| ((SPRaysUntilIntersection == Stop_All_Rays_Except_Prev_Session) && (SessionsNumber - i > 2))
|| ((SPRaysUntilIntersection == Stop_Only_Previous_Session) && (SessionsNumber - i == 2)))
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
if (StringSubstr(obj_name, 0, StringLen(rec_name + "MPSPR" + suffix + last_name)) != rec_name + "MPSPR" + suffix + last_name) continue; // Not this session's Single Print ray.
CheckRayIntersections(obj_name, i + 1);
}
}
}
// Historical arrow placement.
// Here we are inside a cycle through all sessions.
// For each session, we will pass its rays and add arrows if they are visible.
// Before that, it's best to check if any arrows have already been created for this session. If they have, skip.
if (AlertArrows)
{
// We will start checking from the next bar after session's end because previous crosses could be at different places in an uncompleted session.
int bar_start = iBarShiftCustom(Symbol(), Period(), RememberSessionEnd[i]) - 1; // Same for all rays of this session.
// Single Print rays.
// Single Print rays.
if (AlertForSinglePrint)
{
int obj_total = ObjectsTotal(ChartID(), 0, OBJ_TREND);
for (int j = 0; j < obj_total; j++)
{
string obj_name = ObjectName(ChartID(), j, 0, OBJ_TREND);
string obj_prefix = rec_name + "MPSPR" + suffix + last_name;
if (StringSubstr(obj_name, 0, StringLen(obj_prefix)) != obj_prefix) continue; // Not a Single Print ray (or not this seesion's).
if ((color)ObjectGetInteger(ChartID(), obj_name, OBJPROP_COLOR) != clrNONE) // Visible.
{
// Proceed only if no arrow has been found for this ray.
if (!FindAtLeastOneArrowForRay(obj_prefix))
{
for (int k = bar_start; k >= 0; k--) // Check all bars for the given single print ray.
{
CheckAndDrawArrow(k, ObjectGetDouble(ChartID(), obj_name, OBJPROP_PRICE, 0), obj_prefix);
}
}
}
else // Invisible.
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
}
// Value Area rays.
if (AlertForValueArea)
{
string obj_prefix = rec_name + "Value Area HighRay" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
obj_prefix = rec_name + "Value Area LowRay" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
// Median rays.
if (AlertForMedian)
{
string obj_prefix = rec_name + "Median Ray" + suffix + last_name;
if (ObjectFind(ChartID(), obj_prefix) >= 0) // Exists and visible.
{
if (!FindAtLeastOneArrowForRay(obj_prefix)) CheckHistoricalArrowsForNonMPSPRRays(bar_start, obj_prefix);
}
else
{
DeleteArrowsByPrefix(obj_prefix); // Delete all arrows generated by this ray.
}
}
}
}
}
// Delete arrows by prefix (complete or incomplete).
void DeleteArrowsByPrefix(const string prefix)
{
// Delete all arrows.
ObjectsDeleteAll(ChartID(), "ArrCC" + prefix, 0, OBJ_ARROW);
ObjectsDeleteAll(ChartID(), "ArrGC" + prefix, 0, OBJ_ARROW);
ObjectsDeleteAll(ChartID(), "ArrPB" + prefix, 0, OBJ_ARROW);
}
// Returns true if at least one arrow is found, false otherwise.
bool FindAtLeastOneArrowForRay(const string ray_name)
{
int objects_total = ObjectsTotal(ChartID(), 0, OBJ_ARROW);
for (int i = 0; i < objects_total; i++)
{
string obj_name = ObjectName(ChartID(), i, 0, OBJ_ARROW);
if (StringFind(obj_name, ray_name) != -1) return true; // Found an rrrow for a given ray.
}
return false; // No arrows found for the ray.
}
// Checks and draws historical arrow alerts for Median or Value Area ray.
void CheckHistoricalArrowsForNonMPSPRRays(const int bar_start, const string ray_name)
{
int end_bar = 0;
if (ObjectGetInteger(ChartID(), ray_name, OBJPROP_RAY_RIGHT) != true) // Ray was stopped, need to find its end.
{
datetime end_time = (datetime)ObjectGetInteger(ChartID(), ray_name, OBJPROP_TIME, 1);
end_bar = iBarShiftCustom(Symbol(), Period(), end_time) + 1; // End before the new session starts.
}
for (int k = bar_start; k >= end_bar; k--) // Check all bars for the given ray.
{
CheckAndDrawArrow(k, ObjectGetDouble(ChartID(), ray_name, OBJPROP_PRICE, 0), ray_name);
}
}
// Checks if any of the arrow alerts triggered on a given candle (n) with a given ray's level and places a chart object using name.
void CheckAndDrawArrow(const int n, const double level, const string ray_name)
{
// Price breaks (using pre-previous High and previous Close), candle closes, and gap crosses using iClose(Symbol(), Period(), 1).
if (AlertOnPriceBreak) // Price break alerts.
{
if (((iHigh(Symbol(), Period(), n) >= level) && (iClose(Symbol(), Period(), n) < level) && (iClose(Symbol(), Period(), n + 1) < level)) || ((iLow(Symbol(), Period(), n) <= level) && (iClose(Symbol(), Period(), n) > level) && (iClose(Symbol(), Period(), n + 1) > level)))
{
// Draw arrow object:
string obj_name = "ArrPB" + ray_name;
CreateArrowObject(obj_name, iTime(Symbol(), Period(), n), iClose(Symbol(), Period(), n), AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((iClose(Symbol(), Period(), n) >= level) && (iClose(Symbol(), Period(), n + 1) < level)) || ((iClose(Symbol(), Period(), n) <= level) && (iClose(Symbol(), Period(), n + 1) > level)))
{
// Draw arrow object:
string obj_name = "ArrCC" + ray_name;
CreateArrowObject(obj_name, iTime(Symbol(), Period(), n), iClose(Symbol(), Period(), n), AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((iLow(Symbol(), Period(), n) > level) && (iHigh(Symbol(), Period(), n + 1) < level)) || ((iLow(Symbol(), Period(), n + 1) > level) && (iHigh(Symbol(), Period(), n) < level)))
{
string obj_name = "ArrGC" + ray_name;
CreateArrowObject(obj_name, iTime(Symbol(), Period(), n), level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
}
// Creates an arrow object and sets its properties.
void CreateArrowObject(const string name, const datetime time, const double price, const int code, const color colour, const int width, const string tooltip)
{
string obj_name = name + IntegerToString(ArrowsCounter);
ArrowsCounter++;
ObjectCreate(ChartID(), obj_name, OBJ_ARROW, 0, time, price);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_ARROWCODE, code);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_COLOR, colour);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_ANCHOR, ANCHOR_CENTER);
ObjectSetInteger(ChartID(), obj_name, OBJPROP_WIDTH, width);
ObjectSetString(ChartID(), obj_name, OBJPROP_TOOLTIP, tooltip);
}
//+------------------------------------------------------------------+
//| Checks price intersection and cuts a ray for a given object. |
//+------------------------------------------------------------------+
void CheckRayIntersections(const string object, const int start_j)
{
if (ObjectFind(0, object) < 0) return;
double price = ObjectGetDouble(0, object, OBJPROP_PRICE, 0);
for (int j = start_j; j < SessionsNumber; j++) // Find the nearest intersecting session.
{
if ((price <= RememberSessionMax[j]) && (price >= RememberSessionMin[j]))
{
ObjectSetInteger(0, object, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(0, object, OBJPROP_TIME, 1, RememberSessionStart[j]);
break;
}
}
}
//+------------------------------------------------------------------+
//| Print out VAH, VAL, or POC value on the chart. |
//+------------------------------------------------------------------+
void ValuePrintOut(const string obj_name, const datetime time, const double price, const string tooltip, const ENUM_ANCHOR_POINT anchor = ANCHOR_RIGHT, color value_color = 0, const int value = 0)
{
// Find object if it exists.
if (ObjectFind(0, obj_name) >= 0)
{
// Move it.
ObjectMove(0, obj_name, 0, time, price);
}
else
{
if (value_color == 0) value_color = KeyValuesColor;
// Draw a new one.
ObjectCreate(0, obj_name, OBJ_TEXT, 0, time, price);
ObjectSetInteger(0, obj_name, OBJPROP_COLOR, value_color);
ObjectSetInteger(0, obj_name, OBJPROP_FONTSIZE, KeyValuesSize);
ObjectSetInteger(0, obj_name, OBJPROP_BACK, false);
ObjectSetInteger(0, obj_name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, obj_name, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, obj_name, OBJPROP_ANCHOR, anchor);
}
// Should be updated anyway.
string text = DoubleToString(price, _Digits);
if (value > 0) text = IntegerToString(value);
ObjectSetString(0, obj_name, OBJPROP_TEXT, text);
ObjectSetString(0, obj_name, OBJPROP_TOOLTIP, tooltip);
}
//+------------------------------------------------------------------+
//| Calculates dot color based on bar direction and color scheme. |
//| Used only when ColorBullBear == true. |
//+------------------------------------------------------------------+
color CalculateProperColor()
{
color colour = 0;
switch (CurrentColorScheme)
{
case Blue_to_Red:
if (CurrentBarDirection == Bullish)
{
colour = clrBlue;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrDarkRed;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrPink;
}
break;
case Red_to_Green:
if (CurrentBarDirection == Bullish)
{
colour = clrDarkRed;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrDarkGreen;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrBrown;
}
break;
case Green_to_Blue:
if (CurrentBarDirection == Bullish)
{
colour = clrDarkGreen;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrBlue;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrDarkGray;
}
break;
case Yellow_to_Cyan:
if (CurrentBarDirection == Bullish)
{
colour = clrYellow;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrCyan;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Magenta_to_Yellow:
if (CurrentBarDirection == Bullish)
{
colour = clrMagenta;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrYellow;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Cyan_to_Magenta:
if (CurrentBarDirection == Bullish)
{
colour = clrCyan;
}
else if (CurrentBarDirection == Bearish)
{
colour = clrMagenta;
}
else if (CurrentBarDirection == Neutral)
{
colour = clrGreen;
}
break;
case Single_Color:
if (CurrentBarDirection == Bullish)
{
colour = SingleColor;
}
else if (CurrentBarDirection == Bearish)
{
colour = color(0x00FFFFFF - SingleColor);
}
else if (CurrentBarDirection == Neutral)
{
colour = color((int)MathMax(SingleColor, 0x00FFFFFF - SingleColor) / 2);
}
break;
default:
if (CurrentBarDirection == Bullish)
{
colour = SingleColor;
}
else if (CurrentBarDirection == Bearish)
{
colour = color(0x00FFFFFF - SingleColor);
}
else if (CurrentBarDirection == Neutral)
{
colour = color((int)MathMax(SingleColor, 0x00FFFFFF - SingleColor) / 2);
}
break;
}
return colour;
}
void OnTimer()
{
if (IndicatorHidden) return;
if (GetTickCount() - LastRecalculationTime < 500) return; // Do not recalculate on timer if less than 500 ms passed.
int rates_total = iBars(Symbol(), Period());
if (HideRaysFromInvisibleSessions) CheckRays(); // Should be checked regularly if the input parameter requires ray hiding/unhiding.
if (_Session == Rectangle)
{
if (onetick == 0) InitializeOnetick(); // Can fail to initialize via OnTick() when the market is closed and a Rectangle session is used.
CheckRectangles(rates_total);
return; // No need to call RedrawLastSession() even if RightToLeft is on because in that case all Rectangles are all right-to-left and are redrawn as needed.
}
if (((RightToLeft) && (!SeamlessScrollingMode)) || (!FirstRunDone)) return; // Need to finish normal drawing before reacting to timer.
// This what goes below works for RightToLeft mode and for seamless scrolling mode, but only after the first run has been finished.
static datetime prev_converted_time = 0;
datetime converted_time = 0;
int dummy_subwindow;
double dummy_price;
ChartXYToTimePrice(0, (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS), 0, dummy_subwindow, converted_time, dummy_price);
if (converted_time == prev_converted_time) return; // Do not call RedrawLastSession() if the screen hasn't been scrolled.
prev_converted_time = converted_time;
if (SeamlessScrollingMode)
{
ObjectCleanup(); // Delete everything to make sure there are no leftover sessions behind the screen.
if (_Session == Intraday) FirstRunDone = false; // Turn off because FirstRunDone should be false for Intraday sessions to draw properly in the past.
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL))
{
for (int i = 0; i < Bars(Symbol(), Period()); i++) // Clean indicator buffers.
{
DevelopingPOC[i] = EMPTY_VALUE;
DevelopingVAH[i] = EMPTY_VALUE;
DevelopingVAL[i] = EMPTY_VALUE;
}
}
}
// Check right-most time - did it change?
RedrawLastSession(rates_total);
if ((SeamlessScrollingMode) && (_Session == Intraday)) FirstRunDone = true; // Turn back on after processing Intraday sessions.
LastRecalculationTime = GetTickCount(); // Remember last calculation time.
ChartRedraw();
}
// Find rectangles, create objects, process rectangle sessions, delete unneeded sessions (where rectangle no longer exists).
// Make sure rectangles are added to the array in a sorted manner from oldest T1 to newest T1.
void CheckRectangles(const int rates_total)
{
// Check if any existing MPR objects need to be deleted or moved:
for (int i = mpr_total - 1; i >= 0 ; i--)
{
if (ObjectFind(0, MPR_Array[i].name) < 0)
{
ObjectCleanup(MPR_Array[i].name + "_");
// Buffer cleanup for the Developing POC.
if ((EnableDevelopingPOC) || (EnableDevelopingVAHVAL))
{
int sessionstart = iBarShiftCustom(Symbol(), Period(), MPR_Array[i].RectangleTimeMin, true);
int sessionend = iBarShiftCustom(Symbol(), Period(), MPR_Array[i].RectangleTimeMax, true);
if (sessionend < 0) sessionend = 0; // If the rectangle's rightmost side is in the future, reset it to the current bar.
// Re-initialize all bars using old rectangle borders:
for (int j = sessionstart; j >= sessionend; j--)
{
DevelopingPOC[j] = EMPTY_VALUE;
DevelopingVAH[j] = EMPTY_VALUE;
DevelopingVAL[j] = EMPTY_VALUE;
}
}
delete MPR_Array[i];
// Move all array elements with greater index down:
for (int j = i; j < mpr_total - 1; j++)
MPR_Array[j] = MPR_Array[j + 1];
mpr_total--;
ArrayResize(MPR_Array, mpr_total);
}
}
// Find all objects of rectangle type with the name starting with MPR.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_RECTANGLE);
for (int i = 0; i < obj_total; i++)
{
string name = ObjectName(ChartID(), i, -1, OBJ_RECTANGLE);
if (StringSubstr(name, 0, 3) != "MPR") continue;
if (StringFind(name, "_") != -1) continue; // Skip chart objects created based on a rectangle session.
// Find the rectangle among the array's elements by its name.
bool name_found = false;
for (int j = 0; j < mpr_total; j++)
{
if (MPR_Array[j].name == name)
{
name_found = true;
// Check if it should be moved inside the array to keep sorting intact.
datetime t1 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 0);
datetime t2 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 1);
MPR_Array[j].t1 = t1;
MPR_Array[j].t2 = t2;
if (mpr_total == 1) continue; // No need to sort the array if its size is 1.
t1 = MathMin(t1, t2); // Leftmost side.
if (t1 == MPR_Array[j].RectangleTimeMin) continue; // No movement needed.
int k = 0;
if (k == j) k++; // Skip self.
while ((k < mpr_total) && (MPR_Array[k].RectangleTimeMin < t1))
{
k++;
if (k == j) k++; // Skip self.
}
// Now k points either to the first newer rectangle or to beyond the end of the array.
if (j == k - 1) continue; // Already there.
CRectangleMP* tmp = MPR_Array[j]; // Moved rectangle -> to temp.
if (t1 > MPR_Array[j].RectangleTimeMin)
{
// Run a cycle to move others elements lower.
for (int n = j; n < k - 1; n++)
MPR_Array[n] = MPR_Array[n + 1];
MPR_Array[k - 1] = tmp; // Assign the moved rectangle to the final element of the array.
}
else
{
// Run a cycle to move others elements higher.
for (int n = j; n > k; n--)
MPR_Array[n] = MPR_Array[n - 1];
MPR_Array[k] = tmp; // Assign the moved rectangle to the final element of the array.
}
break;
}
}
// New rectangle:
if (!name_found)
{
// Check if it should be moved inside the array to keep sorting intact.
datetime t1 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 0);
datetime t2 = (datetime)ObjectGetInteger(0, name, OBJPROP_TIME, 1);
datetime t = MathMin(t1, t2); // Leftmost side.
int k = 0;
while ((k < mpr_total) && (MPR_Array[k].RectangleTimeMin < t)) k++;
// Now k points either to the first newer rectangle or to beyond the end of the array.
mpr_total++;
ArrayResize(MPR_Array, mpr_total);
// Run a cycle to move others elements higher.
for (int n = mpr_total - 1; n > k; n--)
MPR_Array[n] = MPR_Array[n - 1];
MPR_Array[k] = new CRectangleMP(name); // Assign the new rectangle to the kth element of the array.
MPR_Array[k].RectangleTimeMin = t; // Fill in the leftmost time to enable further sorting.
MPR_Array[k].t1 = t1;
MPR_Array[k].t2 = t2;
}
}
if (SessionsNumber != mpr_total)
{
SessionsNumber = mpr_total;
ArrayResize(RememberSessionMax, SessionsNumber);
ArrayResize(RememberSessionMin, SessionsNumber);
ArrayResize(RememberSessionStart, SessionsNumber);
ArrayResize(RememberSessionSuffix, SessionsNumber);
ArrayResize(RememberSessionEnd, SessionsNumber); // Used only for Arrows.
}
// Process each rectangle.
for (int i = 0; i < mpr_total; i++)
MPR_Array[i].Process(i, rates_total);
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
LastRecalculationTime = GetTickCount(); // Remember last calculation time.
ChartRedraw();
}
CRectangleMP::CRectangleMP(string given_name = "MPR")
{
name = given_name;
RectanglePriceMax = -DBL_MAX;
RectanglePriceMin = DBL_MAX;
prev_RectanglePriceMax = -DBL_MAX;
prev_RectanglePriceMin = DBL_MAX;
RectangleTimeMax = 0;
RectangleTimeMin = D'31.12.3000';
prev_Time0 = 0;
prev_High = -DBL_MAX;
prev_Low = DBL_MAX;
Number = -1;
t1 = 0;
t2 = 0;
}
// i - order number of the rectangle.
void CRectangleMP::Process(const int i, const int rates_total)
{
double p1 = ObjectGetDouble(0, name, OBJPROP_PRICE, 0);
double p2 = ObjectGetDouble(0, name, OBJPROP_PRICE, 1);
if (Number == -1) Number = i;
// Calculate rectangle session's actual time and price boundaries.
int sessionstart = iBarShiftCustom(Symbol(), Period(), (int)MathMin(t1, t2), true);
int sessionend = iBarShiftCustom(Symbol(), Period(), (int)MathMax(t1, t2), true);
// Rectangle actually doesn't start in the future.
if ((MathMin(t1, t2) <= iTime(Symbol(), Period(), 0)))
// But iBarShiftCustom fails.
if ((sessionend == -1) && (sessionstart == -1)) return; // Then the data isn't ready yet.
bool rectangle_changed = false;
bool rectangle_time_changed = false;
bool rectangle_price_changed = false;
// If any of the rectangle parameters changed.
if ((RectangleTimeMax != MathMax(t1, t2)) || (RectangleTimeMin != MathMin(t1, t2)))
{
rectangle_changed = true;
rectangle_time_changed = true;
}
if ((RectanglePriceMax != MathMax(p1, p2)) || (RectanglePriceMin != MathMin(p1, p2)))
{
rectangle_changed = true;
rectangle_price_changed = true;
}
// Buffer cleanup for the Developing POC. Should be run only for a changed rectangle, which isn't brand new.
if (((EnableDevelopingPOC) || (EnableDevelopingVAHVAL)) && (rectangle_changed) && (RectangleTimeMax != D'01.01.1970'))
{
int local_sessionstart = iBarShiftCustom(Symbol(), Period(), RectangleTimeMin, true);
int local_sessionend = iBarShiftCustom(Symbol(), Period(), RectangleTimeMax, true);
if (local_sessionend < 0) local_sessionend = 0; // If the rectangle's rightmost side is in the future, reset it to the current bar.
// Re-initialize all bars using old rectangle borders:
for (int j = local_sessionstart; j >= local_sessionend; j--)
{
DevelopingPOC[j] = EMPTY_VALUE;
DevelopingVAH[j] = EMPTY_VALUE;
DevelopingVAL[j] = EMPTY_VALUE;
}
prev_Time0 = 0;
}
RectangleTimeMax = MathMax(t1, t2);
RectangleTimeMin = MathMin(t1, t2);
RectanglePriceMax = MathMax(p1, p2);
RectanglePriceMin = MathMin(p1, p2);
bool new_bars_are_not_within_rectangle = true;
bool current_bar_changed_within_boundaries = false;
if (iTime(Symbol(), Period(), 0) != prev_Time0)
{
new_bars_are_not_within_rectangle = false;
// Check if any of the new bars fall into rectangle's boundaries:
if (((prev_Time0 < RectangleTimeMin) && (iTime(Symbol(), Period(), 0) < RectangleTimeMin)) || ((prev_Time0 > RectangleTimeMax) && (iTime(Symbol(), Period(), 0) > RectangleTimeMax))) new_bars_are_not_within_rectangle = true;
// Now check if the price of any of the new bars is within the rectangle's boundaries:
if (!new_bars_are_not_within_rectangle)
{
int max_index = iHighest(Symbol(), Period(), MODE_HIGH, iBarShiftCustom(Symbol(), Period(), prev_Time0, true), 0);
int min_index = iLowest(Symbol(), Period(), MODE_LOW, iBarShiftCustom(Symbol(), Period(), prev_Time0, true), 0);
if ((iHigh(Symbol(), Period(), max_index) < RectanglePriceMin) || (iLow(Symbol(), Period(), min_index) > RectanglePriceMax)) new_bars_are_not_within_rectangle = true;
}
prev_Time0 = iTime(Symbol(), Period(), 0);
}
else // No new bars - check if the current bar's high or low changed within the rectangle's boundaries:
{
if ((iTime(Symbol(), Period(), 0) >= RectangleTimeMin) && (iTime(Symbol(), Period(), 0) <= RectangleTimeMax)) // Bar within time boundaries.
{
if (prev_High != iHigh(Symbol(), Period(), 0))
{
if ((iHigh(Symbol(), Period(), 0) <= RectanglePriceMax) && (iHigh(Symbol(), Period(), 0) >= RectanglePriceMin)) current_bar_changed_within_boundaries = true;
}
if (prev_Low != iLow(Symbol(), Period(), 0))
{
if ((iLow(Symbol(), Period(), 0) <= RectanglePriceMax) && (iLow(Symbol(), Period(), 0) >= RectanglePriceMin)) current_bar_changed_within_boundaries = true;
}
}
}
prev_High = iHigh(Symbol(), Period(), 0);
prev_Low = iLow(Symbol(), Period(), 0);
if (sessionend < 0) sessionend = 0; // If the rectangles rightmost side is in the future, reset it to the current bar.
bool need_to_clean_up_dots = false;
bool rectangle_changed_and_recalc_is_due = false;
// If rectangle changed:
if (rectangle_changed)
{
if (rectangle_price_changed)
{
// Max/min bars of the price range within rectangle's boundaries before and after change:
int max_index = iHighest(Symbol(), Period(), MODE_HIGH, sessionstart - sessionend, sessionend);
int min_index = iLowest(Symbol(), Period(), MODE_LOW, sessionstart - sessionend, sessionend);
if ((max_index != -1) && (min_index != -1))
{
if ((RectanglePriceMax > iHigh(Symbol(), Period(), max_index)) && (RectanglePriceMin < iLow(Symbol(), Period(), min_index)) && (prev_RectanglePriceMax > iHigh(Symbol(), Period(), max_index)) && (prev_RectanglePriceMin < iLow(Symbol(), Period(), min_index))) rectangle_changed_and_recalc_is_due = false;
else
{
need_to_clean_up_dots = true;
rectangle_changed_and_recalc_is_due = true;
}
}
}
if (rectangle_time_changed)
{
need_to_clean_up_dots = true;
if (sessionstart >= 0) rectangle_changed_and_recalc_is_due = true;
}
}
prev_RectanglePriceMax = RectanglePriceMax;
prev_RectanglePriceMin = RectanglePriceMin;
// Need to continue drawing profile in the following cases only:
// 1. New bar came in and it is within the rectangle's borders.
// 2. Current bar changed its High or Low and it is now within the borders.
// 3. Rectangle changed its borders.
// 4. Order of rectangles changed - need recalculation for stopping the rays (only when it is really needed).
// Need to delete previous dots before going to drawing in the following cases:
// 1. Rectangle changed its borders.
// 2. When Max_number_of_bars_in_a_session changes.
// Number of bars in the rectangle session changed, need to update colors, so a cleanup is due.
if (sessionstart - sessionend + 1 != Max_number_of_bars_in_a_session)
{
Max_number_of_bars_in_a_session = sessionstart - sessionend + 1;
if (!new_bars_are_not_within_rectangle) need_to_clean_up_dots = true;
}
if (need_to_clean_up_dots) ObjectCleanup(name + "_");
if (sessionstart < 0) return; // Rectangle is drawn in the future.
RememberSessionStart[i] = RectangleTimeMin;
// Used only for Arrows:
if (iTime(Symbol(), Period(), 0) < RectangleTimeMax) RememberSessionEnd[i] = iTime(Symbol(), Period(), 0);
else RememberSessionEnd[i] = RectangleTimeMax;
if ((!new_bars_are_not_within_rectangle) || (current_bar_changed_within_boundaries) || (rectangle_changed_and_recalc_is_due) || ((Number != i) && ((RaysUntilIntersection != Stop_No_Rays) && ((ShowMedianRays != None) || (ShowValueAreaRays != None))))) ProcessSession(sessionstart, sessionend, i, rates_total, &this);
Number = i;
}
void CRectangleMP::ResetPrevTime0()
{
prev_Time0 = 0;
}
void PutSinglePrintMark(const double price, const int sessionstart, const string rectangle_prefix)
{
int t1 = sessionstart + 1, t2 = sessionstart;
bool fill = true;
if (ShowSinglePrint == Rightside)
{
t1 = sessionstart;
t2 = sessionstart - 1;
fill = false;
}
string LastNameStart = " " + TimeToString(iTime(Symbol(), Period(), t1)) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
// If already there - ignore.
if (ObjectFind(0, rectangle_prefix + "MPSP" + Suffix + LastName) >= 0) return;
ObjectCreate(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJ_RECTANGLE, 0, iTime(Symbol(), Period(), t1), price, iTime(Symbol(), Period(), t2), price - onetick);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_COLOR, SinglePrintColor);
// Fills rectangle.
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_FILL, fill);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetString(0, rectangle_prefix + "MPSP" + Suffix + LastName, OBJPROP_TOOLTIP, "Single Print Mark");
}
void RemoveSinglePrintMark(const double price, const int sessionstart, const string rectangle_prefix)
{
int t = sessionstart + 1;
if (ShowSinglePrint == Rightside) t = sessionstart;
string LastNameStart = " " + TimeToString(iTime(Symbol(), Period(), t)) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
ObjectDelete(0, rectangle_prefix + "MPSP" + Suffix + LastName);
}
void PutSinglePrintRay(const double price, const int sessionstart, const string rectangle_prefix, const color spr_color)
{
datetime t1 = iTime(Symbol(), Period(), sessionstart), t2;
if (sessionstart - 1 >= 0) t2 = iTime(Symbol(), Period(), sessionstart - 1);
else t2 = iTime(Symbol(), Period(), sessionstart) + 1;
if (ShowSinglePrint == Rightside)
{
t1 = iTime(Symbol(), Period(), sessionstart);
t2 = iTime(Symbol(), Period(), sessionstart + 1);
}
string LastNameStart = " " + TimeToString(t1) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
// If already there - ignore.
if (ObjectFind(0, rectangle_prefix + "MPSPR" + Suffix + LastName) >= 0) return;
ObjectCreate(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJ_TREND, 0, t1, price, t2, price);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_COLOR, spr_color);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_STYLE, SinglePrintRayStyle);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_WIDTH, SinglePrintRayWidth);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_RAY_RIGHT, true);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_HIDDEN, true);
ObjectSetString(0, rectangle_prefix + "MPSPR" + Suffix + LastName, OBJPROP_TOOLTIP, "Single Print Ray");
}
void RemoveSinglePrintRay(const double price, const int sessionstart, const string rectangle_prefix)
{
datetime t = iTime(Symbol(), Period(), sessionstart);
string LastNameStart = " " + TimeToString(t) + " ";
string LastName = LastNameStart + DoubleToString(price, _Digits);
ObjectDelete(0, rectangle_prefix + "MPSPR" + Suffix + LastName);
}
// Called only when RightToLeft is on to update the right-most session.
void RedrawLastSession(const int rates_total)
{
if (SeamlessScrollingMode)
{
int last_visible_bar = (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR) - (int)ChartGetInteger(ChartID(), CHART_WIDTH_IN_BARS) + 1;
if (last_visible_bar < 0) last_visible_bar = 0;
StartDate = iTime(Symbol(), Period(), last_visible_bar);
}
else if (StartFromCurrentSession) StartDate = iTime(Symbol(), Period(), 0);
else StartDate = StartFromDate;
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(StartDate, rates_total);
int sessionstart = FindSessionStart(sessionend, rates_total);
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return;
}
int SessionToStart = 0;
// In all cases except for the seamless scrolling mode, jump to the latest session.
if (!SeamlessScrollingMode) SessionToStart = _SessionsToCount - 1;
else
{
// Move back to the oldest session to count to start from it.
for (int i = 1; i < _SessionsToCount; i++)
{
sessionend = sessionstart + 1;
if (sessionend >= Bars(Symbol(), Period())) return;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 0) || (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 6))
{
sessionend++;
if (sessionend >= Bars(Symbol(), Period())) break;
}
}
sessionstart = FindSessionStart(sessionend, rates_total);
}
SessionsNumber = 0; // Reset previously remembered sessions as there won't be any need for them.
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (_Session == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i, rates_total)) return;
}
else
{
if (_Session == Daily) Max_number_of_bars_in_a_session = PeriodSeconds(PERIOD_D1) / PeriodSeconds();
else if (_Session == Weekly) Max_number_of_bars_in_a_session = 604800 / PeriodSeconds();
else if (_Session == Monthly) Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds();
else if (_Session == Quarterly) Max_number_of_bars_in_a_session = 8035200 / PeriodSeconds();
else if (_Session == Semiannual) Max_number_of_bars_in_a_session = 16070400 / PeriodSeconds();
else if (_Session == Annual) Max_number_of_bars_in_a_session = 31622400 / PeriodSeconds();
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 0) Max_number_of_bars_in_a_session += (24 * 3600 - (TimeHour(iTime(Symbol(), Period(), sessionstart)) * 3600 + TimeMinute(iTime(Symbol(), Period(), sessionstart)) * 60)) / PeriodSeconds();
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 6) Max_number_of_bars_in_a_session += ((TimeHour(iTime(Symbol(), Period(), sessionend)) * 3600 + TimeMinute(iTime(Symbol(), Period(), sessionend)) * 60)) / PeriodSeconds() + 1;
}
if (!ProcessSession(sessionstart, sessionend, i, rates_total)) return;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend - 1;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 0) || (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 6))
{
sessionstart--;
if (sessionstart == 0) break;
}
}
sessionend = FindSessionEndByDate(iTime(Symbol(), Period(), sessionstart), Bars(Symbol(), Period()));
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
}
//+----------------------------------------------------------------------------------+
//| Go through all prices on all N session bars from 1st to kth bar, where k = 1..N. |
//+----------------------------------------------------------------------------------+
void CalculateDevelopingPOCVAHVAL(const int sessionstart, const int sessionend, CRectangleMP* rectangle = NULL)
{
// Map session boundaries to higher-TF bar indices.
int htf_start = sessionstart;
int htf_end = sessionend;
if (TPOSize > 1)
{
htf_start = iBarShiftCustom(Symbol(), _TPOTimeframe, iTime(Symbol(), Period(), sessionstart));
htf_end = iBarShiftCustom(Symbol(), _TPOTimeframe, iTime(Symbol(), Period(), sessionend));
if (htf_start < 0) htf_start = 0;
if (htf_end < 0) htf_end = 0;
}
// Cycle through all possible end bars to calculate the Developing POC.
for (int htf_max = htf_start; htf_max >= htf_end; htf_max--)
{
// Determine which chart bar this HTF bar corresponds to.
int max_bar = htf_max;
if (TPOSize > 1) // MTF:
{
max_bar = iBarShiftCustom(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max));
while (iTime(Symbol(), Period(), max_bar) < iTime(Symbol(), _TPOTimeframe, htf_max)) // Fix if went too far into the past.
{
max_bar--;
if (max_bar < 0) break;
}
if (max_bar < 0) max_bar = 0;
if (max_bar >= Bars(Symbol(), Period())) continue;
}
if (DevelopingPOC[max_bar] != EMPTY_VALUE && htf_max > 1) continue; // One of the buffers already filled and it isn't/wasn't the latest bar - skip. Valid only for non-Rectangle sessions.
double LocalMax = iHigh(Symbol(), _TPOTimeframe, iHighest(Symbol(), _TPOTimeframe, MODE_HIGH, htf_start - htf_max + 1, htf_max));
double LocalMin = iLow( Symbol(), _TPOTimeframe, iLowest( Symbol(), _TPOTimeframe, MODE_LOW, htf_start - htf_max + 1, htf_max));
// For rectangles, further restrictions may apply.
if (_Session == Rectangle)
{
if (LocalMax > rectangle.RectanglePriceMax) LocalMax = NormalizeDouble(rectangle.RectanglePriceMax, DigitsM);
if (LocalMin < rectangle.RectanglePriceMin) LocalMin = NormalizeDouble(rectangle.RectanglePriceMin, DigitsM);
}
double DistanceToCenter = DBL_MAX; // Reset the distance because each piece of the Developing POC should be using its own.
int DevMaxRange = 0; // Maximum range for the Developing POC.
double PriceOfMaxRange = EMPTY_VALUE;
// Will be necessary for Developing VAH/VAL calculation.
int TotalTPO = 0; // Total amount of dots (TPO's).
int TPOperPrice[];
// Possible price levels if multiplied to integer.
int max = (int)MathRound((LocalMax - LocalMin) / onetick + 2); // + 2 because further we will be possibly checking array at LocalMax + 1.
ArrayResize(TPOperPrice, max);
ArrayInitialize(TPOperPrice, 0);
// Cycle by price inside the local boundaries:
for (double price = LocalMax; price >= LocalMin; price -= onetick)
{
price = NormalizeDouble(price, DigitsM);
int range = 0; // Distance from first bar to the current bar.
// Going through all bars of the session until the current htf_max to see if the price was encountered here.
for (int bar = htf_start; bar >= htf_max; bar--)
{
// Price is encountered in the given bar.
if ((price >= iLow(Symbol(), _TPOTimeframe, bar)) && (price <= iHigh(Symbol(), _TPOTimeframe, bar)))
{
// Update maximum distance from session's start to the found bar for the Developing POC.
// Using the center-most POC if there are more than one.
if ((DevMaxRange < range) || ((DevMaxRange == range) && (MathAbs(price - (LocalMin + (LocalMax - LocalMin) / 2)) < DistanceToCenter))) //SessionMax and SessionMin should be replaced with current N bars' max High and min Low.
{
DevMaxRange = range;
PriceOfMaxRange = price;
DistanceToCenter = MathAbs(price - (LocalMin + (LocalMax - LocalMin) / 2));
}
// Remember the number of encountered bars for this price for Developing VAH/VAL.
int index = (int)MathRound((price - LocalMin) / onetick);
TPOperPrice[index]++;
TotalTPO++;
range++;
}
}
}
if (EnableDevelopingVAHVAL)
{
double TotalTPOdouble = TotalTPO;
// Calculate amount of TPO's in the Value Area.
int ValueControlTPO = (int)MathRound(TotalTPOdouble * ValueAreaPercentage_double);
// Start with the TPO's of the Median.
int index = (int)((PriceOfMaxRange - LocalMin) / onetick);
if (index < 0) continue; // Data wasn't available yet.
int TPOcount = TPOperPrice[index];
// Go through the price levels above and below median adding the biggest to TPO count until the 70% of TPOs are inside the Value Area.
int up_offset = 1;
int down_offset = 1;
while (TPOcount < ValueControlTPO)
{
double abovePrice = PriceOfMaxRange + up_offset * onetick;
double belowPrice = PriceOfMaxRange - down_offset * onetick;
// If belowPrice is out of the session's range then we should add only abovePrice's TPO's, and vice versa.
index = (int)MathRound((abovePrice - LocalMin) / onetick);
int index2 = (int)MathRound((belowPrice - LocalMin) / onetick);
if (((belowPrice < LocalMin) || (TPOperPrice[index] >= TPOperPrice[index2])) && (abovePrice <= LocalMax))
{
TPOcount += TPOperPrice[index];
up_offset++;
}
else if (belowPrice >= LocalMin)
{
TPOcount += TPOperPrice[index2];
down_offset++;
}
// Cannot proceed - too few data points.
else if (TPOcount < ValueControlTPO)
{
break;
}
}
DevelopingVAH[max_bar] = PriceOfMaxRange + up_offset * onetick;
DevelopingVAL[max_bar] = PriceOfMaxRange - down_offset * onetick + onetick;
// Fill intermediate chart bars within this HTF bar with the same values.
if (TPOSize > 1)
{
int next_chart_bar = (htf_max > htf_end) ? iBarShiftCustom(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max - 1)) : sessionend;
if (next_chart_bar == sessionend) next_chart_bar--;
for (int fill = max_bar - 1; fill > next_chart_bar; fill--)
{
DevelopingVAH[fill] = DevelopingVAH[max_bar];
DevelopingVAL[fill] = DevelopingVAL[max_bar];
}
}
}
if (EnableDevelopingPOC)
{
DevelopingPOC[max_bar] = PriceOfMaxRange;
if (TPOSize > 1)
{
// Fill intermediate chart bars within this HTF bar with the same Developing POC value.
int next_chart_bar = (htf_max > htf_end) ? iBarShiftCustom(Symbol(), Period(), iTime(Symbol(), _TPOTimeframe, htf_max - 1)) : sessionend;
if (next_chart_bar == sessionend) next_chart_bar--;
for (int fill = max_bar - 1; fill > next_chart_bar; fill--)
{
DevelopingPOC[fill] = PriceOfMaxRange;
}
}
}
}
}
// Used for Developing POC, VAH, and VAL lines.
void DistributeBetweenTwoBuffers(double &buff1[], double &buff2[], int bar, double price)
{
// Both buffer are empty:
if ((buff1[bar + 1] == EMPTY_VALUE) && (buff2[bar + 1] == EMPTY_VALUE))
{
buff1[bar] = price; // Starting with the first one.
buff2[bar] = EMPTY_VALUE; // The second is initialized to an empty value.
}
// Buffer #1 already had a value,
else if (buff1[bar + 1] != EMPTY_VALUE)
{
// and it is different from what we get now.
if (buff1[bar + 1] != price)
{
buff2[bar] = price; // Use new buffer to get an interrupted shift of lines.
buff1[bar] = EMPTY_VALUE;
}
else // and it is the same price:
{
buff1[bar] = price; // Use the same buffer.
buff2[bar] = EMPTY_VALUE;
}
}
// Buffer #2 already had a value,
else
{
// and it is different from what we get now.
if (buff2[bar + 1] != price)
{
buff1[bar] = price; // Use new buffer to get an interrupted shift of lines.
buff2[bar] = EMPTY_VALUE;
}
else // and it is the same price:
{
buff2[bar] = price; // Use the same buffer.
buff1[bar] = EMPTY_VALUE;
}
}
}
//+------------------------------------------------------------------+
//| For keystroke processing in Rectangle sessions. |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam)
{
if (id == CHARTEVENT_KEYDOWN)
{
if (lparam == 82) // 'r' key pressed.
{
if (_Session != Rectangle) return;
// Find the next untaken MPR rectangle name.
for (int i = 0; i < 1000; i++) // No more than 1000 rectangles!
{
string name = "MPR" + IntegerToString(i);
if (ObjectFind(0, name) >= 0) continue;
// If name not found, create a new rectangle.
// Position it at the chart's center with width and height equal to the half of those of the chart.
int pixel_width = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int pixel_height = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
int half_width = pixel_width / 2;
int half_height = pixel_height / 2;
int x1 = half_width / 2;
int x2 = int(half_width * 1.5);
int y1 = half_height / 2;
int y2 = int(half_height * 1.5);
int dummy_subwindow; // Filler variable.
datetime time1, time2;
double price1, price2;
ChartXYToTimePrice(0, x1, y1, dummy_subwindow, time1, price1); // Convert the first pair of coordinates into a time/price pair.
ChartXYToTimePrice(0, x2, y2, dummy_subwindow, time2, price2); // Convert the second pair of coordinates into a time/price pair.
ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, price1, time2, price2);
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, true);
ObjectSetInteger(0, name, OBJPROP_HIDDEN, false);
ObjectSetInteger(0, name, OBJPROP_SELECTED, true);
ObjectSetInteger(0, name, OBJPROP_FILL, false);
break;
}
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 49) && (_Session != Daily)) // Ctrl+1
{
Print("Switching session to Daily");
Deinitialize();
_Session = Daily;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 50) && (_Session != Weekly)) // Ctrl+2
{
Print("Switching session to Weekly");
Deinitialize();
_Session = Weekly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 51) && (_Session != Monthly)) // Ctrl+3
{
Print("Switching session to Monthly");
Deinitialize();
_Session = Monthly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 52) && (_Session != Quarterly)) // Ctrl+4
{
Print("Switching session to Quarterly");
Deinitialize();
_Session = Quarterly;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 53) && (_Session != Semiannual)) // Ctrl+5
{
Print("Switching session to Semiannual");
Deinitialize();
_Session = Semiannual;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 54) && (_Session != Annual)) // Ctrl+6
{
Print("Switching session to Annual");
Deinitialize();
_Session = Annual;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 55) && (_Session != Intraday)) // Ctrl+7
{
Print("Switching session to Intraday");
Deinitialize();
_Session = Intraday;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
else if ((TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) < 0) && (lparam == 56) && (_Session != Rectangle)) // Ctrl+8
{
Print("Switching session to Rectangle");
Deinitialize();
_Session = Rectangle;
Initialize();
OnCalculateMain(Bars(Symbol(), Period()), 0);
}
}
else if (id == CHARTEVENT_OBJECT_CLICK)
{
if ((ShowToggleButton) && (sparam == ToggleButtonName))
{
ToggleIndicatorVisibility();
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_STATE, false); // Reset button state.
}
}
}
//+------------------------------------------------------------------+
//| Checks all alert conditions and issues alerts if needed. |
//+------------------------------------------------------------------+
void CheckAlerts()
{
// No need to check further if no alert method is chosen.
if ((!AlertNative) && (!AlertEmail) && (!AlertPush) && (!AlertArrows)) return;
// Skip alerts if alerts are disabled for Median, for Value Area, and for Single Print rays.
if ((!AlertForMedian) && (!AlertForValueArea) && (!AlertForSinglePrint)) return;
// Skip alerts if no cross type is chosen.
if ((!AlertOnPriceBreak) && (!AlertOnCandleClose) && (!AlertOnGapCross)) return;
// Skip alerts if only closed bar should be checked and it has already been done.
if ((AlertCheckBar == CheckPreviousBar) && (LastAlertTime == iTime(Symbol(), Period(), 0))) return;
// Cycle through rays starts here.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_TREND);
for (int i = 0; i < obj_total; i++)
{
string object_name = ObjectName(ChartID(), i, -1, OBJ_TREND);
// Skip objects not belonging to this instance.
if ((ObjPrefix != "") && (StringSubstr(object_name, 0, StringLen(ObjPrefix)) != ObjPrefix)) continue;
// Skip if it is either a non-ray or if this particular ray shouldn't get alerted.
if (!(((AlertForMedian) && (StringFind(object_name, "Median Ray") > -1)) ||
((AlertForValueArea) && ((StringFind(object_name, "Value Area HighRay") > -1) || (StringFind(object_name, "Value Area LowRay") > -1))) ||
((AlertForSinglePrint)&& (StringFind(object_name, "MPSPR") > -1) && ((color)ObjectGetInteger(ChartID(), object_name, OBJPROP_COLOR) != clrNONE)))) continue;
// If everything is fine, go on:
double level = NormalizeDouble(ObjectGetDouble(ChartID(), object_name, OBJPROP_PRICE, 0), _Digits);
// Price breaks, candle closes, and gap crosses using iClose(Symbol(), Period(), 0).
if (AlertCheckBar == CheckCurrentBar)
{
if (AlertOnPriceBreak) // Price break alerts.
{
if ((Close_prev != EMPTY_VALUE) && (((iClose(Symbol(), Period(), 0) >= level) && (Close_prev < level)) || ((iClose(Symbol(), Period(), 0) <= level) && (Close_prev > level))))
{
DoAlerts(PriceBreak, object_name);
if (AlertArrows) CreateArrowObject("ArrPB" + object_name, iTime(Symbol(), Period(), 0), iClose(Symbol(), Period(), 0), AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
Close_prev = iClose(Symbol(), Period(), 0);
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((iClose(Symbol(), Period(), 0) >= level) && (iClose(Symbol(), Period(), 1) < level)) || ((iClose(Symbol(), Period(), 0) <= level) && (iClose(Symbol(), Period(), 1) > level)))
{
DoAlerts(CandleCloseCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrCC" + object_name, iTime(Symbol(), Period(), 0), iClose(Symbol(), Period(), 0), AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((iOpen(Symbol(), Period(), 0) > level) && (iHigh(Symbol(), Period(), 1) < level)) || ((iOpen(Symbol(), Period(), 0) < level) && (iLow(Symbol(), Period(), 1) > level)))
{
DoAlerts(GapCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrGC" + object_name, iTime(Symbol(), Period(), 0), level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
}
// Price breaks (using pre-previous High and previous Close), candle closes, and gap crosses using iClose(Symbol(), Period(), 1).
else if (AlertCheckBar == CheckPreviousBar)
{
if (AlertOnPriceBreak) // Price break alerts.
{
if (((iHigh(Symbol(), Period(), 1) >= level) && (iClose(Symbol(), Period(), 1) < level) && (iClose(Symbol(), Period(), 2) < level)) || ((iLow(Symbol(), Period(), 1) <= level) && (iClose(Symbol(), Period(), 1) > level) && (iClose(Symbol(), Period(), 2) > level)))
{
DoAlerts(PriceBreak, object_name);
if (AlertArrows) CreateArrowObject("ArrPB" + object_name, iTime(Symbol(), Period(), 1), iClose(Symbol(), Period(), 1), AlertArrowCodePB, AlertArrowColorPB, AlertArrowWidthPB, "Price Break");
}
}
if (AlertOnCandleClose) // Candle close alerts.
{
if (((iClose(Symbol(), Period(), 1) >= level) && (iClose(Symbol(), Period(), 2) < level)) || ((iClose(Symbol(), Period(), 1) <= level) && (iClose(Symbol(), Period(), 2) > level)))
{
DoAlerts(CandleCloseCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrCC" + object_name, iTime(Symbol(), Period(), 1), iClose(Symbol(), Period(), 1), AlertArrowCodeCC, AlertArrowColorCC, AlertArrowWidthCC, "Candle Close");
}
}
if (AlertOnGapCross) // Gap cross alerts.
{
if (((iLow(Symbol(), Period(), 1) > level) && (iHigh(Symbol(), Period(), 2) < level)) || ((iLow(Symbol(), Period(), 2) > level) && (iHigh(Symbol(), Period(), 1) < level)))
{
DoAlerts(GapCrossover, object_name);
if (AlertArrows) CreateArrowObject("ArrGC" + object_name, iTime(Symbol(), Period(), 1), level, AlertArrowCodeGC, AlertArrowColorGC, AlertArrowWidthGC, "Gap Cross");
}
}
LastAlertTime = iTime(Symbol(), Period(), 0);
}
}
}
//+------------------------------------------------------------------+
//| Issues alerts based on the alert type and includes object name |
//| in the message. |
//+------------------------------------------------------------------+
void DoAlerts(const alert_types alert_type, const string object_name)
{
// Price Breaks for Current Bar should not be be checked for LastAlertTime.
// Candle Close and Gap Cross for Current Bar need to be checked against LastAlertTime.
// All CheckPreviousBar alerts can use a single LastAlertTime (they either trigger at the start of the bar or not). The actual check is performed in CheckAlerts().
// Using TimeCurrent() for all CheckCurrentBar alerts.
// Using iTime(Symbol(), Period(), 0) for all CheckPreviousBar alerts.
// Check last alert time for Candle Close alert type.
if ((alert_type == CandleCloseCrossover) && (AlertCheckBar == CheckCurrentBar) && (TimeCurrent() <= LastAlertTime_CandleCross)) return;
// Check last alert time for Gap Cross alert type.
if ((alert_type == GapCrossover) && (AlertCheckBar == CheckCurrentBar) && (TimeCurrent() <= LastAlertTime_GapCross)) return;
string Subject = "Market Profile: " + Symbol() + " " + EnumToString(alert_type) + " on " + object_name;
if (AlertNative)
{
string AlertText = Subject;
Alert(AlertText);
}
if (AlertEmail)
{
string EmailSubject = Subject;
string EmailBody = AccountInfoString(ACCOUNT_COMPANY) + " - " + AccountInfoString(ACCOUNT_NAME) + " - " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "\r\n\r\n" + Subject;
if (!SendMail(EmailSubject, EmailBody)) Print("Error sending email: " + IntegerToString(GetLastError()) + ".");
}
if (AlertPush)
{
string AppText = Subject;
if (!SendNotification(AppText)) Print("Error sending notification: " + IntegerToString(GetLastError()) + ".");
}
// Remember that this alert has already been sent. For CheckPreviousBar, this is done in CheckAlerts().
if ((alert_type == CandleCloseCrossover) && (AlertCheckBar == CheckCurrentBar)) LastAlertTime_CandleCross = TimeCurrent();
else if ((alert_type == GapCrossover) && (AlertCheckBar == CheckCurrentBar)) LastAlertTime_GapCross = TimeCurrent();
}
// Calculating onetick based on the chart parameters and settings.
void InitializeOnetick()
{
// Adaptive point multiplier. Calculate based on number of digits in the quote (before plus after the dot).
if (PointMultiplier == 0)
{
double quote;
bool success = SymbolInfoDouble(Symbol(), SYMBOL_ASK, quote);
if (!success)
{
Print("Failed to get price data. Error #", GetLastError(), ". Using PointMultiplier = 1.");
PointMultiplier_calculated = 1;
}
else
{
double chart_height = (double)ChartGetInteger(ChartID(), CHART_HEIGHT_IN_PIXELS);
double chart_price_max = ChartGetDouble(ChartID(), CHART_PRICE_MAX);
double chart_price_min = ChartGetDouble(ChartID(), CHART_PRICE_MIN);
double price_diff = chart_price_max - chart_price_min;
if ((chart_height == 0) || (price_diff <= 0)) // If no chart yet, do it old fashioned way.
{
string s = DoubleToString(quote, _Digits);
int total_digits = StringLen(s);
// If there is a dot in a quote.
if (StringFind(s, ".") != -1) total_digits--; // Decrease the count of digits by one.
if (total_digits <= 5) PointMultiplier_calculated = 1;
else PointMultiplier_calculated = (int)MathPow(10, total_digits - 5);
}
else // Otherwise, calculate the multiplier so that 1 TPO = 1 pixel.
{
double price_per_pixel = price_diff / chart_height;
PointMultiplier_calculated = (int)MathRound(price_per_pixel / _Point);
}
}
}
else // Normal point multiplier.
{
PointMultiplier_calculated = PointMultiplier;
}
// Based on number of digits in PointMultiplier_calculated. -1 because if PointMultiplier_calculated < 10, it does not modify the number of digits.
DigitsM = _Digits - (StringLen(IntegerToString(PointMultiplier_calculated)) - 1);
onetick = NormalizeDouble(_Point * PointMultiplier_calculated, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);
if (onetick < TickSize)
{
DigitsM = _Digits - (StringLen(IntegerToString((int)MathRound(TickSize / _Point))) - 1);
onetick = NormalizeDouble(TickSize, DigitsM);
}
}
bool SaveSettingsOnDisk()
{
int fh = FileOpen("MP_Settings\\" + m_FileName, FILE_CSV | FILE_WRITE);
if (fh == INVALID_HANDLE)
{
Print("Failed to open file for writing: MP_Settings\\" + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
// Order does not matter.
FileWrite(fh, "Session");
FileWrite(fh, IntegerToString(_Session));
FileWrite(fh, "IndicatorHidden");
FileWrite(fh, IntegerToString(IndicatorHidden));
// These are not part of settings but are input parameters.
// When the indicator is reloaded due to its input parameters change, these should be compared to the new values.
// If the value is changed, it should be updated in the variables too.
// Is the indicator reloading due to the input parameters change?
if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0)
{
FileWrite(fh, "Parameter_Session");
FileWrite(fh, IntegerToString(Session));
}
FileClose(fh);
Print("Settings saved to file.");
return true;
}
bool LoadSettingsFromDisk()
{
int fh;
if (FileIsExist("MP_Settings\\" + m_FileName))
{
fh = FileOpen("MP_Settings\\" + m_FileName, FILE_CSV | FILE_READ);
if (fh == INVALID_HANDLE)
{
Print("Failed to open file for reading: MP_Settings\\" + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
}
else return false;
while (!FileIsEnding(fh))
{
string var_name = FileReadString(fh);
string var_content = FileReadString(fh);
if (var_name == "Session")
_Session = (session_period)StringToInteger(var_content);
else if (var_name == "IndicatorHidden")
IndicatorHidden = (bool)StringToInteger(var_content);
// Is indicator reloading due to the input parameters change?
else if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0)
{
// These are not part of settings but are input parameters.
// When the indicator is reloaded due to its input parameters change, these should be compared to the new values.
// If the value is changed, it should be updated in the variables too.
if (var_name == "Parameter_Session")
{
if ((session_period)StringToInteger(var_content) != Session) _Session = Session;
}
}
}
FileClose(fh);
Print("Settings loaded from file.");
// Is indicator reloading due to the input parameters change? Delete the flag variable.
if (GlobalVariableGet(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters") > 0) GlobalVariableDel(ObjPrefix + "MP-" + IntegerToString(ChartID()) + "-Parameters");
return true;
}
bool DeleteSettingsFile()
{
string fn_with_path = "MP_Settings\\" + m_FileName;
if (!FileIsExist(fn_with_path)) return false; // Nothing to delete.
if (!FileDelete(fn_with_path))
{
Print("Failed to delete settings file: " + m_FileName + ". Error: " + IntegerToString(GetLastError()));
return false;
}
Print("Settings file deleted.");
return true;
}
int Initialize()
{
InitFailed = false;
// Re-initialize global variables in case this function is called from OnChartEvent().
FirstRunDone = false;
Timer = 0;
NeedToRestartDrawing = false;
CleanedUpOn = 0;
LastAlertTime_CandleCross = 0;
LastAlertTime_GapCross = 0;
LastAlertTime = 0;
Close_prev = EMPTY_VALUE;
ArrowsCounter = 0;
CurrentBarDirection = Neutral;
PreviousBarDirection = Neutral;
NeedToReviewColors = false;
IntradayCrossSessionDefined = -1;
SessionsNumber = 0;
mpr_total = 0;
LastRecalculationTime = 0;
HiddenObjectsDrawn = false;
// Sessions to count for the object creation.
_SessionsToCount = SessionsToCount;
_SaturdaySunday = SaturdaySunday;
// Resolve TPO timeframe: use chart's if PERIOD_CURRENT or if selected is lower than chart's.
_TPOTimeframe = (TPOTimeframe == PERIOD_CURRENT) ? Period() : TPOTimeframe;
if (PeriodSeconds(_TPOTimeframe) < PeriodSeconds()) _TPOTimeframe = Period();
TPOSize = (int)(PeriodSeconds(_TPOTimeframe) / PeriodSeconds());
if (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_D1)) _SaturdaySunday = Saturday_Sunday_Normal_Days; // Cannot distinct between normal days and Sat/Sun sessions if timeframe is higher than daily.
if (TPOSize < 1) TPOSize = 1;
// Check for user Session settings.
if (_Session == Daily)
{
Suffix = "_D";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_M5)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_M30)))
{
string alert_text = "Timeframe should be between M5 and M30 for a Daily session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Weekly)
{
Suffix = "_W";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_M30)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_H4)))
{
string alert_text = "Timeframe should be between M30 and H4 for a Weekly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Monthly)
{
Suffix = "_M";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_H1)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_D1)))
{
string alert_text = "Timeframe should be between H1 and D1 for a Monthly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Quarterly)
{
Suffix = "_Q";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_H4)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_D1)))
{
string alert_text = "Timeframe should be between H4 and D1 for a Quarterly session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Semiannual)
{
Suffix = "_S";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_H4)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_W1)))
{
string alert_text = "Timeframe should be between H4 and W1 for a Semiannual session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Annual)
{
Suffix = "_A";
if ((PeriodSeconds(_TPOTimeframe) < PeriodSeconds(PERIOD_H4)) || (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_W1)))
{
string alert_text = "Timeframe should be between H4 and W1 for an Annual session.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if (_Session == Intraday)
{
if (PeriodSeconds(_TPOTimeframe) > PeriodSeconds(PERIOD_M30))
{
string alert_text = "Timeframe should not be higher than M30 for an Intraday sessions.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
// Check if intraday user settings are valid.
IntradaySessionCount = 0;
if (!CheckIntradaySession(EnableIntradaySession1, IntradaySession1StartTime, IntradaySession1EndTime, IntradaySession1ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession2, IntradaySession2StartTime, IntradaySession2EndTime, IntradaySession2ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession3, IntradaySession3StartTime, IntradaySession3EndTime, IntradaySession3ColorScheme)) return INIT_PARAMETERS_INCORRECT;
if (!CheckIntradaySession(EnableIntradaySession4, IntradaySession4StartTime, IntradaySession4EndTime, IntradaySession4ColorScheme)) return INIT_PARAMETERS_INCORRECT;
// Warn user about Intraday mode
if (IntradaySessionCount == 0)
{
string alert_text = "Enable at least one intraday session if you want to use Intraday mode.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
}
else if ((_Session == Rectangle) && (SeamlessScrollingMode)) // No point in seamless scrolling mode with rectangle sessions.
{
string alert_text = "Seamless scrolling mode doesn't work with Rectangle sessions.";
if (!DisableAlertsOnWrongTimeframes) Alert(alert_text);
else Print("Initialization failed: " + alert_text);
InitFailed = true; // Soft INIT_FAILED.
}
// Indicator Name.
IndicatorSetString(INDICATOR_SHORTNAME, ObjPrefix + "MarketProfile " + EnumToString(_Session));
// Adaptive point multiplier. Calculate based on number of digits in the quote (before plus after the dot).
if (PointMultiplier == 0)
{
double quote;
bool success = SymbolInfoDouble(Symbol(), SYMBOL_ASK, quote);
if (!success)
{
Print("Failed to get price data. Error #", GetLastError(), ". Using PointMultiplier = 1.");
PointMultiplier_calculated = 1;
}
else
{
string s = DoubleToString(quote, _Digits);
StringReplace(s, "-", ""); // Remove the minus sign for a negative price.
int total_digits = StringLen(s);
// If there is a dot in a quote.
if (StringFind(s, ".") != -1) total_digits--; // Decrease the count of digits by one.
if (total_digits <= 5) PointMultiplier_calculated = 1;
else PointMultiplier_calculated = (int)MathPow(10, total_digits - 5);
}
}
else // Normal point multiplier.
{
PointMultiplier_calculated = PointMultiplier;
}
// Based on number of digits in PointMultiplier_calculated. -1 because if PointMultiplier_calculated < 10, it does not modify the number of digits.
DigitsM = _Digits - (StringLen(IntegerToString(PointMultiplier_calculated)) - 1);
onetick = NormalizeDouble(_Point * PointMultiplier_calculated, DigitsM);
// Adjust for TickSize granularity if needed.
double TickSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);
if (onetick < TickSize)
{
DigitsM = _Digits - (StringLen(IntegerToString((int)MathRound(TickSize / _Point))) - 1);
onetick = NormalizeDouble(TickSize, DigitsM);
}
// Get color scheme from user input.
CurrentColorScheme = ColorScheme;
// To clean up potential leftovers when applying a chart template.
ObjectCleanup();
// Check if user wants Session mode as Rectangle or if it is a right-to-left session, or if rays should be constantly monitored, or seamless scrolling is on.
if ((_Session == Rectangle) || (RightToLeft) || (HideRaysFromInvisibleSessions) || (SeamlessScrollingMode))
{
EventSetMillisecondTimer(1000);
}
// Better do this unconditionally to avoid buffer errors.
SetIndexBuffer(0, DevelopingPOC, INDICATOR_DATA);
ArraySetAsSeries(DevelopingPOC, true);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_ARROW, 167);
SetIndexBuffer(1, DevelopingVAH, INDICATOR_DATA);
ArraySetAsSeries(DevelopingVAH, true);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(1, PLOT_ARROW, 167);
SetIndexBuffer(2, DevelopingVAL, INDICATOR_DATA);
ArraySetAsSeries(DevelopingVAL, true);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(2, PLOT_ARROW, 167);
ValueAreaPercentage_double = ValueAreaPercentage * 0.01;
// Create or remove the toggle button.
if (ShowToggleButton)
{
CreateToggleButton();
}
else
{
ObjectDelete(ChartID(), ToggleButtonName);
}
// If the indicator was hidden (restored from settings), suppress buffer plots.
if (IndicatorHidden)
{
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_NONE);
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_NONE);
PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE);
}
// Initialization successful
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Creates the toggle button on the chart. |
//+------------------------------------------------------------------+
void CreateToggleButton()
{
int button_width = 32;
int button_height = 18;
int button_spacing = 1;
int x_margin = (ToggleButtonCorner == CORNER_LEFT_UPPER || ToggleButtonCorner == CORNER_LEFT_LOWER) ? 5 : 5 + button_width;
int base_y = (ToggleButtonCorner == CORNER_LEFT_UPPER || ToggleButtonCorner == CORNER_RIGHT_UPPER) ? 25 : 5 + button_height;
int y_pos = base_y;
// Check if another MP on/off button already exists at that position.
int obj_total = ObjectsTotal(ChartID(), -1, OBJ_BUTTON);
for (int i = 0; i < obj_total; i++)
{
string name = ObjectName(ChartID(), i, -1, OBJ_BUTTON);
if (name == ToggleButtonName) continue; // Skip own button.
int len = StringLen(name);
if (len < 9) continue; // "_MPToggle" is 9 characters.
if (StringSubstr(name, len - 9) != "_MPToggle") continue; // Not a Market Profile toggle button.
if ((ENUM_BASE_CORNER)ObjectGetInteger(ChartID(), name, OBJPROP_CORNER) != ToggleButtonCorner) continue; // Not the same chart corner.
if (ObjectGetInteger(ChartID(), name, OBJPROP_YDISTANCE) == y_pos) // Position already taken.
{
y_pos += button_height + button_spacing; // Try next one.
}
else
{
break; // Position is available, use the current y_pos.
}
}
if (ObjectFind(ChartID(), ToggleButtonName) < 0)
{
ObjectCreate(ChartID(), ToggleButtonName, OBJ_BUTTON, 0, 0, 0);
}
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_CORNER, ToggleButtonCorner);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_XDISTANCE, x_margin);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_YDISTANCE, y_pos);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_XSIZE, button_width);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_YSIZE, button_height);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_FONTSIZE, 7);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_HIDDEN, true);
UpdateToggleButton();
}
//+------------------------------------------------------------------+
//| Updates the toggle button appearance based on visibility state. |
//+------------------------------------------------------------------+
void UpdateToggleButton()
{
if (ObjectFind(ChartID(), ToggleButtonName) < 0) return;
string label = (InstancePrefix != "") ? InstancePrefix : "MP";
if (IndicatorHidden)
{
ObjectSetString(ChartID(), ToggleButtonName, OBJPROP_TEXT, label);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BGCOLOR, clrDarkGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_COLOR, clrGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BORDER_COLOR, clrDimGray);
}
else
{
ObjectSetString(ChartID(), ToggleButtonName, OBJPROP_TEXT, label);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BGCOLOR, C'48,48,48');
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_COLOR, clrLightGray);
ObjectSetInteger(ChartID(), ToggleButtonName, OBJPROP_BORDER_COLOR, clrGray);
}
}
//+------------------------------------------------------------------+
//| Checks if a chart object belongs to this indicator instance. |
//+------------------------------------------------------------------+
bool IsOwnObject(const string name)
{
// Never toggle the button itself.
if (name == ToggleButtonName) return false;
if (ObjPrefix != "")
{
// All indicator objects (except alert arrows) start with ObjPrefix.
if (StringSubstr(name, 0, StringLen(ObjPrefix)) == ObjPrefix) return true;
// Alert arrow objects start with "ArrCC"/"ArrGC"/"ArrPB" followed by ObjPrefix.
if (((StringSubstr(name, 0, 5) == "ArrCC") || (StringSubstr(name, 0, 5) == "ArrGC") || (StringSubstr(name, 0, 5) == "ArrPB")) &&
(StringSubstr(name, 5, StringLen(ObjPrefix)) == ObjPrefix))
return true;
return false;
}
// When ObjPrefix is empty, indicator objects have OBJPROP_HIDDEN == true.
// This covers histogram dots, medians, VA lines, rays, key values, single prints, and TPO counts.
// User-created MPR rectangles have OBJPROP_HIDDEN == false, so they are safely excluded.
if (ObjectGetInteger(ChartID(), name, OBJPROP_HIDDEN) == true) return true;
// Alert arrows do not have OBJPROP_HIDDEN set, so check by their name prefix.
if ((StringSubstr(name, 0, 5) == "ArrCC") || (StringSubstr(name, 0, 5) == "ArrGC") || (StringSubstr(name, 0, 5) == "ArrPB")) return true;
return false;
}
//+------------------------------------------------------------------+
//| Hides all chart objects belonging to this indicator instance. |
//+------------------------------------------------------------------+
void HideOwnObjects()
{
int obj_total = ObjectsTotal(ChartID());
for (int i = obj_total - 1; i >= 0; i--)
{
string name = ObjectName(ChartID(), i);
if (!IsOwnObject(name)) continue;
ObjectSetInteger(ChartID(), name, OBJPROP_TIMEFRAMES, OBJ_NO_PERIODS);
}
}
//+------------------------------------------------------------------+
//| Toggles visibility of all indicator objects on the chart. |
//+------------------------------------------------------------------+
void ToggleIndicatorVisibility()
{
IndicatorHidden = !IndicatorHidden;
long timeframes = IndicatorHidden ? OBJ_NO_PERIODS : OBJ_ALL_PERIODS;
// Toggle all chart objects belonging to this indicator.
int obj_total = ObjectsTotal(ChartID());
for (int i = obj_total - 1; i >= 0; i--)
{
string name = ObjectName(ChartID(), i);
if (!IsOwnObject(name)) continue;
ObjectSetInteger(ChartID(), name, OBJPROP_TIMEFRAMES, timeframes);
}
// Toggle indicator buffer plots.
if (IndicatorHidden)
{
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_NONE);
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_NONE);
PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE);
}
else
{
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_ARROW);
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_ARROW);
PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_ARROW);
}
UpdateToggleButton();
SaveSettingsOnDisk();
ChartRedraw();
}
void Deinitialize()
{
if (_Session == Rectangle)
{
for (int i = 0; i < mpr_total; i++)
{
ObjectCleanup(MPR_Array[i].name + "_");
delete MPR_Array[i];
}
}
else ObjectCleanup();
}
int OnCalculateMain(const int rates_total, const int prev_calculated)
{
// New bars arrived?
// Need to reset buffers even if they are not used because otherwise there will be some garbage values in MT5.
if ((rates_total - prev_calculated > 1) && (CleanedUpOn != rates_total))
{
// Initialize the indicator buffers.
for (int i = prev_calculated; i < rates_total; i++)
{
DevelopingPOC[i] = EMPTY_VALUE;
DevelopingVAH[i] = EMPTY_VALUE;
DevelopingVAL[i] = EMPTY_VALUE;
}
if ((prev_calculated == 0) && (_Session == Rectangle)) // If prev_calculated got reset for some reason, reset the rectangles.
{
for (int i = mpr_total - 1; i >= 0 ; i--)
{
MPR_Array[i].ResetPrevTime0();
}
}
CleanedUpOn = rates_total; // To prevent cleaning up the buffers again and again when the platform just starts.
}
// Skip processing when the indicator is hidden and objects have already been drawn.
if ((IndicatorHidden) && ((FirstRunDone) || (HiddenObjectsDrawn))) return rates_total;
CheckAlerts();
// Check if seamless scrolling mode should be on, else if user requests current session, else a specific date.
if (SeamlessScrollingMode)
{
int last_visible_bar = (int)ChartGetInteger(ChartID(), CHART_FIRST_VISIBLE_BAR) - (int)ChartGetInteger(ChartID(), CHART_WIDTH_IN_BARS) + 1;
if (last_visible_bar < 0) last_visible_bar = 0;
StartDate = iTime(Symbol(), Period(), last_visible_bar);
}
else if (StartFromCurrentSession) StartDate = iTime(Symbol(), Period(), 0);
else StartDate = StartFromDate;
// Adjust date if Ignore_Saturday_Sunday is set.
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Saturday? Switch to Friday.
if (TimeDayOfWeek(StartDate) == 6) StartDate -= 86400;
// Sunday? Switch to Friday too.
else if (TimeDayOfWeek(StartDate) == 0) StartDate -= 2 * 86400;
}
// If we calculate profiles for the past sessions, no need to run it again.
if ((FirstRunDone) && (StartDate != iTime(Symbol(), Period(), 0))) return rates_total;
// Delay the update of Market Profile if ThrottleRedraw is given.
if ((ThrottleRedraw > 0) && (Timer > 0))
{
if ((int)TimeLocal() - Timer < ThrottleRedraw) return rates_total;
}
// Calculate rectangle.
if (_Session == Rectangle) // Everything becomes very simple if rectangle sessions are used.
{
CheckRectangles(rates_total);
if ((IndicatorHidden) && (!HiddenObjectsDrawn))
{
HideOwnObjects();
HiddenObjectsDrawn = true;
}
Timer = (int)TimeLocal();
return rates_total;
}
// In MTF mode, verify that higher timeframe data is synchronized before cleaning up and redrawing.
// After reconnection from sleep mode, the HTF data may not be loaded yet. Proceeding would
// delete existing profiles (ObjectCleanup) and then redraw them incorrectly with incomplete data,
// resulting in missing older sessions and wiped Developing POC/VAH/VAL values.
if ((TPOSize > 1) && ((rates_total - prev_calculated > 1) || (NeedToRestartDrawing)))
{
if ((!SeriesInfoInteger(Symbol(), _TPOTimeframe, SERIES_SYNCHRONIZED)) || (iBars(Symbol(), _TPOTimeframe) <= 0))
{
return prev_calculated; // HTF data not ready yet. Retry on the next tick.
}
}
// Recalculate everything if there were missing bars or something like that. Or if RightToLeft is on and a new right-most session arrived.
if ((rates_total - prev_calculated > 1) || (NeedToRestartDrawing))
{
FirstRunDone = false;
ObjectCleanup();
NeedToRestartDrawing = false;
if (EnableDevelopingPOC)
{
// Initialize the DPOC buffers.
ArrayInitialize(DevelopingPOC, EMPTY_VALUE);
}
}
// Get start and end bar numbers of the given session.
int sessionend = FindSessionEndByDate(StartDate, rates_total); // Finding the session's right-most bar using the date of the previous session or starting date.
int sessionstart = FindSessionStart(sessionend, rates_total); // Finding the session's left-most bar using its end (right-most) bar.
if (sessionstart == -1)
{
Print("Something went wrong! Waiting for data to load.");
return prev_calculated;
}
int SessionToStart = 0;
// Clean up old profiles if their number exceeds the given SessionsToCount.
if ((EnableOldProfilesCleanup) && (FirstRunDone))
{
int max_sessions = _SessionsToCount;
if (_Session == Intraday) max_sessions *= IntradaySessionCount;
if (SessionsNumber > max_sessions)
{
ObjectCleanup();
FirstRunDone = false;
SessionsNumber = 0;
ArrayResize(RememberSessionMax, 0);
ArrayResize(RememberSessionMin, 0);
ArrayResize(RememberSessionStart, 0);
ArrayResize(RememberSessionSuffix, 0);
ArrayResize(RememberSessionEnd, 0);
if (EnableDevelopingPOC)
{
ArrayInitialize(DevelopingPOC, EMPTY_VALUE);
}
}
}
// If all sessions have already been counted, jump to the current one.
if (FirstRunDone) SessionToStart = _SessionsToCount - 1;
else
{
// Move back to the oldest session to count to start from it.
for (int i = 1; i < _SessionsToCount; i++)
{
sessionend = sessionstart + 1;
if (sessionend >= rates_total) return prev_calculated;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 0) || (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 6))
{
sessionend++;
if (sessionend >= rates_total) break;
}
}
sessionstart = FindSessionStart(sessionend, rates_total);
}
}
// We begin from the oldest session coming to the current session or to StartFromDate.
for (int i = SessionToStart; i < _SessionsToCount; i++)
{
if (_Session == Intraday)
{
if (!ProcessIntradaySession(sessionstart, sessionend, i, rates_total)) return 0;
}
else
{
if (_Session == Daily) Max_number_of_bars_in_a_session = PeriodSeconds(PERIOD_D1) / PeriodSeconds();
else if (_Session == Weekly) Max_number_of_bars_in_a_session = 604800 / PeriodSeconds();
else if (_Session == Monthly) Max_number_of_bars_in_a_session = 2678400 / PeriodSeconds();
else if (_Session == Quarterly) Max_number_of_bars_in_a_session = 8035200 / PeriodSeconds();
else if (_Session == Semiannual) Max_number_of_bars_in_a_session = 16070400 / PeriodSeconds();
else if (_Session == Annual) Max_number_of_bars_in_a_session = 31622400 / PeriodSeconds();
if (_SaturdaySunday == Append_Saturday_Sunday)
{
// The start is on Sunday - add remaining time.
if (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 0) Max_number_of_bars_in_a_session += (24 * 3600 - (TimeHour(iTime(Symbol(), Period(), sessionstart)) * 3600 + TimeMinute(iTime(Symbol(), Period(), sessionstart)) * 60)) / PeriodSeconds();
// The end is on Saturday. +1 because even 0:00 bar deserves a bar.
if (TimeDayOfWeek(iTime(Symbol(), Period(), sessionend)) == 6) Max_number_of_bars_in_a_session += ((TimeHour(iTime(Symbol(), Period(), sessionend)) * 3600 + TimeMinute(iTime(Symbol(), Period(), sessionend)) * 60)) / PeriodSeconds() + 1;
}
if (!ProcessSession(sessionstart, sessionend, i, rates_total)) return 0;
}
// Go to the newer session only if there is one or more left.
if (_SessionsToCount - i > 1)
{
sessionstart = sessionend - 1;
if (_SaturdaySunday == Ignore_Saturday_Sunday)
{
// Pass through Sunday and Saturday.
while ((TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 0) || (TimeDayOfWeek(iTime(Symbol(), Period(), sessionstart)) == 6))
{
sessionstart--;
if (sessionstart == 0) break;
}
}
sessionend = FindSessionEndByDate(iTime(Symbol(), Period(), sessionstart), rates_total);
}
}
if ((ShowValueAreaRays != None) || (ShowMedianRays != None) || ((HideRaysFromInvisibleSessions || SPRaysUntilIntersection != Stop_No_Rays) && (SinglePrintRays))) CheckRays();
FirstRunDone = true;
// If drawn while hidden, hide all newly created objects so they are ready for instant reveal on toggle.
if ((IndicatorHidden) && (!HiddenObjectsDrawn))
{
HideOwnObjects();
HiddenObjectsDrawn = true;
}
Timer = (int)TimeLocal();
return rates_total;
}
// iBarShift function with custom search for the bar when standard iBarShift fails.
int iBarShiftCustom(string symbol, ENUM_TIMEFRAMES tf, datetime time, bool exact = false)
{
int i = iBarShift(symbol, tf, time); // Try traditional first.
if (i >= 0) return i; // Success.
else i = 0; // Failed, start from zero.
int bars = iBars(symbol, tf);
while (iTime(symbol, tf, i) > time)
{
i++;
if (i >= bars) return -1;
}
if (exact && iTime(symbol, tf, i) < time) return -1; // Failed to find the exact match.
return i;
}
//+------------------------------------------------------------------+
================================================
FILE: README.md
================================================
[](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md)
# Market Profile
Market Profile indicator for MT4, MT5, and cTrader by EarnForex.com.
Market Profile shows where the price has spent more time, highlighting important levels that can be used in trading.
.png)
Detailed description of indicator can be found here:
https://www.earnforex.com/indicators/MarketProfile/
Installation instructions:
https://www.earnforex.com/guides/metatrader-indicators-installation-tutorial/
Contributions in form of discussions and pull requests are welcome!