buy.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 fetch('https://refined-prun.github.io/refined-prices/all.json').then(r => r.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 fetch('https://rest.fnar.net/fioweb/burn/user/' + username,
  121. {headers: {'Authorization': apiKey}}).then(r => r.json());
  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 fetch('https://rest.fnar.net/sites/warehouses/' + username,
  127. {headers: {'Authorization': apiKey}}).then(r => r.json());
  128. for (const warehouse of warehouses)
  129. if (warehouse.LocationNaturalId === whName) {
  130. const storage: Storage = await fetch(`https://rest.fnar.net/storage/${username}/${warehouse.StoreId}`,
  131. {headers: {'Authorization': apiKey}}).then(r => r.json());
  132. const inventory = new Map<string, number>();
  133. for (const item of storage.StorageItems)
  134. inventory.set(item.MaterialTicker, item.MaterialAmount);
  135. return inventory;
  136. }
  137. throw new Error(`couldn't find ${whName} warehouse`);
  138. }
  139. async function getBids(username: string, apiKey: string, cx: string) {
  140. const allOrders: ExchangeOrder[] = await fetch('https://rest.fnar.net/cxos/' + username,
  141. {headers: {'Authorization': apiKey}}).then(r => r.json());
  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. class Planet {
  150. name: string;
  151. inventory: Map<string, number>;
  152. netConsumption: Amount[];
  153. exporting: Set<string>; // producing more than consumption
  154. constructor(fioBurn: FIOBurn) {
  155. this.name = fioBurn.PlanetName || fioBurn.PlanetNaturalId;
  156. this.inventory = new Map();
  157. for (const item of fioBurn.Inventory)
  158. this.inventory.set(item.MaterialTicker, item.MaterialAmount);
  159. const producing = new Map<string, Amount>();
  160. for (const item of fioBurn.OrderProduction)
  161. producing.set(item.MaterialTicker, item);
  162. this.netConsumption = [];
  163. for (const c of [...fioBurn.OrderConsumption, ...fioBurn.WorkforceConsumption]) {
  164. let net = c.DailyAmount;
  165. const production = producing.get(c.MaterialTicker);
  166. if (production) {
  167. net -= production.DailyAmount;
  168. if (net < 0)
  169. continue;
  170. }
  171. c.netConsumption = net;
  172. this.netConsumption.push(c);
  173. }
  174. const consuming = new Set(this.netConsumption.map(item => item.MaterialTicker));
  175. this.exporting = new Set<string>();
  176. for (const item of fioBurn.OrderProduction)
  177. if (!consuming.has(item.MaterialTicker))
  178. this.exporting.add(item.MaterialTicker);
  179. }
  180. supplyForDays(targetDays: number): Map<string, number> {
  181. const buy = new Map<string, number>();
  182. for (const consumption of this.netConsumption) {
  183. const ticker = consumption.MaterialTicker;
  184. const avail = this.inventory.get(ticker) ?? 0;
  185. const dailyConsumption = consumption.netConsumption!;
  186. const days = avail / dailyConsumption;
  187. if (days < targetDays)
  188. buy.set(ticker, Math.ceil((targetDays - days) * dailyConsumption));
  189. }
  190. return buy;
  191. }
  192. }
  193. interface Material {
  194. ticker: string;
  195. amount: number;
  196. bids: number;
  197. have: number;
  198. spread: number;
  199. savings: number;
  200. }
  201. interface RawPrice {
  202. MaterialTicker: string;
  203. ExchangeCode: string;
  204. Bid: number | null;
  205. Ask: number | null;
  206. FullTicker: string;
  207. }
  208. interface ExchangeOrder {
  209. MaterialTicker: string;
  210. ExchangeCode: string;
  211. OrderType: 'SELLING' | 'BUYING';
  212. Status: 'FILLED' | 'PARTIALLY_FILLED';
  213. Amount: number;
  214. Limit: number;
  215. }
  216. interface StorageItem {
  217. MaterialTicker: string;
  218. MaterialAmount: number;
  219. }
  220. interface Storage {
  221. Name: string;
  222. StorageItems: StorageItem[];
  223. WeightLoad: number;
  224. VolumeLoad: number;
  225. Type: 'STORE' | 'WAREHOUSE_STORE' | 'FTL_FUEL_STORE' | 'STL_FUEL_STORE' | 'SHIP_STORE';
  226. }
  227. interface Warehouse {
  228. StoreId: string;
  229. LocationNaturalId: string;
  230. }
  231. interface Amount {
  232. MaterialTicker: string;
  233. DailyAmount: number;
  234. netConsumption?: number;
  235. }
  236. interface FIOBurn {
  237. PlanetName: string;
  238. PlanetNaturalId: string;
  239. Error: any;
  240. OrderConsumption: Amount[];
  241. WorkforceConsumption: Amount[];
  242. Inventory: StorageItem[];
  243. OrderProduction: Amount[];
  244. }