iex

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 13, 2018 License: LGPL-3.0 Imports: 18 Imported by: 3

README

go-iex

A Go library for accessing the IEX Developer API.

GoDoc Build Status Coverage Status

go-iex is a library to access the IEX Developer API from Go. It provides a thin wrapper for working with the JSON REST endpoints and IEXTP1 pcap data.

IEX is a fair, simple and transparent stock exchange dedicated to investor protection. IEX provides realtime and historical market data for free through the IEX Developer API. By using the IEX API, you agree to the Terms of Use. IEX is not affiliated and does not endorse or recommend this library.

Usage

pcap2json

If you just need a tool to convert the provided pcap data files into JSON, you can use the included pcap2json tool:

$ go install github.com/timpalpant/go-iex/pcap2json
$ pcap2json < input.pcap > output.json
Fetch real-time top-of-book quotes
package main

import (
  "fmt"
  "net/http"

  "github.com/timpalpant/go-iex"
)

func main() {
  client := iex.NewClient(&http.Client{})

  quotes, err := client.GetTOPS([]string{"AAPL", "SPY"})
  if err != nil {
      panic(err)
  }

  for _, quote := range quotes {
      fmt.Printf("%v: bid $%.02f (%v shares), ask $%.02f (%v shares) [as of %v]\n",
          quote.Symbol, quote.BidPrice, quote.BidSize,
          quote.AskPrice, quote.AskSize, quote.LastUpdated)
  }
}
Fetch historical top-of-book quote (L1 tick) data.

Historical tick data (TOPS and DEEP) can be parsed using the PcapScanner.

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/timpalpant/go-iex"
	"github.com/timpalpant/go-iex/iextp/tops"
)

func main() {
	client := iex.NewClient(&http.Client{})

	// Get historical data dumps available for 2016-12-12.
	histData, err := client.GetHIST(time.Date(2016, time.December, 12, 0, 0, 0, 0, time.UTC))
	if err != nil {
		panic(err)
	} else if len(histData) == 0 {
		panic(fmt.Errorf("Found %v available data feeds", len(histData)))
	}

	// Fetch the pcap dump for that date and iterate through its messages.
	resp, err := http.Get(histData[0].Link)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	packetDataSource, err := iex.NewPacketDataSource(resp.Body)
	if err != nil {
		panic(err)
	}
	pcapScanner := iex.NewPcapScanner(packetDataSource)

	// Write each quote update message to stdout, in JSON format.
	enc := json.NewEncoder(os.Stdout)

	for {
		msg, err := pcapScanner.NextMessage()
		if err != nil {
			if err == io.EOF {
				break
			}

			panic(err)
		}

		switch msg := msg.(type) {
		case *tops.QuoteUpdateMessage:
			enc.Encode(msg)
		default:
		}
	}
}

Contributing

Pull requests and issues are welcomed!

License

go-iex is released under the GNU Lesser General Public License, Version 3.0

Documentation

Overview

Package iex provides an API for accessing and using IEX's developer API.

https://www.iextrading.com/developer/

Index

Constants

View Source
const (
	StartMessages    = "O"
	StartSystemHours = "S"
	StartMarketHours = "R"
	EndMarketHours   = "M"
	EndSystemHours   = "E"
	EndMessages      = "C"
)
View Source
const (
	// Trading halted across all US equity markets.
	TradingHalted = "H"
	// Trading halt released into an Order Acceptance Period
	// (IEX-listed securities only)
	TradingOrderAcceptancePeriod = "O"
	// Trading paused and Order Acceptance Period on IEX
	// (IEX-listed securities only)
	TradingPaused = "P"
	// Trading on IEX
	Trading = "T"
)
View Source
const (
	// Trading halt reasons.
	HaltNewsPending            = "T1"
	IPOIssueNotYetTrading      = "IPO1"
	IPOIssueDeferred           = "IPOD"
	MarketCircuitBreakerLevel3 = "MCB3"
	ReasonNotAvailable         = "NA"

	// Order Acceptance Period Reasons
	HaltNewsDisseminations           = "T2"
	IPONewIssueOrderAcceptancePeriod = "IPO2"
	IPOPreLaunchPeriod               = "IPO3"
	MarketCircuitBreakerLevel1       = "MCB1"
	MarketCircuitBreakerLevel2       = "MCB2"
)
View Source
const (
	MarketOpen  = "MarketOpen"
	MarketClose = "MarketClose"
)
View Source
const IEXTP1 = "IEXTP1"

