TerminalStocks

package
v0.0.0-...-db9de54 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2021 License: GPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// URL_EASTMONEY_REAL_TIME = "http://21.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112407201580659678162_1581950914193&pn=1&pz=20000&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152"
	URL_EASTMONEY_REAL_TIME = "" /* 278-byte string literal not displayed */
	URL_EASTMONEY_FUND_FLOW = "http://qt.gtimg.cn/q=ff_%s"
	URL_EASTMONEY_PK        = "http://qt.gtimg.cn/q=s_pk%s"
	URL_EASTMONEY_INFO      = "http://qt.gtimg.cn/q=s_%s"
	URL_EASTMONEY_DAILY     = "" /* 175-byte string literal not displayed */
	URL_EASTMONEY_WEEKLY    = "http://data.gtimg.cn/flashdata/hushen/weekly/%s.js"
)
View Source
const (
	URL_NETEASE_REAL_TIME = "http://api.money.126.net/data/feed/%s,money.api"
	URL_NETEASE_FUND_FLOW = "http://qt.gtimg.cn/q=ff_%s"
	URL_NETEASE_PK        = "http://qt.gtimg.cn/q=s_pk%s"
	URL_NETEASE_INFO      = "http://qt.gtimg.cn/q=s_%s"
	URL_NETEASE_DAILY     = "" /* 158-byte string literal not displayed */
	URL_NETEASE_WEEKLY    = "http://data.gtimg.cn/flashdata/hushen/weekly/%s.js"
)
View Source
const (
	URL_QQ_REAL_TIME = "http://qt.gtimg.cn/q=%s"
	URL_QQ_FUND_FLOW = "http://qt.gtimg.cn/q=ff_%s"
	URL_QQ_PK        = "http://qt.gtimg.cn/q=s_pk%s"
	URL_QQ_INFO      = "http://qt.gtimg.cn/q=s_%s"
	URL_QQ_DAILY     = "http://data.gtimg.cn/flashdata/hushen/daily/%v/%s.js"
	URL_QQ_WEEKLY    = "http://data.gtimg.cn/flashdata/hushen/weekly/%s.js"
)
View Source
const (
	URL_SINA_REAL_TIME = "http://hq.sinajs.cn/list=%s"
	URL_SINA_FUND_FLOW = "http://qt.gtimg.cn/q=ff_%s"
	URL_SINA_PK        = "http://qt.gtimg.cn/q=s_pk%s"
	URL_SINA_INFO      = "http://qt.gtimg.cn/q=s_%s"
	URL_SINA_DAILY     = "http://image.sinajs.cn/newchart/%d/%s/n/"
	URL_SINA_WEEKLY    = "http://image.sinajs.cn/newchart/%s/n/"
)
View Source
const TSrc = `/TSrc.json`

File name in user's home directory where we store the settings.

