Multiple entries
Author: maninjapan
Creation Date: 3/8/2013 10:49 AM
profile picture

maninjapan

#1
I am trying to code a counter trading system with 3 levels and different position sizes for each level. Is there a way to set a default size for each level? I have just added multiple orders for each level which seems to be entering ok.

I am now trying to work on the exits, is there anything I need to be careful of when coding exits for multiple entries? I am using simple limit and stop exits for profit target / stop losses.
I would like to just use one exit for the entire open position? Is there any problem with doing this? Or do I need to add exit orders for each entry?

Below is the code I am using for my long/short 3 level entries. Any advice would be greatly appreciated.

Thanks,

CODE:
Please log in to see this code.
profile picture

Eugene

#2
QUOTE:
I have just added multiple orders for each level which seems to be entering ok.


That makes the code harder to read.

QUOTE:
Is there a way to set a default size for each level?


By calling SetShareSize(fixed_shares), or, for example, by using this PosSizer when you need to assign a percent equity:

Position Options > "Use .Tag"

QUOTE:
is there anything I need to be careful of when coding exits for multiple entries?


For a working design pattern, see the WealthScript Programming Guide > Programming Trading Strategies > Multi-Position Strategies > MP Strategy Template.

QUOTE:
I would like to just use one exit for the entire open position?


Pass Position.AllPositions to ExitAt* to close out the entire position.
profile picture

maninjapan

#3
Thanks Eugene, I have tried getting the exits to work using Position.AllPositions. My code compiles ok, but when I try to run it I get a runtime error "Index outside range, needs to be smaller than collection size" (translated from Japanese). I am trying to get the exit to reference the total average price, or the entry price of the first position. (My coding level is below slime, so apologies if it looks like the son of frankenstein)

CODE:
Please log in to see this code.
profile picture

Eugene

#4
CODE:
Please log in to see this code.
profile picture

maninjapan

#5
Wow, thanks Eugene, would never have got there. Is it possible to just reference the entry price of the first position in place of the average entry price?
profile picture

Eugene

#6
ActivePositions[0] is the first open position.
profile picture

maninjapan

#7
Thanks Eugene, was that simple.... Exits seem to be working fine now! However, I am still having a problem with this
runtime error: "Index outside range, needs to be smaller than collection size" (translated from Japanese).
place: WealthLab.Strategies.MyStrategy.Execute()
place: System.Collections.Generic.List '1.get_item(Int32 index)

The problem seems to be with the second entry order as I can run it fine with just the first one but when I try to run it with the second order it gives this runtime error. Is this associated with the entry or exit prices calculated being incorrect or something similar?

CODE:
Please log in to see this code.



Thanks

profile picture

Eugene

#8
See Wiki > Errors | Strategy > Index was out of range

Most likely you're accessing a Position that does not yet exist.
profile picture

maninjapan

#9
Thanks Eugene, I have tried running the code that you put up as is. I am able to run it on a scale down to 15 minute bars, However I get that error on any scale below that ( I have been trying to test on 5 minute data and have only just realized it works on anything 15 minute and above). Any reason as to why this might happen?

Thanks

profile picture

Eugene

#10
The three most likely groups of reasons you will find by the Wiki link above.
profile picture

maninjapan

#11
I'm not sure what the exact issue was, but it seems to be working now. The problem I am now having is I am getting entries on the same bars as exits on the previous position. I've added the full code as it stands. Have I made a glaring error that I shouldn't have? And is there an easy fix for this?

CODE:
Please log in to see this code.
profile picture

maninjapan

#12
Just to clarify, If there is an exit on a bar, I would like the next entry to be no earlier than the next bar as it uses the previous close to calculate the entry
profile picture

Cone

#13
You're checking ActivePositions.Count == 0 on the same bar for which you're triggering exits for the next bar - that's peeking!

