Broker API - Options Questions

Posted By: AndrewAMD

Broker API - Options Questions - 07/11/17 02:11

Hello,

I'm writing options features into the Ally Invest plugin, and I have three questions:

#1 - What is the correct procedure for writing the BrokerCommand GET_OPTIONS function? Am I supposed to build up an array of CONTRACT's and then copy it to the DWORD like so...

Code:
BrokerCommand (int nCommand, DWORD dwParameter)
{
// the below code is for nCommand=="GET_OPTIONS"

std::vector <CONTRACT> contracts;
// send request to server, 
// get response from server
// parse data into contracts vector

// here's the part I'm not sure about:
dwParameter = (DWORD)contracts.data();
return contracts.size();
}

If not, please point me in the right direction.


#2 - I see that I have two symbol definitions... One is in SET_SYMBOL, and one is char* Asset. If a user wants to buy/sell an option, would the option symbol be defined in SET_SYMBOL or in char* Asset? Will there be cases where I would have to use one and override the other? Is SET_SYMBOL strictly for usage with BrokerCommand?

#3 - Will a user need the options symbols all individually in the AssetFix.csv file?

I appreciate any clarifications. Thanks.

Andrew


EDIT - I did eventually fix the above snippet. I'll document it here.
Code:
BrokerCommand (int nCommand, DWORD dwParameter)
{
// the below code is for nCommand=="GET_OPTIONS"

//this next line is a pointer to an array of 10,000 elements.
CONTRACT* contracts_ptr = (CONTRACT*)dwParameter;

std::vector <CONTRACT> contracts;
// send request to server, 
// get response from server
// parse data into contracts vector

// I copied vector elements to the pointer, not to exceed 10,000 elements.
int i;
for (i = 0; i < Contracts.size() && i < 10000; i++)
{
	contracts_ptr[i] = Contracts[i];
}
return i;
}

Posted By: jcl

Re: Broker API - Options Questions - 07/11/17 09:05

I only know #3 - you need the underlying only in the asset list. About 1 and 2 I'll inquire and post later.
Posted By: jcl

Re: Broker API - Options Questions - 07/11/17 11:04

Ok, for getting the contract chain first SET_SYMBOL, SET_MULTIPLIER, SET_CLASS is called, then GET_OPTIONS with an array of 10000 CONTRACT structs.

For buying and selling an option, the symbol is passed in char* Asset, coded in the way as described on the "IB" page of the manual.
Posted By: AndrewAMD

Re: Broker API - Options Questions - 07/11/17 18:08

Okay, it looks like I can get the CONTRACT array through, but I'm not sure why char* Asset is still coming through as "SPY", even after I selected an available contract. I might need to troubleshoot this a bit. Attached is a screenshot.



EDIT: char* Asset is only "SPY" the second time around. The real problem I need to solve is that Error 10.




EDIT 2: I got it! I moved the Multiplier = 100 line further down in the script.


Attached picture 002.PNG
Attached picture 003.PNG
Attached picture 004.PNG
Posted By: AndrewAMD

Re: Broker API - Options Questions - 07/12/17 03:17

Question #4: Below is the CONTRACT definition:
Code:
typedef struct CONTRACT
{
	DATE	time;			// or trading class
	float fAsk, fBid; // premium without multiplicator
	float fVal;			// open interest or multiplier
	float fVol; 
	float fUnl;			// underlying price
	float fStrike;
	long	Expiry;		// YYYYMMDD
	long	Type;			// PUT, CALL, FUTURE, EUROPEAN, BINARY - functions.h
} CONTRACT; // for options, futures, FOPs



4.a) DATE time: Is this supposed to be the expiration date? Also, what does "or trading class" mean, and how would it apply to options contracts? Is this just an IB thing?
4.b) float fVal: Am I supposed to use the SET_MULTIPLIER value or the actual multiplier for the asset?
Posted By: jcl

Re: Broker API - Options Questions - 07/13/17 16:56

