Bitfinex introduces mining contracts

Bitfinex announced today the start of mining contracts as a trading product on their platform. In total 100 THS (terahashes per second) with an expiration in 3 months have been made available for trading under the name TH1BTC. The 100 THS are part of a larger pool of 3500 THS so more mining contracts might become available in the future. Interestingly, this marks the first time that it is possible to short a mining contract.

Shorting a mining contract means to receive an amount of Bitcoin now (the price we sell it at) and subsequently paying dividends (in Bitcoin) over the following 3 month until the contract expires in the middle of December. A profit is made if the sum of all the dividends paid out (plus the interest we paid to short the contract) is less than what we received at the beginning when we sold the contract (to someone else obviously).

This means the price of TH1BTC should depend on 3 variables (in decreasing order of importance):

  1. The change of the mining difficulty until 15 December
  2. The time remaining until 15 December
  3. The interest rate (swap rate)

If difficulty increases dividend payments become smaller because 1 THS represents a smaller fraction of the whole network hashing power. Therefore the price of one contract should decrease if difficulty increases. The closer we get to expiration the fever Bitcoins can be mind with 1 THS in total. Therefore the price of one contract should decrease the closer we get to expiration and reach a price of 0 at expiration.

The higher the interest rate the more costly it is to enter and keep the contract over the full length of 3 month. Bitfinex does not offer 90 days swaps, therefore entering a contract with the goal to hold it until the end contains quite a bit of interest rate risk because at some point a new swap has to be taken out (at a potentially unfavorable interest rate). This is less of a problem when going long (Bitcoin rates are typically low) than when going short (there is only a maximum of 100 contracts available in total, no naked shorting). To compensate for the risk prices should increase when swap rates are increasing.

The big unknown is of course the change in the mining difficulty over the next 90 days. In the following figure we see how difficulty changed over the previous 6 month.

Change in difficulty over previous 6 month

The data is from Tradeblock and it shows not only a graphical representation of past changes in the difficulty (difficulty changes every 14 days depending on past hash rate. More info can be found in the wiki) but also some basic summary statistics. On average difficulty has increased 27% over the last 30 days and 77% over the last 60 days.

To estimate the fair price of one TH1BTC we will assume that difficulty will increase on average 15% per month over the next 3 month. Currently the price of buying one contract worth 1 THS is 2 BTC. The pool fee is 3% and we will ignore interest rates. Filling in all the information we get the following results:

Inputs and Results

Hence if we go long one contract based on our assumptions we would make a loss of about 0.39 Bitcoin (a bit more in reality since we will start mining in the middle of September until the middle of December) because the expected dividends (monthly revenue) is not going to cover our initial costs of 2 BTC before the contract expires.

On the other hand, going short at a price of 2 Bitcoin would have generated a profit of about 0.39 Bitcoin per contract. Keep in mind that we didn’t include swap costs which are currently at around 1% per day (!).

There are two ways to look at the results. Either we could say prices for TH1BTC are currently overvalued and should be closer to around 1.5 BTC. If we assume difficulty will increase more than 15% per month then prices should be even lower than that. Or we could say that the market is efficient and prices are correct, which would imply that the market is expecting difficulty to decrease on average about 2% per month over the next 90 days. Either way, results will be known with certainty in 90 days.

Bitcoin prices flash crash on BTC-e due to margin calls

Struggling to recover from the most recent Bitcoin flash crash which originated on Bitfinex only four days go, Bitcoin prices took another dive today as margin traders got their positions liquidated on BTC-e.


The event started at 1:36 PM (UTC+1) when large sell orders began to show up on the third largest western Bitcoin exchange BTC-e. Downwards momentum increased steadily as the orderbook became increasingly thin, crashing prices to a low of USD 309 per Bitcoin at 1.43 PM. In the following minutes prices rebounded swiftly on thin volume back to around USD 442 as arbitrage traders started to take advantage of the discount relative to other exchanges.

