-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathround1.py
270 lines (207 loc) · 9.26 KB
/
round1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import json
from abc import abstractmethod
from collections import deque
from datamodel import Listing, Observation, Order, OrderDepth, ProsperityEncoder, Symbol, Trade, TradingState
from typing import Any, TypeAlias
JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None
class Logger:
def __init__(self) -> None:
self.logs = ""
self.max_log_length = 3750
def print(self, *objects: Any, sep: str = " ", end: str = "\n") -> None:
self.logs += sep.join(map(str, objects)) + end
def flush(self, state: TradingState, orders: dict[Symbol, list[Order]], conversions: int, trader_data: str) -> None:
base_length = len(self.to_json([
self.compress_state(state, ""),
self.compress_orders(orders),
conversions,
"",
"",
]))
# We truncate state.traderData, trader_data, and self.logs to the same max. length to fit the log limit
max_item_length = (self.max_log_length - base_length) // 3
print(self.to_json([
self.compress_state(state, self.truncate(state.traderData, max_item_length)),
self.compress_orders(orders),
conversions,
self.truncate(trader_data, max_item_length),
self.truncate(self.logs, max_item_length),
]))
self.logs = ""
def compress_state(self, state: TradingState, trader_data: str) -> list[Any]:
return [
state.timestamp,
trader_data,
self.compress_listings(state.listings),
self.compress_order_depths(state.order_depths),
self.compress_trades(state.own_trades),
self.compress_trades(state.market_trades),
state.position,
self.compress_observations(state.observations),
]
def compress_listings(self, listings: dict[Symbol, Listing]) -> list[list[Any]]:
compressed = []
for listing in listings.values():
compressed.append([listing["symbol"], listing["product"], listing["denomination"]])
return compressed
def compress_order_depths(self, order_depths: dict[Symbol, OrderDepth]) -> dict[Symbol, list[Any]]:
compressed = {}
for symbol, order_depth in order_depths.items():
compressed[symbol] = [order_depth.buy_orders, order_depth.sell_orders]
return compressed
def compress_trades(self, trades: dict[Symbol, list[Trade]]) -> list[list[Any]]:
compressed = []
for arr in trades.values():
for trade in arr:
compressed.append([
trade.symbol,
trade.price,
trade.quantity,
trade.buyer,
trade.seller,
trade.timestamp,
])
return compressed
def compress_observations(self, observations: Observation) -> list[Any]:
conversion_observations = {}
for product, observation in observations.conversionObservations.items():
conversion_observations[product] = [
observation.bidPrice,
observation.askPrice,
observation.transportFees,
observation.exportTariff,
observation.importTariff,
observation.sunlight,
observation.humidity,
]
return [observations.plainValueObservations, conversion_observations]
def compress_orders(self, orders: dict[Symbol, list[Order]]) -> list[list[Any]]:
compressed = []
for arr in orders.values():
for order in arr:
compressed.append([order.symbol, order.price, order.quantity])
return compressed
def to_json(self, value: Any) -> str:
return json.dumps(value, cls=ProsperityEncoder, separators=(",", ":"))
def truncate(self, value: str, max_length: int) -> str:
if len(value) <= max_length:
return value
return value[:max_length - 3] + "..."
logger = Logger()
class Strategy:
def __init__(self, symbol: str, limit: int) -> None:
self.symbol = symbol
self.limit = limit
@abstractmethod
def act(self, state: TradingState) -> None:
raise NotImplementedError()
def run(self, state: TradingState) -> list[Order]:
self.orders = []
self.act(state)
return self.orders
def buy(self, price: int, quantity: int) -> None:
self.orders.append(Order(self.symbol, price, quantity))
def sell(self, price: int, quantity: int) -> None:
self.orders.append(Order(self.symbol, price, -quantity))
def save(self) -> JSON:
return None
def load(self, data: JSON) -> None:
pass
class MarketMakingStrategy(Strategy):
def __init__(self, symbol: Symbol, limit: int) -> None:
super().__init__(symbol, limit)
self.window = deque()
self.window_size = 10
@abstractmethod
def get_true_value(state: TradingState) -> int:
raise NotImplementedError()
def act(self, state: TradingState) -> None:
true_value = self.get_true_value(state)
order_depth = state.order_depths[self.symbol]
buy_orders = sorted(order_depth.buy_orders.items(), reverse=True)
sell_orders = sorted(order_depth.sell_orders.items())
position = state.position.get(self.symbol, 0)
to_buy = self.limit - position
to_sell = self.limit + position
self.window.append(abs(position) == self.limit)
if len(self.window) > self.window_size:
self.window.popleft()
soft_liquidate = len(self.window) == self.window_size and sum(self.window) >= self.window_size / 2 and self.window[-1]
hard_liquidate = len(self.window) == self.window_size and all(self.window)
max_buy_price = true_value - 1 if position > self.limit * 0.5 else true_value
min_sell_price = true_value + 1 if position < self.limit * -0.5 else true_value
for price, volume in sell_orders:
if to_buy > 0 and price <= max_buy_price:
quantity = min(to_buy, -volume)
self.buy(price, quantity)
to_buy -= quantity
if to_buy > 0 and hard_liquidate:
quantity = to_buy // 2
self.buy(true_value, quantity)
to_buy -= quantity
if to_buy > 0 and soft_liquidate:
quantity = to_buy // 2
self.buy(true_value - 2, quantity)
to_buy -= quantity
if to_buy > 0:
popular_buy_price = max(buy_orders, key=lambda tup: tup[1])[0]
price = min(max_buy_price, popular_buy_price + 1)
self.buy(price, to_buy)
for price, volume in buy_orders:
if to_sell > 0 and price >= min_sell_price:
quantity = min(to_sell, volume)
self.sell(price, quantity)
to_sell -= quantity
if to_sell > 0 and hard_liquidate:
quantity = to_sell // 2
self.sell(true_value, quantity)
to_sell -= quantity
if to_sell > 0 and soft_liquidate:
quantity = to_sell // 2
self.sell(true_value + 2, quantity)
to_sell -= quantity
if to_sell > 0:
popular_sell_price = min(sell_orders, key=lambda tup: tup[1])[0]
price = max(min_sell_price, popular_sell_price - 1)
self.sell(price, to_sell)
def save(self) -> JSON:
return list(self.window)
def load(self, data: JSON) -> None:
self.window = deque(data)
class AmethystsStrategy(MarketMakingStrategy):
def get_true_value(self, state: TradingState) -> int:
return 10_000
class StarfruitStrategy(MarketMakingStrategy):
def get_true_value(self, state: TradingState) -> int:
order_depth = state.order_depths[self.symbol]
order_depth = state.order_depths[self.symbol]
buy_orders = sorted(order_depth.buy_orders.items(), reverse=True)
sell_orders = sorted(order_depth.sell_orders.items())
popular_buy_price = max(buy_orders, key=lambda tup: tup[1])[0]
popular_sell_price = min(sell_orders, key=lambda tup: tup[1])[0]
return round((popular_buy_price + popular_sell_price) / 2)
class Trader:
def __init__(self) -> None:
limits = {
"AMETHYSTS": 20,
"STARFRUIT": 20,
}
self.strategies = {symbol: clazz(symbol, limits[symbol]) for symbol, clazz in {
"AMETHYSTS": AmethystsStrategy,
"STARFRUIT": StarfruitStrategy,
}.items()}
def run(self, state: TradingState) -> tuple[dict[Symbol, list[Order]], int, str]:
logger.print(state.position)
conversions = 0
old_trader_data = json.loads(state.traderData) if state.traderData != "" else {}
new_trader_data = {}
orders = {}
for symbol, strategy in self.strategies.items():
if symbol in old_trader_data:
strategy.load(old_trader_data.get(symbol, None))
if symbol in state.order_depths:
orders[symbol] = strategy.run(state)
new_trader_data[symbol] = strategy.save()
trader_data = json.dumps(new_trader_data, separators=(",", ":"))
logger.flush(state, orders, conversions, trader_data)
return orders, conversions, trader_data