buy.ts 8.3 KB

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