Click here to Login

                                                   OnNewPosition event


Peter Gum
2010-10-25 09:42:05

I need some guidance: For any single symbol I want just one outstanding position, I want to enter that position for less than
x dollars (compute the number of allowed shares and set them) and verify that that number of shares is no more than 1% of the average volume.

Taking it just one step at a time, I thought I could reject a second trade in OnNewPosition roughly this way:
if (Portfolio.IsInPortfolio(e.symbol,True)) { PortFolio.RejectAllTradesForThisPeriod(2); return;}
But that won't compile and the reject method is broader (I want to reject just buys, not covers) than I want I think.
Can you get me started down the right path ....


2010-10-25 10:34:02


Best Answer
To reject trades if position size is less than x% of the average volume, you can use an option in simulator settings (Settings tab then Capital).

For any single symbol, the simulator will execute only one trade. If the symbol is already in the portfolio then the simulator will reject other trades until the current position is exited.

If you want to enter only one long position at a time, you can type:

if(Portfolio.GetNumberOfPositions("long") > 0)

Peter Gum
2010-10-26 16:11:47


My programming inexperience is showing: I am getting the error "type is used as a variable" on the last line. I guess I have not instantiated something, but what?
MMNewPosition a=NewPosition;
MMOnNewPosition e= MMOnNewPosition;
double b=a.Price;
double c=a.NbShares;
double d=2500.0;
if(b*c > d) e.UpdateNumberOfShares((int)(d/b));

2010-10-27 05:48:24


You get this error because "NewPosition" is a type/class not a variable.
To get the price for example you should use "NewPosition.Price".

Type CONTROL + SPACE to see the list of available classes/variables. After you type one of them, type "." and the list of available variables or functions inside this variable or class will appear.

Here is your code:
double b = NewPosition.Price;
double c = NewPosition.NbShares;
double d = 2500.0;
if(b*c > d) Functions.UpdateNumberOfShares((int)(d/b));

Peter Gum
2010-10-27 06:28:19


Thank you! I knew the capability was buried in there somewhere.
I have gained confidence that QS has the capabiltiy I need; I am slowed by the time it takes to 'discover' the details I need. I encourage you to publish examples, 'snippets' and member/field/method overviews. 'How to' vignettes would certainly push my leaning curve along.


2010-10-27 06:49:33


We are creating an Interactive QuantShare Learning Center that will contain "how to" lessons, examples...
Thank you Pete

Peter Gum
2010-10-27 08:10:26


I like that idea! That just might efficiently expedite the learning curve.

Next question: the code above compiles but is not yielding the expected results; that is, the the size of positions has not been constrained as expected. How can I debug this?

Also, setting the check marks for "Plot Entries and Exits on chart" and for columns "ScaleIn/Out" are not sticky, which is annoying.


2010-10-27 10:40:30


- I have tried the script and it works as expected.
Sometimes however, an order will be executed a little higher than 2500 because of a gap or increase in price.
NewPosition.Price = 10$ (close price)
Nb Shares = 250 shares.
Execution Price = 11$ (open price tomorrow)
Order Size = 2750$

You can debug a money management script using Divers.Output function.
The output is displayed in "Details" tab in the simulation report (Log textbox)

- We will make the "Plot Entries and Exits on chart" and "ScaleIn/Out" options stick in the new version.

Peter Gum
2010-10-27 13:24:29


I was changing the wrong place. I was using Analysis > Adv MM to create/edit the event formula. That does not refresh the copy the simulator uses (it would be nice if automatic refresh could be implemented). Going throught the simulator > update > MM worked (deleting the old one first). In any event, it indeed is now running as expected.

