Home /Modules/advantage/SLShortBook.sleela

SLShortBook.sleela

lib/advantage/trading-actions-on-verb/SLShortBook.sleela · 340 line(s) · sleela

<< lib/advantage/trading-actions-on-verb/SLShortBook.sleela
   SLeeLa Standard Library Definition.
   Definition: A short-only position book of FIFO lots with verbs shortSell, cover, hold and coverAll, integer cents, a per-share-per-day borrow cost, and invariants checked after every action. >>
#sleela 3.0
material;
artifact;
pure;
gasoline;
< The mirror of SLLongBook. A short position sells shares first and buys them >
< back later. Profit on a covered share is sale price minus cover price. The >
< book is short only: a cover larger than the shares short is refused (code 3), >
< never turned into a long. Lots are kept oldest first and covered first in >
< first out. Money is integer cents, quantity whole shares, time whole days. >
< Borrow cost: borrowRate cents per share per day, charged on every covered >
< share for the days it was short. It is fixed while any share is short. >
< Asymmetry: a long loss is capped by its cost, but a short loss is not capped >
< by its proceeds, because a price can rise without a limit. Use markToMarket. >
< Status codes: 0 ok, 1 bad quantity, 2 bad price, 3 cover exceeds the shares >
< short, 4 book full, 5 day goes backwards, 6 bad fee, 7 nothing short, >
< 8 a size bound would be passed, 9 the borrow rate cannot change while short. >
< SLeeLa int is 64-bit and + - * / % are exact, but comparisons are exact only >
< up to 2^53 - 1 (9,007,199,254,740,991). The bounds below keep every compared >
< value at or below 5e15. Products that are only added (not compared close to >
< the limit) may be larger, so an accrual is checked against its own bound. >
< Time queries need today >= the book day; earlier days answer -1. >
< Illustrative only: no order is placed and nothing here is trading advice. >
class SLShortBook {
  < ---- Descriptive metadata (version 1.11 nested-friendly accessors) ---- >
  << Eleven catalogued attributes with getter/setter pairs. A worker-class
     lesson carries the baseline identity record. >>
  String metaVersion = "1.0.0";
  int metaId = 39203;
  String metaAuthor = "Kiro Agent";
  String metaDate = "2026-11-11";
  String metaCopyright = "SLeeLa project";
  String metaTrademark = "none";
  String metaCorporation = "none";
  < metaOrigin: National | <nation> | International | Galactic >
  String metaOrigin = "International";
  String metaBirthDate = "2026-11-11";
  < metaScienceRating: maturity/robustness on a 1..10 scale >
  int metaScienceRating = 5;
  < metaNationalSchedule: a real, citable instrument or "none" >
  String metaNationalSchedule = "none";

  String getMetaVersion() { return metaVersion; }
  void setMetaVersion(String v) { metaVersion = v; }
  int getMetaId() { return metaId; }
  void setMetaId(int v) { metaId = v; }
  String getAuthor() { return metaAuthor; }
  void setAuthor(String v) { metaAuthor = v; }
  String getDate() { return metaDate; }
  void setDate(String v) { metaDate = v; }
  String getCopyright() { return metaCopyright; }
  void setCopyright(String v) { metaCopyright = v; }
  String getTrademark() { return metaTrademark; }
  void setTrademark(String v) { metaTrademark = v; }
  String getCorporation() { return metaCorporation; }
  void setCorporation(String v) { metaCorporation = v; }
  String getOrigin() { return metaOrigin; }
  void setOrigin(String v) { metaOrigin = v; }
  String getBirthDate() { return metaBirthDate; }
  void setBirthDate(String v) { metaBirthDate = v; }
  int getScienceRating() { return metaScienceRating; }
  void setScienceRating(int v) { metaScienceRating = v; }
  String getNationalSchedule() { return metaNationalSchedule; }
  void setNationalSchedule(String v) { metaNationalSchedule = v; }

  int maxQty = 100000000;
  int maxPrice = 10000000;
  int maxFee = 100000000;
  int maxTotal = 4000000000000000;
  int maxDay = 10000000;
  int maxRate = 1000;
  int[] lotQty = new int[16];
  int[] lotPrice = new int[16];
  int[] lotDay = new int[16];
  int count = 0;
  int lastDay = 0;
  int openedQty = 0;
  int coveredQty = 0;
  int openedProceeds = 0;
  int proceedsCovered = 0;
  int coverCost = 0;
  int feesPaid = 0;
  int borrowRate = 0;
  int borrowPaid = 0;
  < Sale proceeds and profit of the most recent cover, before fees and borrow. >
  int lastCoverProceeds = 0;
  int lastCoverPnl = 0;

  int maxLots() { return 16; }

  String reason(int code) {
    if (code == 0) { return "ok"; }
    if (code == 1) { return "refused: quantity must be a whole number above zero"; }
    if (code == 2) { return "refused: price must be above zero"; }
    if (code == 3) { return "refused: cover exceeds the shares short (short only, no long)"; }
    if (code == 4) { return "refused: book is full"; }
    if (code == 5) { return "refused: day goes backwards"; }
    if (code == 6) { return "refused: fee must not be negative"; }
    if (code == 7) { return "refused: nothing is short"; }
    if (code == 8) { return "refused: a size bound would be passed"; }
    return "refused: the borrow rate cannot change while shares are short";
  }

  int totalShort() {
    int sum = 0;
    int i = 0;
    while (i < count) { sum = sum + lotQty[i]; i = i + 1; }
    return sum;
  }

  < Sale proceeds of the shares still short, in cents. >
  int proceedsHeld() {
    int sum = 0;
    int i = 0;
    while (i < count) { sum = sum + lotQty[i] * lotPrice[i]; i = i + 1; }
    return sum;
  }

  < Average sale price per share still short, rounded down, and the remainder. >
  int avgSaleFloor() {
    int q = totalShort();
    if (q == 0) { return 0; }
    return proceedsHeld() / q;
  }

  int avgSaleRemainder() {
    int q = totalShort();
    if (q == 0) { return 0; }
    return proceedsHeld() % q;
  }

  int lotCount() { return count; }
  int lotQtyAt(int i) { return lotQty[i]; }
  int lotPriceAt(int i) { return lotPrice[i]; }
  int lotDayAt(int i) { return lotDay[i]; }
  int currentDay() { return lastDay; }

  < The borrow rate can only change while nothing is short, so no share is >
  < ever charged at two rates. >
  int setBorrowRate(int rate) {
    if (rate < 0 || rate > maxRate) { return 8; }
    if (count > 0) { return 9; }
    borrowRate = rate;
    return 0;
  }

  < ---- Verbs ---- >

  int shortSell(int day, int qty, int price, int fee) {
    if (qty <= 0) { return 1; }
    if (price <= 0) { return 2; }
    if (fee < 0) { return 6; }
    if (day < lastDay) { return 5; }
    if (qty > maxQty || price > maxPrice || fee > maxFee || day > maxDay) { return 8; }
    if (count >= maxLots()) { return 4; }
    if (openedProceeds + qty * price > maxTotal || feesPaid + fee > maxTotal) { return 8; }
    if (openedQty + qty > maxTotal) { return 8; }
    lotQty[count] = qty;
    lotPrice[count] = price;
    lotDay[count] = day;
    count = count + 1;
    lastDay = day;
    openedQty = openedQty + qty;
    openedProceeds = openedProceeds + qty * price;
    feesPaid = feesPaid + fee;
    return 0;
  }

  < Cover oldest lots first. Refuses, changing nothing, when the cover is not >
  < valid, exceeds the shares short, or would pass a size bound. >
  int cover(int day, int qty, int price, int fee) {
    if (qty <= 0) { return 1; }
    if (price <= 0) { return 2; }
    if (fee < 0) { return 6; }
    if (day < lastDay) { return 5; }
    if (qty > totalShort()) { return 3; }
    if (price > maxPrice || fee > maxFee || day > maxDay) { return 8; }
    if (coverCost + qty * price > maxTotal || feesPaid + fee > maxTotal) { return 8; }
    int need = qty;
    int sale = 0;
    int shareDays = 0;
    int i = 0;
    while (need > 0) {
      int take = lotQty[i];
      if (take > need) { take = need; }
      sale = sale + take * lotPrice[i];
      shareDays = shareDays + take * (day - lotDay[i]);
      need = need - take;
      i = i + 1;
    }
    int borrow = shareDays * borrowRate;
    if (borrowPaid + borrow > maxTotal) { return 8; }
    need = qty;
    i = 0;
    while (need > 0) {
      int take2 = lotQty[i];
      if (take2 > need) { take2 = need; }
      lotQty[i] = lotQty[i] - take2;
      need = need - take2;
      i = i + 1;
    }
    compact();
    int cost = qty * price;
    coveredQty = coveredQty + qty;
    proceedsCovered = proceedsCovered + sale;
    coverCost = coverCost + cost;
    feesPaid = feesPaid + fee;
    borrowPaid = borrowPaid + borrow;
    lastCoverProceeds = sale;
    lastCoverPnl = sale - cost;
    lastDay = day;
    return 0;
  }

  int hold(int day) {
    if (day < lastDay) { return 5; }
    if (day > maxDay) { return 8; }
    lastDay = day;
    return 0;
  }

  int coverAll(int day, int price, int fee) {
    int q = totalShort();
    if (q == 0) { return 7; }
    return cover(day, q, price, fee);
  }

  void compact() {
    int w = 0;
    int r = 0;
    while (r < count) {
      if (lotQty[r] > 0) {
        lotQty[w] = lotQty[r];
        lotPrice[w] = lotPrice[r];
        lotDay[w] = lotDay[r];
        w = w + 1;
      }
      r = r + 1;
    }
    count = w;
  }

  < ---- Money ---- >

  < Profit on shares already covered, before fees and borrow cost. >
  int realizedGross() { return proceedsCovered - coverCost; }
  < Cash view: realizedGross - every fee paid - every borrow cost paid. >
  int realizedNet() { return proceedsCovered - coverCost - feesPaid - borrowPaid; }
  int fees() { return feesPaid; }
  int borrowCostPaid() { return borrowPaid; }

  < Gain (positive) or loss (negative) on the shares still short if they were >
  < covered at price now: proceeds still held - shares short * price. Returns >
  < -(maxTotal + 1) when price is not between 1 and maxPrice. >
  int markToMarket(int price) {
    if (price <= 0 || price > maxPrice) { return 0 - 1 - maxTotal; }
    return proceedsHeld() - totalShort() * price;
  }

  < ---- Time on short ---- >

  boolean validToday(int today) { return today >= lastDay; }

  int ageOf(int i, int today) {
    if (!validToday(today)) { return 0 - 1; }
    return today - lotDay[i];
  }

  int oldestAge(int today) {
    if (count == 0 || !validToday(today)) { return 0 - 1; }
    return today - lotDay[0];
  }

  int weightedAgeFloor(int today) {
    if (!validToday(today)) { return 0 - 1; }
    int q = totalShort();
    if (q == 0) { return 0; }
    int sum = 0;
    int i = 0;
    while (i < count) { sum = sum + lotQty[i] * (today - lotDay[i]); i = i + 1; }
    return sum / q;
  }

  < Borrow cost accrued so far on the shares still short, not yet paid. >
  int borrowAccrued(int today) {
    if (!validToday(today)) { return 0 - 1; }
    int sum = 0;
    int i = 0;
    while (i < count) { sum = sum + lotQty[i] * (today - lotDay[i]); i = i + 1; }
    return sum * borrowRate;
  }

  < Shares short for more than maxAge days. >
  int qtyOlderThan(int today, int maxAge) {
    if (!validToday(today)) { return 0 - 1; }
    int sum = 0;
    int i = 0;
    while (i < count) {
      if (today - lotDay[i] > maxAge) { sum = sum + lotQty[i]; }
      i = i + 1;
    }
    return sum;
  }

  < A lot is long term when it is held for MORE than threshold days. Mirrors >
  < SLLongBook.isLongTerm exactly: added so a short position has the same >
  < term vocabulary as a long one, which it previously lacked. >
  boolean isLongTerm(int i, int today, int threshold) {
    if (!validToday(today)) { return false; }
    return today - lotDay[i] > threshold;
  }

  int qtyLongTerm(int today, int threshold) {
    return qtyOlderThan(today, threshold);
  }

  < ---- Invariants ---- >
  < 1 every lot has positive quantity and price; 2 lot days never decrease and >
  < never pass the book day; 3 count is within the 16-lot capacity; 4 shares >
  < short = shares sold short - shares covered; 5 proceeds held = proceeds >
  < opened - proceeds covered. >
  boolean invariantsHold() {
    if (count < 0 || count > maxLots()) { return false; }
    int i = 0;
    int prev = 0;
    while (i < count) {
      if (lotQty[i] <= 0 || lotPrice[i] <= 0) { return false; }
      if (lotDay[i] < prev || lotDay[i] > lastDay) { return false; }
      prev = lotDay[i];
      i = i + 1;
    }
    if (totalShort() != openedQty - coveredQty) { return false; }
    if (proceedsHeld() != openedProceeds - proceedsCovered) { return false; }
    return true;
  }
}