Back

Crypto Trading on QuantConnect

Hey QC community,

We are excited to announce the launch of cryptocurreny backtesting and live trading on QuantConnect! We’ve partnered with GDAX to support their cryptocurrency exchange.  Using your GDAX account, your algorithms can now trade BTC, LTC and ETH currency pairs. Huge thanks to our community members who helped make Lean ready for crypto. In this post, I’ll demonstrate backtesting a cryptocurrency trading algorithm using python and describe how you can get started live trading cryptocurrencies with GDAX.

Attached is a simple backtest that demonstrates subscribing to BTCUSD hourly data and placing an BTCUSD market order. Initially, QuantConnect is offering a limited set of GDAX quote data for BTCUSD for backtesting, however, users can expect our crypto data library to grow soon. Clone the backtest below to start building your crypto trading algorithms.

In order to get your algorithm live trading, sign up for a GDAX account here: https://www.gdax.com/ . To live trade, you’ll need an api key, api secret and api passcode.  To get this information, login to your GDAX account and click API from the menu in the top right corner. Create a new API key that has permissions to ‘view’ and ‘trade’ and be sure to record the api key, api secret and api passcode. You now have all the information needed to launch your live crypto-trading algorithm! Simply click ‘Go Live’ from your algorithm and follow the wizard. Be sure to select Gdax as your brokerage.

Update Backtest








Imagine you have 1 BTC, $100USD and 100EUR in your account. Do you have BTCUSD or BTCEUR? Or EURUSD?

I understand how this can be confusing -- it confused me for a while too. In most brokerages they provide fictional "BTCUSD" currency pairs. In reality these don't exist - you only have dollars, euro's and coins. If you previously traded some of your dollars for euro's you might have an open position ("EURUSD"). But that historical trade/swap is only based on the memory of the brokerage; in reality you still only have dollars, euros and coins in your account. You may have less of one coin, and more of another; but there is no "BTCUSD" asset itself.

Because GDAX doesn't record these historical swaps we can't track it in production; so we have to start every algorithm at 0.

Once you make a trade we have internal state and can help you by displaying that position. Internally however we still record all these things as coins in the Cashbook.

2

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Just a general update; we have pushed an update to the history server and it should now serve the longer span resolutions. We also fixed a memory leak we discovered from adding in the quote data. We appologize for the production issues and hope its much more stable for everyone now =)

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Not to pile on and thanks a ton for the update, but I was wondering how or if the maker/taker model for fees is implemented/being implemented for GDAX.

0

@Nolan - We have a specific fee model for GDAX which is 0-fee for limit etc orders and 0.1% for market orders.

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Jared, I am still a little confused by this but I did more research on my end.  When I call portfolio.cashbook I get the folowing string 

CashBook = Value in USD BTC: ฿ XXX @ 5929.08 = $XXX.91 ETH: Ether 0.00 @ 317.18 = $0.00 USD: $ XXX @ 1.00 = $XXX ------------------------------------------------- CashBook Total Value: $XXX.0

 Is it possible to call the value of my BTC position directly?  It seems it should be possible being that my BTC position size is recognized in Cashbook.

0

This is a touch tricky to figure out as its only documented in the API tab; Cashbook is a dictionary of the "coins" you have.

self.Portfolio.CashBook["BTC"].ValueInAccountCurrency

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Thank you Jared!  

0

I'm having lots of fun with this ... I was wondering if you support
GDAX Limit Order "Post Only" which only provides liquidity ie fees = 0 which may not be the case with a "regular" limit order...

I have decent working algos but given the expensive fees on crypto trading I was wondering if I could optimise the execution a bit...

2

Indeed we do AlphAngel ! We just merged this last week so its totally undocumented but if you like living on the edge, give it a go! 

https://github.com/QuantConnect/Lean/commit/0b2a28b498ee9ea7ec3f60a7b9775c443b556d29

Stefano Raggi is probably the best person to give you an example.

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


@AlphAngel The PostOnly option for GDAX can be set in Initialize with this line and will be applied to all limit orders:
 

DefaultOrderProperties = new GDAXOrderProperties { PostOnly = true };
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Jared Broad, I still can't get the benchmark working for crypto. I've attached a backtest reproducing the problem.

Also, love the PostOnly option! You should release the Time in Force Policy options too, Immedaite or Cancel being the one I'm most interested in.

1


Also because I thought it'd be handy for others, here's my override of SetHoldings that uses limit orders so you don't have to pay fees! Just paste it into your class for new powers. Made to be tweakable.

# Override SetHoldings to use limit orders (ratio is of totalPortfolioValue.)
def SetHoldings(self, symbol, ratio):

security = self.Securities[symbol]
if not security.IsTradable:
self.Debug("{} is not tradable.".format(symbol))
return # passive fail
ratio = d.Decimal(ratio)
price, quantity = security.Price, security.Holdings.Quantity

