8 ms·
Cryptocurrency trading bot in ~40 lines of JavaScript
- thomasfromcdnjs 7y agoGreat to see people are interested in the tutorial. I'd be happy to answer any questions to the best of my ability.
- mercutio88 7y agoCool stuff. 20% Deviation from the market price is quite high though. I suppose orders will never get a chance to execute. What would be a more realistic percentage? Could it be based on the current volatility for example? Or am I missing something.
- thomasfromcdnjs 7y agoYep, you are 100% correct. This is a very naive bot, it will rarely ever execute at that margin but you will never lose either. You are just betting on the fact that hopefully someone buys out the orderbook by accident or because they really want that asset. A more realistic margin is 0.0000001% but when you start doing that, you will start losing money so you will want a much better algorithmic trading strategy. I will probably write a hedging tutorial next.
- mercutio88 7y agothe current implementation will do great on flash crashes :-)
- uberneo 7y agoI can see that there is no variable of "fees" which usually applies even on a LIMIT order. For example Coinbase Pro has Maker fees of 0.15%. Ideally this fees should be added to BUY order and subtracted from SELL order, as that will actually cost you.
- miroshnik 7y agoIs it profitable?
- hotgeart 7y agoNo. Don't day trade. Never.
- epscylonb 7y agoThis looks great. Only 40 lines, that's some amazing golf right there.
- analpaper 7y agoan included general purpose library with 40 lines of custom business logic? that software can't be very smart lol
- Can_K 7y agoCool, until the tax declaration comes up. Luckily, there are now tools such as Accointing or CryptoTax that take care of the 30,000 transactions.
- mercutio88 7y agowon't tax declaration only apply to executed orders? those will be much lower.
- Can_K 7y agoYes, with 20% you probably have good chances not do get anything taxable at all
- mercutio88 7y agoshould there be successful executed orders in the magnitude of 30k. I'd be more than happy to handle the tax declation some way or the other :-)))
- rolltiide 7y agoOne redeeming quality of cryptocurrencies existing is that all the exchanges have REST compliant APIs and real time data available for free The finance sector’s biggest meme for the last decade and a half was that PhD quants were required to program trading algorithms when really a single exchange cost $12,000 a month for real time data, it came with horrible documentation, support, antiquated protocols, FIX, and then you had to figure out how to co-locate your own server to connect to the exchange fast enough to prevent front running The gatekeeping is what kept this specialized for the most part
- mercutio88 7y agoyou are so right
- short_sells_poo 7y ago> The gatekeeping is what kept this specialized for the most part. It certainly kept the vast majority of retail out, but I disagree that this was the main cause of specialization. I think that the number of lone geniuses who could've beat the market using algo trading is a number approaching zero. It's true that you don't need a PhD, or even higher education, as the math you need can be entirely self taught. However, you need plenty of specialized knowledge to avoid the accidental discharge of the vast number of very expensive footguns that litter the landscape. This knowledge can be gained from literature, but without having someone streetwise as a guide, it's going to be very difficult to discern genuine insight from wishful thinking.
- mruts 7y agoHonestly, it’s pretty easy to create a rough approximation of many popular hedge fund strategies. Like on Quantopian, it’s pretty easy to whip up a simple factor strategy in a couple hours. The returns aren’t bad, either. The part that is hard are trading costs and slippage. But assuming that retail investor’s capital is relatively small and no trading costs (Alpaca provides this), an individual can do pretty well. The parts that are hard for hedge funds is slippage, illiquidity of assets, trading costs, and client demands. As an individual you really don’t have to worry about those things and consequentially things become much easier. The only downside is that it’s harder to get as much cheap leverage as the big guys. Also some (HFT) strategies are off limits to individuals, but that’s fine, because HFT really isn’t a good way to make money in the first place.
- justanegg 7y agoa bot is the perfect way to set a really un-greedy strategy, and then just set and forget.
- deleted 7y ago[deleted]
- dcsan 7y agoThis is dangerous haha! It seems the price coming back from cryptonator doesn't update, TUSD is a stable coin but surely the bitcoin rate against it should be updating every 30s ? https://api.cryptonator.com/api/ticker/btc-tusd https://api.cryptonator.com/api/ticker/btc-tusd https://www.cryptonator.com/api/ https://www.cryptonator.com/api/ > Prices are updated every 30 seconds
- joosters 7y agoIt also seems exceptionally risky to grab a price off some random website and then trade blindly on another. Shouldn't you be getting the prices from the market you are actually trading in?
- thomasfromcdnjs 7y agoYou are correct, the code is more of a tutorial, it should have error prevention. I made it pull from a third party global average because an individual market can shift a lot depending on how volatile it is.
- jacksnipe 7y agoWouldn’t you want your trading bot to have access to that volatility?!
- dcsan 7y agomy point is the API above doesn't seem to update much at all. Maybe every 30 minutes? https://apiv2.bitcoinaverage.com/#price-data https://apiv2.bitcoinaverage.com/#price-data this seems like a better free API, wondering what others use? is there anything with tickdata not just 15s?
- JustFinishedBSG 7y ago> no KYC required Just believing really hard that the law doesn't apply to you doesn't make it true.
- cdiddy2 7y agoYa, that probably wont last long if the exchange is centralized. Would have to re implement on bisq/kyber/uniswap or another decentralized exchange for this to last without KYC. Then of course you have to deal with massively increased latency/network speed to settle trades.
- koolba 7y agoI'm scratching my head wondering what the hell that actually that's supposed to mean. Their terms when you sign up do mention a KYC process: > Blockbid is registered with the Australian Transaction Reports and Analysis Centre (AUSTRAC) which is the regulatory body that deals with the Anti-Money Laundering and Counter-Terrorism Financing Act 2006 (AML/CTF Act). > [... truncated ...] > Blockbid operates a Know Your Customer (KYC) and AML/CTF Program that meets the requirements of the AML/CTF Act (and associated laws).
- thomasfromcdnjs 7y agoThanks for finding this guys. Recently we moved to be a crypto to crypto exchange. Without fiat, we no longer are obliged to enable the KYC process for our users. We will most likely bring it back in as our fiat support matures.
- koolba 7y agoAre you still regulated by and report to AUSTRAC? If so, I do not see how you would avoid KYC. Hell, I don't even know why you'd want to explicitly avoid KYC unless your going out of your way to create a money laundering service. Also, there's some typos in those terms, ex: no space before email in "contact us atsupport@blockbid.io".
- 7y ago
- throwaway77384 7y agoI understand that back-testing is a foolish way to work out whether a bot works, but it'd be interesting to see how this performs on arbitrary lengths of past history. Like, is this enough to beat a lazy index fund calculated over the same time, with interest reinvested?
- gentaro 7y agoWhy is backtesting foolish? As long as you haven't used the data you're using to backtest in any way, it seems like a reasonable way to test your strategy.
- throwaway77384 7y agoI think I was mainly trying to avoid risking that anyone reads this and thinks past performance is an indication of future performance. Your point is perfectly valid and is a useful addition to my prior post.
- gingabriska 7y agoI think because the data you are backtesting doesn't react to the trades you make.
- tardis_thad 7y agoUnless you have order book data, then you can simulate market impact of your trades as well.
- mruts 7y agoIf any wants to try their hand at quant trading, Quantopian is a great place to get started. Great data sources and you can get allocated capital and make a little bit of money. Also the competitions are fun and you get paid $50/day for having (essentially) the best Sharpe ratio. If you want to trade your own money, Alpaca is really awesome. Pretty easy to import an algorithm from Quantopian and use it on Alpaca. I’ve been managing about 15% of my portfolio through Alpaca and it’s been great. On my account, I can get 4x intraday leverage, which has been absolutely awesome. Also there’s no trading costs, so I don’t have any problem with daily rebalancing (I actually rebalance to 4x leverage in the morning and deleverage at the end of the day). Highly recommended! There’s a lot of alpha in the market for retail investors (with leverage, no transaction costs, and the ability to short).
- edf13 7y agoSounds suspiciously like an ad...
- mruts 7y agoBecause I’m totally a salesmen for both Quantopian and Alpaca...
- DennisP 7y agoQuantopian looks amazing, I hadn't seen that. How much historical data and fundamentals do they have for equities?
- mruts 7y agoThey have minute data and a bunch of free fundamentals for US markets going back to 2002. If you want to trade equities, they should have everything you need. And if they don't, you can buy proprietary datasets for a reasonable price, or you can upload your own.
- Severian 7y agoAfter a cursory glance, is it me or is floating point being used? I thought this was something you wanted to avoid because of precision errors. ie 0.2 * 0.1
- uberneo 7y agoThis will work!! parseFloat((0.2 * 0.1).toFixed(10))
- treve 7y agoThe issue is more obvious when rounding something like 0.5, which, due to lack of precision can become either 0 or 1. Shameless plug: use https://www.npmjs.com/package/bigint-money https://www.npmjs.com/package/bigint-money
- gildas 7y agoYou might want to replace the `openOrders.forEach ...` call with a call to `await Promise.all(openOrders.map ...)` if you want to catch errors and stop the program when cancelling previous orders, and more importantly make sure you cancel orders before doing anything else.
- thomasfromcdnjs 7y agoThanks for the tip, I didn't actually know that technique.
- gildas 7y agoYou're welcome. Alternatively, you could simply use "for of" but the requests won't be sent in parallel.
- gpderetta 7y agoIn in experience the vast majority of the code of a trading application is dedicated to safety: pre/post trade checks, price checks, open notional, pnl delta limits, order rate, fill rate etc. And of course error handling and getting out of unexpected states safely and quickly. 40 lines of JS definitely scare me.
- flyGuyOnTheSly 7y agoAgreed. The bot I am currently working on is pushing 6,000 lines of code, and I feel like it might double in size before it's perfect.
- benj111 7y ago"40 lines of JS definitely scare me" Me too. I suppose it depends how you want to treat this though. As a bot programming challenge this seems fair enough. As something to entrust your or others life savings with? No.
- gridlockd 7y ago> As something to entrust your or others life savings with? No. As first rule, you shouldn't entrust anyone's life savings with a single trader. Forty lines of Javascript to me is far less scary than 40,000 lines. At least with forty lines, I can easily tell what the hell it is trying to do. In this case, it's just example code on how to use the API. Its "strategy" is to attempt to buy low and sell high. It doesn't really get any simpler than that.
- benj111 7y agoI was thinking more of the concept than this particular implementation. This is basically a minimum viable product for others to play around with. If that playing leads to bot trading competitions, fine. If it leads to someone building a 40k line monster and thinking it might be a good idea to entrust it with a meaningful proportion of anyone's savings.... No.
- thomasfromcdnjs 7y ago
- deleted 7y ago[deleted]
- haolez 7y agoIt used ccxt, which is a very big library with most of the infrastructure already implemented: https://github.com/ccxt/ccxt https://github.com/ccxt/ccxt
- snvzz 7y ago>trading programmatically >trading money >in javascript Am I alone in thinking this is insane?
- rubbingalcohol 7y agoNo, it is indeed fairly insane. It's a good proof-of-concept of API-based trading, but I am far too timid to trust this sort of thing to a bot, especially considering that other people are running better bots.
- notahacker 7y agotbf, you ought to be getting alarm bells from "Australian crypto exchange, no KYC required" long before we start looking at whether the coding approaches are remotely sane. Considering the well established likelihood of a flash crash in the markets you're trading in, the exchange's own code being stuck together with duct tape or your/their assets being frozen, you probably shouldn't be trading anything you're not willing to lose to buggy javascript anyway.
- alexeiz 7y agoWhen did Blockbid exchange launch? Looks like just yesterday. The btc/usd order book is just 5 levels deep.
- logiclogic 7y agoAdvertisement for their API? Trading is gambling unless you have some insider info to increase your odds. Only rich or stupid people gamble.
- cubano 7y agoActually, it's not irrational for non-rich smart people to gamble ie poker is a game where skill almost always wins the day, and betting baseball parlays can, with a good deal of study, land in a positive expectation. Furthermore, the sheer number of quite profitable high speed trading platforms seems to totally rebuke your assertion.
- logiclogic 7y agoThey all have radical ups and downs and the ones you read about have sponsorships. Welcome to noaccountfree99purecocainecasino. In the end the mass always lose. You want to talk about using machine learning in high speed trading? The initial investment cost will anyway keep anybody except jewberg goldsmith with 10mil of playmoney from making profit.
- lngnmn1 7y agoAnd 1Gb of node_modules
- unnouinceput 7y ago40 lines, yeah...I can do it in 2 lines even, if I use external libraries. body onload="mybot();" and boom, I'm done.
- throwaway857384 7y agoIt seems to be for a specific exchange that has $240 24 hour volume...