Пример #1
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">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (UtcTime.Hour != 6)
            {
                return;
            }

            if (UtcTime.Minute == 0)
            {
                // this order will be rejected for insufficient funds
                LimitOrder("BTCUSD", 100m, 4734.64m);
                LimitOrder("ETHUSD", 1.35505027m, 368.8m);
            }
            else if (UtcTime.Minute == 6)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10576312m, 4727.61m);
            }
            else if (UtcTime.Minute == 12)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10576267m, 4727.63m);
            }
            else if (UtcTime.Minute == 18)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10547724m, 4740.42m);
            }
            else if (UtcTime.Minute == 24)
            {
                Transactions.CancelOpenOrders("BTCUSD");
            }
        }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!data.ContainsKey("SPY"))
            {
                return;
            }

            // After an order is placed, it will decrease in quantity by one for each minute, being cancelled altogether
            // if not filled within 10 minutes.
            if (Transactions.GetOpenOrders().Count == 0)
            {
                var goLong = Time.Day < 9;
                _negative = goLong ? 1 : -1;
                var orderRequest = new SubmitOrderRequest(OrderType.LimitIfTouched, SecurityType.Equity, "SPY",
                                                          _negative * 10, 0,
                                                          data["SPY"].Price - (decimal)_negative, data["SPY"].Price - (decimal)0.25 * _negative, UtcTime,
                                                          $"LIT - Quantity: {_negative * 10}");
                _request = Transactions.AddOrder(orderRequest);
                return;
            }

            // Order updating if request exists
            if (_request != null)
            {
                if (_request.Quantity == 1)
                {
                    Transactions.CancelOpenOrders();
                    _request = null;
                    return;
                }

                var newQuantity = _request.Quantity - _negative;
                _request.UpdateQuantity(newQuantity, $"LIT - Quantity: {newQuantity}");
            }
        }
        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (UtcTime.Hour != 6)
            {
                return;
            }

            if (UtcTime.Minute == 0)
            {
                LimitOrder("BTCUSD", 0.10555181m, 4734.64m);
                LimitOrder("ETHUSD", 1.35505027m, 368.8m);
            }
            else if (UtcTime.Minute == 6)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10576312m, 4727.61m);
            }
            else if (UtcTime.Minute == 12)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10576267m, 4727.63m);
            }
            else if (UtcTime.Minute == 18)
            {
                Transactions.CancelOpenOrders("BTCUSD");
                LimitOrder("BTCUSD", 0.10547724m, 4740.42m);
            }
            else if (UtcTime.Minute == 24)
            {
                Transactions.CancelOpenOrders("BTCUSD");
            }
        }
Пример #4
0
 public override void OnOrderEvent(OrderEvent orderEvent)
 {
     if (orderEvent.Status.IsFill())
     {
         // if we receive a fill cancel the other outstanding order
         Transactions.CancelOpenOrders(orderEvent.Symbol);
     }
 }
Пример #5
0
        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            Log(orderEvent.ToString());

            if (orderEvent.Status == OrderStatus.Filled)
            {
                if (_pendingEntry != null && orderEvent.OrderId == _pendingEntry.OrderId)
                {
                    Console.WriteLine("entry fill! " + orderEvent.FillQuantity);
                    //submit bracket orders
                    SetupBracket(orderEvent);
                }
                else
                {
                    Console.WriteLine("bracket fill! " + orderEvent.FillQuantity);
                    Transactions.CancelOpenOrders(_Symbol);
                }
            }
        }
        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            var order     = Transactions.GetOrderById(orderEvent.OrderId);
            var goUpwards = _lastSMAValue < _sma.Current.Value;

            _lastSMAValue = _sma.Current.Value;

            if (order.Status == OrderStatus.Filled)
            {
                if (order.Type == OrderType.Limit && Math.Abs(_beta.Current.Value - 1) < 0.2m && goUpwards)
                {
                    Transactions.CancelOpenOrders(order.Symbol);
                }
            }

            if (order.Status == OrderStatus.Canceled)
            {
                Log(orderEvent.ToString());
            }
        }
