//+------------------------------------------------------------------+ //| Twiggs Money Flow - OHLC Smoothed Edition | //| Version 3.20 | //| | //| Features: | //| 1. Optional pre-smoothing of Open, High, Low and Close. | //| 2. The same selected MA method and period are applied to OHLC. | //| 3. True High/Low are then built from smoothed High/Low and the | //| previous smoothed Close. | //| 4. Selectable MA method for Twiggs numerator and denominator. | //| 5. Tick volume is used for Forex and other tick-volume markets. | //| 6. Optional Z-Score normalization of the final raw TMF output. | //| 7. Selectable SMA, EMA, Wilder SMMA and VWMA Z-Score methods. | //| 8. MaxBarsToProcess limits plotted history while extra bars are | //| calculated internally to warm up recursive averages. | //+------------------------------------------------------------------+ #property strict #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 clrDeepSkyBlue #property indicator_width1 2 #property indicator_style1 STYLE_SOLID #property indicator_level1 2.0 #property indicator_level2 1.0 #property indicator_level3 0.0 #property indicator_level4 -1.0 #property indicator_level5 -2.0 #property indicator_levelcolor clrDimGray #property indicator_levelstyle STYLE_DOT //--- Moving average methods enum ENUM_TMF_MA_METHOD { MA_SMA = 0, MA_EMA, MA_SMMA_Wilder, MA_LWMA, MA_VWMA }; //--- Z-Score center and dispersion calculation methods. enum ENUM_TMF_ZSCORE_METHOD { ZSCORE_SMA = 0, ZSCORE_EMA, ZSCORE_SMMA_Wilder, ZSCORE_VWMA }; //--- Output mode //--- Raw mode displays the original OHLC-smoothed TMF ratio. //--- Z-Score mode standardizes the final TMF series over a rolling window. enum ENUM_TMF_OUTPUT_MODE { OUTPUT_RAW = 0, OUTPUT_ZSCORE = 1 }; //--- General calculation settings input int MaxBarsToProcess = 5000; //--- OHLC pre-smoothing settings input bool EnableOHLCPreSmoothing = true; input int OHLCPreSmoothPeriod = 60; input ENUM_TMF_MA_METHOD OHLCPreSmoothMethod = MA_VWMA; //--- Twiggs Money Flow settings input int TMFPeriod = 10; input ENUM_TMF_MA_METHOD TMFSmoothingMethod = MA_VWMA; //--- Output normalization settings input ENUM_TMF_OUTPUT_MODE OutputMode = OUTPUT_ZSCORE; input int ZScorePeriod = 60; input ENUM_TMF_ZSCORE_METHOD ZScoreMethod = ZSCORE_SMA; //--- Indicator buffer double TMFBuffer[]; double RawTMF[]; double RawTMFSquared[]; double ZScoreMean[]; double ZScoreSecondMoment[]; //--- Internal calculation arrays double SmoothedOpen[]; double SmoothedHigh[]; double SmoothedLow[]; double SmoothedClose[]; double TickVolumeData[]; double MoneyFlowVolume[]; double SmoothedMoneyFlowVolume[]; double SmoothedTickVolume[]; //+------------------------------------------------------------------+ //| Calculate a moving average on series arrays | //| | //| Arrays are series: index 0 is the current bar. | //| oldestSourceShift is the oldest index with valid source data. | //| VWMA uses tick volume as its weighting series. | //+------------------------------------------------------------------+ void CalculateMovingAverage(const double &source[], const double &weight[], const int oldestSourceShift, const int period, const ENUM_TMF_MA_METHOD method, double &destination[]) { int sourceTotal = ArraySize(source); int destinationTotal = ArraySize(destination); ArrayInitialize(destination, EMPTY_VALUE); if(sourceTotal <= 0 || destinationTotal <= 0 || period < 1) return; if(oldestSourceShift < period - 1 || oldestSourceShift >= sourceTotal) return; if(oldestSourceShift >= destinationTotal) return; int firstValidShift = oldestSourceShift - period + 1; //--- SMA, LWMA and VWMA are calculated directly for every bar. if(method == MA_SMA || method == MA_LWMA || method == MA_VWMA) { for(int shift = firstValidShift; shift >= 0; shift--) { double weightedSum = 0.0; double weightSum = 0.0; double simpleSum = 0.0; for(int j = 0; j < period; j++) { double value = source[shift + j]; simpleSum += value; if(method == MA_LWMA) { double linearWeight = (double)(period - j); weightedSum += value * linearWeight; weightSum += linearWeight; } else if(method == MA_VWMA) { double volumeWeight = weight[shift + j]; weightedSum += value * volumeWeight; weightSum += volumeWeight; } } if(method == MA_SMA) { destination[shift] = simpleSum / (double)period; } else if(weightSum > 0.0) { destination[shift] = weightedSum / weightSum; } else { //--- Safe fallback when weighting data is unavailable. destination[shift] = simpleSum / (double)period; } } return; } //--- EMA and Wilder SMMA are seeded with an SMA, then calculated //--- from older bars to newer bars (descending series index). double seedSum = 0.0; for(int k = 0; k < period; k++) seedSum += source[firstValidShift + k]; destination[firstValidShift] = seedSum / (double)period; if(method == MA_EMA) { double alpha = 2.0 / ((double)period + 1.0); for(int bar = firstValidShift - 1; bar >= 0; bar--) destination[bar] = alpha * source[bar] + (1.0 - alpha) * destination[bar + 1]; } else // MA_SMMA_Wilder { double divisor = (double)period; for(int bar = firstValidShift - 1; bar >= 0; bar--) destination[bar] = (source[bar] + (divisor - 1.0) * destination[bar + 1]) / divisor; } } //+------------------------------------------------------------------+ //| Initialization | //+------------------------------------------------------------------+ int OnInit() { if(MaxBarsToProcess < 0 || OHLCPreSmoothPeriod < 1 || TMFPeriod < 1 || ZScorePeriod < 2) return(INIT_PARAMETERS_INCORRECT); if(OHLCPreSmoothPeriod > 10000 || TMFPeriod > 10000 || ZScorePeriod > 10000) return(INIT_PARAMETERS_INCORRECT); SetIndexBuffer(0, TMFBuffer); ArraySetAsSeries(TMFBuffer, true); SetIndexLabel(0, "Twiggs Money Flow OHLC Smoothed"); SetIndexEmptyValue(0, EMPTY_VALUE); int drawBegin = TMFPeriod + (EnableOHLCPreSmoothing ? OHLCPreSmoothPeriod : 0) + 1; if(OutputMode == OUTPUT_ZSCORE) drawBegin += ZScorePeriod - 1; SetIndexDrawBegin(0, drawBegin); //--- Levels are intentionally not set programmatically here. //--- This allows MetaTrader to retain user edits made in the Levels tab. //--- Default Z-Score levels are declared with indicator_level properties. IndicatorDigits(4); string outputName = (OutputMode == OUTPUT_ZSCORE ? "Z-Score" : "Raw"); IndicatorShortName("Twiggs Money Flow OHLC Smoothed " + outputName + " (" + IntegerToString(TMFPeriod) + ")"); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Main calculation | //+------------------------------------------------------------------+ 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(rates_total < 2) { if(rates_total > 0) ArrayInitialize(TMFBuffer, EMPTY_VALUE); return(0); } //--- Explicitly enforce series indexing. ArraySetAsSeries(open, true); ArraySetAsSeries(high, true); ArraySetAsSeries(low, true); ArraySetAsSeries(close, true); ArraySetAsSeries(tick_volume, true); //--- Clear plotted and internal output arrays. ArrayInitialize(TMFBuffer, EMPTY_VALUE); if(ArrayResize(RawTMF, rates_total) != rates_total || ArrayResize(RawTMFSquared, rates_total) != rates_total || ArrayResize(ZScoreMean, rates_total) != rates_total || ArrayResize(ZScoreSecondMoment, rates_total) != rates_total) return(prev_calculated); ArraySetAsSeries(RawTMF, true); ArraySetAsSeries(RawTMFSquared, true); ArraySetAsSeries(ZScoreMean, true); ArraySetAsSeries(ZScoreSecondMoment, true); ArrayInitialize(RawTMF, EMPTY_VALUE); ArrayInitialize(RawTMFSquared, EMPTY_VALUE); ArrayInitialize(ZScoreMean, EMPTY_VALUE); ArrayInitialize(ZScoreSecondMoment, EMPTY_VALUE); int barsToPlot = rates_total; if(MaxBarsToProcess > 0 && MaxBarsToProcess < barsToPlot) barsToPlot = MaxBarsToProcess; int largestPeriod = TMFPeriod; if(EnableOHLCPreSmoothing && OHLCPreSmoothPeriod > largestPeriod) largestPeriod = OHLCPreSmoothPeriod; if(OutputMode == OUTPUT_ZSCORE && ZScorePeriod > largestPeriod) largestPeriod = ZScorePeriod; //--- Extra history warms up recursive averages outside the plotted range. int warmupBars = largestPeriod * 10 + 10; int barsForCalculation = barsToPlot + warmupBars; if(barsForCalculation > rates_total) barsForCalculation = rates_total; if(barsForCalculation < 2) return(rates_total); //--- Resize and configure internal arrays. if(ArrayResize(SmoothedOpen, barsForCalculation) != barsForCalculation || ArrayResize(SmoothedHigh, barsForCalculation) != barsForCalculation || ArrayResize(SmoothedLow, barsForCalculation) != barsForCalculation || ArrayResize(SmoothedClose, barsForCalculation) != barsForCalculation || ArrayResize(TickVolumeData, barsForCalculation) != barsForCalculation || ArrayResize(MoneyFlowVolume, barsForCalculation) != barsForCalculation || ArrayResize(SmoothedMoneyFlowVolume, barsForCalculation) != barsForCalculation || ArrayResize(SmoothedTickVolume, barsForCalculation) != barsForCalculation) return(prev_calculated); ArraySetAsSeries(SmoothedOpen, true); ArraySetAsSeries(SmoothedHigh, true); ArraySetAsSeries(SmoothedLow, true); ArraySetAsSeries(SmoothedClose, true); ArraySetAsSeries(TickVolumeData, true); ArraySetAsSeries(MoneyFlowVolume, true); ArraySetAsSeries(SmoothedMoneyFlowVolume, true); ArraySetAsSeries(SmoothedTickVolume, true); ArrayInitialize(SmoothedOpen, EMPTY_VALUE); ArrayInitialize(SmoothedHigh, EMPTY_VALUE); ArrayInitialize(SmoothedLow, EMPTY_VALUE); ArrayInitialize(SmoothedClose, EMPTY_VALUE); ArrayInitialize(TickVolumeData, 0.0); ArrayInitialize(MoneyFlowVolume, EMPTY_VALUE); ArrayInitialize(SmoothedMoneyFlowVolume, EMPTY_VALUE); ArrayInitialize(SmoothedTickVolume, EMPTY_VALUE); //--- Copy tick volume for the calculation range. for(int volumeShift = barsForCalculation - 1; volumeShift >= 0; volumeShift--) TickVolumeData[volumeShift] = (double)tick_volume[volumeShift]; //--- Stage 1: smooth all four OHLC components with identical settings. int oldestFlowShift = barsForCalculation - 2; if(EnableOHLCPreSmoothing) { CalculateMovingAverage(open, TickVolumeData, barsForCalculation - 1, OHLCPreSmoothPeriod, OHLCPreSmoothMethod, SmoothedOpen); CalculateMovingAverage(high, TickVolumeData, barsForCalculation - 1, OHLCPreSmoothPeriod, OHLCPreSmoothMethod, SmoothedHigh); CalculateMovingAverage(low, TickVolumeData, barsForCalculation - 1, OHLCPreSmoothPeriod, OHLCPreSmoothMethod, SmoothedLow); CalculateMovingAverage(close, TickVolumeData, barsForCalculation - 1, OHLCPreSmoothPeriod, OHLCPreSmoothMethod, SmoothedClose); //--- Reserve one older valid smoothed close for True Range. oldestFlowShift = barsForCalculation - OHLCPreSmoothPeriod - 1; } else { //--- With smoothing disabled, use the original OHLC candles. for(int copyShift = barsForCalculation - 1; copyShift >= 0; copyShift--) { SmoothedOpen[copyShift] = open[copyShift]; SmoothedHigh[copyShift] = high[copyShift]; SmoothedLow[copyShift] = low[copyShift]; SmoothedClose[copyShift] = close[copyShift]; } //--- Reserve one older close for the first True Range calculation. oldestFlowShift = barsForCalculation - 2; } if(oldestFlowShift < 0) return(rates_total); //--- Stage 2: calculate True-Range-based money flow from smoothed OHLC. //--- True High/Low use the current smoothed High/Low and previous //--- smoothed Close, keeping all price components on the same basis. for(int flowShift = oldestFlowShift; flowShift >= 0; flowShift--) { if(SmoothedOpen[flowShift] == EMPTY_VALUE || SmoothedHigh[flowShift] == EMPTY_VALUE || SmoothedLow[flowShift] == EMPTY_VALUE || SmoothedClose[flowShift] == EMPTY_VALUE || SmoothedClose[flowShift + 1] == EMPTY_VALUE) continue; double previousSmoothedClose = SmoothedClose[flowShift + 1]; double trueHigh = MathMax(SmoothedHigh[flowShift], previousSmoothedClose); double trueLow = MathMin(SmoothedLow[flowShift], previousSmoothedClose); double trueRange = trueHigh - trueLow; double moneyFlowMultiplier = 0.0; if(trueRange > 0.0) moneyFlowMultiplier = (2.0 * SmoothedClose[flowShift] - trueHigh - trueLow) / trueRange; //--- Keep the normalized multiplier inside its theoretical bounds. if(moneyFlowMultiplier > 1.0) moneyFlowMultiplier = 1.0; else if(moneyFlowMultiplier < -1.0) moneyFlowMultiplier = -1.0; MoneyFlowVolume[flowShift] = moneyFlowMultiplier * TickVolumeData[flowShift]; } //--- Stage 3: independently smooth money-flow volume and tick volume. CalculateMovingAverage(MoneyFlowVolume, TickVolumeData, oldestFlowShift, TMFPeriod, TMFSmoothingMethod, SmoothedMoneyFlowVolume); CalculateMovingAverage(TickVolumeData, TickVolumeData, oldestFlowShift, TMFPeriod, TMFSmoothingMethod, SmoothedTickVolume); //--- Stage 4: final normalized Twiggs Money Flow ratio. for(int outputShift = barsForCalculation - 1; outputShift >= 0; outputShift--) { if(SmoothedMoneyFlowVolume[outputShift] == EMPTY_VALUE || SmoothedTickVolume[outputShift] == EMPTY_VALUE) continue; double volumeDenominator = SmoothedTickVolume[outputShift]; if(volumeDenominator > 0.0) RawTMF[outputShift] = SmoothedMoneyFlowVolume[outputShift] / volumeDenominator; else RawTMF[outputShift] = 0.0; } //--- Stage 5: optionally normalize the final TMF series with a //--- rolling population Z-Score. The raw TMF calculation is unchanged. //--- The selected method is applied consistently to the first and second moments. if(OutputMode == OUTPUT_RAW) { for(int rawShift = barsToPlot - 1; rawShift >= 0; rawShift--) TMFBuffer[rawShift] = RawTMF[rawShift]; } else { //--- Build the squared raw-TMF series for a consistent weighted //--- variance: Var(X) = MA(X*X) - MA(X)*MA(X). int oldestRawShift = oldestFlowShift - TMFPeriod + 1; if(oldestRawShift < 0) oldestRawShift = 0; for(int squareShift = oldestRawShift; squareShift >= 0; squareShift--) { if(RawTMF[squareShift] != EMPTY_VALUE) RawTMFSquared[squareShift] = RawTMF[squareShift] * RawTMF[squareShift]; } //--- Translate the selected input method to the common MA engine. ENUM_TMF_MA_METHOD zMethod = MA_SMA; if(ZScoreMethod == ZSCORE_EMA) zMethod = MA_EMA; else if(ZScoreMethod == ZSCORE_SMMA_Wilder) zMethod = MA_SMMA_Wilder; else if(ZScoreMethod == ZSCORE_VWMA) zMethod = MA_VWMA; //--- Apply identical weighting to first and second moments. CalculateMovingAverage(RawTMF, TickVolumeData, oldestRawShift, ZScorePeriod, zMethod, ZScoreMean); CalculateMovingAverage(RawTMFSquared, TickVolumeData, oldestRawShift, ZScorePeriod, zMethod, ZScoreSecondMoment); for(int zShift = barsToPlot - 1; zShift >= 0; zShift--) { if(RawTMF[zShift] == EMPTY_VALUE || ZScoreMean[zShift] == EMPTY_VALUE || ZScoreSecondMoment[zShift] == EMPTY_VALUE) continue; double mean = ZScoreMean[zShift]; double variance = ZScoreSecondMoment[zShift] - mean * mean; //--- Protect against tiny negative values caused by rounding. if(variance < 0.0) variance = 0.0; if(variance > 0.0) TMFBuffer[zShift] = (RawTMF[zShift] - mean) / MathSqrt(variance); else TMFBuffer[zShift] = 0.0; } } return(rates_total); } //+------------------------------------------------------------------+