-
Notifications
You must be signed in to change notification settings - Fork 0
/
comm.py
70 lines (42 loc) · 1.58 KB
/
comm.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
#!/usr/bin/env python3
"""
Copyright (C) 2016 Interactive Brokers LLC. All rights reserved. This code is
subject to the terms and conditions of the IB API Non-Commercial License or the
IB API Commercial License, as applicable.
"""
"""
This module has tools for implementing the IB low level messaging.
"""
import struct
from common import UNSET_INTEGER, UNSET_DOUBLE
from logger import LOGGER
def make_msg(text) -> bytes:
""" adds the length prefix """
#msg = array.array('B',
msg = struct.pack("!I%ds" % len(text), len(text), str.encode(text))
return msg
def make_field(val) -> bytes:
""" adds the NULL string terminator """
if val is None:
raise ValueError("Cannot send None to TWS")
# bool type is encoded as int
if type(val) is bool:
val = int(val)
field = str(val) + '\0'
return field
def make_field_handle_empty(val) -> bytes:
if val is None:
raise ValueError("Cannot send None to TWS")
if UNSET_INTEGER == val or UNSET_DOUBLE == val:
val = ""
return make_field(val)
def read_msg(buf: bytes) -> tuple:
""" first the size prefix and then the corresponding msg payload """
size = struct.unpack("!I", buf[0:4])[0]
LOGGER.debug("read_msg: size: %d", size)
text = struct.unpack("!%ds" % size, buf[4:4+size])[0]
return (size, text, buf[4+size:])
def read_fields(buf: bytes) -> tuple:
""" msg payload is made of fields terminated/separated by NULL chars """
fields = buf.split(b"\0")
return fields[0:-1] #last one is empty; this may slow dow things though, TODO