Пример #7
0
        private readonly Dictionary <Symbol, SymbolData> _sd = new Dictionary <Symbol, SymbolData>(); //portfolio corresponding dic

        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and
        /// start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            //set trade period
            SetStartDate(2010, 01, 01);  //Set Start Date
            SetEndDate(2018, 05, 01);    //Set End Date

            //设置总资金
            SetCash(TOTALCASH);             //Set Strategy Cash

            //select stocks to be traded.
            stockSelection();

            foreach (var val in _sd.Values)
            {
                Schedule.On(DateRules.EveryDay(val.Symbol), TimeRules.AfterMarketOpen(val.Symbol, -1), () =>
                {
                    Debug("EveryDay." + val.Symbol.ToString() + " initialize at: " + Time);
                    Transactions.CancelOpenOrders(val.Symbol);                  //close all open orders at the daily beginning
                });
            }

            SetWarmup(TimeSpan.FromDays(NUMDAYWU));
        }
Пример #8
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">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (Portfolio.CashBook["EUR"].ConversionRate == 0 ||
                Portfolio.CashBook["BTC"].ConversionRate == 0 ||
                Portfolio.CashBook["ETH"].ConversionRate == 0 ||
                Portfolio.CashBook["LTC"].ConversionRate == 0)
            {
                Log($"EUR conversion rate: {Portfolio.CashBook["EUR"].ConversionRate}");
                Log($"BTC conversion rate: {Portfolio.CashBook["BTC"].ConversionRate}");
                Log($"LTC conversion rate: {Portfolio.CashBook["LTC"].ConversionRate}");
                Log($"ETH conversion rate: {Portfolio.CashBook["ETH"].ConversionRate}");

                throw new Exception("Conversion rate is 0");
            }
            if (Time.Hour == 1 && Time.Minute == 0)
            {
                // Sell all ETH holdings with a limit order at 1% above the current price
                var limitPrice = Math.Round(Securities["ETHUSD"].Price * 1.01m, 2);
                var quantity   = Portfolio.CashBook["ETH"].Amount;
                LimitOrder("ETHUSD", -quantity, limitPrice);
            }
            else if (Time.Hour == 2 && Time.Minute == 0)
            {
                // Submit a buy limit order for BTC at 5% below the current price
                var usdTotal   = Portfolio.CashBook["USD"].Amount;
                var limitPrice = Math.Round(Securities["BTCUSD"].Price * 0.95m, 2);
                // use only half of our total USD
                var quantity = usdTotal * 0.5m / limitPrice;
                LimitOrder("BTCUSD", quantity, limitPrice);
            }
            else if (Time.Hour == 2 && Time.Minute == 1)
            {
                // Get current USD available, subtracting amount reserved for buy open orders
                var usdTotal    = Portfolio.CashBook["USD"].Amount;
                var usdReserved = Transactions.GetOpenOrders(x => x.Direction == OrderDirection.Buy && x.Type == OrderType.Limit)
                                  .Where(x => x.Symbol == "BTCUSD" || x.Symbol == "ETHUSD")
                                  .Sum(x => x.Quantity * ((LimitOrder)x).LimitPrice);
                var usdAvailable = usdTotal - usdReserved;

                // Submit a marketable buy limit order for ETH at 1% above the current price
                var limitPrice = Math.Round(Securities["ETHUSD"].Price * 1.01m, 2);

                // use all of our available USD
                var quantity = usdAvailable / limitPrice;

                // this order will be rejected for insufficient funds
                LimitOrder("ETHUSD", quantity, limitPrice);

                // use only half of our available USD
                quantity = usdAvailable * 0.5m / limitPrice;
                LimitOrder("ETHUSD", quantity, limitPrice);
            }
            else if (Time.Hour == 11 && Time.Minute == 0)
            {
                // Liquidate our BTC holdings (including the initial holding)
                SetHoldings("BTCUSD", 0m);
            }
            else if (Time.Hour == 12 && Time.Minute == 0)
            {
                // Submit a market buy order for 1 BTC using EUR
                Buy("BTCEUR", 1m);

                // Submit a sell limit order at 10% above market price
                var limitPrice = Math.Round(Securities["BTCEUR"].Price * 1.1m, 2);
                LimitOrder("BTCEUR", -1, limitPrice);
            }
            else if (Time.Hour == 13 && Time.Minute == 0)
            {
                // Cancel the limit order if not filled
                Transactions.CancelOpenOrders("BTCEUR");
            }
            else if (Time.Hour > 13)
            {
                // To include any initial holdings, we read the LTC amount from the cashbook
                // instead of using Portfolio["LTCUSD"].Quantity

                if (_fast > _slow)
                {
                    if (Portfolio.CashBook["LTC"].Amount == 0)
                    {
                        Buy("LTCUSD", 10);
                    }
                }
                else
                {
                    if (Portfolio.CashBook["LTC"].Amount > 0)
                    {
                        // The following two statements currently behave differently if we have initial holdings:
                        // https://github.com/QuantConnect/Lean/issues/1860

                        Liquidate("LTCUSD");
                        // SetHoldings("LTCUSD", 0);
                    }
                }
            }
        }
