How to Request Candles

Overview

dxFeed Aggregated Data Services provides different types of aggregations that are available:

  • Via Candlewebservice for requesting Candle data for particular time period in the past with from-to period. Read more

  • Through any supported API ( Java API, Webservice, etc.) for requesting historical Candle data with live updates from particular period in the past. This method has fewer restrictions to the data depth, both in numbers of candles and aggregations. For example, 1 min candles can be requested from any period.

Request format

The general format of a candle symbol is:

<baseSymbol>[&]<exchange>{=[<period>]<type>[,a=s][,price=<priceType>][,tho=true]}

Request arguments

Argument

Value

Description

Required

type

String

The type of candle

Required

tho=true

String

Requests that candle data is being limited to regular trading session only (and extended session ignored)

Optional. By default, all trades/quotes are included

priceType

String

The type of the price that is used to build candles

Optional (Required for FOREX). By default, last trade price is used

period

1

The number of aggregation periods of a specified type in each candle

Optional, it is set to 1 by default

exchange

String

The exchange code

Optional, By default, candle is composed from trades/quotes from all exchanges

baseSymbol

String

The market symbol (like IBM, MSFT, etc)

Required

a=s

String

Changes candle alignment to trading session

Optional. By default, candles are aligned to midnight

Type supported values are:

  • t - tick

  • s- second

  • m - minute

  • h - hour

  • d - day

  • w - week

  • mo - month

  • o - standard option expiration (3rd Friday of the month)

  • y - year

  • v - volume

  • p - price

priceType supported values are:

  • last - last trade price

  • bid - quote bid price

  • ask - quote ask price

  • mark - market price defined as average between quote bid and ask prices

  • s - settlement price

Please try demo

Examples

Java Example 1

import java.io.*;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.devexperts.util.TimeFormat;
import com.dxfeed.api.*;
import com.dxfeed.event.candle.*;
 
public class CandleSub {
    static int eventsProcessed;
    public static final CandlePeriod PERIOD = CandlePeriod.valueOf(2, CandleType.HOUR);
 
    public static void main(String[] args) throws InterruptedException, IOException {
        new CandleSub().start(args);
    }
 
    private void start(String[] args) throws InterruptedException, IOException {
 
        DXEndpoint endpoint = DXEndpoint.create(DXEndpoint.Role.FEED);
        DXFeed feed = endpoint.getFeed();
 
        // subscribe to a specified event and symbol
        DXFeedTimeSeriesSubscription<Candle> sub = feed.createTimeSeriesSubscription(Candle.class);
        sub.addEventListener(new CandleListener());
 
        sub.setFromTime(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(10));
        CandleSymbol eurUsd = CandleSymbol.valueOf("EUR/USD", CandlePrice.BID, PERIOD);
        sub.addSymbols(eurUsd); // "EUR/USD{price=bid}");
 
 
        String QD_ADDRESS = "10.10.10.10:1010"; // Endpoint
        endpoint.connect(QD_ADDRESS);
 
        // wait until file is completely parsed
        endpoint.awaitNotConnected();
 
        // close endpoint when we're done
        // this method will gracefully close endpoint, waiting while data processing completes
        endpoint.closeAndAwaitTermination();
    }
 
    private class CandleListener implements DXFeedEventListener<Candle> {
 
        public void eventsReceived(List<Candle> candles) {
            for (Candle candle : candles) {
                eventsProcessed++;
                CandleSymbol symbol = candle.getEventSymbol();
                if (candle.getTime() + PERIOD.getPeriodIntervalMillis() > System.currentTimeMillis())
                    ; // skipping unfinished candle
                else
                    System.out.println("Got candle for symbol " + symbol + " : " + candle);
            }
        }
    }
 }

Java Example 2

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
import com.dxfeed.api.*;
import com.dxfeed.event.candle.*;
import com.dxfeed.promise.Promise;
 
public class CandleGetViaPromise {
    static int eventsProcessed;
    public static final CandlePeriod PERIOD = CandlePeriod.valueOf(1, CandleType.DAY);
 
    public static void main(String[] args) throws InterruptedException, IOException {
        new CandleGetViaPromise().start(args);
    }
 
