{"_id":"@binyyds/lmsr-calculator","_rev":"7-0e4a3cef6994fd6b852aa9f53d40f9c2","name":"@binyyds/lmsr-calculator","dist-tags":{"latest":"1.0.9"},"versions":{"1.0.3":{"name":"@binyyds/lmsr-calculator","version":"1.0.3","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.3","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"7526f0dd721d00a5744aa56cea1895b2247da437","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.3.tgz","fileCount":18,"integrity":"sha512-XhWWhaEzNiaQVGptxl08wOxCfMMWtAuqSTlJvudbNB80bmPiwh1h7DLPoQ+56xh4VrsLu4FP8dO2zC67ZE1gMA==","signatures":[{"sig":"MEQCIAZljOsyPJhOZbg7Er8jhyMQgB5K1/gVfEHgyJuS0v9VAiBY25aSqZMfYPUvlo2yac6G2d+YuH+fEDfbGE8QwAGyRw==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":43287},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.3_1758513600445_0.33748271042663847","host":"s3://npm-registry-packages-npm-production"}},"1.0.4":{"name":"@binyyds/lmsr-calculator","version":"1.0.4","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.4","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"82994d0a959f446b74464fe1a7a2a7e3970c17a4","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.4.tgz","fileCount":18,"integrity":"sha512-3XPTbPyd65qcyyRkNeA6FqoTHKVaw7per8xkNvDYUc6pTyk4712n90SDFzo9Y9Nu1toL5fUzR9B5PWClUtgKeQ==","signatures":[{"sig":"MEUCIClsTwnTiLlgXYQG1T4eaN/VMAwBoWk90Hoo8UzEDnMGAiEAvBxswwMzb8ifxU8U3bygsp9iPUNknn/hWXhkffxzZdM=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":74573},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.4_1758517266490_0.4854609252540629","host":"s3://npm-registry-packages-npm-production"}},"1.0.5":{"name":"@binyyds/lmsr-calculator","version":"1.0.5","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.5","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"3ab0e0c6701ba941ce7338e2b7bdc71f724f8aad","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.5.tgz","fileCount":18,"integrity":"sha512-uVU+60mLXv3aMk5F7kAySMb0XKR5gsDXeC4HYjwXnryUmaQF8Ss++1UmExDoZ2tftun7EImldfrBQfYu0vtmgw==","signatures":[{"sig":"MEYCIQCpYwkJk9WT5Q61JTlb28FZ2HtmyuqKtFosYyenjvyifwIhALzPyWHfyH4Ic6MRe6N71A/55P/pFmz/+WSG8tNjkglD","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":80479},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.5_1758942343362_0.6832218858415431","host":"s3://npm-registry-packages-npm-production"}},"1.0.6":{"name":"@binyyds/lmsr-calculator","version":"1.0.6","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.6","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"2227b70b9d4623d2e172afa6711ee5df64ceea66","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.6.tgz","fileCount":18,"integrity":"sha512-Su0EakiILe7GsMpSOPbL+3ENN96HFqlN5S3gCFRv5VaGq6zPxH2UqUBmdp5HnFKgqgyw5aqtgbz1zBDavnTrTA==","signatures":[{"sig":"MEUCIQDdhvPJdPlgV6j+VQieSKK3APJpJHiOxJAPnOriCBO6ZgIgH3sEgnsnrJGp8bkvZ7e2m9SRmrB/kF3WF/5QlLs0/Lc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":82504},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.6_1759030385524_0.6184002065166829","host":"s3://npm-registry-packages-npm-production"}},"1.0.7":{"name":"@binyyds/lmsr-calculator","version":"1.0.7","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.7","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"17c0ba3c03acd6774e5eb80f716d42f2e5d30d3f","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.7.tgz","fileCount":18,"integrity":"sha512-M/w2tN21Xc4pWKKccjKqrNAOsUkSbnLeL8KGXyzHRIyuE3BF8+cam0KzDjw6Q5eLDtjAgJ1WxfRs9ajNOn7p0g==","signatures":[{"sig":"MEQCIG/Sj8DR0350YaLwf+/7vY79mhuh3d2BVzHAurL4Ru9pAiBJF9hDlEkY4cajOwe+qUQ6L1MctoruuqQ3svkHdcjwZQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":82851},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.7_1759030913645_0.9115838153539602","host":"s3://npm-registry-packages-npm-production"}},"1.0.8":{"name":"@binyyds/lmsr-calculator","version":"1.0.8","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.8","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"homepage":"https://github.com/voteforx/voteforx_maker#readme","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"dist":{"shasum":"c3d025ecce57ef4cf889d5dafe1b2c976fbf837d","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.8.tgz","fileCount":18,"integrity":"sha512-lP34EAlq5t96XzQipJJM3mXea9skObQ3vc4MKwgu4GEfIyR3wYUCWLh/tiO3a5kMkvH/Dcp/nkWAlQAM39270A==","signatures":[{"sig":"MEUCIFtHZP2cRVYhJDhG1RwBGy07NnwCrel9mAlGK9yx8u2aAiEAyR1fGqOT2OJ5LsfcniDPkaoTapgogj2PVhRguuTM1gs=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":84556},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","scripts":{"dev":"tsc --watch","test":"vitest","build":"tsc","prepublishOnly":"npm run build"},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"repository":{"url":"git+https://github.com/voteforx/voteforx_maker.git","type":"git","directory":"packages/lmsr-calculator"},"_npmVersion":"10.9.3","description":"LMSR (对数市场评分规则) 算法计算器","directories":{},"_nodeVersion":"22.19.0","dependencies":{"decimal.js":"^10.4.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0"},"_npmOperationalInternal":{"tmp":"tmp/lmsr-calculator_1.0.8_1759039110992_0.6840429709157465","host":"s3://npm-registry-packages-npm-production"}},"1.0.9":{"name":"@binyyds/lmsr-calculator","version":"1.0.9","description":"LMSR (对数市场评分规则) 算法计算器","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","dev":"tsc --watch","test":"vitest","prepublishOnly":"npm run build"},"keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"dependencies":{"decimal.js":"^10.4.3"},"devDependencies":{"@types/node":"^20.10.0","typescript":"^5.3.0","vitest":"^1.0.0"},"repository":{"type":"git","url":"git+https://github.com/voteforx/voteforx_maker.git","directory":"packages/lmsr-calculator"},"license":"MIT","_id":"@binyyds/lmsr-calculator@1.0.9","gitHead":"d8f37f886d4cdf9d9dbc4cf09c1256f2ad29771a","bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"homepage":"https://github.com/voteforx/voteforx_maker#readme","_nodeVersion":"22.19.0","_npmVersion":"10.9.3","dist":{"integrity":"sha512-+H2AlNVkzSVrkbYLjuJEZn9G53v6CowWfGojqmE2hJ7CINWtQzDP5pPHiqqk7+VylojrWXw8Ywwvhb95Rnx+2A==","shasum":"5616b14bc386fe7e5f3fbce4041beccc15f3c929","tarball":"https://registry.npmjs.org/@binyyds/lmsr-calculator/-/lmsr-calculator-1.0.9.tgz","fileCount":18,"unpackedSize":84281,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIFh8dXeTUD+0qtcAc4jlio1oKlHcHoQDFUl9dffLbTTQAiEAlGXBH1zz5qU7BqeMzxgirUdumJHdD0+0rnGMeNLcO3Q="}]},"_npmUser":{"name":"binyyds","email":"binyyds@proton.me"},"directories":{},"maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/lmsr-calculator_1.0.9_1759139510218_0.41229764349970166"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-22T04:00:00.370Z","modified":"2025-09-29T09:51:50.588Z","1.0.3":"2025-09-22T04:00:00.631Z","1.0.4":"2025-09-22T05:01:06.716Z","1.0.5":"2025-09-27T03:05:43.618Z","1.0.6":"2025-09-28T03:33:05.853Z","1.0.7":"2025-09-28T03:41:53.818Z","1.0.8":"2025-09-28T05:58:31.207Z","1.0.9":"2025-09-29T09:51:50.380Z"},"bugs":{"url":"https://github.com/voteforx/voteforx_maker/issues"},"license":"MIT","homepage":"https://github.com/voteforx/voteforx_maker#readme","keywords":["lmsr","market-scoring","prediction-market","market-maker","typescript"],"repository":{"type":"git","url":"git+https://github.com/voteforx/voteforx_maker.git","directory":"packages/lmsr-calculator"},"description":"LMSR (对数市场评分规则) 算法计算器","maintainers":[{"name":"binyyds","email":"binyyds@proton.me"}],"readme":"# @voteforx/lmsr-calculator\n\nLMSR (对数市场评分规则) 算法计算器 - 用于预测市场的自动做市商算法实现。\n\n## 📖 简介\n\nLMSR (Logarithmic Market Scoring Rule) 是一种数学上严格的自动做市商算法，广泛应用于预测市场。它通过对数函数来确定价格和交易成本，能够：\n\n- 提供连续的流动性\n- 确保价格的数学一致性\n- 自动调节市场深度\n- 控制做市商的最大损失\n\n## 🚀 安装\n\n```bash\nnpm install @voteforx/lmsr-calculator\n```\n\n## 📚 基本用法\n\n```typescript\nimport { LmsrCalculator, createInventoryFromNumbers } from '@voteforx/lmsr-calculator';\nimport { Decimal } from 'decimal.js';\n\n// 创建 LMSR 计算器\nconst calculator = new LmsrCalculator(new Decimal(100)); // 流动性参数 B = 100\n\n// 创建市场库存\nconst inventory = createInventoryFromNumbers(50, 30); // YES: 50, NO: 30\n\n// 计算公允价格\nconst prices = calculator.calculateFairPrices(inventory);\nconsole.log(`YES 价格: ${prices.priceYes.toFixed(4)}`);\nconsole.log(`NO 价格: ${prices.priceNo.toFixed(4)}`);\n\n// 计算购买成本\nconst cost = calculator.calculatePurchaseCost(inventory, 'YES', new Decimal(10));\nconsole.log(`购买 10 个 YES 的成本: ${cost.toFixed(4)}`);\n```\n\n## 🔧 API 文档\n\n### LmsrCalculator\n\n主要的 LMSR 计算器类，提供所有 LMSR 相关的计算功能。\n\n#### 构造函数\n\n```typescript\nconstructor(liquidityParameterB: Decimal | number | string)\n```\n\n**参数说明：**\n- `liquidityParameterB`: 流动性参数 B\n  - **类型**: `Decimal | number | string`\n  - **说明**: 控制市场流动性深度，值越大流动性越好但做市商风险越高\n  - **推荐范围**: 50-500（根据市场规模调整）\n  - **示例**: `100`, `new Decimal(250)`, `\"150.5\"`\n\n#### 主要方法\n\n##### calculateFairPrices(inventory)\n\n根据当前库存计算公允价格，基于 LMSR 算法的核心价格公式。\n\n```typescript\ncalculateFairPrices(inventory: MarketInventory): LMSRPrices\n```\n\n**输入参数：**\n- `inventory`: 市场库存对象\n  - **类型**: `MarketInventory`\n  - **属性**:\n    - `yesQuantity`: YES 结果的净持仓量（`Decimal`）\n    - `noQuantity`: NO 结果的净持仓量（`Decimal`）\n  - **示例**: `{ yesQuantity: new Decimal(50), noQuantity: new Decimal(30) }`\n\n**返回值：**\n- **类型**: `LMSRPrices`\n- **属性**:\n  - `priceYes`: YES 结果的公允价格（`Decimal`，范围 0-1）\n  - `priceNo`: NO 结果的公允价格（`Decimal`，范围 0-1）\n- **数学保证**: `priceYes + priceNo = 1`\n- **示例**: `{ priceYes: Decimal(0.6234), priceNo: Decimal(0.3766) }`\n\n##### calculatePurchaseCost(inventory, outcome, quantity)\n\n计算购买指定数量份额所需的成本，基于 LMSR 成本函数。\n\n```typescript\ncalculatePurchaseCost(\n  currentInventory: MarketInventory,\n  outcome: 'YES' | 'NO',\n  quantity: Decimal | number | string\n): Decimal\n```\n\n**输入参数：**\n- `currentInventory`: 当前市场库存\n  - **类型**: `MarketInventory`\n  - **说明**: 交易前的库存状态\n- `outcome`: 购买的结果类型\n  - **类型**: `'YES' | 'NO'`\n  - **说明**: 要购买的市场结果\n- `quantity`: 购买数量\n  - **类型**: `Decimal | number | string`\n  - **说明**: 要购买的份额数量，必须 > 0\n  - **示例**: `10`, `new Decimal(25.5)`, `\"100\"`\n\n**返回值：**\n- **类型**: `Decimal`\n- **说明**: 购买成本（总价），始终 ≥ 0\n- **计算公式**: `Cost = C(q + Δq) - C(q)`\n- **示例**: `Decimal(45.67)` 表示需要支付 45.67 单位成本\n\n##### calculateMarketScore(inventory)\n\n计算 LMSR 市场评分函数 C(q)，用于内部计算和风险评估。\n\n```typescript\ncalculateMarketScore(inventory: MarketInventory): Decimal\n```\n\n**输入参数：**\n- `inventory`: 市场库存\n  - **类型**: `MarketInventory`\n  - **说明**: 要计算评分的库存状态\n\n**返回值：**\n- **类型**: `Decimal`\n- **说明**: 市场评分值，代表当前状态下的总成本函数值\n- **数学公式**: `C(q) = b * ln(e^(q_yes/b) + e^(q_no/b))`\n- **用途**: 成本计算、风险评估、状态比较\n\n##### generateOrderBook(inventory, config)\n\n基于当前库存和配置生成多层订单簿，用于自动做市。\n\n```typescript\ngenerateOrderBook(\n  inventory: MarketInventory,\n  config: OrderGenerationConfig\n): OrderBook\n```\n\n**输入参数：**\n- `inventory`: 当前市场库存\n  - **类型**: `MarketInventory`\n  - **说明**: 用于计算公允价格的基准库存\n- `config`: 订单生成配置\n  - **类型**: `OrderGenerationConfig`\n  - **属性**:\n    - `liquidityParameterB`: 流动性参数（`Decimal`）\n    - `orderDepthLevels`: 订单深度层级（`number`，推荐 3-10）\n    - `orderSpreadPerLevelBps`: 每层价差基点（`number`，推荐 10-100）\n    - `orderAmountPerLevel`: 每层订单数量（`Decimal`）\n    - `maxInventoryExposure`: 最大库存敞口（`Decimal`）\n\n**返回值：**\n- **类型**: `OrderBook`\n- **属性**:\n  - `bids`: 买单数组（`OrderBookLevel[]`）\n  - `asks`: 卖单数组（`OrderBookLevel[]`）\n- **OrderBookLevel 结构**:\n  - `price`: 订单价格（`Decimal`，0-1 范围）\n  - `quantity`: 订单数量（`Decimal`）\n  - `outcome`: 订单类型（`'YES' | 'NO'`）\n\n##### checkInventoryRisk(inventory, maxExposure)\n\n检查当前库存是否超出风险敞口限制。\n\n```typescript\ncheckInventoryRisk(\n  inventory: MarketInventory,\n  maxExposure: Decimal | number | string\n): RiskCheckResult\n```\n\n**输入参数：**\n- `inventory`: 要检查的库存\n  - **类型**: `MarketInventory`\n  - **说明**: 当前库存状态\n- `maxExposure`: 最大允许敞口\n  - **类型**: `Decimal | number | string`\n  - **说明**: 风险控制阈值，通常为资金池的一定比例\n  - **示例**: `1000`, `new Decimal(5000)`, `\"2500.50\"`\n\n**返回值：**\n- **类型**: `RiskCheckResult`\n- **属性**:\n  - `isWithinLimit`: 是否在限制内（`boolean`）\n  - `currentExposure`: 当前敞口值（`Decimal`）\n- **计算方式**: `|yesQuantity - noQuantity|` 与 `maxExposure` 比较\n\n## 📊 数学原理\n\n### LMSR 公式\n\n1. **市场评分函数**:\n   ```\n   C(q) = b * ln(e^(q_yes/b) + e^(q_no/b))\n   ```\n\n2. **公允价格**:\n   ```\n   P(yes) = e^(q_yes/b) / (e^(q_yes/b) + e^(q_no/b))\n   P(no) = e^(q_no/b) / (e^(q_yes/b) + e^(q_no/b))\n   ```\n\n3. **购买成本**:\n   ```\n   Cost = C(q + Δq) - C(q)\n   ```\n\n其中：\n- `b` 是流动性参数\n- `q_yes`, `q_no` 是各结果的库存数量\n- `Δq` 是购买数量\n\n## 🛠️ 工具函数\n\n### 库存操作函数\n\n#### createEmptyInventory()\n\n创建一个空的市场库存对象。\n\n```typescript\ncreateEmptyInventory(): MarketInventory\n```\n\n**返回值：**\n- **类型**: `MarketInventory`\n- **内容**: `{ yesQuantity: Decimal(0), noQuantity: Decimal(0) }`\n- **用途**: 初始化新市场或重置库存\n\n#### createInventoryFromNumbers(yesQty, noQty)\n\n从数字创建库存对象。\n\n```typescript\ncreateInventoryFromNumbers(yesQuantity: number, noQuantity: number): MarketInventory\n```\n\n**输入参数：**\n- `yesQuantity`: YES 结果数量（`number`）\n- `noQuantity`: NO 结果数量（`number`）\n\n**返回值：**\n- **类型**: `MarketInventory`\n- **示例**: `createInventoryFromNumbers(100, 50)` → `{ yesQuantity: Decimal(100), noQuantity: Decimal(50) }`\n\n#### createInventoryFromStrings(yesQty, noQty)\n\n从字符串创建库存对象，支持高精度小数。\n\n```typescript\ncreateInventoryFromStrings(yesQuantity: string, noQuantity: string): MarketInventory\n```\n\n**输入参数：**\n- `yesQuantity`: YES 结果数量字符串（`string`）\n- `noQuantity`: NO 结果数量字符串（`string`）\n\n**返回值：**\n- **类型**: `MarketInventory`\n- **示例**: `createInventoryFromStrings('100.5', '50.25')` → 高精度 Decimal 对象\n\n#### normalizeInventory(inventory)\n\n标准化库存对象，确保类型正确。\n\n```typescript\nnormalizeInventory(inventory: { yesQuantity: any, noQuantity: any }): MarketInventory\n```\n\n**输入参数：**\n- `inventory`: 包含 yesQuantity 和 noQuantity 的对象\n\n**返回值：**\n- **类型**: `MarketInventory`\n- **说明**: 将输入转换为标准的 Decimal 类型\n\n#### cloneInventory(inventory)\n\n深度克隆库存对象。\n\n```typescript\ncloneInventory(inventory: MarketInventory): MarketInventory\n```\n\n**输入参数：**\n- `inventory`: 要克隆的库存（`MarketInventory`）\n\n**返回值：**\n- **类型**: `MarketInventory`\n- **说明**: 完全独立的副本，修改不会影响原对象\n\n### 价格工具函数\n\n#### formatPrice(price, decimals)\n\n格式化价格为字符串显示。\n\n```typescript\nformatPrice(price: Decimal, decimals?: number): string\n```\n\n**输入参数：**\n- `price`: 要格式化的价格（`Decimal`）\n- `decimals`: 小数位数（`number`，默认 4）\n\n**返回值：**\n- **类型**: `string`\n- **示例**: `formatPrice(new Decimal(0.6789), 2)` → `\"0.68\"`\n\n#### formatQuantity(quantity, decimals)\n\n格式化数量为字符串显示。\n\n```typescript\nformatQuantity(quantity: Decimal, decimals?: number): string\n```\n\n**输入参数：**\n- `quantity`: 要格式化的数量（`Decimal`）\n- `decimals`: 小数位数（`number`，默认 2）\n\n**返回值：**\n- **类型**: `string`\n- **示例**: `formatQuantity(new Decimal(123.456), 1)` → `\"123.5\"`\n\n#### bpsToDecimal(bps)\n\n将基点（basis points）转换为小数。\n\n```typescript\nbpsToDecimal(bps: number): Decimal\n```\n\n**输入参数：**\n- `bps`: 基点值（`number`，1 基点 = 0.01%）\n\n**返回值：**\n- **类型**: `Decimal`\n- **示例**: `bpsToDecimal(500)` → `Decimal(0.05)` (5%)\n\n#### isValidPrice(price)\n\n验证价格是否在有效范围内。\n\n```typescript\nisValidPrice(price: Decimal): boolean\n```\n\n**输入参数：**\n- `price`: 要验证的价格（`Decimal`）\n\n**返回值：**\n- **类型**: `boolean`\n- **验证规则**: `0 ≤ price ≤ 1`\n- **示例**: `isValidPrice(new Decimal(0.75))` → `true`\n\n#### clampPrice(price, min?, max?)\n\n将价格限制在指定范围内。\n\n```typescript\nclampPrice(price: Decimal, min?: Decimal, max?: Decimal): Decimal\n```\n\n**输入参数：**\n- `price`: 要限制的价格（`Decimal`）\n- `min`: 最小值（`Decimal`，默认 0）\n- `max`: 最大值（`Decimal`，默认 1）\n\n**返回值：**\n- **类型**: `Decimal`\n- **说明**: 超出范围时返回边界值\n\n#### calculateSpread(bidPrice, askPrice)\n\n计算买卖价差。\n\n```typescript\ncalculateSpread(bidPrice: Decimal, askPrice: Decimal): Decimal\n```\n\n**输入参数：**\n- `bidPrice`: 买价（`Decimal`）\n- `askPrice`: 卖价（`Decimal`）\n\n**返回值：**\n- **类型**: `Decimal`\n- **计算公式**: `askPrice - bidPrice`\n- **示例**: 买价 0.45，卖价 0.55，价差为 0.10\n\n#### generatePriceGrid(centerPrice, levels, spreadBps)\n\n生成价格网格，用于多层订单。\n\n```typescript\ngeneratePriceGrid(centerPrice: Decimal, levels: number, spreadBps: number): Decimal[]\n```\n\n**输入参数：**\n- `centerPrice`: 中心价格（`Decimal`）\n- `levels`: 网格层数（`number`）\n- `spreadBps`: 每层价差基点（`number`）\n\n**返回值：**\n- **类型**: `Decimal[]`\n- **说明**: 围绕中心价格的对称价格数组\n- **示例**: 中心价 0.5，3层，100基点 → `[0.48, 0.49, 0.50, 0.51, 0.52]`\n\n## 🧪 详细使用示例\n\n### 基础价格计算示例\n\n```typescript\nimport { LmsrCalculator, createInventoryFromNumbers, formatPrice } from '@voteforx/lmsr-calculator';\n\nconst calculator = new LmsrCalculator(100);\n\n// 示例1: 平衡市场 (库存相等)\nconst balancedInventory = createInventoryFromNumbers(50, 50);\nconst balancedPrices = calculator.calculateFairPrices(balancedInventory);\nconsole.log(`平衡市场 - YES: ${formatPrice(balancedPrices.priceYes)}, NO: ${formatPrice(balancedPrices.priceNo)}`);\n// 输出: \"平衡市场 - YES: 0.5000, NO: 0.5000\"\n\n// 示例2: 偏向YES的市场\nconst yesHeavyInventory = createInventoryFromNumbers(100, 20);\nconst yesHeavyPrices = calculator.calculateFairPrices(yesHeavyInventory);\nconsole.log(`YES偏重 - YES: ${formatPrice(yesHeavyPrices.priceYes)}, NO: ${formatPrice(yesHeavyPrices.priceNo)}`);\n// 输出: \"YES偏重 - YES: 0.8176, NO: 0.1824\"\n\n// 示例3: 空市场 (初始状态)\nconst emptyInventory = createInventoryFromNumbers(0, 0);\nconst emptyPrices = calculator.calculateFairPrices(emptyInventory);\nconsole.log(`空市场 - YES: ${formatPrice(emptyPrices.priceYes)}, NO: ${formatPrice(emptyPrices.priceNo)}`);\n// 输出: \"空市场 - YES: 0.5000, NO: 0.5000\"\n```\n\n### 成本计算示例\n\n```typescript\n// 不同数量的购买成本\nconst inventory = createInventoryFromNumbers(50, 30);\n\n// 小额购买\nconst smallCost = calculator.calculatePurchaseCost(inventory, 'YES', 10);\nconsole.log(`购买 10 个 YES: ${formatPrice(smallCost)} 单位`);\n\n// 大额购买\nconst largeCost = calculator.calculatePurchaseCost(inventory, 'YES', 100);\nconsole.log(`购买 100 个 YES: ${formatPrice(largeCost)} 单位`);\n\n// 边际成本递增示例\nfor (let qty = 10; qty <= 50; qty += 10) {\n  const cost = calculator.calculatePurchaseCost(inventory, 'YES', qty);\n  const avgPrice = cost.div(qty);\n  console.log(`购买 ${qty} 个，总成本: ${formatPrice(cost)}，平均价格: ${formatPrice(avgPrice)}`);\n}\n```\n\n### 订单簿生成示例\n\n```typescript\nimport { OrderGenerationConfig } from '@voteforx/lmsr-calculator';\n\nconst inventory = createInventoryFromNumbers(75, 25);\nconst config: OrderGenerationConfig = {\n  liquidityParameterB: new Decimal(100),\n  orderDepthLevels: 5,\n  orderSpreadPerLevelBps: 50,  // 每层 0.5% 价差\n  orderAmountPerLevel: new Decimal(100), // 每层平均 100 单位\n  maxInventoryExposure: new Decimal(1000)\n};\n\nconst orderBook = calculator.generateOrderBook(inventory, config);\n\nconsole.log('买单 (Bids) - 漏斗型分布:');\norderBook.bids.forEach((bid, index) => {\n  console.log(`  Level ${index + 1}: ${formatPrice(bid.price)} @ ${bid.quantity.toFixed(0)} ${bid.outcome}`);\n});\n// 输出示例 (价格精确到 1 分):\n// Level 1: 0.74 @ 50 YES   (最接近公允价格，数量最少)\n// Level 2: 0.73 @ 75 YES   \n// Level 3: 0.72 @ 100 YES  (平均数量)\n// Level 4: 0.71 @ 125 YES  \n// Level 5: 0.70 @ 150 YES  (最远离公允价格，数量最多)\n\nconsole.log('卖单 (Asks) - 漏斗型分布:');\norderBook.asks.forEach((ask, index) => {\n  console.log(`  Level ${index + 1}: ${formatPrice(ask.price)} @ ${ask.quantity.toFixed(0)} ${ask.outcome}`);\n});\n\n// 验证漏斗型分布特性\nconst nearQuantity = orderBook.bids[0].quantity;  // 最近层\nconst farQuantity = orderBook.bids[4].quantity;   // 最远层\nconsole.log(`数量比例: 最远层/最近层 = ${farQuantity.div(nearQuantity).toFixed(1)}`); // 3.0\n```\n\n### 风险管理示例\n\n```typescript\n// 风险检查示例\nconst riskInventory = createInventoryFromNumbers(150, 50);\nconst maxExposure = new Decimal(200);\n\nconst riskResult = calculator.checkInventoryRisk(riskInventory, maxExposure);\nconsole.log(`当前敞口: ${riskResult.currentExposure.toFixed(0)}`);\nconsole.log(`是否安全: ${riskResult.isWithinLimit ? '是' : '否'}`);\n\nif (!riskResult.isWithinLimit) {\n  console.log('⚠️ 风险敞口超限，需要调整策略');\n}\n```\n\n## 🚨 边界情况和注意事项\n\n### 输入验证\n\n```typescript\n// ❌ 错误的输入\ntry {\n  const invalidInventory = createInventoryFromNumbers(-10, 20); // 负数库存\n  // 这会抛出错误或产生意外结果\n} catch (error) {\n  console.error('库存不能为负数');\n}\n\n// ❌ 无效的购买数量\ntry {\n  const cost = calculator.calculatePurchaseCost(inventory, 'YES', 0); // 零数量\n  // 返回 0，但在实际应用中可能不合理\n} catch (error) {\n  console.error('购买数量必须大于 0');\n}\n\n// ✅ 正确的输入验证\nfunction safePurchaseCost(inventory: MarketInventory, outcome: 'YES' | 'NO', quantity: Decimal) {\n  if (quantity.lte(0)) {\n    throw new Error('购买数量必须大于 0');\n  }\n  if (inventory.yesQuantity.lt(0) || inventory.noQuantity.lt(0)) {\n    throw new Error('库存不能为负数');\n  }\n  return calculator.calculatePurchaseCost(inventory, outcome, quantity);\n}\n```\n\n### 数值精度考虑\n\n```typescript\n// 高精度计算示例\nimport { Decimal } from 'decimal.js';\n\n// 使用字符串避免浮点精度问题\nconst preciseInventory = createInventoryFromStrings('100.123456789', '50.987654321');\nconst preciseCost = calculator.calculatePurchaseCost(preciseInventory, 'YES', new Decimal('25.5'));\n\nconsole.log(`高精度成本: ${preciseCost.toFixed(10)}`);\n```\n\n### 极端情况处理\n\n```typescript\n// 极端不平衡的市场\nconst extremeInventory = createInventoryFromNumbers(1000, 1);\nconst extremePrices = calculator.calculateFairPrices(extremeInventory);\n\nconsole.log(`极端市场 - YES: ${formatPrice(extremePrices.priceYes, 6)}`);\n// 输出接近 1.0 的价格\n\n// 大数量购买的影响\nconst hugePurchase = calculator.calculatePurchaseCost(\n  createInventoryFromNumbers(10, 10), \n  'YES', \n  new Decimal(1000)\n);\nconsole.log(`大额购买成本: ${hugePurchase.toFixed(2)}`);\n```\n\n### 性能优化建议\n\n```typescript\n// ✅ 推荐：重用计算器实例\nconst calculator = new LmsrCalculator(100);\nconst inventories = [/* 多个库存状态 */];\n\n// 批量计算价格\nconst allPrices = inventories.map(inv => calculator.calculateFairPrices(inv));\n\n// ❌ 不推荐：重复创建实例\ninventories.forEach(inv => {\n  const calc = new LmsrCalculator(100); // 浪费资源\n  const prices = calc.calculateFairPrices(inv);\n});\n```\n\n## ⚙️ 配置选项\n\n### OrderGenerationConfig\n\n```typescript\ninterface OrderGenerationConfig {\n  liquidityParameterB: Decimal;      // 流动性参数\n  orderDepthLevels: number;          // 订单深度层级\n  orderSpreadPerLevelBps: number;    // 每层价差 (基点)\n  orderAmountPerLevel: Decimal;      // 每层订单数量\n  maxInventoryExposure: Decimal;     // 最大库存风险敞口\n}\n```\n\n## 🎯 使用场景\n\n1. **预测市场做市商**: 自动提供流动性\n2. **价格发现**: 基于供需计算公允价格\n3. **风险管理**: 控制库存风险敞口\n4. **套利检测**: 识别价格不一致\n5. **市场分析**: 计算隐含概率和价格弹性\n\n## 🔍 性能考虑\n\n- 使用 `decimal.js` 确保高精度计算\n- 所有计算都是确定性的\n- 支持大数运算\n- 内存使用优化\n\n## 📄 许可证\n\nMIT License\n\n## 🤝 贡献\n\n欢迎提交 Issue 和 Pull Request！\n\n## 📚 参考资料\n\n- [Logarithmic Market Scoring Rules](https://www.cs.cmu.edu/~sandholm/cs15-892F13/algorithmic-game-theory.pdf)\n- [Automated Market Makers](https://web.stanford.edu/~boyd/papers/pdf/market_making.pdf)\n- [Prediction Markets: Theory and Applications](https://mason.gmu.edu/~rhanson/mktscore.pdf)\n","readmeFilename":"README.md"}