Interactive Broker Python API 開發的Notes #3
攞Account的倉位記錄返來
返轉頭
20180515, 20180515
原來寫左少少關於contract用來落單既,但中間停左搞左其他野,中間寫緊個UI時測試寫左少少攞個account頭寸(倉位)既程式,環保啲講呢樣先。
基本上都用返上兩頁用開果個Example 程式來改,懶+求其於是我地呢度所有Class 都會放晒同一個File,上面出來既result係我個真實戶口,呢度我地都係講返寫程式。
之前講過,IB個API上行同下行分開兩個Class去做,於是我地要Implement 佢EWrapper同EClient,抄返街邊個倒子就係TWrapper同TClient,
然後佢再Multiple Inheritance咁去implement 一個TApp
於是TApp就有晒EWrapper同EClient的Method,向執行果時,就去new 一個TApp的instance來行,就係咁上下:
class TWrapper(EWrapper):
def position(self, account, contract, position, avgCost):
print("Position info come in")
print("{} {} {} {}".format(account, contract, position, avgCost))
pass
呢個例子中,TClient基本上係無野既:
class TClient(EClient):
def __init__(self, wrapper):
## Set up with a wrapper inside
EClient.__init__(self, wrapper)
最後係TApp:
class TApp(TWrapper, TClient):
def __init__(self, ipaddress, portid, clientid):
#TestWrapper.__init__(self)
TWrapper.__init__(self)
TClient.__init__(self, wrapper=self)
try:
self.connect(ipaddress, portid, clientid)
except e:
print("Some error")
print(e)
return
print("connected")
thread = Thread(target = self.run)
thread.start()
setattr(self, "_thread", thread)
由於只係示範去攞到倉位記錄返來,呢度有咁少野得咁少野,唔會有多餘程式。
if __name__ == '__main__':
app = TApp("127.0.0.1", 4001, 10)
app.reqPositions()
time.sleep(10)
app.disconnect()
最訂要加返 Import果堆野
from ibapi.wrapper import EWrapper
from ibapi.client import EClient
from threading import Thread
import time
向Main入面 time.sleep(10)係用來等佢問完 TWS/IB GW攞野返來,如果無左未攞返來已經結束左個程式。
呢度只係最簡單寫法用來玩下,距離可以用來落單或者自動交易仲有好遠好遠。
返轉頭