Hello, hoping someone can help spot the bug in this rather simple code.
I can't seem to find the flaw.

All I am trying to do is optimize over a pair of variables, and dump a
database to a file that contains some stats for each winning pair.
Namely, I want to calculate the minimum distance between the Close and
FastMA, as well as the average distance - over all the Buys for each
pair of optimization variables.

While everything appears to work fine, the problem is that sometimes the
minimum is larger than the average! And of course, that cannot be.  If
you run an optimization and open up the resulting CSV file, you will see
what I mean.

I've been staring at this loop for hours, and just can't see how it can
be wrong. But of course it must be. It's probably something obvious that
my brain is overlooking. Any input much appreciated!


//
-----------------------------------------------------------------------
//                   SIMPLE TRADING SYSTEM
//
-----------------------------------------------------------------------

BuyPrice = SellPrice = ShortPrice = CoverPrice = Close;


Fast     = Optimize( "fast", 5, 5, 10, 1 );
Slow     = Optimize( "Slow", 15, 10, 15, 1 );

FastMA   = MA(C, Fast);
SlowMA   = MA(C, Slow);

Buy      = Cross( Close, FastMA);
Sell     = Cross( SlowMA, Close);

Short    = Sell;
Cover    = Buy;


//
-----------------------------------------------------------------------
//   DUMP STATS TO FILE: Distance between the Close and FastMA @ Buy
//
-----------------------------------------------------------------------


// For each Fast/Slow Pair buy, dump stats to a file.
// Find the Minimum and Average Distances for each Pair.


Distance      = Close - FastMA;

PairFrequency = 0;

DistanceMin   = DistanceSum = DistanceAvg = DistanceOld = 0;

for (i = 0; i < BarCount - 1; i++)
{
if(Buy[i])
{
    PairFrequency++;

    if(Distance[i] < DistanceOld)  DistanceMin = Distance[i];

    DistanceSum = DistanceSum + Distance[i];
    DistanceAvg = DistanceSum/PairFrequency;

    DistanceOld = Distance[i];
   }
}

fh = fopen( "C:\\DistanceStats.csv", "a" );  // a = appending, write our
stats to file

    if ( fh )
    {
     fputs( StrFormat( "%.0f,%.0f,%.0f,%.4f,%.4f\n", PairFrequency, Fast,
Slow, DistanceMin, DistanceAvg), fh );
     fclose( fh );
     }





Reply via email to