softwarespartan / IB4m

Interactive Brokers API for Matlab
GNU General Public License v2.0
62 stars 21 forks source link

Examples of using bracket orders? #29

Closed bginvestor closed 6 years ago

bginvestor commented 6 years ago

Hi Abel,

Per our email discussion, I was looking for any examples of using bracket orders. Here's the code stated in IB's API manual. Thank you very much!

Bginvestor

public static List BracketOrder(int parentOrderId, String action, double quantity, double limitPrice, double takeProfitLimitPrice, double stopLossPrice) { //This will be our main or "parent" order Order parent = new Order(); parent.orderId(parentOrderId); parent.action(action); parent.orderType("LMT"); parent.totalQuantity(quantity); parent.lmtPrice(limitPrice); //The parent and children orders will need this attribute set to false to prevent accidental executions. //The LAST CHILD will have it set to true. parent.transmit(false);

    Order takeProfit = new Order();
    takeProfit.orderId(parent.orderId() + 1);
    takeProfit.action(action.equals("BUY") ? "SELL" : "BUY");
    takeProfit.orderType("LMT");
    takeProfit.totalQuantity(quantity);
    takeProfit.lmtPrice(takeProfitLimitPrice);
    takeProfit.parentId(parentOrderId);
    takeProfit.transmit(false);

    Order stopLoss = new Order();
    stopLoss.orderId(parent.orderId() + 2);
    stopLoss.action(action.equals("BUY") ? "SELL" : "BUY");
    stopLoss.orderType("STP");
    //Stop trigger price
    stopLoss.auxPrice(stopLossPrice);
    stopLoss.totalQuantity(quantity);
    stopLoss.parentId(parentOrderId);
    //In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to true
    //to activate all its predecessors
    stopLoss.transmit(true);

    List<Order> bracketOrder = new ArrayList<>();
    bracketOrder.add(parent);
    bracketOrder.add(takeProfit);
    bracketOrder.add(stopLoss);

    return bracketOrder;
}

... List bracket = OrderSamples.BracketOrder(nextOrderId++, "BUY", 100, 30, 40, 20); for(Order o : bracket) { client.placeOrder(o.orderId(), ContractSamples.EuropeanStock(), o); }

softwarespartan commented 6 years ago

Hi Brian

Apologies for delay, was traveling all week.

This should be fairly straight forward. It is just configuring a sequence of orders to perform the “bracket” function

For example the parent order is configured

% bracket order parameters action = 'BUY'; quantity = 100 ; limitPrice = 58.45; parentOrderId = 12345;

% init parent order parent = com.ib.client.Order();

% configure parent order parent.m_orderId = parentOrderId; parent.m_action = action ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_transmit = 0 ;

If you need a valid orderId, you can use the TWS.NextOrderId.

Let me know if need anything additional or have follow up questions.

Cheers -abel

On Jun 23, 2018, at 3:43 PM, bginvestor notifications@github.com wrote:

Hi Abel,

Per our email discussion, I was looking for any examples of using bracket orders. Here's the code stated in IB's API manual. Thank you very much!

Bginvestor

