I am trying to write a script that will close a position when a position closes below a trailing variable. I want to set (or update if it has been set already) my stop if:
1) sma(close, 20) < sma(close, 50) (20 day sma is less than the 50 day sma on the current bar)
AND
2) ref((sma(close,20),1) > ref((sma(close,50),1) (yesterday's 20 day sma is greater than yesterday's 50 day sma)
If these two conditions are true I want to set a variable (I use "stop") equal to the close of the current bar * 0.95 (stop = close*0.95)
Last of all, if the close of any future bar is less than "stop", I would like to close the position. Here is my first attempt at writing a script, I am fairly certain I butchered it.
If someone could post a working script for this and/or point out where my code is wrong I would greatly appreciate it. I only run a simulation on 1 symbol (^DJI) in order to
simplify the setting of variables since with multiple symbols I believe you might have to make an array of the variable "stop"??? Listed below is my code:
OnNewPosition:
Variables.SetVariable("stop", 0);
OnEndPeriod:
if (Portfolio.GetNumberOfPositions("long") > 0) // this code doesn't need to run if there are no active positions.
{
- sma20[-1] refers to a future bar. You should use sma20[1] instead to refer to yesterday.
- You get the "Specified cast is not valid" error because variable "stop" is of type Integer.
In OnNewPosition you should use: Variables.SetVariable("stop", (double)0);
- You forgot the closing parenthesis "sma(close,50" in the following line:
MMParser sma50parser = Data.ParseFormula("sma50 = sma(close,50");
- You forgot the semi-colon at the end of each formula inside the "ParseFormula" function.
- Use the "Divers.Output" function to debug a money management script. Output data will be displayed under the "Details" tab in the simulation report.
Here is a modified version of your script:
if (Portfolio.GetNumberOfPositions("long") > 0)
{
MMPosition[] positions = Portfolio.GetOpenPositions();
for(int i=0;i<positions.Length;i++)
{
MMPosition pos = positions[i];
if(pos.Var1 == null) // Otherwise the stop is already set
{
MMParser parser = Data.ParseFormula("sma20 = sma(close,20);sma50 = sma(close,50);");
TimeSeries sma20 = parser.GetTimeSeries(pos.Symbol, "sma20");
TimeSeries sma50 = parser.GetTimeSeries(pos.Symbol, "sma50");
TimeSeries close = Data.GetPriceSeries(pos.Symbol, "close");
Note that I have executed your script and the above one on 1 symbol and it took less than 3 seconds.
Note also that you can use the "Trailing Stop" option on the "Update Trading System" form.