Skip to content

Execution API Reference

financelib.trading.execution.Order(symbol: str, side: OrderSide, order_type: OrderType = OrderType.MARKET, price: float = 0.0, amount: float = 0.0, status: OrderStatus = OrderStatus.PENDING, filled_price: float = 0.0, filled_at: str = '', commission: float = 0.0, slippage: float = 0.0, order_id: str = '', created_at: str = (lambda: datetime.now().isoformat())()) dataclass

Represents a trading order.

Attributes:

Name Type Description
symbol str

Trading symbol.

side OrderSide

BUY or SELL.

order_type OrderType

Order type (market, limit, stop, stop_limit).

price float

Limit/stop price (0 for market orders).

amount float

Order quantity.

status OrderStatus

Current order status.

filled_price float

Actual fill price (after slippage).

filled_at str

Fill timestamp.

commission float

Commission paid.

slippage float

Slippage incurred.

order_id str

Unique order identifier.

created_at str

Order creation timestamp.

financelib.trading.execution.OrderManager(slippage_model: Optional[SlippageModel] = None, commission_model: Optional[CommissionModel] = None)

Manages order lifecycle — creation, tracking, and history.

Example

om = OrderManager() order = om.create_order("THYAO.IS", OrderSide.BUY, amount=100, price=172.5) om.fill_order(order.order_id, filled_price=172.55)

Source code in financelib/trading/execution.py
def __init__(
    self,
    slippage_model: Optional[SlippageModel] = None,
    commission_model: Optional[CommissionModel] = None,
) -> None:
    self.slippage_model = slippage_model or SlippageModel()
    self.commission_model = commission_model or CommissionModel()
    self._orders: Dict[str, Order] = {}
    self._next_id = 1

Attributes

total_commission: float property

Total commissions paid across all filled orders.

Functions

cancel_order(order_id: str) -> bool

Cancel a pending order.

Source code in financelib/trading/execution.py
def cancel_order(self, order_id: str) -> bool:
    """Cancel a pending order."""
    order = self._orders.get(order_id)
    if order and order.status == OrderStatus.PENDING:
        order.status = OrderStatus.CANCELLED
        return True
    return False

create_order(symbol: str, side: OrderSide, amount: float, price: float = 0.0, order_type: OrderType = OrderType.MARKET) -> Order

Create a new order.

Parameters:

Name Type Description Default
symbol str

Trading symbol.

required
side OrderSide

BUY or SELL.

required
amount float

Order quantity.

required
price float

Limit/stop price.

0.0
order_type OrderType

Order type.

MARKET

Returns:

Type Description
Order

Created Order object.

Source code in financelib/trading/execution.py
def create_order(
    self,
    symbol: str,
    side: OrderSide,
    amount: float,
    price: float = 0.0,
    order_type: OrderType = OrderType.MARKET,
) -> Order:
    """Create a new order.

    Args:
        symbol: Trading symbol.
        side: BUY or SELL.
        amount: Order quantity.
        price: Limit/stop price.
        order_type: Order type.

    Returns:
        Created Order object.
    """
    order_id = f"ORD-{self._next_id:06d}"
    self._next_id += 1

    order = Order(
        symbol=symbol,
        side=side,
        order_type=order_type,
        price=price,
        amount=amount,
        order_id=order_id,
    )
    self._orders[order_id] = order
    logger.info(f"Order created: {order_id} {side.value} {amount} {symbol} @ {price}")
    return order

fill_order(order_id: str, filled_price: float) -> Optional[Order]

Fill an order at the given price (with slippage and commission).

Parameters:

Name Type Description Default
order_id str

Order ID to fill.

required
filled_price float

Market price before slippage.

required

Returns:

Type Description
Optional[Order]

Updated Order object, or None if not found.

Source code in financelib/trading/execution.py
def fill_order(self, order_id: str, filled_price: float) -> Optional[Order]:
    """Fill an order at the given price (with slippage and commission).

    Args:
        order_id: Order ID to fill.
        filled_price: Market price before slippage.

    Returns:
        Updated Order object, or None if not found.
    """
    order = self._orders.get(order_id)
    if not order or order.status != OrderStatus.PENDING:
        return None

    actual_price = self.slippage_model.apply(filled_price, order.side.value)
    trade_value = actual_price * order.amount
    commission = self.commission_model.calculate(trade_value)

    order.filled_price = round(actual_price, 6)
    order.slippage = round(abs(actual_price - filled_price), 6)
    order.commission = round(commission, 6)
    order.status = OrderStatus.FILLED
    order.filled_at = datetime.now().isoformat()

    logger.info(
        f"Order filled: {order_id} @ {actual_price:.4f} "
        f"(slip: {order.slippage:.4f}, comm: {order.commission:.4f})"
    )
    return order

