buy.ts 10 KB

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