# LangGraph

Source: https://docs.tradefloor.dev/langgraph.html

> Run a LangGraph graph inside a simulated tradefloor market: its decisions become orders, and the run is scored and can be replayed without calling the model.

`tradefloor.integrations.langgraph` wraps any compiled LangGraph graph. The adapter runs your agent inside a simulated market on your machine. At each decision tradefloor sends it a JSON observation, checks the decision it returns, places the orders in the simulation and scores the run. [LLM adapters](https://docs.tradefloor.dev/llm-adapters.html) covers [the observation payload](https://docs.tradefloor.dev/llm-adapters.html#the-observation-payload) and [decisions and model calls](https://docs.tradefloor.dev/llm-adapters.html#decisions-and-model-calls) for all the adapters.

## Install

```
pip install "tradefloor[langgraph]"
```

## A first run

This runs with no API key. The graph's one node is a rule where a model would go.

By default the adapter sends the payload under `observation` and as `messages`. It reads the decision from a `decision` key, an `actions` key or the last message.

```
from typing import Any, TypedDict

import tradefloor as tf
from langgraph.graph import END, START, StateGraph
from tradefloor.integrations.langgraph import LangGraphAdapter

class State(TypedDict, total=False):
    observation: dict[str, Any]
    decision: dict[str, Any]

def decide(state: State) -> State:
    # a rule in place of a model: buy 200 of the first name when flat
    first = state["observation"]["assets"][0]
    if first["position"] > 0:
        return {"decision": {"actions": [], "rationale": "holding"}}
    order = {"symbol": first["symbol"], "side": "BUY", "quantity": 200}
    return {"decision": {"actions": [order], "rationale": "open"}}

builder = StateGraph(State)
builder.add_node("decide", decide)
builder.add_edge(START, "decide")
builder.add_edge("decide", END)
adapter = LangGraphAdapter(builder.compile())

market = tf.Universe.random(12, seed=4242)
card = tf.evaluate({"graph": adapter}, seed=4242, universe=market, days=5)["graph"]
print(card)
print(len(adapter.record), "decisions")
```

```
Scorecard('graph', pnl=448, return=+0.04%, trades=1, impact=+0.04bps, sharpe=n/a (short run), vol=0.2%, in_market=100%, exposure=0.01x)
5 decisions
```

The graph decides five times and trades once. After the first day it holds the name and returns an empty action list, which leaves the position as it is. To run the graph live, make the node call a model and leave the rest unchanged.

## Tested with

`langgraph` 1.2.12 and tradefloor 0.11.0.