This output statement in the event code worked, but with a question:
Divers.Output( string.Format("Symbol: {0} before={1} after={2}", NewPosition.Symbol, c, NewPosition.NbShares) );
The 'c' value is not the 'before' value (because it is a reference rather than a copy?); how do I fix that? (This is a C# question.)
(Puting Output in a daily log window works conveniently, IMHO.)

Under Report > Trader it might be nice to have columns for running capital and p/l.


2010-10-27 14:11:31


The "double" type is not passed by reference and therefore the "before" value is "c" or "NewPosition.NbShares" and the "after" value is "(int)(d/b)".

We will add the running capital and p/l columns in Report/Trades tab.

Peter Gum
2010-10-27 16:58:40


I wasn't clear. The value of 'c' in the log is always identical to the final (possibly replaced) NewPosition.NbShares, even when it is clear my event code reduced the original number. So the question is how do I capture the original so I can put it in the log?

I think an 'uncommitted cash' column would also be informative. It would represent the portion of one's assets not deployed at any point, an indirect measure of the effectiveness of the strategy.

This is related to position sizing. QS appears to divide available capital at the beginning of a simulation by the maximum allowed positions and makes no subsequent adjustments related to the success of the strategy. I'm pretty sure some flexibility in both number of and size of positions could be interesting but I am sure just what I want yet. That's grist for another thread, but knowing the growth pattern of uncommitted cash would motivate me.

While I am on a roll, adding a 'reenter after' parameter to cover and sell just might be interesting, or some other way to set such a condition in conjunction with these events. This is particularly interesting with my present strategy where I am relying on QS to pick randomly from a collection of eligible possibilities: I would like to exclude recently exited assets from the next few picks.

(QS has enabled me to rather rapidly develop a strategy that is already showing promise, which is why you are getting so many questions about details. I appreciate your taking the time.)


Peter Gum
2010-10-27 17:16:47


I figured out the part about orginal value. I'm not getting the *after* because NewShares.NbShares is not (yet) updated. Sorry I bugged you on that one.


2010-10-28 06:38:19


- Yes. "NewShares.NbShares" is always equal to the original number of shares.

- Regarding the position sizing, the available cash is automatically adjusted after each position is entered.
When you change the position size of a position you have two choices:
- Adjust the number of shares of the next positions (add or increase shares depending on whether you have used more or less cash to enter the current position)
- Keep the same number of shares for the next positions (calculated before any position is entered)

You can choose an option by setting the following variable: TradingSystemSettings.IsAutoAjustCashNewPositions = true; (or false)

- Here is a code that will allow you to re-enter old position only after a specific number of days: (Add this before the "UpdateNumberOfShares" function)

int pastDays = 10;
MMPosition[] positions = Portfolio.GetClosedPositions(Divers.CurrentDate.AddDays(-pastDays));
for(int i=0;i<positions.Length;i++)
if(positions[i].Symbol == NewPosition.Symbol)

Peter Gum
2010-10-28 11:59:14


Thank you very much. This gives me something useful to work with.
(Once again, it is nice to see relevant capability already baked into the cake.)

No more messages


No html code. URLs turn into links automatically.

Type in the trading objects you want to include: - Add Objects
To add a trading object in your message, type in the object name, select it and then click on "Add Objects"


Trading Items
Number of Times an Event Occurred in the First N-Minutes of a Tra...
Historical economic calendar data by currency symbol
Adaptive Strategy Indicator
Currency Mgmt v 0.9
Correlation Filter Money Management Strategy

How-to Lessons
How to debug a trading system using the money management tool
How to synchronize stock charts?
How to drag & drop a stock to a static watchlist
How to display notes/commentaries on a chart
How to create trading rules based on Put and Call volume data

Related Forum Threads
OnNewPosition and Timestamps and Order ID
Is there a way to divide a money management event into functions?
How to modify a pending order in the OnEndPeriod event of AMM?
MM Events question
How to update the custom variables (var1,var2,...) in a position ...

Blog Posts
Create a trading strategy using the money management tool - Part ...
Statistical data analysis of time series
How to Backtest Your Trading System for Each Industry
How to Backtest Each Stock or Asset Individually
Money Management: Scale-in Trading Strategy

Create an account
Affiliate Program
Contact Us
Trading Forum
How-to Lessons
About Us
Terms of Use

Copyright 2017
Social Media
Follow us on Facebook
Twitter Follow us on Twitter
Follow us on Google+
RSS Trading Items

Trading financial instruments, including foreign exchange on margin, carries a high level of risk and is not suitable for all investors. The high degree of leverage can work against you as well as for you. Before deciding to invest in financial instruments or foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with trading and seek advice from an independent financial advisor if you have any doubts.