ryanrborn

ryanrborn

A long-running GenServer holds orders, positions, strategy state, and operational flags for a system trading real capital. The post walks the actual state struct, the three categories of data inside it, the persistence model (write to the database before the broker, push heavy work to Oban, never persist candles), and the design principles that fell out of running it in production — including why mid-roll restarts refuse to resume rather than guess.

Showing Posts 1 to 10

derek-zhou

derek-zhou

strategy, market_data_source, account_manager — each is a map with a module key and additional context.

I suggest to flatten them into the parent struct, use tuples, or use new structs. A map is a bad choice because with a map I have to write the keys and I will make typos.

trading?, rolling?, portfolio_heat_warned, portfolio_heat_blocked — state machine flags that control what
the GenServer is allowed to do.

Boolean flags are bad choices to encode state machine states (sooner you will find some combinations are illegal). Ideally, they should use enum types but since Elixir does not have a true enum type I’d just use atoms.

ryanrborn

ryanrborn OP

Thanks Derek — both fair, and both in the direction I’d take this code if I were refactoring it now.

On the maps: bare maps with conventional keys are a typo waiting to happen, you’re right. They ended up that way because each handle carries module-specific context whose shape varies by implementation — a strategy handle for order-flow logic holds different keys than one for a calendar roll. A struct with module: and a free-form context: map would give me a static field on the part that actually dispatches without forcing a schema on the part that legitimately varies. That’s the refactor I’d make.

On the booleans: the case is strongest for portfolio_heat_warned / portfolio_heat_blocked, which are an escalation ladder rather than two independent flags. Collapsing them into portfolio_heat: :ok | :warned | :blocked makes the “blocked but not warned” state unrepresentable, which is exactly what you’d want. trading? and rolling? are closer to genuinely independent — rolling can be in progress while trading is administratively halted — but I’d still take a tagged status to force the question of which combinations are actually reachable.

Appreciate the careful read.

mudasobwa

mudasobwa

Creator of Cure

Either we call if FSM, or we have flags, tertium non datur. State machine is not an object having state field. There should be a single source of truth and any flags spread the responsibility inevitably resulting in a diverged inconsistent state sooner or later.

FSM has transitions and the transition callback in the only place where the decision might have happened.

ryanrborn

ryanrborn OP

Reading you again, your target is derek-zhou’s atoms-as-cure, but the same point lands on the concession I made to them. Renaming rolling? to status: :rolling doesn’t make it a state machine; it just retypes the flag. The FSM lives in the transition function, not the field type. That’s the right correction.

The struct as written has multiple operational flags doing what should be the work of one transition callback. A single transition function owning every legal move (and making the illegal ones structurally impossible) is the shape that wants to exist. :gen_statem is the obvious BEAM tool; a hand-rolled step/3 plus pattern-matched events is the lighter version.

What I’m curious about is where you’d draw the line for what belongs inside the transition function versus what’s an input to it. Some of those flags feel like events the FSM consumes, not states it carries, but I’d rather see you lay it out than guess. The distinction is one a lot of posts get wrong, this one included.

mudasobwa

mudasobwa

Creator of Cure

I would not draw this line whatsoever. As an author of Finitomata, I spent a lot of time playing with different ideas and I came up with the simplest one: each transition callback has an internal state and an incoming payload with each event.

Vidar

Vidar

I find using flags for state machines confusing. I have vague memories of designing state machines using binaries, truth tables and Karnaugh maps. Binaries would be similar to flags, so it can of course be done, but I rather not.

In my possibly naive mind deterministic finite state machines have only a single state at any time, only one valid transition at any time, and have transition callbacks to do side effects.

mudasobwa

mudasobwa

Creator of Cure

Correct.

Incorrect.

Not necessarily.

Vidar

Vidar

How do you do deterministic if there are several valid transitions from a state? It is certainly easier if there is only one.

mudasobwa

mudasobwa

Creator of Cure

Only one state is even easier, but not as handy. Deterministic finite automaton - Wikipedia

Vidar

Vidar

If I read that correctly that depends on using a Mealy state machine with inputs as added guides for a deterministic output, rather than a Moore state machine where there is only present state. For a deterministic Moore state machine I can not understand how there can be more than one valid output at a time?

I’ve used Finitomata earlier so thanks for that!

Where Next? Top

Trending in Blog Posts Top

bartblast
Hey folks, I just published a post about Hologram’s funding and where the project goes next - the short version: Curiosum as Main Spons...
New
pckrishnadas88
Hey everyone! :waving_hand: I’ve published Part 7 of the Building Distributed Systems in Elixir series, where we build core distributed ...
New
zorn
An educational side project in Elixir, Phoenix, and Tauri. I share what I learned while wiring Automerge into the BEAM, including how I s...
New
mudasobwa
So, instead of wasting my afternoon arguing with anonymous handles on X, I turned to my trusty, soulless assistant and said: “Listen, ple...
New
nathanl
Process labels are useful for visualization and debugging. Here’s why you should use them.
New
abreujp
New article: Elixir Project Structure — From mix new to a Growing Codebase I’ve published a new article in my Elixir learning series on d...
New
andreasronge
What happens if you design tools for LLMs instead of letting LLM use human tools ? Wrote a blog on why and what that enables. As I see ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews