Skip to main content

A lightweight Python engine for simulating trading account balances, order states, and exchange-style constraints.

Project description

trading-state

trading-state is a small, focused Python library that models the dynamic state of a trading account, including balances, positions, open orders, and PnL, under realistic exchange-like constraints.

It provides configurable rules for price limits, notional and quantity limits, order validation, and order lifecycle transitions (new, partially filled, filled, canceled, rejected), making it easy to plug into backtesting frameworks, execution simulators, or custom quant research tools.

By separating “trading state” from strategy logic, trading-state helps you build cleaner, more testable quantitative trading systems.

  • Use Decimal to do all internal calculations

Install

$ pip install trading-state

Usage

Below are the most common workflows. For full parameter details, see the docstrings in each class.

1) Initialize state and market data

from decimal import Decimal

from trading_state import (
    TradingConfig,
    TradingState,
    Symbol,
    Balance
)

config = TradingConfig(
    account_currency='USDT',
    alt_account_currencies=('USDC',),
    benchmark_assets=('BTC',)
)
state = TradingState(config)

state.set_symbol(Symbol('BTCUSDT', 'BTC', 'USDT'))
state.set_price('BTCUSDT', Decimal('30000'))
state.set_notional_limit('BTC', Decimal('100000'))

state.set_balances([
    Balance('USDT', Decimal('10000'), Decimal('0'))
])

2) Create target exposure and manage orders

from trading_state import OrderStatus

exception, updated = state.expect(
    'BTCUSDT',
    exposure=Decimal('0.2'),
    price=Decimal('30000'),
    use_market_order=False
)
assert exception is None

orders, _ = state.get_orders()
order = next(iter(orders))

# Apply updates from the exchange
state.update_order(
    order,
    status=OrderStatus.CREATED,
    id='order-1',
    filled_quantity=Decimal('0.1'),
    quote_quantity=Decimal('3000')
)

# Update balances after fills
# according to websocket incomming messages (maybe)
state.set_balances([
    Balance('BTC', Decimal('0.1'), Decimal('0'))
])

state.update_order(order, status=OrderStatus.FILLED)

3) Record performance snapshots

from trading_state import TradingStateEvent, CashFlow
from datetime import datetime

def on_snapshot(snapshot):
    print(snapshot.time, snapshot.account_value, snapshot.realized_pnl)

state.on(TradingStateEvent.PERFORMANCE_SNAPSHOT_RECORDED, on_snapshot)

# Manual snapshot (e.g. end of day)
snapshot = state.record()

# External cash flow (deposit / withdrawal)
state.set_cash_flow(
    CashFlow('USDT', Decimal('1000'), datetime.utcnow())
)

4) Analyze performance

from trading_state.analyzer import PerformanceAnalyzer, AnalyzerType
from trading_state import TradingStateEvent

analyzer = PerformanceAnalyzer([
    AnalyzerType.TOTAL_RETURN,
    AnalyzerType.SHARPE_RATIO.params(trading_days=365),
    AnalyzerType.MAX_DRAWDOWN
])

state.on(
    TradingStateEvent.PERFORMANCE_SNAPSHOT_RECORDED,
    analyzer.add_snapshots
)

results = analyzer.analyze()
total_return = results[AnalyzerType.TOTAL_RETURN].value

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trading_state-1.0.2.tar.gz (69.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

trading_state-1.0.2-py3-none-any.whl (57.7 kB view details)

Uploaded Python 3

File details

Details for the file trading_state-1.0.2.tar.gz.

File metadata

  • Download URL: trading_state-1.0.2.tar.gz
  • Upload date:
  • Size: 69.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for trading_state-1.0.2.tar.gz
Algorithm Hash digest
SHA256 8313dc7a033c9bee136567fd756c40fa47e42e5378fca56b0df9a90e057474f5
MD5 5892513606c954d34c494f90fa79955f
BLAKE2b-256 8c49feb8a0b1c4b7568e062ae455622452e637856a8fdd638045626ac72c6b61

See more details on using hashes here.

File details

Details for the file trading_state-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: trading_state-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 57.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for trading_state-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 634006650fb0409c1626853160429577442f4fee4d9ad449b71ffc4551309eaf
MD5 c7fa949c304644d79e21085b8dfe8e93
BLAKE2b-256 774942181f4b2cfc8d06aa28265f1b964399bca1580e8ccb6acac6a94d559ee1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page