Example #1
0
        public static async Task SellOnPercentOverTime()
        {
            var restClient = new RestClient(Switches.AlpacaAPIKey(), Switches.AlpacaSecretAPIKey(), Switches.AlpacaEndPoint());

            if (File.Exists(Switches.stockDirectory + "Portfolio.csv"))
            {
                var allLines = File.ReadAllLines(Switches.stockDirectory + "Portfolio.csv");
                for (int i = 1; i < allLines.Count(); i++)
                {
                    string[] temp = allLines[i].Split(',');
                    var      p2   = await restClient.GetAssetAsync((temp[0]));

                    var position = await restClient.GetPositionAsync(temp[0]);

                    int numberOfShares = position.Quantity;
                    int daysAlloted    = DateTime.Today.Day - Convert.ToDateTime(temp[1]).Day;

                    //set minimal required selling point
                    double required = Convert.ToDouble(temp[3]);

                    if (daysAlloted < 7 && daysAlloted > 0)
                    {
                        required *= (1 + 0.005 * daysAlloted);
                    }
                    else if (daysAlloted >= 7 && daysAlloted < 30)
                    {
                        required *= (1.03);
                    }
                    else if (daysAlloted > 31 && daysAlloted <= 60)
                    {
                        required *= (1.1);
                    }
                    else
                    {
                        required *= 1.18;
                    }


                    try
                    {
                        if ((double)position.AssetCurrentPrice > required)
                        {
                            var order = await restClient.PostOrderAsync(temp[0], numberOfShares, OrderSide.Sell, OrderType.Market, TimeInForce.Day);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("could not sell because " + ex.ToString());
                    }
                }
            }
        }
Example #2
0
        public async static Task SellOnePercentGain()
        {
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers.Add("APCA-API-KEY-ID", Switches.AlpacaAPIKey());
                    client.Headers.Add("APCA-API-SECRET-KEY", Switches.AlpacaSecretAPIKey());

                    var stream    = client.DownloadString(Switches.AlpacaEndPoint() + "/v2/positions");
                    var Positions = JsonConvert.DeserializeObject <List <Position> >(stream);
                    foreach (var position in Positions)
                    {
                        //if current price is greater than 1 %
                        if (position.current_price > position.avg_entry_price * 1.01M)
                        {
                            //sell
                            SellStock(position.symbol, position.qty).Wait();

                            /*
                             * AlpacaTradingClientConfiguration config = new AlpacaTradingClientConfiguration();
                             * config.ApiEndpoint = new Uri(Switches.AlpacaEndPoint());
                             * config.KeyId = Switches.AlpacaAPIKey();
                             * config.SecurityId = new SecretKey(Switches.AlpacaSecretAPIKey());
                             * var restClient = new AlpacaTradingClient(config);
                             *
                             * //var p = await restClient.PostOrderAsync(position.symbol, position.qty, OrderSide.Sell, OrderType.Market, TimeInForce.Day);
                             *
                             * //sell 2?
                             * client.UploadData("", );
                             */
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw Utility.ThrowException(ex);
            }
        }
Example #3
0
        public static async Task UpdatePortfolio()
        {
            var restClient = new RestClient(Switches.AlpacaAPIKey(), Switches.AlpacaSecretAPIKey(), Switches.AlpacaEndPoint());
            var positions  = await restClient.ListPositionsAsync();

            //start existing
            List <Portfolio> existing = new List <Portfolio>();
            var allLines = File.ReadAllLines(Switches.stockDirectory + "Portfolio.csv");

            List <Portfolio> newList = new List <Portfolio>();

            Console.WriteLine("update portfolio 1");
            if (!File.Exists(Switches.stockDirectory + "Portfolio.csv"))
            {
                foreach (var position in positions)
                {
                    newList.Add(new Portfolio
                    {
                        symbol         = position.Symbol,
                        datePurchased  = DateTime.Today,
                        numberOfShares = position.Quantity,
                        averagePrice   = (double)position.AverageEntryPrice
                    });
                }
            }//end if (!File.Exists(Switches.stockDirectory + "Portfolio.csv"))
            else
            {
                foreach (var position in positions)
                {
                    bool inposition  = false;
                    int  OldPosition = 0;
                    for (int i = 1; i < allLines.Count(); i++)
                    {
                        string[] temp = allLines[i].Split(',');
                        if (position.Symbol.ToLower() == temp[0].ToLower())
                        {
                            inposition  = true;
                            OldPosition = i;
                        }
                    }
                    //if portfolio is still not sold
                    if (inposition)
                    {
                        newList.Add(new Portfolio
                        {
                            symbol         = position.Symbol,
                            datePurchased  = Convert.ToDateTime(allLines[OldPosition].Split(',')[1]),
                            numberOfShares = position.Quantity,
                            averagePrice   = (double)position.AverageEntryPrice
                        });
                    }
                    else
                    {
                        newList.Add(new Portfolio
                        {
                            symbol         = position.Symbol,
                            datePurchased  = DateTime.Today,
                            numberOfShares = position.Quantity,
                            averagePrice   = (double)position.AverageEntryPrice
                        });
                    }
                } //end foreach (var position in positions)
            }     //end else (if (!File.Exists(Switches.stockDirectory + "Portfolio.csv")))

            File.Delete(Switches.stockDirectory + "Portfolio.csv");
            //File.Create(Switches.stockDirectory + "Portfolio.csv");

            //UpdatePortFolio(portfolio.symbol, portfolio.numberOfShares, portfolio.numberOfShares);
            using (StreamWriter file = File.AppendText(Switches.stockDirectory + "Portfolio.csv"))
            {
                file.Write("symbol");
                file.Write(",");

                file.Write("Date Purchased");
                file.Write(",");

                file.Write("Number of Shares");
                file.Write(",");

                file.Write("averagePrice");

                file.Write("\n");

                foreach (var portfolio in newList)
                {
                    file.Write(portfolio.symbol);
                    file.Write(",");

                    file.Write(portfolio.datePurchased);
                    file.Write(",");

                    file.Write(portfolio.numberOfShares);
                    file.Write(",");

                    file.Write(portfolio.averagePrice);

                    file.Write("\n");
                } //end using (StreamWriter file = File.AppendText(Switches.stockDirectory + "Portfolio.csv"))
            }     //end using (StreamWriter file = File.AppendText(Switches.stockDirectory + "Portfolio.csv"))

            // Print the quantity of shares for each position.
            Console.WriteLine("Portfolio Update Finished");
            foreach (var position in positions)
            {
                Console.WriteLine($"{position.Quantity} shares of {position.Symbol}.");
            }
        }
Example #4
0
        public static async Task SellStock(string Symbol, int Quantity)
        {
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(Switches.AlpacaEndPoint() + "/v2/orders");

                httpWebRequest.Method = "POST";
                httpWebRequest.Headers.Add("APCA-API-KEY-ID", Switches.AlpacaAPIKey());
                httpWebRequest.Headers.Add("APCA-API-SECRET-KEY", Switches.AlpacaSecretAPIKey());


                httpWebRequest.ContentType = "application/x-www-form-urlencoded";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    //string json = "{" + "\"tracking\": {" + "\"slug\":\"" + Courier + "\"," + "\"tracking_number\":\"" + trackNumber + "\"}}";
                    SellOrderObject s = new SellOrderObject();
                    s.symbol = Symbol;
                    s.qty    = Quantity;

                    var json = JsonConvert.SerializeObject(s);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                    }
                }

                /*
                 * using (var client = new HttpClient())
                 * using (var request = new HttpRequestMessage(HttpMethod.Post, Switches.AlpacaEndPoint() + "/v2/orders"))
                 * {
                 *  SellOrderObject content = new SellOrderObject();
                 *  content.symbol = Symbol;
                 *  content.qty = Quantity;
                 *  var json = JsonConvert.SerializeObject(content);
                 *  using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
                 *  {
                 *      request.Content = stringContent;
                 *
                 *      request.Headers.Add("APCA-API-KEY-ID", Switches.AlpacaAPIKey());
                 *      request.Headers.Add("APCA-API-SECRET-KEY", Switches.AlpacaSecretAPIKey());
                 *      client.DefaultRequestHeaders.Add("APCA-API-KEY-ID", Switches.AlpacaAPIKey());
                 *      client.DefaultRequestHeaders.Add("APCA-API-SECRET-KEY", Switches.AlpacaSecretAPIKey());
                 *      using (var response = await client
                 *          .PostAsJsonAsync(Switches.AlpacaEndPoint() + "/v2/orders", content))
                 *      {
                 *          response.EnsureSuccessStatusCode();
                 *      }
                 *  }
                 * }
                 */
            }
            catch (Exception ex)
            {
                //throw Utility.ThrowException(ex);
            }
        }