CODE:
Please log in to see this code.
Also, you calculate an "average entry price for open positions" after a single BuyAtLimit - there can only be 0 or 1 Positions after that signal. Now, you're guaranteed to get a limit price or better, but if price gapped lower it will be a better price. However, that price cannot be known in advance for your next two BuyAtLimit signals, so that's peeking too. Instead of AvgEntryPrice , you must use LE1[bar] (or something else known as of the current bar.
profile picture

Eugene

#14
In addition to what Cone said, one can't realistically backtest a strategy with Stop and/or Limit orders on the same bar without applying a workaround outlined here.
profile picture

maninjapan

#15
Thanks Cone and Eugene for the assistance.

Eugene, I plan on eventually testing this with tick data so using a workaround to look inside the bar should work for me.

Cone, simply changing the if condition to 'else' wont compile, so I'm assuming it needs to go into the loop with the exits, however this now produces no trades at all. Is there a specific part of the code the entry orders need to go using the 'else'? ( Iget the average price issue as well, but just want to fix it up 1 step at a time if possible). Below is the attempt I have made at adding the 'else' ( I have commented out the multiple entries for now for simplicity's sake)

Thanks


CODE:
Please log in to see this code.
profile picture

Eugene

#16
QUOTE:
Cone, simply changing the if condition to 'else' wont compile,


CODE:
Please log in to see this code.
profile picture

maninjapan

#17
Thanks Eugene, I am able to compile and run in this format. There is an issue with not being able to get entry orders following the bar of the first entry but I can go back to that later. The issue I am now trying to fix is regarding the Profit targetexit price for multiple entries.
The Stop loss works perfectly, all exiting at an offset distance from the first entry. The profit target however, should be exiting at an offset distance from the average entry price. ( all positions exit at the same price). However from looking at the trade history they are exiting at different prices, the offset distance calculated from each entry price. I have tried to use the average entry price calculation that you provided earlier in the thread, but to no avail. Any advice as to how to get the profit target calculating based on the average entry price and exiting all at the same price?

Thanks again!!


CODE:
Please log in to see this code.

profile picture

Eugene

#18
QUOTE:
The profit target however, should be exiting at an offset distance from the average entry price. ( all positions exit at the same price). However from looking at the trade history they are exiting at different prices, the offset distance calculated from each entry price.


Exiting a position modifies the ActivePositions collection, and when looping over, this inevitably affects the average entry price.

