Example #1
0
 public async Task <IEnumerable <Position> > GetPositions()
 => (await _alpacaTradingClient.ListPositionsAsync())
 .Select(x => new Position
 {
     NumberOfShares = x.Quantity,
     StockSymbol    = x.Symbol
 });
        public async void ListPositionsWorks()
        {
            var positions = await _alpacaTradingClient.ListPositionsAsync();

            Assert.NotNull(positions);
            Assert.NotEmpty(positions);
        }
Example #3
0
        private static void cmdGetPositions()
        {
            IAlpacaTradingClient client = Core.ServiceProvider.GetService <IAlpacaTradingClient>();
            var positions = client.ListPositionsAsync().Result;

            string resultStr = "\n";

            if (positions.Count == 0)
            {
                Core.Logger.LogInfo("No Active Positions");
                return;
            }

            foreach (IPosition position in positions)
            {
                resultStr += ($"Symbol: {position.Symbol} \n" +
                              $"Avg Entry: {position.AverageEntryPrice} \n" +
                              $"Quantity: {position.Quantity} \n" +
                              $"Side: {position.Side} \n" +
                              $"Market Value: {position.MarketValue} \n" +
                              $"P/L Amount: {position.UnrealizedProfitLoss} \n" +
                              $"P'L Percent: {position.UnrealizedProfitLossPercent} \n" +
                              $"Change Percent: {position.AssetChangePercent} \n" +
                              $"-------------------------------------------------");
            }

            Core.Logger.LogInfo(resultStr);
        }
Example #4
0
        public async Task <Trading.OrderResult> PlaceOrder_SellStopLimit(
            Data.Format format, string symbol, int shares, decimal stopPrice, decimal limitPrice, TimeInForce timeInForce = TimeInForce.Gtc)
        {
            IAlpacaTradingClient trading = null;

            try {
                if (format == Data.Format.Live)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret))
                    {
                        return(Trading.OrderResult.Fail);
                    }

                    trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret));
                }
                else if (format == Data.Format.Paper)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret))
                    {
                        return(Trading.OrderResult.Fail);
                    }

                    trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret));
                }

                // Prevents exceptions or unwanted behavior with Alpaca API
                var account = await trading.GetAccountAsync();

                if (trading == null || account == null ||
                    account.IsAccountBlocked || account.IsTradingBlocked ||
                    account.TradeSuspendedByUser)
                {
                    return(Trading.OrderResult.Fail);
                }

                // Prevents unintentionally short selling (selling into negative digits, the API interprets that as intent to short-sell)
                var positions = await trading.ListPositionsAsync();

                if (!positions.Any(p => p.Symbol == symbol))                // If there is no position for this symbol
                {
                    return(Trading.OrderResult.Fail);
                }

                var position = await trading.GetPositionAsync(symbol);      // If there were no position, this would throw an Exception!

                if (position == null || position.Quantity < shares)         // If the current position doesn't have enough shares
                {
                    return(Trading.OrderResult.Fail);
                }

                var order = await trading.PostOrderAsync(StopLimitOrder.Sell(symbol, shares, stopPrice, limitPrice).WithDuration(timeInForce));

                return(Trading.OrderResult.Success);
            } catch (Exception ex) {
                await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex);

                return(Trading.OrderResult.Fail);
            }
        }
Example #5
0
        /// <summary>
        /// Ensure a postion of the amount exists
        /// </summary>
        /// <param name="marketValue"></param>
        /// <returns>Cost of shares bought</returns>
        public async Task <decimal> EnsurePositionExists(string stockSymbol, decimal marketValue)
        {
            var postionTask        = _alpacaTradingClient.ListPositionsAsync();
            var currentAccountTask = _alpacaTradingClient.GetAccountAsync();

            var targetEquityAmount          = (await currentAccountTask).Equity * _config.Percentage_Of_Equity_Per_Position;
            var currentPositionsMarketValue = (await postionTask)?
                                              .SingleOrDefault(x => string.Equals(x.Symbol, stockSymbol, StringComparison.OrdinalIgnoreCase))?.MarketValue ?? 0;
            var missingEquity        = targetEquityAmount - currentPositionsMarketValue;
            var numberOfSharesNeeded = (int)Math.Floor(missingEquity / marketValue);

            if (numberOfSharesNeeded > 0)
            {
                await _alpacaTradingClient.PostOrderAsync(new NewOrderRequest(stockSymbol, numberOfSharesNeeded, OrderSide.Buy, OrderType.Market, TimeInForce.Ioc));

                return(numberOfSharesNeeded * marketValue);
            }

            return(0);
        }
Example #6
0
        public async Task <object> GetPositions(Data.Format format)
        {
            IAlpacaTradingClient client = null;

            try {
                if (format == Data.Format.Live)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret))
                    {
                        return(false);
                    }

                    client = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret));
                }
                else if (format == Data.Format.Paper)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret))
                    {
                        return(false);
                    }

                    client = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret));
                }

                if (client == null)
                {
                    return(false);
                }

                var positions = await client.ListPositionsAsync();

                return(positions.Select(p => new Data.Position()
                {
                    ID = p.AssetId.ToString(),
                    Symbol = p.Symbol,
                    Quantity = p.Quantity
                }).ToList());
            } catch (Exception ex) {
                await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex);

                return(null);
            }
        }