コード例 #1
0
ファイル: LiveFeaturesAlgorithm.cs プロジェクト: tuddman/Lean
 public void OnData(TradeBars data)
 {
     if (!Portfolio.HoldStock && data.ContainsKey("AAPL"))
     {
         int quantity = (int)Math.Floor(Portfolio.Cash / data["AAPL"].Close);
         Order("AAPL", quantity);
         Debug("Purchased SPY on " + Time.ToShortDateString());
         Notify.Email("*****@*****.**", "Test", "Test Body", "test attachment");
     }
 }
コード例 #2
0
ファイル: QCAlgorithm.cs プロジェクト: ychaim/QCAlgorithm
        /// <summary>
        /// Submit a new order for quantity of symbol using type order.
        /// </summary>
        /// <param name="type">Buy/Sell Limit or Market Order Type.</param>
        /// <param name="symbol">Symbol of the MarketType Required.</param>
        /// <param name="quantity">Number of shares to request.</param>
        public int Order(string symbol, int quantity, OrderType type = OrderType.Market)
        {
            //Add an order to the transacion manager class:
            int     orderId       = -1;
            decimal price         = 0;
            string  orderRejected = "Order Rejected at " + Time.ToShortDateString() + " " + Time.ToShortTimeString() + ": ";

            //Internals use upper case symbols.
            symbol = symbol.ToUpper();

            //Ordering 0 is useless.
            if (quantity == 0)
            {
                return(orderId);
            }

            if (type != OrderType.Market)
            {
                Debug(orderRejected + "Currently only market orders supported.");
            }

            //If we're not tracking this symbol: throw error:
            if (!Securities.ContainsKey(symbol))
            {
                Debug(orderRejected + "You haven't requested " + symbol + " data. Add this with AddSecurity() in the Initialize() Method.");
            }

            //Set a temporary price for validating order for market orders:
            if (type == OrderType.Market)
            {
                price = Securities[symbol].Price;
            }

            try
            {
                orderId = Transacions.AddOrder(new Order(symbol, quantity, type, Time, price), Portfolio);

                if (orderId < 0)
                {
                    //Order failed validaity checks and was rejected:
                    Debug(orderRejected + OrderErrors.ErrorTypes[orderId]);
                }
            }
            catch (Exception err) {
                Error("Algorithm.Order(): Error sending order. " + err.Message);
            }
            return(orderId);
        }
コード例 #3
0
        //Handle TradeBar Events: a TradeBar occurs on every time-interval
        public void OnData(TradeBars data)
        {
            //One data point per day:
            if (sampledToday.Date == data[symbol].Time.Date)
            {
                return;
            }

            //Only take one data point per day (opening price)
            price        = Securities[symbol].Close;
            sampledToday = data[symbol].Time;

            //Wait until EMA's are ready:
            if (!emaShort.IsReady || !emaLong.IsReady)
            {
                return;
            }

            //Get fresh cash balance: Set purchase quantity to equivalent 10% of portfolio.
            decimal cash     = Portfolio.Cash;
            int     holdings = Portfolio[symbol].Quantity;

            //quantity = Convert.ToInt32((cash * 0.5m) / price);

            if (holdings > 0)
            {
                //If we're long, or flat: check if EMA crossed negative: and crossed outside our safety margin:
                if ((emaShort * (1 + tolerance)) < emaLong)
                {
                    //Now go short: Short-EMA signals a negative turn: reverse holdings
                    Order(symbol, -(holdings));
                    Log(Time.ToShortDateString() + " > Go Short > Holdings: " + holdings.ToString() + " Quantity:" + quantity.ToString() + " Samples: " + emaShort.Samples);
                }
            }
            else if (holdings == 0)
            {
                //If we're short, or flat: check if EMA crossed positive: and crossed outside our safety margin:
                if ((emaShort * (1 - tolerance)) > emaLong)
                {
                    //Now go long: Short-EMA crossed above long-EMA by sufficient margin
                    var quantity = GetNumSymbols(price);
                    Order(symbol, Math.Abs(holdings) + quantity);
                    Log(Time.ToShortDateString() + "> Go Long >  Holdings: " + holdings.ToString() + " Quantity:" + quantity.ToString() + " Samples: " + emaShort.Samples);
                }
            }
        }
コード例 #4
0
        public void OnData(Nifty data)
        {
            try
            {
                int quantity = (int)(Portfolio.TotalPortfolioValue * 0.9m / data.Close);

                today.NiftyPrice = Convert.ToDouble(data.Close);
                if (today.Date == data.Time)
                {
                    prices.Add(today);

                    if (prices.Count > minimumCorrelationHistory)
                    {
                        prices.RemoveAt(0);
                    }
                }

                //Strategy
                double highestNifty = (from pair in prices select pair.NiftyPrice).Max();
                double lowestNifty  = (from pair in prices select pair.NiftyPrice).Min();
                if (Time.DayOfWeek == DayOfWeek.Wednesday) //prices.Count >= minimumCorrelationHistory &&
                {
                    //List<double> niftyPrices = (from pair in prices select pair.NiftyPrice).ToList();
                    //List<double> currencyPrices = (from pair in prices select pair.CurrencyPrice).ToList();
                    //double correlation = Correlation.Pearson(niftyPrices, currencyPrices);
                    //double niftyFraction = (correlation)/2;

                    if (Convert.ToDouble(data.Open) >= highestNifty)
                    {
                        int code = Order("NIFTY", quantity - Portfolio["NIFTY"].Quantity);
                        Debug("LONG " + code + " Time: " + Time.ToShortDateString() + " Quantity: " + quantity + " Portfolio:" + Portfolio["NIFTY"].Quantity + " Nifty: " + data.Close + " Buying Power: " + Portfolio.TotalPortfolioValue);
                    }
                    else if (Convert.ToDouble(data.Open) <= lowestNifty)
                    {
                        int code = Order("NIFTY", -quantity - Portfolio["NIFTY"].Quantity);
                        Debug("SHORT " + code + " Time: " + Time.ToShortDateString() + " Quantity: " + quantity + " Portfolio:" + Portfolio["NIFTY"].Quantity + " Nifty: " + data.Close + " Buying Power: " + Portfolio.TotalPortfolioValue);
                    }
                }
            }
            catch (Exception err)
            {
                Debug("Error: " + err.Message);
            }
        }
コード例 #5
0
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">TradeBars IDictionary object with your stock data</param>
        public void OnData(TradeBars data)
        {
            if (!_indicators.BB.IsReady || !_indicators.RSI.IsReady)
            {
                return;
            }

            _price = data["SPY"].Close;

            if (!Portfolio.HoldStock)
            {
                int quantity = (int)Math.Floor(Portfolio.Cash / data[_symbol].Close);

                //Order function places trades: enter the string symbol and the quantity you want:
                Order(_symbol, quantity);

                //Debug sends messages to the user console: "Time" is the algorithm time keeper object
                Debug("Purchased SPY on " + Time.ToShortDateString());
            }
        }