The FIX (Financial Information Exchange) Protocol is an industry standard used by financial institutions to… guess what… exchange financial information.
A FIX message is simply a sequence of key-value pairs, each followed by a SOH (ASCII value 1) character. Since SOH is a non-printable character, FIX messages are often illustrated using another character, such as a pipe. The following is an example of a FIX message, taken from FIX Parser:
As you can see, key-value pairs are delimited by the pipe character (which would be a SOH character in a real FIX message). Note how there is also a pipe character at the very end. Keys are separated from values with an equals sign (=). The keys themselves are numbers; each number represents a particular field in the FIX protocol. For example, FIX Field 8 represents the FIX protocol as well as the beginning of a FIX message. The use of numbers instead of field names makes messages less readable, but keeps them small.
“The checksum of a FIX message is calculated by summing every byte of the message up to but not including the checksum field itself. This checksum is then transformed into a modulo 256 number for transmission and comparison. The checksum is calculated after all encryption is completed, i.e. the message as transmitted between parties is processed.
“For transmission, the checksum must be sent as printable characters, so the checksum is transformed into three ASCII digits.
“For example, if the checksum has been calculated to be 274 then the modulo 256 value is 18 (256 + 18 = 274). This value would be transmitted a |10=018| where “10=”is the tag for the checksum field.”
In C#, we can implement this as follows.
First, let’s create our test message. We start with a pipe-delimited representation (just because it’s more readable that way), without the checksum field, and then we swap out the pipes for SOH characters (\u0001). Since FIX uses an ASCII representation, we can easily get a byte representation of the message:
string message = "8=FIX.4.1|9=61|35=A|34=1|49=EXEC|52=20121105-23:24:06|" + "56=BANZAI|98=0|108=30|"; message = message.Replace('|', '\u0001'); byte messageBytes = Encoding.ASCII.GetBytes(message);
The algorithm itself is then easy to implement. We simply iterate over each byte, add its value to a running total, divide it by 256, and take the remainder:
for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256;
There’s nothing more to add – that’s the checksum. If you’re sending a FIX message, you’ll convert the value to a string and pad it with zeroes if necessary to make sure it’s exactly 3 characters:
string checksumStr = checksum.ToString().PadLeft(3, '0');
If you’re parsing a received message, you’ll want to compare the checksum you calculated to the one provided with the message, to make sure the message isn’t corrupt.