buy.ts 9.8 KB

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