Profile Picture

Closing previous position and opening new position

Posted By serge 6 Years Ago
Message
Posted Monday November 14 2011
I'm coming from OpenQuant and can't find in the documentation/forums how to solve this. The strategy trades 2 symbols based on a third indicator symbol at end of day closing price. Doing back testing using imported daily bar data for all 3 (only have closing prices). I'm having an issue where the new position order does not go through (previous order was not closed). All the actions need to happen at EOD on the daily bars (logic/closing/opening positions).

From what I read I need to use MySystem to do the trades after all symbol bars are calculated (as you can see below). Thank you for your help.

Here's the code:

public class MySystem : MySystemBase
{
   int lastTrade = 0;
   
public override void Startup()
{
// Perform initialization or set system wide options here      
}

public override void NewBar()
{
//Before all symbol scripts

//Call the base implementation, which will call NewBar for all the symbol scripts
base.NewBar();

    //After all symbol scripts
BarData THIRD = SymbolScripts["THIRD"].Bars.Current;
Double PERCENT = (double)SystemParameters["StandardDevPercent"];
      
if(THIRD.Close > PERCENT)
{
         if(lastTrade != 1)
         {
            foreach (Position pos in PositionManager.GetOpenPositions())
            {
               pos.CloseAtMarket();
            }
            SymbolScripts["FIRST"].OpenPosition(PositionType.Long, OrderType.Market);
            lastTrade = 1;
         }
}
else
{
   if(lastTrade != 2)
         {
            foreach (Position pos in PositionManager.GetOpenPositions())
   {
   pos.CloseAtMarket();
   }
            SymbolScripts["SECOND"].OpenPosition(PositionType.Long, OrderType.Market);
            lastTrade = 2;
         }
}
}

public override void Shutdown()
{
}
}


Edited: Monday December 19 2011 by serge
Posted Tuesday November 15 2011
I am pretty sure this is the same issue affecting my system as well. Can someone from Right Edge advise on how to best handle this?

My strategy is basically trading two different symbols at the EOD, so everything needs to happen at the close in the following order:

IF an open position exists, sell(buy back) X amount of position.
Use proceeds from sale to buy(sell short) Y amount of new position.

How can I force RightEdge to do the above at the closing price of the current bar in backtests?
Posted Wednesday November 16 2011
By default RightEdge doesn't let you trade at the "current" price. This is to mirror real trading where you submit an order to the broker and there's no guarantee that the price won't have changed by the time the order is filled. So when you submit an order the first time it can be filled is normally the "next" price for that symbol. For orders submitted at the end of day, this means the earliest they can be filled is the open of the next day.

However, some systems want to make a decision based on the EOD price and then trade at that price. Live systems that work like this need to look at the current price shortly before the close, and submit their order before the market closes. For simulations running on daily data, it's convenient to just let them see the close price and then trade based on it. The SystemData.EnableTradeOnClose property and SystemData.BarClosing event enable this. In your MySystem class Startup method, set SystemData.EnableTradeOnClose to true, and subscribe to the SystemData.BarClosing event handler. You can submit your end of day orders in the BarClosing event handler directly, or you might create a BarClosing method in your SymbolScript that you would call for each symbol from the BarClosing handler in MySystem.

For cgorzynski's question, it is a bit more complicated but I think it will work. All else being equal, the paper broker processes orders in the order they were submitted. So you will need to submit the sell order before the buy order in your example.

Thanks,
Daniel
Posted Monday January 16 2012
hi

can you please please give me one simple example? just a really simple example showing how you use to subscribe to SystemData.BarClosing and how it works in the strategy? I've played around with it and it just doesn't work. have searched the forum there are other posts on this topic but no example. please give me an example i would find it really really helpful.
Posted Monday January 16 2012
Here is a sample system:

Trade on Close Sample

Let us know if you would like a C# version or if you have more questions.

Thanks,
Daniel
Posted Tuesday January 17 2012
hi

yes can you please provide a c# version, I don't find the vb version useful.

thanks again
Posted Tuesday January 17 2012
Here's a C# system which trades on the close. The logic is the same as the VB trade on close sample- it opens a position on the close after two down bars.

#region Using statements

using System;

using System.Drawing;

using System.Collections.Generic;

using System.Linq;

using RightEdge.Common;

using RightEdge.Common.ChartObjects;

using RightEdge.Indicators;