As an alternative, you can store the AvgEntryPrice after entering your last planned position (3rd), and use that (static) value in your exit logic as shown below (don't forget to reset it):

CODE:
Please log in to see this code.
profile picture

maninjapan

#19
Thanks Eugene ( and Cone) I have got it now working in a basic form. I was aiming to get the second and third entries to be valid for up to a couple of bars after the initial entry but I might leave that battle for another day....
profile picture

Eugene

#20
QUOTE:
I was aiming to get the second and third entries to be valid for up to a couple of bars after the initial entry


Then you'd move them inside the " if (ActivePositions.Count > 0)" block followed by the AvgEntryPrice logic, and use this technique: Setups, Triggers, Delays, and Timeouts.
profile picture

maninjapan

#21
Thanks Eugene, I have got the extra orders coming in as I need them to using the following code, However the problem I have now is they are also coming in on the same bar as exits. How can I adjust the loop so that this doesn't happen? the loop should stop if there are any exit orders executed and only checking for the extra entries if there are no exit orders.

Thanks again,

CODE:
Please log in to see this code.
profile picture

Eugene

#22
Now this seems to me a royal clutter. Why did you break detection of first position taken by assigning the current position to the variable in the loop? What's the point of repeating AvgEntryPrice triply? And it won't compile since it's incomplete.

I couldn't derive rules from the code, and reverse engineering this lengthy code without clear rules is likely to end up in errors. So if you want me to take a look at it, please consider taking my code from post #18 and clearly describe your additional rules in plain English.
profile picture

maninjapan

#23
Apologies for the mess there Eugene. Here is the code based on post #18. I have added a time filter for entries and profit/stoploss exits as well as a close all positions exit after 2130.

The strategy almost works as I expect it to but for 1 thing regarding entries. Currently 2nd and 3rd entries occur only on the same bar of the 1st entry. Im looking to have those orders to stay active after the initial entry bar, as long as the first entry is open.

all exit prices are calculated based on the current average open price.

CODE:
Please log in to see this code.
profile picture

Eugene

#24
Sorry if I wasn't clear. What is the trading logic i.e. those duplicating pyramid trades? Like what are you trying to add to the code in post #18, but in plain English. Can you just sum it all up from scratch?
profile picture

maninjapan

#25
Sorry Eugene, I may not be getting what you mean, but I thought I explained what was missing in the post above.

Let me try again.

Basic strategy
3 levels of entry with a limit order offset from the close (between 12:00 - 21:00)
Simple Stop loss and exit offset from the average entry price for all open positions.
Exit all trades after 21:30


The strategy almost works as coded in #18, however the 2nd and 3rd limit orders are only valid for the same bar as the entry of the 1st order. (the 2nd and 3rd orders either enter on the same bar as the 1st entry or not at all)
The 2nd and 3rd order entries should stay active ( at the original limit order price) until executed or the open position is exited.
(I guess in other words, 2nd and 3rd level entries should be executable on the same bar as the 1st level entry or any bar after that until the trade is closed)

Hope that makes a bit more sense.

profile picture

Eugene

#26
QUOTE:
Simple Stop loss and exit offset from the average entry price for all open positions.

For that, you average long and short positions together? If you treat them separately, you will have to handle it in the strategy.

I think this prototype code should do the job - after changing the dummy LE,SE... series to VolMult etc. Remember to apply the Position Options PosSizer if you wish to set the number of max open positions (total, long and/or short) the way you like:

CODE:
Please log in to see this code.
profile picture

maninjapan

#27
Thanks Eugene, I'm not sure what you mean by "averaging long and short positions together", I just grouped them by Entry level 1,2,3. There is no way (theoretically) for them to have simultaneous short and long positions though the exits will always between the long and short entries. I will keep an eye on that though to make sure its working as intended.

I have just run this code though and I am noticing multiple open positions of the same entry. There should be only a maximum of one position for each entry level. I am also seeing these multiple entries being exited at different times and prices. The intention is to have one exit for all open positions based on the average price

profile picture

Eugene

#28
QUOTE:
I have just run this code though and I am noticing multiple open positions of the same entry.


You might want to add a condition on top of each entry:

CODE:
Please log in to see this code.


QUOTE:
I am also seeing these multiple entries being exited at different times and prices. The intention is to have one exit for all open positions based on the average price


I presented an example; the actual exit levels are completely up to you. I don't have time for endless iterations on custom script development, sorry.
profile picture

maninjapan

#29
Eugene, Thank you for the help RE the entries, that would have been way out of my reach on my own.

Regarding the second half though, no offense but not sure what that is about..... You asked me to write down my rules in simple English and I did, I was simply giving some feedback as to the code you provided. The exit based on average exit price has been a consistent theme of the strategy, so I don't believe I was asking for "endless iterations on custom script development".

Once again though, thank you very much for your assistance to date.

profile picture

maninjapan

#30
Eugene, Below is the full code with the fix for the multiple entries you gave me. I have eliminated unwanted entries but still having my original issue with getting exits and entries on the same bar.... I seem to be chasing my tail on this one.....

I have reviewed earlier posts from yourself and Cone, but I seem to be able to get multiple entries on 1 bar only and no entries on same bar as exits OR multiple entries across multiple bars and entries on same bar as exit.

I am just looking for a simple fix to get the following code to have no entries on the same bar as exits.


CODE:
Please log in to see this code.
profile picture

Eugene

#31
Deane,

QUOTE:
Regarding the second half though, no offense but not sure what that is about..... You asked me to write down my rules in simple English and I did, I was simply giving some feedback as to the code you provided. The exit based on average exit price has been a consistent theme of the strategy, so I don't believe I was asking for "endless iterations on custom script development".


None taken. I felt confused because different statements contradicted each other - like having one exit for all open positions based on the average price today and having multiple exits before. Now that you have the working prototype, I'm sure you'll be able to express your exit rules in code.
profile picture

maninjapan

#32
Apologies, I may have not expressed my logic clearly enough, but one exit was just referring to all open positions being closed by the same stop loss or the same profit order. the code you provided seems to be providing exactly this, but i was seeing multiple open positions exiting at different prices, not all being closed by the same take profit order or stop loss etc.... This was working in a previous version so I'm sure I reproduce this from posts earlier in the thread, as soon as I can fix this new entries on same bar as exits issue........
profile picture

Eugene

#33
QUOTE:
I have reviewed earlier posts from yourself and Cone, but I seem to be able to get multiple entries on 1 bar only and no entries on same bar as exits OR multiple entries across multiple bars and entries on same bar as exit.


Your code from post #30 appears to work correctly for me after choosing "Position Options" and configuring as per post #26 - i.e. no same bar entries & exits in this case.

EDIT: I tested it in Single Symbol Mode; for MSB, you'd want to uncheck "Max open positions" and check "Max open in symbol" instead.
profile picture

maninjapan

#34
Eugene, Thank you for testing that. However I am still seeing a few issues. To hopefully keep things clear and not waste your time any more than I have with this I have attached a screenshot of each of the 2 issues I am seeing. I have attempted to use the Position Options, the setup is in the 1st screenshot.
I am running this on intraday futures data if that changes anything. And I only intend to test on a single symbol.

1. Open positions exiting at different prices and times. (1.SeparateExits.jpg)
My goals is for an exit to close all the open position, hence the use of the average open price (whether it be a profit target, stop loss or time exit). However I see that positions are being handled separately and exiting at different times and prices.

2. New Positions are being entered on the same bar as the exit of a previous position (2.ExitEntry.jpg)
Im not sure whether this is simply due to my trading rules allowing this to happen, or I have done something to the code so that it is peeking, but my goal is for this not to happen.

Thank you again.
profile picture

Eugene

#35
1. At the risk of repeating, separate exits are absolutely OK with the current logic of your strategy: it allows them. Anyway, fine-tuning your Strategy is outside of my scope.

2. You're using the PosSizer incorrectly: none of the buttons are activated. Yes, you have to click on the buttons - typing in a number is not enough! It's not activated, hence everything you're experiencing. Voila.
profile picture

maninjapan

#36
I have been able to fix 1. by using the exit you provided in the code in # 18. This exits all the open positions with each exit

I am still having 2 issues with the entries that I dont understand however ( Still getting new entries on the same bar but I can forgo that one). I apologize for keep coming back to this, but this is just what I have been attempting to achieve all along. I understand that the way the code is then these might well be expected, however I am trying to understand why they are and how to fix them. I believe I have PosSizer settings set correctly now too. (If I dont, do you have any advice on what needs fixing?)


1. there are 3 levels of buy and sell orders, and there should only be a maximum of 1 entry for each level at any one time up to a maximum position of 3 at one time ( long or short)(eg. there shouldnt be multiple instances of Long1 open at any one time) I assumed the code you provided was to address this "if( firstLong == null )" however I am still seeing multiple entries of the same entry signal so I may be misunderstanding this code

2. Entries 2 and 3 should be able to enter after the bar of the 1st entry until it hits an exit limit order, however they are only entering on the same bar or not at all.

apologies again for dragging this on.

CODE:
Please log in to see this code.
profile picture

Eugene

#37
This is my final stab at it. No "Position Options" required. It satisfies almost all of your criteria except that the additional entries will trigger on bars after the first entry. This is to avoid peeking.

CODE:
Please log in to see this code.
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).