Live data from Hacker News

Case study: Algorithmic trading with Go

polygon.io

161–170 of 311 posts

Re: Case study: Algorithmic trading with Go

#161

I worked in HFT for a while. I find the whole space fascinating. I'm glad OP found similar thrills. "This aspect, the platform itself, seems to be often overlooked in most discussions. Many conversations revolve around strategies (mean reversion, trend following, linear regression, etc.), and backtesting, without fully addressing the practical mechanics or logistics of strategy implementation, particularly in the con…

Seems more pointless than crypto to be honest.

It's quite a statement. You're almost saying capitalism and efficient markets are pointless. Maybe they are, but I think it's nothing like crypto.

In the old days before HFT, you weren't sure you'd get the best price. You'd have to rely on a broker to make sure that happens, but as a retail trader you generally got a worse price/out of date price.

Nowadays with HFT you can get pretty much the best price anywhere. Those Now is it pointless to shave off even more ns in the all out war to grab a piece of the order flow? For retail and institutional investors, at a certain point, yes it's completely pointless.

But it's also just pure capitalism at work. HFT firms compete against each other, and the competition is about speed to provide the best price and volume. If you try to regulate with something like enforced delays, then what do you compete on instead?

Re: Case study: Algorithmic trading with Go

#162
post #84

Earlier quoted context omitted.

"they are the more straightforward part to build" More straightforward, heh, sure. But still damnably complicated. Which just goes to show how much money and how much engineering talent is invested in this world that these things are so taken for granted.

So many intelligent people applied for something that has no value whatsoever to humanity regardless of how you look at it.

HFT is _arguably_ better than advertising for society.

Re: Case study: Algorithmic trading with Go

#163
post #126

Earlier quoted context omitted.

Seems like every person I've ever met in M&A has ended up hating life because of their career choice. They seem to burn out in 5 years or so after salting away a million bucks or 3. Was that your feeling doing the HFT thing?

I work at an HFT firm. Most fun I've ever had.

But is that because of the excellent WLB and pay or because of the social impact?

Re: Case study: Algorithmic trading with Go

#164
post #130

Earlier quoted context omitted.

I think you're right! Go will never beat C++ in this aspect. I used Go because that's what I knew and for the non-professional trading I was aiming, C++ wouldn't have made much difference. My bottlenecks were network (1s+ per trade roundtrip) and chaotic unreliable crypto markets. Just note that Java is used in HTF, but it's a different beast than our average CRUD Java. For example this article states: "Essentially,…

I think there’s a way to disable GC in Go too, no?

Yep, you can with GOGC=off but then I would have to learn about how to generate less garbage in Go for long running processes. Which is good knowledge even for non-trading applications. I just didn't have the energy and time to try it.

Re: Case study: Algorithmic trading with Go

#165

Go itself, or any other language won't give you too much of an advantage. What gives you advantage is trading algo, which is always hard to find. I've spent months on figuring out the best parameters for trading. Ended up this working only on historical data, while in reality it was totally different. I could use Visual Basic, and it would be better than Go, Rust, or whatever it is out there, given the algo and strat…

You can make GC languages work for HFT if you do zero allocation code.

There are places that use Java and just preallocate all the memory they need at startup. Jane Street famously uses OCAML

Re: Case study: Algorithmic trading with Go

#166
post #92

I've been building a bot with Typescript because it is what I know and Python because of the tools available. It is an overwhelming lonely endeavor. With all my other projects, I've always worked on teams, although they have always been very small teams and most of my work was autonomous -- still there was the occasional meeting and stand-ups. I've been working on this for six months and thought about bringing a frie…

Count me in the group of solo algo trading developers. Maybe we should connect and chat.

There are dozens of us! I'd be open to a chat channel or something.

Re: Case study: Algorithmic trading with Go

#167
Nicely done.

A couple of pointers. One on data, one on that RAM usage.

First I’ll go with the RAM usage because this is hackernews and everyone loves algorithms.

—-

There are a lot of libraries out there that do technical analysis, and most of them are designed for batch processing. TALib is an example - it works on large data sets but is not appropriate for live trading because it repeats calculations over and over and over again. If you have 10000 datapoints and calculate indicators, it’ll calculate 10000 of them. Add one more bar, now you have a dataset of 10001 items, which TALib will calculate the indicators on from scratch. Or maybe you just feed the last 10000, and still perform that calculation over all of those, but save that 10001st oldest one. Either way, it’s bad. Same goes for every library I’ve seen, presumably because no one would open source a production grade indicator generation system.

The production approach to this is somewhat different. Turn your features into state engines. Most features are just running calculations that are very easy to perform once per bar.

Moving averages are a perfect example - for a moving average of N bars, store N items in a fixed size array on the stack and keep track of the latest index to be written to. When a new value (X) comes in, increment that index, and grab the value (Y). Modify your old mean by adding (X-Y)/N. Then write X over the old value Y (It’s a ring buffer).

For EMAs, it’s even easier, because you just need to keep track of a numerator and a denominator - nothing else is needed. On a new value X with the scaling factor A (such that A^halflife = 0.5), the numerator N becomes NA+X and the denominator D becomes DA+1. Divide the two and you’ve got your new value.