View Source
const (
	URL_EASTMONEY_LHB = "" /* 169-byte string literal not displayed */
)
View Source
const (
	URL_EASTMONEY_LIMITUP = "" /* 349-byte string literal not displayed */
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APISourceType

type APISourceType int32
const (
	API_VENDOR_YAHOO APISourceType = iota
	API_VENDOR_QQ
	API_VENDOR_SINA
	API_VENDOR_NETEASE
	API_VENDOR_EASTMONEY
	API_VENDOR_LIMITUP_EASTMONEY
	API_VENDOR_LHB_EASTMONEY
)

type Column

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

Column describes formatting rules for individual column within the list of stock quotes.

type ColumnEditor

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

ColumnEditor handles column sort order. When activated it highlights current column name in the header, then waits for arrow keys (choose another column), Enter (reverse sort order), or Esc (exit).

func NewColumnEditor

func NewColumnEditor(screen *Screen, quotes *Quotes) *ColumnEditor

Returns new initialized ColumnEditor struct. As part of initialization it highlights current column name (as stored in Profile).

func (*ColumnEditor) Handle

func (editor *ColumnEditor) Handle(event termbox.Event) bool

Handle takes over the keyboard events and dispatches them to appropriate column editor handlers. It returns true when user presses Esc.

type FundFlow

type FundFlow struct {
	Gid    string  //[0] 代码
	BigIn  float64 //[1] 主力流入
	BigOut float64 //[2] 主力流出
	//[3] 主力净流入
	//[4] 主力净流入/资金流入流出总和
	SmallIn  float64 //[5] 散户流入
	SmallOut float64 //[6] 散户流出
	//[7] 散户净流入
	//[8] 散户净流入/资金流入流出总和
	//[9] 资金流入流出总和1+2+5+6
	//[10] 未知
	//[11] 未知
	Name string //[12] 名字
	Date string //[13] 日期
}

func GetFundFlow

func GetFundFlow(code string) *FundFlow

func GetFundFlowEastmoney

func GetFundFlowEastmoney(code string) *FundFlow

func GetFundFlowNetease

func GetFundFlowNetease(code string) *FundFlow

func GetFundFlowSina

func GetFundFlowSina(code string) *FundFlow

type HistoryData

type HistoryData struct {
	Date  string
	Open  float64
	Close float64
	Max   float64
	Min   float64
	Trade float64
}

func GetDaily

func GetDaily(code string, year int) []*HistoryData

func GetDailyEastmoney

func GetDailyEastmoney(code string) []*HistoryData

func GetDailyNetease

func GetDailyNetease(code string) []*HistoryData

func GetDailySina

func GetDailySina(code string, year int) []*HistoryData

func GetWeekly

func GetWeekly(code string) []*HistoryData

func GetWeeklyEastmoney

func GetWeeklyEastmoney(code string) []*HistoryData

func GetWeeklyNetease

func GetWeeklyNetease(code string) []*HistoryData

func GetWeeklySina

func GetWeeklySina(code string) []*HistoryData

type Layout

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

Layout is used to format and display all the collected data, i.e. market updates and the list of stock quotes.

func NewLayout

func NewLayout(vendor APISourceType) *Layout

Creates the layout and assigns the default values that stay unchanged.

func (*Layout) Header

func (layout *Layout) Header(profile *Profile) string

Header iterates over column titles and formats the header line. The formatting includes placing an arrow next to the sorted column title. When the column editor is active it knows how to highlight currently selected column title.

func (*Layout) Market

func (layout *Layout) Market(market *Market) string

Market merges given market data structure with the market template and returns formatted string that includes highlighting markup.

func (*Layout) Quotes

func (layout *Layout) Quotes(quotes *Quotes) string

Quotes uses quotes template to format timestamp, stock quotes header, and the list of given stock quotes. It returns formatted string with all the necessary markup.

func (*Layout) TotalColumns

func (layout *Layout) TotalColumns() int

TotalColumns is the utility method for the column editor that returns total number of columns.

type LhbData

type LhbData struct {
	SCode      string
	SName      string
	Price      float64
	ChangePer  float64
	ChangeRate float64
	LhbInMoney float64
	TradeAmont float64
	// Ntransac
	LhbCauses string
	// Oldid
	LhbSellMoney  float64
	LhbBuyMoney   float64
	LhbTradeAmont float64
	// Tdate
	LhbNotes string
}

func GetLhbEastmoney

func GetLhbEastmoney(date string) []LhbData

type LineEditor

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

LineEditor kicks in when user presses '+' or '-' to add or delete stock tickers. The data structure and methods are used to collect the input data and keep track of cursor movements (left, right, beginning of the line, end of the line, and backspace).

func NewLineEditor

func NewLineEditor(screen *Screen, quotes *Quotes) *LineEditor

Returns new initialized LineEditor struct.

func (*LineEditor) Handle

func (editor *LineEditor) Handle(ev termbox.Event) bool

Handle takes over the keyboard events and dispatches them to appropriate line editor handlers. As user types or edits the text cursor movements are tracked in `editor.cursor` while the text itself is stored in `editor.input`. The method returns true when user presses Esc (discard) or Enter (process).

func (*LineEditor) Prompt

func (editor *LineEditor) Prompt(command rune) *LineEditor

Prompt displays a prompt in response to '+' or '-' commands. Unknown commands are simply ignored. The prompt is displayed on the 3rd line (between the market data and the stock quotes).

type Market

type Market struct {
	IsClosed  bool              // True when U.S. markets are closed.
	Dow       map[string]string // Hash of Dow Jones indicators.
	Nasdaq    map[string]string // Hash of NASDAQ indicators.
	Sp500     map[string]string // Hash of S&P 500 indicators.
	Tokyo     map[string]string
	HongKong  map[string]string
	London    map[string]string
	Frankfurt map[string]string
	Yield     map[string]string
	Oil       map[string]string
	Yen       map[string]string
	Euro      map[string]string
	Gold      map[string]string
	Szzs      map[string]string
	Szcz      map[string]string
	Hs300     map[string]string
	Cybz      map[string]string
	// contains filtered or unexported fields
}

Market stores current market information displayed in the top three lines of the screen. The market data is fetched and parsed from the HTML page above.

func NewMarket

func NewMarket(vendor APISourceType) *Market

Returns new initialized Market struct.

func (*Market) Fetch

func (market *Market) Fetch() (self *Market)

Fetch downloads HTML page from the 'marketURL', parses it, and stores resulting data in internal hashes. If download or data parsing fails Fetch populates 'market.errors'.

func (*Market) FetchQQ

func (market *Market) FetchQQ() (self *Market)

Fetch downloads HTML page from the 'marketURL', parses it, and stores resulting data in internal hashes. If download or data parsing fails Fetch populates 'market.errors'.

func (*Market) FetchYahoo

func (market *Market) FetchYahoo() (self *Market)

Fetch downloads HTML page from the 'marketURL', parses it, and stores resulting data in internal hashes. If download or data parsing fails Fetch populates 'market.errors'.

func (*Market) Ok

func (market *Market) Ok() (bool, string)

Ok returns two values: 1) boolean indicating whether the error has occured, and 2) the error text itself.