Variables

This section is empty.

Functions

This section is empty.

Types

type Book

type Book struct {
	Bids []*Quote
	Asks []*Quote
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides methods to interact with IEX's HTTP API for developers.

func NewClient

func NewClient(client *http.Client) *Client

func (*Client) GetAllAvailableHIST

func (c *Client) GetAllAvailableHIST() (map[string][]*HIST, error)

GetAllAvailableHIST returns HIST data for all available dates. Returns a map of date string "20060102" -> HIST data for that date.

func (*Client) GetBook

func (c *Client) GetBook(symbols []string) (map[string]*Book, error)

Book shows IEX’s bids and asks for given symbols.

A maximumum of 10 symbols may be requested.

func (*Client) GetDEEP

func (c *Client) GetDEEP(symbol string) (*DEEP, error)

DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed portions of reserve orders are not represented in DEEP.

DEEP also provides last trade price and size information. Trades resulting from either displayed or non-displayed orders matching on IEX will be reported. Routed executions will not be reported.

func (*Client) GetHIST

func (c *Client) GetHIST(date time.Time) ([]*HIST, error)

HIST will provide the output of IEX data products for download on a T+1 basis. Data will remain available for the trailing twelve months.

Only data for the given day will be returned.

func (*Client) GetHistoricalDaily

func (c *Client) GetHistoricalDaily(req *HistoricalDailyRequest) ([]*Stats, error)

This call will return daily stats for a given month or day. Historical data is only available for prior months, starting with January 2014.

func (*Client) GetHistoricalSummary

func (c *Client) GetHistoricalSummary(date time.Time) (*HistoricalSummary, error)

Historical data is only available for prior months, starting with January 2014. If date IsZero(), returns the prior month's data.

func (*Client) GetIntradayStats

func (c *Client) GetIntradayStats() (*IntradayStats, error)

func (*Client) GetLast

func (c *Client) GetLast(symbols []string) ([]*Last, error)

Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time. Last is ideal for developers that need a lightweight stock quote.

Symbols may be any of the available symbols returned by GetSymbols(). If symbols is nil, then all symbols will be returned.

func (*Client) GetMarkets

func (c *Client) GetMarkets() ([]*Market, error)

This endpoint returns near real time traded volume on the markets. Market data is captured by the IEX system from approximately 7:45 a.m. to 5:15 p.m. ET.

func (*Client) GetOperationalHaltStatus

func (c *Client) GetOperationalHaltStatus(symbols []string) (map[string]*OpHaltStatus, error)

The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message.

IEX disseminates a full pre-market spin of Operational halt status messages indicating the operational halt status of all securities. In the spin, IEX will send out an Operational Halt Message with “N” (Not operationally halted on IEX) for all securities that are eligible for trading at the start of the Pre-Market Session. If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre-Market Session.

After the pre-market spin, IEX will use the Operational halt status message to relay changes in operational halt status for an individual security.

A maximumum of 10 symbols may be requested.

func (*Client) GetRecentStats

func (c *Client) GetRecentStats() ([]*Stats, error)

This call will return a minimum of the last five trading days up to all trading days of the current month.

func (*Client) GetSecurityEvents

func (c *Client) GetSecurityEvents(symbols []string) (map[string]*SecurityEventMessage, error)

The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs.

A maximumum of 10 symbols may be requested.

func (*Client) GetShortSaleRestriction

func (c *Client) GetShortSaleRestriction(symbols []string) (map[string]*SSRStatus, error)

In association with Rule 201 of Regulation SHO, the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security.

IEX disseminates a full pre-market spin of Short sale price test status messages indicating the Rule 201 status of all securities. After the pre-market spin, IEX will use the Short sale price test status message in the event of an intraday status change.

The IEX Trading System will process orders based on the latest short sale price test restriction status.

A maximumum of 10 symbols may be requested.

func (*Client) GetSymbols

func (c *Client) GetSymbols() ([]*Symbol, error)

GetSymbols returns an array of symbols IEX supports for trading. This list is updated daily as of 7:45 a.m. ET. Symbols may be added or removed by IEX after the list was produced.

func (*Client) GetSystemEvents

func (c *Client) GetSystemEvents(symbols []string) (map[string]*SystemEvent, error)

The System event message is used to indicate events that apply to the market or the data feed.

There will be a single message disseminated per channel for each System Event type within a given trading session.

A maximumum of 10 symbols may be requested.

func (*Client) GetTOPS

func (c *Client) GetTOPS(symbols []string) ([]*TOPS, error)

TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data.

Symbols may be any of the available symbols returned by GetSymbols(). If symbols is nil, then all symbols will be returned.

func (*Client) GetTradeBreaks

func (c *Client) GetTradeBreaks(symbols []string, last int) (map[string][]*TradeBreak, error)

Trade break messages are sent when an execution on IEX is broken on that same trading day. Trade breaks are rare and only affect applications that rely upon IEX execution based data.

A maximum of 10 symbols may be requested. Last is the number of trades to fetch, and must be <= 500.

func (*Client) GetTrades

func (c *Client) GetTrades(symbols []string, last int) (map[string][]*Trade, error)

Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.

A maximum of 10 symbols may be requested. Last is the number of trades to fetch, and must be <= 500.

func (*Client) GetTradingStatus

func (c *Client) GetTradingStatus(symbols []string) (map[string]*TradingStatusMessage, error)

The Trading status message is used to indicate the current trading status of a security. For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons. For non-IEX-listed securities, IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market, as applicable.

IEX disseminates a full pre-market spin of Trading status messages indicating the trading status of all securities. In the spin, IEX will send out a Trading status message with “T” (Trading) for all securities that are eligible for trading at the start of the Pre-Market Session. If a security is absent from the dissemination, firms should assume that the security is being treated as operationally halted in the IEX Trading System.

After the pre-market spin, IEX will use the Trading status message to relay changes in trading status for an individual security. Messages will be sent when a security is:

Halted
Paused*
Released into an Order Acceptance Period*
Released for trading

*The paused and released into an Order Acceptance Period status will be disseminated for IEX-listed securities only. Trading pauses on non-IEX-listed securities will be treated simply as a halt.

A maximumum of 10 symbols may be requested.

type DEEP

type DEEP struct {
	Symbol        string
	MarketPercent float64
	Volume        int
	LastSalePrice float64
	LastSaleSize  int
	LastSaleTime  Time
	LastUpdate    Time
	Bids          []*Quote
	Asks          []*Quote
	SystemEvent   *SystemEvent
	TradingStatus *TradingStatusMessage
	OpHaltStatus  *OpHaltStatus
	SSRStatus     *SSRStatus
	SecurityEvent *SecurityEventMessage
	Trades        []*Trade
	TradeBreaks   []*TradeBreak
}

type HIST

type HIST struct {
	// URL to the available data file.
	Link string
	// Date of the data contained in this file.
	Date string
	// Which data feed is contained in this file.
	Feed string
	// The feed format specification version.
	Version string
	// The protocol version of the data.
	Protocol string
	// The size, in bytes, of the data file.
	Size int64 `json:",string"`
}

type HistoricalDailyRequest

type HistoricalDailyRequest struct {
	// Option 1: Value needs to be in four-digit year, two-digit
	// month format (YYYYMM) (i.e January 2017 would be written as 201701)
	//
	// Option 2: Value needs to be in four-digit year, two-digit month,
	// two-digit day format (YYYYMMDD) (i.e January 21, 2017 would be
	// written as 20170121).
	Date string `url:"date,omitempty"`

	// Is used in place of date to retrieve last n number of trading days.
	// Value can only be a number up to 90.
	Last int `url:"last,omitempty"`
}

type HistoricalSummary

type HistoricalSummary struct {
	AverageDailyVolume          float64
	AverageDailyRoutedVolume    float64
	AverageMarketShare          float64
	AverageOrderSize            float64
	AverageFillSize             float64
	Bin100Percent               float64
	Bin101Percent               float64
	Bin200Percent               float64
	Bin300Percent               float64
	Bin400Percent               float64
	Bin500Percent               float64
	Bin1000Percent              float64
	Bin5000Percent              float64
	Bin10000Percent             float64
	Bin10000Trades              float64
	Bin20000Trades              float64
	Bin50000Trades              float64
	UniqueSymbolsTraded         float64
	BlockPercent                float64
	SelfCrossPercent            float64
	ETFPercent                  float64
	LargeCapPercent             float64
	MidCapPercent               float64
	SmallCapPercent             float64
	VenueARCXFirstWaveWeight    float64
	VenueBATSFirstWaveWeight    float64
	VenueBATYFirstWaveWeight    float64
	VenueEDGAFirstWaveWeight    float64
	VenueEDGXFirstWaveWeight    float64
	VenueOverallFirstWaveWeight float64
	VenueXASEFirstWaveWeight    float64
	VenueXBOSFirstWaveWeight    float64
	VenueXCHIFirstWaveWeight    float64
	VenueXCISFirstWaveWeight    float64
	VenueXNGSFirstWaveWeight    float64
	VenueXNYSFirstWaveWeight    float64
	VenueXPHLFirstWaveWeight    float64
	VenueARCXFirstWaveRate      float64
	VenueBATSFirstWaveRate      float64
	VenueBATYFirstWaveRate      float64
	VenueEDGAFirstWaveRate      float64
	VenueEDGXFirstWaveRate      float64
	VenueOverallFirstWaveRate   float64
	VenueXASEFirstWaveRate      float64
	VenueXBOSFirstWaveRate      float64
	VenueXCHIFirstWaveRate      float64
	VenueXCISFirstWaveRate      float64
	VenueXNGSFirstWaveRate      float64
	VenueXNYSFirstWaveRate      float64
	VenueXPHLFirstWaveRate      float64
}

type IntradayStats

type IntradayStats struct {
	// Refers to single counted shares matched from executions on IEX.
	Volume struct {
		Value       int
		LastUpdated Time
	}
	// Refers to number of symbols traded on IEX.
	SymbolsTraded struct {
		Value       int
		LastUpdated Time
	}
	// Refers to executions received from order routed to away trading centers.
	RoutedVolume struct {
		Value       int
		LastUpdated Time
	}
	// Refers to sum of matched volume times execution price of those trades.
	Notional struct {
		Value       int
		LastUpdated Time
	}
	// Refers to IEX’s percentage of total US Equity market volume.
	MarketShare struct {
		Value       float64
		LastUpdated Time
	}
}

type Last

type Last struct {
	// Refers to the stock ticker.
	Symbol string
	// Refers to last sale price of the stock on IEX. (Refer to the attribution section above.)
	Price float64
	// Refers to last sale size of the stock on IEX.
	Size int
	// Refers to last sale time in epoch time of the stock on IEX.
	Time Time
}

type Market

type Market struct {
	// Refers to the Market Identifier Code (MIC).
	MIC string
	// Refers to the tape id of the venue.
	TapeID string
	// Refers to name of the venue defined by IEX.
	VenueName string
	// Refers to the amount of traded shares reported by the venue.
	Volume int
	// Refers to the amount of Tape A traded shares reported by the venue.
	TapeA int
	// Refers to the amount of Tape B traded shares reported by the venue.
	TapeB int
	// Refers to the amount of Tape C traded shares reported by the venue.
	TapeC int
	// Refers to the venue’s percentage of shares traded in the market.
	MarketPercent float64
	// Refers to the last update time of the data.
	LastUpdated Time
}

type OpHaltStatus

type OpHaltStatus struct {
	IsHalted  bool
	Timestamp Time
}

type PacketDataSource

type PacketDataSource interface {
	gopacket.PacketDataSource
	LinkType() layers.LinkType
}

func NewPacketDataSource

func NewPacketDataSource(r io.Reader) (PacketDataSource, error)

Initializes a new packet source for pcap or pcap-ng files. Looks at the first 4 bytes to determine if the given Reader is a pcap or pcap-ng format.

type PcapScanner

type PcapScanner struct {
	// contains filtered or unexported fields
}

PcapScanner is a high-level reader for extracting messages from the pcap dumps provided by IEX in the HIST endpoint.

func NewPcapScanner

func NewPcapScanner(packetDataSource PacketDataSource) *PcapScanner

func (*PcapScanner) NextMessage

func (p *PcapScanner) NextMessage() (iextp.Message, error)

Get the next Message in the pcap dump.

type Quote

type Quote struct {
	Price     float64
	Size      float64
	Timestamp Time
}

type Record

type Record struct {
	Value            int    `json:"recordValue"`
	Date             string `json:"recordDate"`
	PreviousDayValue int
	Avg30Value       float64
}

type Records

type Records struct {
	// Refers to single counted shares matched from executions on IEX.
	Volume *Record
	// Refers to number of symbols traded on IEX.
	SymbolsTraded *Record
	// Refers to executions received from order routed to away trading centers.
	RoutedVolume *Record
	// Refers to sum of matched volume times execution price of those trades.
	Notional *Record
}

type SSRStatus

type SSRStatus struct {
	IsSSR     bool
	Detail    string
	Timestamp Time
}

type SecurityEventMessage

type SecurityEventMessage struct {
	SecurityEvent string
	Timestamp     Time
}

type Stats

type Stats struct {
	// Refers to the trading day.
	Date string
	// Refers to executions received from order routed to away trading centers.
	Volume int
	// Refers to single counted shares matched from executions on IEX.
	RoutedVolume int
	// Refers to IEX’s percentage of total US Equity market volume.
	MarketShare float64
	// Will be true if the trading day is a half day.
	IsHalfDay int
	// Refers to the number of lit shares traded on IEX (single-counted).
	LitVolume int
}

type Symbol

type Symbol struct {
	// Refers to the symbol represented in Nasdaq Integrated symbology (INET).
	Symbol string
	// Refers to the name of the company or security.
	Name string
	// Refers to the date the symbol reference data was generated.
	Date string
	// Will be true if the symbol is enabled for trading on IEX.
	IsEnabled bool
}

type SystemEvent

type SystemEvent struct {
	SystemEvent string
	Timestamp   Time
}

type TOPS

type TOPS struct {
	// Refers to the stock ticker.
	Symbol string
	// Refers to IEX’s percentage of the market in the stock.
	MarketPercent float64
	// Refers to amount of shares on the bid on IEX.
	BidSize int
	// Refers to the best bid price on IEX.
	BidPrice float64
	// Refers to amount of shares on the ask on IEX.
	AskSize int
	// Refers to the best ask price on IEX.
	AskPrice float64
	// Refers to shares traded in the stock on IEX.
	Volume int
	// Refers to last sale price of the stock on IEX. (Refer to the attribution section above.)
	LastSalePrice float64
	// Refers to last sale size of the stock on IEX.
	LastSaleSize int
	// Refers to last sale time of the stock on IEX.
	LastSaleTime Time
	// Refers to the last update time of the data.
	// If the value is the zero Time, IEX has not quoted the symbol in
	// the trading day.
	LastUpdated Time
}

type Time

type Time struct {
	time.Time
}

IEX timestamps are always provided in milliseconds since the Unix epoch. Time implements JSON unmarshaling into the native Go Time type.

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

type Trade

type Trade struct {
	Price                 float64
	Size                  int
	TradeID               int64
	IsISO                 bool
	IsOddLot              bool
	IsOutsideRegularHours bool
	IsSinglePriceCross    bool
	IsTradeThroughExcempt bool
	Timestamp             Time
}

type TradeBreak

type TradeBreak struct {
	Price                 float64
	Size                  int
	TradeID               int64
	IsISO                 bool
	IsOddLot              bool
	IsOutsideRegularHours bool
	IsSinglePriceCross    bool
	IsTradeThroughExcempt bool
	Timestamp             Time
}

type TradingStatusMessage

type TradingStatusMessage struct {
	Status    string
	Reason    string
	Timestamp Time
}

Directories

Path Synopsis
deep
Package deep implements an unmarshaler for the DEEP protocol, v1.0.
Package deep implements an unmarshaler for the DEEP protocol, v1.0.
tops
Package tops implements an unmarshaler for the TOPS protocol, v1.6.
Package tops implements an unmarshaler for the TOPS protocol, v1.6.
pcap2json is a small binary for extracting IEXTP messages from a pcap dump and converting them to JSON.
pcap2json is a small binary for extracting IEXTP messages from a pcap dump and converting them to JSON.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL