<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Reactive Markets - Medium]]></title>
        <description><![CDATA[Reactive Markets Engineering &amp; Design - Medium]]></description>
        <link>https://medium.com/reactivemarkets?source=rss----cd27503bfa97---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Reactive Markets - Medium</title>
            <link>https://medium.com/reactivemarkets?source=rss----cd27503bfa97---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:59:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/reactivemarkets" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fun with Strncpy]]></title>
            <link>https://medium.com/reactivemarkets/fun-with-strncpy-17c6a9f63bae?source=rss----cd27503bfa97---4</link>
            <guid isPermaLink="false">https://medium.com/p/17c6a9f63bae</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[ultra-low-latency]]></category>
            <dc:creator><![CDATA[Mark Aylett]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 12:29:49 GMT</pubDate>
            <atom:updated>2020-06-18T12:29:49.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UBNhHq8IdMRHTOda" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=medium&amp;utm_medium=referral">Daria Nepriakhina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The strncpy() function may result in buffer overruns when used incorrectly. Use of this function is understandably frowned upon by many developers. A fresh look at the API, however, reveals some genuine uses for this classic C function that are still applicable today.</p><p>This article aims to:</p><ol><li>rediscover some of the original motivations for this often misunderstood function;</li><li>clarify how and when to use this function safely and effectively in modern code.</li></ol><h3>Background</h3><p><strong>A word of caution</strong>: the dangers of misusing strncpy() are real. It should only be used when the benefits outweigh the risks and it should always be used with extreme care. Higher level, safer APIs should be preferred for the vast majority of use-cases outside of specialist application domains.</p><p>The <a href="https://www.reactivemarkets.com/about">team at Reactive Markets</a> have worked on many low-latency trading systems over the years. In this domain, applications often have latency requirements in the low microsecond or even nanosecond range. Achieving these latencies requires messaging protocols and encodings that are sympathetic to high performance data structures.</p><p>In some cases, it may be appropriate to simply copy bytes from memory to wire, as the example in the next section demonstrates, but this is not always practical or possible due to competing concerns and variable length data elements.</p><p>ITCH and <a href="https://www.fixtrading.org/standards/sbe">SBE</a> are good examples of financial protocols that attempt to balance the need for tight, compact data on the wire and contiguous, aligned in-memory data structures.</p><h3>Binary Messaging</h3><p>Let’s start with a motivational example to help set the stage for the discussion that follows. Imagine that we have been asked to design a binary message format with the following fields:</p><ul><li>id: a 64 bit integer identifier;</li><li>user: an alpha-numeric string of no more than 8 bytes in length.</li></ul><p>Arguably the most efficient way to represent this data structure in memory is as follows:</p><pre>struct Message {<br>  int64_t id;<br>  char user[8];<br>};</pre><p>Each field is 8 bytes in length and they are adjacent in memory with no padding between them. It turns out that this simple data structure also works reasonably well as a binary message format. In this case, the memory layout and the message format are the same, so no encoding or decoding is required when reading and writing messages; bytes can simply be copied to and from the network.</p><p>So far so good, but if we assume that the user field could be less than 8 bytes, or even empty, how do we know how long it is? We could introduce a separate length field, but this is suboptimal when the string is 8 bytes in length and, perhaps more seriously, our data structure no longer naturally aligns to a 16 byte boundary:</p><pre>struct Message {<br>  int64_t id;<br>  int8_t user_len;<br>  char user[8];<br>};</pre><p>One solution to this problem, and the one heavily adopted by the C programming language, is to use a zero byte to indicate the end of a string. This is where the C family of string functions come in and why they are still useful when dealing with low-level data structures.</p><p>An important point to note regarding the user field in our example is that it is only zero-terminated when the string is less than 8 bytes in length.</p><h3>Buffer Overruns</h3><p>The C family of string functions are designed for manipulating zero-terminated strings. Before turning our attention to strncpy(), let&#39;s take a brief look its close cousin the strcpy() function.</p><p>The strcpy() function copies a zero-terminated source string to destination buffer. The strcpy() function will result in a buffer overrun if the source string is larger than the destination:</p><pre>char buf[6];<br>strcpy(buf, &quot;Aylett&quot;);</pre><p>The problem in this example is that a zero terminator is written beyond the end of the buffer:</p><pre>+---+---+---+---+---+---+<br>| A | y | l | e | t | t |\0<br>+---+---+---+---+---+---+ ^<br>  0   1   2   3   4   5   write overrun</pre><p>Programmers often reach for strncpy() as a possible solution, believing it to be a &quot;bounded&quot; version of strcpy():</p><pre>char buf[6];<br>strncpy(buf, &quot;Aylett&quot;, sizeof(buf));</pre><p>In this example, however, the function will stop appending characters when the destination buffer is full, and the resulting string will not be zero-terminated. This may result in a “read overrun” if the consumer expects a C-style (zero-terminated) string:</p><pre>+---+---+---+---+---+---+<br>| A | y | l | e | t | t | ?<br>+---+---+---+---+---+---+ ^<br>  0   1   2   3   4   5   no zero terminator</pre><p>This often leads programmers to question why strncpy() was designed with such a seemingly broken contract and they perhaps abandon it altogether. In order to answer this question, we need to stop thinking of strncpy() as a bounded version of strcpy(), and revisit one of the original motivations for its design.</p><h3>Data Leaks</h3><p>An advantage of low-level languages is that they allow programmers to layout their data structures in contiguous regions of memory:</p><pre>struct Person {<br>  char forename[32];<br>  char surname[32];<br>};<br>static_assert(sizeof(Person) == 64);<br>static_assert(std::is_pod_v&lt;Person&gt;);</pre><p>Tightly packed data such as this are ideal for binary messaging and file formats. When populating such structures, however, programmers must take care to avoid security vulnerabilities and data leaks:</p><pre>Person person;<br>strcpy(person.forename, &quot;Mark&quot;);<br>strcpy(person.surname, &quot;Aylett&quot;);</pre><p>If this data structure were copied verbatim onto the wire, then the use of strcpy() in this example would present a security risk. To understand why, first consider the memory location immediately following the zero terminator:</p><pre>+---+---+---+---+---+---+-------+---+<br>| M | a | r | k |\0 | ? |  ...  | ? |<br>+---+---+---+---+---+---+-------+---+<br>  0   1   2   3   4   5    ...    31</pre><p>The problem is that the “person” object is not zero-initialised, so these memory locations will contain arbitrary data from the stack, which is subsequently leaked onto the wire. If these locations happen to contain sensitive data from old stack objects, then your system is now at risk of attack.</p><h3>Message Padding</h3><p>To avoid exposing private memory locations, we must ensure that any unused gaps in our data structures are suitably filled or padded. What we need is a function that copies the source string to the destination, and then fills any remaining bytes in the destination buffer with a padding:</p><pre>void pstrcpy(char* dst, const char* src, size_t n) noexcept<br>{<br>    // Copy source to destination.<br>    size_t i{0};<br>    for (; i &lt; n &amp;&amp; src[i] != &#39;\0&#39;; ++i) {<br>       dst[i] = src[i];<br>    }<br>    // Pad remaining bytes with space.<br>    for (; i &lt; n; ++i) {<br>        dst[i] = &#39; &#39;;<br>    }<br>}</pre><p>The API can be further simplified by inferring the size of the destination buffer using a function template:</p><pre>template &lt;size_t SizeN&gt;<br>inline void pstrcpy(char (&amp;dst)[SizeN], const char* src) noexcept<br>{<br>    // ...<br>}</pre><p>This function can then be called as follows:</p><pre>char buf[6];<br>pstrcpy(buf, &quot;Mark&quot;);</pre><p>Which will result in a “space padded” string:</p><pre>+---+---+---+---+---+---+<br>| M | a | r | k |   |   |<br>+---+---+---+---+---+---+<br>  0   1   2   3   4   5</pre><p>Note that it is technically more correct to refer to this string encoding as “space padded” rather than “space terminated”, because the string will not be space terminated when the source string length is greater than or equal to the destination.</p><h3>Strncpy Contract</h3><p>We are finally ready to revisit the strncpy() contract. The <a href="https://www.freebsd.org/cgi/man.cgi?strncpy(3)">FreeBSD man page</a> states that:</p><blockquote><em>strncpy() copies at most </em><em>len characters from </em><em>src into </em><em>dst. If </em><em>src is less than </em><em>len characters long, the remainder of </em><em>dst is filled with </em><em>\0 characters.</em></blockquote><p>Does this specification look familiar? It is precisely the function described in the previous section, except the pad character is now a zero (\0) rather than a space.</p><p>The following idiom is often used when zero termination is unconditionally required:</p><pre>char buf[6 + 1];<br>strncpy(buf, &quot;Aylett&quot;, sizeof(buf) - 1);<br>buf[sizeof(buf) - 1] = &#39;\0&#39;;</pre><p>This idiom is neatly encapsulated by the following function template, which avoids common programming errors regarding the buffer size:</p><pre>template &lt;size_t SizeN&gt;<br>inline void zstrcpy(char (&amp;dst)[SizeN], const char* src) noexcept<br>{<br>    strncpy(dst, src, SizeN - 1);<br>    dst[SizeN - 1] = &#39;\0&#39;;<br>}</pre><h3>Read Safety</h3><p>Although we now have a better understanding of the strncpy() contract, we still need a solution for reading these zero-padded strings without overrunning the buffer. Consider the following member function:</p><pre>const char* surname() const noexcept<br>{<br>    return surname_;<br>}</pre><p>If surname_ is a zero-padded string with no padding, then it will not be zero-terminated and the unwary user will likely overrun the buffer when reading. Assuming that we do not need a zero-terminated string, the cleanest solution is to use the std::string_view&lt;&gt; template:</p><pre>std::string_view surname() const noexcept<br>{<br>    return {surname_, strnlen(surname_)};<br>}</pre><p>Again, the key point is to think of strncpy() as a function that copies a C-style string into a fixed length buffer, and then zero pads any remaining bytes.</p><h3>Summary</h3><p>Taking some time to revisit the fundamentals can lead to new insights and fresh perspectives.</p><p>In summary:</p><ul><li>the strncpy() is a genuinely useful function that is unfortunately often misunderstood;</li><li>before using strncpy(), decide whether you actually want a <em>zero-terminated string</em> or a <em>zero-padded fixed length string</em>;</li><li>If a zero-padded fixed length string is required, then use strncpy() to write the string andstd::string_view&lt;&gt; to read the string.</li></ul><p>The functions mentioned in this article and many more besides are freely available in our open source <a href="https://github.com/reactivemarkets/toolbox-cpp">toolbox-cpp</a> project. Please also check out the <a href="https://www.reactivemarkets.com/">Reactive Markets website</a> if you would like to know more about us and how our <a href="https://platform.reactivemarkets.com/">Platform</a> is powering a new generation of professional traders.</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17c6a9f63bae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/reactivemarkets/fun-with-strncpy-17c6a9f63bae">Fun with Strncpy</a> was originally published in <a href="https://medium.com/reactivemarkets">Reactive Markets</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Limit Order Books]]></title>
            <link>https://medium.com/reactivemarkets/limit-order-books-9d48adf2c517?source=rss----cd27503bfa97---4</link>
            <guid isPermaLink="false">https://medium.com/p/9d48adf2c517</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[limit-order-book]]></category>
            <category><![CDATA[exchange]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Mark Aylett]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 11:19:04 GMT</pubDate>
            <atom:updated>2020-06-30T17:40:21.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOyOF8TUrbaBRQtEZuUyuw.png" /></figure><p>This is the first in a series of articles exploring market-data and Exchange connectivity. Industry jargon and the vast array of connectivity options can be overwhelming for newcomers. In this article, we establish the foundations for future discussions by explaining how a Limit Order Book (LOB) works and demystifying the terminology that surrounds them.</p><h3>Exchanges</h3><p>Most electronic Exchanges use LOBs to match orders placed by buyers and sellers. LOBs have entered the mainstream in recent years with the popularisation of Cryptocurrency Exchanges. Understanding how a LOB works is essential for understanding the market-data published by these Exchanges.</p><p>An Exchange is a place where traders come together to exchange goods or services. Sellers offer their goods or services to buyers that bid for them. The Exchange accepts bids and offers in the form of orders and attempts to match them:</p><ul><li>bids are submitted as buy orders;</li><li>offers are submitted as sell orders.</li></ul><p>Exchanges are also known as “venues”, although Exchanges are not the only kind of trading venue.</p><h3>Level 2 Order Books</h3><p>The “liquidity” available in the LOB can be viewed in multiple ways. In this article, we present the liquidity in the LOB as a stack of “price levels”, where each price level comprises one or more orders with the same price and side. This representation is known as a level 2 order book aggregated by price.</p><p>Consider the following LOB with two price levels:</p><pre>| Level | Bid Qty | Bid Price | Spread | Offer Price | Offer Qty |<br>|-------|---------|-----------|--------|-------------|-----------|<br>|     1 |       1 |      9649 |      2 |        9651 |         1 |<br>|     2 |       5 |      9648 |      5 |        9653 |         3 |</pre><p>For each given price level:</p><ul><li>the quantity is the sum of all order quantities at that level;</li><li>the “spread” is the difference between the bid and offer price.</li></ul><p>The first level, or Top Of Book (TOB), shows the best bid and offer available in the order book:</p><ul><li>the bids are arranged in descending order with the best bid at the top;</li><li>the offers are arranged in ascending order with the best offer at the top.</li></ul><h3>Limit Orders</h3><p>The LOB gets its name from a standard order type known as a “limit” order; a LOB is essentially a book of limit orders.</p><p>The price on a limit order is known as the limit price. The limit price specifies the worst price at which the trader is willing to trade (highest for bids and lowest for offers). This article deals exclusively with limit orders, so the limit price is subsequently referred to simply as the price.</p><h3>Resting Orders</h3><p>A trade happens when a buy or sell order is matched with one or more pre-existing orders in the LOB. How an order behaves when it is not immediately filled varies between order types.</p><p>Limit orders may also specify how long they are “good for”. If a limit order is good for a period of time, and it is not immediately filled, then it is placed in the LOB according to its side (buy or sell) and price. An unmatched limit order that is live or “working” in the LOB is known as a “resting” order. Order types that cannot rest in the order book are either immediately filled or cancelled.</p><p>The short-hand notation below will be used in proceeding examples to describe a limit order:</p><p>BUY 2@9650 : a buy order where 2 is the order quantity and 9650 is the price.</p><p>If this limit order is applied to our earlier example, then it will rest at the TOB on the bid side, because its price is better than the current TOB:</p><pre>| Level | Bid Qty | Bid Price | Spread | Offer Price | Offer Qty |<br>|-------|---------|-----------|--------|-------------|-----------|<br>|     1 |       <strong>2</strong> |      <strong>9650</strong> |      1 |        9651 |         1 |<br>|     2 |       1 |      9649 |      4 |        9653 |         3 |<br>|     3 |       5 |      9648 |        |             |           |</pre><p>Similarly, a limit order to “SELL 3@9653” will “join” the second level on the offer side:</p><pre>| Level | Bid Qty | Bid Price | Spread | Offer Price | Offer Qty |<br>|-------|---------|-----------|--------|-------------|-----------|<br>|     1 |       2 |      9650 |      1 |        9651 |         1 |<br>|     2 |       1 |      9649 |      4 |        9653 |         <strong>6</strong> |<br>|     3 |       5 |      9648 |        |             |           |</pre><p>Note that the number of orders at each price level cannot be derived from the aggregate quantity. The order count is often shown as a separate “count” field.</p><h3>Order Matching</h3><p>In a classic LOB, Matching happens by price/time priority. This means that orders are matched first by price, and then by time (order age). If multiple orders exist at the same price level, for example, then the oldest order will be matched first.</p><p>Consider the effect of a limit order to “BUY 2@9652” that crosses the spread:</p><pre>| Level | Bid Qty | Bid Price | Spread | Offer Price | Offer Qty |<br>|-------|---------|-----------|--------|-------------|-----------|<br>|     1 |       <strong>1</strong> |      <strong>9652</strong> |      2 |        9653 |         6 |<br>|     2 |       2 |      9650 |        |             |           |<br>|     3 |       1 |      9649 |        |             |           |<br>|     4 |       5 |      9648 |        |             |           |</pre><p>In this example, the limit order to “BUY 2@9652” crossed with the first level on the offer side (“OFFER 1@9651”). The price on the order was higher than the level it crossed, so the resulting trade will have an improved price of 9651.</p><p>The limit order was not completely filled, because there was insufficient quantity on the offer side. And assuming that this order is good for some time, any quantity remaining after the matching phase is complete will rest on the bid side, hence the new price level on the bid side at TOB.</p><p>Orders that cross the spread and “take” liquidity from the order book are known as an “aggressive” orders. By contrast, orders that do not cross the spread are known as “passive” orders.</p><p>Aggressive orders may “sweep” through multiple price levels, as demonstrated in the following example, where an aggressive order to “SELL 4@9649” sweeps through the top three levels of the bid side:</p><pre>| Level | Bid Qty | Bid Price | Spread | Offer Price | Offer Qty |<br>|-------|---------|-----------|--------|-------------|-----------|<br>|     4 |       5 |      9648 |      5 |        9653 |         6 |</pre><p>This aggressive order will result in the following trades:</p><ul><li>1@9652</li><li>2@9650</li><li>1@9649</li></ul><h3>Makers and Takers</h3><p>Traders that submit aggressive orders are known as “takers”. Traders that submit passive orders are known as “makers”. Market-makers play an important role in providing liquidity to the market, because, under normal market conditions, they are willing to quote two-way prices on a continual basis, thus ensuring that there is always a maker available to take the opposing side of a taker’s trade.</p><p>Each trade transaction comprises two matched orders. These orders can be classified both in terms of a buyer and a seller or a maker and a taker. To avoid confusion, trades are often referred to from the taker’s perspective as “paid” or “given”:</p><ul><li><strong>Paid</strong>: taker bought or “lifted the offer”;</li><li><strong>Given</strong>: taker sold or “hit the bid”.</li></ul><p>This terminology is particular relevant for public trade feeds, where an Exchange may publicise anonymised trade information from the taker’s perspective.</p><h3>Summary</h3><p>This concludes our brief introduction to LOBs and the order matching process. In future articles, we will take a closer at how market-data is derived from the LOB and the options for distributing this data to users over an Application Programming Interface (API).</p><p>Check out the <a href="https://www.reactivemarkets.com/">Reactive Markets website</a> if you would like to know more about us and how our <a href="https://platform.reactivemarkets.com/">Platform</a> is powering a new generation of professional traders.</p><p>See you next time!</p><p><em>Originally published at </em><a href="https://developer.reactivemarkets.com/articles/limitorderbooks/"><em>https://developer.reactivemarkets.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d48adf2c517" width="1" height="1" alt=""><hr><p><a href="https://medium.com/reactivemarkets/limit-order-books-9d48adf2c517">Limit Order Books</a> was originally published in <a href="https://medium.com/reactivemarkets">Reactive Markets</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>