
Cryptocurrency trading bot in ~40 lines of JavaScript - thomasfromcdnjs
https://github.com/thomasdavis/blockbid-ccxt-tutorials
======
gpderetta
In 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.

~~~
thomasfromcdnjs
It definitely should scare you =D

The script is a tutorial to help complete beginners have an understanding of
how to write a bot.

Though you're right, I should have really made it more clear because it is
real money.

~~~
jandrese
Well, "real" money since we're talking about cryptocurrencies here.

------
gildas
You 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
Thanks for the tip, I didn't actually know that technique.

~~~
gildas
You're welcome. Alternatively, you could simply use "for of" but the requests
won't be sent in parallel.

------
haolez
It 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)

------
dcsan
This 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
It 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
You 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
Wouldn’t you want your trading bot to have access to that volatility?!

------
rolltiide
One 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

~~~
short_sells_poo
> 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
Honestly, 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.

------
Severian
After 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
This will work!!

parseFloat((0.2 * 0.1).toFixed(10))

~~~
treve
The 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)

------
JustFinishedBSG
> no KYC required

Just believing really hard that the law doesn't apply to you doesn't make it
true.

~~~
koolba
I'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
Thanks 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
Are 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".

~~~
gridlockd
How exactly is exchanging cryptos with other cryptos conducive to money
laundering?

I can tell you why you want to avoid KYC: It's really annoying for the users
and it's labor-intensive for the company.

~~~
koolba
> How exactly is exchanging cryptos with other cryptos conducive to money
> laundering?

One of the fundamental rules of money laundering is that anything that can be
used for money laundering will be used for money laundering. Allowing
anonymous users to shift from one crypto to another could be part of a money
laundering routine. It does not have to include any fiat currency in the flow.

> I can tell you why you want to avoid KYC: It's really annoying for the users
> and it's labor-intensive for the company.

Ha! It's annoying, labor intensive, and a cost center for non-crypto companies
as well. I can assure you that the entire non-crypto financial services
industry would avoid it if they could as well.

~~~
gridlockd
> Allowing anonymous users to shift from one crypto to another could be part
> of a money laundering routine. It does not have to include any fiat currency
> in the flow.

What's the point? That's like exchanging cash for cash. I guess you could use
it to "launder" crypto in the sense that you can make transfers off-chain. The
exchange still has those records though, they don't need KYC to provide them,
if necessary.

------
mruts
If 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).

~~~
DennisP
Quantopian looks amazing, I hadn't seen that. How much historical data and
fundamentals do they have for equities?

~~~
mruts
They 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.

------
logiclogic
Advertisement for their API? Trading is gambling unless you have some insider
info to increase your odds. Only rich or stupid people gamble.

~~~
cubano
Actually, 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.

------
Can_K
Cool, 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
won't tax declaration only apply to executed orders? those will be much lower.

~~~
Can_K
Yes, with 20% you probably have good chances not do get anything taxable at
all

~~~
mercutio88
should 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 :-)))

------
throwaway77384
I 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
Why 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
I 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.

~~~
daveed
I think it really depends on your experiment, the size of the trades you're
making, and the restrictions you place on your backtest.

Otherwise, they could be an indication of future performance.

------
thomasfromcdnjs
Great to see people are interested in the tutorial.

I'd be happy to answer any questions to the best of my ability.

~~~
mercutio88
Cool 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
Yep, 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
the current implementation will do great on flash crashes :-)

------
snvzz
>trading programmatically

>trading _money_

>in javascript

Am I alone in thinking this is insane?

~~~
rubbingalcohol
No, 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.

------
unnouinceput
40 lines, yeah...I can do it in 2 lines even, if I use external libraries.
body onload="mybot();" and boom, I'm done.

------
alexeiz
When did Blockbid exchange launch? Looks like just yesterday. The btc/usd
order book is just 5 levels deep.

------
throwaway857384
It seems to be for a specific exchange that has $240 24 hour volume...

------
epscylonb
This looks great. Only 40 lines, that's some amazing golf right there.

~~~
analpaper
an included general purpose library with 40 lines of custom business logic?
that software can't be very smart lol

------
miroshnik
Is it profitable?

~~~
hotgeart
No. Don't day trade. Never.

