buy.ts 8.9 KB

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