The multiplier is asset specific, so you must set it after selecting the asset, like the other asset parameters.

The time is a union. In historical data it's the quote time, in option chains it's the first 8 bytes of the trading class.

Here's a section of the IB plugin code that loads the option chain into the CONTRACT structs:

Code:
void contractDetails(int id, const ContractDetails& CD )
{
	if(id != g_Id || !g_Contracts) return;
	Contract C = CD.summary;
	memset(g_Contracts,0,sizeof(CONTRACT));
	int Multiplier = atoi(C.multiplier.c_str());
	if(g_Multiplier > 0 
		&& g_Multiplier != Multiplier) return;
	if(*g_TradingClass 
		&& 0 != strcmpi(g_TradingClass,C.tradingClass.c_str())) return;
	if(C.secType == *SecType::FOP) {
		g_Contracts->Type = FUTURE | ((C.right == "C")? CALL : PUT);
		g_Contracts->fStrike = C.strike;
	} else if(C.secType == *SecType::OPT) {
		g_Contracts->Type = (C.right == "C"? CALL : PUT);
		g_Contracts->fStrike = C.strike;
	} else if(C.secType == *SecType::FUT) {
		g_Contracts->Type = FUTURE;
		g_Contracts->fStrike = 0;
	}
		strcpy_s((char*)g_Contracts,8,C.tradingClass.c_str());
	g_Contracts->Expiry = atoi(C.expiry.c_str());
	g_Contracts->fVal = Multiplier;
	g_Contracts++;
	if(++g_nContracts >= NUM_CONTRACTS) {
		g_End = TRUE;
		g_Contracts = NULL;
	}
}



Posted By: AndrewAMD

Re: Broker API - Options Questions - 07/21/17 15:47

Question #5:

What's the difference between GET_MARGININIT and GET_MARGINREQUIRED? Do either apply to options? to stocks?

Also, I understand that the margin required to sell an option to open is higher than to buy an option to open. Is there some way that I can/should differentiate between the two cases using these brokercommand functions? Does Zorro automatically calculate this?
Posted By: AndrewAMD

Re: Broker API - Options Questions - 07/26/17 11:23

Question #6:

This is more of an engineering question. I'm looking to place "combo" option orders, or "multi-leg" orders. Basically, you pay less commission for up to four simultaneous option orders. Below is an example of a two-leg order:
Code:
<FIXML xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2">
  <NewOrdMleg TmInForce="0" Px="-3.10" OrdTyp="2" Acct="12345678">
    <Ord OrdQty="4" PosEfct="O">
      <Leg Side="1" Strk="190" Mat="2014-01-18T00:00:00.000-05:00" MMY="201401" SecTyp="OPT" CFI="OC" Sym="IBM"/>
    </Ord>
    <Ord OrdQty="4" PosEfct="O">
      <Leg Side="2" Strk="200" Mat="2014-01-18T00:00:00.000-05:00" MMY="201401" SecTyp="OPT" CFI="OC" Sym="IBM"/>
    </Ord>
  </NewOrdMleg>
</FIXML>



Here's an example of how I can currently perform a four-leg order from a zorro script:
Code:
brokerCommand(SET_COMBO_LEGS,4);
// buy leg 1 <-- plugin saves leg, BrokerBuy returns ID from counter
// buy leg 2 <-- plugin saves leg, BrokerBuy returns ID from counter
// buy leg 3 <-- plugin saves leg, BrokerBuy returns ID from counter
// buy leg 4 <-- plugin executes order, BrokerBuy returns ID from counter or 0 if failure



SET_COMBO_LEGS would be a new BrokerCommand that sets the number of legs in a trade. If it's 2, BC will return 1 and execute on the second trade. 3, return 1, third trade, etc.

The problem with this approach is that I have three legs returning a successful trade, with the last one returning the actual status. If the last one returns a trade failure, then Zorro will think the first three trades were fine.

