Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | 2x 26x 10x 10x 10x 5x 5x 5x 5x 5x 5x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 4x 4x 4x 4x 4x 4x 4x 4x 1x 3x 3x 3x 3x 3x 3x 2x 1x 4x 4x 4x 1x 3x 1x 2x 2x 1x 1x 1x | import { autoInjectable, inject, singleton } from "tsyringe";
import type { Logger } from "pino";
import { tokens } from "../../registry/tokens.js";
import { LedgerEvent } from "../../tr8-script/domain/ledger-event.js";
import { AssetState } from "../../tr8-script/domain/eval.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { Amount } from "../../tr8-script/domain/value.js";
import { greaterThanOrEqual } from "../../tr8-script/domain/utils/math.js";
import { decimalStringToAmount } from "../../tr8-script/domain/utils/math-low-level.js";
interface OptionsTradeMetadata {
trade_type: string;
order_side: string;
position_intent?: string;
share_quantity: string;
ticker: string;
option_type?: "call" | "put";
strike_price?: string;
underlying_ticker?: string;
filled_share_quantity?: string;
event_type?: string;
prefix?: string;
}
interface MarginCheckResult {
sufficient: boolean; // Always true when ok: true
required: Amount;
available: Amount;
}
interface ReservationReleaseInfo {
type: "stock" | "cash";
ticker?: string; // For stock releases
reserveAccount: string; // Source account (S-RES-{TICKER} or C-RES)
targetAccount: string; // Destination account (S-OWN-{TICKER} or C-FC)
amount: number; // Amount to release
scale: number; // Scale for amount (0 for shares, 2 for cash)
}
interface PositionValidationResult {
isValid: boolean;
availableQuantity: number; // How many contracts can be closed
requiredQuantity: number; // How many contracts trying to close
}
@singleton()
@autoInjectable()
export class MarginService {
constructor(@inject(tokens.Logger) private readonly logger: Logger) {}
/**
* Check if margin requirements are met for options shorting
*/
async checkMargin(
event: LedgerEvent,
iabAsset: AssetState,
bookId: string,
): Promise<Result<MarginCheckResult, Error>> {
try {
const metadata = JSON.parse(event.metadata) as OptionsTradeMetadata;
// Skip margin check for NOTIF/PARTIAL_NOTIF - REQ already performed margin check and reserved funds
// NOTIF/PARTIAL_NOTIF are just confirmations of execution, no need to re-check margin
if (event.type === "NOTIF" || event.type === "PARTIAL_NOTIF") {
this.logger.info(
{
eventType: event.type,
ticker: metadata.ticker,
optionType: metadata.option_type,
},
"Skipping margin check for NOTIF/PARTIAL_NOTIF - REQ already reserved funds",
);
return {
ok: true,
value: {
sufficient: true,
required: { amount: 0n, scale: 0n },
available: { amount: 0n, scale: 0n },
},
};
}
// Parse trade details for REQ - use share_quantity
const quantity = Math.abs(Number(metadata.share_quantity));
const contracts = quantity; // Assuming share_quantity represents number of contracts
this.logger.info(
{
ticker: metadata.ticker,
optionType: metadata.option_type,
contracts,
strikePrice: metadata.strike_price,
eventType: event.type,
},
"Checking margin for options shorting (REQ)",
);
if (metadata.option_type === "call") {
return this.checkCoveredCallMargin(
metadata,
contracts,
iabAsset,
event.type,
bookId,
);
} else if (metadata.option_type === "put") {
return this.checkCashSecuredPutMargin(
metadata,
contracts,
iabAsset,
event.type,
bookId,
);
} else E{
return {
ok: false,
error: new Error(`Unknown option type: ${metadata.option_type}`),
};
}
} catch (error) {
this.logger.error({ err: error }, "Error in margin check");
return {
ok: false,
error:
error instanceof Error
? error
: new Error("Unknown margin check error"),
};
}
}
/**
* Check if user has enough shares for covered call
*/
private checkCoveredCallMargin(
metadata: OptionsTradeMetadata,
contracts: number,
iabAsset: AssetState,
eventType: string,
bookId: string,
): Result<MarginCheckResult, Error> {
// Extract underlying ticker from option symbol: AAPL240315C150 -> AAPL
const underlyingTicker =
metadata.underlying_ticker ||
this.extractUnderlyingTicker(metadata.ticker);
const requiredShares = contracts * 100; // Each contract = 100 shares
// For covered calls:
// - REQ: check {prefix}-S-OWN-{UNDERLYING} (has shares to reserve)
// - NOTIF/PARTIAL_NOTIF: check {prefix}-S-RES-OP-{TICKER} (has reserved shares from REQ)
const prefix = metadata.prefix || bookId; // Use metadata.prefix if available, fallback to bookId
let stockAccount = `${prefix}-S-OWN-${underlyingTicker}`;
Iif (eventType === "NOTIF" || eventType === "PARTIAL_NOTIF") {
stockAccount = `${prefix}-S-RES-OP-${metadata.ticker}`;
}
const availableShares = iabAsset[stockAccount];
const required = decimalStringToAmount(requiredShares.toString());
const available = availableShares || decimalStringToAmount("0");
const sufficient = greaterThanOrEqual(available, required);
this.logger.info(
{
underlyingTicker,
requiredShares,
stockAccount,
availableShares: available.amount.toString(),
sufficient,
eventType,
},
"Covered call margin check",
);
if (!sufficient) {
return {
ok: false,
error: new Error(
`Insufficient shares for covered call. Required: ${requiredShares}, Available: ${available.amount}`,
),
};
}
return {
ok: true,
value: {
sufficient: true,
required,
available,
},
};
}
/**
* Check if user has enough cash for cash-secured put
*/
private checkCashSecuredPutMargin(
metadata: OptionsTradeMetadata,
contracts: number,
iabAsset: AssetState,
eventType: string,
bookId: string,
): Result<MarginCheckResult, Error> {
if (!metadata.strike_price) {
return {
ok: false,
error: new Error("Strike price required for put options"),
};
}
const strikePrice = Number(metadata.strike_price);
const requiredCash = contracts * 100 * strikePrice; // contracts * shares_per_contract * strike_price
// For put options:
// - REQ: check {prefix}-C-FC (has free cash to reserve)
// - NOTIF/PARTIAL_NOTIF: check {prefix}-C-RES-OP-{TICKER} (has reserved cash from REQ)
const prefix = metadata.prefix || bookId; // Use metadata.prefix if available, fallback to bookId
let cashAccount = `${prefix}-C-FC`;
Iif (eventType === "NOTIF" || eventType === "PARTIAL_NOTIF") {
cashAccount = `${prefix}-C-RES-OP-${metadata.ticker}`;
}
const availableCash = iabAsset[cashAccount];
const required = decimalStringToAmount(requiredCash.toString());
const available = availableCash || decimalStringToAmount("0");
const sufficient = greaterThanOrEqual(available, required);
this.logger.info(
{
contracts,
strikePrice,
requiredCash,
cashAccount,
availableCash: available.amount.toString(),
sufficient,
positionIntent: metadata.position_intent,
},
"Cash secured put margin check",
);
if (!sufficient) {
return {
ok: false,
error: new Error(
`Insufficient cash for cash-secured put. Required: $${requiredCash}, Available: $${
Number(available.amount) / Math.pow(10, Number(available.scale))
}`,
),
};
}
return {
ok: true,
value: {
sufficient: true,
required,
available,
},
};
}
/**
* Extract underlying ticker from option symbol
* Example: AAPL240315C150 -> AAPL
*/
private extractUnderlyingTicker(optionSymbol: string): string {
// Option symbol format: {TICKER}{YYMMDD}{C/P}{STRIKE}
// Find where the date starts (first digit after letters)
const match = optionSymbol.match(/^([A-Z]+)\d/);
return match?.[1] || optionSymbol;
}
/**
* Check if this is a buy-to-close trade (closing short position)
*/
isBuyToCloseTrade(event: LedgerEvent): boolean {
try {
const metadata = JSON.parse(event.metadata) as OptionsTradeMetadata;
return (
metadata.trade_type === "options" &&
metadata.order_side === "buy" &&
metadata.position_intent === "buy_to_close" &&
Number(metadata.share_quantity) > 0
);
} catch (error) {
this.logger.error({ err: error }, "Error checking if buy-to-close trade");
return false;
}
}
/**
* Validate reservation release for buy-to-close trades
*/
async validateReservationRelease(
event: LedgerEvent,
iabAsset: AssetState,
): Promise<Result<{ releaseInfo: ReservationReleaseInfo }, Error>> {
try {
const metadata = JSON.parse(event.metadata) as OptionsTradeMetadata;
// Use filled quantity for NOTIF (partial fills), share_quantity for REQ
const quantityToUse =
(event.type === "NOTIF" || event.type === "PARTIAL_NOTIF") &&
metadata.filled_share_quantity
? metadata.filled_share_quantity
: metadata.share_quantity;
const contracts = Math.abs(Number(quantityToUse));
if (metadata.option_type === "call") {
// Check if user has enough reserved shares to release
const underlyingTicker =
metadata.underlying_ticker ||
this.extractUnderlyingTicker(metadata.ticker);
const requiredReserved = contracts * 100;
const reserveAccount = `S-RES-OP-${metadata.ticker}`;
const availableReserved = iabAsset[reserveAccount];
const reserved = availableReserved || decimalStringToAmount("0");
const required = decimalStringToAmount(requiredReserved.toString());
this.logger.info(
{
underlyingTicker,
requiredReserved,
availableReserved: reserved.amount.toString(),
reserveAccount,
},
"Validating share reservation release",
);
if (!greaterThanOrEqual(reserved, required)) {
return {
ok: false,
error: new Error(
`Insufficient reserved shares for buy-to-close. Required: ${requiredReserved}, Available: ${reserved.amount}`,
),
};
}
return {
ok: true,
value: {
releaseInfo: {
type: "stock",
ticker: underlyingTicker,
reserveAccount: `S-RES-OP-${metadata.ticker}`,
targetAccount: `S-OWN-${underlyingTicker}`,
amount: requiredReserved,
scale: 0,
},
},
};
} else if (metadata.option_type === "put") {
// Check if user has enough reserved cash to release
const strikePrice = Number(metadata.strike_price);
const requiredReserved = contracts * 100 * strikePrice;
const reserveAccount = `C-RES-OP-${metadata.ticker}`;
const availableReserved = iabAsset[reserveAccount];
const reserved = availableReserved || decimalStringToAmount("0");
const required = decimalStringToAmount(requiredReserved.toString());
this.logger.info(
{
contracts,
strikePrice,
requiredReserved,
availableReserved: reserved.amount.toString(),
reserveAccount,
},
"Validating cash reservation release",
);
if (!greaterThanOrEqual(reserved, required)) {
return {
ok: false,
error: new Error(
`Insufficient reserved cash for buy-to-close. Required: $${requiredReserved}, Available: $${
Number(reserved.amount) / 100
}`,
),
};
}
return {
ok: true,
value: {
releaseInfo: {
type: "cash",
reserveAccount: `C-RES-OP-${metadata.ticker}`,
targetAccount: "C-FC",
amount: requiredReserved,
scale: 2,
},
},
};
} else E{
return {
ok: false,
error: new Error(
`Unknown option type for reservation release: ${metadata.option_type}`,
),
};
}
} catch (error) {
this.logger.error(
{ err: error },
"Error in reservation release validation",
);
return {
ok: false,
error:
error instanceof Error
? error
: new Error("Unknown reservation release error"),
};
}
}
/**
* Validate that user has sufficient position to close for buy-to-close trades
*/
async validatePosition(
event: LedgerEvent,
iabAsset: AssetState,
): Promise<Result<PositionValidationResult, Error>> {
try {
const metadata = JSON.parse(event.metadata) as OptionsTradeMetadata;
// Use filled quantity for NOTIF (partial fills), share_quantity for REQ
const quantityToUse =
(event.type === "NOTIF" || event.type === "PARTIAL_NOTIF") &&
metadata.filled_share_quantity
? metadata.filled_share_quantity
: metadata.share_quantity;
const contracts = Math.abs(Number(quantityToUse));
// Extract position details
const underlyingTicker =
metadata.underlying_ticker ||
this.extractUnderlyingTicker(metadata.ticker);
const optionType = metadata.option_type;
const strikePrice = metadata.strike_price;
if (!optionType || !strikePrice) {
return {
ok: false,
error: new Error(
"Missing option_type or strike_price for position validation",
),
};
}
// Look for existing short position in options account OP-OWN-{TICKER}
const shortAccount = `OP-OWN-${metadata.ticker}`;
const currentPosition = iabAsset[shortAccount];
// Convert current position to absolute quantity (should be negative for short positions)
const availableQuantity = currentPosition
? Math.abs(Number(currentPosition.amount))
: 0;
this.logger.info(
{
ticker: metadata.ticker,
underlyingTicker,
optionType,
strikePrice,
requiredQuantity: contracts,
availableQuantity,
shortAccount,
currentPosition: currentPosition?.amount.toString(),
},
"Position validation for buy-to-close",
);
const isValid = availableQuantity >= contracts;
if (!isValid) {
return {
ok: false,
error: new Error(
`Insufficient position to close. Available: ${availableQuantity} contracts, Required: ${contracts} contracts for ${metadata.ticker}`,
),
};
}
return {
ok: true,
value: {
isValid: true,
availableQuantity,
requiredQuantity: contracts,
},
};
} catch (error) {
this.logger.error({ err: error }, "Error in position validation");
return {
ok: false,
error:
error instanceof Error
? error
: new Error("Unknown position validation error"),
};
}
}
/**
* Check if the trade is options shorting (negative quantity with sell-to-open intent)
*/
isOptionsShortingTrade(event: LedgerEvent): boolean {
try {
const metadata = JSON.parse(event.metadata) as OptionsTradeMetadata;
// Check if it's options trade
if (metadata.trade_type !== "options") {
return false;
}
// Check if it's a sell order
if (metadata.order_side !== "sell") {
return false;
}
// Check if quantity is negative (shorting)
const quantity = Number(metadata.share_quantity);
if (quantity >= 0) {
return false;
}
// Check if position intent is sell-to-open
Iif (metadata.position_intent !== "sell_to_open") {
return false;
}
return true;
} catch (error) {
this.logger.error(
{ err: error },
"Error checking if options shorting trade",
);
return false;
}
}
}
|