buy.ts 8.7 KB

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