BTC-e is one of the few large exchanges that offer margin trading to their clients via the MetaTrader platform since November 2013, but the details of who excactly provides the funds necessary for margin trading have remained unclear. The shape and especially timing of the crash points towards margin traders being liquidated (or stop orders being executed), similar to what happened on Bitfinex a couple of days ago.
However, unlike Bitfinex which is transparent about open swap positions, BTC-e does not provide important data which would be needed to provide a more thorough analysis and so this last statement can only be considered a good guess.

Unlike Bitfinex, which relies on a hidden algorithm in an effort to control the order flow, BTC-e seems to have no special safeguards in place to mitigate such events. The fall below 400 was mainly due to a lack of bids in the orderbook and not because the market believed that the true value was below 400, as the rebound back to over 440 only minutes later basically proved. Hence, halting trading during extreme downwards volatility could have easily averted the bloodshed among margin traders by giving other market participants more time to thicken the orderbook.

Update 4:58PM (UTC+1):
BrCapoeira posted on Reddit an interesting graph based on data from the Metatrader platform:

second chart

This graph implies that a single large order was the cause of this event. Whether this order was created due to a margin call, a simple mistake, to manipulate the market, or to open a large short position remains unclear. Common sense would suggest that it was probably the result of a margin call of a single large trader.


Follow up: Bitcoin flash crash August 2014 and the importance of transparency

My previous post on this topic has been brought up during discussions in the aftermath of the most recent Bitcoin flash crash. Coindesk was one of the first to pick it up and since then various posts about transparency and the possible responsibilty of exchanges to actively manage order execution started to appear.
As a result of those events Josh Rossi, Vice President of Business Development at Bitfinex, went on Reddit to openly address some of the issues brought up against the exchange.

What we know

The facts we know for sure are that there were some large sell orders shortly before the crash started, for example a 500 sell order on Bitstamp at 9.49am (UTC+1), about 6 minutes before a large sell order on Bitfinex triggered the crash. However, the data does not tell us whether it was insider trading, some form of market manipulation, or a simple mistake.


Fact is that after the Bitcoin flash crash open swap positions decreased from around $28m to $24m which indicates about 8400 margin long positions were closed (assuming an average of $475) in one way (margin call) or another (stop order hit). The data does not tell us what the ratio is but according to Josh only about 650 Bitcoins were sold as the result of margin calls.


As correctly pointed out by Jonathan Levin, fact is that starting about 24 hours before the bitcoin flash crash until the crash itself an additional 1000 Bitcoins were taken out in short positions and about 2500 shorts were subsequently closed during the crash. Whether those shorts were opened to hedge existing positions, as a malicious attempt to trigger a margin call, or a way to front-run the market using private information cannot be determined from the available data (it does look oddly suspicious though).

BTC Swaps

What was unexpected

Personally, the interesting point is not that Bitcoin flash crashed. Sudden price fluctuations happened in the past and will happen in the future, especially in illiquid markets such as Bitcoin. The interesting point is the involvement of Bitfinex and how they actively managed order execution without informing market participants in advance.

The Bitfinex matching engine was not halted during the whole crash though it did slow down (but nowhere as bad as the infamous 70 minute order lag on the now defunct MtGox exchange during the crash in 2012). However, what Bitfinex did was they introduced something they now refer to as speed bumps. What it means is that they essentially flag orders they deem as invalid or potentially dangerous and slow them down intentionally.

At first sight this might seem like a nice idea. Who doesn’t want a filter to remove or slow down malicious orders? However, as so often with those kind of things the devil is in the detail.

The problem is that Bitfinex has not (and possibly never will) make public how exactly they categorize an order as “bad” and “slow it down”. If a market participant decides to put up a large sell order against a thin orderbook then that’s his decision. Whether his action was intended or not is not up to the exchange to decide.
It might be that this market participant was simply the first person to react to a major event and is entirely willing to bear the additional costs of the resulting slippage in anticipation of a major price move. There simply does not exist a way to accurately classify orders a priori as “good” or “bad” since that would automatically assume knowledge of all immediate future events.

What can be improved

Mistakes (“fat finger”, algorithm going havoc) happen, margins get called and people try to game the system in every possible way. Logically there have to be safeguards in place to protect markets and its participants. Bitfinex was definitely aware of potential toxic order flow and prepared counter measures. The only thing they forgot was to inform their clients about the hidden safety features.

