iklan header

Streaming prices from IB API swigibpy

There is now a local python API. I've written an updated version of this put up, here, which makes use of the local API.

In my last post (http://qoppac.Blogspot.Co.United kingdom/2014/04/getting-expenses-out-of-ib-api-with.Html) we looked at getting snapshot historical prices. In this one we will look at streamed prices - 'market tick data'. Rather than wait until the historical price feed ends with streaming prices we need to tell the streamer when to stop.

No flow rises higher than its supply

Get the supply code from this git repository. The files you will need to take a look at are test3_IB.Py and wrapper_v3.Py.

No move drives whatever with out being restricted

The example code is similar to historical data; we make one of these weird client objects containing a server 'callback' connection, make one of these slightly less weird contract objects (here it is for December 2016 Eurodollar futures) and then shove one into a request function for the other.

from test3_IB.Py, __main characteristic:

callback = IBWrapper()

    consumer=IBclient(callback)

    ibcontract = IBcontract()

    ibcontract.SecType = "FUT"

    ibcontract.Expiry="201612"

    ibcontract.Image="GE"

    ibcontract.Trade="GLOBEX"

    ans=customer.Get_IB_market_data(ibcontract)

    print "Bid size, Ask length; Bid charge; Ask charge"

    print ans

This ought to produce something just like the following (assuming the marketplace is open and you have a IB gateway or TWS server open.:

Bid size, Ask size; Bid charge; Ask price

[10836, 12362, 98.665, 98.67]

Of direction in the dull familar tale within the customer object functions that truely get the statistics we have genuinely were given hidden event driven code again.

From wrapper_v3.Py, IBclient.Get_IB_market_data() technique:

def get_IB_market_data(self, ibcontract, seconds=30,  tickerid=MEANINGLESS_ID):

"""

        Returns granular market records

        Returns a tuple (bid charge, bid length, ask price, ask length)

        """

        ## initialise the tuple

        self.Cb.Init_tickdata(tickerid)

        self.Cb.Init_error()

        # Request a marketplace information circulate

        self.Tws.ReqMktData(

                tickerid,

                ibcontract,

                "",

                False)

<SNIP   ... more code to come>

Ah sure its the standard stuff of putting in place area within the self.Cb callback example to get the records and then name the tws server request characteristic (strictly speakme its one of these 'EClientSocket' whatdoyoucallits once more).

Only lifeless fish swim with the circulation...

We now look inside the server callback object which gets populated as an instance self.cb. As before there are a few EWrapper functions which get triggered whenever the market data arrives.

There are in fact numerous techniques for 'tickString', 'tickGeneric', 'tickSize' and 'tickPrice'; it seems a bit stochastic (quant talk: english translation absolutely bloody random and arbitrary) which of those techniques gets called whilst a tick arrives (a tick can be an replace to a rate or to a quoted size on the top degree of the order book). Lets have a look at the most frequent of those:

def tickGeneric(self, TickerId, tickType, fee):

        marketdata=self.Data_tickdata[TickerId]

        ## update everyday ticks

        if int(tickType)==0:

            ## bid size

            marketdata[0]=int(price)

        elif int(tickType)==three:

            ## ask size

            marketdata[1]=int(fee)

        elif int(tickType)==1:

            ## bid

            marketdata[2]=drift(price)

        elif int(tickType)==2:

            ## ask

            marketdata[3]=flow(value)

All the code does is become aware of which kind of tick it's miles after which populate the precise a part of marketdata. Obviously we are able to grow to be overwriting the values already in marketdata tuple but you could store them for some kind of averaging if you want.

Once inside the movement of history you can not get out

If we just let that baby run we'd be receiving streams of prices until the cows came home. So what we do back in the client world is say STOP I've had enough after a preset amount of time (we could also STOP when the N'th tick has arrived, or when there all the slots in marketdata are filled, which would be easy enough to code up).

From wrapper_v3.Py, IBclient.Get_IB_market_data() technique:

<Continuing from where we were before. Repeating the last call for clarity>

self.Tws.ReqMktData(

                tickerid,

                ibcontract,

                "",

                False)

        start_time=time.Time()

        finished=False

        iserror=False

        at the same time as no longer completed and no longer iserror:

            iserror=self.Cb.Flag_iserror

            if (time.time() - start_time) > seconds:

                completed=True

            bypass

        self.Tws.CancelMktData(tickerid)

        marketdata=self.Cb.Data_tickdata[tickerid]

        ## marketdata need to now include a few thrilling information

        ## Note on this implementation we overwrite the contents with each tick; we ought to preserve them

        if iserror:

            print "Error: " self.Cb.Error_msg

            print "Failed to get any prices with marketdata"

        return marketdata

So we go back the final values we have populated marketdata with before we stopped (despite the fact that once more I could take the medians).

By the manner it can be a chunk risky to average costs an excessive amount of; as an instance if you sample charges throughout the day and then take a median as your input into your trading set of rules you'll underestimate the real amount of volatility within the marketplace. Similarly if you are trading excessive frequency stuff you'll be the use of the energetic nation of the order ebook and averaging common real time bars is probably now not going to be a totally smart element to do. Over this brief term relative to my standard trading pace but its probably okay as on the whole all we're going to be eliminating is a little illusory volatility caused by 'bid-ask' soar.

Also even with this averaging its nonetheless worth walking your expenses through a 'leap detector' to make certain you do not alternate off dirty fees displaying spuriously massive movements; I see these about as soon as a month for each device I trade!

Much plenty greater on this problem in this put up

Islands in the move...

That is it for prices. I use the historical data function whenever I start trading a particular contract but also every day as it gets close prices. This makes my system self recovering since even if it drops for a few days I will end up with daily prices at least being infilled. Also often non actively traded contracts still have close prices, useful if you are using intra contract spreads as a data input. Just be careful how you treat intraday and closing prices if you append them together.

Much plenty greater on this problem in this put up

I use marketplace information to get intraday charges, and when I am pretty much to change to test the marketplace is liquid sufficient for what I need to do (or maybe simply to check it's miles open since I do not hassle preserving a holidays calendar for all my markets - I would not need to spend more than 10 minutes of my time an afternoon running this device now would I?). Plus it permits me to dis-aggregate my trading costs into what's coming from the internal unfold, the cost of processing / execution delays and having to drop deeper into the order e-book.

Next on the menu might be placing an order! I will leave the trivial task of constructing a gadget which comes to a decision what the orders can be to the reader (trace: you might need to apply the charge in some way).

This is the 1/3 in a sequence of posts. The first two posts are:

http://qoppac.Blogspot.Co.United kingdom/2014/04/getting-expenses-out-of-ib-api-with.Html

http://qoppac.Blogspot.Co.Uk/2014/03/the use of-swigibpy-so-that-python-will-play.Html

The subsequent submit is:

http://qoppac.Blogspot.Co.Uk/2014/05/the-putting-of-orders-to-interactive.Html

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel