Пример #1
0
        private void Compare(CoinCapTradeEvent tradeEvent)
        {
            var last = LastPrice.Price;
            var curr = tradeEvent.Msg.Price;
            var move = (curr / last) - 1m;
            var perc = move * 100;
            var mesg = $"{tradeEvent.Msg.Long} moved by {perc:N2}% to ${tradeEvent.Msg.Price:N4} over {Window.Humanize()}";

            if (perc >= PercentageThreshold || perc < -PercentageThreshold)
            {
                if (!IsPaused)
                {
                    var alertsChannel = $"#alerts-{User}";
                    if (alertsChannel.Length > 22)
                    {
                        alertsChannel = alertsChannel.Substring(0, 22);
                    }
                    var sm = new SlackMessage {
                        Channel = alertsChannel, Text = mesg, Mrkdwn = false, Username = "******"
                    };
                    _slackMessenger.Post(sm);
                }
                Logger.Warn(mesg);
            }
            else
            {
                Logger.Debug(mesg);
            }

            LastPrice = new PricePoint {
                Coin = Coin, Price = curr
            };
        }
Пример #2
0
        public void Load(XmlElement xmlElem)
        {
            XmlNodeList nodes = xmlElem.GetElementsByTagName("startpoint");

            if (nodes.Count != 0)
            {
                if (this.StartPoint == null)
                {
                    this.StartPoint = new PricePoint();
                }
                this.StartPoint.Load((XmlElement)nodes[0]);
            }

            nodes = xmlElem.GetElementsByTagName("endpoint");
            if (nodes.Count != 0)
            {
                if (this.EndPoint == null)
                {
                    this.EndPoint = new PricePoint();
                }
                this.EndPoint.Load((XmlElement)nodes[0]);
            }

            if (xmlElem.HasAttribute("width"))
            {
                this.Width = int.Parse(xmlElem.GetAttribute("width"));
            }
            if (xmlElem.HasAttribute("color"))
            {
                this.Color = ColorTranslator.FromHtml(xmlElem.GetAttribute("color"));
            }
        }
Пример #3
0
        public double evaluate(double timeSeconds)
        {
            PricePoint point = null;
            int        num   = -1;

            for (int i = this.PricePoints.Count - 1; i >= 0; i--)
            {
                if (timeSeconds >= this.PricePoints[i].TimeSeconds)
                {
                    point = this.PricePoints[i];
                    num   = i;
                    break;
                }
            }
            if (point == null)
            {
                Debug.LogError("PricePoint not found for value: " + timeSeconds);
                return(0.0);
            }
            if (num == (this.PricePoints.Count - 1))
            {
                return((point.Cost / point.TimeSeconds) * timeSeconds);
            }
            PricePoint point2 = this.PricePoints[num + 1];

            return((((point2.Cost - point.Cost) / (point2.TimeSeconds - point.TimeSeconds)) * (timeSeconds - point.TimeSeconds)) + point.Cost);
        }
Пример #4
0
            public static PricePoint GetPricePoint(JToken test, string currency_pair)
            {
                PricePoint p = new PricePoint();

                p.Currency = currency_pair;

                p.LinuxTime = (int)test[0];
                p.Low       = (float)test[1];
                p.High      = (float)test[2];
                p.Open      = (float)test[3];
                p.Close     = (float)test[4];
                p.Volume    = (float)test[5];

                if (currency_pair.EndsWith("USD"))
                {
                    p.Low = p.Low * USD_EUR;
                }

                int unixTimeStamp = p.LinuxTime;

                System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                DateTime        date       = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();

                p.DateTime = date;
                p.Date     = date.ToString();

                return(p);
            }
Пример #5
0
        public static double GetAverage(StockData data, int startIndex, int count, PricePoint pricePoint)
        {
            double result = 0;

            if (startIndex + count <= data.TimeSeries.DataPoints.Count)
            {
                for (int i = 0; i < count; i++)
                {
                    switch (pricePoint)
                    {
                    case PricePoint.Close:
                        result += data.TimeSeries.DataPoints[startIndex + i].Close;
                        break;

                    case PricePoint.Low:
                        result += data.TimeSeries.DataPoints[startIndex + i].Low;
                        break;

                    case PricePoint.High:
                        result += data.TimeSeries.DataPoints[startIndex + i].High;
                        break;

                    case PricePoint.Open:
                        result += data.TimeSeries.DataPoints[startIndex + i].Open;
                        break;

                    case PricePoint.Volume:
                        result += data.TimeSeries.DataPoints[startIndex + i].Volume;
                        break;
                    }
                }
                result /= count;
            }
            return(result);
        }