Hiding those safeguards from the public adds uncertainty to the market (especially now that we know they exist and sometimes do something) and essentially puts every traders trust into the hands of Bitfinex. At this point a trader can only hope that Bitfinex will always act in the best intentions of their clients. This hope might be futile though, since Bitfinex makes money from trading fees, independently whether a trader actually makes any money. One does not have to think for long to realize the hidden potential for abuse in such a system.

The main reason brought up by Josh why Bitfinex does not intend to publicise their algorithm is to avoid giving traders the possibility to exploit it is bogus and the following shows why.

circuit breaker

Those are the official market wide circuit breakers used by NASDAQ, posted online and entirely transparent for every market participant. Those rules are certainly not perfect but they are simple, transparent, and work for one of the largest stock markets in the world.
Now, I have great respect for the people working on the Bitfinex platform, but I doubt that they managed to come up with an algorithm which protects market participants better than the ones used by a major exchange trading more than 900 million shares per day on average. And if they did, now is the chance for Bitfinex to prove it to the world and possibly write history by teaching the big boys how to properly run an exchange.


When it comes to public exchanges transparency is a must, not just for Bitfinex but for any exchange. Market participants have to know exactly what happens when they place an order and should under no circumstances have to rely on good faith alone. Safeguards are important because accidents happen and markets crash but it is not up to the exchange to engage in secret order discrimination. There are different ways to safeguard financial markets and none of them is perfect. Adding complexity usually increases the chance for unintended side effects and therefore a simple, transparent approach seems more appropriate than a hidden, complex one.

Review BitMEX Market Maker


Two days ago BitMEX reduced their trading fees to 0 and celebrated it by releasing a basic market making bot on Github.

BitMEX is currently running a trading challenge until August 29, 2014 to promote their new platform. Releasing a market marking bot is probably an interesting and effective way to increase API traffic and stress test the platform a bit. Of course I couldn’t resist and had a look.

Market-maker is a forked off Liquidbot, which was original designed to run on the now obsolet MtGox exchange. There were some minor changes (new api class to connect to BitMEX, some additional prints to console, changes to adapt for futures contracts, and a huge and unnecessary print to console when starting up) but no significant changes to the trade logic.


The algorithm uses REST and only checks for changes every 60 seconds. This already disqualifies the bot as it is essential too slow to react to ongoing changes in the orderbook. BitMEX limits requests to the REST API to 150 per 5 minutes so you can try reducing the 60 seconds to something like 3 but it won’t change the fact that as soon as markets start to move you will hit the limit and be stuck with open positions.
To be fair, BitMEX provides the bot more as a marketing stunt and explicitly states that switching to WebSocket will be highly beneficial as it allows real time updates.

Overall, the algorithm is solidly written, technically works and is easy to setup, but it won’t make you any money in the long run. If someone seriously considers to employ this bot I would recommend the following small changes to make the code more usable:

  • 1. Change to Websocket
  • 2. Exit position on close:
        def exit(self):
        def run_loop(self):
            while True:
                except (KeyboardInterrupt, SystemExit):
                    print "Shutting down, cancelling open orders"
  • 3. Build orders starting from the midpoint:
        def get_ticker(self):
            ticker =
            midpoint = (ticker["buy"] + ticker["sell"])/2
            self.start_position_buy = midpoint
            self.start_position_sell = midpoint
            print timestamp_string(), 'Current Ticker:', ticker
            return ticker

In addition I would advise to measure volatility in some way and adapt the distance between orders dynamically as well as the size.

During my testing the API was always responsive and accurate. Volume on the exchange is still low but the fundamentals of the platform look promising. This bot is a fun tool to introduce users into the world of market making and algorithmic trading but it won’t stand a chance against established algorithms.

If you consider using this algorithm keep in mind that market making is a full time job. Anything less than complete dedication, fast reaction time, and 100% uptime will cause you to lose money.

Bitfinex: cascading margin calls resulting in flash crash

Edit: Follow up on the aftermath here

Today Bitcoin prices took a dive as margin traders on one of the largest exchange Bitfinex got their orders liquidated. For many close market observers and more sophisticated traders this did not come as a surprise. In fact, long positions have been building up continuously over the last couple of months in anticipation of a new bubble in Bitcoin prices and reached as high as $30m in outstanding swap positions on Bitfinex.