public static List BracketOrder(int parentOrderId, String action, double quantity, double limitPrice, double takeProfitLimitPrice, double stopLossPrice) { //This will be our main or "parent" order Order parent = new Order(); parent.orderId(parentOrderId); parent.action(action); parent.orderType("LMT"); parent.totalQuantity(quantity); parent.lmtPrice(limitPrice); //The parent and children orders will need this attribute set to false to prevent accidental executions. //The LAST CHILD will have it set to true. parent.transmit(false);

Order takeProfit = new Order();
takeProfit.orderId(parent.orderId() + 1);
takeProfit.action(action.equals("BUY") ? "SELL" : "BUY");
takeProfit.orderType("LMT");
takeProfit.totalQuantity(quantity);
takeProfit.lmtPrice(takeProfitLimitPrice);
takeProfit.parentId(parentOrderId);
takeProfit.transmit(false);

Order stopLoss = new Order();
stopLoss.orderId(parent.orderId() + 2);
stopLoss.action(action.equals("BUY") ? "SELL" : "BUY");
stopLoss.orderType("STP");
//Stop trigger price
stopLoss.auxPrice(stopLossPrice);
stopLoss.totalQuantity(quantity);
stopLoss.parentId(parentOrderId);
//In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to true
//to activate all its predecessors
stopLoss.transmit(true);

List<Order> bracketOrder = new ArrayList<>();
bracketOrder.add(parent);
bracketOrder.add(takeProfit);
bracketOrder.add(stopLoss);

return bracketOrder;

} ... List bracket = OrderSamples.BracketOrder(nextOrderId++, "BUY", 100, 30, 40, 20); for(Order o : bracket) { client.placeOrder(o.orderId(), ContractSamples.EuropeanStock(), o); }

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1IupmGA3IFB2z6uvK0hxhcoMV8gyks5t_ppqgaJpZM4U06J7.

bginvestor commented 6 years ago

Abel, Thank you very much! This is a huge help, not sure I would have figured this out with my limited knowledge of the API.

Thank you! BG

bginvestor commented 6 years ago

Hi Abel,

Ok, I'm banging my head on the wall! lol

Trying to execute this bracket order. However, I'm not getting any orders to the API even using your "orderplacementexample.m"

I'm missing something. I am working outside of regular trading hours, don't know how to turn on outsideRth with your orderfactory.

In any case, I'm trying to get this script to work. Please see below, greatly appreciate any feedback. When I execute eClientSocket.placeOrder, its accepts with no error, but does not send the order through to TWS. How can I ping the system to determine what's going? Thank you.

%% Test example to properly setup a bracket order via IB PaperTrade

% initialize a message handler for servers callbacks handler = com.tws.Handler();

% create a connection objects to TWS linked to our message handler eClientSocket = com.ib.client.EClientSocket(handler);

% connect to TWS eClientSocket.eConnect('127.0.0.1',7496,0); pause(0.5)

contract = com.ib.client.Contract(); % fields(contract) contract.m_symbol = 'SPY'; contract.m_secType = 'STK'; contract.m_exchange = 'SMART'; contract.m_currency = 'USD';

% order = com.ib.client.Order() % fields(order)

% bracket order parameters action = 'BUY'; quantity = 100 ; limitPrice = 270.00; parentOrderId = 8863; % < -- nextValidId()

% init & configure parent order parent = com.ib.client.Order(); parent.m_orderId = parentOrderId;
parent.m_account = 'XXXXXXX' ; <-- my account # parent.m_action = action ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_outsideRth = 1 ; parent.m_transmit = 0 ;

% init & configure takeProfit order takeProfit = com.ib.client.Order();

%IBApi.Order.ParentId attribute by assigning a child order's ... IBApi.Order.ParentId to an existing order's IBApi.Order.OrderId takeProfit.m_parentId = parentOrderId; takeProfit.m_action = 'SELL' ;
takeProfit.m_orderType = 'LMT' ; takeProfit.m_totalQuantity = quantity ; takeProfit.m_lmtPrice = limitPrice * 1.05; takeProfit.m_outsideRth = 1 ; takeProfit.m_transmit = 0 ;

% init & configure StopLoss order StopLoss = com.ib.client.Order(); StopLoss.m_parentId = parentOrderId ; StopLoss.m_action = 'SELL' ; StopLoss.m_orderType = 'STP' ; StopLoss.m_totalQuantity = quantity ; StopLoss.m_lmtPrice = limitPrice * .95 ; StopLoss.m_outsideRth = 1 ; StopLoss.m_transmit = 1 ; %<- last child requires true

% place the order eClientSocket.placeOrder(parentOrderId,contract,parent);

softwarespartan commented 6 years ago

Ok, let me check

Can you place simple orders?

Are you able to do other things like get account info through the api?

