ledger

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: Apache-2.0 Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ledger implements the paper-trading simulated book: an in-memory cash balance, position map, fill journal with client_order_id idempotency, and exact fixed-point fee accounting.

Invariants:

  • all money/quantity math uses big.Int scaled decimals, never float64;
  • a repeated client_order_id returns the original result unchanged;
  • fills are all-or-nothing against displayed top-of-book size;
  • nothing here ever touches the network or credentials.

Index

Constants

View Source
const (
	FeeRateNumerator   = 7
	FeeRateDenominator = 100
)

FeeRateNumerator / FeeRateDenominator encode Kalshi's published trading fee formula: fee = 0.07 * P * (1-P) per contract.

View Source
const JournalCap = 10000

JournalCap bounds memory growth.

Variables

View Source
var (
	ErrInsufficientBook = errors.New("displayed book size does not cover the requested count")
	ErrDuplicateOrder   = errors.New("client_order_id already filled")
	ErrNoRestingOrder   = errors.New("no resting order to cancel")
	ErrJournalFull      = errors.New("fill journal reached its configured cap")
	ErrInsufficientCash = errors.New("paper balance insufficient")
	ErrInvalidInput     = errors.New("invalid price or count")
)

Typed errors surfaced through mcptools.Error codes.

Functions

func Fee

func Fee(priceDollars string, countFP string) (string, error)

Fee computes the trading fee for `countFP` contracts at price `priceDollars` using exact rational arithmetic: count * price * (1-price) * 7/100, rounded half-up to the count scale (2 decimals).

Types

type Fill

type Fill struct {
	ClientOrderID string    `json:"client_order_id"`
	Ticker        string    `json:"ticker"`
	Side          Side      `json:"side"`
	PriceDollars  string    `json:"price_dollars"`
	CountFP       string    `json:"count_fp"`
	FeeDollars    string    `json:"fee_dollars"`
	BookHash      string    `json:"orderbook_hash"`
	Simulated     bool      `json:"simulated"`
	At            time.Time `json:"at"`
}

Fill records one completed simulation.

type FillRequest

type FillRequest struct {
	ClientOrderID string
	Ticker        string
	Side          Side
	PriceDollars  string // limit/fill price quoted by caller (must equal book touch)
	CountFP       string
	BookPrice     string // top-of-book dollars from the fetched snapshot
	BookSizeFP    string // displayed size at that touch
	BookHash      string // hash of the snapshot used
}

FillRequest describes one simulated order.

type FillResult

type FillResult struct {
	Fill      *Fill  `json:"fill,omitempty"`
	Replayed  bool   `json:"replayed,omitempty"`
	CashAfter string `json:"cash_after"`
}

FillResult reports what happened, including idempotent replays.

type Ledger

type Ledger struct {
	// contains filtered or unexported fields
}

Ledger is the concurrency-safe paper book.

func New

func New(startCashDollars string) (*Ledger, error)

New creates a ledger seeded with paper cash, e.g. "100.00".

func (*Ledger) Execute

func (l *Ledger) Execute(req FillRequest) (*FillResult, error)

Execute simulates an immediate all-or-nothing fill.

Pricing rule: a bid (buy YES) pays the ask; an ask (sell YES) hits the bid. The caller passes BookPrice as the touch it wants to cross; we verify the requested PriceDollars equals it to prevent accidental mispricing, then charge fees per the published formula.

func (*Ledger) Snapshot

func (l *Ledger) Snapshot() (cash string, positions []Position, journal []Fill)

Snapshot renders current balance, positions, and journal.

type Money

type Money struct {
	Value *big.Int
	Scale int
}

Money is a fixed-point dollar amount as [value, scale]: value * 10^-scale. Prices use scale 4 ("0.5400"); counts use scale 2 ("10.00"). All arithmetic keeps full precision; only final rendering rounds (half-up) to the target scale.

func NewMoney

func NewMoney(value string, scale int) (*Money, error)

func (*Money) Add

func (m *Money) Add(o *Money, scale int) *Money

func (*Money) Mul

func (m *Money) Mul(o *Money, outScale int) *Money

func (*Money) Render

func (m *Money) Render() string

Render emits the decimal string with exactly `scale` digits after the point (truncation toward zero for negatives is acceptable for display of already-scaled values).

func (*Money) Sub

func (m *Money) Sub(o *Money, scale int) *Money

func (*Money) ValueSign

func (m *Money) ValueSign() *Money

ValueSign helper kept unexported-friendly: returns sign of value.

type Position

type Position struct {
	Ticker string `json:"ticker"`
	YesFP  string `json:"yes_fp"` // net YES contracts (negative == short yes)
}

Position is a net contract position in one ticker.

type Side

type Side string

Side is the single-book order side.

const (
	Bid Side = "bid" // buy YES (or equivalently sell NO)
	Ask Side = "ask" // sell YES (or equivalently buy NO)
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL