Пример #1
0
        public AlpacaClient(
            IAlpacaTradingClient alpacaTradingClient,
            IAlpacaStreamingClient alpacaTradingStreamingClient,
            IAlpacaDataClient alpacaDataClient,
            IAlpacaDataStreamingClient alpacaDataStreamingClient
            )
        {
            _alpacaTradingClient          = alpacaTradingClient ?? throw new ArgumentNullException(nameof(alpacaTradingClient));
            _alpacaTradingStreamingClient = alpacaTradingStreamingClient ?? throw new ArgumentNullException(nameof(alpacaTradingStreamingClient));
            _alpacaDataClient             = alpacaDataClient ?? throw new ArgumentNullException(nameof(alpacaDataClient));
            _alpacaDataStreamingClient    = alpacaDataStreamingClient ?? throw new ArgumentNullException(nameof(alpacaDataStreamingClient));

            _stockActions = new Dictionary <string, List <Action <StockInput> > >(StringComparer.OrdinalIgnoreCase);
        }
Пример #2
0
        public CoreService(ILoggerService loggerService, Settings config, IAlpacaTradingClient tradingClient, IAlpacaStreamingClient streamingClient, IAccountService accountService, ICommandService commandService)
        {
            CoreService.Instance = this;
            LoggerService        = loggerService;
            LoggerService.LogInfo("Initializing Core Service");

            Config = config;
            LoggerService.LogInfo("Fetching Trading Client");
            TradingClient = tradingClient;
            LoggerService.LogInfo("Fetching Streaming Client");
            StreamingClient = streamingClient;
            LoggerService.LogInfo("Initializing Account Service");
            AccountService = accountService;
            CommandService = commandService;
            RunningTasks   = new List <Task>();
        }
Пример #3
0
        public async Task Run()
        {
            alpacaTradingClient = Environments.Paper.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET));

            polygonDataClient = Environments.Paper.GetPolygonDataClient(API_KEY);

            // Connect to Alpaca's websocket and listen for updates on our orders.
            alpacaStreamingClient = Environments.Paper.GetAlpacaStreamingClient(new SecretKey(API_KEY, API_SECRET));

            alpacaStreamingClient.ConnectAndAuthenticateAsync().Wait();

            alpacaStreamingClient.OnTradeUpdate += HandleTradeUpdate;

            // First, cancel any existing orders so they don't impact our buying power.
            var orders = await alpacaTradingClient.ListOrdersAsync(new ListOrdersRequest());

            foreach (var order in orders)
            {
                await alpacaTradingClient.DeleteOrderAsync(order.OrderId);
            }

            // Figure out when the market will close so we can prepare to sell beforehand.
            var calendars = (await alpacaTradingClient
                             .ListCalendarAsync(new CalendarRequest().SetTimeInterval(DateTime.Today.GetInclusiveIntervalFromThat())))
                            .ToList();
            var calendarDate = calendars.First().TradingDateUtc;
            var closingTime  = calendars.First().TradingCloseTimeUtc;

            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 polygonDataClient.ListAggregatesAsync(
                new AggregatesRequest(symbol, new AggregationPeriod(1, AggregationPeriodUnit.Minute))
                .SetInclusiveTimeInterval(today, today.AddDays(1)));

            var lastBars = bars.Items.Skip(Math.Max(0, bars.Items.Count() - 20));

            foreach (var bar in lastBars)
            {
                if (bar.TimeUtc?.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.
            polygonStreamingClient = Environments.Live.GetPolygonStreamingClient(API_KEY);

            polygonStreamingClient.ConnectAndAuthenticateAsync().Wait();
            Console.WriteLine("Polygon client opened.");
            polygonStreamingClient.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 polygonStreamingClient.DisconnectAsync();
                }
                else
                {
                    // Decide whether to buy or sell and submit orders.
                    await HandleMinuteAgg(agg);
                }
            };
            polygonStreamingClient.SubscribeMinuteAgg(symbol);
        }