You should definitely be using the TWS.Session.getInstance() to automatically setup handler etc etc

Then use session to connect

Session also sets up the event callbacks for printing errors etc.

Sent from my iPhone

On Jul 5, 2018, at 2:30 AM, bginvestor notifications@github.com wrote:

Hi Abel,

Ok, I'm banging my head on the wall! lol

Trying to execute this bracket order. However, I'm not getting any orders to the API even using your "orderplacementexample.m"

I'm missing something. I am working outside of regular trading hours, don't know how to turn on outsideRth with your orderfactory.

In any case, I'm trying to get this script to work. Please see below, greatly appreciate any feedback. When I execute eClientSocket.placeOrder, its accepts with no error, but does not send the order through to TWS. How can I ping the system to determine what's going? Thank you.

%% Test example to properly setup a bracket order via IB PaperTrade

% initialize a message handler for servers callbacks handler = com.tws.Handler();

% create a connection objects to TWS linked to our message handler eClientSocket = com.ib.client.EClientSocket(handler);

% connect to TWS eClientSocket.eConnect('127.0.0.1',7496,0); pause(0.5)

contract = com.ib.client.Contract(); % fields(contract) contract.m_symbol = 'SPY'; contract.m_secType = 'STK'; contract.m_exchange = 'SMART'; contract.m_currency = 'USD';

% order = com.ib.client.Order() % fields(order)

% bracket order parameters action = 'BUY'; quantity = 100 ; limitPrice = 270.00; parentOrderId = 8863; % < -- nextValidId()

% init & configure parent order parent = com.ib.client.Order(); parent.m_orderId = parentOrderId; parent.m_account = 'XXXXXXX' ; <-- my account # parent.m_action = action ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_outsideRth = 1 ; parent.m_transmit = 0 ;

% init & configure takeProfit order takeProfit = com.ib.client.Order();

%IBApi.Order.ParentId attribute by assigning a child order's ... IBApi.Order.ParentId to an existing order's IBApi.Order.OrderId takeProfit.m_parentId = parentOrderId; takeProfit.m_action = 'SELL' ; takeProfit.m_orderType = 'LMT' ; takeProfit.m_totalQuantity = quantity ; takeProfit.m_lmtPrice = limitPrice * 1.05; takeProfit.m_outsideRth = 1 ; takeProfit.m_transmit = 0 ;

% init & configure StopLoss order StopLoss = com.ib.client.Order(); StopLoss.m_parentId = parentOrderId ; StopLoss.m_action = 'SELL' ; StopLoss.m_orderType = 'STP' ; StopLoss.m_totalQuantity = quantity ; StopLoss.m_lmtPrice = limitPrice * .95 ; StopLoss.m_outsideRth = 1 ; StopLoss.m_transmit = 1 ; %<- last child requires true

% place the order eClientSocket.placeOrder(parentOrderId,contract,parent);

— You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.

bginvestor commented 6 years ago

Abel, I found part of my problem, when I get a connection closed status , I cannot send out orders. Don't know why I am getting a connection closed status? I was able to successfully send out an order once when I did not get a connection close.

Do I need to close the session before activating another eClientSocket.eConnect('127.0.0.1',7496,0); ?

Here's the script and output:

% initialize a message handler for servers callbacks handler = com.tws.Handler();

% create a connection objects to TWS linked to our message handler eClientSocket = com.ib.client.EClientSocket(handler);

% connect to TWS eClientSocket.eConnect('127.0.0.1',7496,0);

command window output: eClientSocket.eConnect('127.0.0.1',7496,0); Server Version:76 TWS Time at connection:20180705 07:12:07 MST connection closed …

Thank you!!

softwarespartan commented 6 years ago

I can double check this afternoon

But, you can avoid all this connection debugging by just using

sess = TWS.Session.getInstance() sess.eClientSocket.connect ...

On Thu, Jul 5, 2018 at 10:14 AM bginvestor notifications@github.com wrote:

Abel, I found part of my problem, when I get a connection closed status , I cannot send out orders. Don't know why I am getting a connection closed status? I was able to successfully send out an order once when I did not get a connection close.

Do I need to close the session before activating another eClientSocket.eConnect('127.0.0.1',7496,0); ?

Here's the script and output:

% initialize a message handler for servers callbacks handler = com.tws.Handler();

% create a connection objects to TWS linked to our message handler eClientSocket = com.ib.client.EClientSocket(handler);

% connect to TWS eClientSocket.eConnect('127.0.0.1',7496,0);

command window output: eClientSocket.eConnect('127.0.0.1',7496,0); Server Version:76 TWS Time at connection:20180705 07:12:07 MST connection closed …

Thank you!!

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402736128, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1MqIyyp8GxscBEiswHbI18Lm2FCjks5uDh8ogaJpZM4U06J7 .

bginvestor commented 6 years ago

Hi Abel,

I got it! Starting to learn more about how this API language is working .. Thank you!

Below is a start to finish example of a bracket order using EUR.USD

%% Start to Finish Example of setting up bracket order w/ EUR.USD % Thanks Abel!!

session = TWS.Session.getInstance();

% create local buffer for contract details events [buf,lh] = TWS.initBufferForEvent(TWS.Events.NEXTORDERID);

% establish connection with TWS session.eClientSocket.eConnect('127.0.0.1',7496,0);

% request the next order id session.eClientSocket.reqIds(true); pause(0.5)

% blab about it fprintf('the next order id is: %d\n',buf.get().data.nextOrderId);

contract = com.ib.client.Contract(); % fields(contract)

contract.m_symbol = 'EUR'; contract.m_secType = 'CASH'; contract.m_exchange = 'IDEALPRO'; contract.m_currency = 'USD';

% bracket order parameters action = 'BUY'; quantity = 100000; limitPrice = 1.1690; parentOrderId = buf.get().data.nextOrderId; % < -- nextValidId()

% init & configure parent order % fields(parent)

parent = com.ib.client.Order(); parent.m_orderId = parentOrderId;
parent.m_account = 'xxxxxxx' ; % use your account # parent.m_action = action ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_outsideRth = 1 ; parent.m_transmit = 0 ;

% init & configure takeProfit order ProfitTaker = com.ib.client.Order();

%IBApi.Order.ParentId attribute by assigning a child order's ... IBApi.Order.ParentId to an existing order's IBApi.Order.OrderId ProfitTaker.m_orderId = parentOrderId+1 ;
ProfitTaker.m_parentId = parentOrderId ; ProfitTaker.m_action = 'SELL' ;
ProfitTaker.m_orderType = 'LMT' ; ProfitTaker.m_totalQuantity = quantity ; ProfitTaker.m_lmtPrice = 1.1695 ; ProfitTaker.m_outsideRth = 1 ; ProfitTaker.m_transmit = 0 ;

% init & configure StopLoss order StopLoss = com.ib.client.Order(); StopLoss.m_orderId = parentOrderId+2 ; StopLoss.m_parentId = parentOrderId ; StopLoss.m_action = 'SELL' ; StopLoss.m_orderType = 'STP' ; StopLoss.m_totalQuantity = quantity ; StopLoss.m_auxPrice = 1.1685 ; StopLoss.m_outsideRth = 1 ; StopLoss.m_transmit = 1 ; %<- last child requires true

% place the order session.eClientSocket.placeOrder(parent.m_orderId,contract,parent); session.eClientSocket.placeOrder(ProfitTaker.m_orderId,contract,ProfitTaker); session.eClientSocket.placeOrder(StopLoss.m_orderId,contract,StopLoss);

bginvestor commented 6 years ago

Hi Abel,

I wanted to let you know that I got the bracket orders working. I posted a clean example on your site.

Again, thanks for all the help. This will be part of my “expert advisor” script that I’m working on for trading forex using volume profile. This is going to save me a bunch of time and will be very accurate.

