我对您的代码做了一些修改,并在与您的代码不同的地方添加了注释(更正您的错误):
import socket
import base64
import time, datetime
import hmac
import hashlib
PASSPHRASE = "your passphrase"
API_KEY = "your api key"
API_SECRET = "your secret"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 4197))
seq_num = "1" # Correction: using the same MsgSeqNum for signed text and for the field 34
# Correction: t is the same in both signed RawData and in SendingTime (52)
timestamp = str(time.time())
t = str(datetime.datetime.utcnow()).replace("-","").replace(" ", "-")[:-3]
# Correction: '|' is not a valid separator for FIX, it must be '\u0001'
message = "\u0001".join([t, "A", seq_num, API_KEY, "Coinbase", PASSPHRASE]).encode("utf-8")
hmac_key = base64.b64decode(API_SECRET)
signature = hmac.new(hmac_key, message, hashlib.sha256)
sign_b64 = base64.b64encode(signature.digest()).decode()
msgType = "A"
body = "34={}|52={}|49={}|56=Coinbase|98=0|108=30|554={}|96={}|8013=Y|".format(seq_num, t, API_KEY, PASSPHRASE, sign_b64) # using the same time (t) and seq_num as in signed text
# Correction: bodyLength is the number of characters, not bytes, also it must include everything after "8=FIX.4.2|9={}|" i.e. the "35=A|" part of the header
bodyLength = len("35={}|".format(msgType)) + len(body)
header = "8=FIX.4.2|9={}|35={}|".format(bodyLength, msgType)
msg = header + body
msg = msg.replace('|', '\u0001') # Correction: '|' is not a valid separator for FIX, it must be '\u0001'
# generate the checksum:
def check_sum(s):
sum = 0
for char in msg:
sum += ord(char)
sum = str(sum % 256)
while len(sum) < 3:
sum = '0' + sum
return sum
c_sum = check_sum(msg)
logon = msg + "10={}\u0001".format(c_sum)
logon = logon.encode('ascii')
print(logon)
s.sendall(logon)
print(s.recv(4096))
对我来说,这个更正后的代码现在返回来自服务器的登录消息,而不是像您的情况那样仅返回 0 字节。您能否确认它也适用于您并且登录完成后您可以成功发送其他交易?