Renko-based Scalper for Binance Using XTRD FIX API

Binance Overview

Binance is one of the largest cryptocurrency exchanges in the world, responsible for $7.7 trillion crypto exchange volume in 2021. It was founded in 2017 by Changpeng Zhao, who previously worked for Blockchain.info and as CTO of OKCoin.

XTRD Overview

XTRD is an institutional-grade OEMS for digital assets trading. We provide access to major crypto exchanges through the unified FIX API.


In this article, we would like to demonstrate how to build a small yet powerful scalping application that trades on the leading cryptocurrency exchange – Binance. 

The bot will be connected to Binance through XTRD FIX API to receive real-time normalized market data and to place/cancel orders. 

You can reuse this source code in your projects free of charge. 

Disclaimer: the bot is not a ready-to-use solution because it lacks risk controls and proper positions management. Although our R&D shows promising performance, do not expect to achieve the same results. 

Before we dive into the technical part, it’s worth explaining the logic behind the given trading bot. 

Scalping is a momentum-based trading style where positions hold for minutes or even seconds and then sell for profit (or small loss… a sacrifice to Mr. Market). When performed manually, it requires self-discipline, the ability to handle stress, make quick decisions, and act accordingly. 

Renko chart is one of the technical analysis tools that help reduce market noise and identify market trends more precisely. One of the authors of this article was introduced to Renko about 15 years ago and fell in love with it. 

To construct a single brick on a chart we should perform several simple steps:

  • Define a brick size e.g. 10 points
  • Define the price type to track. It can be bids, asks, trades, an average between the bid and ask, etc.
  • Start tracking prices in real-time
  • If the price changed more than 10 points, then form a new Renko brick in the corresponding direction. It is possible that the single price change can form more than one Renko brick.

Here is our trading logic:

  • Wait for a new Renko brick to be formed
  • If it is an UP brick, then place a limit order to SELL with a price at the level of UP + 1 brick
  • If it is a DOWN brick, then place a limit order to BUY with a price at the level of DOWN – 1 brick

  • Continue monitoring the market for changing course or for execution
  • If a newly formed brick changed its direction (this means that the price changed at least 2x of a brick size in the reverse direction), we should cancel our existing limit order and place another one with a new price and reversed direction.
  • If the market moved in the direction we predicted, then our order gets executed and we should start over.

Simply put, it is the good old “buy low, sell high” principle computerized and applied to crypto markets through XTRD FIX API. 

The bot itself contains several main components:

  • Market data connector 
  • Trading connector
  • Market data processor/Renko generator
  • Simple OMS/EMS system

To make this technical-enough material more fun, we decided to build a small user interface to plot Renkos bricks and executions.

Since all high-level details of implementation were discussed, let’s get started with the implementation part.

To build Renko charts we need to establish a connection to a service called XTRD MD Feeder. It is responsible for disseminating real-time normalized market data from Binance (and other crypto exchanges) using FIX protocol. In comparison with WebSockets, FIX is faster and more reliable because it runs on top of a pure TCP/IP stack and has no additional intermediary layers. 

Using FIX protocol, you can easily subscribe to receive updates for one or many trading instruments available on Binance such as BTC/USDT, ETH/USDT, and so on. It is possible to specify what sort of information you’ll need – bids, asks, and/or trades. Another big advantage is that market data itself comes in incremental updates. This means that you receive only actual changes of the entire orders book (like 3-4 levels) but not a full book every time. This is not a big issue with Binance which already streams data as a delta (difference between the previous and current state) but can be extremely helpful with other crypto exchanges XTRD supports. 

There are three major messages defined by FIX standard and implemented inside XTRD that help manage your crypto market data streams – MarketDataRequest, MarketDataSnapshotFullRefresh, and MarketDataIncrementalRefresh. As it is easy to understand from their names, MarketDataRequest is used to manage your subscription (start or stop data streams), MarketDataSnapshotFullRefresh is used by the server to transmit the entire book, and MarketDataIncrementalRefresh is sent by the server when data (price or side) in the particular orders book changed. 

The market data management workflow is simple – once the application established a connection to XTRD OEMs over the FIX, it sends MarketDataRequest to subscribe to all updates on BTC/USDT (or another selected symbol) on Binance. 

If the request was successfully processed, XTRD OEMS for digital assets trading responds with a MarketDataSnapshotFullRefresh message that contains all levels for BTC/USDT orders book. The application uses this data to initiate the book and starts waiting for incoming MarketDataIncrementalRefreshes that carry small (and sometimes not very small) delta changes. These changes have to be applied to the book (delete levels, update sizes on a particular level, add new prices). Once a book is updated, the component responsible for Renko’s generation will check if the conditions to create a new brick are met or if the price is still within the interval. 

Now, when we have a working market data connection and Renkos charts, it’s time to start trading on Binance using FIX API. 

