HPK

mesothelioma survival rates,structured settlement annuity companies,mesothelioma attorneys california,structured settlements annuities,structured settlement buyer,mesothelioma suit,mesothelioma claim,small business administration sba,structured settlement purchasers,wisconsin mesothelioma attorney,houston tx auto insurance,mesotheliama,mesothelioma lawyer virginia,seattle mesothelioma lawyer,selling my structured settlement,mesothelioma attorney illinois,selling annuity,mesothelioma trial attorney,injury lawyer houston tx,baltimore mesothelioma attorneys,mesothelioma care,mesothelioma lawyer texas,structered settlement,houston motorcycle accident lawyer,p0135 honda civic 2004,structured settlement investments,mesothelioma lawyer dallas,caraccidentlawyer,structured settlemen,houston mesothelioma attorney,structured settlement sell,new york mesothelioma law firm,cash out structured settlement,mesothelioma lawyer chicago,lawsuit mesothelioma,truck accident attorney los angeles,asbestos exposure lawyers,mesothelioma cases,emergency response plan ppt,support.peachtree.com,structured settlement quote,semi truck accident lawyers,auto accident attorney Torrance,mesothelioma lawyer asbestos cancer lawsuit,mesothelioma lawyers san diego,asbestos mesothelioma lawsuit,buying structured settlements,mesothelioma attorney assistance,tennessee mesothelioma lawyer,earthlink business internet,meso lawyer,tucson car accident attorney,accident attorney orange county,mesothelioma litigation,mesothelioma settlements amounts,mesothelioma law firms,new mexico mesothelioma lawyer,accident attorneys orange county,mesothelioma lawsuit,personal injury accident lawyer,purchase structured settlements,firm law mesothelioma,car accident lawyers los angeles,mesothelioma attorneys,structured settlement company,auto accident lawyer san francisco,mesotheolima,los angeles motorcycle accident lawyer,mesothelioma attorney florida,broward county dui lawyer,state of california car insurance,selling a structured settlement,best accident attorneys,accident attorney san bernardino,mesothelioma ct,hughes net business,california motorcycle accident lawyer,mesothelioma help,washington mesothelioma attorney,best mesothelioma lawyers,diagnosed with mesothelioma,motorcycle accident attorney chicago,structured settlement need cash now,mesothelioma settlement amounts,motorcycle accident attorney sacramento,alcohol rehab center in florida,fast cash for house,car accident lawyer michigan,maritime lawyer houston,mesothelioma personal injury lawyers,personal injury attorney ocala fl,business voice mail service,california mesothelioma attorney,offshore accident lawyer,buy structured settlements,philadelphia mesothelioma lawyer,selling structured settlement,workplace accident attorney,illinois mesothelioma lawyer

Menu Navigasi

Getting position and accounting data out of IB native python API

Start

This is the final put up. Not the very last put up of the weblog; which can be properly news or bad. But the final post in my short collection on the usage of the brand new local python API forinteractive agents. Having got a few fees and submitted a few orders we need to realize whether or not we made any cash or no longer; and what positions we've got. Although the code is alternatively trivial, deciphering the effects requires some know-how.

This is an update of the following post where I used the non native swigibpy (which I wrote nearly 3 years ago!).

This the fifth in a series of posts on using the native python API  You should read thefirst,second, third, and fourth. You should also read the documentation.

You want to get the code from this gist.

Getting positions

You will need to run the code in thelast post first so you actually have a position to look at (this will submit a market order for Eurodollar futures).

Now, if you've been following the collection up to now this sort of code sample need to be clean to comply with:

## we could get positions
positions_list = app.Get_current_positions()

In the consumer item:

def get_current_positions(self): ## Make a place to store the statistics we're going to go back
			positions_queue = finishableQueue(self.Init_positions()) ## ask for the records
			self.ReqPositions()
			<SNIP>

In the wrapper object:

def init_positions(self): positions_queue = self._my_positions = queue.Queue() return positions_queue def position(self, account, settlement, position, avgCost): ## uses a simple tuple, however you can do different, fancier, matters right here
			position_object = (account, agreement, function, avgCost) self._my_positions.Placed(position_object) def positionEnd(self): ## overriden method self._my_positions.Put(FINISHED)

Back inside the patron object:

def get_current_positions(self):

<SNIP>

