问题
I am trying to run this python script from How to connect to TT X_TRADER API in order to create an automated trading system using python?
import pythoncom
from time import sleep
from win32com.client import Dispatch, DispatchWithEvents, getevents
from win32com.client.gencache import EnsureDispatch, EnsureModule
GATE = None
NOTIFY = None
class InstrNotify(getevents('XTAPI.TTInstrNotify')):
def __init__(self):
pass
def Subscribe(self, pInstr):
self.AttachInstrument(pInstr)
pInstr.Open(0)
def OnNotifyFound(self, pNotify=None, pInstr=None):
pInstr = Dispatch(pInstr)
print 'Found instrument:'
print '--> Contract: %s' % pInstr.Get('Contract')
print '--> Exchange: %s' % pInstr.Get('Exchange')
def OnNotifyNotFound(self, pNotify=None, pInstr=None):
pInstr = Dispatch(pInstr)
print 'Unable to find instrument'
def OnNotifyUpdate(self, pNotify=None, pInstr=None):
pInstr = Dispatch(pInstr)
contract = pInstr.Get('Contract')
bid = pInstr.Get('Bid')
ask = pInstr.Get('Ask')
last = pInstr.Get('Last')
print '[UPDATE] %s: %s/%s' % (contract, bid, ask)
def Connect():
global NOTIFY, GATE
#the below is required in order to establish the com-object links
#that way you don't need to run makepy first
EnsureModule('{98B8AE14-466F-11D6-A27B-00B0D0F3CCA6}', 0, 1, 0)
GATE = EnsureDispatch('XTAPI.TTGate')
NOTIFY = DispatchWithEvents('XTAPI.TTInstrNotify', InstrNotify)
def main():
Connect()
pInstr = EnsureDispatch('XTAPI.TTInstrObj')
pInstr.Exchange = 'CME-A'
pInstr.Product = 'CL'
pInstr.Contract = 'CL Mar13'
pInstr.ProdType = 'FUTURE'
NOTIFY.Subscribe(pInstr)
for i in range(10):
pythoncom.PumpWaitingMessages()
sleep(1.0)
I made one adjustment which was on line 9:
class InstrNotify(getevents('XTAPI.TTInstrNotify')):
to:
class InstrNotify():
in order to make it work (still not too sure why it works like that, but I think its because there is ...'no need to use getevents as DispatchWithevents already does the getevents, so just defining your Events class without a base-class should work.'(from win32 documentation, but I still not sure what it means, hope someone here will be kind enough to explain it too).
Anyway, my main question here is that while I can make this script work in spyder python console, I cannot make it work in the spyder ipython console nor in the cmd console ( windows command line). And I cannot figure out why, nor find the answer anywhere. I sincerely hope someone here will be kind enough to help. Thanks so much in advance.
btw, i am using python 3.6.0, Anaconda 4.3.0 (64bit), on windows 10 (64 bit). in the windows cmd, also using the same conda environment as the spyder.
来源:https://stackoverflow.com/questions/42246098/python-script-works-in-spyder-console-but-not-in-spyder-ipython-or-cmd-in-window