ibpy python-2.7 IB网关TWS API

时间:2015-12-18 08:46:42

标签: python postgresql api tws ibpy

想知道是否有人可以告诉我这个Python代码有什么问题?我知道php和Perl但是Python对我来说很奇怪。我无法理解这里发生了什么。

我想创建这个代码,它将从一个sql select of forex对中取出一个数组并拉出引号并将中点插入到sql表中。现在我甚至无法从IB获取报价!!!

如果有人知道IB和Python可以有人请指出为什么这不起作用......我迷路了。

#!/usr/local/bin/python

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import ibConnection, message
from time import sleep, strftime, localtime
from datetime import datetime

## Global variables
shares = 3
action = 'BUY'
orderID = 30
last = 0
prev_last = 0
sym = 'YM'

## Contract Creation Function
def makeForexContract(contractTuple):
    newContract = Contract()
    newContract.m_symbol = contractTuple[0]
    newContract.m_secType = contractTuple[1]
    newContract.m_exchange = contractTuple[2]
    newContract.m_currency = contractTuple[3]
    newContract.m_expiry = contractTuple[4]
    newContract.m_strike = contractTuple[5]
    newContract.m_right = contractTuple[6]
    FXPair = contractTuple[7]
    print 'Contract Values:%s,%s,%s,%s,%s,%s,%s,%s:' % contractTuple
    return newContract

def makeStkContract(sym):
    contract = Contract()
    contract.m_symbol = 'EUR'
    contract.m_secType = 'CASH'
    #contract.m_expiry = '20130315'
    contract.m_exchange = 'IDEALPRO'
    contract.m_currency = 'CAD'
    return contract

## Order Creation Function
def makeStkOrder(shares,action):
    order = Order()
    order.m_minQty = shares
    #order.m_lmtPrice = limit_price
    order.m_orderType = 'MKT'
    order.m_totalQuantity = shares
    order.m_action = str(action).upper()
    return order

## Tick Handler
def my_tick_handler(msg):
    global last
    global prev_last
    #print msg
    if msg.field == 4:
        prev_last = last
        last = float(msg.price)
        #print msg

##Connect
con = ibConnection('192.168.1.123', 4001, 1)
con.register(my_tick_handler, message.tickSize, message.tickPrice)
con.connect()
sleep(1)

## Make your contract
contractTuple = ('EUR', 'CASH', 'IDEALPRO', 'CAD', '', 0.0, '', 1)
#ForexContract = makeForexContract(contractTuple)
stkContract = makeStkContract(sym)
## Request tick data
con.reqMktData(orderID, stkContract, '', False)
#con.reqMktData(orderID, ForexContract, '', False)
print last
sleep(10)

## Prints last price as long as between 13070 and 13100
while (last > 13070 and last < 13100):
    print last

#### A possible execution plan. Remove '##' to initiate.
#### A paper trading account is recommended for testing and debugging trade execution code.
##    if (last > 13083):
##        action = 'BUY' 
##        stkOrder = makeStkOrder(shares,action)
##        con.placeOrder(orderID,stkContract,stkOrder)
##    elif (last < 13082):
##        action = 'SELL'
##        stkOrder = makeStkOrder(shares,action)
##        con.placeOrder(orderID,stkContract,stkOrder)

sleep(.5)

##Stop receiving tick values
con.cancelMktData(orderID)

##Disconnect from TWS
con.disconnect()

0 个答案:

没有答案