Example #5
0
        public static async Task SellOnOnePercentGainAsync()
        {
            //setup rest client
            //var restClient = new RestClient(Switches.AlpacaAPIKey(), Switches.AlpacaSecretAPIKey(), Switches.AlpacaEndPoint());

            try
            {
                AlpacaTradingClientConfiguration config = new AlpacaTradingClientConfiguration();
                config.ApiEndpoint = new Uri(Switches.AlpacaEndPoint());
                //config.KeyId = Switches.AlpacaAPIKey();
                config.SecurityId = new SecretKey(Switches.AlpacaAPIKey(), Switches.AlpacaSecretAPIKey());
                var restClient = new AlpacaTradingClient(config);

                //var positions1 = await restClient.ListAssetsAsync(AssetStatus.Active);
                //var positions2 = await restClient.ListPositionsAsync();

                /*
                 * foreach (var position in positions)
                 * {
                 *  Console.Write(position);
                 * }
                 */
            }
            catch (Exception ex)
            {
                throw ex;
            }

            /*
             * if (File.Exists(Switches.stockDirectory + "Portfolio.csv"))
             * {
             *  var allLines = File.ReadAllLines(Switches.stockDirectory + "Portfolio.csv");
             *  for (int i = 1; i < allLines.Count(); i++)
             *  {
             *      string[] temp = allLines[i].Split(',');
             *      var p2 = await restClient.GetAssetAsync((temp[0]));
             *
             *      var position = await restClient.GetPositionAsync(temp[0]);
             *      //double required = temp[]
             *      int numberOfShares = position.Quantity;
             *      int daysAlloted = DateTime.Today.Day - Convert.ToDateTime(temp[1]).Day;
             *      double required = Convert.ToDouble(temp[3]);
             *
             *      //set minimal required selling point
             *      required *= 1.01;
             *
             *      try
             *      {
             *          if ((double)position.AssetCurrentPrice > required)
             *          {
             *              var order = await restClient.PostOrderAsync(temp[0], numberOfShares, OrderSide.Sell, OrderType.Market, TimeInForce.Day);
             *          }
             *      }
             *      catch (Exception ex)
             *      {
             *          Console.WriteLine("could not sell because " + ex.ToString());
             *      }
             *  }
             * }
             */
        }