def encode(self, raw=False):
        """Convert message to on-the-wire FIX format.

        :param raw: If True, encode pairs exactly as provided.

        Unless 'raw' is set, this function will calculate and
        correctly set the BodyLength (9) and Checksum (10) fields, and
        ensure that the BeginString (8), Body Length (9), Message Type
        (35) and Checksum (10) fields are in the right positions.

        This function does no further validation of the message content."""

        buf = b""
        if raw:
            # Walk pairs, creating string.
            for tag, value in self.pairs:
                buf += tag + b'=' + value + SOH_STR

            return buf

        # Cooked.
        for tag, value in self.pairs:
            if int(tag) in (8, 9, 35, 10):
                continue
            buf += tag + b'=' + value + SOH_STR

        # Prepend the message type.
        if self.message_type is None:
            raise ValueError("No message type set")

        buf = b"35=" + self.message_type + SOH_STR + buf

        # Calculate body length.
        #
        # From first byte after body length field, to the delimiter
        # before the checksum (which shouldn't be there yet).
        body_length = len(buf)

        # Prepend begin-string and body-length.
        if not self.begin_string:
            raise ValueError("No begin string set")

        buf = b"8=" + self.begin_string + SOH_STR + \
              b"9=" + fix_val("%u" % body_length) + SOH_STR + \
              buf

        # Calculate and append the checksum.
        checksum = 0
        for c in buf:
            checksum += ord(c) if sys.version_info[0] == 2 else c
        buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR

        return buf
Convert message to on-the-wire FIX format.

        :param raw: If True, encode pairs exactly as provided.

        Unless 'raw' is set, this function will calculate and
        correctly set the BodyLength (9) and Checksum (10) fields, and
        ensure that the BeginString (8), Body Length (9), Message Type
        (35) and Checksum (10) fields are in the right positions.

        This function does no further validation of the message content.