On a different note. If I wanted to manually terminate the session.eClientSocket.eConnect('127.0.0.1',7496,0); what command do I use? Also, do you have a command to check the integrity of the connection? I would like to do this before running a few functions.

You’re the man! Thanks.

BG

softwarespartan commented 6 years ago

That’s great!

I was literally typing a response back to you when your message came in.

I’ll just send this code for completeness for the SPY example.

Don’t hesitate to reach out if you need anything additional.

Cheers -abel

% init session with TWS session = TWS.Session.getInstance();

% connect with TWS application session.eClientSocket.eConnect('127.0.0.1',7496,0);

% init helper for next order id nid = TWS.NextOrderId.getInstance();

% helpful if response from TWS is long for nextId pause(0.5)

% init contract contract = com.ib.client.Contract();

% configure contract contract.m_symbol = 'SPY' ; contract.m_secType = 'STK' ; contract.m_exchange = 'SMART'; contract.m_currency = 'USD' ;

% bracket order parameters action = 'BUY' ; quantity = 100 ; limitPrice = 273.00 ; profitPrice = 275.00 ; lossPrice = 271.00 ; parentOrderId = nid.nextOrderId;

% init orders parent = com.ib.client.Order(); takeProfit = com.ib.client.Order(); stopLoss = com.ib.client.Order();

% configure parent order parent.m_orderId = parentOrderId ; parent.m_account = 'DU123456' ; parent.m_action = 'BUY' ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_outsideRth = true ; parent.m_transmit = false ;

% configure take profit order takeProfit.m_orderId = parent.m_orderId+1; takeProfit.m_account = 'DU123456' ; takeProfit.m_action = 'SELL' ; takeProfit.m_orderType = 'LMT' ; takeProfit.m_totalQuantity = quantity ; takeProfit.m_lmtPrice = profitPrice ; takeProfit.m_parentId = parent.m_orderId ; takeProfit.m_outsideRth = true ; takeProfit.m_transmit = false ;

% configure the stop loss order stopLoss.m_orderId = parent.m_orderId+2; stopLoss.m_account = 'DU123456' ; stopLoss.m_action = 'SELL' ; stopLoss.m_orderType = 'STP' ; stopLoss.m_totalQuantity = quantity ; stopLoss.m_auxPrice = lossPrice ; stopLoss.m_parentId = parent.m_orderId ; stopLoss.m_outsideRth = true ; stopLoss.m_transmit = true ;

% package up the bracket order bracketOrder = [parent,takeProfit,stopLoss];

% iterate over orders and place for i = 1:numel(bracketOrder)

% get the ith order
order = bracketOrder(i);

% place the order
session.eClientSocket.placeOrder(order.m_orderId,contract,order)

end

On Jul 5, 2018, at 8:54 PM, bginvestor notifications@github.com wrote:

Hi Abel,

I got it! Starting to learn more about how this API language is working .. Thank you!

Below is a start to finish example of a bracket order using EUR.USD

%% Start to Finish Example of setting up bracket order w/ EUR.USD % Thanks Abel!!

session = TWS.Session.getInstance();

% create local buffer for contract details events [buf,lh] = TWS.initBufferForEvent(TWS.Events.NEXTORDERID);

% establish connection with TWS session.eClientSocket.eConnect('127.0.0.1',7496,0);

% request the next order id session.eClientSocket.reqIds(true); pause(0.5)

% blab about it fprintf('the next order id is: %d\n',buf.get().data.nextOrderId);

contract = com.ib.client.Contract(); % fields(contract)

contract.m_symbol = 'EUR'; contract.m_secType = 'CASH'; contract.m_exchange = 'IDEALPRO'; contract.m_currency = 'USD';

% bracket order parameters action = 'BUY'; quantity = 100000; limitPrice = 1.1690; parentOrderId = buf.get().data.nextOrderId; % < -- nextValidId()

% init & configure parent order % fields(parent)