type Markup

type Markup struct {
	Foreground   termbox.Attribute // Foreground color.
	Background   termbox.Attribute // Background color (so far always termbox.ColorDefault).
	RightAligned bool              // True when the string is right aligned.
	// contains filtered or unexported fields
}

Markup implements some minimalistic text formatting conventions that get translated to Termbox colors and attributes. To colorize a string wrap it in <color-name>...</> tags. Unlike HTML each tag sets a new color whereas the </> tag changes color back to default. For example:

<green>Hello, <red>world!</>

The color tags could be combined with the attributes: <b>...</b> for bold, <u>...</u> for underline, and <r>...</r> for reverse. Unlike colors the attributes require matching closing tag.

The <right>...</right> tag is used to right align the enclosed string (ex. when displaying current time in the upper right corner).

func NewMarkup

func NewMarkup() *Markup

Creates markup to define tag to Termbox translation rules and store default colors and column alignments.

func (*Markup) IsTag

func (markup *Markup) IsTag(str string) bool

IsTag returns true when the given string looks like markup tag. When the tag name matches one of the markup-supported tags it gets translated to relevant Termbox attributes and colors.

func (*Markup) Tokenize

func (markup *Markup) Tokenize(str string) []string

Tokenize works just like strings.Split() except the resulting array includes the delimiters. For example, the "<green>Hello, <red>world!</>" string when tokenized by tags produces the following:

[0] "<green>"
[1] "Hello, "
[2] "<red>"
[3] "world!"
[4] "</>"

type PKData

type PKData struct {
	BuyBig    float64 //0: 买盘大单
	BuySmall  float64 //1: 买盘小单
	SellBig   float64 //2: 卖盘大单
	SellSmall float64 //3: 卖盘小单
}

func GetPK

func GetPK(code string) *PKData

func GetPKEastmoney

func GetPKEastmoney(code string) *PKData

func GetPKNetease

func GetPKNetease(code string) *PKData

func GetPKSina

func GetPKSina(code string) *PKData

type Profile

type Profile struct {
	Tickers       []string // List of stock tickers to display.
	MarketRefresh int      // Time interval to refresh market data.
	QuotesRefresh int      // Time interval to refresh stock quotes.
	SortColumn    int      // Column number by which we sort stock quotes.
	Ascending     bool     // True when sort order is ascending.
	Grouped       bool     // True when stocks are grouped by advancing/declining.
	// contains filtered or unexported fields
}

Profile manages Terminal Stocks program settings as defined by user (ex. list of stock tickers). The settings are serialized using JSON and saved in the ~/.TSrc file.

func NewProfile

func NewProfile(vendor APISourceType) *Profile

Creates the profile and attempts to load the settings from ~/.TSrc file. If the file is not there it gets created with default values.

func (*Profile) AddTickers

func (profile *Profile) AddTickers(tickers []string) (added int, err error)

AddTickers updates the list of existing tikers to add the new ones making sure there are no duplicates.

func (*Profile) Regroup

func (profile *Profile) Regroup() error

Regroup flips the flag that controls whether the stock quotes are grouped by advancing/declining issues.

func (*Profile) RemoveTickers

func (profile *Profile) RemoveTickers(tickers []string) (removed int, err error)

RemoveTickers removes requested stock tickers from the list we track.

func (*Profile) Reorder

func (profile *Profile) Reorder() error

Reorder gets called by the column editor to either reverse sorting order for the current column, or to pick another sort column.

func (*Profile) Save

func (profile *Profile) Save() error

Save serializes settings using JSON and saves them in ~/.TSrc file.

type Quotes

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

Quotes stores relevant pointers as well as the array of stock quotes for the tickers we are tracking.

func NewQuotes

