Back

How to find the closing price of the previous bars?

Hi Guys,

I have just started using this system and I am still in the learning phase. This is a very beginner question. I was trying to code a simple algorithm for which I needed to compare the Closing price of the previous two candles. So for example, if I was doing something like this on mql4 I would have used Close[1] > Close[2] to get the close price. But, how would I get something like this on this system. Could you guys help me out or point me to the right direction. Any help would be greatly appreciated.

 

 

Update Backtest








In QuantConnect/Lean, we cannot access past values automaticly like in MQL4.
We need to rely on the RollingWindow class that saves past values:

// Rolling window of closing values (decimal)
private RollingWindow<decimal> Close;

We then access past values similarly to MQL4. In our case, zero index means current value, 1 previous one, etc:

// In OnData even handler:
// Buy if current close is higher than previous
// and no holdings in the portfolio
if (!Portfolio.Invested && Close[0] > Close[1])
{
SetHoldings(_spy, 1);
Debug(Time + " -> Buy signal: " + Close[0] + " . " + Close[1]);
}

 

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Wow thanks Alexandre for a quick reply, the explanation and the example were clear and made sense. Another thing that I wanted to ask about RollingWindow that was confusing me:

1)You say that we that RollingWindow store past values, does it also include the high,low,open prices? If not, what do we send into the angular brackets for RollingWindow so we can retreive these values

2) I Want to store the bollinger band values of those past candles and be able to retrieve the values for those candles, I want to able to retrieve both upper, lower and middle bollinger band value. What should I send into the angular bracket so that I am able to retrieve those values.

3) Can you give me any advice on how do I go about learning

Thanks Again.  

0

RollingWindow is a "smart" C# List, we can save any type we want. In the previous example, we were saving System.Decimal. However we can save a TradeBar that contains the OHLCV information and an indicator:

private RollingWindow<decimal> Close;
private RollingWindow<TradeBar> Bar;
private RollingWindow<BollingerBandState> BB;

Please checkout the attached project.

Note that we needed to create a helper/wrapper class BollingerBandState to hold the current state of a bollinger band instance.

The best place to learn is reading the docs, following QuantConnect University examples and, of course, searching answers for our questions in this community.

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


@Alexandre I am new here. How come Close[0]  is the current and Close[1] is the previous? I  thought it would make more sense if Close[0] is the previous one. (Is it designed to insert into the list the opposite way?)

0

By definition, a rolling window has a moving reference (the origin of the time axis) which is always "now". The convention is that the origin of the time axis is zero (t = 0). Therefore Close[t=0], is the Close at the reference.
If C# allowed negative index (like Python does), we would probably use Close[-1], Close[-2], etc... but it does not.

Also, it is more intuitive, in my humble opinion, to access a value with that design. Say we want the Close from 10 days ago: Close[10], independently of out window size. On the other hand, with your reasoning, we would have to know the window size and the Close from 10 days ago would come as Close[Close.Count - 10].

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


@Alexandre Catarino I have some more questions that I needed help with .

1)I have send a Market Order, eg. a buy order, how do I go about closing this order and how do I check the status of the order.

2) How do I check from within the code whether the order was buy or sell

3)Is there a way of sending a stop-loss order?

4) How do I find out currency related information such as lot size, minimum stoploss level etc(these are for forex related symbols) 

Thanks

 

0

We can check the status of all orders using the Transactions property. For example, we can get an order that is recorded by its ID.

var order = Transactions.GetOrderById(_ticket.OrderId);

_ticket represents an OrderTicket that we define when we submit an order:

_ticket = MarketOrder("EURUSD", 1000);

The order above holds all the information we need to take action:

  • Symbol
  • Direction: OrderDirection.Buy, OrderDirection.Sell or OrderDirection.Hold
  • Quantity 

Please checkout the docs for orders type.
In order to place a stop loss, please use the StopMarketOrder.

The information about a given symbol can be find in its SymbolPropeties:

var properties = Securities["EURUSD"].SymbolProperties;
properties.Description
.ContractMultiplier
.LotSize
.MinimumPriceVariation
.QuoteCurrency

At this moment, we do not have information about minimum stoploss level.

 

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Could I possibly ask how this is done in python? Getting the OHLC of the bars?

Thanking you in advance!

0

Sorry i should have stated, for Forex

0

class MyAlgo(QCAlgorithm):

    
    def Initialize(self):
 # Initalise data, resolution, cash, start-date, end-date, pair to trade and make that 100% of portfolio::
        self.SetStartDate(2000,1,1)
        self.SetEndDate(2016,12,31)
        self.SetCash(5000)

        self.AddForex("EURUSD", Resolution.Minute)
        self.SetHoldings("EURUSD", 1.00)

 # Broker to get data from and trade with:
        self.SetBrokerageModel(BrokerageName.OandaBrokerage, AccountType.Margin)
        
 # Consolidator to create 15 minute bars:
        consolidator = QuoteBarConsolidator(15) # Consolidate the Minute bar data
        consolidator.DataConsolidated += self.OnDataConsolidated 
        self.SubscriptionManager.AddConsolidator("EURUSD", consolidator)
        
 # Moving Average:
        self.sma = SimpleMovingAverage(20) # Create the MA
     self.RegisterIndicator("EURUSD", self.sma, consolidator) # Put it on EURUSD and our consolidator so it all matches up

        self.SetWarmUp(20) # Warm up of 20 bars to account for our SMA and get data
        # coming in straight away
        
  # Get history for all instruments and those timeframes:
        self.History(5, Resolution.Daily) # get history of all subscribed instruments in,
        # 5 bars back from current bar and for our daily bars
        self.History(5, Resolution.Hour) # same as above for our hourly bars
        self.History(5, Resolution.Minute) # same as above but for our minute chart

        # Rolling Window
        self.quoteBarWindow = RollingWindow[QuoteBar](2) # Where the confusion comes in

# QUETION: Is the above what allows me to query the current bar close '[0]', then [1],[2],[3] going back further? Also, how do i determine how many bars back i can query in my algorhythm? What is the 2 at the end for?

        
    def OnData(self, data): 
        self.quoteBarWindow.Add(data["EURUSD"])
        stopprice = self.quoteBarWindow[0].Close * 0.07

        # Place an order if conditions are met:
        if not self.Portfolio.Invested:
            if self.quoteBarWindow[0].Close > self.sma.Current.Value:
                open_an_order = self.MarketOrder("EURUSD", 1000)
        
        # Stop out the order if conditions are met:
            if self.quoteBarWindow[0].Close < self.sma.Current.Value:
                close_an_order = self.StopMarketOrder("EURUSD", -1000, stopprice)
        
    # Consolidator Class:
    def OnDataConsolidated(self, sender, bar):
        self.Debug(str(self.Time) + " > New Bar!")
       
    def SmaUpdated(self, sender, updated):
        self.smaWin.Add(updated)
        
        Just had a few questions:

1. Could you let me know if my notes # are correct? Just want to get the logic of putting it all together correct as I have a number of strategies (the rules for them) that I want to just implement here.

2. self.quoteBarWindow[0].Close <<< Is this the correct syntax to get the last bar that closed? If so, how do i get the bar before and bar before that? I got an error when i tried before saying only accepts 0 to 0. so [1] wouldnt work.

For example, I would like to say if the last bar closed goes above the SMA line, open a trade. If the last bar to close closed below the SMA, close the trade.

3. If I wanted to do a fixed pip based stop and target, what is the syntax for this? 

For exmaple, if last closed bar is anove SMA, enter a trade with a target of 40 pips and stop of 20 pips?

Sorry for all the questions, but I think once i get these fundamental bits down, I can build on that and go from there. I really appreciate your help! :) 
        
        
        
        
        
        
        
        

0

Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed