# Functions, types, enums and lists

> Simple on top, a full language underneath.

Source: https://algobarsx.com/docs/functions-and-types/

```algobarsx
type Level:
    price: price
    touched: int = 0
    formed_at: time

enum Regime: trending, ranging, volatile

fn swing_strength(len: int) -> number:
    up = highest(high, len) - close
    down = close - lowest(low, len)
    return (down - up) / atr(14)

action fn enter_long(size_risk: percent = 1%) -> bool:
    buy risk: size_risk, stop: 20 pips, target: 2R
    return true
```

- `fn` defines a pure function. It calculates and returns a value.
- `action fn` may place orders, so it can only be called where orders are allowed. A plain `fn` that tries to trade is an error ([AS0403](https://algobarsx.com/docs/diag-where-things-may-go/#AS0403)).
- `type` defines a record with named, typed fields and optional defaults. `enum` defines a fixed set of names.
- Parameters can have types and defaults: `fn f(source: series<number> = close, length: int = 20) -> number`.

## Lists and lambdas

```algobarsx
levels.push(Level(price: high, formed_at: time))
levels = levels.filter(l => l.touched == 0).keep_last(50)
ranked = levels.sort_by((a, b) => a.price - b.price)
```

Lists support `push`, `pop`, `remove`, `filter`, `map`, `sort_by`, `keep_last`, `first`, `last`, `len` and `contains`, plus the aggregates `sum`, `mean`, `min` and `max`. A lambda is written `x => expression`.
