market.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. markets.append(Market(price['FullTicker'], bid=price['Bid'], ask=price['Ask'], spread=spread, traded=traded,
  34. bids_filled=bids_filled, asks_filled=asks_filled))
  35. markets.sort(key=lambda m: (m.ask - m.bid) * min(m.bids_filled, m.asks_filled), reverse=True)
  36. print(f'{"mat":^8} {"bid":^5} {"ask":^5} spread {"traded":^7} bids filled asks filled')
  37. for m in markets:
  38. 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}')
  39. def check_cxos() -> None:
  40. orders: typing.Sequence[ExchangeOrder] = cache.get('https://rest.fnar.net/cxos/' + config.username,
  41. headers={'Authorization': config.fio_api_key})
  42. summary: typing.Mapping[tuple[str, str], ExchangeSummary] = {
  43. (summary['MaterialTicker'], summary['ExchangeCode']): summary
  44. for summary in cache.get('https://rest.fnar.net/exchange/all')
  45. }
  46. for order in orders:
  47. state = summary[order['MaterialTicker'], order['ExchangeCode']]
  48. if order['OrderType'] == 'BUYING' and state['Bid'] is not None and state['Bid'] > order['Limit']:
  49. print('outbid on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  50. elif order['OrderType'] == 'SELLING' and state['Ask'] is not None and state['Ask'] < order['Limit']:
  51. print('undercut on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  52. print()
  53. warehouses: typing.Sequence[Warehouse] = cache.get('https://rest.fnar.net/sites/warehouses/' + config.username,
  54. headers={'Authorization': config.fio_api_key})
  55. for warehouse in warehouses:
  56. if warehouse['LocationNaturalId'] in config.ignore_warehouses:
  57. continue
  58. storage: Storage = cache.get(f'https://rest.fnar.net/storage/{config.username}/{warehouse["StoreId"]}',
  59. headers={'Authorization': config.fio_api_key})
  60. if storage['WeightLoad'] > 0 or storage['VolumeLoad'] > 0:
  61. print('warehouse', warehouse['LocationNaturalId'], 'is not empty')
  62. print()
  63. def estimate_filled_orders(exchange_ticker: str, midpoint: float) -> tuple[float, float]:
  64. '''use price chart to estimate how many bids and asks were filled'''
  65. bids = asks = 0
  66. for hist in cache.get('https://rest.fnar.net/exchange/cxpc/' + exchange_ticker):
  67. if hist['Interval'] != 'MINUTE_FIVE':
  68. continue
  69. if hist['Low'] > midpoint:
  70. asks += hist['Traded']
  71. elif hist['High'] < midpoint:
  72. bids += hist['Traded']
  73. elif hist['High'] == hist['Low']:
  74. assert hist['High'] == midpoint
  75. else:
  76. interval_bids = (hist['High'] * hist['Traded'] - hist['Volume']) / (hist['High'] - hist['Low'])
  77. interval_asks = hist['Traded'] - interval_bids
  78. bids += interval_bids
  79. asks += interval_asks
  80. return bids, asks
  81. class ExchangeOrder(typing.TypedDict):
  82. MaterialTicker: str
  83. ExchangeCode: str
  84. OrderType: typing.Literal['SELLING'] | typing.Literal['BUYING']
  85. Limit: float
  86. class ExchangeSummary(typing.TypedDict):
  87. MaterialTicker: str
  88. ExchangeCode: str
  89. Bid: float | None
  90. Ask: float | None
  91. class Warehouse(typing.TypedDict):
  92. StoreId: str
  93. LocationNaturalId: str
  94. class Storage(typing.TypedDict):
  95. StorageItems: typing.Sequence
  96. WeightLoad: float
  97. VolumeLoad: float
  98. class RawPrice(typing.TypedDict):
  99. FullTicker: str
  100. Bid: float | None
  101. Ask: float | None
  102. HighYesterday: float | None
  103. LowYesterday: float | None
  104. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  105. class PriceChartPoint(typing.TypedDict):
  106. 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']
  107. High: float
  108. Low: float
  109. Volume: float
  110. Traded: int
  111. @dataclasses.dataclass(eq=False, slots=True)
  112. class Market:
  113. full_ticker: str
  114. bid: float
  115. ask: float
  116. spread: float
  117. traded: float
  118. bids_filled: float
  119. asks_filled: float
  120. if __name__ == '__main__':
  121. main()