Loading…

Return Math Helpers

Return arithmetic looks trivial right up until a data gap hands a function a zero opening price or a bad tick reports a non-positive quote. A plain percent-change formula divides by that zero and the equity report shows -nan or +inf for the rest of the run; a log return taken from a non-positive price is undefined for the same reason. This header puts a single guarded implementation of each conversion in one place instead of re-deriving the guard, correctly or not, at every call site that needs it. It also gets return compounding right. Summing a series of daily fractional returns overstates the true multi-period result the moment compounding starts to matter - the correct combination is the product of (1 + return) across the series, minus one. Log returns are the other way round: they sum directly, which is exactly why some callers prefer log space for multi-period work. Both are provided so a caller in either convention gets the arithmetic that actually matches their space, plus an annualise/de-annualise pair built on the same compounding formula. Notes and limitations All conversion functions are pure math over the numbers passed in - none of them read live market data, so they carry no repaint or feed-dependency risk of their own. Zero-guards return 0.0 (or a caller-supplied fallback for RmhSafeDivide) rather than raising a runtime error; a caller that needs to distinguish "genuinely zero" from "guarded because the input was invalid" should check its own inputs before calling. RmhCompoundReturns and RmhSumLogReturns assume the array already holds returns in chronological order - passing an unsorted or mis-ordered array compiles and runs fine but produces a meaningless combined figure.

Script · MT4 · v1.0 · Free

About Return Math Helpers

Return Math Helpers is a script for MetaTrader 4. It has 2 settings, such as From price and To price. MQL source code included.

Files in the download: ReturnMathHelpers.mqh, ReturnMathHelpers.txt, ReturnMathHelpersDemo.mq4.

Settings

SettingDefaultWhat it does
From price100.0starting price for the basic conversion demo
To price110.0ending price for the basic conversion demo

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Scripts.
  3. Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
  4. Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the script onto a chart to run it once.

Download the PDF guide

Tags: MT4 Script · MQL4 Source Code

MQL4 & MQL5 scripts · PolyMaria