Creating contingent orders for Fidelity
Author: innertrader
Creation Date: 10/1/2011 11:29 PM
profile picture

innertrader

#1
As part of a trading strategy is there a programming procedure for creating and submitting contingent trades to Fidelity (see: http://personal.fidelity.com/products/trading/Trading_Platforms_Tools/Trading_Advanced_Order_Types.shtml.cvsr

e.g. "If .SPX goes above 1200, Buy XXX shares of UPRO at market"
profile picture

Cone

#2
No problem. You can do it 2 ways:

1. Run the script on .SPX, but when you enter a position trade, SetContext() to the symbol that you want to trade (and then always RestoreContext().)

2. If you want to trade 1 or more symbols using the same script, then just access .SPX data using GetExternalSymbol() and run it on the DataSet that you want to trade.

Which one?
profile picture

Eugene

#3
Just one thought: that contingent order can not buy UPRO at market at the same bar the .SPX goes above 1200. It can be next open (or this bar's close at best).
profile picture

innertrader

#4
I don't want to require WL place the trade on the secondary symbol in real-time (intraday). I want the WB strategy to stage a GTC Contingent Trade for Fidelity to execute if a price on the primary is met. The link in the initial post shows the capability Fidelity has. My question is whether WB has a matching procedure to generate such a trade.

The reason for doing it this way is that it does not require the WB application to be online and for me to place the trade manually during the day. The contingent order can be made before or at market open and the Fidelity trading backend will execute it intraday if trigger is met, even it WB is offline, or I am.
profile picture

innertrader

#5
To be more accurate about my goal I should revise the last sentence of the first paragraph of the above post to:

"My question is whether WB has a matching programming procedure to *stage such a contingent order for transmission to Fidelity.*"
profile picture

Cone

#6
True contingent orders are not supported by Wealth-Lab, but they probably by AT Pro. You'd have to call Fidelity support to know for sure.
profile picture

innertrader

#7
Eugene,

Regarding your post on 10/2/2011 in this thread:

Eugene wrote: "Just one thought: that contingent order can not buy UPRO at market at the same bar the .SPX goes above 1200. It can be next open (or this bar's close at best)."

Is this because WL generates alerts only at the completion of a bar, or because it cannot generate market orders in the same timeframe of the alert bar, or ...? In the real world, does WB monitor tick by tick (realtime) for reaching a threshhold (assuming streaming data is enabled)?

One example I am trying to code is a re-purposing of a "BuyAtStop" by having a buy stop of an index buy at market another symbol (by using SetContext). Since I am using 60-Minute timeframes, if the system cannot purchase within the timeframe (i.e. issue a market order for another symbol immediately when the stop is triggered on the index) then too much time might pass (up to 60 minutes) for the purchase of the ETF, which could materially affect the performance of the strategy.

I have succeeded so far in getting the basic ETF pairs (long / short) for the underlying symbol working, and the index "buys" and "sells" at the stop price in backtesting (theoretically, since I don't buy or sell the index directly, but use it to trigger another buy or sell), I cannot get the actual buy of the ETF to happen mid-bar of its price within the hour.

Here's the core logic that's involved:

if (SellAtStop( bar + 1, p, LowerChannel[bar] - Bars.SymbolInfo.Tick, x ))
{
SetContext(etfLong, true);
SellAtMarket(bar + 1, p, "Long");
SetContext(etfShort, true);
BuyAtMarket(bar + 1, "Short");
RestoreContext();
}

This code, for example, currently buys the Short ETF at the Open price of the same time bar of a SellAtStop trigger of the index(which, of course, is impossible in the real world). Please let me know your thoughts as to whether what I am trying to do is possible.
profile picture

Cone

#8
QUOTE:
Is this because WL generates alerts only at the completion of a bar
Right. Strategies are executed on complete bars only. That happens when a new bar enters the chart for streaming or when you press "Go", F5, or click on a new symbol.

The logic in the snippet is mistaken. if (SellAtStop( bar + 1... will always return false on the last bar of the chart (the bar on which Alerts are created), so the logic it modifies will never execute to create the AtMarket trades.

Just think about it: The logic is saying "if price reaches my stop trigger price sometime during the next bar, create some trades at the beginning of the bar." Impossible!
profile picture

innertrader

#9
Pending a response to my question I was thinking I had to change the ETF to bar + 2 for the reason you describe. I believe this is what you are saying and that the ETF alert will execute on the next bar (e.g. the Open, if At Market). Am I to understand that there is not a way to simulate Buy At Stop programmatically within the timeframe of a bar in the real world, although it does issue alerts within bars for backtesting? So it would only work if a XXXAtStop trade was placed with Fidelity and their system would trigger a market order in real time? Unfortunately, that approach won't work with derivative trades on the index.

I am struggling with a couple of other things. I can get my program to buy long or inverse ETFs, but I can't get it to sell either one of them. So it just keeps loading up on positions and never exits them. I think this is because the SellAtXXX function requires "p" and ChangeContext does not appear to change the value of p. What's the proper procedure for this?

Also, how can I get the buy/sell indicators to appear in the Panes where I have the ETFs plotted (as they do in the main Pane for the index)? Finally, is there a way to use the index to trigger another purchase (as I am doing), while preventing the system from trading the index (so it doesn't appear in my performance results)?
profile picture

Eugene

#10
QUOTE:
I was thinking I had to change the ETF to bar + 2 for the reason you describe.

Don't use "bar+N" where N is greater than 1.
QUOTE:
Am I to understand that there is not a way to simulate Buy At Stop programmatically within the timeframe of a bar in the real world, although it does issue alerts within bars for backtesting?

Yes, not possible. First, a complete bar updates, then your strategy executes over all the bars in the chart and determines if a signal on the next bar is to be generated. If it does, an order is placed for the next bar (strategy finishes for the current bar), otherwise no action.
QUOTE:
I can get my program to buy long or inverse ETFs, but I can't get it to sell either one of them.

How about downloading all available strategies (Open Strategy > Download...) and reviewing this working example among them: ActiveTrader 2011-05 | Inverse ETF switching system?
QUOTE:
Also, how can I get the buy/sell indicators to appear in the Panes where I have the ETFs plotted (as they do in the main Pane for the index)?

See the example. Also it's a FAQ: [LINK=http://www2.wealth-lab.com/WL5WIKI/kbFAQStrategy.ashx]
Is there a way to see the trades on secondary symbols?[/LINK]
QUOTE:
Finally, is there a way to use the index to trigger another purchase (as I am doing), while preventing the system from trading the index (so it doesn't appear in my performance results)?

Unless the index is explicitly defined as Benchmark Buy&Hold symbol in Preferences or it's the underlying symbol the strategy is running on, how can it appear in your performance results?
profile picture

Cone

#11
QUOTE:
Am I to understand that there is not a way to simulate Buy At Stop programmatically within the timeframe of a bar in the real world, although it does issue alerts within bars for backtesting?
I want to respond to this too, but I think Eugene answered a different aspect of the question.

Yes, you can use AtStop and AtLimit orders in the real world. When a bar completes, you generate signals (Alerts) for the next bar, i.e. bar + 1. These orders are worked in the market for that bar in real time, however, Wealth-Lab won't know if the order has filled until that bar is complete because Wealth-Lab only processes complete bars. Consequently, when it's the last bar in the chart, signals that generate entry Alerts cannot return Position objects, or in the case of exit Alerts they cannot return true because we cannot see into the future.

Example: Assume 1-minute bar interval.
At 09:45:00 your script processes the 0945 bar and generates a SellAtStop signal for bar + 1, i.e., the 0946 bar. (Keep in mind that Wealth-Lab always assumes end-of-bar timestamps, so 0946 is the bar that includes the trading from 09:45:00.001 to 09:46:00.000.) While the 0946 bar is building, i.e., before 09:46:00, let's say your stop order triggers. Your script doesn't know that it triggered because it hasn't processesed the 0946 bar yet. At 09:46:00, the script processes the complete bar, and only then it will know that the trade [should have been] executed. This is pretty much how all retail trading apps work.

The important thing to note is that NOW the script signal can tell you true or false. Again, at the time of the Alert, it necessarily will be false. You simply must know that it's not valid to peek ahead a bar and create an action based on that information. That's why your logic is flawed. For more, Help > WealthScript Programming Guide: Programming Trading Strategies > Peeking

Hope this helps.
profile picture

innertrader

#12
Thank you, Eugene, for your thorough responses. I have responded to each comment below.
QUOTE:
Don't use "bar+N" where N is greater than 1.

The nature of this strategy "Adaptive Price Strategies" (APS) requires a "[bar + 1]" approach for the trigger event. When I used [bar+1] for the Change Context purchase, it was buying at the Open of the trigger bar, which as Cone pointed out, is impossible in the real world. So I changed it to BuyAtMarket [bar+2] for the actual ETF purpose and it buys it on the Open of the bar following the trigger bar. I believe this is correct. Do you agree?
QUOTE:
How about downloading all available strategies (Open Strategy > Download...) and reviewing this working example among them: ActiveTrader 2011-05 | Inverse ETF switching system?

I actually used this design pattern for the pair switching and SetContext() method, which I have (partially) working. However, I have, for example, a one (SPX) relationship to two (IVV, SH), so I am not sure how the handling of the positions applies to my case. I will take another look at that.
QUOTE:
See the example. Also it's a FAQ:
Is there a way to see the trades on secondary symbols?

The FAQ looks promising. I will get into it today. Do you know if it can perform the magic that is done on the main Pane, which is to draw lines between Open/Close of a position upon hover, popping up return for the trade on the screen?
QUOTE:
Unless the index is explicitly defined as Benchmark Buy&Hold symbol in Preferences or it's the underlying symbol the strategy is running on, how can it appear in your performance results?

It is the benchmark buy & hold symbol in the APC strategy. I just don't want to buy it. I want to buy a derivative of it to simulate going long or short on the signal. But in that case, how can the IsPositionActive logic WL uses for a template ever trigger?
profile picture

innertrader

#13
Thank you, Cone for your response. I have a follow-up clarification question to one of your statements.
QUOTE:
These orders are worked in the market for that bar in real time, however, Wealth-Lab won't know if the order has filled until that bar is complete because Wealth-Lab only processes complete bars.
Using your example, if a BuyStop is triggered at 9:45:10, my strategy is running, and I have streaming data enabled, will it issue a trade alert before real-time 9:46:00 that I can act upon? I am asking for clarification on your use of the term "real time" above. While I realize that wanting interminute trade alerts may not seem significant, if you are using one-hour timeframes, they could be, especially with a breakout strategy, which APC appears to be.
profile picture

Cone

#14
QUOTE:
Using your example, if a BuyStop is triggered at 9:45:10, my strategy is running, and I have streaming data enabled, will it issue a trade alert before real-time 9:46:00 that I can act upon?
No. There is no such thing as a "trade alert". In fact, Wealth-Lab 6 only shows hypothetical trading based on the data - it does not (and cannot) receive any feedback from the Orders tool.

You need to understand this -> Processing only occurs at the end of an interval

If you want to run an hourly strategy and do things on a 1-minute basis, that's fine, but you have to use 1-minute bars to do it. Scale your indicators for hourly bars, see SetScaleCompressed(), but trade at the 1-minute chart interval.

Re: Bar + 2
Don't do it. It might look like it works in backtesting, but it won't be handled properly for live trading. Bar + 1, +2, +3, +N, all mean the same thing on the last bar: CREATE AN ALERT NOW. If you need an extra bar of delay, then the logic must handle it.

For example, if something occurred on the current bar and you need to create an Alert on the next bar, just store the current bar in a variable and when you get to the next bar, the logic Alerts. Quick example:

CODE:
Please log in to see this code.


profile picture

Eugene

#15
QUOTE:
Do you know if it can perform the magic that is done on the main Pane, which is to draw lines between Open/Close of a position upon hover, popping up return for the trade on the screen?

No, it can't: it's only a script-based eye candy. Nonetheless, fixed trade lines can be drawn using this routine: DrawTradeLines
profile picture

innertrader

#16
Thank you Cone and Eugene. I am making progress on just about every front based on your comments and suggestions. Hoever, I am having trouble conceptualizing what I am supposed to be doing with Cone's suggestion:
QUOTE:
If you want to run an hourly strategy and do things on a 1-minute basis, that's fine, but you have to use 1-minute bars to do it. Scale your indicators for hourly bars, see SetScaleCompressed(), but trade at the 1-minute chart interval.
I might require a further description of what this would accomplish with my current strategy because I am having trouble wrapping my head around it.

I am diplaying 3 panes. The first is the signal pane which provides long / short trading signals based on an index. The other two panes plot the long and inverse (short) ETF that is traded to simulate long and short of the index.

I am now running this strategy with one minute data but want to try to emulate what Cone was referring to. I was not sure where exactly to use the SetScaleCompressed() method. The trading signal in the main pane (PricePane) is based on the Adaptive Price Channel (APC) formula. I have reviewed the example code for this funcition and the following is my current attempt to modify the code that does the calculation of the and plots it in the PricePane:
CODE:
Please log in to see this code.


WIth the code version above I am not getting hourly plots of the variables above, only one minute plots. Also, the indicator Upper and Lower Channels are not generating the correct values. Further, the indicators (channels) now stops calculating early in the chart (and the trading stops) while the index and ETF prices continue to plot to the end of the period. I suspect that I am not compensating somewhere for the compression, but I'm not sure where. I have tried to add " * 60 " in various places but get a runtime error that the index is out of range.

If I understand Cone's comment, getting this working would allow me to run an hourly strategy (as if I were using one-hour data, which would reduce the number of daily trades), while being able to trade on intrahour signals. Do I understand correctly or is that wishful thinking?
profile picture

Eugene

#17
Here's what you need to do:
CODE:
Please log in to see this code.

In other words, create the APC DataSeries not in the original bar scale but in compressed bar scale.
profile picture

innertrader

#18
Thank you Eugene. Your suggestion worked perfectly and created the result Cone was talking about. Now that I see how this works it answers the additoinal questions that I had. I can see it is not "wishful thinking" on my part at all. Thanks to both of you.
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).