parent = com.ib.client.Order(); parent.m_orderId = parentOrderId; parent.m_account = 'DU528204' ; parent.m_action = action ; parent.m_orderType = 'LMT' ; parent.m_totalQuantity = quantity ; parent.m_lmtPrice = limitPrice ; parent.m_outsideRth = 1 ; parent.m_transmit = 0 ;

% init & configure takeProfit order ProfitTaker = com.ib.client.Order();

%IBApi.Order.ParentId attribute by assigning a child order's ... IBApi.Order.ParentId to an existing order's IBApi.Order.OrderId ProfitTaker.m_orderId = parentOrderId+1 ; ProfitTaker.m_parentId = parentOrderId ; ProfitTaker.m_action = 'SELL' ; ProfitTaker.m_orderType = 'LMT' ; ProfitTaker.m_totalQuantity = quantity ; ProfitTaker.m_lmtPrice = 1.1695 ; ProfitTaker.m_outsideRth = 1 ; ProfitTaker.m_transmit = 0 ;

% init & configure StopLoss order StopLoss = com.ib.client.Order(); StopLoss.m_orderId = parentOrderId+2 ; StopLoss.m_parentId = parentOrderId ; StopLoss.m_action = 'SELL' ; StopLoss.m_orderType = 'STP' ; StopLoss.m_totalQuantity = quantity ; StopLoss.m_auxPrice = 1.1685 ; StopLoss.m_outsideRth = 1 ; StopLoss.m_transmit = 1 ; %<- last child requires true

% place the order session.eClientSocket.placeOrder(parent.m_orderId,contract,parent); session.eClientSocket.placeOrder(ProfitTaker.m_orderId,contract,ProfitTaker); session.eClientSocket.placeOrder(StopLoss.m_orderId,contract,StopLoss);

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402893238, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1AQf7LlKslkmVs5UUztQp2kAMKToks5uDrUogaJpZM4U06J7.

softwarespartan commented 6 years ago

No problem. Always happy to help.

At some point in your code you need to call ' session.eClientSocket.eConnect’

As silly as it sounds, it’s not always clear which part of the code does/should have responsibility for connecting.

I myself write all functions to assume the the session is connected. Then i have high level strategies that init the session and connect at the top and then all the execution code doesn’t have to worry about it. This avoids every part of the code calling ‘connect’ over and over and over. And, avoids a bunch of control flow logic like ‘if isConnected then do this else do that’. Too much control flow gets really hard to debug very fast.

But keep in mind, there is no penalty for calling ‘eConnect’ many many times. TWS will just respond with something like “already connected” and ignore your api call.

If all parts of the code call

sess = TWS.Session.getInstance()

then all get the same session object. Once it is connected one time then it is connected for everyone.

If you want to make an API call you can ask if the client is connected with

session.eClientSocket.isConnected()

which will return a boolean.

Cheers -abel

On Jul 5, 2018, at 9:10 PM, bginvestor notifications@github.com wrote:

Hi Abel,

I wanted to let you know that I got the bracket orders working. I posted a clean example on your site.

Again, thanks for all the help. This will be part of my “expert advisor” script that I’m working on for trading forex using volume profile. This is going to save me a bunch of time and will be very accurate.

On a different note. If I wanted to manually terminate the session.eClientSocket.eConnect('127.0.0.1',7496,0); what command do I use? Also, do you have a command to check the integrity of the connection? I would like to do this before running a few functions.

You’re the man! Thanks.

BG

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402895474, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1HR_lLGp477bVmH1YbMpjqXnzGa1ks5uDrjxgaJpZM4U06J7.

bginvestor commented 6 years ago

I was expanding my code to define multiple bracket orders.

I get this warning after the first successful bracket order , “8929 105 Order being modified does not match original order”

To resolve, I needed to use clear all each time to reconnect and submit. This is not really a solution.

Maybe I need to disconnect and reconnect each time I send a bracket order? Is there a command to close session.eClientSocket.eConnect and restart? Or do you have any suggestions?

Thanks for getting me started. BG

Sent from Mail for Windows 10

