/// <summary> /// Initializes a new instance of the <see cref="AlpacaBrokerage"/> class. /// </summary> /// <param name="orderProvider">The order provider.</param> /// <param name="securityProvider">The holdings provider.</param> /// <param name="accountKeyId">The Alpaca api key id</param> /// <param name="secretKey">The api secret key</param> /// <param name="tradingMode">The Alpaca trading mode. paper/live</param> public AlpacaBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string accountKeyId, string secretKey, string tradingMode) : base("Alpaca Brokerage") { var baseUrl = "api.alpaca.markets"; if (tradingMode.Equals("paper")) { baseUrl = "paper-" + baseUrl; } baseUrl = "https://" + baseUrl; _orderProvider = orderProvider; _securityProvider = securityProvider; _marketHours = MarketHoursDatabase.FromDataFolder(); // api client for alpaca _restClient = new RestClient(accountKeyId, secretKey, baseUrl); // websocket client for alpaca _sockClient = new SockClient(accountKeyId, secretKey, baseUrl); _sockClient.OnTradeUpdate += OnTradeUpdate; _sockClient.OnError += OnSockClientError; // polygon client for alpaca _natsClient = new NatsClient(accountKeyId, baseUrl.Contains("staging")); _natsClient.QuoteReceived += OnQuoteReceived; _natsClient.TradeReceived += OnTradeReceived; _natsClient.OnError += OnNatsClientError; }
public SmppInternalConnection(SmppSettings Settings) { TcpConnection = new SockClient(); PendingResponse = new ListDictionary(); PendingQueue = new ArrayList(15); PendingBind = new ArrayList(10); ReleasedDateTime = DateTime.Now; LastReceptionTime = DateTime.Now; ClientGuid = Guid.NewGuid(); this.Settings = Settings; TcpConnection.DataReceived += TcpConnection_DataReceived; TcpConnection.CloseConnection += TcpConnection_CloseConnection; }
/// <summary> /// Initializes a new instance of the <see cref="AlpacaBrokerage"/> class. /// </summary> /// <param name="orderProvider">The order provider.</param> /// <param name="securityProvider">The holdings provider.</param> /// <param name="accountKeyId">The Alpaca api key id</param> /// <param name="secretKey">The api secret key</param> /// <param name="tradingMode">The Alpaca trading mode. paper/live</param> /// <param name="handlesMarketData">true if market data subscriptions will be handled by Alpaca</param> /// <param name="aggregator">consolidate ticks</param> public AlpacaBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string accountKeyId, string secretKey, string tradingMode, bool handlesMarketData, IDataAggregator aggregator) : base("Alpaca Brokerage") { _handlesMarketData = handlesMarketData; _aggregator = aggregator; var httpScheme = "https://"; var alpacaBaseUrl = "api.alpaca.markets"; if (tradingMode.Equals("paper")) { alpacaBaseUrl = "paper-" + alpacaBaseUrl; } var httpAlpacaBaseUrl = httpScheme + alpacaBaseUrl; _orderProvider = orderProvider; _securityProvider = securityProvider; _marketHours = MarketHoursDatabase.FromDataFolder(); // Alpaca trading client _alpacaTradingClient = new AlpacaTradingClient(new AlpacaTradingClientConfiguration { ApiEndpoint = tradingMode.Equals("paper") ? Environments.Paper.AlpacaTradingApi : Environments.Live.AlpacaTradingApi, SecurityId = new SecretKey(accountKeyId, secretKey) }); // api client for alpaca data _polygonDataClient = new PolygonDataClient(new PolygonDataClientConfiguration { ApiEndpoint = Environments.Live.PolygonDataApi, KeyId = accountKeyId }); // websocket client for alpaca _sockClient = new SockClient(accountKeyId, secretKey, httpAlpacaBaseUrl); _sockClient.OnTradeUpdate += OnTradeUpdate; _sockClient.OnError += OnSockClientError; // Polygon Streaming client for Alpaca (streams trade and quote data) _polygonStreamingClient = new PolygonStreamingClient(new PolygonStreamingClientConfiguration { ApiEndpoint = Environments.Live.PolygonStreamingApi, KeyId = accountKeyId, WebSocketFactory = new WebSocketClientFactory() }); _polygonStreamingClient.QuoteReceived += OnQuoteReceived; _polygonStreamingClient.TradeReceived += OnTradeReceived; _polygonStreamingClient.OnError += OnPolygonStreamingClientError; }
/// <summary> /// Initializes a new instance of the <see cref="AlpacaBrokerage"/> class. /// </summary> /// <param name="orderProvider">The order provider.</param> /// <param name="securityProvider">The holdings provider.</param> /// <param name="mapFileProvider">representing all the map files</param> /// <param name="accountKeyId">The Alpaca api key id</param> /// <param name="secretKey">The api secret key</param> /// <param name="tradingMode">The Alpaca trading mode. paper/live</param> public AlpacaBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, IMapFileProvider mapFileProvider, string accountKeyId, string secretKey, string tradingMode) : base("Alpaca Brokerage") { var httpScheme = "https://"; var alpacaBaseUrl = "api.alpaca.markets"; if (tradingMode.Equals("paper")) { alpacaBaseUrl = "paper-" + alpacaBaseUrl; } var httpAlpacaBaseUrl = httpScheme + alpacaBaseUrl; _orderProvider = orderProvider; _securityProvider = securityProvider; _symbolMapper = new AlpacaSymbolMapper(mapFileProvider); _marketHours = MarketHoursDatabase.FromDataFolder(); // Alpaca trading client _alpacaTradingClient = new AlpacaTradingClient(new AlpacaTradingClientConfiguration { ApiEndpoint = tradingMode.Equals("paper") ? Environments.Paper.AlpacaTradingApi : Environments.Live.AlpacaTradingApi, SecurityId = new SecretKey(accountKeyId, secretKey) }); // api client for alpaca data _polygonDataClient = new PolygonDataClient(new PolygonDataClientConfiguration { ApiEndpoint = Environments.Live.PolygonDataApi, KeyId = accountKeyId }); // websocket client for alpaca _sockClient = new SockClient(accountKeyId, secretKey, httpAlpacaBaseUrl); _sockClient.OnTradeUpdate += OnTradeUpdate; _sockClient.OnError += OnSockClientError; }
public async Task Run() { restClient = new RestClient(API_KEY, API_SECRET, API_URL, apiVersion: 2); // Connect to Alpaca's websocket and listen for updates on our orders. sockClient = new SockClient(API_KEY, API_SECRET, API_URL); sockClient.ConnectAndAuthenticateAsync().Wait(); sockClient.OnTradeUpdate += HandleTradeUpdate; // First, cancel any existing orders so they don't impact our buying power. var orders = await restClient.ListOrdersAsync(); foreach (var order in orders) { await restClient.DeleteOrderAsync(order.OrderId); } // Figure out when the market will close so we can prepare to sell beforehand. var calendars = (await restClient.ListCalendarAsync(DateTime.Today)).ToList(); var calendarDate = calendars.First().TradingDate; var closingTime = calendars.First().TradingCloseTime; closingTime = new DateTime(calendarDate.Year, calendarDate.Month, calendarDate.Day, closingTime.Hour, closingTime.Minute, closingTime.Second); var today = DateTime.Today; // Get the first group of bars from today if the market has already been open. var bars = await restClient.ListMinuteAggregatesAsync(symbol, 1, today, today.AddDays(1)); var lastBars = bars.Items.Skip(Math.Max(0, bars.Items.Count() - 20)); foreach (var bar in lastBars) { if (bar.Time.Date == today) { closingPrices.Add(bar.Close); } } Console.WriteLine("Waiting for market open..."); await AwaitMarketOpen(); Console.WriteLine("Market opened."); // Connect to Polygon's websocket and listen for price updates. polygonSockClient = new PolygonSockClient(API_KEY); polygonSockClient.ConnectAndAuthenticateAsync().Wait(); Console.WriteLine("Polygon client opened."); polygonSockClient.MinuteAggReceived += async(agg) => { // If the market's close to closing, exit position and stop trading. TimeSpan minutesUntilClose = closingTime - DateTime.UtcNow; if (minutesUntilClose.TotalMinutes < 15) { Console.WriteLine("Reached the end of trading window."); await ClosePositionAtMarket(); await polygonSockClient.DisconnectAsync(); } else { // Decide whether to buy or sell and submit orders. await HandleMinuteAgg(agg); } }; polygonSockClient.SubscribeSecondAgg(symbol); }
public async void Run() { restClient = new RestClient(API_KEY, API_SECRET, API_URL, apiVersion: 2); // First, cancel any existing orders so they don't impact our buying power. var orders = restClient.ListOrdersAsync().Result; foreach (var order in orders) { restClient.DeleteOrderAsync(order.OrderId); } // Figure out when the market will close so we can prepare to sell beforehand. var calendars = restClient.ListCalendarAsync(DateTime.Today).Result; var calendarDate = calendars.First().TradingDate; var closingTime = calendars.First().TradingCloseTime; closingTime = new DateTime(calendarDate.Year, calendarDate.Month, calendarDate.Day, closingTime.Hour, closingTime.Minute, closingTime.Second); // Get the first group of bars from today if the market has already been open. var bars = restClient.ListMinuteAggregatesAsync(symbol: symbol, limit: 20).Result.Items; foreach (var bar in bars) { if (bar.Time.Date == DateTime.Now.Date) { closingPrices.Add(bar.Close); } } Console.WriteLine("Waiting for market open..."); AwaitMarketOpen(); Console.WriteLine("Market opened."); // Connect to Polygon and listen for price updates. var natsClient = new NatsClient(API_KEY, false); natsClient.Open(); Console.WriteLine("Polygon client opened."); natsClient.AggReceived += (agg) => { // If the market's close to closing, exit position and stop trading. TimeSpan minutesUntilClose = closingTime - DateTime.UtcNow; if (minutesUntilClose.TotalMinutes < 15) { Console.WriteLine("Reached the end of trading window."); ClosePositionAtMarket(); natsClient.Close(); } else { // Decide whether to buy or sell and submit orders. HandleMinuteAgg(agg); } }; natsClient.SubscribeMinuteAgg(symbol); // Connect to Alpaca and listen for updates on our orders. var sockClient = new SockClient(API_KEY, API_SECRET, API_URL); await sockClient.ConnectAsync(); Console.WriteLine("Socket client opened."); sockClient.OnTradeUpdate += (trade) => { HandleTradeUpdate(trade); }; }
public void RemoveClient(SockClient client) { // ( client as DBClientHandler ).Logout(); clients.Remove(client); }