{
    "componentChunkName": "component---src-templates-post-page-js",
    "path": "/2018/cryptomate/trading-port",
    "result": {"data":{"site":{"siteMetadata":{"title":"Solid Abstractions","siteUrl":"https://solidabstractions.com","twitterId":291334023,"author":{"fullName":"Julien Hartmann","profileHtml":"I am an open-source de­vel­op­er, for­mer IT con­sul­tant with a pas­sion for new tech­nol­o­gies. I be­lieve the role of an en­gi­neer is to em­pow­er peo­ple, by as­sem­bling sim­ple, re­fined de­signs.\n","links":[{"url":"https://github.com/spectras/","name":"github","title":"GitHub"},{"url":"https://stackoverflow.com/users/3212865/spectras","name":"stackoverflow","title":"StackOverflow"},{"url":"https://www.linkedin.com/in/julienhartmann/","name":"linkedin","title":"LinkedIn"}],"profilePicNode":{"original":{"src":"/static/profile-pic-301a9cbe7b572c3e7910c9717d2b3bcd.jpg"}},"url":"https://etherdream.org/about"}}},"markdownRemark":{"id":"58d29eb3-a179-5399-93ac-f956100f1750","excerpt":"In the “modules and components” post, we defined the trading port as a gateway\nto exchanges, managing a trading account, placing and canceling orders.","html":"<p>In the “modules and components” post, we defined the trading port as a gateway\nto exchanges, managing a trading account, placing and canceling orders.</p>\n<p>--- excerpt ---</p>\n<p>Continuing the strategy port sub-series, we will now design the trading port.</p>\n<blockquote>\n<ol>\n<li><a href=\"market-port\" class=\"internal\">Market port</a>.</li>\n<li>Trading port <em>(this post)</em>.</li>\n<li><a href=\"other-strategy-ports\" class=\"internal\">Other strategy ports</a>.</li>\n</ol>\n</blockquote>\n<p>In the <a href=\"modules\" class=\"internal\">modules and components</a> post, we defined the trading port as a gateway\nto exchanges, managing a trading account, placing and canceling orders.</p>\n<p>We will do as we did for the <a href=\"market-port\" class=\"internal\">market port</a>, that is, start with describing\nthe <strong>domain model</strong> then proceed to defining the <strong>features</strong> supporting this\nrepresentation of the world.</p>\n<h2 id=\"domain-model\">Domain model</h2>\n<h3 id=\"trading-account\">Trading account</h3>\n<p>A trading account is a financial account maintained by an exchange or broker, that represents\nthe funds they hold on behalf of the customer. The customer can use those to trade directly,\nor in the case of more sophisticated instruments, as a collateral securing repayment of\n<a href=\"https://en.wikipedia.org/wiki/Leverage_(finance)\" class=\"external\" rel=\"external noopener noreferrer\">leveraged</a> positions.</p>\n<p>As such, it has a more complex working than the usual deposit account. We shall use the\nfollowing definitions, relevant to our trading project using accounts that support\n<a href=\"https://en.wikipedia.org/wiki/Margin_(finance)\" class=\"external\" rel=\"external noopener noreferrer\">trading on margin</a>:</p>\n<dl><dt>Asset balances</dt><dd><p>The amount of each commodity and security owned by the customer. Barring blocked funds\nused as collateral, those are the amounts available for withdrawal.</p></dd><dt>Margin balance</dt><dd><p>The total value usable as a collateral for margin positions. It might differ from the total\ncounter-value of asset balances, because not all assets might be usable as a collateral.</p></dd><dt>Open positions</dt><dd><p>On-going trades, where the asset was successfully sold (for short positions) or bought (for\nlong positions) but not yet bought/sold back.</p></dd><dt>Used margin</dt><dd><p>Total counter-value currently blocked as a collateral to open positions.</p></dd><dt>Equity</dt><dd><p>Current counter-value of the account. That is, the total counter-value of asset balances\nplus/minus any unrealized profits/losses from open positions.</p></dd><dt>Margin level</dt><dd><p>Ratio of equity to used margin. This gives a measure of how exposed the account currently\nis to markets. When this number goes below a certain exchange-specific threshold, it will\nstart forcefully closing loosing positions (a process known as liquidation).</p></dd></dl>\n<p>In addition, an account is associated a list of orders, and a ledger that keeps track of\nall fund movements for legal and fiscal proceedings.</p>\n<h3 id=\"anatomy-of-an-order\">Anatomy of an order</h3>\n<p>Apart from deposits and withdrawals, which Cryptomate does not care about, all changes on\na trading account are the results of executing orders.</p>\n<p>Each order represents the intent of the account owner to buy or sell an asset for\nanother. They come in two types:</p>\n<ul>\n<li>A <em>limit order</em> has a fixed price, representing the worst price the owner wants to trade at.\nThat is, highest price he wants to buy at, or lowest price he wants to sell at. Such an order\ngoes to the order book if it has no counterparty when it is opened.</li>\n<li>A <em>market order</em> has no fixed price, it requests an immediate trade, at whatever the best\nprices currently are.</li>\n</ul>\n<p>In addition to their type, orders have a <code class=\"language-text\">side</code> (buy or sell), total <code class=\"language-text\">volume</code> to trade,\n<code class=\"language-text\">expiration</code> date and for margin trading, the <code class=\"language-text\">leverage</code> to use.</p>\n<p>Once issued, the order follows the following life-cycle:</p>\n<div class=\"figure-wrapper\"><figure id=\"fig-1\"><img src=\"/files/domain-order-state-89f9d5f6a4157a69691595f409854246.png\" alt=\"Order state diagram\" srcset=\"/files/domain-order-state-1.5x-4a4c16a1adb31c31398c0e0d74c644f3.png 1.5x, /files/domain-order-state-2x-cb8d2ffd76af94535a81b6102d41a656.png 2x\"><figcaption><div class=\"figcaption-wrapper\">Order state diagram.</div></figcaption></figure></div>\n<p>Market orders follow the same state diagram, except they are executed instantly at the best\npossible value. This leaves no opportunity for cancelling or expiration, and it only remains\nif partially filled state while it is being processed.</p>\n<p>During its life, an order will generate trades. Possibly zero if it gets cancelled, possibly\nmany if it gets matched to a several smaller orders. The exact list of trades is usually\nof little value, but some aggregated statistics are commonly used, most notably:</p>\n<div class=\"figure-wrapper\"><figure id=\"fig-2\"><table>\n<thead>\n<tr>\n<th>Name</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code class=\"language-text\">Executed volume</code></td>\n<td>How much was bought/sold so far.<br>Equals total volume on a closed order.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Cost</code></td>\n<td>How much was spent to buy/sell so far.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Average price</code></td>\n<td>Cost / executed volume.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Fee</code></td>\n<td>Total amount of fees paid for the trade so far.<br><em>Ever heard trading is a zero-sum game? Well, not so much.</em></td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Cancellation time</code></td>\n<td>Time at which the order was cancelled.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Close time</code></td>\n<td>Time at which the order got fully filled.</td>\n</tr>\n</tbody>\n</table><figcaption><div class=\"figcaption-wrapper\">Order statistics.</div></figcaption></figure></div>\n<p>Lastly, it is a common practice to match orders on the same market into positions. This\nlogical grouping makes it possible to easily think about a position in terms of running\nprofits and losses. As this grouping as actually related to a specific way of thinking\nabout the strategy, it will not be handled at the trading port level.</p>\n<h2 id=\"trading-port-features\">Trading port features</h2>\n<p>As previously established, the purpose of the trading port is to abstract out\nall the details of connecting to a trading account and using it. That is:</p>\n<ul>\n<li>Querying its status.</li>\n<li>Placing and cancelling orders.</li>\n<li>Subscribing to real-time events that affect account's orders.</li>\n</ul>\n<h3 id=\"workflow\">Workflow</h3>\n<p>Seen from client code, the trading port is straightforward:</p>\n<ul>\n<li>Hand an account description to the trading engine.</li>\n<li>Get an <code class=\"language-text\">Account</code> object back.</li>\n<li>Use it to query its state, place or cancel orders.</li>\n<li>Get notified of every order-related events through a callback.</li>\n<li>Close the <code class=\"language-text\">Account</code> object when no longer needed.</li>\n</ul>\n<h3 id=\"interface-list\">Interface list</h3>\n<p>Assembling the features and objects described in previous sections, here is the full\nlist of interfaces that, together, constitute the trading port:</p>\n<div class=\"figure-wrapper\"><figure id=\"fig-3\"><table>\n<thead>\n<tr>\n<th>Name</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code class=\"language-text\">Account</code></td>\n<td>A valid, opened account on a trading platform.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">AccountDescription</code></td>\n<td>Static data granting access to a trading account.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">AccountEventHandler</code></td>\n<td>Callable that responds to events happening on an account.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Engine</code></td>\n<td>Main port entry point.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Order</code></td>\n<td>Buy/sell intent.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">RuleSet</code></td>\n<td>Relevant trading rules for an <code class=\"language-text\">Account</code>.</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">Trade</code></td>\n<td>A single trade resulting from an order.</td>\n</tr>\n</tbody>\n</table><figcaption><div class=\"figcaption-wrapper\">Trading port interfaces</div></figcaption></figure></div>\n<p>For detailed specification of each interface, check their definition and inline documentation\non <a href=\"https://github.com/solid-abstractions/cryptomate/tree/posts/trading-port/1\" class=\"external\" rel=\"external noopener noreferrer\">GitHub</a>. Again, due to the dynamic nature of python, not all interfaces need to\nappear as python types within the code.</p>\n<h2 id=\"conclusion\">Conclusion</h2>\n<p>That is it for the trading port. You will find the result on GitHub under the <a href=\"https://github.com/solid-abstractions/cryptomate/tree/posts/trading-port/1/cryptomate/trading\" class=\"external\" rel=\"external noopener noreferrer\"><code class=\"language-text\">trading</code></a>\ndirectory. In the <a href=\"other-strategy-ports\" class=\"internal\">next post</a>, we will turn to the remaining ports\nof the strategy evaluator, which should be simpler.</p>","fields":{"isPage":false,"slug":"/2018/cryptomate/trading-port"},"frontmatter":{"title":"Trading Port","classname":null,"date":"2018-10-20T00:00:00.000Z","formattedDate":"October 20, 2018","isoDate":"2018-10-20T00:00:00+00:00"},"headings":[{"value":"Domain model","depth":1},{"value":"Trading account","depth":2},{"value":"Anatomy of an order","depth":2},{"value":"Trading port features","depth":1},{"value":"Workflow","depth":2},{"value":"Interface list","depth":2},{"value":"Conclusion","depth":1}],"image":null,"series":{"name":"cryptomate","fullName":null,"fields":{"slug":"/cryptomate"}},"tags":[{"name":"architecture","slug":"/tag/architecture"},{"name":"ports","slug":"/tag/ports"}]}},"pageContext":{"series":"cryptomate","slug":"/2018/cryptomate/trading-port","previous":{"fields":{"slug":"/2018/cryptomate/market-port"},"frontmatter":{"title":"Market Port","series":"cryptomate"},"tags":[{"name":"architecture","slug":"/tag/architecture"},{"name":"ports","slug":"/tag/ports"}]},"next":{"fields":{"slug":"/2018/cryptomate/other-strategy-ports"},"frontmatter":{"title":"Other Strategy Ports","series":"cryptomate"},"tags":[{"name":"architecture","slug":"/tag/architecture"},{"name":"ports","slug":"/tag/ports"}]},"seriesPrevious":{"fields":{"slug":"/2018/cryptomate/market-port"},"frontmatter":{"title":"Market Port","series":"cryptomate"},"tags":[{"name":"architecture","slug":"/tag/architecture"},{"name":"ports","slug":"/tag/ports"}]},"seriesNext":{"fields":{"slug":"/2018/cryptomate/other-strategy-ports"},"frontmatter":{"title":"Other Strategy Ports","series":"cryptomate"},"tags":[{"name":"architecture","slug":"/tag/architecture"},{"name":"ports","slug":"/tag/ports"}]}}},
    "staticQueryHashes": ["1733002695","4006707078"]}