From: Abel Brown Sent: Thursday, July 5, 2018 6:35 PM To: softwarespartan/IB4m Cc: bginvestor; Author Subject: Re: [softwarespartan/IB4m] Examples of using bracket orders? (#29)

No problem. Always happy to help.

At some point in your code you need to call ' session.eClientSocket.eConnect’

As silly as it sounds, it’s not always clear which part of the code does/should have responsibility for connecting.

I myself write all functions to assume the the session is connected. Then i have high level strategies that init the session and connect at the top and then all the execution code doesn’t have to worry about it. This avoids every part of the code calling ‘connect’ over and over and over. And, avoids a bunch of control flow logic like ‘if isConnected then do this else do that’. Too much control flow gets really hard to debug very fast.

But keep in mind, there is no penalty for calling ‘eConnect’ many many times. TWS will just respond with something like “already connected” and ignore your api call.

If all parts of the code call

sess = TWS.Session.getInstance()

then all get the same session object. Once it is connected one time then it is connected for everyone.

If you want to make an API call you can ask if the client is connected with

session.eClientSocket.isConnected()

which will return a boolean.

Cheers -abel

On Jul 5, 2018, at 9:10 PM, bginvestor notifications@github.com wrote:

Hi Abel,

I wanted to let you know that I got the bracket orders working. I posted a clean example on your site.

Again, thanks for all the help. This will be part of my “expert advisor” script that I’m working on for trading forex using volume profile. This is going to save me a bunch of time and will be very accurate.

On a different note. If I wanted to manually terminate the session.eClientSocket.eConnect('127.0.0.1',7496,0); what command do I use? Also, do you have a command to check the integrity of the connection? I would like to do this before running a few functions.

You’re the man! Thanks.

BG

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402895474, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1HR_lLGp477bVmH1YbMpjqXnzGa1ks5uDrjxgaJpZM4U06J7.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

softwarespartan commented 6 years ago

I think this is just an issue with the order ids

be sure to manually increment to account for all the orders placed …

OrderIds are just numbers used for ID meaning that there is nothing special about them.

You can increment by 10 or by 100 each time, whatever … the ids just have to be unique.

If for some reason things get way out of hand while testing an algo or something, there is option in TWS settings to reset all IDs and begins back at 1 again.

Cheers -abel

On Jul 5, 2018, at 9:59 PM, bginvestor notifications@github.com wrote:

I was expanding my code to define multiple bracket orders.

I get this warning after the first successful bracket order , “8929 105 Order being modified does not match original order”

To resolve, I needed to use clear all each time to reconnect and submit. This is not really a solution.

Maybe I need to disconnect and reconnect each time I send a bracket order? Is there a command to close session.eClientSocket.eConnect and restart? Or do you have any suggestions?

Thanks for getting me started. BG

Sent from Mail for Windows 10

From: Abel Brown Sent: Thursday, July 5, 2018 6:35 PM To: softwarespartan/IB4m Cc: bginvestor; Author Subject: Re: [softwarespartan/IB4m] Examples of using bracket orders? (#29)

No problem. Always happy to help.

At some point in your code you need to call ' session.eClientSocket.eConnect’

As silly as it sounds, it’s not always clear which part of the code does/should have responsibility for connecting.

I myself write all functions to assume the the session is connected. Then i have high level strategies that init the session and connect at the top and then all the execution code doesn’t have to worry about it. This avoids every part of the code calling ‘connect’ over and over and over. And, avoids a bunch of control flow logic like ‘if isConnected then do this else do that’. Too much control flow gets really hard to debug very fast.

But keep in mind, there is no penalty for calling ‘eConnect’ many many times. TWS will just respond with something like “already connected” and ignore your api call.

If all parts of the code call

sess = TWS.Session.getInstance()

then all get the same session object. Once it is connected one time then it is connected for everyone.

If you want to make an API call you can ask if the client is connected with

session.eClientSocket.isConnected()

which will return a boolean.

Cheers -abel

On Jul 5, 2018, at 9:10 PM, bginvestor notifications@github.com wrote:

Hi Abel,

I wanted to let you know that I got the bracket orders working. I posted a clean example on your site.

Again, thanks for all the help. This will be part of my “expert advisor” script that I’m working on for trading forex using volume profile. This is going to save me a bunch of time and will be very accurate.

On a different note. If I wanted to manually terminate the session.eClientSocket.eConnect('127.0.0.1',7496,0); what command do I use? Also, do you have a command to check the integrity of the connection? I would like to do this before running a few functions.

You’re the man! Thanks.

BG

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402895474, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1HR_lLGp477bVmH1YbMpjqXnzGa1ks5uDrjxgaJpZM4U06J7.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402902699, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1L5BuTmm7XbizPOKHhyLrUOpZLnCks5uDsSUgaJpZM4U06J7.

softwarespartan commented 6 years ago

I put updated bracketOrderSample into the repo here

https://github.com/softwarespartan/IB4m/blob/master/examples/bracketOrderSample.m https://github.com/softwarespartan/IB4m/blob/master/examples/bracketOrderSample.m

If use the TWS.NextOrderId() class to set the order ids it will increment appropriately for multiple bracket orders to avoid the error 8929

Cheers -abel

On Jul 5, 2018, at 9:59 PM, bginvestor notifications@github.com wrote:

I was expanding my code to define multiple bracket orders.

I get this warning after the first successful bracket order , “8929 105 Order being modified does not match original order”

To resolve, I needed to use clear all each time to reconnect and submit. This is not really a solution.

Maybe I need to disconnect and reconnect each time I send a bracket order? Is there a command to close session.eClientSocket.eConnect and restart? Or do you have any suggestions?

Thanks for getting me started. BG

Sent from Mail for Windows 10

From: Abel Brown Sent: Thursday, July 5, 2018 6:35 PM To: softwarespartan/IB4m Cc: bginvestor; Author Subject: Re: [softwarespartan/IB4m] Examples of using bracket orders? (#29)

No problem. Always happy to help.

At some point in your code you need to call ' session.eClientSocket.eConnect’

As silly as it sounds, it’s not always clear which part of the code does/should have responsibility for connecting.

I myself write all functions to assume the the session is connected. Then i have high level strategies that init the session and connect at the top and then all the execution code doesn’t have to worry about it. This avoids every part of the code calling ‘connect’ over and over and over. And, avoids a bunch of control flow logic like ‘if isConnected then do this else do that’. Too much control flow gets really hard to debug very fast.

But keep in mind, there is no penalty for calling ‘eConnect’ many many times. TWS will just respond with something like “already connected” and ignore your api call.

If all parts of the code call

sess = TWS.Session.getInstance()

then all get the same session object. Once it is connected one time then it is connected for everyone.

If you want to make an API call you can ask if the client is connected with

session.eClientSocket.isConnected()

which will return a boolean.

Cheers -abel

On Jul 5, 2018, at 9:10 PM, bginvestor notifications@github.com wrote:

Hi Abel,

I wanted to let you know that I got the bracket orders working. I posted a clean example on your site.

Again, thanks for all the help. This will be part of my “expert advisor” script that I’m working on for trading forex using volume profile. This is going to save me a bunch of time and will be very accurate.

On a different note. If I wanted to manually terminate the session.eClientSocket.eConnect('127.0.0.1',7496,0); what command do I use? Also, do you have a command to check the integrity of the connection? I would like to do this before running a few functions.

You’re the man! Thanks.

BG

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402895474, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1HR_lLGp477bVmH1YbMpjqXnzGa1ks5uDrjxgaJpZM4U06J7.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/softwarespartan/IB4m/issues/29#issuecomment-402902699, or mute the thread https://github.com/notifications/unsubscribe-auth/AEWq1L5BuTmm7XbizPOKHhyLrUOpZLnCks5uDsSUgaJpZM4U06J7.