market.py 5.1 KB

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