market.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from __future__ import annotations
  2. import collections
  3. import dataclasses
  4. import sys
  5. import typing
  6. import cache
  7. from config import config
  8. def main() -> None:
  9. if len(sys.argv) > 1:
  10. exchange_tickers = sys.argv[1:]
  11. for ticker in exchange_tickers:
  12. bids_filled, asks_filled = estimate_filled_orders(ticker, 0)
  13. print(f'{ticker}: {bids_filled=}, {asks_filled=}')
  14. return
  15. check_cxos()
  16. raw_prices: list[RawPrice] = cache.get('https://refined-prun.github.io/refined-prices/all.json')
  17. markets: dict[str, list[Market]] = collections.defaultdict(list)
  18. for price in raw_prices:
  19. if (traded := price['AverageTraded7D']) is None or traded < 100:
  20. continue
  21. if price['Bid'] is None or price['Ask'] is None:
  22. continue
  23. if (high := price['HighYesterday']) is None or (low := price['LowYesterday']) is None:
  24. continue
  25. if (high - low) / high < 0.1:
  26. continue
  27. spread = (price['Ask'] - price['Bid']) / price['Ask']
  28. if spread < 0.15:
  29. continue
  30. bids_filled, asks_filled = estimate_filled_orders(price['FullTicker'], (price['Bid'] + price['Ask']) / 2)
  31. bid_fill_ratio = bids_filled / (bids_filled + asks_filled)
  32. if bid_fill_ratio < 0.05 or bid_fill_ratio > 0.95:
  33. continue
  34. max_profit = (price['Ask'] - price['Bid']) * min(bids_filled, asks_filled)
  35. markets[price['ExchangeCode']].append(Market(price['FullTicker'], bid=price['Bid'], ask=price['Ask'],
  36. spread=spread, traded=traded, bids_filled=bids_filled, asks_filled=asks_filled, max_profit=max_profit))
  37. print(f'{"mat":^8} {"bid":^5} {"ask":^5} spread {"traded":^7} bids filled asks filled max profit')
  38. for commodities in markets.values():
  39. for m in commodities:
  40. print(f'{m.full_ticker:>8} {m.bid:5} {m.ask:5} {m.spread*100: 5.0f}% {m.traded:7.0f} {m.bids_filled:10.0f} {m.asks_filled:10.0f} {m.max_profit:10.0f}')
  41. def check_cxos() -> None:
  42. orders: typing.Sequence[ExchangeOrder] = cache.get('https://rest.fnar.net/cxos/' + config.username,
  43. headers={'Authorization': config.fio_api_key})
  44. summary: typing.Mapping[tuple[str, str], ExchangeSummary] = {
  45. (summary['MaterialTicker'], summary['ExchangeCode']): summary
  46. for summary in cache.get('https://rest.fnar.net/exchange/all')
  47. }
  48. for order in orders:
  49. state = summary[order['MaterialTicker'], order['ExchangeCode']]
  50. if order['OrderType'] == 'BUYING' and state['Bid'] is not None and state['Bid'] > order['Limit']:
  51. print('outbid on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  52. elif order['OrderType'] == 'SELLING' and state['Ask'] is not None and state['Ask'] < order['Limit']:
  53. print('undercut on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  54. print()
  55. warehouses: typing.Sequence[Warehouse] = cache.get('https://rest.fnar.net/sites/warehouses/' + config.username,
  56. headers={'Authorization': config.fio_api_key})
  57. for warehouse in warehouses:
  58. if warehouse['LocationNaturalId'] in config.ignore_warehouses:
  59. continue
  60. storage: Storage = cache.get(f'https://rest.fnar.net/storage/{config.username}/{warehouse["StoreId"]}',
  61. headers={'Authorization': config.fio_api_key})
  62. if storage['WeightLoad'] > 0 or storage['VolumeLoad'] > 0:
  63. print('warehouse', warehouse['LocationNaturalId'], 'is not empty')
  64. print()
  65. def estimate_filled_orders(exchange_ticker: str, midpoint: float) -> tuple[float, float]:
  66. '''use price chart to estimate how many bids and asks were filled'''
  67. bids = asks = 0
  68. for hist in cache.get('https://rest.fnar.net/exchange/cxpc/' + exchange_ticker):
  69. if hist['Interval'] != 'MINUTE_FIVE':
  70. continue
  71. if hist['Low'] > midpoint:
  72. asks += hist['Traded']
  73. elif hist['High'] < midpoint:
  74. bids += hist['Traded']
  75. elif hist['High'] == hist['Low']:
  76. assert hist['High'] == midpoint
  77. else:
  78. interval_bids = (hist['High'] * hist['Traded'] - hist['Volume']) / (hist['High'] - hist['Low'])
  79. interval_asks = hist['Traded'] - interval_bids
  80. bids += interval_bids
  81. asks += interval_asks
  82. return bids, asks
  83. class ExchangeOrder(typing.TypedDict):
  84. MaterialTicker: str
  85. ExchangeCode: str
  86. OrderType: typing.Literal['SELLING'] | typing.Literal['BUYING']
  87. Limit: float
  88. class ExchangeSummary(typing.TypedDict):
  89. MaterialTicker: str
  90. ExchangeCode: str
  91. Bid: float | None
  92. Ask: float | None
  93. class Warehouse(typing.TypedDict):
  94. StoreId: str
  95. LocationNaturalId: str
  96. class Storage(typing.TypedDict):
  97. StorageItems: typing.Sequence
  98. WeightLoad: float
  99. VolumeLoad: float
  100. class RawPrice(typing.TypedDict):
  101. FullTicker: str
  102. ExchangeCode: str
  103. Bid: float | None
  104. Ask: float | None
  105. HighYesterday: float | None
  106. LowYesterday: float | None
  107. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  108. class PriceChartPoint(typing.TypedDict):
  109. Interval: typing.Literal['MINUTE_FIVE'] | typing.Literal['MINUTE_FIFTEEN'] | typing.Literal['MINUTE_THIRTY'] | typing.Literal['HOUR_ONE'] | typing.Literal['HOUR_TWO'] | typing.Literal['HOUR_FOUR'] | typing.Literal['HOUR_SIX'] | typing.Literal['HOUR_TWELVE'] | typing.Literal['DAY_ONE'] | typing.Literal['DAY_THREE']
  110. High: float
  111. Low: float
  112. Volume: float
  113. Traded: int
  114. @dataclasses.dataclass(eq=False, slots=True)
  115. class Market:
  116. full_ticker: str
  117. bid: float
  118. ask: float
  119. spread: float
  120. traded: float
  121. bids_filled: float
  122. asks_filled: float
  123. max_profit: float
  124. def __lt__(self, o) -> bool:
  125. return self.max_profit < o.max_profit
  126. if __name__ == '__main__':
  127. main()