# Keep 2% Cash (for the limit order, rounding errors, and safety)
totalPortfolioValue = self.Portfolio.TotalPortfolioValue * d.Decimal(0.98)

# +0.1% Limit Order
# (to make sure it executes quickly and without much loss)
# (if you set the limit large it will act like a market order)
limit = 1.001
desiredQuantity = totalPortfolioValue * ratio / price
orderQuantity = desiredQuantity - quantity
# limit needs to be inverse when selling
limitPrice = price * d.Decimal(limit if orderQuantity >= 0 else 1/limit)
self.Log("Limit Order: {} coins @ ${} per coin".format(orderQuantity, limitPrice))
self.LimitOrder(self.crypto, orderQuantity, limitPrice)

Use it like regular SetHoldings:

self.SetHoldings("BTCUSD", 1) # all in

Although order quantities are rounded for now, until someone fixes LimitOrder :).

2


Sorry there was a typo in the last line, but I can't edit so here's it all again:

# Override SetHoldings to use limit orders (ratio is of totalPortfolioValue.)
def SetHoldings(self, symbol, ratio):

security = self.Securities[symbol]
if not security.IsTradable:
self.Debug("{} is not tradable.".format(symbol))
return # passive fail
ratio = d.Decimal(ratio)
price, quantity = security.Price, security.Holdings.Quantity

# Keep 3% Cash (for the limit order, rounding errors, and safety)
keep = .03
usablePortfolioValue = self.Portfolio.TotalPortfolioValue * d.Decimal(1 - keep)

# +0.1% Limit Order
# (to make sure it executes quickly and without much loss)
# (if you set the limit large it will act like a market order)
limit = 1.001
desiredQuantity = usablePortfolioValue * ratio / price
orderQuantity = desiredQuantity - quantity
# limit needs to be inverse when selling
limitPrice = price * d.Decimal(limit if orderQuantity >= 0 else 1/limit)
self.Log("Limit Order: {} coins @ ${} per coin".format(orderQuantity, limitPrice))
self.LimitOrder(symbol, orderQuantity, limitPrice)
3

Hi

Something that would be very useful woudl be StopLimitOrder for crypto, as far as I can't tell it does not work. 

Since the exchange is very unreliable at the moment, it would be good to be able to protect yourself with StopLimitOrder stop losses. Based on recent incidents most of the time they would be executed when the exchange API crashes during big sell offs.

Is this something in the pipeline? (or something I did not test properly!) 

thanks,

0

@AlphAngel, sadly the GDAX API does not support StopLimit orders, very strange since they are actually supported in their trading platform (Stop -> Advanced -> Limit price). 

If enough people requested this feature (omission) to them, maybe they will add them to the API and we will quickly add them to the QC GDAXBrokerage implementation.

2

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


I see these currencies have historical quote data (like forex) so the data has accurate Ask/Bid prices. I can't remember, but does this mean that backtests buy at the ask and sell at the bid? I'm wondering if slippage is something to factor in or not with backtest results.

2

Crypto minute data has spread yes; sub-minute only has spread at the minute boundaries. This will buy and sell at the ask and bid price. 

You still need to worry about slippage as the depth of the market is shallow at the top of book. At most you'll normally only have 0.1 BTC etc available to trade. We have the depth data but LEAN doesn't support it yet so its on the todo.

1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Yes I'd absolutely love depth simulation, I'm working on a low-liquidity strategy but it's making unrealistically large sums of money in backtests because the backtester doesn't understand when the market is illiquid. I'll be trying live soon but it'd be great to see realistic performance historically.

0

.Plot() seems to be broken now in my example above? Throws fatal error that doesn't make sense to me.

0

This is so exciting! Thank you so much for all your hard work getting crypto added to QC. You guys rock! 

2

Haumed Rahmani, there are two bugs in the Plot method that we will fix ASAP.
Meanwhile, do not use self.Plot(string, value). Instead use self.Plot(string, string, float(value)):

self.Plot("Leverage?", "Leverage?", float(portfolio.TotalHoldingsValue / portfolio.TotalPortfolioValue)) # inaccurate
self.Plot("Price", "Price", float(security.Price))
self.Plot("Quantity", "Quantity", float(quantity))
1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


I just stumbled about the QuantConnect website and really like it. I'm more or less only trading in Crypto thus that's the important part for me. So a question would for sure be if there are plans to add other Crypto-Exchanges, cause honestly spoken, GDAX is one of the worst of them and only offers an extremly limited set of Trading-Pairs. The, in my opinion, interesting Crypto Exchanges are more Poloniex, Bittrex, HitBTC, COSS in the future (they are in Beta and don't have an API ready at the moment). The point is simply that trading Altcoins is the more interesting and rewarding part than trading Bitcoin/Ethereum/Litecoin.

3

Absolutely thomas_brawand! We're working on Bitfinex now. LEAN requires a reliable API and ideally streaming order messages so it does limit us to the major exchanges.

5

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Bitfinex is a step into the right direction ;) 

