buy.ts 9.8 KB

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