func NewQuotes(market *Market, profile *Profile) *Quotes

Sets the initial values and returns new Quotes struct.

func (*Quotes) AddTickers

func (quotes *Quotes) AddTickers(tickers []string) (added int, err error)

AddTickers saves the list of tickers and refreshes the stock data if new tickers have been added. The function gets called from the line editor when user adds new stock tickers.

func (*Quotes) Fetch

func (quotes *Quotes) Fetch() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) FetchEastmoney

func (quotes *Quotes) FetchEastmoney() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) FetchLhbEastmoney

func (quotes *Quotes) FetchLhbEastmoney() (self *Quotes)

func (*Quotes) FetchLimitupEastmoney

func (quotes *Quotes) FetchLimitupEastmoney() (self *Quotes)

func (*Quotes) FetchNetease

func (quotes *Quotes) FetchNetease() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) FetchQQ

func (quotes *Quotes) FetchQQ() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) FetchSina

func (quotes *Quotes) FetchSina() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) FetchYahoo

func (quotes *Quotes) FetchYahoo() (self *Quotes)

Fetch the latest stock quotes and parse raw fetched data into array of []Stock structs.

func (*Quotes) Ok

func (quotes *Quotes) Ok() (bool, string)

Ok returns two values: 1) boolean indicating whether the error has occured, and 2) the error text itself.

func (*Quotes) RemoveTickers

func (quotes *Quotes) RemoveTickers(tickers []string) (removed int, err error)

RemoveTickers saves the list of tickers and refreshes the stock data if some tickers have been removed. The function gets called from the line editor when user removes existing stock tickers.

type RealTimeData

type RealTimeData struct {
	Name         string  /*[1]股票名称*/
	Gid          string  /*[2]股票编号*/
	NowPri       float64 /*[3]当前价格*/
	YestClosePri float64 /*[4]昨日收盘价*/
	OpeningPri   float64 /*[5]今日开盘价*/
	TraNumber    int64   /*[6]成交量*/
	Outter       int64   /*[7]外盘*/
	Inner        int64   /*[8]内盘*/
	BuyOne       int64   /*[9]买一*/
	BuyOnePri    float64 /*[10]买一报价*/
	BuyTwo       int64   /*[11]买二*/
	BuyTwoPri    float64 /*[12]买二报价*/
	BuyThree     int64   /*[13]买三*/
	BuyThreePri  float64 /*[14]买三报价*/
	BuyFour      int64   /*[15]买四*/
	BuyFourPri   float64 /*[16]买四报价*/
	BuyFive      int64   /*[17]买五*/
	BuyFivePri   float64 /*[18]买五报价*/
	SellOne      int64   /*[19]卖一*/
	SellOnePri   float64 /*[20]卖一报价*/
	SellTwo      int64   /*[21]卖二*/
	SellTwoPri   float64 /*[22]卖二报价*/
	SellThree    int64   /*[23]卖三*/
	SellThreePri float64 /*[24]卖三报价*/
	SellFour     int64   /*[25]卖四*/
	SellFourPri  float64 /*[26]卖四报价*/
	SellFive     int64   /*[27]卖五*/
	SellFivePri  float64 /*[28]卖五报价*/
	/*[29]最近逐笔成交*/
	Time      string  /*[30]时间*/
	Change    float64 /*[31]涨跌*/
	ChangePer float64 /*[32]涨跌%*/
	TodayMax  float64 /*[33]今日最高价*/
	TodayMin  float64 /*[34]今日最低价*/
	/*[35]价格/成交量(手)/成交额*/
	TradeCount int64   /*[36]成交量*/
	TradeAmont int64   /*[37]成交额*/
	ChangeRate float64 /*[38]换手率*/
	PERatio    float64 /*[39]市盈率*/
	/*[40]*/
	/*[41]最高*/
	/*[42]最低*/
	MaxMinChange float64 /*[43]振幅*/
	MarketAmont  float64 /*[44]流通市值*/
	TotalAmont   float64 /*[45]总市值*/
	PBRatio      float64 /*[46]市净率*/
	HighPri      float64 /*[47]涨停价*/
	LowPri       float64 /*[48]跌停价*/
}

func GetRealtime

func GetRealtime(code string) []*RealTimeData

func GetRealtimeEastmoney

func GetRealtimeEastmoney(code string) []*RealTimeData

func GetRealtimeNetease

func GetRealtimeNetease(code string) []*RealTimeData

func GetRealtimeSina

func GetRealtimeSina(code string) []*RealTimeData

type Screen

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

Screen is thin wrapper aroung Termbox library to provide basic display capabilities as requied by Mop.