Now, this wouldn’t be a problem all by itself as long as there is enough capital backing the loan. Unfortunately, most of those long positions were entered around 600 – 640 USD/BTC and the collateral was mostly provided in Bitcoins itself. The following chart nicely shows the buildup of long positions, peaking around July 14 with close to $32m in swaps.


Running some quick math based on the maintenance margin of Bitfinex of 13% and assuming Bitcoin as collateral we find that margin calls should start around the 520 – 540 USD/BTC mark. Yesterday, prices came close and today they finally jumped over the cliff.

Prices came close

The problem is that once margin calls set in you have a cascading effect which rips through the order book, causing even more orders to reach the point of no return and increasing the downward momentum further. These kind of events are not limited to Bitcoin exchanges but can also occur on major exchanges such as during the 2010 flash crash in the US. The cause of such a flash crashe can vary and goes from fat finger mistakes to programming errors to cascading margin calls.

It is interesting to see how the exchanges deal with these events. In the US, Nasdaq implemented market wide circuit breakers which will cause trading to stop under such extreme circumstances.
Bitcoin markets are not yet as advanced and usually continue trading. If we look at the order action on Bitfinex today we see something very peculiar:


It seems (and this is just a guess as there is no official comment from the exchange) as if Bitfinex is running an algorithm to handle the margin calls. The algorithm starts selling but limits itself to a 10% drop in prices within 1 minute. If prices drop more than 10% in 1 minute it will stop selling and wait for buy orders to come in. Once there are again a certain amount of buy orders in the orderbook the algorithm starts selling again until all margin calls are met.
Edit: LeMogawai was the first to point this out in this post and it matches my personal observation at the time of the event.

This seems to be an interesting way to deal with cascading margin calls but can also be considered as borderline market manipulation from the exchange side. By spreading out the sell orders over time the downwards momentum is reduced, however traders end up trading against the exchange itself and not the market anymore. The exchange has an informational advantage at that point and is therefore more likely to profit than the traders. Fortunately, this only lasted for about 10 minutes after which control was given back to the market.

Other exchanges which also offer margin trading such as BTC-e and OKcoin are now in a favorable position and can learn from todays events. Implementing a system more closely resembling the circuit breakers of big exchanges such as Nasdaq might be a smart first move.

Predictability of Bitcoin Returns using Simple Trading Strategy

Screenshot 2013-11-25 19.30.56

Recently I am working to get my new trading platform going. This new version is based on Python, uses MySQL to keep a database of all time series of different virtual currencies with automatic backfill from BitcoinCharts and integrates the 3 major exchanges MtGox, BTC-E and Bitstamp. The platform will be used as way to backtest some strategies and engage in automatic trading.

During the run-up to this I decided to pull some data of BTC against USD from BitcoinCharts and based on the ideas of a paper by Hashem and Timmermann (1995) implemented a simple trading strategy. The idea is to forecast the sign of the t+1 period return based on a regression, which is estimated on an automatic selection of technical indicators during the last n period up until t. Then, after t+1 happened, we refresh the model and try to predict t+2 using all the data available of the last periods until t+1 and so on.

Continue reading

Paper: High Frequency Trading Rules in Forex Markets

For my Bachelor Thesis I examined four different technical trading rules in Forex markets. It uses MCS and SPA test to search for valid models among different parameters that are not subject to data snooping. Taking into account realistic transaction costs we find no evidence of excess returns, which is consistent with market efficiency.

Continue reading

BTC-e Arbitrage Code written in Python

url3With this code you should be able to look for Bitcoin arbitrage opportunities within BTC-e. It uses the idea of one price and applies triangular arbitrage, taking into account costs and spread. The reason I post this here is despite that it works, chances are you will be too slow to compete with other investors doing the same.

Possible improvements would be to take into account the order book depth and split the trades up dynamically, trying to undercut other traders doing the same. Also setting everything up on a dedicated server close to the physical location of the BTC-e match engine should drastically reduce lag and give you a potential edge.

Continue reading