-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv_lob.py
More file actions
617 lines (555 loc) · 27.4 KB
/
env_lob.py
File metadata and controls
617 lines (555 loc) · 27.4 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# rlte/env_lob.py
# LOB-Simulator mit Noise-, Tactical- und Strategic-Teilnehmern
# Preis-Zeit-Priorität, Queue-Tracking für Agentenorders (Sec. 2, 3.1–3.3, 5; App. A–D).
# Trainingsschnittstelle: reset() / step(a) (vektorisiert wird in train_ln.py umgesetzt).
# :contentReference[oaicite:5]{index=5}
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional
import numpy as np
import torch
from . import config as C
from .utils import shifted_half_normal_int, integer_allocation, compute_reallocation
# === Dataklassen für Agenten-Limitorders (Tracking von "Ahead-of-NonAgent" & FIFO) ===
@dataclass
class AgentLot:
level: int # 1..D, relativ zur aktuellen BestAsk-Seite (Sell-Queue)
ahead_nonagent: int # Anzahl Non-Agent-Lots vor diesem Lot bei Einreihung
filled: bool = False
@dataclass
class StepInfo:
reward_cashflow: float
sold_lots: int # γ_n in Eq.(3)
forced_liq: bool
pb: int
pa: int
class LOBExecutionEnv:
"""
Einzelumgebung (für Vektorisierung in train_ln.py dupliziert).
- Märkte: "noise", "tactical", "strategic" (entsprechen Sec. 6.1 und App. A.1).
- Aktion: a ∈ S_K (K+1) -> Integer-Allokation (Market/Limit/Hold). (Sec. 3.2)
- Reward: normalisierter Cashflow (Eq. (3)); Forced Sell bei T. (Sec. 3.3)
- Zustände: gemäß Sec. 3.1 + Normalisierung aus App. D.
"""
def __init__(self, market: str = "noise", M0: int = 20, seed: Optional[int] = None, device: str = "cpu"):
assert market in ("noise", "tactical", "strategic")
self.market = market
self.M0 = int(M0)
self.device = device
self.rng = np.random.RandomState(C.SEED if seed is None else seed)
# Buchzustand (je Seite 1..D; Index 1 = Best-Level)
self.D = C.D_DEPTH
self.K = C.K_SIMPLEX
self.reset()
# ====================== Reset / Stationäre Form ======================
def reset(self) -> Dict[str, np.ndarray]:
# Zeit & Startpreise
self.t = -C.DT
self.pb = int(C.P_B_INIT)
self.pa = int(C.P_A_INIT)
# Volumina (Non-Agent)
self.bid_non = np.zeros(self.D, dtype=np.int64)
self.ask_non = np.zeros(self.D, dtype=np.int64)
# Agenten-Lots (Sell-Seite), je Level FIFO-Liste
self.agent_orders: Dict[int, List[AgentLot]] = {L: [] for L in range(1, self.D + 1)}
# Inventar und Caches
self.M_remaining = int(self.M0)
self.pb0 = None # wird bei t=0 gesetzt (normalisiert wird ggü. pb(0))
self.gamma_k = np.zeros(self.K) # γ-Feature (Anteil pro Preisniveau, K-1 relevant; App. D)
# Statistik in (t-DT, t]
self.delta_market_flow = 0 # Δm: Buy - Sell
self.delta_limit_flow = 0 # Δl: Buy - Sell (Signum auf Limit-Basis)
# Stationäre Form (App. A.2): Buch in Gleichgewicht bringen
self._seed_numpy()
self._reach_stationarity()
# Vorschritt bis t=0 (Marktteilnehmer handeln im Intervall [-Δt, 0])
self._simulate_interval(external_only=True)
# Normierungsanker
self.pb0 = int(self.pb)
# Baue initialen State (t=0)
return self._build_state()
def _seed_numpy(self):
np.random.seed(self.rng.randint(0, 2**31-1))
def _reach_stationarity(self):
"""
Schätze langfristige durchschnittliche Buchform (App. A.2) und initialisiere Buch ungefähr
in der Nähe dieses Gleichgewichts. Wir mitteln über STATIONARY_BURN_STEPS mit Stride.
"""
# Start mit leeren Queues am Startspread 1
self.pb = int(C.P_B_INIT)
self.pa = int(C.P_A_INIT)
self.bid_non[:] = 0
self.ask_non[:] = 0
burn = C.STATIONARY_BURN_STEPS
stride = C.STATIONARY_SAMPLE_STRIDE
acc_bid = np.zeros(self.D, dtype=np.float64)
acc_ask = np.zeros(self.D, dtype=np.float64)
cnt = 0
# temporär ohne Agent
for s in range(burn):
self._simulate_interval(external_only=True)
if s % stride == 0:
acc_bid += self.bid_non
acc_ask += self.ask_non
cnt += 1
mean_bid = np.maximum(1.0, acc_bid / max(1, cnt))
mean_ask = np.maximum(1.0, acc_ask / max(1, cnt))
# Initialisiere mit gerundeter Mittel-Form
self.bid_non = mean_bid.astype(np.int64).copy()
self.ask_non = mean_ask.astype(np.int64).copy()
# ====================== Schrittlogik ======================
def step(self, a: np.ndarray) -> Tuple[Dict[str, np.ndarray], float, bool, StepInfo]:
"""
a ∈ S_K (K+1 Komp.). Führt Re-Allokation + Markt-/Limitplatzierung des Agenten aus und
simuliert danach das Intervall (t, t+Δt]. Reward enthält Fill aus Market sofort und aus
Limit-Fills in (t, t+Δt]; erzwungene Market-Order bei T (Sec. 3.3).
"""
assert a.shape[0] == self.K + 1
done = False
forced = False
cash_before = 0.0
sold_before = 0
# Integer-Allokation bezogen auf M(t)
mkt_qty, limit_qtys, hold_qty = integer_allocation(a, self.M_remaining, self.K)
# Map k=1..K-1 -> Ask-Level-Index relativ zur aktuellen Spread j (meist 1)
spread = self.pa - self.pb
desired_levels: Dict[int, int] = {}
for k in range(1, self.K):
L = k - spread + 1
if L < 1:
L = 1 # bei Large-Tick Assets ist j≈1; clamp in sichtbaren Bereich
if L > self.D:
L = self.D
qty = int(limit_qtys[k-1])
if qty > 0:
desired_levels[L] = desired_levels.get(L, 0) + qty
# Aktueller Level-Bestand des Agenten
current_levels: Dict[int, int] = {L: len(self.agent_orders[L]) for L in self.agent_orders}
# Re-Allokation (nur Nötiges stornieren; Storno-Reihenfolge "höchste Queue" erfolgt unten)
diff = compute_reallocation(current_levels, desired_levels)
# 1) Storniere nötige Lots – immer zuletzt eingequeue-te (höchste Queue-Position zuerst)
for L, n_cancel in diff.cancel_levels.items():
for _ in range(n_cancel):
if self.agent_orders[L]:
self.agent_orders[L].pop() # jüngstes zuerst
# Volumina auf Ask-Seite reduzieren (Agentenanteil)
# (wir zählen Agentenvolumen implizit über Anzahl AgentLots; Ask-NON bleibt unberührt)
# 2) Market-Sell sofort ausführen (Cashflow direkt)
if mkt_qty > 0:
cash_mkt, sold_mkt = self._execute_market_sell(mkt_qty)
cash_before += cash_mkt
sold_before += sold_mkt
self.M_remaining -= sold_mkt
# 3) Fehlende Limit-Lots hinzufügen (am Ende der Queue; ahead_nonagent = aktuelles non-agent Vol)
for L, n_add in diff.add_levels.items():
for _ in range(n_add):
ahead = int(self.ask_non[L-1]) # non-agent vor uns am Level
self.agent_orders[L].append(AgentLot(level=L, ahead_nonagent=ahead))
# 4) Simuliere externes Marktgeschehen im Intervall (t, t+Δt] (inkl. Fills unserer Limits)
self._simulate_interval(external_only=False)
# 5) Ende prüfen: letzter Schritt n=N-1? Dann erzwungene Liquidation per Market
steps_passed = int((self.t + C.DT) / C.DT) # wie viele Δt seit 0 vergangen
if steps_passed >= C.N_STEPS:
# Forced Market Sell des Restbestands bei T
if self.M_remaining > 0:
cash_forced, sold_forced = self._execute_market_sell(self.M_remaining)
forced = True
cash_after = cash_before + cash_forced
sold_after = sold_before + sold_forced
self.M_remaining = 0
else:
cash_after = cash_before
sold_after = sold_before
done = True
else:
cash_after = cash_before
sold_after = sold_before
# Reward gemäß Eq. (3): r = rbar - γ_n * pb(0) / M0
gamma_n = sold_after # im gesamten Schritt verkaufte Lots durch uns (Market + Limit)
rbar = cash_after # unser Cashflow (pro Tickpreis)
norm_penalty = (gamma_n * self.pb0) / float(self.M0)
reward = rbar - norm_penalty
# Nächster State
state = self._build_state()
# Schritt vorwärts
self.t += C.DT
info = StepInfo(reward_cashflow=rbar, sold_lots=gamma_n, forced_liq=forced, pb=self.pb, pa=self.pa)
return state, float(reward), done, info
# ====================== Externe Prozesse & Matching ======================
def _simulate_interval(self, external_only: bool):
"""
Simuliere in (t, t+Δt]:
- Noise-Trader (Market/Limit/Cancel),
- Tactical-Trader (falls aktiviert),
- Strategischer Trader (falls aktiviert, deterministische Zeitpunkte),
führe Matching (Preis-Zeit-Priorität) durch und aktualisiere Fills unserer Agenten-Limits.
"""
self.delta_market_flow = 0
self.delta_limit_flow = 0
# --- Skalierungsfaktoren pro Markt ---
noise_scale = 1.0
tactical_active = False
strategic_active = False
if self.market == "noise":
noise_scale = 1.0
elif self.market == "tactical":
noise_scale = C.NOISE_SCALE_TACTICAL
tactical_active = True
elif self.market == "strategic":
noise_scale = C.NOISE_SCALE_TACTICAL * C.TACTICAL_EXTRA_SCALE_WITH_STRATEGIC
tactical_active = True
strategic_active = True
# --- Taktische Imbalance I (Sec. 5.2) ---
def weighted_volumes():
w = np.exp(-C.C_DAMP * np.arange(self.D))
Vb = float(np.dot(self.bid_non, w))
# Agentenvolumen auf Ask-Seite zählt zur ask-Seite – Anzahl AgentLots pro Level
agent_ask_counts = np.array([len(self.agent_orders[L]) for L in range(1, self.D+1)], dtype=np.float64)
AskTotal = self.ask_non.astype(np.float64) + agent_ask_counts
Va = float(np.dot(AskTotal, w))
return Vb, Va
I_pos = I_neg = 0.0
if tactical_active:
Vb, Va = weighted_volumes()
if Vb + Va > 0:
I = (Vb - Va) / (Vb + Va)
else:
I = 0.0
I_pos, I_neg = max(I, 0.0), max(-I, 0.0)
# --- Strategische Trades im Intervall ---
strat_actions = []
if strategic_active:
# Zeitpunkte: -Δt, -Δt+Δt_M, ... bis T
# Wir prüfen, ob in (t, t+Δt] geplante Timeslots liegen.
if not hasattr(self, "_strategic_init"):
self._strategic_init = True
self._strategic_dir = self.rng.choice([-1, +1]) # +1 = Buy, -1 = Sell
self._next_M_time = -C.DT
self._next_L_time = -C.DT
# iteriere und füge Ereignisse hinzu
t0, t1 = self.t, self.t + C.DT
# Market schrittweise
while self._next_M_time <= t1 + 1e-9:
if self._next_M_time > t0 - 1e-9:
strat_actions.append(("market", self._strategic_dir, C.NU_M))
self._next_M_time += C.DT_M
if self._next_M_time > C.T + 1e-9:
break
# Limit schrittweise
while self._next_L_time <= t1 + 1e-9:
if self._next_L_time > t0 - 1e-9:
strat_actions.append(("limit", self._strategic_dir, C.NU_L))
self._next_L_time += C.DT_L
if self._next_L_time > C.T + 1e-9:
break
# --- Noise & Tactical Poisson-Ereignisse (Arrivals pro Typ) ---
def poisson(lmbda: float) -> int:
return np.random.poisson(max(0.0, lmbda * C.DT))
# Market Orders (Noise)
n_mkt = poisson(noise_scale * C.LAMBDA_M)
for _ in range(n_mkt):
size = shifted_half_normal_int(C.NOISE_SCALE)
# symmetrisch Buy/Sell
if self.rng.rand() < 0.5:
self._external_market_buy(size)
else:
self._external_market_sell(size)
# Market Orders (Tactical)
if tactical_active:
nb = poisson(C.D_M * I_pos)
ns = poisson(C.D_M * I_neg)
for _ in range(nb):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_market_buy(size)
for _ in range(ns):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_market_sell(size)
# Limit Orders (Noise + Tactical) über k=1..D
# Buys: k Ticks unter Best-Ask | Sells: k Ticks über Best-Bid
maxk = min(self.D, max(C.LAMBDA_L.keys()))
for k in range(1, maxk + 1):
lamLk = C.LAMBDA_L.get(k, 0.0)
# Noise arrivals:
nb = poisson(noise_scale * lamLk) # buy limits
ns = poisson(noise_scale * lamLk) # sell limits
# Tactical arrivals:
if tactical_active:
nb += poisson(C.D_L * I_pos) # buy
ns += poisson(C.D_L * I_neg) # sell
# Größen und Einreihen
for _ in range(nb):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_limit_buy(k, size)
self.delta_limit_flow += size # Buy +
for _ in range(ns):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_limit_sell(k, size)
self.delta_limit_flow -= size # Sell -
# Cancellations (Noise + Tactical), nur sichtbare Levels k ∈ {j,..,D}, j = Spread
spread = self.pa - self.pb
maxc = min(self.D, max(C.LAMBDA_C_x10.keys()))
for k in range(spread, maxc + 1):
lamCk = C.LAMBDA_C_x10.get(k, 0.0) / 10.0 # zurückskalieren
# buy cancellations (unter Best-Ask, ab k=j): Intensität λ_C,k · v_{b, k-j+1}
Lb = k - spread + 1
if 1 <= Lb <= self.D:
vb = self.bid_non[Lb-1]
nb = poisson(noise_scale * lamCk * float(vb))
if tactical_active:
nb += poisson(C.D_C * I_neg * float(vb)) # I_- (vgl. Sec. 5.2)
for _ in range(nb):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_cancel_buy_level(Lb, size)
# sell cancellations (über Best-Bid)
La = k - spread + 1
if 1 <= La <= self.D:
va = self.ask_non[La-1]
ns = poisson(noise_scale * lamCk * float(va))
if tactical_active:
ns += poisson(C.D_C * I_pos * float(va)) # I_+ (vgl. Sec. 5.2)
for _ in range(ns):
size = shifted_half_normal_int(C.NOISE_SCALE)
self._external_cancel_sell_level(La, size)
# Strategische Trader ausführen
for kind, direction, size in strat_actions:
if kind == "market":
if direction > 0:
self._external_market_buy(size)
else:
self._external_market_sell(size)
else: # limit
# einfache Heuristik: 1-Tick zum Top jeweils
if direction > 0:
self._external_limit_buy(1, size)
self.delta_limit_flow += size
else:
self._external_limit_sell(1, size)
self.delta_limit_flow -= size
# Agenten-Limitfills wurden während Market-Buy-Verarbeitung gehandhabt.
# Ende Intervall: keine weitere Aktion.
# === Preis-/Buch-Shift-Hilfen ===
def _shift_ask_up_if_empty(self):
while self.ask_non[0] + sum(1 for _ in self.agent_orders[1]) == 0 and self.pa > self.pb + 0:
# Level 1 ist leer: pa steigt um 1, alle Ask-Level rücken näher
self.pa += 1
# Verschieben Non-Agent Ask nach unten (Index-1)
self.ask_non[:-1] = self.ask_non[1:]
self.ask_non[-1] = 0
# Agentenorders an Leveln verschieben (Level-1)
new_orders = {L: [] for L in range(1, self.D + 1)}
for L in range(1, self.D + 1):
newL = max(1, L - 1)
new_orders[newL].extend(self.agent_orders[L])
self.agent_orders = new_orders
def _shift_bid_down_if_empty(self):
while self.bid_non[0] == 0 and self.pa > self.pb + 0:
# Best-Bid erschöpft -> pb sinkt um 1 (Preis tiefer), Bid-Level rücken hoch (tiefer ins Buch)
self.pb -= 1
self.bid_non[:-1] = self.bid_non[1:]
self.bid_non[-1] = 0
# === Externe Ereignisse / Matching (Non-Agent) ===
def _external_market_buy(self, size: int):
"""Buy Market Orders (extern) treffen Ask-Seite -> füllen zuerst Non-Agent, dann Agent (FIFO)."""
remain = size
L = 1
while remain > 0 and L <= self.D:
# 1) Non-Agent Ask füllen
take = min(remain, int(self.ask_non[L-1]))
self.ask_non[L-1] -= take
remain -= take
self.delta_market_flow += take # Buy +
# 2) Agenten an Level L füllen, falls 'remain' noch >0
if remain > 0 and self.agent_orders[L]:
# Non-Agent vor jedem Lot berücksichtigen:
# Wenn Non-Agent am Level aufgebraucht ist (take==...), können Agenten drankommen.
# Wir füllen FIFO der AgentLots, solange remain > 0.
idx = 0
while remain > 0 and idx < len(self.agent_orders[L]):
lot = self.agent_orders[L][idx]
if lot.filled:
idx += 1
continue
if lot.ahead_nonagent > 0:
# Non-Agent war vor ihm – dieser Schritt hat bereits Non-Agent reduziert;
# reduziere die "ahead_nonagent" um 'take' der Non-Agent-Fills am Level.
# Hier approximieren wir: das zuvor entnommene Non-Agent Volumen 'take'
# reduziert für alle Lots die "ahead_nonagent" gleichmäßig.
lot.ahead_nonagent = max(0, lot.ahead_nonagent - take)
# solange ahead>0, kann er nicht gefüllt werden
if lot.ahead_nonagent > 0:
idx += 1
continue
# Jetzt kann dieser Lot ggf. gefüllt werden:
lot.filled = True
remain -= 1
self.M_remaining = max(0, self.M_remaining - 1)
# Cash: Wir addieren den Preis (Ask L) als Erlös für uns?
# Achtung: externe Market-Buys füllen unsere SELL-Limits -> Erlös = Preis am Level
# Preis am Level L ist pa + (L-1) - (pa - Top). Hier: pa ist Best Ask Price, Level 1 = pa.
# Für Reward verwenden wir den "Preis in Ticks". Cashflow summieren wir außerhalb (step()).
# -> Wir akkumulieren Cashflow unmittelbar: Preis pro Lot = pa + (L-1)
# Wir speichern Cashflow nicht hier (um Doppelsummen zu vermeiden); sammeln in step() via rbar.
idx += 1
# Entferne gefüllte Lots
self.agent_orders[L] = [lot for lot in self.agent_orders[L] if not lot.filled]
if self.ask_non[L-1] == 0 and len(self.agent_orders[L]) == 0:
# wenn ganz leer -> ggf. pa nach oben schieben
pass
# nächstes Level wenn remain > 0
if remain > 0:
L += 1
# Spread/Prices aktualisieren, falls Level 1 leer
self._shift_ask_up_if_empty()
def _external_market_sell(self, size: int):
"""Sell Market Orders (extern) treffen Bid-Seite -> Non-Agent bid wird konsumiert."""
remain = size
L = 1
while remain > 0 and L <= self.D:
take = min(remain, int(self.bid_non[L-1]))
self.bid_non[L-1] -= take
remain -= take
self.delta_market_flow -= take # Sell -
if self.bid_non[L-1] == 0:
pass
if remain > 0:
L += 1
# ggf. pb absenken
self._shift_bid_down_if_empty()
def _external_limit_buy(self, k: int, size: int):
"""Limit-Buy k Ticks unter Best-Ask -> Bid-Seite: Level Lb = k - spread + 1 (sichtbarer Bereich clamp)."""
spread = self.pa - self.pb
Lb = k - spread + 1
Lb = max(1, min(self.D, Lb))
self.bid_non[Lb-1] += size
def _external_limit_sell(self, k: int, size: int):
"""Limit-Sell k Ticks über Best-Bid -> Ask-Seite: Level La = k - spread + 1."""
spread = self.pa - self.pb
La = k - spread + 1
La = max(1, min(self.D, La))
self.ask_non[La-1] += size
def _external_cancel_buy_level(self, Lb: int, size: int):
"""Cancel auf Bid-Seite: entferne Non-Agent vom Ende der Queue (hier aggregiert)."""
self.bid_non[Lb-1] = max(0, self.bid_non[Lb-1] - size)
def _external_cancel_sell_level(self, La: int, size: int):
"""Cancel auf Ask-Seite: entferne Non-Agent vom Ende der Queue (Agentenorders bleiben bestehen)."""
self.ask_non[La-1] = max(0, self.ask_non[La-1] - size)
# === Unsere eigenen Aktionen (Market-Sell, Limit-Sell wurden oben behandelt) ===
def _execute_market_sell(self, qty: int) -> Tuple[float, int]:
"""
Sofortige Market-Sell-Order des Agenten (konsumiert Bid-Seite).
Gibt Cashflow (in Tick-Preisen) und verkaufte Lots zurück.
"""
remain = int(qty)
sold = 0
cash = 0.0
L = 1
while remain > 0 and L <= self.D:
avail = int(self.bid_non[L-1])
take = min(remain, avail)
self.bid_non[L-1] -= take
remain -= take
sold += take
# Preis pro Lot = pb - (L-1) (da Level 1 = Best-Bid, Level 2 = pb-1, ...)
price = self.pb - (L - 1)
cash += take * price
self.delta_market_flow -= take # unsere Sell-MO zählt zum Marktfluss
if self.bid_non[L-1] == 0:
# evtl. Best-Bid tiefer
pass
if remain > 0:
L += 1
self._shift_bid_down_if_empty()
return cash, sold
# ====================== State-Konstruktion & Reward-Preiswerte ======================
def _build_state(self) -> Dict[str, np.ndarray]:
"""
State nach Sec. 3.1; Normalisierung gemäß App. D.
Market-States (öffentlich) + Private-States (nur Agent).
"""
# Preise normiert um Startwerte (App. D)
pa_norm = (self.pa - C.P_A_INIT) / C.PRICE_NORM_DIV
pb_norm = (self.pb - C.P_B_INIT) / C.PRICE_NORM_DIV
# Volumina: erste K-1 Level pro Seite, durch langfristige Form ~v normieren
Kminus1 = self.K - 1
vb = self.bid_non[:Kminus1].astype(np.float32)
va = self.ask_non[:Kminus1].astype(np.float32) + \
np.array([len(self.agent_orders[L]) for L in range(1, Kminus1+1)], dtype=np.float32)
# Hier verwenden wir eine laufende Schätzung der Mittel-Form: zur Stabilisierung
# nutzten wir beim Reset eine stationäre Annäherung (vgl. _reach_stationarity()).
# Um Normierung robust zu halten, setzen wir ~v = max(1, aktuelles Mittel aus Reset).
vtilde_b = np.maximum(1.0, vb.mean() if vb.size > 0 else 1.0)
vtilde_a = np.maximum(1.0, va.mean() if va.size > 0 else 1.0)
vb_norm = vb / vtilde_b
va_norm = va / vtilde_a
# Δm, Δl (in [-1,1] nach App. D Grenzen): hier grob durch Gesamtvolumina normieren
# (Für strikte Reproduktion könnte man Gesamtvolumina im Intervall akkumulieren.)
total_m = max(1.0, abs(float(self.delta_market_flow)))
total_l = max(1.0, abs(float(self.delta_limit_flow)))
delta_m_norm = np.clip(self.delta_market_flow / total_m, -1.0, 1.0)
delta_l_norm = np.clip(self.delta_limit_flow / total_l, -1.0, 1.0)
# Mid-Price-Drift Δp = p(t) - p(t-Δt), normiert relativ zu p(t-Δt) (App. D)
mid = 0.5 * (self.pb + self.pa)
# Für t=-Δt fehlt p(t-Δt); hier setzen wir Δp=0 am Anfang
if not hasattr(self, "_prev_mid"):
dp_norm = 0.0
else:
prev = float(self._prev_mid)
dp_norm = (mid - prev) / max(1.0, abs(prev))
self._prev_mid = mid
# Private: t/T, M(t)/M, m(t)/M, Levels/Queues, γ(t)
t_norm = np.clip((max(0.0, self.t) / C.T), 0.0, 1.0)
M_norm = self.M_remaining / float(self.M0)
m_active = sum(len(v) for v in self.agent_orders.values())
m_norm = (m_active / max(1, self.M_remaining)) if self.M_remaining > 0 else 0.0
# Levels & Queues (feste Länge M0, Clip auf [-K,K] und [-50,50])
levels_list = []
queues_list = []
# sortiere Orders nach (Level aufsteigend, dann Einfüge-Reihenfolge implizit)
for L in range(1, self.D + 1):
for lot in self.agent_orders[L]:
levels_list.append(L)
queues_list.append(lot.ahead_nonagent) # Approx: Queue-Position ~ Non-Agent ahead
u = self.M_remaining # Lots außerhalb Buch
# Fülle auf Länge M0 mit Regeln aus App. D
# levels: aktive L, dann K, dann -K
# queues: aktive q, dann +50, dann -50
Kclip = C.LEVEL_CLIP_K
Qclip = C.MAX_QUEUE_CLIP
# aktive
L_active = levels_list[:min(len(levels_list), self.M0)]
q_active = queues_list[:min(len(queues_list), self.M0)]
# ergänze außerhalb (u) mit K / 50
L_pad_pos = [Kclip for _ in range(min(u, max(0, self.M0 - len(L_active))))]
q_pad_pos = [Qclip for _ in range(len(L_pad_pos))]
# rest mit -K / -50
rest_len = self.M0 - len(L_active) - len(L_pad_pos)
L_pad_neg = [-Kclip for _ in range(max(0, rest_len))]
q_pad_neg = [-Qclip for _ in range(max(0, rest_len))]
L_emb = np.array(L_active + L_pad_pos + L_pad_neg, dtype=np.float32) / float(Kclip)
q_emb = np.array(q_active + q_pad_pos + q_pad_neg, dtype=np.float32) / float(Qclip)
# γ-Feature: Anteil des Inventars pro Preisniveau (K-1), letzter Slot = Rest/Höher/Nicht im Buch
gamma = np.zeros(self.K, dtype=np.float32)
total_inv = max(1, self.M_remaining + m_active)
for k in range(1, self.K):
# Anteil an Level k (relativ zu Ask-Sichtbarkeit) – ordne Levels 1..K-1 zu
L = k
gamma[k-1] = min(1.0, len(self.agent_orders.get(L, [])) / float(total_inv))
gamma[-1] = 1.0 - float(np.sum(gamma[:-1]))
gamma = np.clip(gamma, 0.0, 1.0)
# Packe State als Dict mit numpy arrays
state = {
"pa": np.array([pa_norm], dtype=np.float32),
"pb": np.array([pb_norm], dtype=np.float32),
"vb": vb_norm.astype(np.float32),
"va": va_norm.astype(np.float32),
"delta_m": np.array([delta_m_norm], dtype=np.float32),
"delta_l": np.array([delta_l_norm], dtype=np.float32),
"dp": np.array([dp_norm], dtype=np.float32),
"t": np.array([t_norm], dtype=np.float32),
"M": np.array([M_norm], dtype=np.float32),
"m": np.array([m_norm], dtype=np.float32),
"levels": L_emb.astype(np.float32),
"queues": q_emb.astype(np.float32),
"gamma": gamma.astype(np.float32),
}
return state