## ballot until we get a termination or die of boredom
			MAX_WAIT_SECONDS = 10
			positions_list = positions_queue.Get(timeout=MAX_WAIT_SECONDS) whilst self.Wrapper.Is_error(): print(self.Get_error()) if positions_queue.Timed_out(): print("Exceeded maximum anticipate wrapper to confirm completed even as getting positions") go back positions_list

Results:

print(positions_list)
 [

('DU15153',

140109276672072: 56825063,GE,FUT,20181217,0.0,,2500,,,USD,GEZ8,GE,False,,combo:,

10.0,

244889.9)]

The effects come again as a four tuple: account figuring out name, settlement, role and realised PNL (this might seem massive - however that is a demo account so it will depend on what different humans have been trading). I'd endorse making a nice class to put those into, even though I don't trouble doing that here.

Finally be very  careful about using these snapshots to work out what positions you have. Firstly it is common to get the position coming back repeated times. So you will need to filter out duplicates. Secondly positions may sometimes not appear at all.

I use my own record of trades to find out what my current position should be. I compare this to the IB snapshot throughout the day.If there are any breaks in the reconciliation I temporarily halt trading in the relevant contract until the break has gone away. Occasionally this is because IB has sent me a fill I haven't picked up, or because the IB position snapshot is missing some contracts.

Getting accounting facts

The accounting records is a touch more complex. Firstly, we get three styles of accounting statistics from IB, which need to be prominent. Secondly, I pick out to access the accounting information through a cache in the purchaser item which most effective refreshes if the data we've is more than five mins vintage. Of direction after you apprehend the common sense sense loose to implement this otherwise your self.

Accounting values

The first type of accounting data we get are accounting values (returned by updateAccountValue in the wrapper)

## get the account name from the position
## normally you would understand your account but this is the demo
nameaccountName = positions_list[0][0] ## and accounting statistics
accounting_values = app.Get_accounting_values(accountName)

In the consumer item:

def get_accounting_values(self, accountName): #All these functions follow the same pattern: check if stale, if not return cache, else update values
					return self._account_cache.get_updated_cache(accountName, ACCOUNT_VALUE_FLAG)

