private void FormLoaded(object sender, RoutedEventArgs e)
        {
            // Setup account data
            Account.Account account = new Account.Account();
            account.accessToken = "secret-token-from-your-oanda-account";

            // Get candle data
            HttpGet httpGet = new HttpGet();

            httpGet.accessToken = account.accessToken;
            var data = httpGet.Get("https://api-fxpractice.oanda.com/v1/candles?instrument=EUR_USD&count=30&granularity=D");

            // Deserialize JSON into List<Candle> object
            CandlesResponse candlesResponse = JsonConvert.DeserializeObject <CandlesResponse>(data);

            //List<Candle> candles = new List<Candle>();
            candles = new List <Candle>();
            candles.AddRange(candlesResponse.candles);



            canGraph.Width  = this.ActualWidth;
            canGraph.Height = this.ActualHeight;

            // Draw the graph
            //DrawGraphOrig();
            DrawGraph();
        }
Example #2
0
        /// <summary>
        /// More detailed request to retrieve candles
        /// </summary>
        /// <param name="request">the request data to use when retrieving the candles</param>
        /// <returns>List of Candles received (or empty list)</returns>
        public static async Task <List <Candle> > GetCandlesAsync(CandlesRequest request)
        {
            string requestString = Server(EServer.Rates) + request.GetRequestString();

            CandlesResponse candlesResponse = await MakeRequestAsync <CandlesResponse>(requestString);

            List <Candle> candles = new List <Candle>();

            candles.AddRange(candlesResponse.candles);

            return(candles);
        }
Example #3
0
        /// <summary>
        /// Basic request to retrieve candles for the pair/granularity provided
        /// </summary>
        /// <param name="pair">The pair/symbol for which to retrieve candles</param>
        /// <param name="granularity">the granularity for which to retrieve candles</param>
        /// <returns>List of Candle objects (or empty list)</returns>
        public static async Task <List <Candle> > GetCandlesAsync(string pair, string granularity)
        {
            string requestString = Server(EServer.Rates) + "" + "instruments/" + pair + "/candles?granularity=" + granularity;

            CandlesResponse candlesResponse = await MakeRequestAsync <CandlesResponse>(requestString);

            List <Candle> candles = new List <Candle>();

            candles.AddRange(candlesResponse.candles);

            return(candles);
        }
        /// <summary>
        /// More detailed request to retrieve candles
        /// </summary>
        /// <param name="request">the request data to use when retrieving the candles</param>
        /// <returns>List of Candles received (or empty list)</returns>
        internal static List <Candle> GetCandles(CandlesRequest request)
        {
            string requestString = Server(EServer.Rates) + request.GetRequestString();

            var candles = new List <Candle>();

            CandlesResponse candlesResponse = MakeRequest <CandlesResponse>(requestString);

            candles.AddRange(candlesResponse.Candles);

            return(candles);
        }
Example #5
0
        /// <summary>
        /// More detailed request to retrieve candles
        /// </summary>
        /// <param name="request">the request data to use when retrieving the candles</param>
        /// <returns>List of Candles received (or empty list)</returns>
        public static List <Candle> GetCandles(CandlesRequest request)
        {
            string requestString = Credentials.GetDefaultCredentials().GetServer(EServer.Rates) + request.GetRequestString();

            CandlesResponse candlesResponse = MakeRequest <CandlesResponse>(requestString);
            List <Candle>   candles         = new List <Candle>();

            if (candlesResponse != null)
            {
                candles.AddRange(candlesResponse.candles);
            }
            return(candles);
        }
        private void OnCandlesResponse(CandlesResponse response)
        {
            var key           = Tuple.Create(response.SecId, response.Period);
            var transactionId = _candleTransactions.TryGetValue2(key);

            if (transactionId == null)
            {
                SendOutError(LocalizedStrings.Str3513Params.Put(response.SecCode, response.Board, response.Period));
                return;
            }

            var isFinished = false;

            switch (response.Status)
            {
            case CandleResponseStatus.Finished:
            case CandleResponseStatus.Done:
            case CandleResponseStatus.NotAvailable:
                isFinished = true;
                _candleTransactions.Remove(key);
                break;
            }

            var index = 0;

            foreach (var candle in response.Candles)
            {
                var time = candle.Date.ToDto();

                SendOutMessage(new TimeFrameCandleMessage
                {
                    OriginalTransactionId = (long)transactionId,
                    SecurityId            = new SecurityId {
                        Native = response.SecId
                    },
                    OpenPrice    = candle.Open,
                    HighPrice    = candle.High,
                    LowPrice     = candle.Low,
                    ClosePrice   = candle.Close,
                    TotalVolume  = candle.Volume,
                    OpenTime     = time,
                    CloseTime    = time + _candlePeriods[response.Period],
                    OpenInterest = candle.Oi,
                    IsFinished   = isFinished && ++index == response.Candles.Length,
                    State        = CandleStates.Finished,
                });
            }
        }
        /// <summary>
        /// Retrieves the list of candles available for the given instrument
        /// </summary>
        /// <param name="instrument">the instrument to retrieve candles for</param>
        /// <param name="requestParams">the parameters for the request</param>
        /// <returns>List of Candlestick objects (or empty list) </returns>
        public static async Task <List <CandlestickPlus> > GetCandlesAsync(string instrument, Dictionary <string, string> requestParams)
        {
            string requestString = Server(EServer.Account) + "instruments/" + instrument + "/candles";

            CandlesResponse response = await MakeRequestAsync <CandlesResponse>(requestString, "GET", requestParams);

            var candles = new List <CandlestickPlus>();

            foreach (var candle in response.candles)
            {
                candles.Add(new CandlestickPlus(candle)
                {
                    instrument = instrument, granularity = response.granularity
                });
            }
            return(candles);
        }
Example #8
0
        public override async Task <CandlesResponse> GetCandles(CandlesRequest request, ServerCallContext context)
        {
            var candles = await _candlesHistoryService.GetCandlesHistoryAsync(
                request.AssetPairId,
                _mapper.Map <CandlePriceType>(request.Type),
                _mapper.Map <CandleTimeInterval>(request.Interval),
                request.From.ToDateTime().ToUniversalTime(),
                request.To.ToDateTime().ToUniversalTime());

            var result = new CandlesResponse {
                Body = new CandlesResponse.Types.Body()
            };

            result.Body.Candles.AddRange(_mapper.Map <List <Candle> >(candles.History));

            return(result);
        }
Example #9
0
        static void Main(string[] args)
        {
            TradeioApi api    = new TradeioApi("aaaaaaaa-bbbb-cccc-dddd-eeeeeeee", "aaaaaaaa-bbbb-cccc-dddd-eeeeeeee");
            string     symbol = "btc_usdt";

            Console.WriteLine("******PAIRS******");
            PairsResponse pairsResponse = api.GetPairs().Result;

            Console.WriteLine(string.Join(',', pairsResponse.Pairs));

            Console.WriteLine("******CANDLES******");
            CandlesResponse candles = api.GetCandles("btc_usdt", CandleInterval.OneDay, DateTime.UtcNow.AddMonths(-1), DateTime.UtcNow, 20).Result;

            foreach (CandleInfo candle in candles.Candles)
            {
                Console.WriteLine($"open: {candle.Open}; close: {candle.Close}; low: {candle.Low}; high: {candle.High}");
            }

            Console.WriteLine("******ORDER BOOK******");
            OrderBookResponse orderBookResponse = api.GetOrderBook(symbol, 2).Result;

            Console.WriteLine("***ASK***");
            foreach (var askArray in orderBookResponse.Book.Asks)
            {
                Console.WriteLine($"Price: {askArray[0]}; Count: {askArray[1]}");
            }
            Console.WriteLine("***BID***");
            foreach (var bidArray in orderBookResponse.Book.Bids)
            {
                Console.WriteLine($"Price: {bidArray[0]}; Count: {bidArray[1]}");
            }

            Console.WriteLine("******TICKER******");
            TickerResponse tickerResponse = api.GetTicker(symbol).Result;

            Console.WriteLine($"ASK price: {tickerResponse.Ticker.AskPrice}, qty: {tickerResponse.Ticker.AskQty}; BID price: {tickerResponse.Ticker.BidPrice}, qty: {tickerResponse.Ticker.BidQty}");
            //tickers for all pairs
            //var tickers = api.GetTickers().Result;

            Console.WriteLine("******RECENT TRADES******");
            TradesResponse tradesResponse = api.GetRecentTrades("btc_usdt", 2).Result;

            foreach (TradeInfo trade in tradesResponse.Trades)
            {
                Console.WriteLine($"{trade.Symbol} price: {trade.Price}, qty: {trade.Quantity}, side: {trade.Type}, date: {UnixTime.GetDateTime(trade.Time)} UTC");
            }


            //PRIVATE METHODS. NOT WORKING WITHOUT PUBLIC AND PRIVATE KEY

            Console.WriteLine("******CURRENT BALANCES******");
            AccountBalanceResponse accountBalance = api.GetAccount().Result;

            foreach (BalanceInfo balanceInfo in accountBalance.Balances)
            {
                Console.WriteLine($"{balanceInfo.Asset}:{balanceInfo.Available} (locked: {balanceInfo.Locked})");
            }

            Console.WriteLine("******OPEN ORDERS******");
            OrdersResponse ordersResponse = api.GetOpenOrders(symbol).Result;

            foreach (OrderInfoResponse order in ordersResponse.Orders)
            {
                Console.WriteLine($"{order.Side} {order.Instrument} for {order.Price}. Filled: {order.UnitsFilled}");
            }
            Console.WriteLine("******CLOSED ORDERS******");
            FilteredResponse <OrderInfoResponse> closeOrdersResponse = api.GetClosedOrders(symbol, UnixTime.Get(DateTime.UtcNow.AddDays(-1)), UnixTime.Get(DateTime.UtcNow)).Result;

            foreach (OrderInfoResponse order in closeOrdersResponse.Data)
            {
                Console.WriteLine($"{order.Side} {order.Instrument} for {order.Price}. Filled: {order.UnitsFilled}. Status: {order.Status}");
            }
            Console.WriteLine("******PLACE ORDER******");
            var orderResponse = api.PlaceOrder(new Models.OrderRequest()
            {
                Price    = 4000,
                Quantity = 10,
                Side     = Models.OrderSide.Buy,
                Symbol   = symbol,
                Type     = Models.OrderType.Limit
            }).Result;

            Console.WriteLine("******CANCEL ORDER******");
            Response response = api.CancelOrder(orderResponse.Order.OrderId).Result;

            if (response.Code == 200)
            {
                Console.WriteLine("Order canceled");
            }
            Console.ReadLine();
        }
        public override async Task <CandlesResponse> GetCandles(CandlesRequest request, ServerCallContext context)
        {
            var symbol = request.AssetPairId;

            TimeSpan delta;

            const int defaultCountOfCandle = 1000;

            AntaresClientApi.Database.CandleData.Models.CandleType interval;

            switch (request.Interval)
            {
            //todo: implement other candle intervals;

            //case CandleInterval.Min5:   delta = TimeSpan.FromMinutes(5); break;
            //case CandleInterval.Min15:  delta = TimeSpan.FromMinutes(15); break;
            //case CandleInterval.Min30:  delta = TimeSpan.FromMinutes(30); break;
            case CandleInterval.Hour:   delta = TimeSpan.FromHours(1); interval = CandleType.Hour;  break;

            //case CandleInterval.Hour4:  delta = TimeSpan.FromHours(4); break;
            //case CandleInterval.Hour6:  delta = TimeSpan.FromHours(6); break;
            //case CandleInterval.Hour12: delta = TimeSpan.FromHours(12); break;
            case CandleInterval.Day:    delta = TimeSpan.FromDays(1); interval = CandleType.Day; break;

            //case CandleInterval.Week:   delta = TimeSpan.FromDays(7); break;
            case CandleInterval.Month:  delta = TimeSpan.FromDays(30); interval = CandleType.Month; break;

            default:
            {
                var response = new CandlesResponse();
                return(response);
            }
            }

            var toDate   = DateTime.UtcNow;
            var fromDate = toDate.AddSeconds(-delta.TotalSeconds * defaultCountOfCandle);

            if (request.From != null && request.To != null)
            {
                fromDate = request.From.ToDateTime();
                toDate   = request.To.ToDateTime();
            }
            else if (request.From != null)
            {
                fromDate = request.From.ToDateTime();
                toDate   = fromDate.AddSeconds(delta.Seconds * defaultCountOfCandle);
            }
            else if (request.To != null)
            {
                toDate   = request.To.ToDateTime();
                fromDate = toDate.AddSeconds(-delta.Seconds * defaultCountOfCandle);
            }

            //todo: implement different charts for ask\bid\mig\trade
            //request.Type


            try
            {
                var candles = await _marketDataService.GetCandles(request.AssetPairId,
                                                                  fromDate,
                                                                  toDate,
                                                                  interval);

                var result = new CandlesResponse
                {
                    Candles =
                    {
                        candles.OrderBy(c => c.Time)
                        .Select(c => new Candle
                        {
                            Timestamp =
                                Timestamp.FromDateTime(DateTime.SpecifyKind(c.Time, DateTimeKind.Utc)),
                            Volume         = "0",
                            OppositeVolume = "0",
                            Open           = c.Open.ToString(CultureInfo.InvariantCulture),
                            Close          = c.Close.ToString(CultureInfo.InvariantCulture),
                            High           = c.High.ToString(CultureInfo.InvariantCulture),
                            Low            = c.Close.ToString(CultureInfo.InvariantCulture),
                            LastPrice      = c.Close.ToString(CultureInfo.InvariantCulture)
                        })
                    }
                };

                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }