Category Archives: Code

Quick Stop Loss Kata Implementation

This was a quick implementation of a slight variant of the stop loss kata. There are some easier ways it can be built that don’t use state. They are however trickier to work with.

class stoploss {
   private Dictionary<Guid, decimal> fifteen = new Dictionary>Guid, decimal>()
   private Dictionary<Guid, decimal> thirty = new Dictionary>Guid, decimal>();;
   bool alive = true;
   decimal price
   Guid id;

   public stoploss(PositionAcquiredMessage m) {
      id = m.PositionId;
   }

   public void Consume(PriceChangeMessage m) {
       fifteen.Add(m.Id, m.Price);
       thirty.Add(m.Id, m.Price);
       Raise(SendMeInNSeconds(new RemoveFromFifteen(m.Id), 15);
       Raise(SendMeInNSeconds(new RemoveFromThirty(m.Id), 30);   }
}
   public void Consume(RemoveFromFifteen m) {
      fifteen.Remove(m.Id);
      CheckMove();
   }

   public void Consume(RemoveFromThirty m) {
      CheckSell();
      thtirty.Remove(m.Id);
   }

   void CheckMove() {
      if(fifteen.Values.Where(x => x > target).Count != fiften.Values.Count) return;
      price = fifteen.Values.Minimum();
   }

   void CheckSell() {
       if(!alive) return;
       if(!thirty.Where(x.Value > price * .95).Count() == 0) return;
       Raise(new SellPosition(this.Id));
       alive = false;
   }
}

The main “trick” here is that the little piece of code sends messages to its future self telling it to remove items from the two collections. If it has the two lists its very easy to see if prices have been sustained over a period of time.

Also consider how unit tests would work on this code. The concept of time has been removed from it. Time is now represented as sequences of messages. This is a key concept when moving to this style of development. Sequences of messages are easy to test, time is hard to test. Let’s solve easy problems.

You can get past this. You can do this kata without even having the state of the lists but its more tricky.

Do I need to point out how little code this is?

Follow

Get every new post delivered to your Inbox.

Join 7,607 other followers