Пример #9
0
 public override void OnWarmupFinished()
 {
     Transactions.CancelOpenOrders();
     LogHoldings("<OnWarmupFinished>");
 }
Пример #10
0
        public override void Initialize()
        {
            //set trade period
            SetStartDate(2014, 6, 1);  //Set Start Date
            SetEndDate(2018, 6, 1);    //Set End Date

            //set total capital
            SetCash(TOTALCASH);             //Set Strategy Cash

            SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash);

            //select stocks to be traded.
            stockSelection();

            DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb["America/New_York"];

            Schedule.On(DateRules.EveryDay(), TimeRules.At(9, 40, TimeZone), () =>
            {
                List <SymbolData> ranks = new List <SymbolData>();
                decimal tmp             = 0;

                foreach (var val in _sd.Values)
                {
                    if (!val.Security.Exchange.DateIsOpen(Time))
                    {
                        continue;
                    }
                    else
                    {
                        Transactions.CancelOpenOrders(val.Symbol);      //close all open orders at the daily beginning
                        if (!val.IsReady)
                        {
                            continue;
                        }
                    }

                    var tradeBarHistory = History <TradeBar>(val.Symbol, TimeSpan.FromDays(HS), Resolution.Daily);

                    //Calculate LSma
                    foreach (TradeBar tradeBar in tradeBarHistory)
                    {
                        tmp = tmp + tradeBar.Close;
                        //Debug("His_bar time: " + tradeBar.Time);
                    }
                    if (tradeBarHistory.Count() > 0)
                    {
                        val.LSma = tmp / tradeBarHistory.Count();
                    }
                    else
                    {
                        continue;
                    }

                    //Calculate SSma
                    int i = 0;
                    int count;
                    tmp = 0;
                    if (tradeBarHistory.Count() - WD2 > 0)
                    {
                        i     = tradeBarHistory.Count() - WD2;
                        count = WD2;
                    }
                    else
                    {
                        count = tradeBarHistory.Count();
                    }
                    for (int j = i; j < tradeBarHistory.Count(); j++)
                    {
                        tmp = tmp + tradeBarHistory.ElementAt(j).Close;
                    }
                    val.SSma = tmp / count;

                    //System.Console.WriteLine("Count: " + tradeBarHistory.Count());

                    if (tradeBarHistory.Count() - WD1 > 0)
                    {
                        tmp = tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1).Close
                              - tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close;
                        if (tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close > 0)
                        {
                            tmp = tmp /
                                  tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close;
                        }
                        else
                        {
                            tmp = tmp / ZERO;
                        }
                    }
                    else
                    {
                        tmp = tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1).Close
                              - tradeBarHistory.ElementAt(0).Close;
                        if (tradeBarHistory.ElementAt(0).Close > 0)
                        {
                            tmp = tmp / tradeBarHistory.ElementAt(0).Close;
                        }
                        else
                        {
                            tmp = tmp / ZERO;
                        }
                    }
                    val.Return = tmp;
                    ranks.Add(val);
                }

                ranks.Sort(delegate(SymbolData x, SymbolData y) { return(y.CompareTo(x)); });

                for (int i = 0; i < ranks.Count; i++)
                {
                    if (i < TOP_K && ranks.ElementAt(i).SSma - ranks.ElementAt(i).LSma > 0)
                    {
                        ranks.ElementAt(i).wt = LEVERAGE / TOP_K;
                    }
                    else
                    {
                        ranks.ElementAt(i).wt = 0;
                    }
                }

                reweight(ranks);
            });
        }
