It wasn’t that bad, Nykredit only lost 650.000 USD but …

A couple of days ago, a Danish Finance Institution, Nykredit, was in the media due to a stock mistake: Stock mistake costs Nykredit millions. The mistake was that instead of selling 4 A.P. Møller - Mærsk B at 14.000 DKK/stock, the stock broker sold 14.000 shares to the price of 4 DKK/stock.

A bit of simple mathematics will show us how bad that deal was:

  • 14000 x 14000 - 14000 x 4 = 195.944.000 DKK

in looses, more or less 33 million dollars. The finance institution was lucky that the deal was made in the last five minutes before the close of trading, where all deal are secret and the final price is set when trading in closed, which in this case was 13.980 DKK/Stock. Nykredit only lost 3.780.000 DKK, about 650.000 USD, which given the circumstances wasn’t that bad.

You might be thinking: “How the heck can a Finance Institution make such a big mistake, aren’t these guys supposed to be looking after our money?” but then you also might think: “Well these greedy bastards had a lot to do with the financial crisis so …” The main issue here is, why would the stock broker even be allowed to make this kind of mistakes? The answer would be that most business critical solutions are still made with an old fashioned approach.

I will, in very few lines of F# code, show how this kind of mistakes would never be possible by using their Units of Measure to construct a very simple but correct and robust DSL (Domain specific language):

1
2
3
4
5
6
7
8
9
10
11
12
open System

[<Measure>] type DKK
[<Measure>] type STOCK

let priceMaerskB : int<DKK/STOCK> = 14000<DKK/STOCK>

let buyPrice  (stocks:int<STOCK>)                        = stocks*priceMaerskB
let sellPrice (stocks:int<STOCK>) (price:int<DKK/STOCK>) = stocks*price

buyPrice  4<STOCK>
sellPrice 4<STOCK> 13900<DKK/STOCK>

In the example above, the stock broker needs to explicitly assign to each of the used integers, a corresponding units of measure tag. The result is what we intended it to be, which we also don’t need to make any kind of unit test, as we have ensured that is not possible to represent an illegal statement with our domain:

[<Measure>]
type DKK
[<Measure>]
type STOCK
val priceMaerskB : int<DKK/STOCK> = 14000
val buyPrice : stocks:int<STOCK> -> int<DKK>
val sellPrice : stocks:int<STOCK> -> price:int<DKK/STOCK> -> int<DKK>
val it : int<DKK> = 56000
val it : int<DKK> = 55600

Sadly, there are still to many people, in charge, that live in the past and keep banging their heads against the same walls over and over again instead of taking a ladder and climb over them once and for all … Anyway, if you want to read a few testimonials on how using this kind of approach, please visit:

The funny stuff …

All