get_all_orders() -> List[Order]

Get all orders.

Source code in financelib/trading/execution.py
def get_all_orders(self) -> List[Order]:
    """Get all orders."""
    return list(self._orders.values())

get_filled_orders() -> List[Order]

Get all filled orders.

Source code in financelib/trading/execution.py
def get_filled_orders(self) -> List[Order]:
    """Get all filled orders."""
    return [o for o in self._orders.values() if o.status == OrderStatus.FILLED]

get_open_orders() -> List[Order]

Get all pending orders.

Source code in financelib/trading/execution.py
def get_open_orders(self) -> List[Order]:
    """Get all pending orders."""
    return [o for o in self._orders.values() if o.status == OrderStatus.PENDING]

get_order(order_id: str) -> Optional[Order]

Get an order by ID.

Source code in financelib/trading/execution.py
def get_order(self, order_id: str) -> Optional[Order]:
    """Get an order by ID."""
    return self._orders.get(order_id)

financelib.trading.execution.SlippageModel(fixed_bps: float = 5.0, volume_impact: float = 0.0)

Slippage model for realistic backtesting.

Parameters:

Name Type Description Default
fixed_bps float

Fixed slippage in basis points (1 bp = 0.01%).

5.0
volume_impact float

Price impact as a function of order size / volume.

0.0
Example

model = SlippageModel(fixed_bps=5) actual_price = model.apply(100.0, "buy") 100.05

Source code in financelib/trading/execution.py
def __init__(self, fixed_bps: float = 5.0, volume_impact: float = 0.0) -> None:
    self.fixed_bps = fixed_bps
    self.volume_impact = volume_impact

Functions

apply(price: float, side: str, order_size: float = 0, volume: float = 0) -> float

Apply slippage to a price.

Parameters:

Name Type Description Default
price float

Original price.

required
side str

'buy' or 'sell'.

required
order_size float

Order quantity.

0
volume float

Market volume.

0

Returns:

Type Description
float

Adjusted price after slippage.

Source code in financelib/trading/execution.py
def apply(
    self, price: float, side: str, order_size: float = 0, volume: float = 0
) -> float:
    """Apply slippage to a price.

    Args:
        price: Original price.
        side: 'buy' or 'sell'.
        order_size: Order quantity.
        volume: Market volume.

    Returns:
        Adjusted price after slippage.
    """
    slip_pct = self.fixed_bps / 10000
    if volume > 0 and order_size > 0:
        slip_pct += self.volume_impact * (order_size / volume)

    if side == "buy":
        return price * (1 + slip_pct)
    else:
        return price * (1 - slip_pct)

financelib.trading.execution.CommissionModel(rate: float = 0.001, minimum: float = 0.0)

Commission model for trade cost calculation.

Parameters:

Name Type Description Default
rate float

Commission rate as a decimal (e.g., 0.001 for 0.1%).

0.001
minimum float

Minimum commission per trade.

0.0
Example

model = CommissionModel(rate=0.001, minimum=1.0) model.calculate(10000) 10.0

Source code in financelib/trading/execution.py
def __init__(self, rate: float = 0.001, minimum: float = 0.0) -> None:
    self.rate = rate
    self.minimum = minimum

Functions

calculate(trade_value: float) -> float

Calculate commission for a trade.

Parameters:

Name Type Description Default
trade_value float

Total value of the trade.

required

Returns:

Type Description
float

Commission amount.

Source code in financelib/trading/execution.py
def calculate(self, trade_value: float) -> float:
    """Calculate commission for a trade.

    Args:
        trade_value: Total value of the trade.

    Returns:
        Commission amount.
    """
    return max(trade_value * self.rate, self.minimum)

financelib.trading.execution.OrderStatus

Bases: Enum

financelib.trading.execution.OrderSide

Bases: Enum

financelib.trading.execution.OrderType

Bases: Enum