What is that this doing below the hood? First we check to peer if the cache is up to date (default is to test if we've were given an account price inside the closing 5 minutes). If not then we ask for the accounting information to be updated. We then go back the cached cost (eithier historical, or just up to date)

Let's have a look at the workhorse function that actually updates the data _update_accounting_data:

In the wrapper object:

## get accounting datadef init_accounts(self, accountName): accounting_queue = self._my_accounts[accountName] = queue.Queue() return accounting_queue def updateAccountValue(self, key:str, val:str, foreign money:str, accountName:str): ## use this to seperate out different account statistics
				statistics = identifed_as(ACCOUNT_VALUE_FLAG, (key,val, foreign money)) self._my_accounts[accountName].Positioned(facts) def updatePortfolio(self, settlement, role:drift, marketPrice:glide, marketValue:glide, averageCost:go with the flow, unrealizedPNL:glide, realizedPNL:flow, accountName:str): ## use this to seperate out unique account facts
				facts = identifed_as(ACCOUNT_UPDATE_FLAG, (contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL)) self._my_accounts[accountName].Put(records) def updateAccountTime(self, timeStamp:str): ## use this to seperate out one-of-a-kind account records
				records = identifed_as(ACCOUNT_TIME_FLAG, timeStamp) self._my_accounts[accountName].Put(records) def accountDownloadEnd(self, accountName:str): self._my_accounts[accountName].Put(FINISHED)

The only novel thing here are these identifed_as(ACCOUNT_VALUE_FLAG, (key,val, currency)) guys. Because we push three different types of data on to the same queue we need to be able to distinguish them from each other. Rather than just push the raw data we're getting from IB (all stored as tuples, except for the single length timeStamp in updateAccountTime) we push an object which comes with a labelling flag to identify where it came from.

Back inside the patron object:

So some distance that is boilerplate, but this isn't:

The queue is made of 3 distinct types of facts (values, updates, and time) from three specific wrapper functions, so we need to cut up them up. We now have a dictionary, we now use this to update the extraordinary components of the cache:

We're now returned to the get_accounting_values characteristic with the intention to actually go back the up to date cache values we need:

				
def get_accounting_values(self, accountName): #All these functions follow the same pattern: check if stale, if not return cache, else update values
						return self._account_cache.get_updated_cache(accountName, ACCOUNT_VALUE_FLAG)


Results:

print(accounting_values)

[('AccountCode', 'DU15153', ''), ('AccountOrGroup', 'DU15153', 'BASE'), ('AccountOrGroup', 'DU15153', 'USD'), ('AccountReady', 'true', ''), .... <SNIP>

The account_value output may be a totally long listing of 3 tuples. Each one includes (keyname, fee, forex). Currency BASE indicates it's far the bills base foreign money (USD for the take a look at account). Here are some of the extra interesting account price entries.

  • ExchangeRate: In the form of ('ExchangeRate', '1.00', 'USD') This is a very boring exchange rate as the base currency is USD.
  •  FuturesPNL: This is how much we have made trading futures today, by currency. BASE is the total in base currency.
  • StockMarketValue: Self explanatory
  • NetLiquidation: This is what is my account worth if I close all my positions out (ignoring commissions and bid-ask). Its what I use to ultimately determine the total profit and loss used for rescaling my risk capital.
  • CashBalance: Quite self explanatory. Negative means you have borrowed money. BASE is the net of your balances converted into base currency.

When you initially do a futures trade in a non BASE country you will have to borrow money for initial margin. Only if you move into profit beyond this will you have no net borrowing.IB charges you for borrowing money! This is done at LIBOR+spread so is expensive for currencies with higher interest rates (this spread is also why I use IMM's to get direct currency exposure). You can flatten out your exposure by doing a spot FX trade. Personally I try and keep a small positive balance in all currencies, although not excessive as thismeans I am taking on currency risk. Note you can't trade all possible pairs eg if you find you can't buy AUDGBP then try selling GBPAUD instead. The exception is Korea where you can't hold any speculative currency exposure i.e. not arising from margin requirements in other kinds of trading. All you are allowed to do is flatten your Korean currency position back to zero.

There are many greater keywords than proven above. The fine advice I even have for looking to recognize what they all suggest is first of all a smooth simulated account (a demo account is no good since you are exposed to other peoples random buying and selling, and the account will often be 'empty'). Take a dump of the account cost output, then do a alternate. Take any other dump, then watch for charges to transport. By evaluating each unload you have to be capable of see how account value, margin, coins and so on have interaction. This is pretty time ingesting but truly really worth it for an perception into how the IB accounts function for the sort of gadgets you want to change.

Accounting updates

The next kind of data we get are accounting updates. I won't go through the code in detail, suffice to say it's very similar to accounting values, except that it's returning things populated by the updatePortfolio method in the wrapper; these are labelled in the joint queue with ACCOUNT_UPDATE_FLAG:

accounting_updates = app.Get_accounting_updates(accountName)
print(accounting_updates)

[(140109274417416: 56825063,GE,FUT,20181217,0.0,0,2500,,GLOBEX,USD,GEZ8,GE,False,,combo:, 10.0, 97.93250275, 2448312.57, 244889.9, -586.43, 0.0)]

This is a tuple with (contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL) A nice touch is to combine this with the information you get from get positions above: I leave this as an exercise to the reader!

Note: for completeness please note that you can also app.get_accounting_time_from_server(self, accountName) asdfto access the results from the wrapper method updateAccountTime although I don't bother myself.

Anything missing?

I have not covered the overall gamut of what you can get from the IB API. There is a wealthy style of information this is available. I haven't looked at information, fundamental records, option records, scanners and controlled debts because I do not use them. However I desire there's enough meat in this collection of examples to get you started out using IB with the new python API, and to avoid losing time trying to recognize a number of the more strange behaviour.

This is the final of a sequence of five posts on building a simple interface in python to the IB API the use of swigiby. The first 4 posts are:

http://qoppac.Blogspot.Co.United kingdom/2017/03/interactive-brokers-native-python-api.Html

http://qoppac.Blogspot.Co.United kingdom/2017/03/ancient-data-from-local-ib-pyhon-api.Html

http://qoppac.Blogspot.Co.United kingdom/2017/03/streaming-market-information-from-native.Html

http://qoppac.Blogspot.Co.United kingdom/2017/03/setting-orders-in-local-python-ib-api.Html

If you've got found this series useful then your next steps is probably tolearn a way to design a systematic trading approach, use a python backtester to check your strategy, and tounderstand the nuts and bolts of making a completely computerized device.

Finish
Bagikan ke Facebook

Artikel Terkait

Lanjut