// Submit an order if quantity is not zero. private async Task SubmitOrder(Int32 quantity, Decimal price, OrderSide side) { if (quantity == 0) { Console.WriteLine("No order necessary."); return; } Console.WriteLine($"Submitting {side} order for {quantity} shares at ${price}."); var order = await alpacaTradingClient.PostOrderAsync( side.Limit(symbol, quantity, price)); lastTradeId = order.OrderId; }
// Submit a market order if quantity is not zero. public async Task <Guid> SubmitMarketOrder(int quantity, OrderSide side, string clientId = "", decimal stopDollars = 0) { //if (quantity == 0) if (quantity == 0) { return(Guid.Empty); } //Console.WriteLine($"Submitting {side} order for {quantity} shares."); try { IOrder order; if (clientId.Length > 0) { order = await client.PostOrderAsync(side.Market(symbol, quantity).WithClientOrderId(clientId)); } else { order = await client.PostOrderAsync(side.Market(symbol, quantity)); } lastTradeId = order.OrderId; if (stopDollars > 0) { // Submit a trailing stop order to sell / buy quantitu of symbol at market - stoploss // trailing stop of if (side == OrderSide.Buy) { order = await client.PostOrderAsync( TrailingStopOrder.Sell(symbol, quantity, TrailOffset.InDollars(stopDollars))); // stop price will be hwm - stopDollars$ (326.44 - 0.05 = 326.39) } else { order = await client.PostOrderAsync( TrailingStopOrder.Buy(symbol, quantity, TrailOffset.InDollars(stopDollars))); // stop price will be hwm + stopDollars$ } } } catch (Exception ex) { // jsruntime.alert(ex.Message); } if (clientId.Length > 0) { await GetOrders(clientId); } return(lastTradeId); }
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); } }
/// <summary> /// Buy or sell stock /// </summary> public Task PlaceOrder(Order order, OrderTiming?orderTiming = null) => _alpacaTradingClient.PostOrderAsync( new NewOrderRequest( symbol: order.StockSymbol, quantity: order.SharesBought > 0 ? order.SharesBought : order.SharesBought * (-1), side: order.SharesBought > 0 ? OrderSide.Buy : OrderSide.Sell, type: OrderType.Market, duration: (TimeInForce)(orderTiming ?? OrderTiming.PartialFillOrKill)));
// Submit an order if quantity is not zero. private async Task SubmitOrder(Int32 quantity, Decimal price, OrderSide side) { if (quantity == 0) { return; } try { var order = await alpacaTradingClient.PostOrderAsync( side.Limit(symbol, quantity, price)); lastTradeId = order.OrderId; lastTradeOpen = true; } catch (Exception e) { Console.WriteLine("Warning: " + e.Message); } }
/// <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); }
public async Task <Trading.OrderResult> PlaceOrder_BuyMarket( Data.Format format, string symbol, int shares, TimeInForce timeInForce = TimeInForce.Gtc, bool useMargin = false) { IAlpacaTradingClient trading = null; IAlpacaDataClient data = 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)); data = Environments.Live.GetAlpacaDataClient(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)); data = Environments.Paper.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } var account = await trading.GetAccountAsync(); if (trading == null || account == null || account.IsAccountBlocked || account.IsTradingBlocked || account.TradeSuspendedByUser) { return(Trading.OrderResult.Fail); } var order = await trading.PostOrderAsync(MarketOrder.Buy(symbol, shares).WithDuration(timeInForce)); return(Trading.OrderResult.Success); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(Trading.OrderResult.Fail); } }