mt5direct 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. mt5direct/__init__.py +18 -0
  2. mt5direct/client.py +196 -0
  3. mt5direct/constants/__init__.py +5 -0
  4. mt5direct/constants/commands.py +16 -0
  5. mt5direct/constants/network.py +12 -0
  6. mt5direct/constants/orders.py +29 -0
  7. mt5direct/constants/retcodes.py +26 -0
  8. mt5direct/constants/timeframes.py +17 -0
  9. mt5direct/exceptions.py +13 -0
  10. mt5direct/models/__init__.py +13 -0
  11. mt5direct/models/account.py +11 -0
  12. mt5direct/models/candle.py +12 -0
  13. mt5direct/models/frame.py +10 -0
  14. mt5direct/models/history.py +20 -0
  15. mt5direct/models/position.py +24 -0
  16. mt5direct/models/symbol.py +12 -0
  17. mt5direct/models/tick.py +16 -0
  18. mt5direct/models/trade.py +29 -0
  19. mt5direct/parsers/__init__.py +10 -0
  20. mt5direct/parsers/account.py +18 -0
  21. mt5direct/parsers/candles.py +21 -0
  22. mt5direct/parsers/history.py +38 -0
  23. mt5direct/parsers/positions.py +35 -0
  24. mt5direct/parsers/resolve.py +89 -0
  25. mt5direct/parsers/symbols.py +32 -0
  26. mt5direct/parsers/ticks.py +44 -0
  27. mt5direct/parsers/trade.py +41 -0
  28. mt5direct/protocol/__init__.py +7 -0
  29. mt5direct/protocol/crypto.py +27 -0
  30. mt5direct/protocol/framing.py +29 -0
  31. mt5direct/protocol/layouts.py +22 -0
  32. mt5direct/protocol/reader.py +44 -0
  33. mt5direct/protocol/serializer.py +50 -0
  34. mt5direct/services/__init__.py +7 -0
  35. mt5direct/services/account.py +22 -0
  36. mt5direct/services/auth.py +78 -0
  37. mt5direct/services/base.py +32 -0
  38. mt5direct/services/market_data.py +91 -0
  39. mt5direct/services/positions.py +69 -0
  40. mt5direct/services/symbols.py +66 -0
  41. mt5direct/services/trading.py +116 -0
  42. mt5direct/transport/__init__.py +2 -0
  43. mt5direct/transport/session.py +86 -0
  44. mt5direct/transport/websocket.py +45 -0
  45. mt5direct-0.1.0.dist-info/METADATA +122 -0
  46. mt5direct-0.1.0.dist-info/RECORD +49 -0
  47. mt5direct-0.1.0.dist-info/WHEEL +5 -0
  48. mt5direct-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. mt5direct-0.1.0.dist-info/top_level.txt +1 -0
mt5direct/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """mt5direct: standalone MetaTrader 5 client over the native WebSocket protocol."""
2
+
3
+ from .client import MT5Client
4
+ from .constants import * # noqa: F401,F403
5
+ from .exceptions import ConnectionFailed, LoginFailed, MT5Error
6
+ from .models import (
7
+ AccountInfo, Candle, Deal, Frame, HistoryOrder, Position, PositionPnL, Symbol, Tick,
8
+ TradeAck, TradeResult,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "MT5Client", "__version__",
15
+ "MT5Error", "ConnectionFailed", "LoginFailed",
16
+ "AccountInfo", "Candle", "Deal", "Frame", "HistoryOrder", "Position", "PositionPnL",
17
+ "Symbol", "Tick", "TradeAck", "TradeResult",
18
+ ]
mt5direct/client.py ADDED
@@ -0,0 +1,196 @@
1
+ """Facade that wires the session and services behind one object."""
2
+
3
+ from typing import Optional
4
+
5
+ from .constants.network import TRADE_HOSTS
6
+ from .models import Frame, Symbol
7
+ from .services import (
8
+ AccountService, AuthService, ClientState, MarketDataService, PositionService,
9
+ SymbolService, TradingService,
10
+ )
11
+ from .transport import Session
12
+
13
+
14
+ class MT5Client:
15
+ """Standalone MT5 client.
16
+
17
+ Domain operations live on ``auth``, ``account``, ``symbols``, ``market``, ``trading``
18
+ and ``positions``; the flat methods below delegate to them for convenience.
19
+ """
20
+
21
+ def __init__(self, host: Optional[str] = None):
22
+ self.session = Session(host or TRADE_HOSTS[0])
23
+ self.state = ClientState()
24
+ self.account = AccountService(self.session, self.state)
25
+ self.symbols = SymbolService(self.session, self.state)
26
+ self.auth = AuthService(self.session, self.state, self.symbols, self.account)
27
+ self.market = MarketDataService(self.session, self.state, self.auth)
28
+ self.trading = TradingService(self.session, self.state)
29
+ self.positions = PositionService(self.session, self.state, self.trading)
30
+
31
+ # -- connection -------------------------------------------------------
32
+
33
+ @property
34
+ def host(self) -> str:
35
+ return self.session.host
36
+
37
+ @host.setter
38
+ def host(self, value: str) -> None:
39
+ self.session.host = value
40
+
41
+ @property
42
+ def server_id(self) -> int:
43
+ return self.session.server_id
44
+
45
+ def connect(self) -> None:
46
+ self.session.connect()
47
+
48
+ def close(self) -> None:
49
+ self.session.close()
50
+
51
+ def recv_any(self, timeout: float = 5) -> Optional[Frame]:
52
+ return self.session.recv_any(timeout=timeout)
53
+
54
+ def __enter__(self):
55
+ self.connect()
56
+ return self
57
+
58
+ def __exit__(self, *exc) -> None:
59
+ self.close()
60
+
61
+ # -- symbol tables ----------------------------------------------------
62
+
63
+ @property
64
+ def symbol_list(self) -> list[Symbol]:
65
+ return self.state.symbols
66
+
67
+ @property
68
+ def symbol_map(self) -> dict[str, Symbol]:
69
+ return self.state.symbol_map
70
+
71
+ @property
72
+ def ta_to_sym(self) -> dict[int, Symbol]:
73
+ return self.state.ta_to_sym
74
+
75
+ # -- auth -------------------------------------------------------------
76
+
77
+ def login(self, login_id: int, password: str):
78
+ return self.auth.login(login_id, password)
79
+
80
+ def ping(self):
81
+ return self.auth.ping()
82
+
83
+ def reconnect(self, login_id=None, password=None):
84
+ return self.auth.reconnect(login_id, password)
85
+
86
+ # -- account ----------------------------------------------------------
87
+
88
+ def get_account_info(self):
89
+ return self.account.get_account_info()
90
+
91
+ def init_trading(self):
92
+ return self.account.init_trading()
93
+
94
+ def get_history(self, from_ts=0, to_ts=0):
95
+ return self.account.get_history(from_ts, to_ts)
96
+
97
+ # -- symbols ----------------------------------------------------------
98
+
99
+ def get_symbol_types(self):
100
+ return self.symbols.get_symbol_types()
101
+
102
+ def get_symbols(self):
103
+ return self.symbols.get_symbols()
104
+
105
+ def resolve_symbols(self, ta_list):
106
+ return self.symbols.resolve_symbols(ta_list)
107
+
108
+ def subscribe(self, ta_values):
109
+ return self.symbols.subscribe(ta_values)
110
+
111
+ def subscribe_by_name(self, *names):
112
+ return self.symbols.subscribe_by_name(*names)
113
+
114
+ def subscribe_all(self):
115
+ return self.symbols.subscribe_all()
116
+
117
+ def parse_trade_sessions(self, resolve_data):
118
+ return self.symbols.parse_trade_sessions(resolve_data)
119
+
120
+ def parse_trade_modes(self, resolve_data):
121
+ return self.symbols.parse_trade_modes(resolve_data)
122
+
123
+ def find_resolve_bid_offset(self, resolve_data, sym_name, expected_price, digits, tolerance=0.02):
124
+ return self.symbols.find_resolve_bid_offset(resolve_data, sym_name, expected_price, digits, tolerance)
125
+
126
+ def extract_resolve_prices(self, resolve_data, bid_offset):
127
+ return self.symbols.extract_resolve_prices(resolve_data, bid_offset)
128
+
129
+ # -- market data ------------------------------------------------------
130
+
131
+ def get_candles(self, symbol, timeframe='H1', count=1000, from_ts=None, to_ts=None):
132
+ return self.market.get_candles(symbol, timeframe, count, from_ts, to_ts)
133
+
134
+ def parse_tick(self, data, offset=0):
135
+ return self.market.parse_tick(data, offset)
136
+
137
+ def on_tick(self, callback):
138
+ return self.market.on_tick(callback)
139
+
140
+ def start_tick_listener(self, symbols=None):
141
+ return self.market.start_tick_listener(symbols)
142
+
143
+ def stop_tick_listener(self):
144
+ return self.market.stop_tick_listener()
145
+
146
+ # -- trading ----------------------------------------------------------
147
+
148
+ def trade(self, *args, **kwargs):
149
+ return self.trading.trade(*args, **kwargs)
150
+
151
+ def wait_trade_result(self, timeout=30):
152
+ return self.trading.wait_trade_result(timeout)
153
+
154
+ def buy(self, symbol, lots, sl=0.0, tp=0.0, comment=""):
155
+ return self.trading.buy(symbol, lots, sl, tp, comment)
156
+
157
+ def sell(self, symbol, lots, sl=0.0, tp=0.0, comment=""):
158
+ return self.trading.sell(symbol, lots, sl, tp, comment)
159
+
160
+ def buy_limit(self, symbol, lots, price, sl=0.0, tp=0.0, comment=""):
161
+ return self.trading.buy_limit(symbol, lots, price, sl, tp, comment)
162
+
163
+ def sell_limit(self, symbol, lots, price, sl=0.0, tp=0.0, comment=""):
164
+ return self.trading.sell_limit(symbol, lots, price, sl, tp, comment)
165
+
166
+ def buy_stop(self, symbol, lots, price, sl=0.0, tp=0.0, comment=""):
167
+ return self.trading.buy_stop(symbol, lots, price, sl, tp, comment)
168
+
169
+ def sell_stop(self, symbol, lots, price, sl=0.0, tp=0.0, comment=""):
170
+ return self.trading.sell_stop(symbol, lots, price, sl, tp, comment)
171
+
172
+ def modify_sl_tp(self, symbol, position_ticket, sl=0.0, tp=0.0):
173
+ return self.trading.modify_sl_tp(symbol, position_ticket, sl, tp)
174
+
175
+ def modify_pending(self, symbol, order_ticket, price, sl=0.0, tp=0.0):
176
+ return self.trading.modify_pending(symbol, order_ticket, price, sl, tp)
177
+
178
+ def cancel_order(self, symbol, order_ticket):
179
+ return self.trading.cancel_order(symbol, order_ticket)
180
+
181
+ def close_position(self, symbol, ticket, lots=None, pos_type='BUY'):
182
+ return self.trading.close_position(symbol, ticket, lots, pos_type)
183
+
184
+ def close_by_order(self, symbol, order_ticket, lots, pos_type='BUY'):
185
+ return self.trading.close_by_order(symbol, order_ticket, lots, pos_type)
186
+
187
+ # -- positions --------------------------------------------------------
188
+
189
+ def get_positions(self):
190
+ return self.positions.get_positions()
191
+
192
+ def close_all(self, symbol=None):
193
+ return self.positions.close_all(symbol)
194
+
195
+ def track_positions(self, duration=60, callback=None):
196
+ return self.positions.track_positions(duration, callback)
@@ -0,0 +1,5 @@
1
+ from .commands import * # noqa: F401,F403
2
+ from .network import INITIAL_KEY, TRADE_HOSTS, WS_PATH, WS_PORT # noqa: F401
3
+ from .orders import * # noqa: F401,F403
4
+ from .retcodes import RETCODE_DONE, RETCODE_DONE_PARTIAL, RETCODES, retcode_name # noqa: F401
5
+ from .timeframes import TF_SECONDS, TIMEFRAMES # noqa: F401
@@ -0,0 +1,16 @@
1
+ """Protocol command identifiers (u16, little-endian)."""
2
+
3
+ CMD_HELLO = 0
4
+ CMD_ACCOUNT = 3
5
+ CMD_INIT_TRADING = 4
6
+ CMD_HISTORY = 5
7
+ CMD_SUBSCRIBE = 7
8
+ CMD_TICK = 8
9
+ CMD_SYMBOL_TYPES = 9
10
+ CMD_CANDLES = 11
11
+ CMD_TRADE = 12
12
+ CMD_RESOLVE = 18
13
+ CMD_TRADE_RESULT = 19
14
+ CMD_LOGIN = 28
15
+ CMD_SYMBOLS = 34
16
+ CMD_PING = 51
@@ -0,0 +1,12 @@
1
+ """Connection endpoints and the bootstrap AES key used before the hello handshake."""
2
+
3
+ INITIAL_KEY = bytes.fromhex('02de02a1a65cc794684fcbea1ecb0fd74ae657e43662c11eee885d2fd64f4964')
4
+
5
+ TRADE_HOSTS = [
6
+ "mt5trial6.exwebterm.com",
7
+ "8.219.172.6", "47.236.224.248", "16.79.3.122",
8
+ "47.130.41.116", "57.182.183.85", "18.61.99.175",
9
+ ]
10
+
11
+ WS_PORT = 443
12
+ WS_PATH = "/terminal"
@@ -0,0 +1,29 @@
1
+ """Order, execution and filling constants used by trade requests."""
2
+
3
+ EXEC_INSTANT_NOPX = 0
4
+ EXEC_INSTANT_PX = 1
5
+ EXEC_MARKET = 3
6
+ EXEC_EXCHANGE = 4
7
+
8
+ ORDER_BUY = 0
9
+ ORDER_SELL = 1
10
+ ORDER_BUY_LIMIT = 2
11
+ ORDER_SELL_LIMIT = 3
12
+ ORDER_BUY_STOP = 4
13
+ ORDER_SELL_STOP = 5
14
+ ORDER_BUY_STOP_LIMIT = 6
15
+ ORDER_SELL_STOP_LIMIT = 7
16
+ ORDER_CLOSE_BY = 8
17
+
18
+ TRADE_ACTION_DEAL = 3
19
+ TRADE_ACTION_PENDING = 5
20
+ TRADE_ACTION_SLTP = 6
21
+ TRADE_ACTION_MODIFY = 7
22
+ TRADE_ACTION_REMOVE = 8
23
+
24
+ FILLING_FOK = 0
25
+ FILLING_IOC = 1
26
+ FILLING_RETURN = 2
27
+
28
+ FLAGS_NONE = 0
29
+ FLAGS_XA = 2
@@ -0,0 +1,26 @@
1
+ """Trade server return codes."""
2
+
3
+ RETCODE_DONE = 10009
4
+ RETCODE_DONE_PARTIAL = 10011
5
+
6
+ RETCODES = {
7
+ 0: 'PENDING', 1: 'OK',
8
+ 10001: 'ON_THE_WAY', 10002: 'ACCEPTED', 10003: 'PROCESSED',
9
+ 10004: 'REQUOTE', 10005: 'PRICES', 10006: 'REJECTED', 10007: 'CANCELED',
10
+ 10008: 'PLACED', 10009: 'DONE', 10011: 'DONE_PARTIAL',
11
+ 10012: 'TIMEOUT', 10013: 'INVALID', 10014: 'INVALID_VOLUME',
12
+ 10015: 'INVALID_PRICE', 10016: 'INVALID_SLTP',
13
+ 10017: 'TRADE_DISABLED', 10018: 'MARKET_CLOSED', 10019: 'NO_MONEY',
14
+ 10020: 'PRICE_CHANGED', 10021: 'OFF_QUOTES',
15
+ 10026: 'ALGO_DISABLED_SERVER', 10027: 'ALGO_DISABLED_CLIENT',
16
+ 10023: 'ORDER_LOCKED', 10024: 'LONG_ONLY',
17
+ 10030: 'UNSUPPORTED_FILLING', 10033: 'ORDERS_LIMIT',
18
+ 10034: 'VOLUME_LIMIT', 10035: 'INVALID_ORDER_TYPE',
19
+ 10036: 'INVALID_ORDER', 10038: 'POSITION_NOT_FOUND',
20
+ 10040: 'LIMIT_POSITIONS', 10041: 'NO_CHANGES',
21
+ 10042: 'CONNECTION_LOST', 10043: 'FREQUENT_REQUESTS',
22
+ }
23
+
24
+
25
+ def retcode_name(code: int) -> str:
26
+ return RETCODES.get(code, f'UNKNOWN_{code}')
@@ -0,0 +1,17 @@
1
+ """Timeframe identifiers and their length in seconds."""
2
+
3
+ TIMEFRAMES = {
4
+ 'M1': 1, 'M2': 2, 'M3': 3, 'M4': 4, 'M5': 5, 'M6': 6,
5
+ 'M10': 10, 'M12': 12, 'M15': 15, 'M20': 20, 'M30': 30,
6
+ 'H1': 16385, 'H2': 16386, 'H3': 16387, 'H4': 16388,
7
+ 'H6': 16390, 'H8': 16392, 'H12': 16396,
8
+ 'D1': 16408, 'W1': 32769, 'MN1': 49153,
9
+ }
10
+
11
+ TF_SECONDS = {
12
+ 1: 60, 2: 120, 3: 180, 4: 240, 5: 300, 6: 360,
13
+ 10: 600, 12: 720, 15: 900, 20: 1200, 30: 1800,
14
+ 16385: 3600, 16386: 7200, 16387: 10800, 16388: 14400,
15
+ 16390: 21600, 16392: 28800, 16396: 43200,
16
+ 16408: 86400, 32769: 604800, 49153: 2592000,
17
+ }
@@ -0,0 +1,13 @@
1
+ """Exception hierarchy for mt5direct."""
2
+
3
+
4
+ class MT5Error(Exception):
5
+ """Base class for all mt5direct errors."""
6
+
7
+
8
+ class ConnectionFailed(MT5Error, ConnectionError):
9
+ """Hello handshake with the trade server failed."""
10
+
11
+
12
+ class LoginFailed(MT5Error, ConnectionError):
13
+ """Server rejected the login request."""
@@ -0,0 +1,13 @@
1
+ from .account import AccountInfo
2
+ from .candle import Candle
3
+ from .frame import Frame
4
+ from .history import Deal, HistoryOrder
5
+ from .position import Position, PositionPnL
6
+ from .symbol import Symbol
7
+ from .tick import Tick
8
+ from .trade import TradeAck, TradeResult
9
+
10
+ __all__ = [
11
+ "AccountInfo", "Candle", "Deal", "Frame", "HistoryOrder",
12
+ "Position", "PositionPnL", "Symbol", "Tick", "TradeAck", "TradeResult",
13
+ ]
@@ -0,0 +1,11 @@
1
+ from dataclasses import dataclass
2
+
3
+ from .frame import Frame
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class AccountInfo:
8
+ balance: float
9
+ credit: float
10
+ currency: str
11
+ raw: Frame
@@ -0,0 +1,12 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Candle:
6
+ time: int
7
+ open: float
8
+ high: float
9
+ low: float
10
+ close: float
11
+ tick_volume: int
12
+ spread: int
@@ -0,0 +1,10 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Frame:
6
+ """One decrypted server message."""
7
+
8
+ cmd: int
9
+ status: int
10
+ payload: bytes
@@ -0,0 +1,20 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Deal:
6
+ deal: int
7
+ symbol: str
8
+ time: int
9
+ action: str
10
+ """``'BUY'`` or ``'SELL'``."""
11
+ entry: str
12
+ """``'IN'`` or ``'OUT'``."""
13
+ price: float
14
+ volume: float
15
+ profit: float
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class HistoryOrder:
20
+ order: int
@@ -0,0 +1,24 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Position:
6
+ ticket: int
7
+ symbol: str
8
+ type: str
9
+ """``'BUY'`` or ``'SELL'``."""
10
+ volume: float
11
+ price_open: float
12
+ price_current: float
13
+ sl: float
14
+ tp: float
15
+ contract_size: float
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class PositionPnL:
20
+ """A position with a live price and the floating P&L computed from it."""
21
+
22
+ position: Position
23
+ current_price: float
24
+ pnl: float
@@ -0,0 +1,12 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Symbol:
6
+ name: str
7
+ description: str
8
+ index: int
9
+ ta: int
10
+ """Server-side numeric id used for resolve/subscribe and in tick records."""
11
+ digits: int
12
+ path: str
@@ -0,0 +1,16 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, slots=True)
5
+ class Tick:
6
+ ta: int
7
+ symbol: str
8
+ digits: int
9
+ bid: float
10
+ ask: float
11
+ bid_raw: float
12
+ ask_raw: float
13
+ last: float
14
+ timestamp: int
15
+ flags: int
16
+ spread: int
@@ -0,0 +1,29 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+ from .frame import Frame
5
+
6
+
7
+ @dataclass(frozen=True, slots=True)
8
+ class TradeAck:
9
+ """Immediate reply to a trade request. ``retcode`` is ``None`` if the reply had no code."""
10
+
11
+ retcode: Optional[int]
12
+ retcode_str: Optional[str]
13
+ raw: Frame
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class TradeResult:
18
+ """Final execution report. Only the ``retcode`` fields are meaningful on failure."""
19
+
20
+ retcode: int
21
+ retcode_str: str
22
+ deal: int = 0
23
+ order: int = 0
24
+ volume: float = 0.0
25
+ volume_raw: int = 0
26
+ price: float = 0.0
27
+ bid: float = 0.0
28
+ ask: float = 0.0
29
+ comment: str = ""
@@ -0,0 +1,10 @@
1
+ from .account import parse_account # noqa: F401
2
+ from .candles import parse_candles # noqa: F401
3
+ from .history import parse_history # noqa: F401
4
+ from .positions import parse_positions # noqa: F401
5
+ from .resolve import ( # noqa: F401
6
+ extract_resolve_prices, find_resolve_bid_offset, parse_trade_modes, parse_trade_sessions,
7
+ )
8
+ from .symbols import parse_symbols # noqa: F401
9
+ from .ticks import parse_tick, parse_ticks # noqa: F401
10
+ from .trade import parse_trade_ack, parse_trade_result # noqa: F401
@@ -0,0 +1,18 @@
1
+ from typing import Optional
2
+
3
+ from ..models import AccountInfo, Frame
4
+ from ..protocol import BinaryReader
5
+ from ..protocol.layouts import ACCOUNT_MIN_SIZE
6
+
7
+
8
+ def parse_account(frame: Optional[Frame]) -> Optional[AccountInfo]:
9
+ """``None`` unless the frame is a successful reply of at least 89 bytes."""
10
+ if frame is None or frame.status != 0 or len(frame.payload) < ACCOUNT_MIN_SIZE:
11
+ return None
12
+ r = BinaryReader(frame.payload)
13
+ return AccountInfo(
14
+ balance=r.f64(9),
15
+ credit=r.f64(17),
16
+ currency=r.wchar(25, 64),
17
+ raw=frame,
18
+ )
@@ -0,0 +1,21 @@
1
+ from ..models import Candle
2
+ from ..protocol import BinaryReader
3
+ from ..protocol.layouts import CANDLE_RECORD_SIZE
4
+
5
+
6
+ def parse_candles(payload: bytes) -> list[Candle]:
7
+ r = BinaryReader(payload)
8
+ candles = []
9
+ off = 0
10
+ while off + CANDLE_RECORD_SIZE <= len(payload):
11
+ candles.append(Candle(
12
+ time=r.i32(off),
13
+ open=r.f64(off + 4),
14
+ high=r.f64(off + 12),
15
+ low=r.f64(off + 20),
16
+ close=r.f64(off + 28),
17
+ tick_volume=r.i64(off + 36),
18
+ spread=r.i32(off + 44),
19
+ ))
20
+ off += CANDLE_RECORD_SIZE
21
+ return candles
@@ -0,0 +1,38 @@
1
+ from ..models import Deal, HistoryOrder
2
+ from ..protocol import BinaryReader, raw_to_vol
3
+ from ..protocol.layouts import DEAL_RECORD_SIZE, ORDER_RECORD_SIZE
4
+
5
+
6
+ def parse_history(payload: bytes) -> tuple[list[Deal], list[HistoryOrder]]:
7
+ """Decode ``[u32 deal_count][deals...][u32 order_count][orders...]``."""
8
+ if len(payload) < 4:
9
+ return [], []
10
+ r = BinaryReader(payload)
11
+ deal_count = r.u32(0)
12
+ off = 4
13
+ deals = []
14
+ for _ in range(deal_count):
15
+ if off + DEAL_RECORD_SIZE > len(payload):
16
+ break
17
+ rec = BinaryReader(payload[off:off + DEAL_RECORD_SIZE])
18
+ deals.append(Deal(
19
+ deal=rec.i64(0),
20
+ symbol=rec.wchar(88, 64),
21
+ time=rec.u32(80),
22
+ action='BUY' if rec.u32(152) == 0 else 'SELL',
23
+ entry='IN' if rec.u32(156) == 0 else 'OUT',
24
+ price=rec.f64(160),
25
+ volume=raw_to_vol(rec.u64(192)),
26
+ profit=rec.f64(200),
27
+ ))
28
+ off += DEAL_RECORD_SIZE
29
+ orders = []
30
+ if off + 4 <= len(payload):
31
+ order_count = r.u32(off)
32
+ off += 4
33
+ for _ in range(order_count):
34
+ if off + ORDER_RECORD_SIZE > len(payload):
35
+ break
36
+ orders.append(HistoryOrder(order=r.i64(off)))
37
+ off += ORDER_RECORD_SIZE
38
+ return deals, orders
@@ -0,0 +1,35 @@
1
+ from ..models import Position
2
+ from ..protocol import BinaryReader, raw_to_vol
3
+ from ..protocol.layouts import POSITION_HEADER_SIZE, POSITION_RECORD_SIZE
4
+
5
+ _PRICE_SANITY_LIMIT = 1e10
6
+
7
+
8
+ def _clean_level(v: float) -> float:
9
+ return v if 0 < v < _PRICE_SANITY_LIMIT else 0.0
10
+
11
+
12
+ def parse_positions(payload: bytes) -> list[Position]:
13
+ """Decode the open-position list returned by the init-trading command."""
14
+ if len(payload) < POSITION_HEADER_SIZE:
15
+ return []
16
+ r = BinaryReader(payload)
17
+ pos_count = r.u32(0)
18
+ positions = []
19
+ for i in range(pos_count):
20
+ base = POSITION_HEADER_SIZE + i * POSITION_RECORD_SIZE
21
+ if base + POSITION_RECORD_SIZE > len(payload):
22
+ break
23
+ rec = BinaryReader(payload[base:base + POSITION_RECORD_SIZE])
24
+ positions.append(Position(
25
+ ticket=rec.i64(0),
26
+ symbol=rec.wchar(24, 64),
27
+ type='BUY' if rec.u32(88) == 0 else 'SELL',
28
+ volume=raw_to_vol(rec.u64(124)),
29
+ price_open=rec.f64(92),
30
+ price_current=rec.f64(100),
31
+ sl=_clean_level(rec.f64(108)),
32
+ tp=_clean_level(rec.f64(116)),
33
+ contract_size=rec.f64(248),
34
+ ))
35
+ return positions