market.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. a = analyze_price_chart(ticker, 0)
  13. print(f'{ticker}: bids filled = {a.bids_filled:6}, asks filled = {a.asks_filled:6}, profit per interval = {a.profit_per_interval:10}')
  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. chart_analysis = analyze_price_chart(price['FullTicker'], (price['Bid'] + price['Ask']) / 2)
  31. max_profit = (price['Ask'] - price['Bid']) * min(chart_analysis.bids_filled, chart_analysis.asks_filled)
  32. markets[price['ExchangeCode']].append(Market(price['FullTicker'], bid=price['Bid'], ask=price['Ask'],
  33. spread=spread, max_profit=max_profit, chart_analysis=chart_analysis))
  34. print(' mat bid ask spread bids filled asks filled profit/time max profit')
  35. for commodities in markets.values():
  36. commodities.sort(reverse=True)
  37. for m in commodities:
  38. print(f'{m.full_ticker:>8} {m.bid:5} {m.ask:5} {m.spread*100: 5.0f}% {m.chart_analysis.bids_filled:12.0f} '
  39. f'{m.chart_analysis.asks_filled:12.0f} {m.chart_analysis.profit_per_interval:12.0f} {m.max_profit:11.0f}')
  40. print()
  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. if order['Status'] == 'FILLED':
  50. continue
  51. state = summary[order['MaterialTicker'], order['ExchangeCode']]
  52. if order['OrderType'] == 'BUYING' and state['Bid'] is not None and state['Bid'] > order['Limit']:
  53. print('outbid on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  54. elif order['OrderType'] == 'SELLING' and state['Ask'] is not None and state['Ask'] < order['Limit']:
  55. print('undercut on', f'{order["MaterialTicker"]}.{order["ExchangeCode"]}')
  56. print()
  57. warehouses: typing.Sequence[Warehouse] = cache.get('https://rest.fnar.net/sites/warehouses/' + config.username,
  58. headers={'Authorization': config.fio_api_key})
  59. for warehouse in warehouses:
  60. if warehouse['LocationNaturalId'] in config.ignore_warehouses:
  61. continue
  62. storage: Storage = cache.get(f'https://rest.fnar.net/storage/{config.username}/{warehouse["StoreId"]}',
  63. headers={'Authorization': config.fio_api_key})
  64. if storage['WeightLoad'] > 0 or storage['VolumeLoad'] > 0:
  65. print('warehouse', warehouse['LocationNaturalId'], 'is not empty')
  66. print()
  67. def analyze_price_chart(exchange_ticker: str, midpoint: float) -> ChartAnalysis:
  68. '''use price chart to estimate how long it takes to fill a bid and then an ask'''
  69. pcpoints: list[PriceChartPoint] = [p for p in cache.get('https://rest.fnar.net/exchange/cxpc/' + exchange_ticker)
  70. if p['Interval'] == 'MINUTE_FIVE']
  71. pcpoints.reverse()
  72. five_min = 5 * 60 * 1000
  73. asks_filled: list[AskFilled] = []
  74. r = ChartAnalysis(bids_filled=0, asks_filled=0, profit_per_interval=0)
  75. for hist in pcpoints:
  76. time = hist['DateEpochMs'] // five_min
  77. bids = asks = 0
  78. if hist['Low'] > midpoint:
  79. asks = hist['Traded']
  80. r.asks_filled += asks
  81. elif hist['High'] < midpoint:
  82. bids = hist['Traded']
  83. r.bids_filled += bids
  84. elif hist['High'] == hist['Low']: # all trades right at midpoint
  85. assert hist['High'] == midpoint
  86. else:
  87. interval_bids = (hist['High'] * hist['Traded'] - hist['Volume']) / (hist['High'] - hist['Low'])
  88. interval_asks = hist['Traded'] - interval_bids
  89. r.bids_filled += interval_bids
  90. r.asks_filled += interval_asks
  91. bids = int(interval_bids)
  92. asks = int(interval_asks)
  93. if bids and asks:
  94. intra_interval_trades = min(bids, asks)
  95. r.profit_per_interval += (hist['High'] - hist['Low']) * intra_interval_trades
  96. bids -= intra_interval_trades
  97. asks -= intra_interval_trades
  98. assert bids == 0 or asks == 0
  99. while bids > 0 and len(asks_filled) > 0:
  100. profit_per_unit_per_interval = (asks_filled[-1].price - hist['Low']) / (asks_filled[-1].time - time)
  101. if asks_filled[-1].amount >= bids:
  102. r.profit_per_interval += bids * profit_per_unit_per_interval
  103. asks_filled[-1].amount -= bids
  104. if asks_filled[-1].amount == 0:
  105. asks_filled.pop()
  106. bids = 0
  107. else:
  108. r.profit_per_interval += asks_filled[-1].amount * profit_per_unit_per_interval
  109. bids -= asks_filled[-1].amount
  110. asks_filled.pop()
  111. if asks:
  112. asks_filled.append(AskFilled(price=hist['High'], amount=asks, time=time))
  113. return r
  114. class ExchangeOrder(typing.TypedDict):
  115. MaterialTicker: str
  116. ExchangeCode: str
  117. OrderType: typing.Literal['SELLING'] | typing.Literal['BUYING']
  118. Status: typing.Literal['FILLED'] | typing.Literal['PARTIALLY_FILLED'] | typing.Literal['FILLED']
  119. Limit: float
  120. class ExchangeSummary(typing.TypedDict):
  121. MaterialTicker: str
  122. ExchangeCode: str
  123. Bid: float | None
  124. Ask: float | None
  125. class Warehouse(typing.TypedDict):
  126. StoreId: str
  127. LocationNaturalId: str
  128. class Storage(typing.TypedDict):
  129. StorageItems: typing.Sequence
  130. WeightLoad: float
  131. VolumeLoad: float
  132. class RawPrice(typing.TypedDict):
  133. FullTicker: str
  134. MaterialTicker: str
  135. ExchangeCode: str
  136. Bid: float | None
  137. Ask: float | None
  138. HighYesterday: float | None
  139. LowYesterday: float | None
  140. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  141. class PriceChartPoint(typing.TypedDict):
  142. 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']
  143. DateEpochMs: int
  144. High: float
  145. Low: float
  146. Volume: float
  147. Traded: int
  148. @dataclasses.dataclass(eq=False, slots=True)
  149. class AskFilled:
  150. price: float
  151. amount: int
  152. time: int
  153. @dataclasses.dataclass(eq=False, slots=True)
  154. class ChartAnalysis:
  155. bids_filled: float
  156. asks_filled: float
  157. profit_per_interval: float
  158. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  159. class Market:
  160. full_ticker: str
  161. bid: float
  162. ask: float
  163. spread: float
  164. max_profit: float
  165. chart_analysis: ChartAnalysis
  166. def __lt__(self, o: Market) -> bool:
  167. return self.chart_analysis.profit_per_interval < o.chart_analysis.profit_per_interval
  168. if __name__ == '__main__':
  169. main()