FIX specification contains plenty of different messages (commands and responses) that cover pretty much everything in a typical trade lifecycle starting from initiation to ending with trade confirmation and settlement. XTRD OEMS system allows managing orders (get all, place, cancel, replace) and viewing positions through the unified FIX API. 

When it comes to trading, there are three major messages – NewOrderSingle, OrderCancelRequest, and ExecutionReport.

NewOrderSingle is used to initiate an order. The message allows specifying different order characteristics, such as side (e.g. BUY), size, type (e.g. LIMIT), symbol, time in force (e.g. Good Till Cancel), among others.

Below is a textual representation of the raw FIX request to buy 0.001 BTC for USDT at Market on the Binance.

In many cases, the server interacts with clients over ExecutionReports. This message is used to indicate changes of your orders over time – was it accepted or rejected, canceled, or executed, and if executed, what are the price and size? 

Each message has clear status, a clear ID, and a timestamp associated with it. 

Many exchanges have their own workflows. XTRD OEMS for digital assets trading helps normalize these statuses and make them identical across all supported platforms:

Our demo application utilizes only two simple commands – NewOrderSingle (to place a new order) and OrderCancelRequest (to cancel an order we don’t need anymore). 

Another useful command is OrderCancelRequest. It is used to initiate the cancellation of a pending order or the outstanding amount of a partially filled order. 

Below is a sample of FIX-based OrderCancelRequest to cancel a pending order on Binance:

Our demo application will send requests to open an order (using NewOrderSingle) and to cancel it (using OrderCancelRequest) over the FIX to Binance. The server will notify us (using ExecutionReports) in real-time about any status changes of our order(s). 

In real life, it’s always a good idea to separate business logic that makes decisions about entering or exiting the market from orders management. This component is usually complex and covers a vast array of scenarios of what can happen with orders starting from regular behavior when everything goes as expected and ending with different doomsday scenarios. 

For the sake of simplicity, in this sample, we decided to use oversimplified orders management which also handles incoming market data-related events (OMS.java). 

Below is the video of the working system (replayed with 50х speed):

Building a successful trading system is a challenging task where you must overcome many obstacles. Our goal is to make sure that the connectivity between your application and target exchange (or exchanges) will not become one of these blocking factors. By using XTRD OEMS for digital assets trading, you can easily build a reliable system that can operate around the clock. Connect to our FIX API to trade on Binance or many other exchanges and/or to receive real-time normalized market data. Focus on your business and let XTRD be your ‘pipes and plumbing’ provider! 

Coinbase Pro API Review

By XTRD CTO Serg Gulko

Like most people, my first impressions are based on visual appeal. Yes, I realize that it might be the wrong approach to judge a book by it’s cover, but it’s hard to beat human nature.

As part of the crypto exchange integration process at XTRD, we usually familiarize ourselves with the exchange’s provided user interface, support systems, communication channels, public documentation, and so on. I remember that the day we started working on Coinbase Pro, I posted a long and exciting speech in the internal employee group chat about my findings.

After dozens and dozens of clunky, sometimes even absurd GUIs I’ve witnessed, Coinbase Pro was like a breath of fresh air. Everything was so polished, so smooth (no, smooooooth), and worked so intuitively, that I said — “guys, that’s why Coinbase is one of most popular platforms to trade crypto. Yes, fees are high but you enjoy the process. It’s like a switchover from an old Soviet Union “Zhuguli” to Mercedes Benz. Look, they even have a FIX API!”.

Image for post

But then we started working with Conbase’s API. First impressions can be deceiving. Below is the list of things that puzzled us (and which we solved).

Your order is not yours

The FIX protocol defines a special field called ClOrdId (Client Order ID) to carry client-assigned IDs of his/her orders. The client’s OME/EMS (order/execution management system) uses these unique IDs to track each order individually for many reasons. It could be execution, reporting, accounting, or of the above.

When the server receives and accepts the client’s order, it assigns its own ID to the order (transmitted using field OrderID). This is completely reasonable because you can’t rely on a counterparty to track orders. Your system, your rules, your order IDs.

Unfortunately, in Coinbase Pro, a client’s order IDs are not really clients’. In accordance with their rules, the field ClOrdId should contain a UUID string (something like this 58d1f436–6a53–11eb-9439–0242ac130002).

Any attempts to send something different — numbers (1,2,3…), strings (my_super_order_1, cool_order_132) or any other forms of IDs will be rejected. This means that your OMS/EMS should discard the existing methodology of client side ID generation (database IDs, timestamps, random strings, and so on) and start using Coinbase Pro rules. Time to rename ClOrdId to CoinbaseClOrdId!

Wait, UUID is not that bad for ID management, there are several other exchanges that use it. Why not adopt it and stop complaining?

Because there is another surprise with ClOrdIds on Coinbase Pro! Once an order is confirmed and you received the first ExecutionReport with OrderID, you’ll never see your IDs again. Any following update attempts to extract a list of open orders or trading history — everything will contain only the Coinbase-assigned ID.

