//+------------------------------------------------------------------+
//|                                          TestOrderFlowDelta.mq5  |
//|                             Verification script for the project  |
//+------------------------------------------------------------------+
#property version     "1.00"
#property description "Runs deterministic tests on the pure project classes."

#include <OrderFlowDelta/OrderFlowTypes.mqh>
#include <OrderFlowDelta/TickClassifier.mqh>
#include <OrderFlowDelta/TickDeltaAggregator.mqh>
#include <OrderFlowDelta/TickDataReader.mqh>
#include <OrderFlowDelta/DivergenceDetector.mqh>

int g_pass=0;
int g_fail=0;

#define ASSERT(condition,message) CheckAssert((condition),(message),__LINE__)

//+------------------------------------------------------------------+
//| Records one check result                                         |
//+------------------------------------------------------------------+
void CheckAssert(const bool condition,const string message,const int line)
  {
   if(condition)
     {
      g_pass++;
      return;
     }
   g_fail++;
   PrintFormat("FAIL (line %d): %s",line,message);
  }

//+------------------------------------------------------------------+
//| Compares two doubles with a tolerance                            |
//+------------------------------------------------------------------+
bool NearlyEqual(const double first,const double second,const double tolerance=1.0e-9)
  {
   return(MathAbs(first-second)<=tolerance);
  }

//+------------------------------------------------------------------+
//| Builds a synthetic tick                                          |
//+------------------------------------------------------------------+
MqlTick MakeTick(const double bid,
                 const double last,
                 const ulong volume,
                 const double volume_real,
                 const ulong time_msc)
  {
   MqlTick tick;
   ZeroMemory(tick);
   tick.bid=bid;
   tick.ask=bid;
   tick.last=last;
   tick.volume=volume;
   tick.volume_real=volume_real;
   tick.time_msc=(long)time_msc;
   tick.time=(datetime)(time_msc/1000);
   return(tick);
  }

//+------------------------------------------------------------------+
//| Tick rule: up, down, unchanged, and the first tick               |
//+------------------------------------------------------------------+
void TestTickRule()
  {
   CTickClassifier classifier;
   ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_NONE,1.1)==OF_DIR_BUY,"up tick is a buy");
   ASSERT(classifier.ClassifyDirection(true,1.1,OF_DIR_NONE,1.0)==OF_DIR_SELL,"down tick is a sell");
   ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_BUY,1.0)==OF_DIR_BUY,"unchanged after buy repeats buy");
   ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_SELL,1.0)==OF_DIR_SELL,"unchanged after sell repeats sell");
   ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_NONE,1.0)==OF_DIR_NONE,"unchanged with no direction is unclassified");
   ASSERT(classifier.ClassifyDirection(false,0.0,OF_DIR_NONE,1.0)==OF_DIR_NONE,"first tick is unclassified");
   ASSERT(classifier.ClassifyDirection(false,0.0,OF_DIR_BUY,1.0)==OF_DIR_NONE,"no previous price ignores stale direction");
  }

//+------------------------------------------------------------------+
//| Price and volume extraction                                      |
//+------------------------------------------------------------------+
void TestExtraction()
  {
   CTickClassifier classifier;
   double value=0.0;
   MqlTick tick=MakeTick(1.2300,1.2345,5,0.0,1000);
   ASSERT(classifier.ExtractPrice(tick,OF_PRICE_LAST,value) && NearlyEqual(value,1.2345),"last price extracted");
   ASSERT(classifier.ExtractPrice(tick,OF_PRICE_BID,value) && NearlyEqual(value,1.2300),"bid price extracted");
   MqlTick zero_last=MakeTick(1.2300,0.0,5,0.0,1000);
   ASSERT(!classifier.ExtractPrice(zero_last,OF_PRICE_LAST,value) && NearlyEqual(value,0.0),"zero last price rejected");
   MqlTick zero_bid=MakeTick(0.0,1.2345,5,0.0,1000);
   ASSERT(!classifier.ExtractPrice(zero_bid,OF_PRICE_BID,value),"zero bid price rejected");
//--- volume modes
   ASSERT(classifier.ExtractVolume(tick,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,5.0),"integer tick volume used");
   MqlTick real_tick=MakeTick(1.0,1.0,2,2.5,1000);
   ASSERT(classifier.ExtractVolume(real_tick,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,2.5),"real volume preferred");
   MqlTick zero_volume=MakeTick(1.0,1.0,0,0.0,1000);
   ASSERT(!classifier.ExtractVolume(zero_volume,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,0.0),"zero volume field reports false");
   ASSERT(classifier.ExtractVolume(zero_volume,OF_VOL_TICK_COUNT,value) && NearlyEqual(value,1.0),"tick count mode returns one");
  }