Is there some way that I can delay the return of the first 1-3 legs until I receive all of the legs and get a response from the server?
Posted By: jcl

Re: Broker API - Options Questions - 07/26/17 14:32

GET_MARGINREQUIRED was a relict and no one knows what it's supposed to mean, so it can be disregarded. Zorro uses anyway only the MarginCost parameter, which is the margin for the next trade with the current asset. Complex margin rules, as for options trading, must be calculated by script before opening the position, and MarginCost set to the result.

For the combo, I would send the 4 trades as usual, but store the IDs of the 3 previous legs and cancel them with cancelTrade() when the combo is not filled.
Posted By: AndrewAMD

Re: Broker API - Options Questions - 07/28/17 02:34

Then I'm pretty much done developing. laugh I just need to document a couple of things before I submit it for beta testing.
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/02/17 16:34

Originally Posted By: jcl
For buying and selling an option, the symbol is passed in char* Asset, coded in the way as described on the "IB" page of the manual.
jcl,

Is there some way that my plugin can define a futures/options/futures-options contract symbol so that Zorro's use of char* Asset always matches that of my broker?

I mean like this:
* Zorro calls GET_OPTIONS or GET_FUTURES.
* Plugin copies the CONTRACT structs and then return a **negative** number of contracts to indicate that the plugin has symbols to supply. Plugin saves the symbols.
* Zorro calls a new function GET_OPTIONS_SYMBOLS or GET_FUTURES_SYMBOLS. Zorro provides a pointer to an array of strings, and the plugin copies the symbols to the array of strings.
* The number of CONTRACT structs and symbols would therefore be identical.
* Any BrokerAsset, BrokerHistory2, and BrokerBuy call using one of these contracts would therefore use the respective symbol for char* Asset.

This would be especially helpful to me, since my SC plugin will be multi-broker.
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/06/17 17:36

bump
Posted By: jcl

Re: Broker API - Options Questions - 12/07/17 15:46

The symbols are fact already loaded, only it's an undocumented function because it's not used yet. The string is stored at the begin of any CONTRACT* struct in the Contracts list, instead of the date that is not needed in the options chain.

So, string Class = Contracts + ContractRow should get the symbol of the current contract.
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/07/17 17:26

Originally Posted By: jcl
The symbols are fact already loaded, only it's an undocumented function because it's not used yet. The Symbol string is stored at the begin of any CONTRACT* struct in the Contracts list, instead of the date that is not needed in the options chain.

So, string CSymbol = Contracts + ContractRow should get the symbol of the current contract.
Earlier in the thread, you gave me this line of code:
Code:
strcpy_s((char*)g_Contracts,8,C.tradingClass.c_str());

... and you said it was reserved for the trading class. Are you saying that this has been changed to the actual symbol?

Back to the struct...
Code:
typedef struct CONTRACT
{
	DATE	time;			// or trading class
	float fAsk, fBid; // premium without multiplier (f1,f2)
	float fVal;			// open interest or multiplier (f3)
	float fVol;			// volume (f4)
	float fUnl;			// unadjusted underlying price (f5)
	float fStrike;		// (f6)
	long	Expiry;		// YYYYMMDD (i7)
	long	Type;			// PUT, CALL, FUTURE, EUROPEAN, BINARY (s8)
} CONTRACT; // for options, futures, FOPs

"time" only has room for 8 characters... I don't think that's enough room for an options / futures / FOP symbol.

Did you mean that I can overwrite fAsk and fBid as well, giving me 16 characters?
Posted By: jcl

Re: Broker API - Options Questions - 12/08/17 07:35

No. I thought you were talking about the class. What is then a "symbol"?
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/08/17 11:34

The equivalent of char* Asset.
Posted By: jcl

Re: Broker API - Options Questions - 12/08/17 15:46

Like "AAPL" for Apple options?
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/08/17 16:29