    private void start(String[] args) throws InterruptedException, IOException {
 
        DXEndpoint endpoint = DXEndpoint.create(DXEndpoint.Role.FEED);//.user("username").password("password");
        String QD_ADDRESS = "10.10.10.10:1010"; // Endpoint
        endpoint.connect(QD_ADDRESS);
 
        DXFeed feed = endpoint.getFeed();
 
        String symbol = "EUR/USD";
        CandleSymbol eurUsd = CandleSymbol.valueOf(symbol, CandlePrice.BID, PERIOD);
 
        endpoint.connect(QD_ADDRESS);
 
        Thread.sleep(5000L);
 
        long fromTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(10);
        long toTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(5);
 
        List<Candle> onlySelectedCandles = feed.getTimeSeriesIfSubscribed(Candle.class, eurUsd, fromTime, toTime);
        printAndCountCandles(onlySelectedCandles, "[GET SUBSCRIBED] ");
 
        Promise<List<Candle>> requested = feed.getTimeSeriesPromise(Candle.class, eurUsd, fromTime, toTime);
        requested.await();
        printAndCountCandles(requested.getResult(), "[GET VIA PROMISE] ");
 
        // wait until file is completely parsed
        endpoint.awaitNotConnected();
 
        // close endpoint when we're done
        // this method will gracefully close endpoint, waiting while data processing completes
        endpoint.closeAndAwaitTermination();
    }
 
    private void printAndCountCandles(List<Candle> candles, String prefix) {
        int nCandles = 0;
        System.out.println("Got prefix: " + prefix + " and candles: " + candles);
        if (candles == null) {
            System.out.println("Got null candles - exiting");
            return;
        }
        for (Candle candle : candles) {
            eventsProcessed++;
            nCandles++;
            CandleSymbol symbol = candle.getEventSymbol();
            if (candle.getTime() + PERIOD.getPeriodIntervalMillis() > System.currentTimeMillis()) {
                ; // skipping unfinished candle
            } else {
                System.out.println(prefix + "Got candle for symbol " + symbol + " : " + candle);
            }
        }
        System.out.println(prefix + "Totally got " + nCandles + " candles");
    }
}

C#

using System;
using System.Net.Http;
using System.Net.Http.Headers;
 
namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            const string URL = "https://tools.dxfeed.com/webservice/rest/events.json";
 
            using (var client = new HttpClient {BaseAddress = new Uri(URL)}) {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
 
                var response = client
                    .GetAsync("?events=Candle&symbols=IBM{=d},MSFT{=d}&fromTime=2019-02-18&toTime=2019-02-28&indent")
                    .Result;
                if (response.IsSuccessStatusCode) {
                    var data = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine("{0}", data);
                } else {
                    Console.WriteLine("{0}({1})", response.StatusCode, response.ReasonPhrase);
                }
            }
        }
    }
}

REST

curl -X GET -u IPFlogin:IPFpassword "https://tools.dxfeed.com/webservice/rest/events.json?events=Candle&symbols=MSFT&sources=NYSE&indent"
{
  "status" : "OK",
  "Candle" : {
    "MSFT" : [ {
      "eventSymbol" : "MSFT",
      "eventTime" : 0,
      "eventFlags" : 0,
      "index" : 6659879986868184211,
      "time" : 1550624144000,
      "sequence" : 189587,
      "count" : 1,
      "open" : 108.17,
      "high" : 108.17,
      "low" : 108.17,
      "close" : 108.17,
      "volume" : 447.0,
      "vwap" : "NaN",
      "bidVolume" : "NaN",
      "askVolume" : "NaN",
      "impVolatility" : "NaN"
    } ]
  }

URL encoding

If you use a URL request to get IPF, some URL chapters should be encoded because characters are not used in their special role. URL encoding of a character consists of a % symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character.

Character

Code Points (Hex)

Code Points (Dec)

Ampersand ("&")

26

38

Colon (":")

3A

58

Comma (",")

2C

44

Dollar ("$")

24

36

Equals ("=")

3D

61

Forward slash/Virgule ("/")

2F

47

Plus ("+")

2B

43

Question mark ("?")

3F

63

Semi-colon (";")

3B

59

Examples

  • "&" = "%26"

  • "+" = "%2B"

Please refer to RFC 3986 and its errata.