Пример #11
0
        public override void Initialize()
        {
            SetStartDate(2006, 5, 1);  //Set Start Date
            SetEndDate(2015, 5, 1);    //Set End Date

            //Set up total capital
            SetCash(TOTALCASH);             //Set Strategy Cash

            SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);

            //select stocks to be traded.
            stockSelection();

            DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb["America/New_York"];

            Schedule.On(DateRules.EveryDay(), TimeRules.At(9, 40, TimeZone), () =>
            {
                foreach (var val in _sd.Values)
                {
                    if (!val.Security.Exchange.DateIsOpen(Time))
                    {
                        return;
                    }
                    else
                    {
                        Transactions.CancelOpenOrders(val.Symbol);      //close all open orders at the daily beginning
                        if (!val.IsReady)
                        {
                            return;
                        }
                    }
                }

                Dictionary <Symbol, IEnumerable <TradeBar> > bdic = new Dictionary <Symbol, IEnumerable <TradeBar> >();
                int count = -1;
                foreach (var val in _sd.Values)
                {
                    IEnumerable <TradeBar> bars = History <TradeBar>(val.Symbol, TimeSpan.FromDays(HS), Resolution.Daily);
                    //Debug(Time + " " + val.Symbol + " " + bars.Count());
                    if (bars.Count() != count && count != -1)
                    {
                        return;
                    }
                    count = bars.Count();
                    bdic.Add(val.Symbol, bars);
                }

                //if less than 2 days, STD will be 0.
                if (count < 2)
                {
                    return;
                }

                decimal[] comb_price_past_window = new decimal[count];
                for (int i = 0; i < count; i++)
                {
                    comb_price_past_window[i] = 0;
                }

                for (int i = 0; i < count; i++)
                {
                    int j = 0;
                    Nullable <DateTime> time = null;
                    foreach (KeyValuePair <Symbol, IEnumerable <TradeBar> > kv in bdic)
                    {
                        if (j > 0)
                        {
                            if (!time.Equals(kv.Value.ElementAt(i).Time))
                            {
                                return;
                            }
                        }
                        j++;
                        time = kv.Value.ElementAt(i).Time;
                        comb_price_past_window[i] = comb_price_past_window[i]
                                                    + _sd[kv.Key].Weight * kv.Value.ElementAt(i).Close;
                    }
                }

                decimal meanPrice  = comb_price_past_window.Average();
                double sum         = comb_price_past_window.Sum(d => Math.Pow((double)(d - meanPrice), 2));
                decimal stdPrice   = (decimal)Math.Sqrt(sum / comb_price_past_window.Count());
                decimal comb_price = 0;

                foreach (var val in _sd.Values)
                {
                    comb_price = comb_price + val.Weight * val.Security.Close;
                }
                //Debug("Debug: " + Time + ": std: " + stdPrice);
                decimal h = (comb_price - meanPrice) / stdPrice;

                //update positions
                foreach (var val in _sd.Values)
                {
                    decimal current_position = val.Security.Holdings.Quantity;
                    //Debug("Debug: Time: " + Time + " Symbol: " + val.Symbol +
                    //" current_position:" + current_position);
                    decimal new_position = USHARE * -1 * h * val.Weight;
                    //Debug("Debug: Time: " + Time + " Symbol: " + val.Symbol +
                    //" new_position:" + current_position);
                    MarketOrder(val.Symbol, new_position - current_position);
                }
            });
        }