# Fork a market

Source: https://docs.tradefloor.dev/guide-fork.html

> Fork a tradefloor market to run two futures from one past: checkpoints, engine branches, and a counterfactual that runs one agent with and without a scenario.

A [fork](https://docs.tradefloor.dev/glossary.html#fork) copies a running market so you can run it forward twice with one input changed. The copies match bit for bit up to the fork, so any later difference comes from that change. The signatures are in the reference, [Forks and counterfactuals](https://docs.tradefloor.dev/api-counterfactual.html). Each code block on this page runs by itself.

## Two futures from one past

`tf.Checkpoint.of` marks a point in a running engine, with its [seed](https://docs.tradefloor.dev/glossary.html#seed) and [universe](https://docs.tradefloor.dev/glossary.html#universe), and `branch` builds independent engines at that point. Change one input in one copy and run both on.

```
import struct

import tradefloor as tf

def last_price(engine, ticker):
    # prices() is each last price as little-endian float64 bytes, in roster order
    prices = struct.unpack(f"<{len(engine.tickers)}d", engine.prices())
    return prices[engine.index_of(ticker)]

universe = tf.Universe.random(40, seed=7)
engine = tf.Engine(seed=42, universe=universe)
engine.run_days(60)                              # one shared past

mark = tf.Checkpoint.of(engine, universe=universe, seed=42)
calm, hiked = mark.branch(2)                     # two engines at day 60
print("identical at the fork:", calm.state_hash() == hiked.state_hash())

calm.run_days(20)
for _ in range(20):                              # one change, in one copy:
    hiked.pin_macro(corporate_bond_yield=0.09)   # a write lasts a day, so hold it
    hiked.run_days(1)
print(f"AAA after 20 more days: {last_price(calm, 'AAA'):.2f} calm, "
      f"{last_price(hiked, 'AAA'):.2f} with credit at 9%")

text = mark.to_json()                            # outlives the process
again = tf.Checkpoint.from_json(text).resume()
print("resumed from text:", again.state_hash() == engine.state_hash())
```

```
identical at the fork: True
AAA after 20 more days: 481.88 calm, 359.87 with credit at 9%
resumed from text: True
```

The state hash covers prices, all columns, the random generators and the economy, so equal hashes mean the two copies are the same market. Holding the corporate bond yield at 9% is the only difference between the two futures, and AAA ends about 25% lower under it. `pin_macro` writes a value for one day and the model moves it on from the next close, so the loop writes it each day. `Scenario.hold` does the same inside a scenario.

## Branch or checkpoint

|  | Cost | Survives the process |
| --- | --- | --- |
| tf.branch(engine, 2) | under 1 ms | no |
| Checkpoint.resume() or Checkpoint.branch() | seconds, growing with the order log | yes |

`tf.branch` copies the engine's state directly, including all columns and the position of each random stream. A checkpoint stores the order log and rebuilds the engine by replaying it, and it's the one to save and cite in a published result. A checkpoint records the universe's fingerprint and won't load against a universe that changed, since two universes can share tickers and differ in fundamentals. It also won't load on a build whose arithmetic differs from the one that wrote it, and the error names both builds. The arithmetic digest changed in 0.8.0, so a checkpoint written by 0.7.x loads only on 0.7.x.

## A counterfactual with an agent

A `World` holds the market, one agent, its portfolio and the macro path. Forking a world copies all of them, and the agent, with its position, then trades two markets that differ in one input. Here the agent buys 300 shares of AAA on the first step and holds them, and one arm gets the packaged `liquidity_crisis` scenario.

```
import tradefloor as tf

class BuyOnce:
    # buy 300 AAA on the run's first step, then hold
    def act(self, obs):
        return {"AAA": 300} if obs.step == 0 else None

universe = tf.Universe.random(24, seed=7)
world = tf.World(seed=7, universe=universe, agent=BuyOnce())
world.run(50)                                    # 50 shared days

control, stress = world.fork("control", "stress")
stress.apply(tf.Scenario.load("liquidity_crisis"))
started = tf.agree(control, stress)
print("identical at the fork:", started.identical)

control.run(80)
stress.run(80)
result = tf.compare(control, stress, agreement=started)
first = result.as_dict()["divergence"]
print("prices first differ on day", first["prices"] // first["steps_per_day"])
print(result.render())
```

```
identical at the fork: True
prices first differ on day 100
                                    control           stress
  ----------------------------------------------------------
  --- agent behaviour ---
  final gross exposure                0.14x            0.05x
  steps it traded on                      0                0
  orders sent                             0                0
  unusable responses                      0                0
  turnover                               $0               $0
  --- execution ---
  trades filled                           0                0
  partial fills                           0                0
  refused trades                          0                0
  cost against arrival                   $0               $0
  the same, in bps                +0.00 bps        +0.00 bps
  --- portfolio ---
  cash                             $852,945         $852,945
  final value                      $993,284         $897,983
  P&L since the fork               $-18,992        $-114,293
  return since the fork              -1.88%          -11.29%
  max drawdown since                  4.82%           14.21%
  P&L since inception               $-6,716        $-102,017
  return since inception             -0.67%          -10.20%
```

## Reading the comparison

`agree` checks that the two arms match in engine state, order books, portfolio, agent state and random-stream positions, and `compare` with `agreement=` states that in the result. The scenario's shocks start on its day 50, which `apply` counts from the day you apply it, so the arms run identically for 50 more days and first differ on day 100. `compare` finds that first step separately for the macro path, the agent's decisions, its orders, the prices and the portfolios.

This agent never trades after the fork. Both arms show no orders and equal cash, and the whole difference in value is the scenario's effect on its 300 shares. An agent that reacts to prices would show its decisions diverging too. An external agent, such as a model behind an [LLM adapter](https://docs.tradefloor.dev/llm-adapters.html), runs in a world like any other, and `world.manifest()` records the run as a [manifest](https://docs.tradefloor.dev/glossary.html#manifest), as in [Record and replay](https://docs.tradefloor.dev/guide-replay.html#recording-the-market).

The result describes this simulated market under the change you made. To claim something about a real market, you need evidence from a real market.

## Next steps
- [Scenarios](https://docs.tradefloor.dev/api-scenario.html) builds what `World.apply` takes.
- [World](https://docs.tradefloor.dev/api-counterfactual.html#world) lists every method of a world, including several agents in one market.
- Read [Measuring the market impact of your own orders](https://tradefloor.dev/market-impact.html), a guide that prices every fill against a fork where the order was never sent.
- Watch [Would my trading bot survive a crash?](https://tradefloor.dev/video-crash-test.html), a 2:15 video recorded on the hosted app.
