-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepo-context.xml
More file actions
5700 lines (4604 loc) · 202 KB
/
repo-context.xml
File metadata and controls
5700 lines (4604 loc) · 202 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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
main.py
src/__init__.py
src/app/__init__.py
src/app/application/__init__.py
src/app/application/account/__init__.py
src/app/application/account/use_cases/__init__.py
src/app/application/account/use_cases/get_balance.py
src/app/application/market/__init__.py
src/app/application/market/mappers/__init__.py
src/app/application/market/mappers/mexc.py
src/app/application/market/qrl/__init__.py
src/app/application/market/qrl/get_qrl_depth.py
src/app/application/market/qrl/get_qrl_kline.py
src/app/application/market/qrl/get_qrl_price.py
src/app/application/market/use_cases/__init__.py
src/app/application/market/use_cases/get_depth.py
src/app/application/market/use_cases/get_kline.py
src/app/application/market/use_cases/get_market_trades.py
src/app/application/market/use_cases/get_stats24h.py
src/app/application/market/use_cases/get_ticker.py
src/app/application/ports/__init__.py
src/app/application/ports/exchange_gateway.py
src/app/application/ports/exchange_service.py
src/app/application/system/__init__.py
src/app/application/system/use_cases/__init__.py
src/app/application/system/use_cases/allocation.py
src/app/application/system/use_cases/get_server_time.py
src/app/application/system/use_cases/ping.py
src/app/application/trading/__init__.py
src/app/application/trading/dto/__init__.py
src/app/application/trading/dtos.py
src/app/application/trading/mappers/__init__.py
src/app/application/trading/mappers/mexc.py
src/app/application/trading/qrl/__init__.py
src/app/application/trading/qrl/cancel_qrl_order.py
src/app/application/trading/qrl/get_qrl_order.py
src/app/application/trading/qrl/guards/__init__.py
src/app/application/trading/qrl/guards/qrl_balance_guard.py
src/app/application/trading/qrl/guards/qrl_duplicate_guard.py
src/app/application/trading/qrl/guards/qrl_price_guard.py
src/app/application/trading/qrl/guards/qrl_rate_limit_guard.py
src/app/application/trading/qrl/place_qrl_order.py
src/app/application/trading/use_cases/__init__.py
src/app/application/trading/use_cases/cancel_order.py
src/app/application/trading/use_cases/get_kline.py
src/app/application/trading/use_cases/get_order.py
src/app/application/trading/use_cases/get_price.py
src/app/application/trading/use_cases/list_orders.py
src/app/application/trading/use_cases/list_trades.py
src/app/application/trading/use_cases/place_order.py
src/app/domain/__init__.py
src/app/domain/aggregates/__init__.py
src/app/domain/aggregates/account_state.py
src/app/domain/aggregates/market_snapshot.py
src/app/domain/aggregates/trading_session.py
src/app/domain/entities/__init__.py
src/app/domain/entities/account.py
src/app/domain/entities/kline.py
src/app/domain/entities/order_book_level.py
src/app/domain/entities/order.py
src/app/domain/entities/trade.py
src/app/domain/entities/trading_pair.py
src/app/domain/events/__init__.py
src/app/domain/events/balance_event.py
src/app/domain/events/market_depth_event.py
src/app/domain/events/order_event.py
src/app/domain/events/trade_event.py
src/app/domain/factories/aggregates.py
src/app/domain/services/__init__.py
src/app/domain/services/balance_comparison_rule.py
src/app/domain/services/depth_calculator.py
src/app/domain/services/qrl_guards.py
src/app/domain/services/slippage_analyzer.py
src/app/domain/services/valuation_service.py
src/app/domain/value_objects/__init__.py
src/app/domain/value_objects/api_key.py
src/app/domain/value_objects/api_secret.py
src/app/domain/value_objects/balance_comparison_result.py
src/app/domain/value_objects/balance.py
src/app/domain/value_objects/client_order_id.py
src/app/domain/value_objects/kline_interval.py
src/app/domain/value_objects/kline.py
src/app/domain/value_objects/normalized_balances.py
src/app/domain/value_objects/order_book.py
src/app/domain/value_objects/order_command.py
src/app/domain/value_objects/order_id.py
src/app/domain/value_objects/order_side.py
src/app/domain/value_objects/order_status.py
src/app/domain/value_objects/order_type.py
src/app/domain/value_objects/price.py
src/app/domain/value_objects/qrl_price.py
src/app/domain/value_objects/qrl_quantity.py
src/app/domain/value_objects/qrl_usdt_pair.py
src/app/domain/value_objects/quantity.py
src/app/domain/value_objects/side.py
src/app/domain/value_objects/slippage.py
src/app/domain/value_objects/sub_account_id.py
src/app/domain/value_objects/symbol.py
src/app/domain/value_objects/ticker.py
src/app/domain/value_objects/time_in_force.py
src/app/domain/value_objects/timestamp.py
src/app/domain/value_objects/trade_id.py
src/app/infrastructure/__init__.py
src/app/infrastructure/config.py
src/app/infrastructure/exchange/__init__.py
src/app/infrastructure/exchange/mexc_api_client.py
src/app/infrastructure/exchange/mexc/__init__.py
src/app/infrastructure/exchange/mexc/adapters/__init__.py
src/app/infrastructure/exchange/mexc/adapters/balance_mapper.py
src/app/infrastructure/exchange/mexc/adapters/depth_mapper.py
src/app/infrastructure/exchange/mexc/adapters/market_event_adapter.py
src/app/infrastructure/exchange/mexc/adapters/order_mapper.py
src/app/infrastructure/exchange/mexc/adapters/trade_mapper.py
src/app/infrastructure/exchange/mexc/factories.py
src/app/infrastructure/exchange/mexc/generated/__init__.py
src/app/infrastructure/exchange/mexc/generated/PrivateAccountV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PrivateDealsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PrivateOrdersV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicAggreBookTickerV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicAggreDealsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicAggreDepthsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicBookTickerBatchV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicBookTickerV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicDealsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicIncreaseDepthsBatchV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicIncreaseDepthsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicLimitDepthsV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicMiniTickersV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicMiniTickerV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PublicSpotKlineV3Api_pb2.py
src/app/infrastructure/exchange/mexc/generated/PushDataV3ApiWrapper_pb2.py
src/app/infrastructure/exchange/mexc/mappers.py
src/app/infrastructure/exchange/mexc/proto/__init__.py
src/app/infrastructure/exchange/mexc/qrl/__init__.py
src/app/infrastructure/exchange/mexc/qrl/qrl_rest_client.py
src/app/infrastructure/exchange/mexc/qrl/qrl_settings.py
src/app/infrastructure/exchange/mexc/rest_client.py
src/app/infrastructure/exchange/mexc/service.py
src/app/infrastructure/exchange/mexc/settings.py
src/app/infrastructure/exchange/mexc/ws_client.py
src/app/infrastructure/exchange/mexc/ws/__init__.py
src/app/infrastructure/exchange/mexc/ws/mexc_ws_client.py
src/app/infrastructure/external/mexc/__init__.py
src/app/interfaces/__init__.py
src/app/interfaces/http/__init__.py
src/app/interfaces/http/api/__init__.py
src/app/interfaces/http/api/account_routes.py
src/app/interfaces/http/api/market_routes.py
src/app/interfaces/http/api/qrl_routes.py
src/app/interfaces/http/api/system_routes.py
src/app/interfaces/http/api/tasks_routes.py
src/app/interfaces/http/api/trading_api.py
src/app/interfaces/http/api/trading_routes.py
src/app/interfaces/http/api/ws_routes.py
src/app/interfaces/http/dependencies.py
src/app/interfaces/http/pages/__init__.py
src/app/interfaces/http/pages/dashboard_routes.py
src/app/interfaces/http/pages/static/js/application/dashboard.js
src/app/interfaces/http/pages/static/js/core/chart.js
src/app/interfaces/http/pages/static/js/core/dom.js
src/app/interfaces/http/pages/static/js/core/http.js
src/app/interfaces/http/pages/static/js/domain/depth.js
src/app/interfaces/http/pages/static/js/domain/order.js
src/app/interfaces/http/pages/static/js/domain/price.js
src/app/interfaces/http/pages/static/js/domain/trade.js
src/app/interfaces/http/pages/static/js/pages/dashboard-config.js
src/app/interfaces/http/pages/static/js/pages/dashboard-renderers.js
src/app/interfaces/http/pages/static/js/pages/dashboard.js
src/app/interfaces/http/pages/templates/dashboard/index.html
src/app/interfaces/http/schemas.py
src/app/interfaces/tasks/__init__.py
src/app/interfaces/tasks/entrypoints.py
src/app/interfaces/tasks/market_tasks.py
src/app/interfaces/tasks/system_tasks.py
src/app/interfaces/tasks/trading_tasks.py
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="src/__init__.py">
"""Root package for application code."""
</file>
<file path="src/app/__init__.py">
"""Application package root for MEXC QRL/USDT bot."""
</file>
<file path="src/app/application/__init__.py">
"""Application layer use cases (no infrastructure)."""
</file>
<file path="src/app/application/account/__init__.py">
# Account bounded context.
</file>
<file path="src/app/application/account/use_cases/__init__.py">
# Account use cases.
</file>
<file path="src/app/application/market/__init__.py">
"""Market use cases."""
</file>
<file path="src/app/application/market/mappers/__init__.py">
"""
Mappers for translating market data payloads into domain market objects.
"""
</file>
<file path="src/app/application/market/mappers/mexc.py">
from decimal import Decimal
from datetime import datetime, timezone
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.ticker import Ticker
def map_ws_ticker_event_to_domain(event: dict) -> Ticker:
"""Map MEXC WS ticker event to Ticker VO."""
return Ticker(
symbol=Symbol(str(event.get("symbol", "QRLUSDT"))),
last_price=Decimal(str(event.get("last", "0"))),
bid_price=Decimal(str(event.get("bidPrice", "0"))),
ask_price=Decimal(str(event.get("askPrice", "0"))),
ts=datetime.fromtimestamp(
int(event.get("ts", 0)) / 1000, tz=timezone.utc
),
)
</file>
<file path="src/app/application/market/qrl/__init__.py">
# QRL market application use cases package
</file>
<file path="src/app/application/market/use_cases/__init__.py">
# Market use cases.
</file>
<file path="src/app/application/ports/__init__.py">
from .exchange_gateway import ExchangeGateway
__all__ = ["ExchangeGateway"]
</file>
<file path="src/app/application/ports/exchange_gateway.py">
from typing import AsyncIterator, Protocol
from app.domain.events.market_depth_event import MarketDepthEvent
from app.domain.events.trade_event import TradeEvent
from app.domain.events.order_event import OrderEvent
from app.domain.events.balance_event import BalanceEvent
from app.domain.value_objects.symbol import Symbol
class ExchangeGateway(Protocol):
"""Application port for streaming market/account data."""
async def subscribe_market_depth(
self, symbol: Symbol
) -> AsyncIterator[MarketDepthEvent]:
...
async def subscribe_trades(self, symbol: Symbol) -> AsyncIterator[TradeEvent]:
...
async def subscribe_orders(self) -> AsyncIterator[OrderEvent]:
...
async def subscribe_balances(self) -> AsyncIterator[BalanceEvent]:
...
</file>
<file path="src/app/application/system/__init__.py">
"""System use cases."""
</file>
<file path="src/app/application/system/use_cases/__init__.py">
# System use cases.
</file>
<file path="src/app/application/system/use_cases/ping.py">
"""
System use case: ping.
"""
class PingUseCase:
def execute(self) -> None:
# TODO: implement system ping orchestration
return None
</file>
<file path="src/app/application/trading/__init__.py">
"""Trading use cases."""
</file>
<file path="src/app/application/trading/dto/__init__.py">
# DTOs for trading application layer.
</file>
<file path="src/app/application/trading/mappers/__init__.py">
"""
Mappers for translating external MEXC payloads into domain trading objects.
"""
</file>
<file path="src/app/application/trading/mappers/mexc.py">
from decimal import Decimal
from datetime import datetime, timezone
from src.app.domain.entities.order import Order
from src.app.domain.entities.trade import Trade
from src.app.domain.value_objects.order_id import OrderId
from src.app.domain.value_objects.order_status import OrderStatus
from src.app.domain.value_objects.quantity import Quantity
from src.app.domain.value_objects.side import Side
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.timestamp import Timestamp
from src.app.domain.value_objects.trade_id import TradeId
def map_rest_order_dto_to_domain(dto: dict) -> Order:
"""Map MEXC REST order DTO (primitives) to Order entity."""
return Order(
order_id=OrderId(str(dto.get("orderId", ""))),
symbol=Symbol(str(dto.get("symbol", "QRLUSDT"))),
side=Side(str(dto.get("side", "")).upper()),
status=OrderStatus(str(dto.get("status", "")).upper()),
price=Decimal(str(dto.get("price", "0"))),
quantity=Quantity(Decimal(str(dto.get("origQty", "0")))),
created_at=Timestamp(
datetime.fromtimestamp(int(dto.get("time", 0)) / 1000, tz=timezone.utc)
),
updated_at=Timestamp(
datetime.fromtimestamp(
int(dto.get("updateTime", dto.get("time", 0))) / 1000, tz=timezone.utc
)
)
if dto.get("updateTime")
else None,
)
def map_rest_trade_dto_to_domain(dto: dict) -> Trade:
"""Map MEXC REST trade DTO to Trade entity."""
return Trade(
trade_id=TradeId(str(dto.get("id", ""))),
order_id=OrderId(str(dto.get("orderId", ""))),
symbol=Symbol(str(dto.get("symbol", "QRLUSDT"))),
side=Side(str(dto.get("side", "")).upper()),
price=Decimal(str(dto.get("price", "0"))),
quantity=Decimal(str(dto.get("qty", "0"))),
fee=Decimal(str(dto["commission"])) if dto.get("commission") is not None else None,
fee_asset=str(dto["commissionAsset"]) if dto.get("commissionAsset") else None,
timestamp=Timestamp(
datetime.fromtimestamp(int(dto.get("time", 0)) / 1000, tz=timezone.utc)
),
)
</file>
<file path="src/app/application/trading/qrl/__init__.py">
# QRL trading use cases package
</file>
<file path="src/app/application/trading/qrl/guards/__init__.py">
# QRL guard utilities
</file>
<file path="src/app/application/trading/use_cases/__init__.py">
# Trading use cases.
</file>
<file path="src/app/domain/__init__.py">
"""Domain layer root."""
</file>
<file path="src/app/domain/aggregates/__init__.py">
"""Domain aggregates for the QRL/USDT trading context."""
from src.app.domain.aggregates.account_state import AccountState
from src.app.domain.aggregates.market_snapshot import MarketSnapshot
from src.app.domain.aggregates.trading_session import TradingSession
__all__ = ["AccountState", "MarketSnapshot", "TradingSession"]
</file>
<file path="src/app/domain/aggregates/account_state.py">
from dataclasses import dataclass, field
from src.app.domain.entities.account import Account
from src.app.domain.entities.order import Order
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass
class AccountState:
"""Aggregate for account balances and outstanding orders."""
symbol: Symbol
account: Account
open_orders: list[Order] = field(default_factory=list)
updated_at: Timestamp | None = None
</file>
<file path="src/app/domain/aggregates/market_snapshot.py">
from dataclasses import dataclass, field
from src.app.domain.entities.order_book_level import OrderBookLevel
from src.app.domain.entities.trade import Trade
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.ticker import Ticker
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass
class MarketSnapshot:
"""Combined market view for depth, trades, and ticker."""
symbol: Symbol
bids: list[OrderBookLevel] = field(default_factory=list)
asks: list[OrderBookLevel] = field(default_factory=list)
trades: list[Trade] = field(default_factory=list)
ticker: Ticker | None = None
updated_at: Timestamp | None = None
</file>
<file path="src/app/domain/aggregates/trading_session.py">
from dataclasses import dataclass, field
from src.app.domain.entities.order import Order
from src.app.domain.entities.trade import Trade
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass
class TradingSession:
"""Session-level aggregate for managing open and historical activity."""
symbol: Symbol
open_orders: list[Order] = field(default_factory=list)
trades: list[Trade] = field(default_factory=list)
started_at: Timestamp | None = None
last_activity_at: Timestamp | None = None
</file>
<file path="src/app/domain/entities/__init__.py">
"""Domain entities for QRL/USDT spot trading."""
from src.app.domain.entities.account import Account
from src.app.domain.entities.kline import Kline
from src.app.domain.entities.order import Order
from src.app.domain.entities.order_book_level import OrderBookLevel
from src.app.domain.entities.trade import Trade
__all__ = ["Account", "Kline", "Order", "OrderBookLevel", "Trade"]
</file>
<file path="src/app/domain/entities/account.py">
from dataclasses import dataclass
from src.app.domain.value_objects.balance import Balance
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass
class Account:
"""Spot account snapshot."""
can_trade: bool
update_time: Timestamp
balances: list[Balance]
</file>
<file path="src/app/domain/entities/kline.py">
from dataclasses import dataclass
from decimal import Decimal
from src.app.domain.value_objects.kline_interval import KlineInterval
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass
class Kline:
"""Kline entity for QRL/USDT spot."""
symbol: Symbol
interval: KlineInterval
open: Decimal
high: Decimal
low: Decimal
close: Decimal
volume: Decimal
open_time: Timestamp
close_time: Timestamp | None = None
</file>
<file path="src/app/domain/entities/order_book_level.py">
from dataclasses import dataclass
from decimal import Decimal
from src.app.domain.value_objects.order_side import OrderSide
@dataclass
class OrderBookLevel:
"""Single depth level for the QRL/USDT order book."""
price: Decimal
quantity: Decimal
side: OrderSide
</file>
<file path="src/app/domain/entities/trading_pair.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class TradingPair:
"""Represents a trading pair such as QRL/USDT."""
base_currency: str
quote_currency: str
@property
def symbol(self) -> str:
return f"{self.base_currency}{self.quote_currency}".upper()
</file>
<file path="src/app/domain/events/balance_event.py">
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class BalanceEvent:
"""Account balance snapshot/update."""
asset: str
free: Decimal
locked: Decimal
timestamp: int
</file>
<file path="src/app/domain/events/market_depth_event.py">
from dataclasses import dataclass
from typing import List, Tuple
from app.domain.value_objects.price import Price
from app.domain.value_objects.quantity import Quantity
from app.domain.value_objects.symbol import Symbol
@dataclass(frozen=True)
class MarketDepthEvent:
"""
Order book depth snapshot/update at a point in time.
Notes:
- Bids/asks are sorted by price on the exchange side.
- Versions allow consumers to detect gaps and request replay.
"""
symbol: Symbol
bids: List[Tuple[Price, Quantity]]
asks: List[Tuple[Price, Quantity]]
event_type: str | None
from_version: str | None
to_version: str | None
</file>
<file path="src/app/domain/events/order_event.py">
from dataclasses import dataclass
from app.domain.value_objects.order_id import OrderId
from app.domain.value_objects.order_status import OrderStatus
from app.domain.value_objects.price import Price
from app.domain.value_objects.quantity import Quantity
from app.domain.value_objects.symbol import Symbol
@dataclass(frozen=True)
class OrderEvent:
"""Private order update event."""
order_id: OrderId
symbol: Symbol
price: Price
quantity: Quantity
status: OrderStatus
timestamp: int
</file>
<file path="src/app/domain/events/trade_event.py">
from dataclasses import dataclass
from app.domain.value_objects.price import Price
from app.domain.value_objects.quantity import Quantity
from app.domain.value_objects.symbol import Symbol
from app.domain.value_objects.trade_id import TradeId
@dataclass(frozen=True)
class TradeEvent:
"""Public trade tick."""
trade_id: TradeId
symbol: Symbol
price: Price
quantity: Quantity
is_buyer_maker: bool
timestamp: int
</file>
<file path="src/app/domain/value_objects/__init__.py">
"""Domain Value Objects for QRL/USDT scope."""
from src.app.domain.value_objects.order_id import OrderId
from src.app.domain.value_objects.kline_interval import KlineInterval
from src.app.domain.value_objects.order_side import OrderSide
from src.app.domain.value_objects.order_status import OrderStatus
from src.app.domain.value_objects.price import Price
from src.app.domain.value_objects.quantity import Quantity
from src.app.domain.value_objects.side import Side
from src.app.domain.value_objects.symbol import Symbol
from src.app.domain.value_objects.ticker import Ticker
from src.app.domain.value_objects.timestamp import Timestamp
from src.app.domain.value_objects.trade_id import TradeId
from src.app.domain.value_objects.kline import KLine
from src.app.domain.value_objects.sub_account_id import SubAccountId
__all__ = [
"OrderId",
"OrderStatus",
"OrderSide",
"KlineInterval",
"Price",
"KLine",
"Quantity",
"Side",
"Symbol",
"Ticker",
"Timestamp",
"TradeId",
"SubAccountId",
]
</file>
<file path="src/app/domain/value_objects/api_key.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class ApiKey:
"""API key used for authenticated MEXC requests."""
value: str
def __post_init__(self):
if not self.value:
raise ValueError("API key cannot be empty")
</file>
<file path="src/app/domain/value_objects/api_secret.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class ApiSecret:
"""API secret used to sign requests."""
value: str
def __post_init__(self):
if not self.value:
raise ValueError("API secret cannot be empty")
</file>
<file path="src/app/domain/value_objects/balance.py">
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class Balance:
"""Asset balance with free and locked amounts."""
asset: str
free: Decimal
locked: Decimal
def __post_init__(self):
if not self.asset:
raise ValueError("Asset symbol cannot be empty")
if self.free < 0 or self.locked < 0:
raise ValueError("Balance amounts cannot be negative")
</file>
<file path="src/app/domain/value_objects/client_order_id.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class ClientOrderId:
"""Client-supplied idempotency key for orders."""
value: str
def __post_init__(self):
if not self.value:
raise ValueError("Client order id cannot be empty")
if len(self.value) > 32:
raise ValueError("Client order id must be 32 characters or fewer")
</file>
<file path="src/app/domain/value_objects/kline_interval.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class KlineInterval:
"""Supported MEXC spot kline intervals for QRL/USDT."""
value: str
_allowed = {
"1m",
"5m",
"15m",
"30m",
"1h",
"4h",
"1d",
}
def __post_init__(self):
if self.value not in self._allowed:
raise ValueError(f"KlineInterval must be one of {sorted(self._allowed)}")
</file>
<file path="src/app/domain/value_objects/kline.py">
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass(frozen=True)
class KLine:
"""Single candlestick for a trading pair."""
open: Decimal
high: Decimal
low: Decimal
close: Decimal
volume: Decimal
interval: str
timestamp: Timestamp
def __post_init__(self):
if min(self.open, self.high, self.low, self.close) < 0:
raise ValueError("KLine prices cannot be negative")
if self.volume < 0:
raise ValueError("KLine volume cannot be negative")
if not self.interval:
raise ValueError("KLine interval is required")
@classmethod
def from_raw(
cls,
open_price: Decimal,
high: Decimal,
low: Decimal,
close: Decimal,
volume: Decimal,
interval: str,
timestamp_ms: int,
) -> "KLine":
ts = Timestamp(datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc))
return cls(open=open_price, high=high, low=low, close=close, volume=volume, interval=interval, timestamp=ts)
</file>
<file path="src/app/domain/value_objects/order_id.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class OrderId:
"""Order identifier returned by MEXC."""
value: str
def __post_init__(self):
if not self.value:
raise ValueError("OrderId cannot be empty")
</file>
<file path="src/app/domain/value_objects/order_side.py">
from src.app.domain.value_objects.side import Side
class OrderSide(Side):
"""Alias for Side specific to order semantics."""
</file>
<file path="src/app/domain/value_objects/order_status.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class OrderStatus:
"""Order status with a minimal allowed set."""
value: str
_allowed = {
"NEW",
"PARTIALLY_FILLED",
"FILLED",
"CANCELED",
"REJECTED",
}
def __post_init__(self):
if self.value not in self._allowed:
raise ValueError(f"OrderStatus must be one of {sorted(self._allowed)}")
</file>
<file path="src/app/domain/value_objects/order_type.py">
from dataclasses import dataclass
@dataclass(frozen=True)
class OrderType:
"""Supported MEXC order types."""
value: str
_allowed = {"LIMIT", "MARKET"}
def __post_init__(self):
if self.value not in self._allowed:
raise ValueError(f"OrderType must be one of {sorted(self._allowed)}")
</file>
<file path="src/app/domain/value_objects/price.py">
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from src.app.domain.value_objects.timestamp import Timestamp
@dataclass(frozen=True)
class Price:
"""Quote for a trading pair with bid/ask/last and timestamp."""
bid: Decimal
ask: Decimal
last: Decimal
timestamp: Timestamp
def __post_init__(self):
if self.bid <= 0 or self.ask <= 0 or self.last <= 0:
raise ValueError("Price values must be positive")
@classmethod
def from_single(cls, value: Decimal, ts: datetime | None = None) -> "Price":
"""Construct a Price when only a single quote is available."""
stamp = Timestamp(ts or datetime.now(timezone.utc))
return cls(bid=value, ask=value, last=value, timestamp=stamp)
</file>
<file path="src/app/domain/value_objects/qrl_price.py">
from __future__ import annotations
from decimal import Decimal, ROUND_DOWN, getcontext
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from src.app.domain.value_objects.qrl_quantity import QrlQuantity
getcontext().prec = 28
class QrlPrice:
"""
QRL/USDT 專用價格 Value Object
- 不可變
- 強制 tick size
"""
TICK_SIZE = Decimal("0.0001")
MIN_PRICE = TICK_SIZE
def __init__(self, value: Decimal | str | float):
self._value = self._normalize(Decimal(str(value)))
@staticmethod
def _normalize(value: Decimal) -> Decimal:
if value <= 0:
raise ValueError("QRL price must be > 0")
normalized = (value // QrlPrice.TICK_SIZE) * QrlPrice.TICK_SIZE
if normalized < QrlPrice.MIN_PRICE:
raise ValueError("QRL price below minimum tick size")
return normalized.quantize(QrlPrice.TICK_SIZE, rounding=ROUND_DOWN)
@property
def value(self) -> Decimal:
return self._value
def __str__(self) -> str:
return format(self._value, "f")
def __repr__(self) -> str:
return f"QrlPrice({self._value})"
def multiply(self, quantity: "QrlQuantity") -> Decimal:
return (self._value * quantity.value).quantize(
Decimal("0.00000001"), rounding=ROUND_DOWN
)
</file>
<file path="src/app/domain/value_objects/qrl_quantity.py">
from __future__ import annotations
from decimal import Decimal, ROUND_DOWN, getcontext
getcontext().prec = 28
class QrlQuantity:
"""
QRL 專用數量 Value Object
- 不可變
- 防 fat finger
"""
STEP_SIZE = Decimal("1")
MIN_QTY = Decimal("1")
MAX_QTY = Decimal("1000000")
def __init__(self, value: Decimal | str | int | float):
self._value = self._normalize(Decimal(str(value)))
@staticmethod
def _normalize(value: Decimal) -> Decimal:
if value <= 0:
raise ValueError("QRL quantity must be > 0")
normalized = (value // QrlQuantity.STEP_SIZE) * QrlQuantity.STEP_SIZE