So there are challenges to solve:

  • adopt your OMS/EMS to use UUIDs or build a mapper between your native IDs and what you send to Coinbase
  • build a matching mechanism that allows identifying orders using only OrderID and links it to ClOrdIds

Needless to say, our clients simply don’t know about the twists and turns of this plot. XTRD’s FIX API is designed in a way that doesn’t limit you or creates additional obstacles to solve. Your system, your orders, your rules.

XTRD allows the assignment of any type of IDs — numbers or strings. Each ExecutionReport (if successful) contains an OrderID (ID in our system, always a number), and an exchange-assigned ID (could be anything) that can be used for cross-checks between internal and exchange systems for a binary, synergistic execution verification and audit.

Image for post

As a final word: Coinbase Pro is a fantastic product and a great exchange to trade on — it’s normal that some parts of a very complex offering have minor rough spots.

XTRD’s job is to ensure that our clients’ awareness of integration difficulties only exists from our complaints in articles!

single_point_of_access_crypto_trading

3 Reasons a Single Point of Access is Hugely Beneficial for Those who Trade Cryptocurrency

Ten years into the crypto revolution and markets are still considered immature. Where traders on mainstream platforms have access to unlimited amounts of liquidity and a vast array of advanced tools to help facilitate their transactions, cryptocurrency traders still function in a sort of technological ‘stone age.’ 

If you want to trade on multiple exchanges, you have to create multiple accounts with different login credentials. Traders have to deal with separate fees and separate slippage, cutting into profits more and more. There is also the counterparty risk which gets multiplied with every exchange you interact with. 

While these problems might not bother small retail traders, it creates tremendous headaches for those looking to trade with larger sums of capital. This is one of many reasons that bigger financial players have yet to enter the cryptocurrency sector in a significant way.  

Thankfully, there is a solution coming. One which allows traders to interact with a single entity and reduce, or eliminate, the hassles and risks associated with trading across multiple exchanges.

How A Single Point of Access Improves Trading

Being able to have a single point of access (SPA) provides traders with the resources they need to function effectively and be successful. While the benefits of trading through a SPA are extensive, here we will focus on three in particular.

1. Ability to Interact with Additional Exchanges

A single point of access gives traders access to multiple exchanges. Why would anyone want such a thing?

The simplest reason is liquidity. In markets as shallow as cryptocurrency, it’s just not possible to transact with very large amounts of capital. It becomes necessary to buy/sell coins on several different exchanges simultaneously. 

Not all exchanges list all coins/tokens or all trading pairs that exist. The token you want may be absent on one exchange, listed in a BTC pair on another exchange, or possibly in a stablecoin pair such as USDC on yet another exchange. If you wanted to trade this hypothetical coin for a stablecoin using fiat, you would have to:

  1. Convert fiat to BTC,
  2. Move the BTC to the exchange with your desired coin, 
  3. Make a trade, 
  4. Move the new coin to another exchange, 
  5. Make another trade

After undergoing these five steps, in which you have racked up hefty fees (and a massive headache), you would finally have finished trading the coin you wanted in the stablecoin pair you were looking for.

2. Reduced Counterparty Risk

Trading anything on any platform comes with some kind of counterparty risk. To some extent, you always have to trust your funds in someone else’s hands for a certain length of time. This results in the possibility of something going wrong on part of the party holding your funds. 

The term “counterparty risk” refers to the risk of someone defaulting on their debt owed to you. In the case of cryptocurrency, some exchanges have mismanaged user funds in the past, resulting in traders losing most or all of their coins. The users in such cases fell victim to the counterparty risk inherent in holding coins on an exchange.

But going through the process described above multiplies counterparty risk to a large and unnecessary degree. Instead of being concerned with the potential of something going wrong at a single point of failure, you now have to endure risk at least three times over. 

3. Reduced Slippage and Fees

As if all the problems described above weren’t enough, you are also losing chunks of capital during this long and drawn out process. Every exchange you use charges its own fees, creates its own slippage (the small losses that result from large buy/sell orders being executed in multiple trades at different prices), and requires a network transaction or miner fee for moving crypto from one wallet to another. 

This can result in a trader incurring losses at the end of the day even if they make a profitable trade.

Being able to use a single point of access allows traders to keep things simple – one account, one trade, one simple and clear fee.

The Future of Crypto Trading Is About To Get Much Simpler

Multiple companies are currently developing a solution, but none has achieved industry-wide success yet. Currently, XTRD is the closest trading company to achieving a single point of access for traders. Very soon, it is likely that the industry will coalesce around a kind of cross-exchange trading mechanism that other financial markets have used for decades. This instrument will allow for improved transactionality, which can lead to not only the maturation of the industry, but to mainstream adoption of blockchain technologies.