func NewScreen

func NewScreen(vendor APISourceType) *Screen

Initializes Termbox, creates screen along with layout and markup, and calculates current screen dimensions. Once initialized the screen is ready for display.

func (*Screen) Clear

func (screen *Screen) Clear() *Screen

Clear makes the entire screen blank using default background color.

func (*Screen) ClearLine

func (screen *Screen) ClearLine(x int, y int) *Screen

ClearLine erases the contents of the line starting from (x,y) coordinate till the end of the line.

func (*Screen) Close

func (screen *Screen) Close() *Screen

Close gets called upon program termination to close the Termbox.

func (*Screen) Draw

func (screen *Screen) Draw(objects ...interface{}) *Screen

Draw accepts variable number of arguments and knows how to display the market data, stock quotes, current time, and an arbitrary string.

func (*Screen) DrawLine

func (screen *Screen) DrawLine(x int, y int, str string)

DrawLine takes the incoming string, tokenizes it to extract markup elements, and displays it all starting at (x,y) location.

func (*Screen) Pause

func (screen *Screen) Pause(pause bool) *Screen

Pause is a toggle function that either creates a timestamp of the pause request or resets it to nil.

func (*Screen) Resize

func (screen *Screen) Resize() *Screen

Resize gets called when the screen is being resized. It recalculates screen dimensions and requests to clear the screen on next update.

func (*Screen) Vendor

func (screen *Screen) Vendor() APISourceType

Resize gets called when the screen is being resized. It recalculates screen dimensions and requests to clear the screen on next update.

type Sorter

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

Sorter gets called to sort stock quotes by one of the columns. The setup is rather lengthy; there should probably be more concise way that uses reflection and avoids hardcoding the column names.

func NewSorter

func NewSorter(profile *Profile) *Sorter

Returns new Sorter struct.

func (*Sorter) SortByCurrentColumn

func (sorter *Sorter) SortByCurrentColumn(stocks []Stock) *Sorter

SortByCurrentColumn builds a list of sort interface based on current sort order, then calls sort.Sort to do the actual job.

type Stock

type Stock struct {
	Ticker     string `json:"symbol"` // Stock ticker.
	Gid        string `json:"gid"`
	LastTrade  string `json:"regularMarketPrice"`          // l1: last trade.
	Change     string `json:"regularMarketChange"`         // c6: change real time.
	ChangePct  string `json:"regularMarketChangePercent"`  // k2: percent change real time.
	Open       string `json:"regularMarketOpen"`           // o: market open price.
	Low        string `json:"regularMarketDayLow"`         // g: day's low.
	High       string `json:"regularMarketDayHigh"`        // h: day's high.
	Low52      string `json:"fiftyTwoWeekLow"`             // j: 52-weeks low.
	High52     string `json:"fiftyTwoWeekHigh"`            // k: 52-weeks high.
	Volume     string `json:"regularMarketVolume"`         // v: volume.
	AvgVolume  string `json:"averageDailyVolume10Day"`     // a2: average volume.
	PeRatio    string `json:"trailingPE"`                  // r2: P/E ration real time.
	PeRatioX   string `json:"trailingPE"`                  // r: P/E ration (fallback when real time is N/A).
	Dividend   string `json:"trailingAnnualDividendRate"`  // d: dividend.
	Yield      string `json:"trailingAnnualDividendYield"` // y: dividend yield.
	MarketCap  string `json:"marketCap"`                   // j3: market cap real time.
	MarketCapX string `json:"marketCap"`                   // j1: market cap (fallback when real time is N/A).
	Advancing  bool   // True when change is >= $0.
}

Stock stores quote information for the particular stock ticker. The data for all the fields except 'Advancing' is fetched using Yahoo market API.

func GetLimitupEastmoney

func GetLimitupEastmoney() ([]Stock, error)

type StockGetter

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

type StockInfo

type StockInfo struct {
	//0: 未知
	Name       string  //1: 名字
	Gid        string  //2: 代码
	Price      float64 //3: 当前价格
	Change     float64 //4: 涨跌
	ChangePer  float64 //5: 涨跌%
	TradeCount float64 //6: 成交量(手)
	TradeAmont float64 //7: 成交额(万)
	//8:
	TotalAmont float64 //9: 总市值
}

func GetInfo

func GetInfo(code string) *StockInfo

func GetInfoEastmoney

func GetInfoEastmoney(code string) *StockInfo

func GetInfoNetease

func GetInfoNetease(code string) *StockInfo

func GetInfoSina

func GetInfoSina(code string) *StockInfo

Jump to

Keyboard shortcuts

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