#endregion

 

public class MySystem : MySystemBase

{

         public override void Startup()

         {

                 // Perform initialization or set system wide options here

                 SystemData.EnableTradeOnClose = true;

                 SystemData.BarClosing += BarClosing;

         }

        

         void BarClosing(object sender, NewBarEventArgs args)

         {

                 foreach (MySymbolScript symbolScript in SymbolScripts)

                 {

                          symbolScript.BarClosing();

                 }

         }

}

 

public class MySymbolScript : MySymbolScriptBase

{

         public override void Startup()

         {

                 // Perform initialization here.

 

         }

 

         public override void NewBar()

         {

                 // Put your trading code here

 

         }

        

         public void BarClosing()

         {

                 if (Bars.Count < 2)

                 {

                          return;

                 }

                 if (Close.Current < Open.Current && Close.LookBack(1) < Open.LookBack(1))

                 {

                          //       Open a position after two down bars in a row

                          OpenPosition(PositionType.Long, OrderType.Market);

                 }

         }

 

         public override void OrderFilled(Position position, Trade trade)

         {

                 // This method is called when an order is filled

 

         }

 

         public override void OrderCancelled(Position position, Order order, string information)

         {

                 // This method is called when an order is cancelled or rejected

                 if (!order.CancelPending)

                 {

                          OutputWarning("Unexpected order cancel: " + order.ToString() + " " + information);

                 }

         }

}

 

Thanks,
Daniel

Posted Wednesday January 18 2012
Daniel

this still doesn't seem to work as I expect it.

this is what I want, assume a daily trading strategy, using close data (e.g. yahoo daily data)

and say I have a long position open.

using the above code, I want to:
1. close this position
2. go short

so that's TWO (2) trades. when I use the onclose event above, the send trade (going short) happens t+1 (the following day), that's not what I want! I want this switch to happen on the closing price of the same day!

is this at all possible? what's going on, am I still using the wrong code?

thanks
Posted Thursday January 19 2012
If you submit both orders in the BarClosing method (and they are both market orders), then they should both be filled on the close of the same bar. If that's not happening then I'd probably need to see your code to figure out what's going on.

If you prefer, you can also reverse the position with a single order. Here is a system that shows how to do this:
Indicator Based Stop and Reverse

You should be able to create a BarClosing method as shown in the code I posted, and move the trading code in the stop and reverse system from NewBar to BarClosing, and the position should reverse at the close of the bar.

Thanks,
Daniel
Posted Wednesday January 25 2012


that code still doesn't work and produces trades outside priced different to close.

I would really appreciate to get to the bottom of this.

look this is very very simple. I'm not sure why it's so complicated why there needs to be so much code to get something simple done.

what I want is both trades (close of current and open of second new trade) to be at the same close and the same CLOSING price.

here is an example:

english:
1. if price is greater than some calculated value then go long & and close short positions
2. if price is less than some calculated number then go short & close long positions.


example code:

//for the close bar event etc..
SystemData.EnableTradeOnClose = true;

SystemData.BarClosing += BarClosing;
      

   }
   
    void BarClosing(object sender, NewBarEventArgs args)

{

foreach (MySymbolScript symbolScript in SymbolScripts)

{

symbolScript.BarClosing();

}

}



//for the actualy signal

double x = some number



   if (Close.Current > x)
      {
         if (OpenPositions.Count!=0)
         {
         
         foreach (Position pos in OpenPositions)
            {
               if (pos.Type==PositionType.Long)
               {
            
                  continue;
                  
               }
               else
               {   
                  pos.CloseAtMarket();
                  OpenPosition(PositionType.Long, OrderType.Market);
                  
                  
               }
            }
            
      
         }
         
         else
         {
            
      OpenPosition(PositionType.Long, OrderType.Market);

            
         }
      
      }
      
      else
         
      {
         
         if (OpenPositions.Count!=0)
         {
         
         foreach (Position pos in OpenPositions)
            {
               if (pos.Type==PositionType.Short)
               {
                  continue;
                  
               }
               else
               {
               pos.CloseAtMarket();
            OpenPosition(PositionType.Short, OrderType.Market);
         
               }
            }
            
            
         }
         
         else
         {
         OpenPosition(PositionType.Short, OrderType.Market);
         }
         
      }


Similar Topics


Reading This Topic


2005-2017 © RightEdge Systems