title: simple moving average of "live" stream - fast implementation
body: <p>In my trading application I have "live ticks" of stock prices. I need to maintain SMA. Let's assume I want SMA of 20 candles, where duration of each candle is 10 seconds. This means that</p>
  
  <p>Every 10 seconds I have "checkpoint" where:</p>
  
  <ol>
  <li>I "close" current candle and store <strong>average</strong> price for the last 10 seconds. Average is (max - min) / 2</li>
  <li>I "start" new candle and store <strong>last</strong> price.</li>
  <li>I clean-up "outdated" candle.</li>
  </ol>
  
  <p>Every tick:</p>
  
  <ol>
  <li>I update "last" price of current "forming" candle and recalculate SMA.</li>
  </ol>
  
  <p>So on any tick I need to "recalculate" SMA. In most cases only price of the last candle is changed (cause we using <strong>last</strong> price). Once per 10 seconds I need a little bit more extra work - I need to "forget" average of the outdated candle, and "store" average of "just created" candle.</p>
  
  <p>Can you suggest how to implement this with lowest latency? Low latency is primary requirement.</p>