Thanks for the lightning fast answer

2

Another crypto exchange would be great! 

1

Hi, my experience live with gdax so far as been pretty poor, during the big selloff the API usually gets disconnected meaning your sell orders are not executed and you can place stop loss order so it is very risky... still works in mild market but just be aware that the connectivity is nto as realibale as with the big equity/Fx brokers... so you need to be on top of it !!

2

@AlphAngel have you had any luck with LimitOrders on GDAX? How did you do that?

I'm using the code by @Haumed_Rahmani but it doesn't work for Liquidate it seems, just SetHoldings.

0

Crypto is working fine for all supported order types - inc liquidate and set holdings. GDAX doesn't support virtual positions; I've given a detailed explaination at the link below. Lots of users seem to be stubling with this so we'll try and write something to help understanding/using crypto.

https://www.quantconnect.com/forum/discussion/3178/quotbtcusdquot---what-are-virtual-positions/p1
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


@Drew baker, I don't have any issues with Limit orders they work fine (even Post Only), I'm using c# not sure if it makes a difference..

1

Seconded on adding more exchanges--GDAX is only 9th of the Crypto exchanges by Daily Volume.

I'd love to see the top 8, including Binance, Bithumb, and Bitfinex (which you mentioned is indev) get prioritized and added ASAP!

3

What is the GDAX fee model assumption in backtesting and live paper trading? Is it 0.25% for market orders? Are they different in live vs backtesting?

0

+1  on the eventual adding of Bitfinex.

4

+1 on adding Binance.com

https://github.com/sammchardy/python-binance
4

I've only spent minimal time playing with QC (I live traded with Quantopian, then discovered crypto after Robinhood integration was killed off), but I'd become a paying customer if Binance was added.

2

Another crypto exchange would be great! 

2

During live trading on GDAX my algo will execute both buy and sell orders.  Yet, eventually, I will get this error in the log:

Unable to submit order with id -10 that has zero quantity.

and this log will repeat on every trade attempt until i stop the live trading.  Yet, both the QC platform and GDAX show I'm still holding a long position.  Does anyone know why it's showing zero quantity?  Does liquidate() automatically update my portfolio with zero quantity even if it hasn't actually sold my long position on the exchange? I ask this question because it doesn't make sense to me why it would be submitting zero quantity in the liquidate() command even after the QC dashboard shows I'm holding a position and this is also confirmed in GDAX.  At this point, I'm just grasping at straws, but I'm assuming SetHoldings() and Liquidate() both update the portfolio to it's respective quantity regardless of if the trade was actually executed.  Is this the case?   

I've seen various posts in the QC community to address latency issues, but is there a general concensous on which method works best?  

0

Ted Smith discussed in this thread - 

https://www.quantconnect.com/forum/discussion/2747/crypto-trading-on-quantconnect/p2/comment-8904
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Would this: 

SetHoldings(Symbol, 1);

verus:

SetHoldings(Symbol, 1.0);

be the cause of the log error:

Unable to submit order with id -10 that has zero quantity.

0

Is there any progress on adding another exchange? When do you think it will be ready?

0

Hi everyone Im very new to coding, but been in the trading game awhile, I am trying to deploy an algo live on GDAX but the only error im getting is a failure to get cash balance for GDAX brokerage, does anyone have any adivce for me?

0

COBINHOOD, take a look for a possible broker, low volume which is actually good for trade execution, ZERO fees with an extremely similar  API, Please Take A Look 

0

Jared Broad  any plans to add kraken for shorting?

0

Sorry, a noob here at coding.

Could someone explain this code to me

0

Can be in perl?:)

0

 Jared Broad 

Would be nice to see Bitfinex, Binance, Kraken or other crypto exchanges to QuantConnect

Gdax unfortunately has also several country restrictions.

Any plans?

0

Lots of plans Donkey! There are several open-source projects in the works now =) Brokerages are really hard but viliwonka is making some great progress. His team is working on Kraken and Binance. Bitfinex has stagnated after their USDT concerns. The branch could use some work. 

1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


+1 for Binance. They trade a fair bit of volume compared to the other exchanges and they have lots of altcoins. Data for backtesting is crucial. Their Kline API call isn't going to get the job done so someone will likely have to cut a deal with them to get their historical data. Complete order book histories would be very nice....

3

+1 binance, bitfinex and huobi

1

+1 Binance, Bitfinex and Huobi. Maybe as a stretch goal some consideration can be given to Bitmex. It is the largest exchange by volume, has the highest available leverage and supports websocket (for live pricing).

0

Yeah true !!

0

Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed