buy.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import {setupPopover} from './popover';
  2. const warehouseNames = {
  3. 'AI1': 'ANT',
  4. 'CI1': 'BEN',
  5. 'IC1': 'HRT',
  6. 'NC1': 'MOR',
  7. } as const;
  8. const username = document.querySelector('#username') as HTMLInputElement;
  9. const apiKey = document.querySelector('#api-key') as HTMLInputElement;
  10. {
  11. const storedUsername = localStorage.getItem('fio-username');
  12. if (storedUsername)
  13. username.value = storedUsername;
  14. const storedApiKey = localStorage.getItem('fio-api-key');
  15. if (storedApiKey)
  16. apiKey.value = storedApiKey;
  17. }
  18. const xitAct = document.querySelector('textarea#xit-act') as HTMLTextAreaElement;
  19. document.querySelector('#fetch')!.addEventListener('click', async () => {
  20. const supplyForDays = parseInt((document.querySelector('#days') as HTMLInputElement).value, 10);
  21. const cx = (document.querySelector('#cx') as HTMLInputElement).value;
  22. if (!(cx in warehouseNames))
  23. throw new Error(`invalid CX ${cx}`);
  24. const output = await calculate(username.value, apiKey.value, supplyForDays, cx as keyof typeof warehouseNames);
  25. console.log(output);
  26. localStorage.setItem('fio-username', username.value);
  27. localStorage.setItem('fio-api-key', apiKey.value);
  28. });
  29. document.querySelector('#copy-xit-act')!.addEventListener('click', () => {
  30. navigator.clipboard.writeText(xitAct.value);
  31. });
  32. setupPopover();
  33. async function calculate(username: string, apiKey: string, supplyForDays: number, cx: keyof typeof warehouseNames): Promise<void> {
  34. const [prices, planets, avail, {bids, orders}] = await Promise.all([
  35. getPrices(cx),
  36. getPlanets(username, apiKey),
  37. warehouseInventory(username, apiKey, warehouseNames[cx]),
  38. getBids(username, apiKey, cx)
  39. ]);
  40. const buy = new Map<string, number>();
  41. for (const planet of planets) {
  42. for (const [mat, amount] of planet.supplyForDays(supplyForDays))
  43. buy.set(mat, (buy.get(mat) ?? 0) + amount);
  44. for (const mat of planet.exporting) {
  45. const planetExport = planet.inventory.get(mat);
  46. if (planetExport)
  47. avail.set(mat, (avail.get(mat) ?? 0) + planetExport);
  48. }
  49. }
  50. // what's left to buy
  51. const materials: Material[] = [];
  52. for (const [mat, amount] of buy) {
  53. const remaining = Math.max(amount - (bids.get(mat) ?? 0) - (avail.get(mat) ?? 0), 0);
  54. const price = prices.get(mat);
  55. if (!price || price.Bid === null || price.Ask === null) {
  56. console.log(mat, 'has no bid/ask');
  57. continue;
  58. }
  59. const spread = price.Ask - price.Bid;
  60. materials.push({
  61. ticker: mat,
  62. amount,
  63. bids: bids.get(mat) ?? 0,
  64. have: avail.get(mat) ?? 0,
  65. spread,
  66. savings: spread * remaining,
  67. });
  68. }
  69. materials.sort((a, b) => b.savings - a.savings);
  70. const toBuy: Record<string, number> = {};
  71. const priceLimits: Record<string, number> = {};
  72. const tbody = document.querySelector('tbody')!;
  73. tbody.innerHTML = '';
  74. const format = new Intl.NumberFormat(undefined, {maximumFractionDigits: 0}).format;
  75. for (const m of materials) {
  76. const tr = document.createElement('tr');
  77. const buyAmount = Math.max(m.amount - m.bids - m.have, 0);
  78. tr.innerHTML = `
  79. <td>${m.ticker}</td>
  80. <td>${format(m.amount)}</td>
  81. <td>${format(m.bids)}</td>
  82. <td>${format(m.have)}</td>
  83. <td>${format(buyAmount)}</td>
  84. <td>${format(m.spread)}</td>
  85. <td>${format(m.savings)}</td>
  86. `;
  87. if (buyAmount > 0) {
  88. if (m.bids === 0)
  89. tr.children[2].classList.add('red');
  90. toBuy[m.ticker] = buyAmount;
  91. const bid = prices.get(m.ticker)!.Bid!;
  92. const epsilon = 10 ** (Math.floor(Math.log10(bid)) - 2);
  93. const limit = bid + 2 * epsilon;
  94. priceLimits[m.ticker] = limit;
  95. }
  96. tbody.appendChild(tr);
  97. }
  98. xitAct.value = JSON.stringify({
  99. 'actions': [
  100. {'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': cx,
  101. 'priceLimits': priceLimits, 'buyPartial': true, 'allowUnfilled': true, 'useCXInv': false},
  102. ],
  103. 'global': {'name': `buy orders for ${supplyForDays} days`},
  104. 'groups': [{'type': 'Manual', 'name': 'A1', 'materials': toBuy}],
  105. });
  106. // deposits of current bids
  107. orders.sort((a, b) => (b.Limit * b.Amount) - (a.Limit * a.Amount));
  108. for (const order of orders) {
  109. const deposit = order.Limit * order.Amount;
  110. console.log(`${order.MaterialTicker.padEnd(4)} ${deposit}\n`);
  111. }
  112. }
  113. async function getPrices(cx: string) {
  114. const rawPrices= await fetch('https://refined-prun.github.io/refined-prices/all.json').then(r => r.json());
  115. const prices = new Map<string, RawPrice>();
  116. for (const p of rawPrices)
  117. if (p.ExchangeCode === cx)
  118. prices.set(p.MaterialTicker, p);
  119. return prices;
  120. }
  121. async function getPlanets(username: string, apiKey: string) {
  122. const fioBurns: FIOBurn[] = await fetch('https://rest.fnar.net/fioweb/burn/user/' + username,
  123. {headers: {'Authorization': apiKey}}).then(r => r.json());
  124. const planets = fioBurns.map(burn => new Planet(burn));
  125. return planets;
  126. }
  127. async function warehouseInventory(username: string, apiKey: string, whName: string): Promise<Map<string, number>> {
  128. const warehouses: Warehouse[] = await fetch('https://rest.fnar.net/sites/warehouses/' + username,
  129. {headers: {'Authorization': apiKey}}).then(r => r.json());
  130. for (const warehouse of warehouses)
  131. if (warehouse.LocationNaturalId === whName) {
  132. const storage: Storage = await fetch(`https://rest.fnar.net/storage/${username}/${warehouse.StoreId}`,
  133. {headers: {'Authorization': apiKey}}).then(r => r.json());
  134. const inventory = new Map<string, number>();
  135. for (const item of storage.StorageItems)
  136. inventory.set(item.MaterialTicker, item.MaterialAmount);
  137. return inventory;
  138. }
  139. throw new Error(`couldn't find ${whName} warehouse`);
  140. }
  141. async function getBids(username: string, apiKey: string, cx: string) {
  142. const allOrders: ExchangeOrder[] = await fetch('https://rest.fnar.net/cxos/' + username,
  143. {headers: {'Authorization': apiKey}}).then(r => r.json());
  144. const orders = allOrders.filter(order =>
  145. order.OrderType === 'BUYING' && order.Status !== 'FILLED' && order.ExchangeCode === cx);
  146. const bids = new Map<string, number>();
  147. for (const order of orders)
  148. bids.set(order.MaterialTicker, (bids.get(order.MaterialTicker) ?? 0) + order.Amount);
  149. return {bids, orders};
  150. }
  151. class Planet {
  152. name: string;
  153. inventory: Map<string, number>;
  154. netConsumption: Amount[];
  155. exporting: Set<string>; // producing more than consumption
  156. constructor(fioBurn: FIOBurn) {
  157. this.name = fioBurn.PlanetName || fioBurn.PlanetNaturalId;
  158. this.inventory = new Map();
  159. for (const item of fioBurn.Inventory)
  160. this.inventory.set(item.MaterialTicker, item.MaterialAmount);
  161. const producing = new Map<string, Amount>();
  162. for (const item of fioBurn.OrderProduction)
  163. producing.set(item.MaterialTicker, item);
  164. this.netConsumption = [];
  165. for (const c of [...fioBurn.OrderConsumption, ...fioBurn.WorkforceConsumption]) {
  166. let net = c.DailyAmount;
  167. const production = producing.get(c.MaterialTicker);
  168. if (production) {
  169. net -= production.DailyAmount;
  170. if (net < 0)
  171. continue;
  172. }
  173. c.netConsumption = net;
  174. this.netConsumption.push(c);
  175. }
  176. const consuming = new Set(this.netConsumption.map(item => item.MaterialTicker));
  177. this.exporting = new Set<string>();
  178. for (const item of fioBurn.OrderProduction)
  179. if (!consuming.has(item.MaterialTicker))
  180. this.exporting.add(item.MaterialTicker);
  181. }
  182. supplyForDays(targetDays: number): Map<string, number> {
  183. const buy = new Map<string, number>();
  184. for (const consumption of this.netConsumption) {
  185. const ticker = consumption.MaterialTicker;
  186. const avail = this.inventory.get(ticker) ?? 0;
  187. const dailyConsumption = consumption.netConsumption!;
  188. const days = avail / dailyConsumption;
  189. if (days < targetDays)
  190. buy.set(ticker, Math.ceil((targetDays - days) * dailyConsumption));
  191. }
  192. return buy;
  193. }
  194. }
  195. interface Material {
  196. ticker: string;
  197. amount: number;
  198. bids: number;
  199. have: number;
  200. spread: number;
  201. savings: number;
  202. }
  203. interface RawPrice {
  204. MaterialTicker: string;
  205. ExchangeCode: string;
  206. Bid: number | null;
  207. Ask: number | null;
  208. FullTicker: string;
  209. }
  210. interface ExchangeOrder {
  211. MaterialTicker: string;
  212. ExchangeCode: string;
  213. OrderType: 'SELLING' | 'BUYING';
  214. Status: 'FILLED' | 'PARTIALLY_FILLED';
  215. Amount: number;
  216. Limit: number;
  217. }
  218. interface StorageItem {
  219. MaterialTicker: string;
  220. MaterialAmount: number;
  221. }
  222. interface Storage {
  223. Name: string;
  224. StorageItems: StorageItem[];
  225. WeightLoad: number;
  226. VolumeLoad: number;
  227. Type: 'STORE' | 'WAREHOUSE_STORE' | 'FTL_FUEL_STORE' | 'STL_FUEL_STORE' | 'SHIP_STORE';
  228. }
  229. interface Warehouse {
  230. StoreId: string;
  231. LocationNaturalId: string;
  232. }
  233. interface Amount {
  234. MaterialTicker: string;
  235. DailyAmount: number;
  236. netConsumption?: number;
  237. }
  238. interface FIOBurn {
  239. PlanetName: string;
  240. PlanetNaturalId: string;
  241. Error: any;
  242. OrderConsumption: Amount[];
  243. WorkforceConsumption: Amount[];
  244. Inventory: StorageItem[];
  245. OrderProduction: Amount[];
  246. }