Meet Algolang
Algolang is a platform for developing, testing and running trading strategies. You describe a decision rule in a program; Algolang supplies its market data, tracks its orders and account, and records what happened. A backtest runs that program through historical observations. A live run connects it to supported live data and execution services. This book begins with backtests, because a small recorded experiment lets us inspect every decision and fill.
Despite the name, you do not begin by learning a new strategy language. An Algolang strategy is a standalone executable. The examples here are Go programs using the Go strategy SDK, a library that handles communication and bookkeeping. Other languages can participate by implementing a supported protocol, although their client libraries and supported features differ. The engine does not load your Go source: you compile it, then give algo the executable’s path.
No previous Algolang knowledge is assumed. The opening chapters explain the platform, the command line and the trading/data concepts used by the examples. Reading the source needs basic familiarity with Go structs, methods and conditionals, but each program is complete and its Algolang-specific parts are explained. You can run the supplied executable before changing its code. The website and technical reference provide further detail; neither is required to follow the journey in this PDF.
What you are building
A strategy answers questions such as: “When the last 20 daily closes average more than the last 200, should I buy?” A complete experiment must answer more: which instrument and price history, when the decision is possible, how much to buy, how the order might fill, what it costs and what happens if it does not fill. The moving-average formula is only one part of that experiment.
The useful unit of work is a run: a strategy executable, its input values, an instrument universe, a date window, requested data and execution settings, and an initial account. Changing any of these creates a different experiment. For example, a 20/200 rule on daily SPY and the same rule on hourly ES are different strategies in practical terms, even if their source is identical.
Our working cycle will be:
- State the trading rule and what observations it is allowed to use.
- Choose data, instrument metadata, sessions and a decision interval.
- Build the program and run a small, inspectable case.
- Follow signals through orders, actual fills, positions and costs.
- Evaluate longer samples and compare saved experiments, including periods that were not used to choose the rule.
Algolang supplies the machinery for those steps. A profitable report does not by itself establish that the rule generalizes, that all required costs were modeled, or that the live venue supports the same execution assumptions.
The platform and its boundaries
historical files / marketfeed archive / supported live source
|
data adapter process
|
v
Algolang engine (algo)
| ^
bars, events, state | | orders, cancellations
v |
strategy process + SDK
engine -> execution venue -> fills and account state
|
backtest simulator
or live broker
engine -> saved results -> reports / charts / exportsThe engine coordinates these exchanges; the diagram separates them to show which component owns each responsibility.
| Piece | Its job | What you do with it |
|---|---|---|
algo, the engine and CLI | Own the run clock, merge delivered series, validate and route orders, maintain the run record. | Choose a run configuration and inspect its result. |
Strategy executable, such as smacross | Read information available at a decision and propose orders. | Write the rule, its parameters and any private state. |
Go strategy SDK, imported as algolang | Handle process communication, callbacks, buffered series and the strategy’s view of positions and orders. | Implement a few methods instead of decoding messages yourself. |
| Data adapter | Resolve instruments and deliver requested bars or other observations. | Select the source and supply its inputs. |
| Venue adapter | Submit/cancel orders and supply execution outcomes. In a backtest it connects to the simulator; a supported live run connects to its broker path. | Select execution assumptions or the supported live configuration. |
| Reporting layer | Turn recorded results into terminal tables, HTML, CSV and portable exports. | Compare, audit and reopen experiments without rerunning their strategy. |
The strategy host is the engine’s machinery for starting the strategy process and presenting it through that common interface. A wire protocol is the message format used between processes. The standard Go SDK handles it. A strategy must leave standard output available for those messages; human diagnostics use ctx.Logf or standard error.
There are two separate data connections to keep in mind: adapter to engine, and engine to strategy. Choosing --data-protocol pb selects the adapter’s protobuf connection. It is not the name of an indicator or a trading rule, and it does not change what historical information existed.
Where marketfeed and the indicator libraries fit
Marketfeed is the companion market-data archive and adapter project. It acquires and organizes data, instrument identities, exchange calendars, continuous futures, equity adjustments and supported reference releases. Its adapter serves those products to Algolang. Installing an adapter does not populate the archive: a run still needs coverage for its symbols, intervals, dates and warm-up history.
The ownership split matters for reproducibility. Marketfeed supplies the continuous-contract schedule and adjusted series. Algolang follows that schedule and translates between the strategy’s price view and the venue’s raw contract prices. A strategy should not independently invent a different roll schedule while claiming to have traded the served continuous series. We work through this with diagrams and executable examples in continuous futures.
You can also begin without a marketfeed archive. The bundled file-CSV adapter reads local bars; the bundled Databento adapter reads recorded sample files. These are useful for tiny fixtures with an expected result. In this setup, marketfeed is the component that acquires vendor history; Algolang’s Databento file adapter is not a separate vendor-download workflow.
nseries supplies indicator and numerical calculations. Algolang’s indicators package adapts the SDK’s buffered data to that library, so the strategy can ask for an SMA, EMA, ATR and other calculations. strategies/kit contains reusable strategy helpers for tasks such as session handling, order reconciliation and persistent event indicators. These libraries are building blocks used inside the strategy process, not additional data feeds.
The vocabulary behind a run
| Term | Meaning in this book |
|---|---|
| Instrument / symbol | What the data or order refers to: an equity, a dated future, a continuous futures identity or a reference series. |
| Series | One stream of observations with its own identity and construction. One symbol can have daily and hourly series. |
| Bar | A completed summary of observations, usually open, high, low, close and volume over an interval. |
| Signal | A condition computed by the strategy, such as an upward crossover. It is not an execution. |
| Order | An instruction to buy or sell a quantity under specified conditions. It may remain working, be refused or be cancelled. |
| Fill | An execution of some or all of an order. Fills change the position and incur the applicable costs. |
| Position | The quantity actually held: positive for long, negative for short, zero for flat. |
| Trade | An opening and closing of exposure as paired by the reporting rules. One reversal order can close one trade and open another. |
| Equity | The account’s marked value, including open-position profit or loss and accounted-for costs. |
| Drawdown | A decline from a previous equity peak; it measures the path of losses, not just the final return. |
“Buy one” is an order quantity, not a target position. Buying one while short one leaves you flat. Moving from short one to long one requires buying two. The first crossover will compute this difference from the filled position, rather than keeping an isLong flag that changes on submission.
From a close to a recorded result
A normal run begins by checking the data source’s capabilities and resolving instruments. The engine starts the strategy, applies its inputs and negotiates the features it supports. The strategy declares its history, extra data and other requirements. The resolved universe and any requested calendars are provided before warm-up and decisions.
Warm-up loads earlier observations into the SDK’s buffers. Those bars help form an indicator; they do not invoke trading decisions. During the requested window, the engine delivers each eligible completed bar. The SDK updates the series and calls the strategy’s OnBar method. The method can return no orders, one order or several. The engine then validates them and hands admitted orders to the execution venue. Execution notifications update positions and working orders; later decisions read that updated state.
At orderly completion, the engine records results and shuts down the strategy. The last bar is not a promise that every order filled or that every position was closed. An open position contributes to marked equity but is not automatically a completed trade.
Here is a deliberately small arithmetic trace, separate from the crossover rule. Assume USD 1,000 initial equity, one share, a USD 0.01 tick, one tick of slippage on each market fill and USD 1 commission per fill. There are no other positions or costs.
| Observation or action | What changes |
|---|---|
| Monday closes at 100; the strategy returns a market buy for one share. | There is an order, but the position is still zero. Today’s close cannot justify buying at today’s earlier open. |
| Tuesday opens at 101; the buy fills at 101.01. | Position becomes +1. The adverse tick is in the execution price; commission is charged separately. |
| Tuesday closes at 104; the strategy returns a market sell for one share. | Gross open profit is 2.99 and marked equity is 1,001.99 after the entry commission. The position is still +1 until the sell fills. |
| Wednesday opens at 103; the sell fills at 102.99. | Position becomes zero. Gross trade profit is 1.98; two commissions make net account profit −0.02 and final equity 999.98. |
The simulator’s ordinary market-order convention makes a decision at one close eligible on the following bar’s path, normally its open. Different order types and finer execution data add rules, but they do not make future information available to an earlier decision. Slippage is already reflected in these fill prices: do not subtract the same amount a second time.
What a backtest tells you, and what to inspect
The fill simulator applies an execution model to the observations supplied. A daily OHLC bar tells us the day’s range, but not the ordering of every move inside it. If both a profit target and a stop lie inside that range, the answer depends on the chosen ambiguity policy or finer available data. A more detailed strategy does not compensate for missing execution evidence.
Start reading a report with the experiment itself: strategy and inputs, symbols and intervals, actual dates, warm-up, price adjustment, initial capital and execution costs. Then examine marked equity, drawdown, exposure, trade count and individual trades. A win rate alone ignores the relative sizes of wins and losses. A large gross profit can coexist with weak net returns after costs, and an unrealized loss can be hidden by considering only closed trades.
The results directory retains the structured result, trades, equity curve and an HTML report. An .algorun export packages the run set and its bars for later inspection; algo report can reopen saved results. Strategy logs explain decisions, fill exports show executions, and a lifecycle trace explains what happened to orders that did not simply fill. The next chapter gives the exact flags and paths for this reporting convention.
Deterministic means the same code, data, inputs and execution assumptions produce the same decisions and outcomes. Use the run’s clock rather than your computer’s current time; preserve build and dependency versions; record data, calendar and roll provenance. An archive correction or a changed commission is a changed experiment, even if the strategy’s source is unchanged. The ability to replay a result makes it inspectable; it does not remove selection bias or establish future profitability.
The route through this book
First build and call an existing program. Then learn how symbols, series, bars, sessions, price views and the SDK fit together. Hello provides a small non-trading observer, followed by the first complete trading rule: the 20/200-day crossover.
Each following strategy adds a reason to learn something new: account enquiries and a drawdown brake; extra symbols and clocks; published economic information; cross-exchange time zones; resting orders, brackets and session timers; continuous futures and explicit contract routing; relative-value and term-structure spreads; daily and intraday momentum baskets; activity bars and persistent event indicators. The event journal brings the callbacks together before portfolio and research evaluation. The final chapter records important limitations and desirable improvements. Complete annotated source accompanies every demonstration.