buy.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. document.querySelector('#fetch')!.addEventListener('click', async () => {
  19. const supplyForDays = parseInt((document.querySelector('#days') as HTMLInputElement).value, 10);
  20. const loader = document.querySelector('#loader') as HTMLElement;
  21. loader.innerHTML = '';
  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. const buy = new Map<string, number>();
  63. for (const planet of planets) {
  64. for (const [mat, amount] of planet.supplyForDays(supplyForDays))
  65. buy.set(mat, (buy.get(mat) ?? 0) + amount);
  66. for (const mat of planet.exporting) {
  67. const planetExport = planet.inventory.get(mat);
  68. if (planetExport)
  69. avail.set(mat, (avail.get(mat) ?? 0) + planetExport);
  70. }
  71. }
  72. // what's left to buy
  73. const materials: Material[] = [];
  74. for (const [mat, amount] of buy) {
  75. const remaining = Math.max(amount - (bids.get(mat) ?? 0) - (avail.get(mat) ?? 0), 0);
  76. const price = prices.get(mat);
  77. if (!price || price.Bid === null || price.Ask === null) {
  78. console.log(mat, 'has no bid/ask');
  79. continue;
  80. }
  81. const spread = price.Ask - price.Bid;
  82. materials.push({
  83. ticker: mat,
  84. amount,
  85. bids: bids.get(mat) ?? 0,
  86. have: avail.get(mat) ?? 0,
  87. spread,
  88. savings: spread * remaining,
  89. });
  90. }
  91. materials.sort((a, b) => b.savings - a.savings);
  92. const h2 = document.createElement('h2');
  93. h2.textContent = `${cx}/${warehouseNames[cx]}`;
  94. const span = document.createElement('span');
  95. span.textContent = planets.map(p => p.name).join(', ');
  96. const table = document.createElement('table');
  97. table.innerHTML = `
  98. <thead>
  99. <tr>
  100. <th>mat</th>
  101. <th data-tooltip="needed to supply all planets">want</th>
  102. <th>bids</th>
  103. <th data-tooltip="in warehouse">have</th>
  104. <th data-tooltip="want - bids - have">buy</th>
  105. <th data-tooltip="ask - bid">spread</th>
  106. <th data-tooltip="buy × spread">savings</th>
  107. </tr>
  108. </thead>
  109. <tbody></tbody>`;
  110. const tbody = table.querySelector('tbody')!;
  111. const toBuy: Record<string, number> = {};
  112. const priceLimits: Record<string, number> = {};
  113. const format = new Intl.NumberFormat(undefined, {maximumFractionDigits: 0}).format;
  114. for (const m of materials) {
  115. const tr = document.createElement('tr');
  116. const buyAmount = Math.max(m.amount - m.bids - m.have, 0);
  117. tr.innerHTML = `
  118. <td>${m.ticker}</td>
  119. <td>${format(m.amount)}</td>
  120. <td>${format(m.bids)}</td>
  121. <td>${format(m.have)}</td>
  122. <td>${format(buyAmount)}</td>
  123. <td>${format(m.spread)}</td>
  124. <td>${format(m.savings)}</td>
  125. `;
  126. if (buyAmount > 0) {
  127. if (m.bids === 0)
  128. tr.children[2].classList.add('red');
  129. toBuy[m.ticker] = buyAmount;
  130. const bid = prices.get(m.ticker)!.Bid!;
  131. const epsilon = 10 ** (Math.floor(Math.log10(bid)) - 2);
  132. const limit = bid + 2 * epsilon;
  133. priceLimits[m.ticker] = limit;
  134. }
  135. tbody.appendChild(tr);
  136. }
  137. const xitSection = document.createElement('section');
  138. xitSection.classList.add('xit-act');
  139. xitSection.innerHTML = `
  140. <textarea readonly></textarea>
  141. <input type="button" value="copy">`;
  142. xitSection.querySelector('textarea')!.value = JSON.stringify({
  143. 'actions': [
  144. {'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': cx,
  145. 'priceLimits': priceLimits, 'buyPartial': true, 'allowUnfilled': true, 'useCXInv': false},
  146. ],
  147. 'global': {'name': `${cx} buy orders for ${supplyForDays} days`},
  148. 'groups': [{'type': 'Manual', 'name': 'A1', 'materials': toBuy}],
  149. });
  150. // deposits of current bids
  151. orders.sort((a, b) => (b.Limit * b.Amount) - (a.Limit * a.Amount));
  152. for (const order of orders) {
  153. const deposit = order.Limit * order.Amount;
  154. console.log(`${order.MaterialTicker.padEnd(4)} ${deposit}\n`);
  155. }
  156. return [h2, span, table, xitSection];
  157. }
  158. async function getPrices(cx: string) {
  159. const rawPrices= await cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json');
  160. const prices = new Map<string, RawPrice>();
  161. for (const p of rawPrices)
  162. if (p.ExchangeCode === cx)
  163. prices.set(p.MaterialTicker, p);
  164. return prices;
  165. }
  166. async function getPlanets(username: string, apiKey: string) {
  167. const fioBurns: FIOBurn[] = await cachedFetchJSON('https://rest.fnar.net/fioweb/burn/user/' + username,
  168. {headers: {'Authorization': apiKey}});
  169. const planets = fioBurns.map(burn => new Planet(burn));
  170. return planets;
  171. }
  172. async function warehouseInventory(username: string, apiKey: string, whName: string): Promise<Map<string, number>> {
  173. const warehouses: Warehouse[] = await cachedFetchJSON('https://rest.fnar.net/sites/warehouses/' + username,
  174. {headers: {'Authorization': apiKey}});
  175. const inventory = new Map<string, number>();
  176. for (const warehouse of warehouses)
  177. if (warehouse.LocationNaturalId === whName) {
  178. const storage: Storage = await cachedFetchJSON(`https://rest.fnar.net/storage/${username}/${warehouse.StoreId}`,
  179. {headers: {'Authorization': apiKey}});
  180. for (const item of storage.StorageItems)
  181. inventory.set(item.MaterialTicker, item.MaterialAmount);
  182. break;
  183. }
  184. return inventory;
  185. }
  186. async function getBids(username: string, apiKey: string, cx: string) {
  187. const allOrders: ExchangeOrder[] = await cachedFetchJSON('https://rest.fnar.net/cxos/' + username,
  188. {headers: {'Authorization': apiKey}});
  189. const orders = allOrders.filter(order =>
  190. order.OrderType === 'BUYING' && order.Status !== 'FILLED' && order.ExchangeCode === cx);
  191. const bids = new Map<string, number>();
  192. for (const order of orders)
  193. bids.set(order.MaterialTicker, (bids.get(order.MaterialTicker) ?? 0) + order.Amount);
  194. return {bids, orders};
  195. }
  196. const fetchCache = new Map<string, any>();
  197. async function cachedFetchJSON(url: string, options?: RequestInit): Promise<any> {
  198. if (fetchCache.has(url))
  199. return fetchCache.get(url);
  200. const response = await fetch(url, options).then((r) => r.json());
  201. fetchCache.set(url, response);
  202. return response;
  203. }
  204. class Planet {
  205. id: string;
  206. name: string;
  207. inventory: Map<string, number>;
  208. netConsumption: Amount[];
  209. exporting: Set<string>; // producing more than consumption
  210. constructor(fioBurn: FIOBurn) {
  211. this.id = fioBurn.PlanetId;
  212. this.name = fioBurn.PlanetName || fioBurn.PlanetNaturalId;
  213. this.inventory = new Map();
  214. for (const item of fioBurn.Inventory)
  215. this.inventory.set(item.MaterialTicker, item.MaterialAmount);
  216. const producing = new Map<string, Amount>();
  217. for (const item of fioBurn.OrderProduction)
  218. producing.set(item.MaterialTicker, item);
  219. this.netConsumption = [];
  220. for (const c of [...fioBurn.OrderConsumption, ...fioBurn.WorkforceConsumption]) {
  221. let net = c.DailyAmount;
  222. const production = producing.get(c.MaterialTicker);
  223. if (production) {
  224. net -= production.DailyAmount;
  225. if (net < 0)
  226. continue;
  227. }
  228. c.netConsumption = net;
  229. this.netConsumption.push(c);
  230. }
  231. const consuming = new Set(this.netConsumption.map(item => item.MaterialTicker));
  232. this.exporting = new Set<string>();
  233. for (const item of fioBurn.OrderProduction)
  234. if (!consuming.has(item.MaterialTicker))
  235. this.exporting.add(item.MaterialTicker);
  236. }
  237. supplyForDays(targetDays: number): Map<string, number> {
  238. const buy = new Map<string, number>();
  239. for (const consumption of this.netConsumption) {
  240. const ticker = consumption.MaterialTicker;
  241. const avail = this.inventory.get(ticker) ?? 0;
  242. const dailyConsumption = consumption.netConsumption!;
  243. const days = avail / dailyConsumption;
  244. if (days < targetDays)
  245. buy.set(ticker, Math.ceil((targetDays - days) * dailyConsumption));
  246. }
  247. return buy;
  248. }
  249. }
  250. interface Material {
  251. ticker: string;
  252. amount: number;
  253. bids: number;
  254. have: number;
  255. spread: number;
  256. savings: number;
  257. }
  258. interface RawPrice {
  259. MaterialTicker: string;
  260. ExchangeCode: string;
  261. Bid: number | null;
  262. Ask: number | null;
  263. FullTicker: string;
  264. }
  265. interface ExchangeOrder {
  266. MaterialTicker: string;
  267. ExchangeCode: string;
  268. OrderType: 'SELLING' | 'BUYING';
  269. Status: 'FILLED' | 'PARTIALLY_FILLED';
  270. Amount: number;
  271. Limit: number;
  272. }
  273. interface StorageItem {
  274. MaterialTicker: string;
  275. MaterialAmount: number;
  276. }
  277. interface Storage {
  278. Name: string;
  279. StorageItems: StorageItem[];
  280. WeightLoad: number;
  281. VolumeLoad: number;
  282. Type: 'STORE' | 'WAREHOUSE_STORE' | 'FTL_FUEL_STORE' | 'STL_FUEL_STORE' | 'SHIP_STORE';
  283. }
  284. interface Warehouse {
  285. StoreId: string;
  286. LocationNaturalId: string;
  287. }
  288. interface Amount {
  289. MaterialTicker: string;
  290. DailyAmount: number;
  291. netConsumption?: number;
  292. }
  293. interface FIOBurn {
  294. PlanetId: string;
  295. PlanetName: string;
  296. PlanetNaturalId: string;
  297. Error: any;
  298. OrderConsumption: Amount[];
  299. WorkforceConsumption: Amount[];
  300. Inventory: StorageItem[];
  301. OrderProduction: Amount[];
  302. }