2018/04/12

元大證劵API python 串接

元大證劵API 也是使用 ComTypes
目前串接進度:串接到 Open 呼叫 Login 沒有反應

使用需修改
1. GetModule 需要修改目錄位置
2. 由於使用 x32 的 dll, 所以需要使用 python 32位元的版本
3. 帳號/密碼使用元大給的測試帳/密



# -*- coding: utf-8 -*-
import sys, os, time
import ctypes, comtypes, pythoncom
from ctypes import *
from comtypes.client import GetModule, CreateObject
from comtypes.client import ShowEvents, GetEvents, PumpEvents
import queue as queue
q = queue.Queue ()
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
class Job:
STOCK_OPEN = 1
STOCK_CLOSE = 2
STOCK_LOGIN = 3
STOCK_WATCH = 4
def __init__ (self, do_type):
self.do_type = do_type
def DoJob(Bot, x):
for case in switch(x.do_type):
print ("DoJob: " + str (x.do_type))
if case(Job.STOCK_OPEN):
Bot.open ()
break
if case(Job.STOCK_CLOSE):
time.sleep(100)
Bot.close ()
break
if case(Job.STOCK_LOGIN):
Bot.login ()
break
class PolaisB2BTraderEvents(object):
def __init__(self, parent):
self.parent = parent
def OnResponse(self, intmark, dwIndex, strIndex, Handle, aryValue):
print ("OnResponse: " + aryValue)
for case in switch(intmark):
if case(0):
if aryValue == "Is Connected!!":
j = Job(Job.STOCK_LOGIN)
q.put (j)
break
if case(1):
print ("OnResponse: intmark 1")
break
class YuantaWapper:
def __init__(self, uid, bot):
self.uid = uid
self.bot = bot
path = os.path.join("c:\\B2BAPI_User_Docs", "PolarisB2BAPI.dll")
PolarisB2BAPI = GetModule(path)
import comtypes.gen.PolarisB2BAPI as PolarisB2BAPI
self.PolarisB2BAPI = PolarisB2BAPI
self.PolaisB2BTrader = CreateObject(PolarisB2BAPI.PolaisB2BTrader)
self.PolaisB2BTraderEvents = PolaisB2BTraderEvents (self)
self.PolaisB2BTraderEventsConnect = GetEvents (self.PolaisB2BTrader, self.PolaisB2BTraderEvents)
class StockBot:
def __init__(self, botuid, account, pwd, acc_type):
self.Yuanta = YuantaWapper (botuid, self)
self.Account = account
self.Pwd = pwd
self.AccType = acc_type
def open (self):
self.Yuanta.PolaisB2BTrader.Open ()
def close (self):
self.Yuanta.PolaisB2BTrader.Close ()
def login (self):
#from struct import pack
intFunID = int(0) #總帳登入
abyAccount = (self.AccType + self.Account).ljust(22)
retValue = self.Yuanta.PolaisB2BTrader.Login (intFunID, abyAccount, self.Pwd)
print ('login: ' + str(retValue))
if __name__ == "__main__":
comtypes.CoInitialize()
Bot = StockBot(0, '98875005091', '1234', 'S')
j = Job(Job.STOCK_OPEN)
q.put (j)
while 1:
while not q.empty():
next_job = q.get()
DoJob (Bot, next_job)
pythoncom.PumpWaitingMessages()