Пример #6
0
        public IActionResult GetTickerPriceOverTimespan([FromRoute][Required] int tickerId, [FromQuery][Required] int timespanId /*, [FromHeader][Required] string token*/)
        {
            /*if (!Authentication.IsTokenValid(token)) {
             *      return Problem("token is not valid");
             * }*/

            List <PricePoint> pricePoints = new List <PricePoint>();

            using (SqlConnection conn = new SqlConnection(Startup.ConnectionString)) {
                conn.Open();

                SqlCommand command = new SqlCommand(@"SELECT * FROM [PricePoint] WHERE (TickerId = @tickerId) AND (TimespanId = @timespanId) ORDER BY CloseTimestamp ASC;", conn);
                command.Parameters.AddWithValue("@tickerId", tickerId);
                command.Parameters.AddWithValue("@timespanId", timespanId);


                using (SqlDataReader reader = command.ExecuteReader()) {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            DateTimeOffset tickTime = new DateTimeOffset(reader.GetDateTime(8).Ticks, new TimeSpan(-5, 0, 0));
                            //DateTime tickTimer = new DateTime(tickTime.ToUnixTimeSeconds());

                            PricePoint pricePoint = new PricePoint(
                                reader.GetInt32(0),
                                reader.GetInt32(1),
                                reader.GetInt32(2),
                                reader.GetDouble(3),
                                reader.GetDouble(4),
                                reader.GetDouble(5),
                                reader.GetDouble(6),
                                reader.GetDouble(7),
                                //reader.GetDateTime(8).ToString("yyyy-MM-dd"),// HH:mm:ss"),
                                tickTime.ToUnixTimeMilliseconds(),
                                //tickTime.ToString(),
                                reader.GetDouble(9),
                                reader.GetInt32(10)
                                );

                            pricePoints.Add(pricePoint);
                        }
                    }
                    else
                    {
                        return(Problem("Invalid ticker or timespan"));
                    }
                }
            }

            if (pricePoints == null)
            {
                return(NotFound("no prices found"));
            }
            else
            {
                return(Ok(JsonConvert.SerializeObject(pricePoints, Formatting.Indented)));
            }
        }
        private static void addPricePoint(SQLiteDB db, PricePoint point, CommodityPrice price)
        {
            Dictionary <string, string> pointFieldValues = new Dictionary <string, string>();

            pointFieldValues.Add("CommodityPriceGuid", price.Guid.ToString());
            pointFieldValues.Add("Price", point.Price.ToString());
            pointFieldValues.Add("DateTime", point.DateTime.Ticks.ToString());
            db.AddValueToTable("PricePoint", pointFieldValues);
        }
