detecting certain simple pattern in the series of deals
<p>I need to detect series of deals in my program like that:</p>

<p>buy 100,
sell 98,
buy 100,
sell 99,
buy 100,
sell 99</p>

<p>(total result is negative)</p>

<p>This is an exceptional situation and almost certanly means that there is fatal error, so I'm using my filter to terminate program in that case. I wrote such class:</p>

<pre><code>using System;

namespace Commons
{
    public class UltimateLossTracker : Resetable
    {

        private Side lastOperation;
        private decimal lastPrice;

        private int count;
        private const int Threashold = 40;

        public UltimateLossTracker(int frequency) : base(frequency)
        {
        }

        protected override void DoReset()
        {
            count = 0;
        }

        public bool UltimateLoss(decimal price, Side operation)
        {
            bool loss = false;
            if (operation != lastOperation)
            {
                switch (operation)
                {
                    case Side.Buy:
                        loss = price &gt;= lastPrice;
                        break;
                    case Side.Sell:
                        loss = price &lt;= lastPrice;
                        break;
                }
            }
            lastOperation = operation;
            lastPrice = price;
            if (loss)
            {
                return ++count &gt; Threashold;
            }
            return false;
        }
    }
}
</code></pre>

<p>Of course it will not detect all situations but it will detect the most common. The question I have - how to make it thread-safe without adding <code>lock</code>? Method <code>UltimateLoss</code> can be called from different threads. Using <code>lock</code> is unacceptable due performance reason and I'm afraid it is not possible to make method thread-safe without <code>lock</code>.</p>

<p>Well probably someone can suggest completely another lock-free algorithm of detecting such "patterns" taking into account that deals may go from several threads parallel?</p>
