// One-shot signed binary FIX market-data client, using generated SBE Go codecs. package main import ( "bytes" "crypto" "crypto/ed25519" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/binary" "encoding/pem" "errors" "fmt" "io" "log" "math" "net" "os" "strings" "time" sbe "example.com/fixmd/kalshi_fix_sbe" ) func check(err error) { if err != nil { log.Fatal(err) } } func require(ok bool, message string) { if !ok { log.Fatal(message) } } type message interface { SbeTemplateId() uint16 SbeBlockLength() uint16 Encode(*sbe.SbeGoMarshaller, io.Writer, bool) error } type peer struct { net.Conn m *sbe.SbeGoMarshaller sendSeq, recvSeq uint32 } func (p *peer) send(m message, now time.Time) { p.sendSeq++ h := sbe.MessageHeader{BlockLength: m.SbeBlockLength(), TemplateId: m.SbeTemplateId(), SchemaId: 3, Version: 1, SeqNum: p.sendSeq, SendingTime: now.UnixMicro()} var payload bytes.Buffer check(h.Encode(p.m, &payload)) check(m.Encode(p.m, &payload, true)) require(payload.Len()+6 <= 2<<20, "frame too large") var frame bytes.Buffer check(binary.Write(&frame, binary.BigEndian, uint32(payload.Len()+6))) check(binary.Write(&frame, binary.BigEndian, uint16(0xeb50))) frame.Write(payload.Bytes()) _, err := io.Copy(p.Conn, &frame) check(err) } func (p *peer) receive() (sbe.MessageHeader, []byte) { var sofh [6]byte _, err := io.ReadFull(p.Conn, sofh[:]) check(err) size := binary.BigEndian.Uint32(sofh[:]) require(size >= 26 && size <= 2<<20 && binary.BigEndian.Uint16(sofh[4:]) == 0xeb50, "invalid SOFH") buf := make([]byte, size-6) _, err = io.ReadFull(p.Conn, buf) check(err) var h sbe.MessageHeader check(h.Decode(p.m, bytes.NewReader(buf), 1)) p.recvSeq++ require(h.SchemaId == 3 && h.Version == 1 && h.SeqNum == p.recvSeq && h.SeqNum <= math.MaxInt32, "unexpected profile or sequence") return h, buf[20:] } // Check group/variable lengths against the actual frame before the generated // struct decoder allocates the declared strings or number of levels. func decode(p *peer, h sbe.MessageHeader, b []byte, m interface { SbeBlockLength() uint16 Decode(*sbe.SbeGoMarshaller, io.Reader, uint16, uint16, bool) error }, levels bool, stringsCount int) { pos := int(h.BlockLength) require(h.BlockLength == m.SbeBlockLength() && pos <= len(b), "bad block length") if levels { require(len(b)-pos >= 6 && binary.LittleEndian.Uint16(b[pos:]) == 17, "bad level group") count := uint64(binary.LittleEndian.Uint32(b[pos+2:])) pos += 6 require(count <= uint64(len(b)-pos)/17, "truncated levels") pos += int(count) * 17 } for range stringsCount { require(len(b)-pos >= 4, "truncated string length") n := uint64(binary.LittleEndian.Uint32(b[pos:])) pos += 4 require(n <= uint64(len(b)-pos), "truncated string") pos += int(n) } require(pos == len(b), "trailing data") check(m.Decode(p.m, bytes.NewReader(b), h.Version, h.BlockLength, true)) } func sign(path, text string) string { buf, err := os.ReadFile(path) check(err) block, _ := pem.Decode(buf) require(block != nil, "invalid PEM") var key any if block.Type == "RSA PRIVATE KEY" { key, err = x509.ParsePKCS1PrivateKey(block.Bytes) } else { key, err = x509.ParsePKCS8PrivateKey(block.Bytes) } check(err) var sig []byte switch k := key.(type) { case ed25519.PrivateKey: sig = ed25519.Sign(k, []byte(text)) case *rsa.PrivateKey: digest := sha256.Sum256([]byte(text)) sig, err = rsa.SignPSS(rand.Reader, k, crypto.SHA256, digest[:], nil) check(err) default: check(errors.New("key must be Ed25519 or RSA")) } return base64.StdEncoding.EncodeToString(sig) } type level struct { price, qty int64 set bool } func (l level) String() string { if !l.set { return "-" } return fmt.Sprintf("%d,%d", l.price, l.qty) } type bestBook struct{ bid, offer level } func (b *bestBook) add(kind uint8, price, qty int64) { switch kind { case '0': if !b.bid.set || price > b.bid.price { b.bid = level{price, qty, true} } case '1': if !b.offer.set || price < b.offer.price { b.offer = level{price, qty, true} } default: log.Fatal("unexpected snapshot entry type") } } func main() { log.SetFlags(0) require(len(os.Args) == 7 || len(os.Args) == 8, "usage: fixmd HOST PORT KEY_ID KEY_PEM SYMBOL predictions|margin [TLS_SERVER_NAME]") host, port, id, key, symbol, product := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5], os.Args[6] profile := uint8(1) if product == "margin" { profile = 3 } else { require(product == "predictions", "unknown product") } serverName := host if len(os.Args) == 8 { serverName = os.Args[7] require(serverName != "", "empty TLS server name") } tlsCfg := &tls.Config{ServerName: serverName, MinVersion: tls.VersionTLS12} if path := os.Getenv("KALSHI_FIX_CA_FILE"); path != "" { data, err := os.ReadFile(path) check(err) tlsCfg.RootCAs = x509.NewCertPool() require(tlsCfg.RootCAs.AppendCertsFromPEM(data), "invalid CA PEM") } conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 10 * time.Second}, "tcp", net.JoinHostPort(host, port), tlsCfg) check(err) defer conn.Close() check(conn.SetDeadline(time.Now().Add(20 * time.Second))) p := peer{Conn: conn, m: sbe.NewSbeGoMarshaller()} now := time.Now().UTC().Truncate(time.Millisecond) logon := sbe.Logon{Profile: profile, Reset: 1, HeartbeatSeconds: 30, SenderCompId: []byte(id), TargetCompId: []byte("KalshiMD")} var unsigned bytes.Buffer check(logon.Encode(p.m, &unsigned, true)) options := unsigned.Bytes()[:logon.SbeBlockLength()] text := strings.Join([]string{"kalshi.fix.sbe." + product + ".md", "3", "1", now.Format("20060102-15:04:05.000"), "A", "1", id, "KalshiMD", fmt.Sprintf("%x", sha256.Sum256(options))}, "\x01") logon.SignatureBase64 = []byte(sign(key, text)) p.send(&logon, now) h, b := p.receive() var ack sbe.LogonAck require(h.TemplateId == ack.SbeTemplateId(), "expected LogonAck") decode(&p, h, b, &ack, false, 2) require(ack.Profile == profile && ack.Reset == 1 && ack.HeartbeatSeconds == 30 && ack.PresentOptions == 0 && ack.EnabledOptions == 0 && string(ack.ClientCompId) == id && string(ack.GatewayCompId) == "KalshiMD", "LogonAck mismatch") p.send(&sbe.MarketDataRequest{SubscriptionType: '0', Feed: 3, Symbols: []sbe.MarketDataRequestSymbols{{Symbol: []byte(symbol)}}}, time.Now()) var best bestBook var snapshotID, total, count uint64 var parts, index uint32 var marker string var when int64 var hasTime uint8 for { h, b = p.receive() switch h.TemplateId { case 4: var beat sbe.Heartbeat decode(&p, h, b, &beat, false, 1) case 5: var req sbe.TestRequest decode(&p, h, b, &req, false, 1) p.send(&sbe.Heartbeat{TestRequestId: req.TestRequestId}, time.Now()) case 101: var snap sbe.MarketDataSnapshot decode(&p, h, b, &snap, true, 2) require(index == 0 && string(snap.Symbol) == symbol, "unexpected book") count = uint64(len(snap.Levels)) for _, l := range snap.Levels { best.add(l.EntryType, l.Price, l.Size) } fmt.Printf("%s levels=%d bid(price,qty)=%s offer(price,qty)=%s\n", symbol, count, best.bid, best.offer) p.send(&sbe.Logout{}, time.Now()) return case 106: var chunk sbe.MarketDataSnapshotChunk decode(&p, h, b, &chunk, true, 2) if index == 0 { snapshotID, parts, total, marker, when, hasTime = chunk.SnapshotId, chunk.ChunkCount, chunk.TotalLevels, string(chunk.MdExecId), chunk.EntryTimeMs, chunk.HasEntryTime } require(parts != 0 && index < parts && chunk.ChunkIndex == index && chunk.SnapshotId == snapshotID && chunk.ChunkCount == parts && chunk.TotalLevels == total && string(chunk.Symbol) == symbol && string(chunk.MdExecId) == marker && chunk.EntryTimeMs == when && chunk.HasEntryTime == hasTime, "snapshot chunk mismatch") count += uint64(len(chunk.Levels)) for _, l := range chunk.Levels { best.add(l.EntryType, l.Price, l.Size) } require(count <= total, "excess snapshot levels") index++ if index == parts { require(count == total, "incomplete snapshot") fmt.Printf("%s levels=%d bid(price,qty)=%s offer(price,qty)=%s\n", symbol, count, best.bid, best.offer) p.send(&sbe.Logout{}, time.Now()) return } default: log.Fatalf("expected a snapshot or session control; received template %d", h.TemplateId) } } }