If an indicator depends on another, don’t recalculate it. Break the indicators down into fundamental calculations and you’ll often find a lot of redundant calculations being done. Rearrange it all so it fits. Automate that process if you enjoy that kind of thing like I do.

Most indicators can be handled this way. The indicators that can’t - are rarely useful. After all, what you’re tracking is the evolving state of the market, and if you’re doing gymnastics over an indefinite number of bars, it probably doesn’t mean much.

The end result is that you don’t end up accumulating memory throughout the day. You receive a bar, you throw it through your indicator generators (all of which using a fixed size of memory), then you discard the bar and wait for the next. Save state at the end of the day and load that on the following market day.

The result will be a speed up like you couldn’t imagine. I promise. I run an indicator generation engine in a container capped at 40MB ram on one CPU, and it generates hundreds in much less than a millisecond after the bar arrives.

—-

Now, onto data. I recommend cleaning your data. You have a screenshot of a Tesla chart in there with some funky highs/lows every so often. It has been a long time since I’ve worked with US equities (and gladly so, it’s a mess of a system!) but the following is the best of my recollection.

The trades you receive will come from several sources. For US stocks, there are several different venues that operate their own order books. These will operate as typical markets between the open and close of the day. By typical I mean that the bid and ask represent what you’d get if you market order instantly (which you can’t), and the market trades on them have to take from the bid and ask side of the order book (formed by people placing limit orders).

However. There’s also the ADF - the Alternative Display Facility. This is the DIY of trade reporting (and quote reporting, but no one does). If someone sells some shares to their grandmother for a low price in exchange for the recipe to her famous apple pie, the ADF is where they can tell other participants about that trade, manually, subject to fat finger errors, prices of weird fractions of cents, and very relaxed constraints on timing.

It’s also where dark pools post trades.

The problem with this is that this data has no direct relationship to the rest of the market. This is why, every so often, you’ll see those blips.

If you don’t clean them, they’ll play havoc with any indicator that uses highs and lows.

The other problem is that ADF trades - at least when I last analysed this very issue - are not rare. They make up a large fraction of trades. So my approach was to clean ADF trades more rigorously than the venues by matching them against prior prices from an ADF-free background.

Re: Case study: Algorithmic trading with Go

#168
post #158

When developing an automatic trading system the following aspects are important: - Data feeds and data ingestion. It can be a fairly independent component which collects data from different sources (might be even discussion forums) making it available to other components in some uniform format - Feature generation. The source data is rarely used in its original form for decision making and having good (informative) f…

Hey, thanks. Yeah, I agree with you. That's an oversight on my end. I'll tell you here though. I'm just using go routines and channels to talk between them and then a giant mutex for locking. That's basically it. So, as new data comes in, it builds aggregates (tick based candlesticks) as needed, this then triggers the the BUY logic loop on that new data, if something is detected, that triggers a IB API order. It is d…

Does it work synchronously or asynchronously? For example, if you integrate WebSockets then you could act as soon as you get new data. If it works synchronously then you regularly request data (say, every second) and then act.

If you process many positions and then choose top 5 candidates then do you choose one of them for buying or you can allocate resources between them (depending on some score)?

Re: Case study: Algorithmic trading with Go

#169
post #29
post #16

Earlier quoted context omitted.

Why not switch to Mojo lang for this? It's Python-compatible with Golang like performance from what I hear.

@eshnil (& others familiar with Mojo) I had not looked at Mojo... thanks for the pointer. In the past, I've had issues with library compatibility with compiled derivative languages of interpreted ones (eg: Crystal of Ruby, etc, etc). Know if Mojo directly uses existing Python ecosystem? I've been using Polars, etc.

> Know if Mojo directly uses existing Python ecosystem?

They say they do, including libs with C bindings.

Re: Case study: Algorithmic trading with Go

#170
post #124

Earlier quoted context omitted.

Go is great for network heavy apps like algo trading! I used Go to write trading algos that would find small windows of triangle arbitrages in crypto exchanges. Made me some money but the risk of a big loss made me stop pursing crypto trade and it required too much time and attention. It's a full time job from my experience. Reasons I could lose big at any given time if I scaled up the stakes: - Exchanges temporarily…

Have you tried non crypto markets

Yes but not with Go.

I read like 5 or so books about trading, mostly the classic ones, and tried to toy around with backtracking some self-made strategies using MetaTrader: https://www.metatrader4.com/en/trading-platform

First week was funny. I kept thinking I found goldmines with fine-tunned stochastic lagging indicators, only to realize that I overfitted and an algo that made me rich when tested against a certain period of time would make me go broke when applied to another period.

I tried applying some defense against local maximum, but to no avail.

Best I could do is tie after paying exchange fees. And that took me endless weekends toying around with code, reading books and articles.

My hunch is that algos that don't rely on external signals (i.e. news) need extreme technical edge like High Frequency Trading have with their ultra low latency and premium exchange data feeds.

And I wasn't ready to dive into news sentiment analysis and other external indicators.

Post reply on HN