I mean the complete "ticker symbol" to represent a specific future or option or futures option which, in the symbol itself, indicates:
* core or underlying symbol ("ES" for e-mini, "AAPL" for Apple)
* call or put or future, etc.
* futures expiration month (if applicable)
* strike price (if applicable)
* exchange (depending on the broker)

... all of those things in one string.

But you see, I have an engineering problem: The nomenclature is completely different for every broker, and I need a universal approach to support them all:
* IB has unique nomenclature
* TD Ameritrade has unique nomenclature
* CQG has unique nomenclature
* and so on.

I am already able to define the contract structs. I simply would like to be able to define the complete "ticker symbol" as well.

So I'm asking for a pointer to an array of strings - that way, I can give Zorro the complete "ticker symbols".

The intent is for BrokerAsset (and other plugin calls) to use this complete ticker symbol for char* Asset.

Is this possible?
Posted By: jcl

Re: Broker API - Options Questions - 12/08/17 16:46

Do you mean a code like "AAPL-OPT-150-20180303-USD"? That's not supplied by the plugin. It is an internal code used only by Zorro for sending strike, expiry and other parameters to the IB plugin. The API does not know this code. If broker APIs have similar codes in internal lists, they are then broker specific, and not used by Zorro.

Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/18/17 13:15

Originally Posted By: jcl
Do you mean a code like "AAPL-OPT-150-20180303-USD"? That's not supplied by the plugin. It is an internal code used only by Zorro for sending strike, expiry and other parameters to the IB plugin. The API does not know this code. If broker APIs have similar codes in internal lists, they are then broker specific, and not used by Zorro.

Yes, that's it! laugh

Did you know that Zorro has been sending IB codes to my Ally plugin for options, and that my plugin had to parse the IB codes and translate them to Ally codes? (Look at my source. I distinguish between "Zorro Assets" and "Ally Assets".)

This approach is not feasible for my new plugin, since it supports many brokers, and therefore many broker codes.

I have a new idea:

1) Zorro calls GET_OPTIONS or GET_FUTURES.
2) Plugin fills CONTRACT structs.

BUT... instead of filling in the exchange info for the time variable, the plugin sends a uint32_t value instead. This will act as an Asset ID number.

Before: strcpy to CONTRACT.time the exchange name, eight bytes max.
New approach: memcpy eight bytes to CONTRACT.time: "ID#\0xxxx", where "ID#\0" is a header, and "xxxx" is the uint32_t Asset ID number which the plugin has memorized.

Plugin will be responsible for memorizing the Asset broker code associated with each Asset ID number.

3) Plugin returns number of structs.

4) NEW FEATURE: Zorro will see that the plugin has filled out the CONTRACT time value in a certain way (such as with a header) and instead of sending an IB code upon BrokerAsset, will send a string indicating the ID number, so that my plugin can retrieve the broker code.

For example: "ID#123456789";

5) My plugin parses this string and retrieves the ID number. Now it knows what broker code to use.

Can this be implemented?
Posted By: AndrewAMD

Re: Broker API - Options Questions - 12/21/17 16:16

I came up with a workaround. It assumes that the trading class string will show up in the char* Asset string (the IB Asset code). I will document it here.

Basically, I encode a 32-bit unsigned int into a readable char string. This string gets copied into the CONTRACT struct.

"__abcde\0"

So my plan is to parse the IB code for the first instance of the double underscore "__".

Then the five characters ("abcde") can have up to 86 values each, giving me 86^5 possible values, which is greater than 2^32. I have some rules:
* The characters must be readable by a human.
* The characters must be able to be typed by an ordinary keyboard.
* The characters must be nonzero (not a null character).

Finally, there is a null character to terminate the string.

I will be testing this soon.
Posted By: jcl

Re: Broker API - Options Questions - 12/22/17 08:43

How about using the Zorro code also for your plugin? It is relatively easily to generate from the strike, expiration, etc. The class is stored at the begin of the CONTRACT struct and the exchange is converted to a number and stored in the Type field. That's all data you need. I can give you some code for the conversion.
© 2024 lite-C Forums