Пример #8
0
        async internal static Task GetHistoricValues(int granularity, string currency_pair)
        {
            String URL = "https://api.gdax.com/products/" + currency_pair + "/candles";

            if (granularity != 0)
            {
                URL += "?granularity=" + granularity; //https://api.gdax.com/products/ETH-EUR/candles?granularity=60
            }
            HttpClient httpClient = new HttpClient();

            //Add a user-agent header to the GET request.
            var headers = httpClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri(URL);

            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string response = "";

            try {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();

                response = await httpResponse.Content.ReadAsStringAsync();

                var data = JRaw.Parse(response);

                int count = ((JContainer)data).Count;

                pp.Clear();
                //List<PricePoint> p = new List<PricePoint>();
                for (int i = 0; i < count; i++)
                {
                    pp.Add(PricePoint.GetPricePoint(data[i], currency_pair));
                }
            }
            catch (Exception ex) {
                response = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
Пример #9
0
        ////////////////////////////////////////////////////////////////////////////////////////
        internal async static Task GetHisto(string crypto, string time, int limit)
        {
            //CCCAGG    Bitstamp Bitfinex Coinbase HitBTC Kraken Poloniex
            String URL = "https://min-api.cryptocompare.com/data/histo" + time + "?e=CCCAGG&fsym="
                         + crypto + "&tsym=" + coin + "&limit=" + limit;

            if (limit == 0)
            {
                URL = "https://min-api.cryptocompare.com/data/histoday?e=CCCAGG&fsym=" + crypto + "&tsym=" + coin + "&allData=true";
            }

            Uri                 uri          = new Uri(URL);
            HttpClient          httpClient   = new HttpClient();
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            string response = "";

            try {
                response = await httpClient.GetStringAsync(uri);

                var data = JToken.Parse(response);

                historic.Clear();
                int lastIndex = ((JContainer)data["Data"]).Count;
                for (int i = 0; i < lastIndex; i++)
                {
                    historic.Add(PricePoint.GetPricePointHisto(data["Data"][i]));
                }
                switch (crypto)
                {
                case "BTC":
                    BTC_now = (float)Math.Round((float)data["Data"][lastIndex - 1]["close"], 2);
                    BTC_old = (float)Math.Round((float)data["Data"][0]["close"], 2);
                    break;

                case "ETH":
                    ETH_now = (float)Math.Round((float)data["Data"][lastIndex - 1]["close"], 2);
                    ETH_old = (float)Math.Round((float)data["Data"][0]["close"], 2);
                    break;

                case "LTC":
                    LTC_now = (float)Math.Round((float)data["Data"][lastIndex - 1]["close"], 2);
                    LTC_old = (float)Math.Round((float)data["Data"][0]["close"], 2);
                    break;

                case "XRP":
                    XRP_now = (float)Math.Round((float)data["Data"][lastIndex - 1]["close"], 2);
                    XRP_old = (float)Math.Round((float)data["Data"][0]["close"], 2);
                    break;
                }
            } catch (Exception ex) {
                //var dontWait = await new MessageDialog(ex.Message).ShowAsync();
            }
        }
Пример #10
0
 public static double GetSMA(StockData data, int index, int period, PricePoint pricePoint)
 {
     if (index + 1 - period >= 0)
     {
         return(GetAverage(data, index + 1 - period, period, pricePoint));
     }
     else
     {
         return(-1);
     }
 }
Пример #11
0
        public void DrawPolyLine(PricePolyLine polyLine)
        {
            PriceRectangle priceRect = mapping.PriceRect;
            int            start     = priceRect.StartIndex;
            int            end       = priceRect.EndIndex;

            for (int i = 0; i < polyLine.Points.Count; i++)
            {
                PricePoint point = polyLine.Points[i];
            }
        }
Пример #12
0
        public PricePoint Get()
        {
            PricePoint pp = new PricePoint();

            pp.Price       = this.numericUpDownValue.Value;
            pp.StopOffset  = this.stopPriceCustomNumericUpDown.Value;
            pp.TrailPrcntg = this.trailPrcntgNumericUpDown.Value;
            pp.Type        = (PricePointControl.OrderType) this.comboBoxOrderType.SelectedValue;
            pp.Execution   = (PricePointControl.Execution) this.comboBoxExecution.SelectedValue;
            pp.Trigger     = (TriggerType)this.triggerComboBox.SelectedValue;
            pp.FollowPrice = (PricePointControl.FollowPrice) this.toFollowComboBox.SelectedValue;
            pp.NoOfShares  = (int)this.numericUpDownNoOfShares.Value;
            return(pp);
        }
Пример #13
0
 public void Set(PricePoint pp)
 {
     this.numericUpDownValue.Value           = pp.Price;
     this.stopPriceCustomNumericUpDown.Value = pp.StopOffset;
     this.trailPrcntgNumericUpDown.Value     = pp.TrailPrcntg;
     this.comboBoxOrderType.SelectedItem     = pp.Type;
     this.comboBoxExecution.SelectedItem     = pp.Execution;
     if (pp.NoOfShares < 0)
     {
         pp.NoOfShares *= -1;
     }
     this.numericUpDownNoOfShares.Value = pp.NoOfShares;
     this.triggerComboBox.SelectedItem  = pp.Trigger;
     this.toFollowComboBox.SelectedItem = pp.FollowPrice;
 }
Пример #14
0
        public void UpdatePricing(decimal bidPrice, decimal askPrice, DateTime timestamp)
        {
            // Add price point to history
            PricePoint p = new PricePoint(bidPrice, askPrice, timestamp);

            _history.AddPoint(ref p);

            // and update current values
            CurrentBidPrice = bidPrice;
            CurrentAskPrice = askPrice;

            // Finally, let any interested clients know
            var priceUpdate = new PriceUpdate(Symbol, bidPrice, askPrice, timestamp);

            NotifySubscribers(priceUpdate);
        }
Пример #15
0
 public void Load(XmlElement xmlElem)
 {
     if (this.point == null)
     {
         this.point = new PricePoint();
     }
     this.point.Load(xmlElem);
     if (xmlElem.HasAttribute("text"))
     {
         this.text = xmlElem.GetAttribute("text");
     }
     if (xmlElem.HasAttribute("color"))
     {
         this.Color = ColorTranslator.FromHtml(xmlElem.GetAttribute("color"));
     }
 }
Пример #16
0
        private void HandlePriceChange(List <PricePoint> prices, OrderTracker orderTracker, decimal quantity,
                                       decimal priceDelta)
        {
            decimal mostRecentOrderPrice = orderTracker.Price;

            if (prices.Count == 0)
            {
                //if there's no best price, we can't decide what price to place, so exit
                return;
            }
            PricePoint bestPriceInTheMarket = prices[0];

            // Make sure we have a best bid price, and it's not the same as the order we just placed
            // and place similar to the ask price change.
            if (mostRecentOrderPrice == 0 || mostRecentOrderPrice != bestPriceInTheMarket.Price)
            {
                switch (orderTracker.OrderState)
                {
                // Place an order inside the spread if there isn't one currently in the market
                case OrderState.None:
                    orderTracker.Price = bestPriceInTheMarket.Price + priceDelta;

                    orderTracker.InstructionId = NextInstructionId();
                    LimitOrderSpecification order =
                        new LimitOrderSpecification(orderTracker.InstructionId, _instrumentId, orderTracker.Price,
                                                    quantity, TimeInForce.GoodForDay);

                    _session.PlaceLimitOrder(order,
                                             OrderSuccessCallback(orderTracker),
                                             FailureCallback("Place order failed for instruction ID " +
                                                             orderTracker.InstructionId));
                    break;

                // Cancel a working order on a price change.
                case OrderState.Working:
                    CancelOrder(orderTracker);
                    break;
                }
            }
        }
Пример #17
0
        public void Initialise(ITradeObserver tradeObserver, ISlackMessenger slackMessenger)
        {
            _slackMessenger = slackMessenger;

            // Get the first price update  (no need to dispose as First() completes automatically)
            tradeObserver.TradeStream
            .Where(t => t.Coin.Equals(Coin))
            .FirstAsync()
            .Subscribe(first =>
            {
                // Note the price
                LastPrice = new PricePoint {
                    Coin = first.Coin, Price = first.Msg.Price
                };

                // Subscribe to the relevant window
                _subscription = tradeObserver.TradeStream
                                .Where(t => t.Coin.Equals(Coin))
                                .Sample(Window)
                                .Subscribe(Compare);
            });
        }
Пример #18
0
        public void PlaceOrder(string ticker, PricePoint pricePoint, TimeInForce tif)
        {
            Account account = Robinhood.rh.DownloadAllAccounts().Result.First();

            Instrument instrument = null;

            while (instrument == null)
            {
                try
                {
                    instrument = Robinhood.rh.FindInstrument(ticker.ToUpperInvariant()).Result.First(i => i.Symbol == ticker);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Problem. Try again. " + e.Message);
                }
            }

            var newOrderSingle = new NewOrderSingle(instrument);

            newOrderSingle.AccountUrl = account.AccountUrl;
            newOrderSingle.Quantity   = Math.Abs(pricePoint.NoOfShares);
            newOrderSingle.Side       = pricePoint.NoOfShares > 0 ? Side.Buy : Side.Sell;

            newOrderSingle.TimeInForce = tif;
            if (pricePoint.Price == 0)
            {
                newOrderSingle.OrderType = OrderType.Market;
            }
            else
            {
                newOrderSingle.OrderType = OrderType.Limit;
                newOrderSingle.Price     = pricePoint.Price;
            }

            var order = Robinhood.rh.PlaceOrder(newOrderSingle).Result;
        }
Пример #19
0
        internal async static Task GetCoinStats(String crypto)
        {
            String URL = "https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=" + crypto + "&tsym=" + coin;

            Uri                 requestUri   = new Uri(URL);
            HttpClient          httpClient   = new HttpClient();
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            string response = "";

            try {
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();

                response = await httpResponse.Content.ReadAsStringAsync();

                var data = JToken.Parse(response);

                stats = PricePoint.GetPricePointStats(data["Data"]["AggregatedData"]);
            } catch (Exception ex) {
                var dontWait = await new MessageDialog(ex.Message).ShowAsync();
            }
        }
Пример #20
0
        private static double natLogReturn(StockData data, int index, PricePoint pricePoint)
        {
            double result = 0;

            if (index - 1 >= 0)
            {
                double priceI     = 1;
                double priceIPrev = 1;

                switch (pricePoint)
                {
                case PricePoint.Close:
                    priceI     = data.TimeSeries.DataPoints[index].Close;
                    priceIPrev = data.TimeSeries.DataPoints[index - 1].Close;
                    break;

                case PricePoint.Low:
                    priceI     = data.TimeSeries.DataPoints[index].Low;
                    priceIPrev = data.TimeSeries.DataPoints[index - 1].Low;
                    break;

                case PricePoint.High:
                    priceI     = data.TimeSeries.DataPoints[index].High;
                    priceIPrev = data.TimeSeries.DataPoints[index - 1].High;
                    break;

                case PricePoint.Open:
                    priceI     = data.TimeSeries.DataPoints[index].Open;
                    priceIPrev = data.TimeSeries.DataPoints[index - 1].Open;
                    break;
                }

                result = Math.Log(priceI / priceIPrev);
            }
            return(result);
        }
Пример #21
0
        public void Load(XmlElement xmlElem)
        {
            XmlNodeList nodes = xmlElem.GetElementsByTagName("point");

            for (int i = 0; i < nodes.Count; i++)
            {
                XmlNode node = nodes[i];
                if (node is XmlElement)
                {
                    XmlElement nodeElem = (XmlElement)node;
                    PricePoint point    = new PricePoint();
                    point.Load(nodeElem);
                    this.points.Add(point);
                }
            }
            if (xmlElem.HasAttribute("width"))
            {
                this.Width = int.Parse(xmlElem.GetAttribute("width"));
            }
            if (xmlElem.HasAttribute("color"))
            {
                this.Color = ColorTranslator.FromHtml(xmlElem.GetAttribute("color"));
            }
        }
Пример #22
0
 public void Removepoint(PricePoint point)
 {
     this.points.Remove(point);
 }
Пример #23
0
            public static int[] FindTurningPoints(StockData data, int startIndex, int SMAPeriod, PricePoint pricePoint)
            {
                List <int> PointIndices = new List <int>();
                int        dataCount    = data.TimeSeries.DataPoints.Count;
                double     prevSMA      = -1;
                double     newSMA;
                int        priceDir = 0;

                for (int i = startIndex; i < dataCount; i++)
                {
                    newSMA = Indicators.GetSMA(data, i, SMAPeriod, pricePoint);
                    if (prevSMA >= 0 && newSMA >= 0)
                    {
                        if (newSMA > prevSMA)
                        {
                            if (priceDir <= 0)
                            {
                                if (priceDir != 0)
                                {
                                    PointIndices.Add(i);
                                }
                                priceDir = 1;
                            }
                        }
                        else if (newSMA < prevSMA)
                        {
                            if (priceDir >= 0)
                            {
                                if (priceDir != 0)
                                {
                                    PointIndices.Add(i);
                                }
                                priceDir = -1;
                            }
                        }
                    }
                    prevSMA = newSMA;
                }
                return(PointIndices.ToArray());
            }
Пример #24
0
        ///// <summary>
        ///// Gets the best supplier's name, part number, and price breaks,
        ///// from the JSON result string, based on supplier affinity.
        ///// </summary>
        ///// <remarks>
        ///// For our current purposes of costing the board in US dollars, only suppliers
        ///// who have price lists in US dollars are considered qualified.
        /////
        ///// To find the best supplier for this part, first we create two dictionaries:
        ///// one that maps all qualified suppliers to their quantity in stock, and one
        ///// that maps all qualified suppliers to their US-dollar price list.
        /////
        ///// Then, the best supplier is the first supplier we find on the affinity list
        ///// who is also in our dictionary of qualified suppliers.
        /////
        ///// If none of the affinity suppliers make the cut, then the best is considered
        ///// to be the qualified supplier with the maximum number of these parts in stock.
        ///// </remarks>
        ///// <param name="supplierName">The best supplier's name</param>
        ///// <param name="supplierPartNumber">The best supplier's part number</param>
        ///// <param name="supplierPriceBreaks">The best supplier's price breaks, in US dollars</param>
        ///// <param name="OctopartResult">The input JSON results string</param>
        ///// <param name="SourceAffinity">A list of preferred suppliers, with the most favored first.</param>
        //public static void GetSupplierNameAndPartNumberAndPriceBreaks(
        //        out string supplierName,
        //        out string supplierPartNumber,
        //        out List<KeyValuePair<int, float>> supplierPriceBreaks,
        //        String OctopartResult,
        //        List<String> SourceAffinity = null)
        //{
        //    supplierName = "";
        //    supplierPartNumber = "";
        //    supplierPriceBreaks = new List<KeyValuePair<int, float>>();

        //    dynamic dynJson = JsonConvert.DeserializeObject(OctopartResult);
        //    bool done = false;

        //    Dictionary<string, string> mapSupplierToPartNumber = new Dictionary<string, string>();
        //    Dictionary<string, int> mapSupplierToQtyInStock = new Dictionary<string, int>();

        //    // Create a mapping of suppliers to part numbers and qualified in-stock quantities.
        //    // For now, only suppliers that have a price list in US dollars are considered qualified.
        //    if ((dynJson != null) &&
        //        (dynJson.offers != null))
        //    {
        //        foreach (var item in dynJson.offers)
        //        {
        //            string partNumber = item.sku;
        //            string supplier = item.seller.name;
        //            int qtyInStock = item.in_stock_quantity;

        //            if ((item.prices != null) && (item.prices.USD != null))
        //            {
        //                // Only choose suppliers who have price breaks in US dollars.
        //                mapSupplierToPartNumber.Add(supplier, partNumber);
        //                mapSupplierToQtyInStock.Add(supplier, qtyInStock);
        //            }
        //        }
        //    }

        //    // Check if any of our favorite sources are listed
        //    if (null != SourceAffinity)
        //    {
        //        foreach (string favSource in SourceAffinity)
        //        {
        //            if (mapSupplierToPartNumber.ContainsKey(favSource))
        //            {
        //                // We found a favorite source...
        //                supplierName = favSource;
        //                supplierPartNumber = mapSupplierToPartNumber[favSource];
        //                done = true;    // so, we are done.
        //                break;
        //            }
        //        }
        //    }

        //    if (!done)
        //    {
        //        // No favorite source was found, so find a supplier with maximum stock available.
        //        int maxAvailable = -1;
        //        foreach (KeyValuePair<string, int> entry in mapSupplierToQtyInStock)
        //        {
        //            int qtyInStock = entry.Value;
        //            if (qtyInStock > maxAvailable)
        //            {
        //                maxAvailable = qtyInStock;
        //                supplierName = entry.Key;
        //                supplierPartNumber = mapSupplierToPartNumber[supplierName];
        //            }
        //        }
        //    }

        //    // Find the price breaks for this supplier.
        //    if( supplierName.Length > 0 )
        //    {
        //        // Find our chosen seller's offer.
        //        foreach (var item in dynJson.offers)
        //        {
        //            if( item.seller.name == supplierName )
        //            {
        //                // We found the seller's offer
        //                if ((item.prices != null) && (item.prices.USD != null))
        //                {
        //                    // only take price lists in US dollars for now.
        //                    foreach (var pair in item.prices.USD)
        //                    {
        //                        int qty = pair[0];
        //                        float price = float.Parse((string)pair[1]);

        //                        KeyValuePair<int, float> pricePoint = new KeyValuePair<int, float>(qty, price);
        //                        supplierPriceBreaks.Add(pricePoint);
        //                    }
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}


        /// <summary>
        /// Fill in the sellermapStructure from the Octopart results string.
        /// </summary>
        /// <param name="OctopartResult">The Octopart results string to parse.</param>
        /// <returns>the filled-in sellermapStructure</returns>
        public static SellerMapStruct GetSellerMapStructure(String OctopartResult)
        {
            var sellermapStructure = new SellerMapStruct();

            sellermapStructure.sellerMap = new Dictionary <string, SkuMapStruct>();
            dynamic dynJson = JsonConvert.DeserializeObject(OctopartResult);

            if ((dynJson != null) && (dynJson.offers != null))
            {
                foreach (var offer in dynJson.offers)
                {
                    // get the sku
                    string sku = "";
                    if (offer.sku != null)
                    {
                        sku = offer.sku;
                    }

                    // get the seller name
                    string sellerName = "";
                    if ((offer.seller != null) && (offer.seller.name != null))
                    {
                        sellerName = offer.seller.name;
                    }

                    // Check if the seller isn't already in the seller map
                    if (!sellermapStructure.sellerMap.ContainsKey(sellerName))
                    {
                        // We need to add it with an empty SKU map structure.
                        SkuMapStruct emptySkuMapStruct = new SkuMapStruct();
                        sellermapStructure.sellerMap.Add(sellerName, emptySkuMapStruct);
                    }

                    // Check if the SKU is in the SKU map structure.
                    if (!sellermapStructure.sellerMap[sellerName].skuMap.ContainsKey(sku))
                    {
                        CurrencyMapStruct emptyCurrencyMapStruct = new CurrencyMapStruct();
                        sellermapStructure.sellerMap[sellerName].skuMap.Add(sku, emptyCurrencyMapStruct);
                    }

                    // Cerate an alias to avoid a few levels of indirection
                    CurrencyMapStruct thisCurrencyMapStruct = sellermapStructure.sellerMap[sellerName].skuMap[sku];

                    // get the prices
                    if (offer.prices != null)
                    {
                        foreach (var currency in offer.prices)
                        {
                            string currencyCode = "";
                            // Get the currency code
                            currencyCode = currency.Name;

                            List <PricePoint> priceBreaks = new List <PricePoint>();
                            foreach (var pricePair in currency.Value)
                            {
                                int        qty        = pricePair[0];
                                float      price      = float.Parse((string)pricePair[1], CultureInfo.InvariantCulture);
                                PricePoint pricePoint = new PricePoint(qty, price);
                                priceBreaks.Add(pricePoint);
                            }

                            // Add the price breaks to the currency map
                            thisCurrencyMapStruct.currencyMap[currencyCode] = priceBreaks;
                        }
                    }
                }
            }

            return(sellermapStructure);
        }
Пример #25
0
 public void AddPoint(PricePoint point)
 {
     this.points.Add(point);
 }
Пример #26
0
        public static double GetAnualVolatility(StockData data, int index, int period, PricePoint pricePoint)
        {
            double result = 0;

            if (index + 1 - period > 0)
            {
                double dailyVol = GetDailyVolatility(data, index, period, pricePoint);
                result = dailyVol * Math.Sqrt(252);
            }
            return(result);
        }
Пример #27
0
        public static void PlaceOrder(Stock stock, TimeInForce tif, TradeStep tradeStep, Form parentForm)
        {
            string     errString      = string.Empty;
            PricePoint pricePoint     = null;
            var        newOrderSingle = new NewOrderSingle();

            try
            {
                Account account = rh.DownloadAllAccounts().Result.First();
                //if (pricePoint.PendingOrders == null)
                //  pricePoint.PendingOrders = new Dictionary<decimal, String>();
                if (tradeStep == TradeStep.Entry)
                {
                    pricePoint = stock.Entry;
                }
                else if (tradeStep == TradeStep.ProfitTarget)
                {
                    pricePoint = stock.PriceTarget;
                    if (pricePoint.NoOfShares > 0)
                    {
                        pricePoint.NoOfShares *= -1;
                    }
                }
                else if (tradeStep == TradeStep.StopLoss)
                {
                    if (stock.PendingOrders != null && stock.PendingOrders.Any(o => o.Side == Side.Sell && o.Trigger == "stop"))
                    {
                        ThreadPool.QueueUserWorkItem(Robinhood.CancelOrder,
                                                     new KeyValuePair <Form, ThreadedBindingList <OrderSnapshot> >(parentForm, stock.PendingOrders));
                    }

                    while (stock.PendingOrders != null && stock.PendingOrders.Count > 0)
                    {
                        Thread.Sleep(1000);
                    }

                    pricePoint = stock.StopLoss;
                    if (pricePoint.NoOfShares > 0)
                    {
                        pricePoint.NoOfShares *= -1;
                    }
                }
                else
                {
                    pricePoint = null;
                }

                Instrument instrument = null;
                while (instrument == null)
                {
                    try
                    {
                        instrument = rh.FindInstrument(stock.Ticker.ToUpperInvariant()).Result.First(i => i.Symbol == stock.Ticker);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Problem. Try again. " + e.Message);
                    }
                }

                lastOrderSuccess = false;
                if (pricePoint.Execution == CustomControls.PricePointControl.Execution.Limit ||
                    pricePoint.Execution == CustomControls.PricePointControl.Execution.Trailing)
                {
                    newOrderSingle             = new NewOrderSingle(instrument);
                    newOrderSingle.AccountUrl  = account.AccountUrl;
                    newOrderSingle.TimeInForce = tif;
                    newOrderSingle.Side        = pricePoint.NoOfShares > 0 ? Side.Buy : Side.Sell;
                    newOrderSingle.Quantity    = Math.Abs(pricePoint.NoOfShares);
                    newOrderSingle.OrderType   = (OrderType)Enum.Parse(typeof(OrderType), pricePoint.Type.ToString());
                    newOrderSingle.Trigger     = pricePoint.Trigger;
                    //if (pricePoint.Value == 0)
                    //{
                    //  //newOrderSingle.OrderType = OrderType.Market;
                    //}
                    //else
                    //{
                    //newOrderSingle.OrderType = OrderType.Limit;
                    if (pricePoint.Trigger == TriggerType.Stop)
                    {
                        //newOrderSingle.OrderType = OrderType.Market;
                        //newOrderSingle.Trigger = "stop";
                        if (newOrderSingle.OrderType == OrderType.Limit)
                        {
                            newOrderSingle.Price = pricePoint.Price;
                        }
                        else if (newOrderSingle.OrderType == OrderType.Market)
                        {
                            newOrderSingle.Price = stock.LastTradePrice;
                        }

                        newOrderSingle.StopPrice = pricePoint.Price + pricePoint.StopOffset;
                    }
                    else if (pricePoint.Trigger == TriggerType.Immediate)
                    {
                        newOrderSingle.Price = pricePoint.Price;
                    }
                    //}

                    var order = rh.PlaceOrder(newOrderSingle).Result;
                    PlacingOrder.Set();

                    if (order.State == "queued")
                    {
                        lastOrderSuccess = true;
                    }
                    // var test = rh.DownloadAllOrders().Result;
                    //test.Start();
                    //test.Wait();
                    //pricePoint.PendingOrders.Add(pricePoint.Value, order.CancelUrl.Uri.AbsoluteUri.First());
                }
                else if (pricePoint.Execution == CustomControls.PricePointControl.Execution.Spread)
                {
                    int noOfShare = pricePoint.NoOfShares > 0 ? 1 : -1;
                    foreach (decimal orderValue in pricePoint.ExecutionSpread)
                    {
                        newOrderSingle             = new NewOrderSingle(instrument);
                        newOrderSingle.AccountUrl  = account.AccountUrl;
                        newOrderSingle.TimeInForce = tif;
                        newOrderSingle.Side        = pricePoint.NoOfShares > 0 ? Side.Buy : Side.Sell;
                        newOrderSingle.OrderType   = (OrderType)Enum.Parse(typeof(OrderType), pricePoint.Type.ToString());
                        newOrderSingle.Trigger     = pricePoint.Trigger;
                        newOrderSingle.Quantity    = Math.Abs(noOfShare);
                        if (pricePoint.Trigger == TriggerType.Stop)
                        {
                            if (newOrderSingle.OrderType == OrderType.Limit)
                            {
                                newOrderSingle.Price = orderValue;
                            }
                            newOrderSingle.StopPrice = orderValue + 0.02m;
                        }
                        else if (pricePoint.Trigger == TriggerType.Immediate)
                        {
                            newOrderSingle.Price = orderValue;
                        }

                        var order = rh.PlaceOrder(newOrderSingle).Result;
                        //pricePoint.PendingOrders.Add(pricePoint.Value, order.CancelUrl);
                    }
                }

                Notification notifForm = new Notification();
                parentForm.Invoke((MethodInvoker) delegate()
                {
                    notifForm.label1.Text = string.Format("{0} {1} {2} Order Sent for {3} shares at {4}",
                                                          stock.Ticker, newOrderSingle.Side, newOrderSingle.OrderType,
                                                          newOrderSingle.Quantity, newOrderSingle.Price);
                    notifForm.Show();
                });
            }
            catch (WebException e)
            {
                if (pricePoint.Execution != CustomControls.PricePointControl.Execution.Trailing &&
                    !stock.ManageTrade)
                {
                    if (pricePoint.NoOfShares > 0)
                    {
                        errString = String.Format("Error Placing Buy Order for {0}, Check network connection", stock.Ticker);
                    }
                    else
                    {
                        errString = String.Format("Error Placing Sell Order for {0}, Check network connection", stock.Ticker);
                    }

                    Notification notifForm = new Notification();
                    parentForm.Invoke((MethodInvoker) delegate()
                    {
                        notifForm.label1.Text = string.Format(errString);
                        notifForm.Show();
                    });
                }
            }
            catch (HttpException e)
            {
                if (pricePoint.Execution != CustomControls.PricePointControl.Execution.Trailing &&
                    !(stock.ManageTrade && tradeStep == TradeStep.StopLoss))
                {
                    if (pricePoint.NoOfShares > 0)
                    {
                        errString = String.Format("Error Placing Buy Order for {0}, Check network connection", stock.Ticker);
                    }
                    else
                    {
                        errString = String.Format("Error Placing Sell Order for {0}, Check network connection", stock.Ticker);
                    }

                    Notification notifForm = new Notification();
                    parentForm.Invoke((MethodInvoker) delegate()
                    {
                        notifForm.label1.Text = string.Format(errString);
                        notifForm.Show();
                    });
                }
            }
            catch
            {
                if (pricePoint.Execution != CustomControls.PricePointControl.Execution.Trailing &&
                    !(stock.ManageTrade && tradeStep == TradeStep.StopLoss))
                {
                    if (pricePoint.NoOfShares > 0)
                    {
                        errString = String.Format("Error Placing Buy Order for {0}, Check buying power", stock.Ticker);
                    }
                    else
                    {
                        errString = String.Format("Error Placing Sell Order for {0}, Make sure you have enough shares available", stock.Ticker);
                    }

                    Notification notifForm = new Notification();
                    parentForm.Invoke((MethodInvoker) delegate()
                    {
                        notifForm.label1.Text = string.Format(errString);
                        notifForm.Show();
                    });
                }
            }
        }
Пример #28
0
            private static PriceTrend GetTrend(StockData data, int index, int period, PricePoint pricePoint)
            {
                int        startIndex = index + 1 - period;
                PriceTrend result     = PriceTrend.Flat;

                if (startIndex >= 0)
                {
                    int      sectorCount         = 3;
                    int      sectorSize          = period / sectorCount;
                    double[] sectorSMAs          = new double[sectorCount];
                    int      remaininglastSector = period % sectorSize;

                    //get sector SMAs
                    for (int i = 0; i < sectorCount; i++)
                    {
                        switch (pricePoint)
                        {
                        case PricePoint.Close:
                            sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Close);
                            break;

                        case PricePoint.Low:
                            sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Low);
                            break;

                        case PricePoint.High:
                            sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.High);
                            break;

                        case PricePoint.Open:
                            sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Open);
                            break;
                        }
                    }

                    //compare sector SMAs
                    double lastSMA = sectorSMAs[0];
                    bool   isUp    = true;
                    bool   isDown  = true;
                    for (int i = 1; i < sectorCount; i++)
                    {
                        if (sectorSMAs[i] < lastSMA)
                        {
                            isUp = false;
                        }
                        if (sectorSMAs[i] > lastSMA)
                        {
                            isDown = false;
                        }
                        lastSMA = sectorSMAs[i];
                    }
                    if (isUp)
                    {
                        result = PriceTrend.Up;
                    }
                    if (isDown)
                    {
                        result = PriceTrend.Down;
                    }
                }
                return(result);
            }