//+------------------------------------------------------------------+
//| Aggregation of one synthetic bar and its identities              |
//+------------------------------------------------------------------+
void TestAggregation()
  {
   CTickDeltaAggregator aggregator;
   MqlTick ticks[];
   ArrayResize(ticks,6);
   ticks[0]=MakeTick(99.99,100.0,2,0.0,1000);
   ticks[1]=MakeTick(100.49,100.5,3,0.0,1001);
   ticks[2]=MakeTick(100.49,100.5,4,0.0,1002);
   ticks[3]=MakeTick(100.19,100.2,1,0.0,1003);
   ticks[4]=MakeTick(100.19,100.2,5,0.0,1004);
   ticks[5]=MakeTick(100.69,100.7,2,0.0,1005);
   CTickState state;
   CBarDelta bar;
   aggregator.AggregateTicks(ticks,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,bar);
   ASSERT(bar.data_complete,"bar is data complete");
   ASSERT(bar.tick_count==6 && bar.classified_count==5 && bar.unclassified_count==1,"tick counts");
   ASSERT(NearlyEqual(bar.buy_volume,9.0),"buy volume");
   ASSERT(NearlyEqual(bar.sell_volume,6.0),"sell volume");
   ASSERT(NearlyEqual(bar.unclassified_volume,2.0),"unclassified volume");
   ASSERT(NearlyEqual(bar.total_volume,17.0),"total volume");
   ASSERT(NearlyEqual(bar.buy_volume+bar.sell_volume+bar.unclassified_volume,bar.total_volume),"volume identity");
   ASSERT(NearlyEqual(bar.delta,bar.buy_volume-bar.sell_volume) && NearlyEqual(bar.delta,3.0),"delta identity");
   ASSERT(bar.delta_ratio_defined && NearlyEqual(bar.delta_ratio,3.0/17.0),"delta ratio");
   ASSERT(bar.end_state.has_price && NearlyEqual(bar.end_state.last_price,100.7) && bar.end_state.last_direction==OF_DIR_BUY,"end state");
  }

//+------------------------------------------------------------------+
//| Empty tick array gives a defined, zero-tick, ratio-undefined bar |
//+------------------------------------------------------------------+
void TestEmptyArray()
  {
   CTickDeltaAggregator aggregator;
   MqlTick ticks[];
   ArrayResize(ticks,0);
   CTickState state;
   CBarDelta bar;
   aggregator.AggregateTicks(ticks,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,bar);
   ASSERT(bar.data_complete && bar.tick_count==0,"empty array is a defined zero-tick bar");
   ASSERT(NearlyEqual(bar.delta,0.0) && NearlyEqual(bar.total_volume,0.0),"empty array has zero totals");
   ASSERT(!bar.delta_ratio_defined,"empty array leaves ratio undefined");
   ASSERT(!bar.end_state.has_price,"empty array leaves state empty");
  }

//+------------------------------------------------------------------+
//| State carry across two bars, and equality with a single pass     |
//+------------------------------------------------------------------+
void TestStateCarry()
  {
   CTickDeltaAggregator aggregator;
   MqlTick bar_a[];
   MqlTick bar_b[];
   MqlTick both[];
   ArrayResize(bar_a,2);
   ArrayResize(bar_b,2);
   ArrayResize(both,4);
   bar_a[0]=MakeTick(99.9,100.0,1,0.0,1000);
   bar_a[1]=MakeTick(100.3,100.4,1,0.0,1001);
   bar_b[0]=MakeTick(100.2,100.3,2,0.0,2000);
   bar_b[1]=MakeTick(100.2,100.3,1,0.0,2001);
   both[0]=bar_a[0];
   both[1]=bar_a[1];
   both[2]=bar_b[0];
   both[3]=bar_b[1];
   CTickState state;
   CBarDelta first_bar;
   CBarDelta second_bar;
   aggregator.AggregateTicks(bar_a,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,first_bar);
   ASSERT(NearlyEqual(first_bar.end_state.last_price,100.4) && first_bar.end_state.last_direction==OF_DIR_BUY,"first bar end state");
//--- the second bar starts from the stored end state of the first
   CTickState carried=first_bar.end_state;
   aggregator.AggregateTicks(bar_b,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,carried,second_bar);
   ASSERT(NearlyEqual(second_bar.sell_volume,3.0),"first tick of bar two is classified against bar one");
   ASSERT(second_bar.unclassified_count==0,"no unclassified ticks after carry");
//--- a fresh state would have lost that information
   CTickState fresh;
   CBarDelta isolated;
   aggregator.AggregateTicks(bar_b,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,fresh,isolated);
   ASSERT(NearlyEqual(isolated.unclassified_volume,3.0),"fresh state leaves the bar unclassified");
//--- chained bars equal one pass over all ticks
   CTickState single_state;
   CBarDelta single;
   aggregator.AggregateTicks(both,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,single_state,single);
   ASSERT(NearlyEqual(single.buy_volume,first_bar.buy_volume+second_bar.buy_volume),"chained buy equals single pass");
   ASSERT(NearlyEqual(single.sell_volume,first_bar.sell_volume+second_bar.sell_volume),"chained sell equals single pass");
   ASSERT(NearlyEqual(single.unclassified_volume,first_bar.unclassified_volume+second_bar.unclassified_volume),"chained unclassified equals single pass");
  }

//+------------------------------------------------------------------+
//| Time range boundaries                                            |
//+------------------------------------------------------------------+
void TestRange()
  {
   CTickDataReader reader;
   ulong from_a=0,to_a=0,from_b=0,to_b=0;
   ASSERT(reader.BuildRange(1000,1060,from_a,to_a),"range builds");
   ASSERT(reader.BuildRange(1060,1120,from_b,to_b),"next range builds");
   ASSERT(from_a==1000000 && to_a==1059999,"first range bounds");
   ASSERT(from_b==to_a+1,"adjacent bars leave no gap and no overlap");
   ASSERT(!reader.BuildRange(1060,1060,from_a,to_a),"empty range rejected");
   ASSERT(!reader.BuildRange(1060,1000,from_a,to_a),"reversed range rejected");
  }

//+------------------------------------------------------------------+
//| Cumulative series with an undefined bar and the daily reset      |
//+------------------------------------------------------------------+
void TestCumulative()
  {
   CTickDeltaAggregator aggregator;
   datetime base=(datetime)(86400*20);
   datetime times[6];
   times[0]=base+3600;
   times[1]=base+7200;
   times[2]=base+10800;
   times[3]=base+86400+3600;
   times[4]=base+86400+7200;
   times[5]=base+86400+10800;
   double delta[6]= {3.0,-2.0,0.0,4.0,1.0,-1.0};
   bool flags_ok[6]= {true,true,false,true,true,true};
   double cumulative[6];
   bool cumulative_defined[6];
//--- no reset
   ASSERT(aggregator.BuildCumulativeSeries(delta,flags_ok,times,0,6,false,cumulative,cumulative_defined),"cumulative builds");
   ASSERT(NearlyEqual(cumulative[0],3.0) && NearlyEqual(cumulative[1],1.0),"running total on defined bars");
   ASSERT(!cumulative_defined[2] && NearlyEqual(cumulative[2],1.0),"undefined bar is flagged and carries the total");
   ASSERT(NearlyEqual(cumulative[3],5.0) && NearlyEqual(cumulative[4],6.0) && NearlyEqual(cumulative[5],5.0),"total continues across days without reset");
//--- daily reset
   aggregator.BuildCumulativeSeries(delta,flags_ok,times,0,6,true,cumulative,cumulative_defined);
   ASSERT(NearlyEqual(cumulative[2],1.0),"day one is unchanged by the reset");
   ASSERT(NearlyEqual(cumulative[3],4.0) && NearlyEqual(cumulative[4],5.0) && NearlyEqual(cumulative[5],4.0),"total restarts on the first bar of the new day");
//--- tail recomputation equals the full pass
   cumulative[3]=-999.0;
   cumulative[4]=-999.0;
   cumulative[5]=-999.0;
   aggregator.BuildCumulativeSeries(delta,flags_ok,times,3,6,true,cumulative,cumulative_defined);
   ASSERT(NearlyEqual(cumulative[3],4.0) && NearlyEqual(cumulative[5],4.0),"tail recomputation matches");
   ASSERT(aggregator.IsDifferentDay(times[2],times[3]) && !aggregator.IsDifferentDay(times[0],times[1]),"day boundary helper");
  }

//+------------------------------------------------------------------+
//| Fills the baseline arrays used by the divergence tests           |
//+------------------------------------------------------------------+
void FillFlat(double &high[],double &low[],double &cumulative[],bool &flags_ok[])
  {
   ArrayResize(high,7);
   ArrayResize(low,7);
   ArrayResize(cumulative,7);
   ArrayResize(flags_ok,7);
   for(int i=0; i<7; i++)
     {
      high[i]=10.0;
      low[i]=5.0;
      cumulative[i]=0.0;
      flags_ok[i]=true;
     }
  }

//+------------------------------------------------------------------+
//| Divergence cases                                                 |
//+------------------------------------------------------------------+
void TestDivergence()
  {
   CDivergenceDetector detector;
   double high[],low[],cum[];
   bool flags_ok[];
//--- bearish: new high, lower cumulative delta than at the previous high
   FillFlat(high,low,cum,flags_ok);
   double bear_high[7]= {9,10,12,11,11,11.5,13};
   double bear_cum[7]= {0,10,50,30,20,25,40};
   for(int i=0; i<7; i++)
     {
      high[i]=bear_high[i];
      cum[i]=bear_cum[i];
     }
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_BEARISH,"bearish divergence");
//--- equal highs
   high[6]=12.0;
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal highs give no divergence");
   high[6]=13.0;
//--- equal delta
   cum[6]=50.0;
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal delta gives no divergence");
   cum[6]=40.0;
//--- insufficient lookback
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,3,5)==OF_DIV_NONE,"insufficient lookback gives no divergence");
//--- undefined cumulative delta at the signal bar
   flags_ok[6]=false;
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"undefined data gives no divergence");
//--- bullish: new low, higher cumulative delta than at the previous low
   FillFlat(high,low,cum,flags_ok);
   double bull_low[7]= {9,8,5,6,7,6.5,4};
   double bull_cum[7]= {0,-10,-50,-30,-20,-25,-30};
   for(int i=0; i<7; i++)
     {
      low[i]=bull_low[i];
      cum[i]=bull_cum[i];
     }
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_BULLISH,"bullish divergence");
   low[6]=5.0;
   ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal lows give no divergence");
  }

//+------------------------------------------------------------------+
//| Color index mapping, including the exact zero case               |
//+------------------------------------------------------------------+
void TestColorIndex()
  {
   CTickDeltaAggregator aggregator;
   ASSERT(aggregator.ColorIndexForDelta(true,5.0)==OF_COLOR_POSITIVE,"positive delta is green");
   ASSERT(aggregator.ColorIndexForDelta(true,-5.0)==OF_COLOR_NEGATIVE,"negative delta is red");
   ASSERT(aggregator.ColorIndexForDelta(true,0.0)==OF_COLOR_NEUTRAL,"exact zero delta is neutral");
   ASSERT(aggregator.ColorIndexForDelta(false,5.0)==OF_COLOR_NEUTRAL,"undefined delta is neutral");
  }

//+------------------------------------------------------------------+
//| Script entry point                                               |
//+------------------------------------------------------------------+
void OnStart()
  {
   g_pass=0;
   g_fail=0;
   TestTickRule();
   TestExtraction();
   TestAggregation();
   TestEmptyArray();
   TestStateCarry();
   TestRange();
   TestCumulative();
   TestDivergence();
   TestColorIndex();
   PrintFormat("TestOrderFlowDelta: %d passed, %d failed.",g_pass,g_fail);
   if(g_fail==0)
      Print("RESULT: PASS");
   else
      Print("RESULT: FAIL");
  }
//+------------------------------------------------------------------+