Пример #29
0
 ///<summary>
 /// Compares this PricePoint to another one
 ///</summary>
 ///<param name="other">The PricePoint to compare this to</param>
 ///<returns>True if this PricePoint is equal to the second</returns>
 public bool Equals(PricePoint other)
 {
     return(other._price == _price && other._quantity == _quantity);
 }
Пример #30
0
 ///<summary>
 /// Compares this PricePoint to another one
 ///</summary>
 ///<param name="other">The PricePoint to compare this to</param>
 ///<returns>True if this PricePoint is equal to the second</returns>
 public bool Equals(PricePoint other)
 {
     return other._price == _price && other._quantity == _quantity;
 }
Пример #31
0
        ///// <summary>
        ///// Gets the best supplier's name, part number, and price breaks, 
        ///// from the JSON result string, based on supplier affinity.
        ///// </summary>
        ///// <remarks>
        ///// For our current purposes of costing the board in US dollars, only suppliers
        ///// who have price lists in US dollars are considered qualified.
        ///// 
        ///// To find the best supplier for this part, first we create two dictionaries:
        ///// one that maps all qualified suppliers to their quantity in stock, and one
        ///// that maps all qualified suppliers to their US-dollar price list.
        ///// 
        ///// Then, the best supplier is the first supplier we find on the affinity list
        ///// who is also in our dictionary of qualified suppliers.
        ///// 
        ///// If none of the affinity suppliers make the cut, then the best is considered
        ///// to be the qualified supplier with the maximum number of these parts in stock.
        ///// </remarks>
        ///// <param name="supplierName">The best supplier's name</param>
        ///// <param name="supplierPartNumber">The best supplier's part number</param>
        ///// <param name="supplierPriceBreaks">The best supplier's price breaks, in US dollars</param>
        ///// <param name="OctopartResult">The input JSON results string</param>
        ///// <param name="SourceAffinity">A list of preferred suppliers, with the most favored first.</param>
        //public static void GetSupplierNameAndPartNumberAndPriceBreaks(
        //        out string supplierName, 
        //        out string supplierPartNumber,
        //        out List<KeyValuePair<int, float>> supplierPriceBreaks,
        //        String OctopartResult, 
        //        List<String> SourceAffinity = null)
        //{
        //    supplierName = "";
        //    supplierPartNumber = "";
        //    supplierPriceBreaks = new List<KeyValuePair<int, float>>();

        //    dynamic dynJson = JsonConvert.DeserializeObject(OctopartResult);
        //    bool done = false;

        //    Dictionary<string, string> mapSupplierToPartNumber = new Dictionary<string, string>();
        //    Dictionary<string, int> mapSupplierToQtyInStock = new Dictionary<string, int>();

        //    // Create a mapping of suppliers to part numbers and qualified in-stock quantities.
        //    // For now, only suppliers that have a price list in US dollars are considered qualified.
        //    if ((dynJson != null) &&
        //        (dynJson.offers != null))
        //    {
        //        foreach (var item in dynJson.offers)
        //        {
        //            string partNumber = item.sku;
        //            string supplier = item.seller.name;
        //            int qtyInStock = item.in_stock_quantity;

        //            if ((item.prices != null) && (item.prices.USD != null))
        //            {
        //                // Only choose suppliers who have price breaks in US dollars.
        //                mapSupplierToPartNumber.Add(supplier, partNumber);
        //                mapSupplierToQtyInStock.Add(supplier, qtyInStock);
        //            }
        //        }
        //    }

        //    // Check if any of our favorite sources are listed
        //    if (null != SourceAffinity)
        //    {
        //        foreach (string favSource in SourceAffinity)
        //        {
        //            if (mapSupplierToPartNumber.ContainsKey(favSource))
        //            {
        //                // We found a favorite source...
        //                supplierName = favSource;
        //                supplierPartNumber = mapSupplierToPartNumber[favSource];
        //                done = true;    // so, we are done.
        //                break;
        //            }
        //        }
        //    }

        //    if (!done)
        //    {
        //        // No favorite source was found, so find a supplier with maximum stock available.
        //        int maxAvailable = -1;
        //        foreach (KeyValuePair<string, int> entry in mapSupplierToQtyInStock)
        //        {
        //            int qtyInStock = entry.Value;
        //            if (qtyInStock > maxAvailable)
        //            {
        //                maxAvailable = qtyInStock;
        //                supplierName = entry.Key;
        //                supplierPartNumber = mapSupplierToPartNumber[supplierName];
        //            }
        //        }
        //    }

        //    // Find the price breaks for this supplier.
        //    if( supplierName.Length > 0 )
        //    {
        //        // Find our chosen seller's offer.
        //        foreach (var item in dynJson.offers)
        //        {
        //            if( item.seller.name == supplierName )
        //            {
        //                // We found the seller's offer
        //                if ((item.prices != null) && (item.prices.USD != null))
        //                {
        //                    // only take price lists in US dollars for now.
        //                    foreach (var pair in item.prices.USD)
        //                    {
        //                        int qty = pair[0];
        //                        float price = float.Parse((string)pair[1]);

        //                        KeyValuePair<int, float> pricePoint = new KeyValuePair<int, float>(qty, price);
        //                        supplierPriceBreaks.Add(pricePoint);
        //                    }
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// Fill in the sellermapStructure from the Octopart results string.
        /// </summary>
        /// <param name="OctopartResult">The Octopart results string to parse.</param>
        /// <returns>the filled-in sellermapStructure</returns>
        public static SellerMapStruct GetSellerMapStructure( String OctopartResult)
        {
            var sellermapStructure = new SellerMapStruct();
            sellermapStructure.sellerMap = new Dictionary<string,SkuMapStruct>();
            dynamic dynJson = JsonConvert.DeserializeObject(OctopartResult);

            if ((dynJson != null) && (dynJson.offers != null))
            {
                foreach (var offer in dynJson.offers)
                {
                    // get the sku
                    string sku = "";
                    if (offer.sku != null)
                    {
                        sku = offer.sku;
                    }

                    // get the seller name
                    string sellerName = "";
                    if ((offer.seller != null) && (offer.seller.name != null))
                    {
                        sellerName = offer.seller.name;
                    }

                    // Check if the seller isn't already in the seller map
                    if (!sellermapStructure.sellerMap.ContainsKey(sellerName))
                    {
                        // We need to add it with an empty SKU map structure.
                        SkuMapStruct emptySkuMapStruct = new SkuMapStruct();
                        sellermapStructure.sellerMap.Add(sellerName, emptySkuMapStruct);
                    }

                    // Check if the SKU is in the SKU map structure.
                    if (!sellermapStructure.sellerMap[sellerName].skuMap.ContainsKey(sku))
                    {
                        CurrencyMapStruct emptyCurrencyMapStruct = new CurrencyMapStruct();
                        sellermapStructure.sellerMap[sellerName].skuMap.Add(sku, emptyCurrencyMapStruct);
                    }

                    // Cerate an alias to avoid a few levels of indirection
                    CurrencyMapStruct thisCurrencyMapStruct = sellermapStructure.sellerMap[sellerName].skuMap[sku];

                    // get the prices
                    if (offer.prices != null)
                    {
                        foreach (var currency in offer.prices)
                        {
                            string currencyCode = "";
                            // Get the currency code
                            currencyCode = currency.Name;

                            List<PricePoint> priceBreaks = new List<PricePoint>();
                            foreach (var pricePair in currency.Value)
                            {
                                int qty = pricePair[0];
                                float price = float.Parse((string)pricePair[1]);
                                PricePoint pricePoint = new PricePoint(qty,price);
                                priceBreaks.Add(pricePoint);
                            }

                            // Add the price breaks to the currency map
                            thisCurrencyMapStruct.currencyMap[currencyCode] = priceBreaks;
                        }
                    }
                }
            }

            return sellermapStructure;
        }
Пример #32
0
 public void DrawPoint(PricePoint points)
 {
 }